@ureck/alexandria 1.0.0 → 1.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.
- package/README.md +17 -2
- package/dist/chunk-53SIGH5A.js +69 -0
- package/dist/{chunk-DYCARGQR.js → chunk-CIOCSIB5.js} +50 -0
- package/dist/{chunk-DCKYTO4O.js → chunk-FBGIFNIO.js} +1 -1
- package/dist/chunk-QB37UGO6.js +490 -0
- package/dist/{chunk-RZI7TYAG.js → chunk-UWB6RKVN.js} +2 -1
- package/dist/{chunk-DHXL36RG.js → chunk-ZIQYAQCF.js} +19 -33
- package/dist/cli.js +574 -159
- package/dist/hooks/on-prompt.js +41 -27
- package/dist/hooks/on-session-start.js +9 -9
- package/dist/hooks/on-stop.js +27 -3
- package/dist/mcp/server.js +10 -10
- package/dist/{viewer-73ZWPIDC.js → viewer-JQCSWJ3C.js} +2 -3
- package/package.json +1 -1
- package/dist/chunk-D5ROL42O.js +0 -267
- package/dist/chunk-DEDAOKAV.js +0 -44
- package/dist/chunk-XWR74BQ2.js +0 -170
package/README.md
CHANGED
|
@@ -63,7 +63,7 @@ Verify:
|
|
|
63
63
|
|
|
64
64
|
```bash
|
|
65
65
|
$ ale --version
|
|
66
|
-
1.
|
|
66
|
+
1.2.0
|
|
67
67
|
```
|
|
68
68
|
|
|
69
69
|
## Getting started
|
|
@@ -132,6 +132,18 @@ ale add "Vercel deploy" -c "Region cdg1, see [[Prisma setup]]" -t deploy
|
|
|
132
132
|
|
|
133
133
|
(Automatic capture via hooks already does this in every Claude Code session — `add` is for extra knowledge.)
|
|
134
134
|
|
|
135
|
+
### Control what spends tokens (`ale toggles`)
|
|
136
|
+
|
|
137
|
+
Every token-spending behavior is opt-out — before or after installing (the config is global, independent of the vault):
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
$ ale toggles # interactive menu: each toggle with its real approximate cost
|
|
141
|
+
ale init --off architect.enrich,digest.map # disable from the start
|
|
142
|
+
ale config set tokens.solutionCache false # scriptable, one by one
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
The six toggles: Protocol manifest (~6% of the session digest), Architect enrichment in `plan_create` (~+90 tokens/plan), solution cache (up to ~500 tokens/prompt), per-prompt semantic search (the **main saving mechanism** — up to ~1500 tokens/prompt, disabling it defeats the point), project map in the digest (up to ~1000 tokens), title index (~200 tokens). All on by default; nothing changes unless you touch them.
|
|
146
|
+
|
|
135
147
|
### Deep project context (`ale scan`)
|
|
136
148
|
|
|
137
149
|
`ale init --project` already runs it; re-run anytime the project changes:
|
|
@@ -147,6 +159,7 @@ Four read-only scanners write compact notes (one line per entry) that the agent
|
|
|
147
159
|
- **`Env - <project>`** — environment variable **NAMES only, never values** (from `.env.example` / `.env` / `.env.local`).
|
|
148
160
|
- **`Datos - <project>`** — data schema parsed from files (prisma models, drizzle tables, `CREATE TABLE` in migrations) — no DB connection.
|
|
149
161
|
- **`Convenciones - <project>`** — package manager, monorepo, TS strict, import aliases, framework.
|
|
162
|
+
- **`Flujo - <project>`** — what a request goes through: `GET /api/x → auth: requirePermiso(...) → datos: getX, createX → audits`, plus what the middleware protects. The others say what exists; this one says how it connects.
|
|
150
163
|
|
|
151
164
|
It never touches your source code, and it guarantees the vault (and personal configs) are gitignored before writing — your notes never reach a shared repo, even if you never ran `ale init`.
|
|
152
165
|
|
|
@@ -277,7 +290,9 @@ AI agent session
|
|
|
277
290
|
| Command | What it does |
|
|
278
291
|
|---|---|
|
|
279
292
|
| `ale init [--project] [--path <dir>] [--agents <ids>] [--auto\|--manual] [--no-protocol] [--portable]` | Installs everything: vault, hooks, MCP, .gitignore, project scan, CLAUDE.md. `--portable` writes an npx-based MCP command safe to commit for teams |
|
|
280
|
-
| `ale scan` | Deep project context: API routes, env var **names**, data schema (file parse), conventions → compact notes. Read-only; ensures .gitignore |
|
|
293
|
+
| `ale scan` | Deep project context: API routes, env var **names**, data schema (file parse), conventions → compact notes (adaptive cap ≤200 entries, fair sampling in monorepos). Read-only; ensures .gitignore |
|
|
294
|
+
| `ale toggles` | Interactive menu to enable/disable every token-spending behavior, each with its real approximate cost. Works before or after install; scriptable via `ale init --off <keys>` |
|
|
295
|
+
| `ale skills:evolve` | Generates/updates a **living skill for the project** from what the vault knows (stack, conventions, app flow, lessons). Always shows a diff and asks before writing |
|
|
281
296
|
| `ale agents [ids] [--project]` | List agents / register the MCP server |
|
|
282
297
|
| `ale search <query> [-k n] [--expand]` | Hybrid search; `--expand` pulls graph neighbors. With the Protocol on, appends the **chain** (plan + verification + lesson) connected to the top hit |
|
|
283
298
|
| `ale add <title> [-c text] [--file <path>] [-t tags]` | Save a note (inline, from file, or stdin) |
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/hooks/util.ts
|
|
4
|
+
import fs from "fs";
|
|
5
|
+
import os from "os";
|
|
6
|
+
import path from "path";
|
|
7
|
+
async function readStdinJson() {
|
|
8
|
+
const chunks = [];
|
|
9
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
10
|
+
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
11
|
+
if (!raw) return {};
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(raw);
|
|
14
|
+
} catch {
|
|
15
|
+
return {};
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
var expired = false;
|
|
19
|
+
function logHookError(kind, detail) {
|
|
20
|
+
try {
|
|
21
|
+
const dir = process.platform === "win32" && process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "alexandria") : path.join(os.homedir(), ".cache", "alexandria");
|
|
22
|
+
const file = path.join(dir, "hook-errors.log");
|
|
23
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
24
|
+
try {
|
|
25
|
+
if (fs.statSync(file).size > 256 * 1024) fs.rmSync(file, { force: true });
|
|
26
|
+
} catch {
|
|
27
|
+
}
|
|
28
|
+
fs.appendFileSync(file, `${(/* @__PURE__ */ new Date()).toISOString()} ${kind} ${detail.slice(0, 500)}
|
|
29
|
+
`);
|
|
30
|
+
} catch {
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function runHook(budgetMs, body) {
|
|
34
|
+
process.env.ALEXANDRIA_HOOK = "1";
|
|
35
|
+
const cleanup = async () => {
|
|
36
|
+
try {
|
|
37
|
+
const { disposeEmbedder } = await import("./embedder-7Z4XNL6H.js");
|
|
38
|
+
await disposeEmbedder();
|
|
39
|
+
} catch {
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const timer = setTimeout(() => {
|
|
43
|
+
expired = true;
|
|
44
|
+
logHookError("timeout", `presupuesto de ${budgetMs}ms agotado`);
|
|
45
|
+
void cleanup();
|
|
46
|
+
}, budgetMs);
|
|
47
|
+
timer.unref();
|
|
48
|
+
process.exitCode = 0;
|
|
49
|
+
readStdinJson().then((input) => body(input)).catch((e) => {
|
|
50
|
+
logHookError("error", e instanceof Error ? `${e.message}
|
|
51
|
+
${e.stack ?? ""}` : String(e));
|
|
52
|
+
}).finally(() => {
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
void cleanup();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function projectName(cwd) {
|
|
58
|
+
if (!cwd) return "general";
|
|
59
|
+
return cwd.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || "general";
|
|
60
|
+
}
|
|
61
|
+
function truncate(text, max) {
|
|
62
|
+
return text.length <= max ? text : text.slice(0, max) + " \u2026";
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export {
|
|
66
|
+
runHook,
|
|
67
|
+
projectName,
|
|
68
|
+
truncate
|
|
69
|
+
};
|
|
@@ -95,6 +95,54 @@ function protocolEnabled() {
|
|
|
95
95
|
const v = getConfigKey("protocol");
|
|
96
96
|
return v !== false && v !== "false";
|
|
97
97
|
}
|
|
98
|
+
function toggleEnabled(key) {
|
|
99
|
+
const v = getConfigKey(key);
|
|
100
|
+
return v !== false && v !== "false";
|
|
101
|
+
}
|
|
102
|
+
var TOKEN_TOGGLES = [
|
|
103
|
+
{
|
|
104
|
+
key: "protocol",
|
|
105
|
+
label: "Protocolo Alexandria",
|
|
106
|
+
desc: "Ciclo plan \u2192 verificar \u2192 aprender (manifiesto en el digest + tools MCP)",
|
|
107
|
+
impact: "cuesta ~6% del digest (~120 tokens); su ahorro es diferido: lecciones evitan re-debug"
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
key: "architect.enrich",
|
|
111
|
+
label: "Arquitecto en plan_create",
|
|
112
|
+
desc: "Planes similares + lecciones + hints de calidad en cada plan nuevo",
|
|
113
|
+
impact: "encarece cada plan_create ~2-3\xD7 (~+90-110 tokens); apuesta a no duplicar trabajo"
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
key: "tokens.solutionCache",
|
|
117
|
+
label: "Cach\xE9 de soluciones",
|
|
118
|
+
desc: "Si un prompt casi id\xE9ntico ya se resolvi\xF3, inyecta esa soluci\xF3n",
|
|
119
|
+
impact: "cuesta hasta ~33% del presupuesto por prompt (~500 tokens); evita re-derivar completo"
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
key: "tokens.promptSearch",
|
|
123
|
+
label: "B\xFAsqueda sem\xE1ntica por prompt",
|
|
124
|
+
desc: "Inyecta fragmentos relevantes de la b\xF3veda en cada prompt \u2014 el mecanismo PRINCIPAL de ahorro",
|
|
125
|
+
impact: "cuesta hasta ~1500 tokens/prompt; apagarlo apaga la raz\xF3n de ser de Alexandria"
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
key: "digest.map",
|
|
129
|
+
label: "Mapa del proyecto al iniciar sesi\xF3n",
|
|
130
|
+
desc: "Inyecta el mapa (stack, estructura, decisiones) en el digest de SessionStart",
|
|
131
|
+
impact: "cuesta hasta ~50% del digest (~1000 tokens); evita re-explorar el proyecto"
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
key: "digest.titleIndex",
|
|
135
|
+
label: "\xCDndice de t\xEDtulos en el digest",
|
|
136
|
+
desc: "Lista hasta 25 t\xEDtulos de lo que la b\xF3veda ya sabe",
|
|
137
|
+
impact: "cuesta ~10% del digest (~200 tokens); orienta al agente sobre qu\xE9 buscar"
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
key: "index.autoRebuild",
|
|
141
|
+
label: "Reparar el \xEDndice al cerrar sesi\xF3n",
|
|
142
|
+
desc: "Si el \xEDndice qued\xF3 sin vectores, reconstruirlo en segundo plano al terminar la sesi\xF3n",
|
|
143
|
+
impact: "no gasta tokens; sin esto la b\xFAsqueda puede quedarse en keyword-only (peor contexto por prompt)"
|
|
144
|
+
}
|
|
145
|
+
];
|
|
98
146
|
function writeProjectConfig(projectDir, vaultPath) {
|
|
99
147
|
const file = path.join(projectDir, ".vault.json");
|
|
100
148
|
const rel = path.relative(projectDir, vaultPath) || ".";
|
|
@@ -113,5 +161,7 @@ export {
|
|
|
113
161
|
getConfigKey,
|
|
114
162
|
setConfigKey,
|
|
115
163
|
protocolEnabled,
|
|
164
|
+
toggleEnabled,
|
|
165
|
+
TOKEN_TOGGLES,
|
|
116
166
|
writeProjectConfig
|
|
117
167
|
};
|
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
DIM,
|
|
4
|
+
MODEL_ID,
|
|
5
|
+
chunkMarkdown,
|
|
6
|
+
dot,
|
|
7
|
+
embed,
|
|
8
|
+
modelPresent
|
|
9
|
+
} from "./chunk-EDYBSJSS.js";
|
|
10
|
+
|
|
11
|
+
// src/core/notes.ts
|
|
12
|
+
import fs from "fs";
|
|
13
|
+
import path from "path";
|
|
14
|
+
import matter from "gray-matter";
|
|
15
|
+
var NOTE_TYPES = [
|
|
16
|
+
"note",
|
|
17
|
+
"prompt",
|
|
18
|
+
"session",
|
|
19
|
+
"map",
|
|
20
|
+
"plan",
|
|
21
|
+
"task",
|
|
22
|
+
"verification",
|
|
23
|
+
"lesson",
|
|
24
|
+
"solution"
|
|
25
|
+
];
|
|
26
|
+
var SKIP_DIRS = /* @__PURE__ */ new Set([".obsidian", ".vault", ".trash", ".git", "node_modules"]);
|
|
27
|
+
function extractWikilinks(content) {
|
|
28
|
+
const out = /* @__PURE__ */ new Set();
|
|
29
|
+
const re = /\[\[([^\]|#\n]+)(?:[|#][^\]]*)?\]\]/g;
|
|
30
|
+
let m;
|
|
31
|
+
while ((m = re.exec(content)) !== null) {
|
|
32
|
+
const target = m[1].trim();
|
|
33
|
+
if (target) out.add(target);
|
|
34
|
+
}
|
|
35
|
+
return [...out];
|
|
36
|
+
}
|
|
37
|
+
function slugify(text) {
|
|
38
|
+
return text.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "nota";
|
|
39
|
+
}
|
|
40
|
+
function listMarkdownFiles(root) {
|
|
41
|
+
const out = [];
|
|
42
|
+
const walk = (dir) => {
|
|
43
|
+
let entries;
|
|
44
|
+
try {
|
|
45
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
46
|
+
} catch {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
for (const e of entries) {
|
|
50
|
+
if (e.name.startsWith(".") || SKIP_DIRS.has(e.name)) continue;
|
|
51
|
+
const full = path.join(dir, e.name);
|
|
52
|
+
if (e.isDirectory()) walk(full);
|
|
53
|
+
else if (e.isFile() && e.name.endsWith(".md")) out.push(full);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
walk(root);
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
function parseNote(root, absPath) {
|
|
60
|
+
const raw = fs.readFileSync(absPath, "utf8");
|
|
61
|
+
const { data, content } = matter(raw);
|
|
62
|
+
const rel = path.relative(root, absPath).split(path.sep).join("/");
|
|
63
|
+
const title = typeof data.title === "string" && data.title || path.basename(absPath, ".md");
|
|
64
|
+
const type = NOTE_TYPES.includes(data.type) ? data.type : "note";
|
|
65
|
+
const status = ["active", "completed", "failed"].includes(data.status) ? data.status : void 0;
|
|
66
|
+
const tags = Array.isArray(data.tags) ? data.tags.map(String) : [];
|
|
67
|
+
return {
|
|
68
|
+
rel,
|
|
69
|
+
title,
|
|
70
|
+
type,
|
|
71
|
+
status,
|
|
72
|
+
tags,
|
|
73
|
+
created: data.created ? String(data.created) : void 0,
|
|
74
|
+
hits: typeof data.hits === "number" ? data.hits : 1,
|
|
75
|
+
content,
|
|
76
|
+
links: extractWikilinks(content)
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function frontmatter(n) {
|
|
80
|
+
const lines = [
|
|
81
|
+
"---",
|
|
82
|
+
`title: ${JSON.stringify(n.title)}`,
|
|
83
|
+
// aliases: Obsidian resuelve [[wikilinks]] contra alias, no contra el title
|
|
84
|
+
// del frontmatter — sin esto su graph view muestra los enlaces como rotos
|
|
85
|
+
`aliases: [${JSON.stringify(n.title)}]`,
|
|
86
|
+
`type: ${n.type}`,
|
|
87
|
+
...n.status ? [`status: ${n.status}`] : [],
|
|
88
|
+
`tags: [${n.tags.map((t) => JSON.stringify(t)).join(", ")}]`,
|
|
89
|
+
`created: ${(/* @__PURE__ */ new Date()).toISOString()}`,
|
|
90
|
+
`hits: ${n.hits ?? 1}`,
|
|
91
|
+
"---",
|
|
92
|
+
""
|
|
93
|
+
];
|
|
94
|
+
return lines.join("\n");
|
|
95
|
+
}
|
|
96
|
+
function ensureAlias(absPath) {
|
|
97
|
+
try {
|
|
98
|
+
const raw = fs.readFileSync(absPath, "utf8");
|
|
99
|
+
const { data, content } = matter(raw);
|
|
100
|
+
if (!data.title || data.aliases) return false;
|
|
101
|
+
data.aliases = [String(data.title)];
|
|
102
|
+
fs.writeFileSync(absPath, matter.stringify(content, data));
|
|
103
|
+
return true;
|
|
104
|
+
} catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function createNote(managed, n) {
|
|
109
|
+
const dir = path.join(managed, n.dir ?? "notes");
|
|
110
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
111
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
112
|
+
const base = `${date}-${slugify(n.title)}`;
|
|
113
|
+
let file = path.join(dir, `${base}.md`);
|
|
114
|
+
let i = 2;
|
|
115
|
+
while (fs.existsSync(file)) file = path.join(dir, `${base}-${i++}.md`);
|
|
116
|
+
fs.writeFileSync(
|
|
117
|
+
file,
|
|
118
|
+
frontmatter({ title: n.title, type: n.type ?? "note", tags: n.tags ?? [], status: n.status }) + n.content.trim() + "\n"
|
|
119
|
+
);
|
|
120
|
+
return file;
|
|
121
|
+
}
|
|
122
|
+
function setNoteStatus(absPath, status) {
|
|
123
|
+
const raw = fs.readFileSync(absPath, "utf8");
|
|
124
|
+
const { data, content } = matter(raw);
|
|
125
|
+
data.status = status;
|
|
126
|
+
data.updated = (/* @__PURE__ */ new Date()).toISOString();
|
|
127
|
+
fs.writeFileSync(absPath, matter.stringify(content, data));
|
|
128
|
+
}
|
|
129
|
+
function touchNote(absPath) {
|
|
130
|
+
const raw = fs.readFileSync(absPath, "utf8");
|
|
131
|
+
const { data, content } = matter(raw);
|
|
132
|
+
data.hits = (typeof data.hits === "number" ? data.hits : 1) + 1;
|
|
133
|
+
data.updated = (/* @__PURE__ */ new Date()).toISOString();
|
|
134
|
+
fs.writeFileSync(absPath, matter.stringify(content, data));
|
|
135
|
+
}
|
|
136
|
+
function upsertNote(managed, n) {
|
|
137
|
+
const dir = path.join(managed, n.dir ?? "notes");
|
|
138
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
139
|
+
const file = path.join(dir, `${n.fixedName}.md`);
|
|
140
|
+
if (fs.existsSync(file)) {
|
|
141
|
+
const raw = fs.readFileSync(file, "utf8");
|
|
142
|
+
const { data } = matter(raw);
|
|
143
|
+
data.updated = (/* @__PURE__ */ new Date()).toISOString();
|
|
144
|
+
fs.writeFileSync(file, matter.stringify(n.content.trim() + "\n", data));
|
|
145
|
+
} else {
|
|
146
|
+
fs.writeFileSync(
|
|
147
|
+
file,
|
|
148
|
+
frontmatter({ title: n.title, type: n.type ?? "note", tags: n.tags ?? [], status: n.status }) + n.content.trim() + "\n"
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
return file;
|
|
152
|
+
}
|
|
153
|
+
function appendToNote(managed, n) {
|
|
154
|
+
const dir = path.join(managed, n.dir ?? "sessions");
|
|
155
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
156
|
+
const file = path.join(dir, `${n.fixedName}.md`);
|
|
157
|
+
if (fs.existsSync(file)) {
|
|
158
|
+
fs.appendFileSync(file, "\n" + n.content.trim() + "\n");
|
|
159
|
+
} else {
|
|
160
|
+
fs.writeFileSync(
|
|
161
|
+
file,
|
|
162
|
+
frontmatter({ title: n.title, type: n.type ?? "session", tags: n.tags ?? [], status: n.status }) + n.content.trim() + "\n"
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
return file;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// src/core/index.ts
|
|
169
|
+
import fs2 from "fs";
|
|
170
|
+
import path2 from "path";
|
|
171
|
+
function isHookProcess() {
|
|
172
|
+
return process.env.ALEXANDRIA_HOOK === "1";
|
|
173
|
+
}
|
|
174
|
+
var SEMANTIC_THRESHOLD = 0.9;
|
|
175
|
+
var SEMANTIC_TOP = 3;
|
|
176
|
+
var VaultIndex = class _VaultIndex {
|
|
177
|
+
constructor(vault) {
|
|
178
|
+
this.vault = vault;
|
|
179
|
+
this.meta = {
|
|
180
|
+
version: 1,
|
|
181
|
+
model: MODEL_ID,
|
|
182
|
+
dim: DIM,
|
|
183
|
+
mtimes: {},
|
|
184
|
+
notes: {},
|
|
185
|
+
chunks: [],
|
|
186
|
+
links: []
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
vault;
|
|
190
|
+
meta;
|
|
191
|
+
/** filas de embeddings alineadas 1:1 con meta.chunks; null = índice sin vectores */
|
|
192
|
+
emb = null;
|
|
193
|
+
/** diccionario lazy tag/type → rels; la bóveda nunca borra, así que los
|
|
194
|
+
* escaneos lineales sobre TODAS las notas crecen para siempre — esto los evita */
|
|
195
|
+
_tagIndex = null;
|
|
196
|
+
/**
|
|
197
|
+
* ¿Puede este contexto reconstruir el índice entero (caro)? true en CLI,
|
|
198
|
+
* false en hooks — un hook con presupuesto corto jamás debe intentarlo.
|
|
199
|
+
* Default = lo que diga el proceso (runHook marca el proceso como hook), así
|
|
200
|
+
* queda cubierto CUALQUIER camino de código, no solo los que pasan el flag.
|
|
201
|
+
*/
|
|
202
|
+
allowFullRebuild = !isHookProcess();
|
|
203
|
+
get metaPath() {
|
|
204
|
+
return path2.join(this.vault.cache, "meta.json");
|
|
205
|
+
}
|
|
206
|
+
get embPath() {
|
|
207
|
+
return path2.join(this.vault.cache, "embeddings.bin");
|
|
208
|
+
}
|
|
209
|
+
static load(vault) {
|
|
210
|
+
const idx = new _VaultIndex(vault);
|
|
211
|
+
try {
|
|
212
|
+
const meta = JSON.parse(fs2.readFileSync(idx.metaPath, "utf8"));
|
|
213
|
+
if (meta.version === 1 && meta.model === MODEL_ID) {
|
|
214
|
+
idx.meta = meta;
|
|
215
|
+
try {
|
|
216
|
+
const buf = fs2.readFileSync(idx.embPath);
|
|
217
|
+
const arr = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);
|
|
218
|
+
if (arr.length === meta.chunks.length * meta.dim) {
|
|
219
|
+
idx.emb = arr.slice();
|
|
220
|
+
} else {
|
|
221
|
+
idx.emb = null;
|
|
222
|
+
try {
|
|
223
|
+
fs2.rmSync(idx.embPath, { force: true });
|
|
224
|
+
} catch {
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
} catch {
|
|
228
|
+
idx.emb = null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
} catch (e) {
|
|
232
|
+
if (fs2.existsSync(idx.metaPath)) {
|
|
233
|
+
try {
|
|
234
|
+
fs2.rmSync(idx.metaPath, { force: true });
|
|
235
|
+
fs2.rmSync(idx.embPath, { force: true });
|
|
236
|
+
} catch {
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return idx;
|
|
241
|
+
}
|
|
242
|
+
get rebuildFlagPath() {
|
|
243
|
+
return path2.join(this.vault.cache, "needs-rebuild");
|
|
244
|
+
}
|
|
245
|
+
/** Deja constancia de que el índice está degradado y hace falta un reindex completo. */
|
|
246
|
+
markNeedsRebuild() {
|
|
247
|
+
try {
|
|
248
|
+
if (fs2.existsSync(this.rebuildFlagPath)) return;
|
|
249
|
+
fs2.mkdirSync(this.vault.cache, { recursive: true });
|
|
250
|
+
fs2.writeFileSync(this.rebuildFlagPath, (/* @__PURE__ */ new Date()).toISOString());
|
|
251
|
+
} catch {
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/** ¿El índice tiene chunks pero le faltan los vectores (búsqueda degradada)? */
|
|
255
|
+
isDegraded() {
|
|
256
|
+
return this.emb === null && this.meta.chunks.length > 0 && modelPresent();
|
|
257
|
+
}
|
|
258
|
+
/** ¿El índice quedó marcado como degradado (chunks sin vectores)? */
|
|
259
|
+
needsRebuild() {
|
|
260
|
+
return fs2.existsSync(this.rebuildFlagPath);
|
|
261
|
+
}
|
|
262
|
+
clearNeedsRebuild() {
|
|
263
|
+
try {
|
|
264
|
+
fs2.rmSync(this.rebuildFlagPath, { force: true });
|
|
265
|
+
} catch {
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/** Escritura atómica: tmp + rename — un hook y un comando concurrentes nunca dejan el archivo a medias. */
|
|
269
|
+
writeAtomic(file, data) {
|
|
270
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
271
|
+
fs2.writeFileSync(tmp, data);
|
|
272
|
+
fs2.renameSync(tmp, file);
|
|
273
|
+
}
|
|
274
|
+
save() {
|
|
275
|
+
fs2.mkdirSync(this.vault.cache, { recursive: true });
|
|
276
|
+
this.writeAtomic(this.metaPath, JSON.stringify(this.meta));
|
|
277
|
+
if (this.emb) {
|
|
278
|
+
this.writeAtomic(this.embPath, Buffer.from(this.emb.buffer, this.emb.byteOffset, this.emb.byteLength));
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
row(i) {
|
|
282
|
+
return this.emb.subarray(i * this.meta.dim, (i + 1) * this.meta.dim);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Reindexado incremental por mtime. Solo procesa archivos nuevos/cambiados.
|
|
286
|
+
* `withEmbeddings=false` → índice keyword-only (sin cargar modelo).
|
|
287
|
+
*/
|
|
288
|
+
async refresh(withEmbeddings = modelPresent(), force = false) {
|
|
289
|
+
const files = listMarkdownFiles(this.vault.root);
|
|
290
|
+
const onDisk = /* @__PURE__ */ new Map();
|
|
291
|
+
for (const abs of files) {
|
|
292
|
+
const rel = path2.relative(this.vault.root, abs).split(path2.sep).join("/");
|
|
293
|
+
onDisk.set(rel, { abs, mtime: fs2.statSync(abs).mtimeMs });
|
|
294
|
+
}
|
|
295
|
+
if (withEmbeddings && this.emb === null && this.meta.chunks.length > 0) {
|
|
296
|
+
if (this.allowFullRebuild) {
|
|
297
|
+
force = true;
|
|
298
|
+
} else {
|
|
299
|
+
this.markNeedsRebuild();
|
|
300
|
+
withEmbeddings = false;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
const changed = [];
|
|
304
|
+
for (const [rel, info] of onDisk) {
|
|
305
|
+
if (force || this.meta.mtimes[rel] !== info.mtime) changed.push(rel);
|
|
306
|
+
}
|
|
307
|
+
const removed = Object.keys(this.meta.mtimes).filter((rel) => !onDisk.has(rel));
|
|
308
|
+
if (changed.length === 0 && removed.length === 0) {
|
|
309
|
+
return { changed: 0, removed: 0, embedded: this.emb !== null };
|
|
310
|
+
}
|
|
311
|
+
this._tagIndex = null;
|
|
312
|
+
const keep = new Set(
|
|
313
|
+
this.meta.chunks.map((_, i) => i).filter((i) => {
|
|
314
|
+
const rel = this.meta.chunks[i].note;
|
|
315
|
+
return onDisk.has(rel) && !changed.includes(rel);
|
|
316
|
+
})
|
|
317
|
+
);
|
|
318
|
+
const newChunks = [];
|
|
319
|
+
const keptRows = [];
|
|
320
|
+
const hadEmb = this.emb !== null;
|
|
321
|
+
for (const i of keep) {
|
|
322
|
+
newChunks.push(this.meta.chunks[i]);
|
|
323
|
+
if (hadEmb) keptRows.push(this.row(i).slice());
|
|
324
|
+
}
|
|
325
|
+
const freshChunks = [];
|
|
326
|
+
for (const rel of changed) {
|
|
327
|
+
const info = onDisk.get(rel);
|
|
328
|
+
try {
|
|
329
|
+
const managedRel = path2.relative(this.vault.root, this.vault.managed).split(path2.sep).join("/");
|
|
330
|
+
const inManaged = managedRel === "" || rel.startsWith(`${managedRel}/`);
|
|
331
|
+
if (inManaged && ensureAlias(info.abs)) {
|
|
332
|
+
info.mtime = fs2.statSync(info.abs).mtimeMs;
|
|
333
|
+
}
|
|
334
|
+
const note = parseNote(this.vault.root, info.abs);
|
|
335
|
+
this.meta.notes[rel] = {
|
|
336
|
+
rel,
|
|
337
|
+
title: note.title,
|
|
338
|
+
type: note.type,
|
|
339
|
+
status: note.status,
|
|
340
|
+
tags: note.tags,
|
|
341
|
+
created: note.created,
|
|
342
|
+
hits: note.hits,
|
|
343
|
+
links: note.links
|
|
344
|
+
};
|
|
345
|
+
const pieces = chunkMarkdown(note.content);
|
|
346
|
+
const titlePrefix = note.title ? `${note.title}. ` : "";
|
|
347
|
+
for (const p of pieces) {
|
|
348
|
+
freshChunks.push({ note: rel, heading: p.heading, text: p.text });
|
|
349
|
+
}
|
|
350
|
+
if (pieces.length === 0 && note.title) {
|
|
351
|
+
freshChunks.push({ note: rel, text: titlePrefix });
|
|
352
|
+
}
|
|
353
|
+
} catch {
|
|
354
|
+
}
|
|
355
|
+
this.meta.mtimes[rel] = info.mtime;
|
|
356
|
+
}
|
|
357
|
+
for (const rel of removed) {
|
|
358
|
+
delete this.meta.mtimes[rel];
|
|
359
|
+
delete this.meta.notes[rel];
|
|
360
|
+
}
|
|
361
|
+
for (const rel of Object.keys(this.meta.notes)) {
|
|
362
|
+
if (!onDisk.has(rel)) delete this.meta.notes[rel];
|
|
363
|
+
}
|
|
364
|
+
let embedded = hadEmb || newChunks.length === 0;
|
|
365
|
+
let freshRows = [];
|
|
366
|
+
if (withEmbeddings && freshChunks.length > 0) {
|
|
367
|
+
try {
|
|
368
|
+
freshRows = await embed(
|
|
369
|
+
freshChunks.map((c) => `${this.meta.notes[c.note]?.title ?? ""}
|
|
370
|
+
${c.heading ?? ""}
|
|
371
|
+
${c.text}`),
|
|
372
|
+
"passage"
|
|
373
|
+
);
|
|
374
|
+
embedded = true;
|
|
375
|
+
} catch {
|
|
376
|
+
embedded = false;
|
|
377
|
+
}
|
|
378
|
+
} else if (freshChunks.length > 0) {
|
|
379
|
+
embedded = false;
|
|
380
|
+
}
|
|
381
|
+
this.meta.chunks = [...newChunks, ...freshChunks];
|
|
382
|
+
if (embedded && (hadEmb || newChunks.length === 0) && freshRows.length === freshChunks.length) {
|
|
383
|
+
const all = new Float32Array(this.meta.chunks.length * this.meta.dim);
|
|
384
|
+
[...keptRows, ...freshRows].forEach((r, i) => all.set(r, i * this.meta.dim));
|
|
385
|
+
this.emb = all;
|
|
386
|
+
} else if (freshChunks.length > 0 && !embedded) {
|
|
387
|
+
this.emb = null;
|
|
388
|
+
}
|
|
389
|
+
this.rebuildLinks();
|
|
390
|
+
this.save();
|
|
391
|
+
if (this.emb !== null) this.clearNeedsRebuild();
|
|
392
|
+
else if (this.meta.chunks.length > 0 && modelPresent()) this.markNeedsRebuild();
|
|
393
|
+
try {
|
|
394
|
+
const { writeStaticGraph } = await import("./viewer-JQCSWJ3C.js");
|
|
395
|
+
writeStaticGraph(this);
|
|
396
|
+
} catch {
|
|
397
|
+
}
|
|
398
|
+
return { changed: changed.length, removed: removed.length, embedded: this.emb !== null };
|
|
399
|
+
}
|
|
400
|
+
/** Wikilinks (título → nota) + links semánticos (similitud entre notas). */
|
|
401
|
+
rebuildLinks() {
|
|
402
|
+
const byTitle = /* @__PURE__ */ new Map();
|
|
403
|
+
for (const n of Object.values(this.meta.notes)) {
|
|
404
|
+
byTitle.set(n.title.toLowerCase(), n.rel);
|
|
405
|
+
byTitle.set(n.rel.replace(/\.md$/, "").split("/").pop().toLowerCase(), n.rel);
|
|
406
|
+
}
|
|
407
|
+
const links = [];
|
|
408
|
+
for (const n of Object.values(this.meta.notes)) {
|
|
409
|
+
for (const target of n.links) {
|
|
410
|
+
const to = byTitle.get(target.toLowerCase());
|
|
411
|
+
if (to && to !== n.rel) links.push({ from: n.rel, to, type: "wikilink" });
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (this.emb) {
|
|
415
|
+
const rels = Object.keys(this.meta.notes);
|
|
416
|
+
const noteVec = /* @__PURE__ */ new Map();
|
|
417
|
+
for (const rel of rels) {
|
|
418
|
+
const idxs = this.meta.chunks.map((c, i) => c.note === rel ? i : -1).filter((i) => i >= 0);
|
|
419
|
+
if (idxs.length === 0) continue;
|
|
420
|
+
const v = new Float32Array(this.meta.dim);
|
|
421
|
+
for (const i of idxs) {
|
|
422
|
+
const r = this.row(i);
|
|
423
|
+
for (let d = 0; d < this.meta.dim; d++) v[d] += r[d];
|
|
424
|
+
}
|
|
425
|
+
let norm = 0;
|
|
426
|
+
for (let d = 0; d < this.meta.dim; d++) norm += v[d] * v[d];
|
|
427
|
+
norm = Math.sqrt(norm) || 1;
|
|
428
|
+
for (let d = 0; d < this.meta.dim; d++) v[d] /= norm;
|
|
429
|
+
noteVec.set(rel, v);
|
|
430
|
+
}
|
|
431
|
+
const seen = new Set(links.map((l) => `${l.from}\u2192${l.to}`));
|
|
432
|
+
const vecRels = [...noteVec.keys()];
|
|
433
|
+
for (const a of vecRels) {
|
|
434
|
+
const sims = [];
|
|
435
|
+
for (const b of vecRels) {
|
|
436
|
+
if (a === b) continue;
|
|
437
|
+
sims.push({ rel: b, s: dot(noteVec.get(a), noteVec.get(b)) });
|
|
438
|
+
}
|
|
439
|
+
sims.sort((x, y) => y.s - x.s);
|
|
440
|
+
for (const { rel: b, s } of sims.slice(0, SEMANTIC_TOP)) {
|
|
441
|
+
if (s < SEMANTIC_THRESHOLD) break;
|
|
442
|
+
const key = a < b ? `${a}\u2192${b}` : `${b}\u2192${a}`;
|
|
443
|
+
if (seen.has(key) || seen.has(`${a}\u2192${b}`) || seen.has(`${b}\u2192${a}`)) continue;
|
|
444
|
+
seen.add(key);
|
|
445
|
+
links.push({ from: a, to: b, type: "semantic", w: Math.round(s * 100) / 100 });
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
this.meta.links = links;
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Notas por tag o por tipo (`notesByTag('plan')`, `notesByTag('oauth')`) —
|
|
453
|
+
* lookup O(1) contra el diccionario en vez de filtrar todas las notas.
|
|
454
|
+
*/
|
|
455
|
+
notesByTag(key) {
|
|
456
|
+
if (!this._tagIndex) {
|
|
457
|
+
const m = /* @__PURE__ */ new Map();
|
|
458
|
+
for (const n of Object.values(this.meta.notes)) {
|
|
459
|
+
for (const k of [n.type, ...n.tags]) {
|
|
460
|
+
const arr = m.get(k);
|
|
461
|
+
if (arr) arr.push(n.rel);
|
|
462
|
+
else m.set(k, [n.rel]);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
this._tagIndex = m;
|
|
466
|
+
}
|
|
467
|
+
return (this._tagIndex.get(key) ?? []).map((rel) => this.meta.notes[rel]).filter(Boolean);
|
|
468
|
+
}
|
|
469
|
+
/** Vecinos directos de una nota en el grafo (sin releer archivos). */
|
|
470
|
+
neighbors(rel) {
|
|
471
|
+
const out = [];
|
|
472
|
+
for (const l of this.meta.links) {
|
|
473
|
+
const other = l.from === rel ? l.to : l.to === rel ? l.from : null;
|
|
474
|
+
if (other && this.meta.notes[other]) {
|
|
475
|
+
out.push({ note: this.meta.notes[other], type: l.type, w: l.w });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
return out;
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
export {
|
|
483
|
+
slugify,
|
|
484
|
+
createNote,
|
|
485
|
+
setNoteStatus,
|
|
486
|
+
touchNote,
|
|
487
|
+
upsertNote,
|
|
488
|
+
appendToNote,
|
|
489
|
+
VaultIndex
|
|
490
|
+
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
VaultIndex
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-QB37UGO6.js";
|
|
5
5
|
import {
|
|
6
6
|
dot,
|
|
7
7
|
embed,
|
|
@@ -61,6 +61,7 @@ async function hybridSearch(vault, query, k = 6, opts = {}) {
|
|
|
61
61
|
await idx.refresh().catch(() => {
|
|
62
62
|
});
|
|
63
63
|
}
|
|
64
|
+
if (idx.isDegraded()) idx.markNeedsRebuild();
|
|
64
65
|
if (idx.meta.chunks.length === 0) return [];
|
|
65
66
|
const rrf = /* @__PURE__ */ new Map();
|
|
66
67
|
const cosineByChunk = /* @__PURE__ */ new Map();
|