knowpool 0.0.0-stage → 0.1.0-alpha.2
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/LICENSE +21 -0
- package/README.md +101 -2
- package/bin/knowpool.mjs +150 -0
- package/docs/DESIGN.md +111 -0
- package/docs/NAMING.md +65 -0
- package/docs/PROTOCOL.md +146 -0
- package/docs/ROADMAP.md +33 -0
- package/docs/architecture/BUILD.md +36 -0
- package/docs/architecture/README.md +125 -0
- package/docs/architecture/mermaid.json +18 -0
- package/docs/architecture/print.css +58 -0
- package/docs/architecture/print.py +121 -0
- package/docs/architecture/sources/evidence.mmd +13 -0
- package/docs/architecture/sources/export.mmd +11 -0
- package/docs/architecture/sources/review.mmd +12 -0
- package/docs/architecture/sources/sync.mmd +18 -0
- package/docs/architecture/sources/system.mmd +13 -0
- package/docs/architecture/sources/team.mmd +14 -0
- package/docs/architecture/sources/vaults.mmd +14 -0
- package/docs/architecture/svg/evidence.svg +1 -0
- package/docs/architecture/svg/export.svg +1 -0
- package/docs/architecture/svg/review.svg +1 -0
- package/docs/architecture/svg/sync.svg +1 -0
- package/docs/architecture/svg/system.svg +1 -0
- package/docs/architecture/svg/team.svg +1 -0
- package/docs/architecture/svg/vaults.svg +1 -0
- package/docs/design-history/README.md +25 -0
- package/docs/design-history/icons/kbloom.svg +1 -0
- package/docs/design-history/icons/knowary.svg +1 -0
- package/docs/design-history/icons/knowcommit.svg +1 -0
- package/docs/design-history/icons/knowcrate.svg +1 -0
- package/docs/design-history/icons/knowmill.svg +1 -0
- package/docs/design-history/icons/lorekiln.svg +1 -0
- package/docs/design-history/icons/loreparcel.svg +1 -0
- package/docs/design-history/icons/loreyard.svg +1 -0
- package/docs/design-history/icons/zhicang.svg +1 -0
- package/docs/design-history/original-layouts.md +100 -0
- package/examples/demo.mjs +54 -0
- package/examples/review.html +10 -0
- package/package.json +13 -4
- package/skills/knowpool/SKILL.md +16 -0
- package/src/contexts.mjs +44 -0
- package/src/export.mjs +107 -0
- package/src/extract.py +68 -0
- package/src/io.mjs +129 -0
- package/src/notes.mjs +132 -0
- package/src/pr.mjs +32 -0
- package/src/setup.mjs +63 -0
- package/src/sources.mjs +136 -0
- package/src/storage.mjs +87 -0
- package/src/vault.mjs +78 -0
- package/src/versioning.mjs +198 -0
- package/test/adapters.test.mjs +60 -0
- package/test/audit.test.mjs +129 -0
- package/test/fixtures/two-pages.pdf +87 -0
- package/test/release.test.mjs +126 -0
- package/test/support.mjs +56 -0
- package/test/workflow.test.mjs +193 -0
package/src/notes.mjs
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { atomicText, dir, git, isHash, json, readFile, requireThat, sha, statOrNull } from './io.mjs';
|
|
5
|
+
import { allowContribution, idOf, idTypes, localMainCommit } from './vault.mjs';
|
|
6
|
+
import { readAt, validateLocator } from './sources.mjs';
|
|
7
|
+
|
|
8
|
+
const types = ['note', 'research', 'decision'];
|
|
9
|
+
async function noteFile(vault, id) {
|
|
10
|
+
idOf('note', id);
|
|
11
|
+
return path.join(await dir(vault.root, 'knowledge'), id + '.md');
|
|
12
|
+
}
|
|
13
|
+
async function draftFile(vault, id) {
|
|
14
|
+
idOf('draft', id);
|
|
15
|
+
return path.join(await dir(vault.local, 'drafts'), id + '.json');
|
|
16
|
+
}
|
|
17
|
+
function formatMarkdown(fields, body) {
|
|
18
|
+
const lines = Object.entries(fields).map(([key, value]) => key + ': ' + JSON.stringify(value));
|
|
19
|
+
return ['---', ...lines, '---', '', body.trim(), ''].join('\n');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function parseNote(text, id) {
|
|
23
|
+
idOf('note', id);
|
|
24
|
+
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text.replaceAll('\r\n', '\n'));
|
|
25
|
+
requireThat(match, 'FORMAT', 'Missing front matter in ' + id);
|
|
26
|
+
const meta = Object.create(null);
|
|
27
|
+
for (const line of match[1].split('\n')) {
|
|
28
|
+
const pair = /^([a-z]+):\s*(.+)$/.exec(line);
|
|
29
|
+
requireThat(pair && !Object.hasOwn(meta, pair[1]), 'FORMAT', 'Invalid front matter in ' + id);
|
|
30
|
+
meta[pair[1]] = JSON.parse(pair[2]);
|
|
31
|
+
}
|
|
32
|
+
requireThat(meta.format === 1 && meta.id === id && typeof meta.title === 'string' && meta.title.trim()
|
|
33
|
+
&& types.includes(meta.type) && Array.isArray(meta.tags) && meta.tags.every(t => typeof t === 'string')
|
|
34
|
+
&& Array.isArray(meta.sources) && meta.sources.length && typeof meta.created === 'string'
|
|
35
|
+
&& typeof meta.updated === 'string' && match[2].trim(), 'FORMAT', 'Invalid note: ' + id);
|
|
36
|
+
for (const ref of meta.sources) {
|
|
37
|
+
idOf('source', ref.id);
|
|
38
|
+
requireThat(typeof ref.at === 'string', 'LOCATOR', 'Missing evidence locator');
|
|
39
|
+
}
|
|
40
|
+
return { ...meta, body: match[2].trim() };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function checkReferences(note, sources) {
|
|
44
|
+
for (const ref of note.sources) {
|
|
45
|
+
const source = sources.get(ref.id);
|
|
46
|
+
requireThat(source, 'SOURCE', 'Missing source ' + ref.id + ' in ' + note.id);
|
|
47
|
+
validateLocator(source, ref.at);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function workingNotes(vault) {
|
|
52
|
+
const files = await fs.readdir(await dir(vault.root, 'knowledge'));
|
|
53
|
+
return Promise.all(files.filter(f => f.endsWith('.md') && idTypes.note.test(f.slice(0, -3))).sort().map(async f => {
|
|
54
|
+
const id = f.slice(0, -3);
|
|
55
|
+
return parseNote(await readFile(await noteFile(vault, id)), id);
|
|
56
|
+
}));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function readableNotes(vault) {
|
|
60
|
+
if (vault.config.mode === 'personal') return { ref: 'worktree', notes: await workingNotes(vault) };
|
|
61
|
+
const ref = localMainCommit(vault);
|
|
62
|
+
if (!ref) return { ref: 'unborn-main', notes: [] };
|
|
63
|
+
const files = git(vault.root, 'ls-tree', '-r', '-z', '--name-only', ref, '--', 'knowledge').split('\0').filter(Boolean);
|
|
64
|
+
const notes = files.filter(f => /^knowledge\/note_[^/]+\.md$/.test(f))
|
|
65
|
+
.map(f => parseNote(git(vault.root, 'show', ref + ':' + f), path.basename(f, '.md')));
|
|
66
|
+
return { ref, notes };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function createDraft(vault, { title, bodyFile, sources, locators, update, type, tags }) {
|
|
70
|
+
requireThat(title.trim() && sources.length && sources.length === locators.length,
|
|
71
|
+
'INPUT', 'Give a title and one locator per source');
|
|
72
|
+
const refs = sources.map((id, index) => ({ id: idOf('source', id), at: locators[index] }));
|
|
73
|
+
for (const ref of refs) await readAt(vault, ref.id, ref.at);
|
|
74
|
+
const note = update ? idOf('note', update) : 'note_' + randomUUID();
|
|
75
|
+
const before = update ? await readFile(await noteFile(vault, note)) : null;
|
|
76
|
+
const previous = before && parseNote(before, note);
|
|
77
|
+
const now = new Date().toISOString();
|
|
78
|
+
const markdown = formatMarkdown({
|
|
79
|
+
format: 1, id: note, title: title.trim(), type: type ?? previous?.type ?? 'note',
|
|
80
|
+
tags: tags ?? previous?.tags ?? [], created: previous?.created ?? now, updated: now, sources: refs
|
|
81
|
+
}, await readFile(path.resolve(bodyFile)));
|
|
82
|
+
parseNote(markdown, note);
|
|
83
|
+
const draft = 'draft_' + randomUUID();
|
|
84
|
+
const record = { vault: vault.config.id, draft, note, base: before === null ? null : sha(before), markdown };
|
|
85
|
+
const bytes = json(record);
|
|
86
|
+
await atomicText(await draftFile(vault, draft), bytes);
|
|
87
|
+
return { draft, note, base: record.base, digest: sha(bytes) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function loadDraft(vault, id) {
|
|
91
|
+
const bytes = await readFile(await draftFile(vault, id));
|
|
92
|
+
const record = JSON.parse(bytes);
|
|
93
|
+
requireThat(record.vault === vault.config.id && record.draft === id
|
|
94
|
+
&& (record.base === null || isHash(record.base)), 'DRAFT', 'Invalid draft or vault binding');
|
|
95
|
+
parseNote(record.markdown, record.note);
|
|
96
|
+
return { ...record, digest: sha(bytes) };
|
|
97
|
+
}
|
|
98
|
+
async function currentText(vault, note) {
|
|
99
|
+
const file = await noteFile(vault, note);
|
|
100
|
+
return await statOrNull(file) ? await readFile(file) : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function preview(vault, id) {
|
|
104
|
+
const draft = await loadDraft(vault, id);
|
|
105
|
+
const current = await currentText(vault, draft.note);
|
|
106
|
+
const evidence = [];
|
|
107
|
+
for (const ref of parseNote(draft.markdown, draft.note).sources) evidence.push(await readAt(vault, ref.id, ref.at));
|
|
108
|
+
const stale = current !== draft.markdown && (current === null ? null : sha(current)) !== draft.base;
|
|
109
|
+
return { ...draft, current, stale, evidence };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function approve(vault, id, digest) {
|
|
113
|
+
allowContribution(vault);
|
|
114
|
+
const draft = await loadDraft(vault, id);
|
|
115
|
+
requireThat(isHash(digest) && digest === draft.digest, 'REVIEW_CHANGED', 'Review the current draft and its digest');
|
|
116
|
+
const current = await currentText(vault, draft.note);
|
|
117
|
+
if (current === draft.markdown) return { note: draft.note, digest, repeated: true };
|
|
118
|
+
requireThat((current === null ? null : sha(current)) === draft.base,
|
|
119
|
+
'STALE', 'The target note changed. Build a new draft against its current revision');
|
|
120
|
+
for (const ref of parseNote(draft.markdown, draft.note).sources) await readAt(vault, ref.id, ref.at);
|
|
121
|
+
await atomicText(await noteFile(vault, draft.note), draft.markdown, current !== null);
|
|
122
|
+
return { note: draft.note, digest, repeated: false };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function search(vault, term) {
|
|
126
|
+
requireThat(term.trim(), 'INPUT', 'Provide a nonempty search term');
|
|
127
|
+
const { ref, notes } = await readableNotes(vault);
|
|
128
|
+
const query = term.trim().toLowerCase();
|
|
129
|
+
const matches = notes.filter(n => [n.title, n.body, ...n.tags].some(s => s.toLowerCase().includes(query)))
|
|
130
|
+
.map(n => ({ id: n.id, title: n.title, sources: n.sources }));
|
|
131
|
+
return { vault: vault.config.id, ref, matches };
|
|
132
|
+
}
|
package/src/pr.mjs
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import { branch, git, requireThat, run } from './io.mjs';
|
|
3
|
+
import { allowContribution } from './vault.mjs';
|
|
4
|
+
|
|
5
|
+
export async function knowledgePr(vault, remote, options) {
|
|
6
|
+
requireThat(vault.config.mode === 'team', 'MODE', 'Use a team vault for knowledge PRs');
|
|
7
|
+
allowContribution(vault);
|
|
8
|
+
requireThat(/^[a-zA-Z0-9][\w.-]*$/.test(remote), 'REMOTE', 'Choose a named Git remote');
|
|
9
|
+
const url = git(vault.root, 'remote', 'get-url', '--push', remote).trim();
|
|
10
|
+
const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)\/?$/.exec(url.replace(/\.git$/, ''));
|
|
11
|
+
requireThat(match, 'REMOTE', 'Select a GitHub.com repository');
|
|
12
|
+
const repo = match[1] + '/' + match[2];
|
|
13
|
+
const head = branch(vault.root);
|
|
14
|
+
const gh = (...args) => run('gh', ['pr', ...args, '--repo', repo], vault.root);
|
|
15
|
+
const open = () => JSON.parse(gh('list', '--state', 'open', '--head', head, '--base', vault.config.defaultBranch, '--json', 'url,headRefOid,number'));
|
|
16
|
+
if (!options) return { branch: head, pullRequests: open() };
|
|
17
|
+
const commit = git(vault.root, 'rev-parse', 'HEAD').trim();
|
|
18
|
+
const published = git(vault.root, 'ls-remote', '--heads', '--', url, 'refs/heads/' + head).trim().split('\t')[0];
|
|
19
|
+
requireThat(published === commit, 'UNPUBLISHED', 'Sync the reviewed branch before opening its PR');
|
|
20
|
+
const existing = open();
|
|
21
|
+
if (existing.length) return { ...existing[0], existing: true };
|
|
22
|
+
const file = await fs.realpath(options.bodyFile);
|
|
23
|
+
requireThat((await fs.stat(file)).isFile(), 'FILE', 'Supply a PR description file');
|
|
24
|
+
try {
|
|
25
|
+
return { url: gh('create', '--base', vault.config.defaultBranch, '--head', head,
|
|
26
|
+
'--title', options.title, '--body-file', file).trim(), commit, existing: false };
|
|
27
|
+
} catch (error) {
|
|
28
|
+
const raced = open();
|
|
29
|
+
if (raced.length) return { ...raced[0], existing: true };
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
}
|
package/src/setup.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { atomicText, dir, git, readFile, requireThat, sha, statOrNull, withLock } from './io.mjs';
|
|
5
|
+
import { initVault, openVault } from './vault.mjs';
|
|
6
|
+
|
|
7
|
+
export async function installSkill(vault) {
|
|
8
|
+
const source = fileURLToPath(new URL('../skills/knowpool/SKILL.md', import.meta.url));
|
|
9
|
+
const contents = await readFile(source);
|
|
10
|
+
const target = path.join(await dir(vault.root, '.agents', 'skills', 'knowpool'), 'SKILL.md');
|
|
11
|
+
const marker = path.join(vault.local, 'installed-skill.sha256');
|
|
12
|
+
const previous = await statOrNull(marker) ? (await readFile(marker)).trim() : null;
|
|
13
|
+
if (await statOrNull(target)) {
|
|
14
|
+
const current = await readFile(target);
|
|
15
|
+
if (current !== contents) {
|
|
16
|
+
requireThat(sha(current) === previous || sha(current) === '50ccea5befd6485fabe4a58e7b0ad354be099ea5292ef9bdd3584542e64d8292', 'EXISTS', 'An edited skill already exists at ' + target);
|
|
17
|
+
await atomicText(target, contents, true);
|
|
18
|
+
}
|
|
19
|
+
} else await atomicText(target, contents);
|
|
20
|
+
await atomicText(marker, sha(contents) + '\n', true);
|
|
21
|
+
return { installed: target };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function cloneEndpoint(url, base) {
|
|
25
|
+
const remote = !path.isAbsolute(url) && /^[^/\\:]+:/.test(url);
|
|
26
|
+
if (remote) return url;
|
|
27
|
+
const local = path.resolve(base, url);
|
|
28
|
+
return await statOrNull(local) ? fs.realpath(local) : local;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function cloneVault(root, url, mode) {
|
|
32
|
+
requireThat(url && !url.startsWith('-') && !url.includes('::') && !/[\r\n]/.test(url), 'REMOTE', 'Use an ordinary Git URL or path');
|
|
33
|
+
if (/^https?:/i.test(url)) {
|
|
34
|
+
const parsed = new URL(url);
|
|
35
|
+
requireThat(!parsed.username && !parsed.password, 'REMOTE', 'Use a credential helper for HTTPS authentication');
|
|
36
|
+
}
|
|
37
|
+
const endpoint = await cloneEndpoint(url, process.cwd());
|
|
38
|
+
await fs.mkdir(path.dirname(root), { recursive: true });
|
|
39
|
+
if (await statOrNull(root)) {
|
|
40
|
+
if ((await fs.readdir(root)).length) {
|
|
41
|
+
const existing = await openVault(root);
|
|
42
|
+
const origin = git(root, 'remote', 'get-url', 'origin').trim();
|
|
43
|
+
requireThat(await cloneEndpoint(origin, root) === endpoint
|
|
44
|
+
&& (!mode || existing.config.mode === mode), 'VAULT', 'Existing vault points to a different remote or mode');
|
|
45
|
+
return existing;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const staging = await fs.mkdtemp(path.join(path.dirname(root), '.knowpool-clone-'));
|
|
49
|
+
try {
|
|
50
|
+
git(path.dirname(root), 'clone', '--', endpoint, staging);
|
|
51
|
+
const clone = await openVault(staging);
|
|
52
|
+
requireThat(!mode || clone.config.mode === mode, 'MODE', 'Cloned vault has a different mode');
|
|
53
|
+
await fs.rename(staging, root);
|
|
54
|
+
} finally { await fs.rm(staging, { recursive: true, force: true }); }
|
|
55
|
+
return openVault(root);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function setup(root, mode, clone) {
|
|
59
|
+
if (!clone) await initVault(root, mode);
|
|
60
|
+
const vault = clone ? await cloneVault(root, clone, mode) : await openVault(root);
|
|
61
|
+
const { installed } = await withLock(path.join(vault.local, 'write.lock'), () => installSkill(vault));
|
|
62
|
+
return { vault: vault.config.id, mode: vault.config.mode, root: vault.root, skill: installed };
|
|
63
|
+
}
|
package/src/sources.mjs
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createReadStream } from 'node:fs';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { allowContribution, idOf, idTypes, localMainCommit } from './vault.mjs';
|
|
7
|
+
import { atomicText, checkBytes, copyBytes, dir, fingerprint, git, inside, json, objectPath, readFile,
|
|
8
|
+
requireThat, run, statOrNull, storeBytes } from './io.mjs';
|
|
9
|
+
|
|
10
|
+
const adapter = fileURLToPath(new URL('./extract.py', import.meta.url));
|
|
11
|
+
const kinds = ['text', 'html', 'pdf', 'sqlite', 'binary'];
|
|
12
|
+
const locatorKinds = { text: 'line', html: 'para', pdf: 'page' };
|
|
13
|
+
|
|
14
|
+
function validUrl(raw) {
|
|
15
|
+
if (raw === null) return null;
|
|
16
|
+
const url = new URL(raw);
|
|
17
|
+
requireThat(['http:', 'https:'].includes(url.protocol) && !url.username && !url.password,
|
|
18
|
+
'URL', 'Use an HTTP(S) origin URL without embedded credentials');
|
|
19
|
+
return url.href;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function parseManifest(text, id) {
|
|
23
|
+
idOf('source', id);
|
|
24
|
+
const m = JSON.parse(text);
|
|
25
|
+
requireThat(m.format === 1 && m.id === id && 'src_' + m.sha256 === id
|
|
26
|
+
&& Number.isSafeInteger(m.size) && m.size >= 0 && kinds.includes(m.kind)
|
|
27
|
+
&& typeof m.filename === 'string' && m.filename.length > 0 && !/[\/\\\x00-\x1f]/.test(m.filename)
|
|
28
|
+
&& !['.', '..'].includes(m.filename) && typeof m.created === 'string', 'FORMAT', 'Invalid source manifest: ' + id);
|
|
29
|
+
validUrl(m.url);
|
|
30
|
+
return m;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function manifest(vault, id) {
|
|
34
|
+
idOf('source', id);
|
|
35
|
+
return parseManifest(await readFile(path.join(await dir(vault.root, 'sources'), id + '.json')), id);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function readableManifest(vault, id) {
|
|
39
|
+
idOf('source', id);
|
|
40
|
+
if (vault.config.mode === 'team') {
|
|
41
|
+
const ref = localMainCommit(vault);
|
|
42
|
+
const file = 'sources/' + id + '.json';
|
|
43
|
+
if (ref && git(vault.root, 'ls-tree', '-z', '--name-only', ref, '--', file))
|
|
44
|
+
return parseManifest(git(vault.root, 'show', ref + ':' + file), id);
|
|
45
|
+
}
|
|
46
|
+
return manifest(vault, id);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function manifests(vault) {
|
|
50
|
+
const files = await fs.readdir(await dir(vault.root, 'sources'));
|
|
51
|
+
return Promise.all(files.filter(f => f.endsWith('.json') && idTypes.source.test(f.slice(0, -5)))
|
|
52
|
+
.sort().map(f => manifest(vault, f.slice(0, -5))));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function verifiedPath(vault, source) {
|
|
56
|
+
const file = await objectPath(vault.local, source.sha256);
|
|
57
|
+
checkBytes(await fingerprint(file), source);
|
|
58
|
+
return file;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function detectKind(file) {
|
|
62
|
+
requireThat(!/-(wal|shm|journal)$/i.test(file), 'SQLITE', 'Import the SQLite database itself for an online backup');
|
|
63
|
+
const handle = await fs.open(file, 'r');
|
|
64
|
+
const header = Buffer.alloc(16);
|
|
65
|
+
try { await handle.read(header, 0, header.length, 0); } finally { await handle.close(); }
|
|
66
|
+
if (header.toString('latin1') === 'SQLite format 3\u0000' || /\.(sqlite3?|db)$/i.test(file)) return 'sqlite';
|
|
67
|
+
if (header.subarray(0, 5).toString() === '%PDF-') return 'pdf';
|
|
68
|
+
const ext = path.extname(file).toLowerCase();
|
|
69
|
+
if (['.txt', '.md', '.csv', '.tsv'].includes(ext)) return 'text';
|
|
70
|
+
if (['.html', '.htm'].includes(ext)) return 'html';
|
|
71
|
+
return 'binary';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function python(command, args) {
|
|
75
|
+
return run(process.env.KNOWPOOL_PYTHON || 'python3', ['-I', adapter, command, ...args]);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function addSource(vault, fileName, url = null) {
|
|
79
|
+
allowContribution(vault);
|
|
80
|
+
const input = path.resolve(fileName);
|
|
81
|
+
requireThat((await statOrNull(input))?.isFile(), 'FILE', 'Import a regular file');
|
|
82
|
+
const origin = validUrl(url);
|
|
83
|
+
const kind = await detectKind(input);
|
|
84
|
+
let data;
|
|
85
|
+
if (kind === 'sqlite') {
|
|
86
|
+
const folder = await fs.mkdtemp(path.join(await dir(vault.local, 'tmp'), 'backup-'));
|
|
87
|
+
const snap = path.join(folder, 'snapshot.sqlite');
|
|
88
|
+
try { python('backup', [input, snap]); data = await storeBytes(vault.local, snap); }
|
|
89
|
+
finally { await fs.rm(folder, { recursive: true, force: true }); }
|
|
90
|
+
} else data = await storeBytes(vault.local, input);
|
|
91
|
+
const id = 'src_' + data.sha256;
|
|
92
|
+
const out = path.join(await dir(vault.root, 'sources'), id + '.json');
|
|
93
|
+
if (await statOrNull(out)) return { ...await manifest(vault, id), duplicate: true };
|
|
94
|
+
const m = { format: 1, id, ...data, filename: path.basename(input), kind, url: origin, created: new Date().toISOString() };
|
|
95
|
+
parseManifest(json(m), id);
|
|
96
|
+
await atomicText(out, json(m));
|
|
97
|
+
return { ...m, duplicate: false };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function validateLocator(source, at) {
|
|
101
|
+
const match = /^(line|para|page):([1-9]\d*)$/.exec(at);
|
|
102
|
+
requireThat(match && Number.isSafeInteger(Number(match[2])) && match[1] === locatorKinds[source.kind],
|
|
103
|
+
'LOCATOR', 'Expected a supported locator for ' + source.kind + ': ' + (locatorKinds[source.kind] || 'archive only'));
|
|
104
|
+
return Number(match[2]);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function readAt(vault, id, at, lookup = manifest) {
|
|
108
|
+
const m = await lookup(vault, id);
|
|
109
|
+
const number = validateLocator(m, at);
|
|
110
|
+
const file = await verifiedPath(vault, m);
|
|
111
|
+
let text;
|
|
112
|
+
if (m.kind === 'text') {
|
|
113
|
+
const stream = createReadStream(file, { encoding: 'utf8' });
|
|
114
|
+
const lines = createInterface({ input: stream, crlfDelay: Infinity });
|
|
115
|
+
let index = 0;
|
|
116
|
+
try { for await (const line of lines) { if (++index === number) { text = line; break; } } }
|
|
117
|
+
finally { lines.close(); stream.destroy(); }
|
|
118
|
+
} else if (m.kind === 'html') {
|
|
119
|
+
text = python('paragraph', [file, String(number)]);
|
|
120
|
+
} else {
|
|
121
|
+
text = run(process.env.KNOWPOOL_PDFTOTEXT || 'pdftotext',
|
|
122
|
+
['-f', String(number), '-l', String(number), '-enc', 'UTF-8', '-layout', file, '-']);
|
|
123
|
+
}
|
|
124
|
+
requireThat(text?.trim(), 'LOCATOR', 'No extractable text at ' + at);
|
|
125
|
+
return { source: id, filename: m.filename, at, text: text.trim() };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function getSource(vault, id, name) {
|
|
129
|
+
const m = await readableManifest(vault, id);
|
|
130
|
+
const out = path.resolve(name);
|
|
131
|
+
const folder = await fs.realpath(path.dirname(out));
|
|
132
|
+
const target = path.join(folder, path.basename(out));
|
|
133
|
+
requireThat(!inside(vault.root, target), 'PATH', 'Export the original outside the vault');
|
|
134
|
+
await copyBytes(await objectPath(vault.local, m.sha256), folder, () => target, m);
|
|
135
|
+
return { source: id, path: target, sha256: m.sha256, bytes: m.size };
|
|
136
|
+
}
|
package/src/storage.mjs
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
|
+
import { checkBytes, dir, fingerprint, inside, objectPath, requireThat, run, statOrNull, storeBytes } from './io.mjs';
|
|
5
|
+
|
|
6
|
+
export async function external(vault, name) {
|
|
7
|
+
const folder = await fs.realpath(name);
|
|
8
|
+
requireThat((await fs.stat(folder)).isDirectory() && !inside(vault.root, folder) && !inside(folder, vault.root),
|
|
9
|
+
'PATH', 'Choose a separate directory outside the vault');
|
|
10
|
+
return folder;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async function transfer(from, to, m) {
|
|
14
|
+
const target = await objectPath(to, m.sha256);
|
|
15
|
+
if (await statOrNull(target)) { checkBytes(await fingerprint(target), m); return; }
|
|
16
|
+
await storeBytes(to, await objectPath(from, m.sha256), m);
|
|
17
|
+
checkBytes(await fingerprint(target), m);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function rclone(...args) {
|
|
21
|
+
for (let attempt = 0; ; attempt++) {
|
|
22
|
+
try {
|
|
23
|
+
return run('rclone', [...args, '--retries', '2', '--low-level-retries', '3', '--contimeout', '15s',
|
|
24
|
+
'--timeout', '2m', '--tpslimit', '2', '--tpslimit-burst', '1']);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (attempt >= 2 || !/requests per minute|rateLimitExceeded|userRateLimitExceeded|429 Too Many Requests/i.test(error.message)) throw error;
|
|
27
|
+
await delay(attempt === 0 ? 20000 : 60000);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function backend(name) {
|
|
33
|
+
try {
|
|
34
|
+
const list = (await rclone('listremotes', '--long')).split('\n').map(line => line.trim().split(/\s+/));
|
|
35
|
+
return list.find(([remote]) => remote === name)?.[1];
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if (!/unknown flag|flag provided but not defined/i.test(error.message)) throw error;
|
|
38
|
+
const features = JSON.parse(await rclone('backend', 'features', name));
|
|
39
|
+
if (features.Features?.IsLocal) return 'local';
|
|
40
|
+
return /^Google drive root/i.test(features.String) ? 'drive' : 'other';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function openStore(vault, { storeDir, cloud }, create = false) {
|
|
45
|
+
requireThat(Boolean(storeDir) !== Boolean(cloud), 'USAGE', 'Select one store using --store or --cloud');
|
|
46
|
+
if (storeDir) {
|
|
47
|
+
const root = await external(vault, storeDir);
|
|
48
|
+
const store = create ? await dir(root, vault.config.id) : path.join(root, vault.config.id);
|
|
49
|
+
requireThat((await statOrNull(store))?.isDirectory(), 'STORE', 'No object namespace for this vault');
|
|
50
|
+
return { type: 'directory', root, push: m => transfer(vault.local, store, m), pull: m => transfer(store, vault.local, m) };
|
|
51
|
+
}
|
|
52
|
+
const match = /^([A-Za-z0-9][\w.-]*):(.+)$/.exec(cloud);
|
|
53
|
+
requireThat(match && !/[\x00-\x1f\\]/.test(cloud) && !match[2].split('/').includes('..'),
|
|
54
|
+
'STORE', 'Supply a named rclone remote and its folder');
|
|
55
|
+
const name = match[1] + ':';
|
|
56
|
+
const type = await backend(name);
|
|
57
|
+
requireThat(type === 'drive' || type === 'local', 'STORE', 'This release supports named Google Drive and local rclone backends');
|
|
58
|
+
const prefix = cloud.replace(/\/+$/, '') + '/' + vault.config.id;
|
|
59
|
+
const root = type === 'local' ? await external(vault, match[2]) : null;
|
|
60
|
+
const remoteFile = m => prefix + '/objects/sha256/' + m.sha256.slice(0, 2) + '/' + m.sha256;
|
|
61
|
+
async function receive(m, install) {
|
|
62
|
+
const folder = await fs.mkdtemp(path.join(await dir(vault.local, 'tmp'), 'readback-'));
|
|
63
|
+
const file = path.join(folder, 'object');
|
|
64
|
+
try {
|
|
65
|
+
await rclone('copyto', remoteFile(m), file);
|
|
66
|
+
if (install) await storeBytes(vault.local, file, m);
|
|
67
|
+
else checkBytes(await fingerprint(file), m);
|
|
68
|
+
} catch (e) { throw Object.assign(new Error(m.id + ': ' + e.message), { code: e.code }); }
|
|
69
|
+
finally { await fs.rm(folder, { recursive: true, force: true }); }
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
type, root,
|
|
73
|
+
async push(m) {
|
|
74
|
+
const file = await objectPath(vault.local, m.sha256);
|
|
75
|
+
if (await statOrNull(file)) {
|
|
76
|
+
checkBytes(await fingerprint(file), m);
|
|
77
|
+
await rclone('copyto', file, remoteFile(m), '--ignore-existing');
|
|
78
|
+
}
|
|
79
|
+
await receive(m, false);
|
|
80
|
+
},
|
|
81
|
+
async pull(m) {
|
|
82
|
+
const target = await objectPath(vault.local, m.sha256);
|
|
83
|
+
if (await statOrNull(target)) checkBytes(await fingerprint(target), m);
|
|
84
|
+
else await receive(m, true);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
package/src/vault.mjs
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { atomicText, branch, dir, git, json, readFile, requireThat, statOrNull } from './io.mjs';
|
|
5
|
+
|
|
6
|
+
export const configFile = 'knowpool.json';
|
|
7
|
+
export const vaultIgnore = '/.knowpool/\n/.agents/skills/knowpool/\n.DS_Store\n';
|
|
8
|
+
const uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
|
|
9
|
+
export const idTypes = {
|
|
10
|
+
vault: new RegExp('^vault_' + uuid + '$'),
|
|
11
|
+
note: new RegExp('^note_' + uuid + '$'),
|
|
12
|
+
draft: new RegExp('^draft_' + uuid + '$'),
|
|
13
|
+
source: /^src_[0-9a-f]{64}$/
|
|
14
|
+
};
|
|
15
|
+
export function idOf(type, value) {
|
|
16
|
+
requireThat(typeof value === 'string' && idTypes[type].test(value), 'ID', 'Invalid ' + type + ' ID');
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function parseConfig(text) {
|
|
21
|
+
const value = JSON.parse(text);
|
|
22
|
+
requireThat(value.format === 1 && ['personal', 'team'].includes(value.mode)
|
|
23
|
+
&& value.defaultBranch === 'main', 'FORMAT', 'Unsupported vault format, mode or default branch');
|
|
24
|
+
idOf('vault', value.id);
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function openVault(name) {
|
|
29
|
+
const root = await fs.realpath(name);
|
|
30
|
+
const config = parseConfig(await readFile(path.join(root, configFile)));
|
|
31
|
+
requireThat(await fs.realpath(git(root, 'rev-parse', '--show-toplevel').trim()) === root,
|
|
32
|
+
'VAULT', 'Use the root of an independent knowledge repository');
|
|
33
|
+
const local = await dir(root, '.knowpool');
|
|
34
|
+
return { root, config, local };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function initVault(name, mode) {
|
|
38
|
+
requireThat(mode === undefined || ['personal', 'team'].includes(mode), 'MODE', 'Choose personal or team');
|
|
39
|
+
const absolute = path.resolve(name);
|
|
40
|
+
await fs.mkdir(path.dirname(absolute), { recursive: true });
|
|
41
|
+
const existing = await statOrNull(absolute);
|
|
42
|
+
const root = existing ? await fs.realpath(absolute) : path.join(await fs.realpath(path.dirname(absolute)), path.basename(absolute));
|
|
43
|
+
async function reopen() {
|
|
44
|
+
const vault = await openVault(root);
|
|
45
|
+
requireThat(mode === undefined || vault.config.mode === mode, 'MODE', 'Existing vault has a different mode');
|
|
46
|
+
return { ...vault.config, root, existing: true };
|
|
47
|
+
}
|
|
48
|
+
if (existing && await statOrNull(path.join(root, configFile))) return reopen();
|
|
49
|
+
requireThat(!existing || (await fs.readdir(root)).length === 0, 'VAULT', 'Initialize an empty directory');
|
|
50
|
+
let parentRepo;
|
|
51
|
+
try { parentRepo = git(path.dirname(root), 'rev-parse', '--show-toplevel').trim(); } catch { /* new repository */ }
|
|
52
|
+
requireThat(!parentRepo, 'VAULT', 'Create the knowledge repository outside other Git worktrees');
|
|
53
|
+
const config = { format: 1, id: 'vault_' + randomUUID(), mode: mode ?? 'personal', defaultBranch: 'main' };
|
|
54
|
+
const staging = await fs.mkdtemp(path.join(path.dirname(root), '.knowpool-init-'));
|
|
55
|
+
try {
|
|
56
|
+
git(staging, 'init', '-b', 'main');
|
|
57
|
+
await atomicText(path.join(staging, '.gitignore'), vaultIgnore);
|
|
58
|
+
await atomicText(path.join(staging, configFile), json(config));
|
|
59
|
+
if (existing) await fs.chmod(staging, (await fs.stat(root)).mode & 0o777);
|
|
60
|
+
try { await fs.rename(staging, root); }
|
|
61
|
+
catch (e) {
|
|
62
|
+
if (['EEXIST', 'ENOTEMPTY'].includes(e.code) && await statOrNull(path.join(root, configFile))) return reopen();
|
|
63
|
+
throw e;
|
|
64
|
+
}
|
|
65
|
+
} finally { await fs.rm(staging, { recursive: true, force: true }); }
|
|
66
|
+
return { ...config, root, existing: false };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function localMainCommit(vault) {
|
|
70
|
+
const name = 'refs/heads/' + vault.config.defaultBranch;
|
|
71
|
+
const refs = git(vault.root, 'for-each-ref', '--format=%(refname) %(objectname)', name);
|
|
72
|
+
return refs.split('\n').find(line => line.startsWith(name + ' '))?.slice(name.length + 1);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function allowContribution(vault) {
|
|
76
|
+
if (vault.config.mode === 'team') requireThat(branch(vault.root) !== vault.config.defaultBranch,
|
|
77
|
+
'BRANCH', 'Create a contribution branch before changing team knowledge');
|
|
78
|
+
}
|