@ureck/alexandria 1.3.3 → 1.5.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 CHANGED
@@ -6,11 +6,11 @@
6
6
  [![license](https://img.shields.io/badge/license-MIT-green)](./LICENSE)
7
7
  [![Buy Me a Coffee](https://img.shields.io/badge/☕_Buy_me_a_coffee-ureck-yellow)](https://buymeacoffee.com/ureck)
8
8
 
9
- [![docs](https://img.shields.io/badge/docs-ES%20%C2%B7%20EN-b8860b)](https://ureckchan.github.io/alexandria/) **[Documentation / Documentación](https://ureckchan.github.io/alexandria/)**
9
+ [![docs](https://img.shields.io/badge/docs-ES%20%C2%B7%20EN-b8860b)](https://alexandria.ureck.dev/) **[Documentation / Documentación](https://alexandria.ureck.dev/)**
10
10
 
11
11
  Alexandria automatically captures your AI prompts and sessions, searches that knowledge **before** spending tokens, and connects everything in an Obsidian-style graph. **100% local**: no database, no API keys, no telemetry, no cost.
12
12
 
13
- Works with the most popular agents via MCP: **Claude Code · Cursor · OpenCode · Devin CLI · Cline · Codex CLI · Gemini CLI · VS Code (Copilot) · OpenClaw · Hermes Agent · Windsurf (legacy)**.
13
+ Works with the most popular agents via MCP: **Claude Code · Codex CLI · Gemini CLI · Cursor · OpenCode · Devin CLI · Cline · VS Code (Copilot) · OpenClaw · Hermes Agent · Windsurf (legacy)** — and since 1.4, **automatic capture + context injection via hooks in Claude Code, Codex, Gemini CLI, Cursor and OpenCode**.
14
14
 
15
15
  ## Why?
16
16
 
@@ -63,7 +63,7 @@ Verify:
63
63
 
64
64
  ```bash
65
65
  $ ale --version
66
- 1.3.1
66
+ 1.5.0
67
67
  ```
68
68
 
69
69
  ## Getting started
@@ -130,7 +130,31 @@ cat DECISIONS.md | ale add "Q3 architecture decisions"
130
130
  ale add "Vercel deploy" -c "Region cdg1, see [[Prisma setup]]" -t deploy
131
131
  ```
132
132
 
133
- (Automatic capture via hooks already does this in every Claude Code session — `add` is for extra knowledge.)
133
+ (Automatic capture via hooks already does this in every Claude Code, Codex, Gemini CLI, Cursor and OpenCode session — `add` is for extra knowledge.)
134
+
135
+ ### Read documents without paying for the whole thing (PDF, DOCX, XLSX, CSV, HTML)
136
+
137
+ Reading a PDF directly costs an agent ~1,500–3,000 tokens **per page** (Claude sends each page as image + text). Alexandria converts documents locally to markdown sections and the agent asks only for what it needs:
138
+
139
+ ```bash
140
+ ale ingest "Manual Tecnico.pdf" reports/ # file or folder (pdf, docx, xlsx, csv, tsv, html, md, txt)
141
+ ale docs # list ingested documents
142
+ ale docs read "Manual Tecnico" -q "which env vars does the deploy need?"
143
+ ale docs read pagos.xlsx -q "F-137 pagado" # spreadsheets: returns the MATCHING ROWS
144
+ ```
145
+
146
+ From any agent, the MCP tools `doc_ingest` (returns a ~200-token section outline) and `doc_read` (sections by id or by question, never over `max_tokens`, always telling what was left out) do the same. Measured on real documents:
147
+
148
+ | Document | Read directly | Outline | Answer to one question |
149
+ |---|---|---|---|
150
+ | 10-page technical manual (PDF) | ~20,000 tokens | ~248 | ~179 |
151
+ | 2,016-row spreadsheet (XLSX) | ~1,241,000 tokens | ~526 | ~579 (matching rows) |
152
+
153
+ - **PDF**: headings detected by font size (multi-line titles merged), source page kept for citations; scanned PDFs (no text layer) are flagged — Alexandria doesn't do OCR.
154
+ - **Spreadsheets**: never sent whole — a per-column summary (type, distinct values, samples) plus 50-row blocks; huge cells (geometries, JSON) are trimmed.
155
+ - **Claude Code**: the first direct `Read` of a large PDF/DOCX/XLSX/CSV in a session is redirected to `doc_ingest`/`doc_read`; a second attempt goes through (for when the agent really needs to see images). Toggle: `docs.interceptRead`.
156
+ - Unchanged files are never reconverted (sha256). Documents live in `Alexandria/docs/`, outside the vector index (a big spreadsheet would be thousands of chunks); section vectors are computed once per document version and cached.
157
+ - `ale stats` shows the **measured** document savings: tokens of the originals vs tokens actually served.
134
158
 
135
159
  ### Control what spends tokens (`ale toggles`)
136
160
 
@@ -142,7 +166,7 @@ ale init --off architect.enrich,digest.map # disable from the start
142
166
  ale config set tokens.solutionCache false # scriptable, one by one
143
167
  ```
144
168
 
145
- The 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), and background index rebuild at session close (costs no tokens). All on by default; nothing changes unless you touch them.
169
+ The 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), redirecting direct reads of large PDFs/spreadsheets to `doc_read` (`docs.interceptRead`), background index rebuild at session close, and weekly background cleanup `clean.auto` (neither costs tokens). All on by default; nothing changes unless you touch them.
146
170
 
147
171
  ### Deep project context (`ale scan`)
148
172
 
@@ -232,9 +256,11 @@ Flags plans without a Definition of Done, failures without lessons, and orphan n
232
256
  ```bash
233
257
  ale doctor # checks & repairs: model, hooks, MCP, index
234
258
  ale reindex [--force] # incremental by default
235
- ale consolidate [--days 45] # ARCHIVES old unused prompts to Alexandria/archive/
236
- # — out of the graph and injection, still searchable: nothing is ever lost
237
- ale uninstall # removes hooks; your notes stay untouched
259
+ ale clean # PREVIEW of a safe cleanup (touches nothing)
260
+ ale clean --yes [--backup f] # apply: old unused prompts → compacted monthly files (full text),
261
+ # harness noise dropped, stale caches purged. Lessons, plans, maps,
262
+ # sessions are NEVER touched. Still searchable: ale search --archive "…"
263
+ ale uninstall # removes hooks + MCP from every agent; your notes stay untouched
238
264
  ```
239
265
 
240
266
  Every command self-repairs before running: missing model → downloads it; stale index → updates it.
@@ -247,35 +273,50 @@ ale agents all # register the MCP server in all of them
247
273
  ale agents cursor,gemini # just these
248
274
  ```
249
275
 
250
- | Agent | Config written | Per-project |
251
- |---|---|---|
252
- | Claude Code | `.mcp.json` / `claude mcp add` + hooks | ✓ |
253
- | Cursor | `~/.cursor/mcp.json` / `.cursor/mcp.json` | ✓ |
254
- | OpenCode | `opencode.json` | ✓ |
255
- | Devin CLI (Cognition) | `.devin/mcp_config.local.json` | ✓ |
256
- | Windsurf (legacy) | `~/.codeium/windsurf/mcp_config.json` | — |
257
- | Cline | `cline_mcp_settings.json` (VS Code) | — |
258
- | Codex CLI | `~/.codex/config.toml` | — |
259
- | Gemini CLI | `~/.gemini/settings.json` / `.gemini/settings.json` | ✓ |
260
- | VS Code (Copilot) | `mcp.json` (profile) / `.vscode/mcp.json` | ✓ |
261
- | OpenClaw | `~/.openclaw/openclaw.json` | — |
262
- | Hermes Agent (Nous) | `hermes mcp add` / `~/.hermes/config.yaml` | — |
263
-
264
- Registrations are **idempotent merges** — your other MCP servers are never touched.
265
-
266
- **Note**: automatic capture via hooks (session digest, per-prompt injection, session save on close) is Claude Code-only — other agents don't have a hook system. There, knowledge flows through the MCP tools, which the agent uses on its own (the protocol instructions travel inside the tool descriptions).
276
+ | Agent | MCP config written | Hooks (auto capture + injection) | Per-project |
277
+ |---|---|---|---|
278
+ | Claude Code | `.mcp.json` / `claude mcp add` | `.claude/settings.json` — SessionStart · UserPromptSubmit · Stop · PreCompact | ✓ |
279
+ | Codex CLI | `~/.codex/config.toml` / `.codex/config.toml` | `.codex/hooks.json` — SessionStart · UserPromptSubmit · Stop · PreCompact ¹ | ✓ |
280
+ | Gemini CLI | `~/.gemini/settings.json` / `.gemini/settings.json` | same file — SessionStart · BeforeAgent · AfterAgent · PreCompress | ✓ |
281
+ | Cursor | `~/.cursor/mcp.json` / `.cursor/mcp.json` | `.cursor/hooks.json` — sessionStart · beforeSubmitPrompt ² · afterAgentResponse | ✓ |
282
+ | OpenCode | `opencode.json` | plugin `.opencode/plugins/alexandria.js` — injects into the system prompt | ✓ |
283
+ | Devin CLI (Cognition) | `.devin/mcp_config.local.json` | — | ✓ |
284
+ | Cline | `cline_mcp_settings.json` (VS Code) | — | — |
285
+ | VS Code (Copilot) | `mcp.json` (profile) / `.vscode/mcp.json` | — | ✓ |
286
+ | OpenClaw | `~/.openclaw/openclaw.json` | — | — |
287
+ | Hermes Agent (Nous) | `hermes mcp add` / `~/.hermes/config.yaml` | — | — |
288
+ | Windsurf (legacy → Devin) | `~/.codeium/windsurf/mcp_config.json` | — | — |
289
+
290
+ ¹ Codex skips untrusted hooks: open Codex once and approve them with `/hooks`.
291
+ ² Cursor's `beforeSubmitPrompt` can't inject context — there Alexandria captures the prompt; context arrives via `sessionStart` and the MCP tools.
292
+
293
+ `ale agents <ids>` registers MCP **and** hooks (`--no-hooks` for MCP only). Registrations are **idempotent merges** — your other MCP servers and hooks are never touched, and a config file that doesn't parse is never overwritten. `ale init` also writes the usage block to `AGENTS.md` (read by Codex, OpenCode, Cursor, Devin…) besides `CLAUDE.md`.
294
+
295
+ Agents without hooks still get everything through the MCP tools, which the agent uses on its own (the protocol instructions travel inside the tool descriptions).
296
+
297
+ ### As a plugin
298
+
299
+ The public repo is also a **Claude Code plugin marketplace** (and ships a Codex plugin manifest). The plugin runs the globally installed `alexandria` (falls back to `npx`):
300
+
301
+ ```bash
302
+ npm i -g @ureck/alexandria
303
+ claude plugin marketplace add UreckChan/alexandria
304
+ claude plugin install alexandria@alexandria
305
+ ```
267
306
 
268
307
  ## How it works
269
308
 
270
309
  ```
271
310
  AI agent session
272
311
  │
273
- ├─ SessionStart ──► injects digest: protocol manifest + project map + open plans (hooks, Claude Code)
274
- ├─ Every prompt ──► local hybrid search → injects only what's relevant (hooks, Claude Code)
312
+ ├─ SessionStart ──► injects digest: protocol manifest + project map + open plans (hooks)
313
+ ├─ Every prompt ──► local hybrid search → injects only what's relevant (hooks)
275
314
  │ └─ near-identical prompt already solved → injects the solution (cache)
276
315
  ├─ MCP tools ─────► vault_search · vault_save · vault_related · vault_link (all agents)
316
+ │ doc_ingest · doc_read (documents by section, token budget)
277
317
  │ plan_create · task_verify · lesson_extract (the Protocol)
278
- └─ Stop/PreCompact► saves the session outcome into the vault (hooks, Claude Code)
318
+ └─ Stop/PreCompact► saves the session outcome into the vault (hooks)
319
+ hooks: Claude Code · Codex · Gemini CLI · Cursor · OpenCode (one set of scripts, --harness=<id>)
279
320
  │
280
321
  <Obsidian vault>/Alexandria/*.md ← markdown, [[wikilinks]]
281
322
  <vault>/.vault/ ← index (regenerable)
@@ -294,8 +335,8 @@ AI agent session
294
335
  | `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 |
295
336
  | `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>` |
296
337
  | `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 |
297
- | `ale agents [ids] [--project]` | List agents / register the MCP server |
298
- | `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 |
338
+ | `ale agents [ids] [--project] [--no-hooks]` | List agents / register the MCP server + hooks where supported |
339
+ | `ale search <query> [-k n] [--expand] [--archive]` | Hybrid search; `--archive` searches prompts compacted by `ale clean`; `--expand` pulls graph neighbors. With the Protocol on, appends the **chain** (plan + verification + lesson) connected to the top hit |
299
340
  | `ale add <title> [-c text] [--file <path>] [-t tags]` | Save a note (inline, from file, or stdin) |
300
341
  | `ale plan <file> [--title t]` | Create a Protocol plan from a .md/.txt file (checkboxes → Definition of Done); surfaces similar past plans + quality hints |
301
342
  | `ale graph [--out file.html] [--no-open]` | Live local graph viewer |
@@ -304,9 +345,13 @@ AI agent session
304
345
  | `ale config <get\|set> <key> [value]` | Configuration (e.g. `protocol` true/false) |
305
346
  | `ale skills [-y] [--project]` | Recommends & installs Claude skills — semantic (e5) + keyword detection over your vault. Local source configurable with `ale config set skills.repo <path>`; otherwise installs from skills.sh |
306
347
  | `ale reindex [--force]` | Reindex (incremental by default) |
307
- | `ale consolidate [--days n] [--dry]` | Archive old unused prompts — never deletes |
348
+ | `ale clean [--yes] [--days n] [--backup f] [--keep-noise]` | Safe cleanup: compacts old unused prompts (full text kept, out of the vector index), drops harness noise, purges regenerable caches, rotates stats. Preview by default. Runs weekly in the background (toggle `clean.auto`) |
349
+ | `ale consolidate [--days n] [--dry]` | Alias of `ale clean --prompts-only` |
308
350
  | `ale doctor [--project]` | Check & repair: model, hooks, MCP, index |
309
- | `ale uninstall [--project]` | Remove hooks (notes stay untouched) |
351
+ | `ale uninstall [--project]` | Remove hooks, MCP and instruction blocks from every agent (notes stay untouched) |
352
+ | `ale ingest <paths...> [--force]` | Convert PDF/DOCX/XLSX/CSV/HTML/MD to markdown sections and store them in the vault |
353
+ | `ale docs` / `ale docs read <doc> [-s ids] [-q question] [--max-tokens n]` | List ingested documents / read only the sections (or spreadsheet rows) you need |
354
+ | `ale hook <session-start\|prompt\|stop\|read> [--harness id]` | Run a hook (used by the plugins) |
310
355
  | `ale --vault <path> <cmd>` | Run any command against another vault |
311
356
 
312
357
  `alexandria` works as an alias of `ale`.
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ charsToTokens
4
+ } from "./chunk-POA77JSS.js";
5
+ import {
6
+ isHarnessInjected
7
+ } from "./chunk-CEHNXDUE.js";
8
+ import {
9
+ isoDate
10
+ } from "./chunk-BV2KJV5W.js";
11
+ import {
12
+ MODEL_ID,
13
+ modelCacheDir
14
+ } from "./chunk-EDYBSJSS.js";
15
+
16
+ // src/core/clean.ts
17
+ import fs from "fs";
18
+ import path from "path";
19
+ import matter from "gray-matter";
20
+ var ARCHIVE_DIR = "archive";
21
+ var STATS_KEEP_DAYS = 90;
22
+ function archiveRoot(vault) {
23
+ return path.join(vault.managed, ARCHIVE_DIR);
24
+ }
25
+ function bodyOf(abs) {
26
+ try {
27
+ return matter(fs.readFileSync(abs, "utf8")).content.trim();
28
+ } catch {
29
+ return "";
30
+ }
31
+ }
32
+ function promptText(body) {
33
+ return body.replace(/^Proyecto: \[\[[^\]]*\]\]\s*/m, "").replace(/^## Prompt\s*/m, "").trim();
34
+ }
35
+ function sizeOf(p) {
36
+ try {
37
+ const st = fs.statSync(p);
38
+ if (!st.isDirectory()) return st.size;
39
+ return fs.readdirSync(p).reduce((s, f) => s + sizeOf(path.join(p, f)), 0);
40
+ } catch {
41
+ return 0;
42
+ }
43
+ }
44
+ function planClean(vault, notes, opts) {
45
+ const cutoff = Date.now() - opts.days * 864e5;
46
+ const archRel = path.relative(vault.root, archiveRoot(vault)).split(path.sep).join("/");
47
+ const bundles = /* @__PURE__ */ new Map();
48
+ const noise = [];
49
+ const legacy = [];
50
+ try {
51
+ for (const f of fs.readdirSync(archiveRoot(vault))) {
52
+ if (!f.endsWith(".md")) continue;
53
+ const abs = path.join(archiveRoot(vault), f);
54
+ if (!fs.statSync(abs).isFile()) continue;
55
+ const fm = matter(fs.readFileSync(abs, "utf8")).data;
56
+ if (fm.type !== "prompt") continue;
57
+ legacy.push({
58
+ rel: path.relative(vault.root, abs).split(path.sep).join("/"),
59
+ title: fm.title ?? f,
60
+ type: "prompt",
61
+ tags: Array.isArray(fm.tags) ? fm.tags : [],
62
+ created: isoDate(fm.created),
63
+ hits: fm.hits ?? 1,
64
+ links: []
65
+ });
66
+ }
67
+ } catch {
68
+ }
69
+ for (const n of [...notes, ...legacy]) {
70
+ if (n.type !== "prompt") continue;
71
+ const abs = path.join(vault.root, n.rel);
72
+ if (!opts.keepNoise && isHarnessInjected(promptText(bodyOf(abs)))) {
73
+ noise.push(n);
74
+ continue;
75
+ }
76
+ const legacy2 = n.rel.startsWith(`${archRel}/`);
77
+ const old = n.created !== void 0 && Date.parse(n.created) < cutoff;
78
+ if (!legacy2 && !(old && (n.hits ?? 1) <= 1)) continue;
79
+ const proj = (n.tags.find((t) => t !== "prompt") ?? "general").replace(/[\\/:*?"<>|]/g, "-");
80
+ const key = `${proj}/${(n.created ?? "").slice(0, 7) || "sin-fecha"}`;
81
+ const list = bundles.get(key) ?? [];
82
+ list.push(n);
83
+ bundles.set(key, list);
84
+ }
85
+ let tmpFiles = [];
86
+ try {
87
+ tmpFiles = fs.readdirSync(vault.cache).filter((f) => f.endsWith(".tmp")).map((f) => path.join(vault.cache, f));
88
+ } catch {
89
+ }
90
+ const staleModels = [];
91
+ const [org, name] = MODEL_ID.split("/");
92
+ try {
93
+ for (const o of fs.readdirSync(modelCacheDir())) {
94
+ const orgDir = path.join(modelCacheDir(), o);
95
+ if (!fs.statSync(orgDir).isDirectory()) continue;
96
+ for (const m of fs.readdirSync(orgDir)) {
97
+ const dir = path.join(orgDir, m);
98
+ if (!(o === org && m === name) && fs.existsSync(path.join(dir, "config.json"))) staleModels.push(dir);
99
+ }
100
+ }
101
+ } catch {
102
+ }
103
+ return { bundles, noise, tmpFiles, staleModels, statsLinesToRotate: oldStatsLines(vault).length };
104
+ }
105
+ function oldStatsLines(vault) {
106
+ const cutoff = Date.now() - STATS_KEEP_DAYS * 864e5;
107
+ try {
108
+ return fs.readFileSync(path.join(vault.cache, "stats.jsonl"), "utf8").split("\n").filter((l) => {
109
+ try {
110
+ const o = JSON.parse(l);
111
+ return o.t !== "summary" && o.kind !== "doc" && Date.parse(o.t ?? "") < cutoff;
112
+ } catch {
113
+ return false;
114
+ }
115
+ });
116
+ } catch {
117
+ return [];
118
+ }
119
+ }
120
+ function writeAtomic(file, text) {
121
+ const tmp = `${file}.${process.pid}.tmp`;
122
+ fs.writeFileSync(tmp, text);
123
+ fs.renameSync(tmp, file);
124
+ }
125
+ function section(n, text) {
126
+ return `## ${(n.created ?? "").slice(0, 10)} \u2014 ${n.title.replace(/\n/g, " ")}
127
+
128
+ ${text}
129
+ `;
130
+ }
131
+ function applyClean(vault, plan) {
132
+ const res = { compacted: 0, dropped: 0, bundlesWritten: 0, removedDerived: 0, bytesFreed: 0 };
133
+ for (const [key, list] of plan.bundles) {
134
+ const [proj, month] = key.split("/");
135
+ const file = path.join(archiveRoot(vault), proj, `${month}.md`);
136
+ fs.mkdirSync(path.dirname(file), { recursive: true });
137
+ const items = list.sort((a, b) => (a.created ?? "").localeCompare(b.created ?? "")).map((n) => ({ n, abs: path.join(vault.root, n.rel), text: promptText(bodyOf(path.join(vault.root, n.rel))) })).filter((x) => x.text);
138
+ if (items.length === 0) continue;
139
+ let current = "";
140
+ try {
141
+ current = fs.readFileSync(file, "utf8");
142
+ } catch {
143
+ current = matter.stringify(
144
+ `Prompts archivados por \`ale clean\`: texto \xEDntegro, fuera del \xEDndice sem\xE1ntico y del grafo.
145
+ B\xFAscalos con \`ale search --archive "<texto>"\`.
146
+
147
+ Proyecto: [[Mapa - ${proj}]]
148
+ `,
149
+ { title: `Archivo de prompts \u2014 ${proj} ${month}`, type: "archive", tags: [proj, "archivo"], created: (/* @__PURE__ */ new Date()).toISOString() }
150
+ ).trimEnd() + "\n";
151
+ }
152
+ const next = current.trimEnd() + "\n\n" + items.map((x) => section(x.n, x.text)).join("\n");
153
+ writeAtomic(file, next);
154
+ res.bundlesWritten++;
155
+ const written = fs.readFileSync(file, "utf8");
156
+ for (const x of items) {
157
+ if (!written.includes(x.text)) continue;
158
+ res.bytesFreed += sizeOf(x.abs);
159
+ fs.rmSync(x.abs, { force: true });
160
+ res.compacted++;
161
+ }
162
+ }
163
+ for (const n of plan.noise) {
164
+ const abs = path.join(vault.root, n.rel);
165
+ res.bytesFreed += sizeOf(abs);
166
+ fs.rmSync(abs, { force: true });
167
+ res.dropped++;
168
+ }
169
+ for (const p of [...plan.tmpFiles, ...plan.staleModels]) {
170
+ res.bytesFreed += sizeOf(p);
171
+ fs.rmSync(p, { recursive: true, force: true });
172
+ res.removedDerived++;
173
+ }
174
+ rotateStats(vault);
175
+ return res;
176
+ }
177
+ function rotateStats(vault) {
178
+ const file = path.join(vault.cache, "stats.jsonl");
179
+ const old = new Set(oldStatsLines(vault));
180
+ if (old.size === 0) return 0;
181
+ const lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean);
182
+ const agg = /* @__PURE__ */ new Map();
183
+ const keep = [];
184
+ for (const l of lines) {
185
+ let o;
186
+ try {
187
+ o = JSON.parse(l);
188
+ } catch {
189
+ continue;
190
+ }
191
+ if (old.has(l) || o.t === "summary") {
192
+ const a = agg.get(o.kind ?? "inject") ?? { injectedChars: 0, count: 0, tokens: 0 };
193
+ a.injectedChars += o.injectedChars ?? 0;
194
+ a.count += o.count ?? 1;
195
+ a.tokens += o.tokens ?? charsToTokens(o.injectedChars ?? 0);
196
+ agg.set(o.kind ?? "inject", a);
197
+ } else keep.push(l);
198
+ }
199
+ const summary = [...agg].map(([kind, a]) => JSON.stringify({ t: "summary", kind, ...a }));
200
+ writeAtomic(file, [...summary, ...keep].join("\n") + "\n");
201
+ return old.size;
202
+ }
203
+ function searchArchive(vault, query, k = 5) {
204
+ const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length > 2);
205
+ if (terms.length === 0) return [];
206
+ const hits = [];
207
+ const walk = (dir) => {
208
+ let entries = [];
209
+ try {
210
+ entries = fs.readdirSync(dir, { withFileTypes: true });
211
+ } catch {
212
+ return;
213
+ }
214
+ for (const e of entries) {
215
+ const full = path.join(dir, e.name);
216
+ if (e.isDirectory()) walk(full);
217
+ else if (e.name.endsWith(".md")) {
218
+ const text = fs.readFileSync(full, "utf8");
219
+ for (const sec of text.split(/\n(?=## )/)) {
220
+ const low = sec.toLowerCase();
221
+ const score = terms.reduce((s, t) => s + (low.includes(t) ? 1 : 0), 0);
222
+ if (score === 0) continue;
223
+ const heading = sec.match(/^## (.+)$/m)?.[1] ?? path.basename(full);
224
+ hits.push({ file: path.relative(vault.root, full), heading, excerpt: sec.replace(/^## .+\n/, "").trim().slice(0, 400), score });
225
+ }
226
+ }
227
+ }
228
+ };
229
+ walk(archiveRoot(vault));
230
+ return hits.sort((a, b) => b.score - a.score).slice(0, k).map(({ score: _s, ...h }) => h);
231
+ }
232
+ function dirBytes(p, exclude) {
233
+ return sizeOf(p) - (exclude ? sizeOf(exclude) : 0);
234
+ }
235
+ var LAST_CLEAN = "last-clean";
236
+ function autoCleanDue(vault) {
237
+ try {
238
+ const t = fs.statSync(path.join(vault.cache, LAST_CLEAN)).mtimeMs;
239
+ return Date.now() - t > 7 * 864e5;
240
+ } catch {
241
+ return true;
242
+ }
243
+ }
244
+ function markCleaned(vault) {
245
+ try {
246
+ fs.mkdirSync(vault.cache, { recursive: true });
247
+ fs.writeFileSync(path.join(vault.cache, LAST_CLEAN), (/* @__PURE__ */ new Date()).toISOString());
248
+ } catch {
249
+ }
250
+ }
251
+
252
+ export {
253
+ ARCHIVE_DIR,
254
+ planClean,
255
+ applyClean,
256
+ searchArchive,
257
+ dirBytes,
258
+ autoCleanDue,
259
+ markCleaned
260
+ };
@@ -21,7 +21,9 @@ var NOTE_TYPES = [
21
21
  "task",
22
22
  "verification",
23
23
  "lesson",
24
- "solution"
24
+ "solution",
25
+ "archive",
26
+ "document"
25
27
  ];
26
28
  var SKIP_DIRS = /* @__PURE__ */ new Set([".obsidian", ".vault", ".trash", ".git", "node_modules"]);
27
29
  function extractWikilinks(content) {
@@ -37,9 +39,16 @@ function extractWikilinks(content) {
37
39
  function slugify(text) {
38
40
  return text.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "nota";
39
41
  }
40
- function listMarkdownFiles(root) {
42
+ function isoDate(v) {
43
+ if (v === void 0 || v === null || v === "") return void 0;
44
+ const d = v instanceof Date ? v : new Date(String(v));
45
+ return isNaN(d.getTime()) ? String(v) : d.toISOString();
46
+ }
47
+ function listMarkdownFiles(root, skip = []) {
41
48
  const out = [];
49
+ const skipSet = new Set(skip.map((d) => path.resolve(d)));
42
50
  const walk = (dir) => {
51
+ if (skipSet.has(path.resolve(dir))) return;
43
52
  let entries;
44
53
  try {
45
54
  entries = fs.readdirSync(dir, { withFileTypes: true });
@@ -70,7 +79,7 @@ function parseNote(root, absPath) {
70
79
  type,
71
80
  status,
72
81
  tags,
73
- created: data.created ? String(data.created) : void 0,
82
+ created: isoDate(data.created),
74
83
  hits: typeof data.hits === "number" ? data.hits : 1,
75
84
  content,
76
85
  links: extractWikilinks(content)
@@ -212,6 +221,7 @@ var VaultIndex = class _VaultIndex {
212
221
  const meta = JSON.parse(fs2.readFileSync(idx.metaPath, "utf8"));
213
222
  if (meta.version === 1 && meta.model === MODEL_ID) {
214
223
  idx.meta = meta;
224
+ for (const n of Object.values(meta.notes)) n.created = isoDate(n.created);
215
225
  try {
216
226
  const buf = fs2.readFileSync(idx.embPath);
217
227
  const arr = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);
@@ -286,7 +296,10 @@ var VaultIndex = class _VaultIndex {
286
296
  * `withEmbeddings=false` → índice keyword-only (sin cargar modelo).
287
297
  */
288
298
  async refresh(withEmbeddings = modelPresent(), force = false) {
289
- const files = listMarkdownFiles(this.vault.root);
299
+ const files = listMarkdownFiles(this.vault.root, [
300
+ path2.join(this.vault.managed, "archive"),
301
+ path2.join(this.vault.managed, "docs")
302
+ ]);
290
303
  const onDisk = /* @__PURE__ */ new Map();
291
304
  for (const abs of files) {
292
305
  const rel = path2.relative(this.vault.root, abs).split(path2.sep).join("/");
@@ -390,8 +403,8 @@ ${c.text}`),
390
403
  this.save();
391
404
  if (this.emb !== null) this.clearNeedsRebuild();
392
405
  else if (this.meta.chunks.length > 0 && modelPresent()) this.markNeedsRebuild();
393
- try {
394
- const { writeStaticGraph } = await import("./viewer-JQCSWJ3C.js");
406
+ if (!isHookProcess()) try {
407
+ const { writeStaticGraph } = await import("./viewer-WQQSQETT.js");
395
408
  writeStaticGraph(this);
396
409
  } catch {
397
410
  }
@@ -456,7 +469,7 @@ ${c.text}`),
456
469
  if (!this._tagIndex) {
457
470
  const m = /* @__PURE__ */ new Map();
458
471
  for (const n of Object.values(this.meta.notes)) {
459
- for (const k of [n.type, ...n.tags]) {
472
+ for (const k of /* @__PURE__ */ new Set([n.type, ...n.tags])) {
460
473
  const arr = m.get(k);
461
474
  if (arr) arr.push(n.rel);
462
475
  else m.set(k, [n.rel]);
@@ -481,6 +494,7 @@ ${c.text}`),
481
494
 
482
495
  export {
483
496
  slugify,
497
+ isoDate,
484
498
  createNote,
485
499
  setNoteStatus,
486
500
  touchNote,
@@ -147,6 +147,18 @@ var TOKEN_TOGGLES = [
147
147
  label: "Reparar el \xEDndice al cerrar sesi\xF3n",
148
148
  desc: "Si el \xEDndice qued\xF3 sin vectores, reconstruirlo en segundo plano al terminar la sesi\xF3n",
149
149
  impact: "no gasta tokens; sin esto la b\xFAsqueda puede quedarse en keyword-only (peor contexto por prompt)"
150
+ },
151
+ {
152
+ key: "docs.interceptRead",
153
+ label: "Redirigir lectura de PDF/DOCX/XLSX",
154
+ desc: "En Claude Code, la primera lectura directa de un PDF/DOCX/XLSX/CSV grande se redirige a doc_ingest/doc_read (el segundo intento pasa)",
155
+ impact: "ahorra ~2,000 tokens por p\xE1gina de PDF; desact\xEDvalo si sueles necesitar ver im\xE1genes/gr\xE1ficas"
156
+ },
157
+ {
158
+ key: "clean.auto",
159
+ label: "Limpieza autom\xE1tica semanal",
160
+ desc: "Al cerrar sesi\xF3n (m\xE1x. 1 vez por semana, en segundo plano): compacta prompts viejos sin reuso y purga cach\xE9s \u2014 nunca toca lecciones, planes, mapas ni sesiones",
161
+ impact: "no gasta tokens; baja el \xEDndice y el ruido en la b\xFAsqueda (mejor contexto por prompt)"
150
162
  }
151
163
  ];
152
164
  function writeProjectConfig(projectDir, vaultPath) {
@@ -157,6 +169,74 @@ function writeProjectConfig(projectDir, vaultPath) {
157
169
  return file;
158
170
  }
159
171
 
172
+ // src/hooks/adapters.ts
173
+ var HARNESSES = ["claude", "codex", "gemini", "cursor", "opencode"];
174
+ function currentHarness(argv = process.argv) {
175
+ const arg = argv.find((a) => a.startsWith("--harness="))?.slice("--harness=".length);
176
+ return HARNESSES.includes(arg ?? "") ? arg : "claude";
177
+ }
178
+ function normalizeInput(raw) {
179
+ const event = raw.hook_event_name ?? "";
180
+ return {
181
+ session_id: raw.session_id ?? raw.conversation_id,
182
+ transcript_path: raw.transcript_path ?? void 0,
183
+ cwd: raw.cwd ?? raw.workspace_roots?.[0],
184
+ prompt: raw.prompt,
185
+ answer: raw.last_assistant_message ?? raw.prompt_response ?? raw.text,
186
+ compact: /^(PreCompact|PreCompress|preCompact)$/.test(event) || Boolean(raw.trigger),
187
+ toolName: raw.tool_name,
188
+ filePath: raw.tool_input?.file_path
189
+ };
190
+ }
191
+ function formatContext(harness, kind, text) {
192
+ switch (harness) {
193
+ case "claude":
194
+ case "opencode":
195
+ return text;
196
+ case "codex":
197
+ return JSON.stringify({
198
+ hookSpecificOutput: { hookEventName: kind === "session" ? "SessionStart" : "UserPromptSubmit", additionalContext: text }
199
+ });
200
+ case "gemini":
201
+ return JSON.stringify({
202
+ hookSpecificOutput: { hookEventName: kind === "session" ? "SessionStart" : "BeforeAgent", additionalContext: text }
203
+ });
204
+ case "cursor":
205
+ return kind === "session" ? JSON.stringify({ additional_context: text }) : null;
206
+ }
207
+ }
208
+ function defaultOutput(harness, kind) {
209
+ if (harness === "cursor" && kind === "prompt") return JSON.stringify({ continue: true });
210
+ return null;
211
+ }
212
+ var TEXT_PARTS = /* @__PURE__ */ new Set(["text", "input_text", "output_text"]);
213
+ function textOf(content) {
214
+ if (typeof content === "string") return content;
215
+ if (!Array.isArray(content)) return "";
216
+ return content.filter((p) => TEXT_PARTS.has(p?.type) && typeof p?.text === "string").map((p) => p.text).join("\n");
217
+ }
218
+ function lastExchange(lines) {
219
+ let user = "";
220
+ let assistant = "";
221
+ for (const line of lines) {
222
+ let msg;
223
+ try {
224
+ msg = JSON.parse(line);
225
+ } catch {
226
+ continue;
227
+ }
228
+ const role = msg.message?.role ?? msg.payload?.role ?? msg.role ?? msg.type;
229
+ const text = textOf(msg.message?.content ?? msg.payload?.content ?? msg.content).trim();
230
+ if (!text) continue;
231
+ if (role === "user" && !text.startsWith("<")) user = text;
232
+ if (role === "assistant") assistant = text;
233
+ }
234
+ return { user, assistant };
235
+ }
236
+ function isHarnessInjected(prompt) {
237
+ return /^<(task-notification|system-reminder|command-|local-command|user-prompt-submit-hook|ide_)/i.test(prompt.trim());
238
+ }
239
+
160
240
  export {
161
241
  globalConfigPath,
162
242
  defaultVaultPath,
@@ -170,5 +250,11 @@ export {
170
250
  toggleEnabled,
171
251
  initScopeWarning,
172
252
  TOKEN_TOGGLES,
173
- writeProjectConfig
253
+ writeProjectConfig,
254
+ currentHarness,
255
+ normalizeInput,
256
+ formatContext,
257
+ defaultOutput,
258
+ lastExchange,
259
+ isHarnessInjected
174
260
  };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-QB37UGO6.js";
4
+ } from "./chunk-BV2KJV5W.js";
5
5
 
6
6
  // src/graph/viewer.ts
7
7
  import fs from "fs";