@ureck/alexandria 0.2.0

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.
@@ -0,0 +1,231 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ listMarkdownFiles,
4
+ parseNote
5
+ } from "./chunk-CZM5NQZJ.js";
6
+ import {
7
+ DIM,
8
+ MODEL_ID,
9
+ chunkMarkdown,
10
+ dot,
11
+ embed,
12
+ modelPresent
13
+ } from "./chunk-EDYBSJSS.js";
14
+
15
+ // src/core/index.ts
16
+ import fs from "fs";
17
+ import path from "path";
18
+ var SEMANTIC_THRESHOLD = 0.9;
19
+ var SEMANTIC_TOP = 3;
20
+ var VaultIndex = class _VaultIndex {
21
+ constructor(vault) {
22
+ this.vault = vault;
23
+ this.meta = {
24
+ version: 1,
25
+ model: MODEL_ID,
26
+ dim: DIM,
27
+ mtimes: {},
28
+ notes: {},
29
+ chunks: [],
30
+ links: []
31
+ };
32
+ }
33
+ vault;
34
+ meta;
35
+ /** filas de embeddings alineadas 1:1 con meta.chunks; null = índice sin vectores */
36
+ emb = null;
37
+ get metaPath() {
38
+ return path.join(this.vault.cache, "meta.json");
39
+ }
40
+ get embPath() {
41
+ return path.join(this.vault.cache, "embeddings.bin");
42
+ }
43
+ static load(vault) {
44
+ const idx = new _VaultIndex(vault);
45
+ try {
46
+ const meta = JSON.parse(fs.readFileSync(idx.metaPath, "utf8"));
47
+ if (meta.version === 1 && meta.model === MODEL_ID) {
48
+ idx.meta = meta;
49
+ try {
50
+ const buf = fs.readFileSync(idx.embPath);
51
+ const arr = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);
52
+ if (arr.length === meta.chunks.length * meta.dim) idx.emb = arr.slice();
53
+ } catch {
54
+ idx.emb = null;
55
+ }
56
+ }
57
+ } catch {
58
+ }
59
+ return idx;
60
+ }
61
+ save() {
62
+ fs.mkdirSync(this.vault.cache, { recursive: true });
63
+ fs.writeFileSync(this.metaPath, JSON.stringify(this.meta));
64
+ if (this.emb) {
65
+ fs.writeFileSync(this.embPath, Buffer.from(this.emb.buffer, this.emb.byteOffset, this.emb.byteLength));
66
+ }
67
+ }
68
+ row(i) {
69
+ return this.emb.subarray(i * this.meta.dim, (i + 1) * this.meta.dim);
70
+ }
71
+ /**
72
+ * Reindexado incremental por mtime. Solo procesa archivos nuevos/cambiados.
73
+ * `withEmbeddings=false` → índice keyword-only (sin cargar modelo).
74
+ */
75
+ async refresh(withEmbeddings = modelPresent(), force = false) {
76
+ const files = listMarkdownFiles(this.vault.root);
77
+ const onDisk = /* @__PURE__ */ new Map();
78
+ for (const abs of files) {
79
+ const rel = path.relative(this.vault.root, abs).split(path.sep).join("/");
80
+ onDisk.set(rel, { abs, mtime: fs.statSync(abs).mtimeMs });
81
+ }
82
+ const changed = [];
83
+ for (const [rel, info] of onDisk) {
84
+ if (force || this.meta.mtimes[rel] !== info.mtime) changed.push(rel);
85
+ }
86
+ const removed = Object.keys(this.meta.mtimes).filter((rel) => !onDisk.has(rel));
87
+ if (changed.length === 0 && removed.length === 0) {
88
+ return { changed: 0, removed: 0, embedded: this.emb !== null };
89
+ }
90
+ const keep = new Set(
91
+ this.meta.chunks.map((_, i) => i).filter((i) => {
92
+ const rel = this.meta.chunks[i].note;
93
+ return onDisk.has(rel) && !changed.includes(rel);
94
+ })
95
+ );
96
+ const newChunks = [];
97
+ const keptRows = [];
98
+ const hadEmb = this.emb !== null;
99
+ for (const i of keep) {
100
+ newChunks.push(this.meta.chunks[i]);
101
+ if (hadEmb) keptRows.push(this.row(i).slice());
102
+ }
103
+ const freshChunks = [];
104
+ for (const rel of changed) {
105
+ const info = onDisk.get(rel);
106
+ try {
107
+ const note = parseNote(this.vault.root, info.abs);
108
+ this.meta.notes[rel] = {
109
+ rel,
110
+ title: note.title,
111
+ type: note.type,
112
+ tags: note.tags,
113
+ created: note.created,
114
+ hits: note.hits,
115
+ links: note.links
116
+ };
117
+ const pieces = chunkMarkdown(note.content);
118
+ const titlePrefix = note.title ? `${note.title}. ` : "";
119
+ for (const p of pieces) {
120
+ freshChunks.push({ note: rel, heading: p.heading, text: p.text });
121
+ }
122
+ if (pieces.length === 0 && note.title) {
123
+ freshChunks.push({ note: rel, text: titlePrefix });
124
+ }
125
+ } catch {
126
+ }
127
+ this.meta.mtimes[rel] = info.mtime;
128
+ }
129
+ for (const rel of removed) {
130
+ delete this.meta.mtimes[rel];
131
+ delete this.meta.notes[rel];
132
+ }
133
+ for (const rel of Object.keys(this.meta.notes)) {
134
+ if (!onDisk.has(rel)) delete this.meta.notes[rel];
135
+ }
136
+ let embedded = hadEmb || newChunks.length === 0;
137
+ let freshRows = [];
138
+ if (withEmbeddings && freshChunks.length > 0) {
139
+ try {
140
+ freshRows = await embed(
141
+ freshChunks.map((c) => `${this.meta.notes[c.note]?.title ?? ""}
142
+ ${c.heading ?? ""}
143
+ ${c.text}`),
144
+ "passage"
145
+ );
146
+ embedded = true;
147
+ } catch {
148
+ embedded = false;
149
+ }
150
+ } else if (freshChunks.length > 0) {
151
+ embedded = false;
152
+ }
153
+ this.meta.chunks = [...newChunks, ...freshChunks];
154
+ if (embedded && (hadEmb || newChunks.length === 0) && freshRows.length === freshChunks.length) {
155
+ const all = new Float32Array(this.meta.chunks.length * this.meta.dim);
156
+ [...keptRows, ...freshRows].forEach((r, i) => all.set(r, i * this.meta.dim));
157
+ this.emb = all;
158
+ } else if (freshChunks.length > 0 && !embedded) {
159
+ this.emb = null;
160
+ }
161
+ this.rebuildLinks();
162
+ this.save();
163
+ return { changed: changed.length, removed: removed.length, embedded: this.emb !== null };
164
+ }
165
+ /** Wikilinks (título → nota) + links semánticos (similitud entre notas). */
166
+ rebuildLinks() {
167
+ const byTitle = /* @__PURE__ */ new Map();
168
+ for (const n of Object.values(this.meta.notes)) {
169
+ byTitle.set(n.title.toLowerCase(), n.rel);
170
+ byTitle.set(n.rel.replace(/\.md$/, "").split("/").pop().toLowerCase(), n.rel);
171
+ }
172
+ const links = [];
173
+ for (const n of Object.values(this.meta.notes)) {
174
+ for (const target of n.links) {
175
+ const to = byTitle.get(target.toLowerCase());
176
+ if (to && to !== n.rel) links.push({ from: n.rel, to, type: "wikilink" });
177
+ }
178
+ }
179
+ if (this.emb) {
180
+ const rels = Object.keys(this.meta.notes);
181
+ const noteVec = /* @__PURE__ */ new Map();
182
+ for (const rel of rels) {
183
+ const idxs = this.meta.chunks.map((c, i) => c.note === rel ? i : -1).filter((i) => i >= 0);
184
+ if (idxs.length === 0) continue;
185
+ const v = new Float32Array(this.meta.dim);
186
+ for (const i of idxs) {
187
+ const r = this.row(i);
188
+ for (let d = 0; d < this.meta.dim; d++) v[d] += r[d];
189
+ }
190
+ let norm = 0;
191
+ for (let d = 0; d < this.meta.dim; d++) norm += v[d] * v[d];
192
+ norm = Math.sqrt(norm) || 1;
193
+ for (let d = 0; d < this.meta.dim; d++) v[d] /= norm;
194
+ noteVec.set(rel, v);
195
+ }
196
+ const seen = new Set(links.map((l) => `${l.from}\u2192${l.to}`));
197
+ const vecRels = [...noteVec.keys()];
198
+ for (const a of vecRels) {
199
+ const sims = [];
200
+ for (const b of vecRels) {
201
+ if (a === b) continue;
202
+ sims.push({ rel: b, s: dot(noteVec.get(a), noteVec.get(b)) });
203
+ }
204
+ sims.sort((x, y) => y.s - x.s);
205
+ for (const { rel: b, s } of sims.slice(0, SEMANTIC_TOP)) {
206
+ if (s < SEMANTIC_THRESHOLD) break;
207
+ const key = a < b ? `${a}\u2192${b}` : `${b}\u2192${a}`;
208
+ if (seen.has(key) || seen.has(`${a}\u2192${b}`) || seen.has(`${b}\u2192${a}`)) continue;
209
+ seen.add(key);
210
+ links.push({ from: a, to: b, type: "semantic", w: Math.round(s * 100) / 100 });
211
+ }
212
+ }
213
+ }
214
+ this.meta.links = links;
215
+ }
216
+ /** Vecinos directos de una nota en el grafo (sin releer archivos). */
217
+ neighbors(rel) {
218
+ const out = [];
219
+ for (const l of this.meta.links) {
220
+ const other = l.from === rel ? l.to : l.to === rel ? l.from : null;
221
+ if (other && this.meta.notes[other]) {
222
+ out.push({ note: this.meta.notes[other], type: l.type, w: l.w });
223
+ }
224
+ }
225
+ return out;
226
+ }
227
+ };
228
+
229
+ export {
230
+ VaultIndex
231
+ };