@ureck/alexandria 1.3.2 → 1.4.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.4.0
67
67
  ```
68
68
 
69
69
  ## Getting started
@@ -130,7 +130,7 @@ 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
134
 
135
135
  ### Control what spends tokens (`ale toggles`)
136
136
 
@@ -142,7 +142,7 @@ ale init --off architect.enrich,digest.map # disable from the start
142
142
  ale config set tokens.solutionCache false # scriptable, one by one
143
143
  ```
144
144
 
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.
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), 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
146
 
147
147
  ### Deep project context (`ale scan`)
148
148
 
@@ -232,9 +232,11 @@ Flags plans without a Definition of Done, failures without lessons, and orphan n
232
232
  ```bash
233
233
  ale doctor # checks & repairs: model, hooks, MCP, index
234
234
  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
235
+ ale clean # PREVIEW of a safe cleanup (touches nothing)
236
+ ale clean --yes [--backup f] # apply: old unused prompts → compacted monthly files (full text),
237
+ # harness noise dropped, stale caches purged. Lessons, plans, maps,
238
+ # sessions are NEVER touched. Still searchable: ale search --archive "…"
239
+ ale uninstall # removes hooks + MCP from every agent; your notes stay untouched
238
240
  ```
239
241
 
240
242
  Every command self-repairs before running: missing model → downloads it; stale index → updates it.
@@ -247,35 +249,49 @@ ale agents all # register the MCP server in all of them
247
249
  ale agents cursor,gemini # just these
248
250
  ```
249
251
 
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).
252
+ | Agent | MCP config written | Hooks (auto capture + injection) | Per-project |
253
+ |---|---|---|---|
254
+ | Claude Code | `.mcp.json` / `claude mcp add` | `.claude/settings.json` — SessionStart · UserPromptSubmit · Stop · PreCompact | ✓ |
255
+ | Codex CLI | `~/.codex/config.toml` / `.codex/config.toml` | `.codex/hooks.json` — SessionStart · UserPromptSubmit · Stop · PreCompact ¹ | ✓ |
256
+ | Gemini CLI | `~/.gemini/settings.json` / `.gemini/settings.json` | same file — SessionStart · BeforeAgent · AfterAgent · PreCompress | ✓ |
257
+ | Cursor | `~/.cursor/mcp.json` / `.cursor/mcp.json` | `.cursor/hooks.json` — sessionStart · beforeSubmitPrompt ² · afterAgentResponse | ✓ |
258
+ | OpenCode | `opencode.json` | plugin `.opencode/plugins/alexandria.js` — injects into the system prompt | ✓ |
259
+ | Devin CLI (Cognition) | `.devin/mcp_config.local.json` | — | ✓ |
260
+ | Cline | `cline_mcp_settings.json` (VS Code) | — | — |
261
+ | VS Code (Copilot) | `mcp.json` (profile) / `.vscode/mcp.json` | — | ✓ |
262
+ | OpenClaw | `~/.openclaw/openclaw.json` | — | — |
263
+ | Hermes Agent (Nous) | `hermes mcp add` / `~/.hermes/config.yaml` | — | — |
264
+ | Windsurf (legacy → Devin) | `~/.codeium/windsurf/mcp_config.json` | — | — |
265
+
266
+ ¹ Codex skips untrusted hooks: open Codex once and approve them with `/hooks`.
267
+ ² Cursor's `beforeSubmitPrompt` can't inject context — there Alexandria captures the prompt; context arrives via `sessionStart` and the MCP tools.
268
+
269
+ `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`.
270
+
271
+ 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).
272
+
273
+ ### As a plugin
274
+
275
+ 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`):
276
+
277
+ ```bash
278
+ npm i -g @ureck/alexandria
279
+ claude plugin marketplace add UreckChan/alexandria
280
+ claude plugin install alexandria@alexandria
281
+ ```
267
282
 
268
283
  ## How it works
269
284
 
270
285
  ```
271
286
  AI agent session
272
287
  │
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)
288
+ ├─ SessionStart ──► injects digest: protocol manifest + project map + open plans (hooks)
289
+ ├─ Every prompt ──► local hybrid search → injects only what's relevant (hooks)
275
290
  │ └─ near-identical prompt already solved → injects the solution (cache)
276
291
  ├─ MCP tools ─────► vault_search · vault_save · vault_related · vault_link (all agents)
277
292
  │ plan_create · task_verify · lesson_extract (the Protocol)
278
- └─ Stop/PreCompact► saves the session outcome into the vault (hooks, Claude Code)
293
+ └─ Stop/PreCompact► saves the session outcome into the vault (hooks)
294
+ hooks: Claude Code · Codex · Gemini CLI · Cursor · OpenCode (one set of scripts, --harness=<id>)
279
295
  │
280
296
  <Obsidian vault>/Alexandria/*.md ← markdown, [[wikilinks]]
281
297
  <vault>/.vault/ ← index (regenerable)
@@ -294,8 +310,8 @@ AI agent session
294
310
  | `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
311
  | `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
312
  | `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 |
313
+ | `ale agents [ids] [--project] [--no-hooks]` | List agents / register the MCP server + hooks where supported |
314
+ | `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
315
  | `ale add <title> [-c text] [--file <path>] [-t tags]` | Save a note (inline, from file, or stdin) |
300
316
  | `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
317
  | `ale graph [--out file.html] [--no-open]` | Live local graph viewer |
@@ -304,9 +320,11 @@ AI agent session
304
320
  | `ale config <get\|set> <key> [value]` | Configuration (e.g. `protocol` true/false) |
305
321
  | `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
322
  | `ale reindex [--force]` | Reindex (incremental by default) |
307
- | `ale consolidate [--days n] [--dry]` | Archive old unused prompts — never deletes |
323
+ | `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`) |
324
+ | `ale consolidate [--days n] [--dry]` | Alias of `ale clean --prompts-only` |
308
325
  | `ale doctor [--project]` | Check & repair: model, hooks, MCP, index |
309
- | `ale uninstall [--project]` | Remove hooks (notes stay untouched) |
326
+ | `ale uninstall [--project]` | Remove hooks, MCP and instruction blocks from every agent (notes stay untouched) |
327
+ | `ale hook <session-start\|prompt\|stop> [--harness id]` | Run a hook (used by the plugins) |
310
328
  | `ale --vault <path> <cmd>` | Run any command against another vault |
311
329
 
312
330
  `alexandria` works as an alias of `ale`.
@@ -0,0 +1,258 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ charsToTokens,
4
+ isHarnessInjected
5
+ } from "./chunk-MDGFK6UC.js";
6
+ import {
7
+ isoDate
8
+ } from "./chunk-3CB7GRFJ.js";
9
+ import {
10
+ MODEL_ID,
11
+ modelCacheDir
12
+ } from "./chunk-EDYBSJSS.js";
13
+
14
+ // src/core/clean.ts
15
+ import fs from "fs";
16
+ import path from "path";
17
+ import matter from "gray-matter";
18
+ var ARCHIVE_DIR = "archive";
19
+ var STATS_KEEP_DAYS = 90;
20
+ function archiveRoot(vault) {
21
+ return path.join(vault.managed, ARCHIVE_DIR);
22
+ }
23
+ function bodyOf(abs) {
24
+ try {
25
+ return matter(fs.readFileSync(abs, "utf8")).content.trim();
26
+ } catch {
27
+ return "";
28
+ }
29
+ }
30
+ function promptText(body) {
31
+ return body.replace(/^Proyecto: \[\[[^\]]*\]\]\s*/m, "").replace(/^## Prompt\s*/m, "").trim();
32
+ }
33
+ function sizeOf(p) {
34
+ try {
35
+ const st = fs.statSync(p);
36
+ if (!st.isDirectory()) return st.size;
37
+ return fs.readdirSync(p).reduce((s, f) => s + sizeOf(path.join(p, f)), 0);
38
+ } catch {
39
+ return 0;
40
+ }
41
+ }
42
+ function planClean(vault, notes, opts) {
43
+ const cutoff = Date.now() - opts.days * 864e5;
44
+ const archRel = path.relative(vault.root, archiveRoot(vault)).split(path.sep).join("/");
45
+ const bundles = /* @__PURE__ */ new Map();
46
+ const noise = [];
47
+ const legacy = [];
48
+ try {
49
+ for (const f of fs.readdirSync(archiveRoot(vault))) {
50
+ if (!f.endsWith(".md")) continue;
51
+ const abs = path.join(archiveRoot(vault), f);
52
+ if (!fs.statSync(abs).isFile()) continue;
53
+ const fm = matter(fs.readFileSync(abs, "utf8")).data;
54
+ if (fm.type !== "prompt") continue;
55
+ legacy.push({
56
+ rel: path.relative(vault.root, abs).split(path.sep).join("/"),
57
+ title: fm.title ?? f,
58
+ type: "prompt",
59
+ tags: Array.isArray(fm.tags) ? fm.tags : [],
60
+ created: isoDate(fm.created),
61
+ hits: fm.hits ?? 1,
62
+ links: []
63
+ });
64
+ }
65
+ } catch {
66
+ }
67
+ for (const n of [...notes, ...legacy]) {
68
+ if (n.type !== "prompt") continue;
69
+ const abs = path.join(vault.root, n.rel);
70
+ if (!opts.keepNoise && isHarnessInjected(promptText(bodyOf(abs)))) {
71
+ noise.push(n);
72
+ continue;
73
+ }
74
+ const legacy2 = n.rel.startsWith(`${archRel}/`);
75
+ const old = n.created !== void 0 && Date.parse(n.created) < cutoff;
76
+ if (!legacy2 && !(old && (n.hits ?? 1) <= 1)) continue;
77
+ const proj = (n.tags.find((t) => t !== "prompt") ?? "general").replace(/[\\/:*?"<>|]/g, "-");
78
+ const key = `${proj}/${(n.created ?? "").slice(0, 7) || "sin-fecha"}`;
79
+ const list = bundles.get(key) ?? [];
80
+ list.push(n);
81
+ bundles.set(key, list);
82
+ }
83
+ let tmpFiles = [];
84
+ try {
85
+ tmpFiles = fs.readdirSync(vault.cache).filter((f) => f.endsWith(".tmp")).map((f) => path.join(vault.cache, f));
86
+ } catch {
87
+ }
88
+ const staleModels = [];
89
+ const [org, name] = MODEL_ID.split("/");
90
+ try {
91
+ for (const o of fs.readdirSync(modelCacheDir())) {
92
+ const orgDir = path.join(modelCacheDir(), o);
93
+ if (!fs.statSync(orgDir).isDirectory()) continue;
94
+ for (const m of fs.readdirSync(orgDir)) {
95
+ const dir = path.join(orgDir, m);
96
+ if (!(o === org && m === name) && fs.existsSync(path.join(dir, "config.json"))) staleModels.push(dir);
97
+ }
98
+ }
99
+ } catch {
100
+ }
101
+ return { bundles, noise, tmpFiles, staleModels, statsLinesToRotate: oldStatsLines(vault).length };
102
+ }
103
+ function oldStatsLines(vault) {
104
+ const cutoff = Date.now() - STATS_KEEP_DAYS * 864e5;
105
+ try {
106
+ return fs.readFileSync(path.join(vault.cache, "stats.jsonl"), "utf8").split("\n").filter((l) => {
107
+ try {
108
+ const o = JSON.parse(l);
109
+ return o.t !== "summary" && Date.parse(o.t ?? "") < cutoff;
110
+ } catch {
111
+ return false;
112
+ }
113
+ });
114
+ } catch {
115
+ return [];
116
+ }
117
+ }
118
+ function writeAtomic(file, text) {
119
+ const tmp = `${file}.${process.pid}.tmp`;
120
+ fs.writeFileSync(tmp, text);
121
+ fs.renameSync(tmp, file);
122
+ }
123
+ function section(n, text) {
124
+ return `## ${(n.created ?? "").slice(0, 10)} \u2014 ${n.title.replace(/\n/g, " ")}
125
+
126
+ ${text}
127
+ `;
128
+ }
129
+ function applyClean(vault, plan) {
130
+ const res = { compacted: 0, dropped: 0, bundlesWritten: 0, removedDerived: 0, bytesFreed: 0 };
131
+ for (const [key, list] of plan.bundles) {
132
+ const [proj, month] = key.split("/");
133
+ const file = path.join(archiveRoot(vault), proj, `${month}.md`);
134
+ fs.mkdirSync(path.dirname(file), { recursive: true });
135
+ 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);
136
+ if (items.length === 0) continue;
137
+ let current = "";
138
+ try {
139
+ current = fs.readFileSync(file, "utf8");
140
+ } catch {
141
+ current = matter.stringify(
142
+ `Prompts archivados por \`ale clean\`: texto \xEDntegro, fuera del \xEDndice sem\xE1ntico y del grafo.
143
+ B\xFAscalos con \`ale search --archive "<texto>"\`.
144
+
145
+ Proyecto: [[Mapa - ${proj}]]
146
+ `,
147
+ { title: `Archivo de prompts \u2014 ${proj} ${month}`, type: "archive", tags: [proj, "archivo"], created: (/* @__PURE__ */ new Date()).toISOString() }
148
+ ).trimEnd() + "\n";
149
+ }
150
+ const next = current.trimEnd() + "\n\n" + items.map((x) => section(x.n, x.text)).join("\n");
151
+ writeAtomic(file, next);
152
+ res.bundlesWritten++;
153
+ const written = fs.readFileSync(file, "utf8");
154
+ for (const x of items) {
155
+ if (!written.includes(x.text)) continue;
156
+ res.bytesFreed += sizeOf(x.abs);
157
+ fs.rmSync(x.abs, { force: true });
158
+ res.compacted++;
159
+ }
160
+ }
161
+ for (const n of plan.noise) {
162
+ const abs = path.join(vault.root, n.rel);
163
+ res.bytesFreed += sizeOf(abs);
164
+ fs.rmSync(abs, { force: true });
165
+ res.dropped++;
166
+ }
167
+ for (const p of [...plan.tmpFiles, ...plan.staleModels]) {
168
+ res.bytesFreed += sizeOf(p);
169
+ fs.rmSync(p, { recursive: true, force: true });
170
+ res.removedDerived++;
171
+ }
172
+ rotateStats(vault);
173
+ return res;
174
+ }
175
+ function rotateStats(vault) {
176
+ const file = path.join(vault.cache, "stats.jsonl");
177
+ const old = new Set(oldStatsLines(vault));
178
+ if (old.size === 0) return 0;
179
+ const lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean);
180
+ const agg = /* @__PURE__ */ new Map();
181
+ const keep = [];
182
+ for (const l of lines) {
183
+ let o;
184
+ try {
185
+ o = JSON.parse(l);
186
+ } catch {
187
+ continue;
188
+ }
189
+ if (old.has(l) || o.t === "summary") {
190
+ const a = agg.get(o.kind ?? "inject") ?? { injectedChars: 0, count: 0, tokens: 0 };
191
+ a.injectedChars += o.injectedChars ?? 0;
192
+ a.count += o.count ?? 1;
193
+ a.tokens += o.tokens ?? charsToTokens(o.injectedChars ?? 0);
194
+ agg.set(o.kind ?? "inject", a);
195
+ } else keep.push(l);
196
+ }
197
+ const summary = [...agg].map(([kind, a]) => JSON.stringify({ t: "summary", kind, ...a }));
198
+ writeAtomic(file, [...summary, ...keep].join("\n") + "\n");
199
+ return old.size;
200
+ }
201
+ function searchArchive(vault, query, k = 5) {
202
+ const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length > 2);
203
+ if (terms.length === 0) return [];
204
+ const hits = [];
205
+ const walk = (dir) => {
206
+ let entries = [];
207
+ try {
208
+ entries = fs.readdirSync(dir, { withFileTypes: true });
209
+ } catch {
210
+ return;
211
+ }
212
+ for (const e of entries) {
213
+ const full = path.join(dir, e.name);
214
+ if (e.isDirectory()) walk(full);
215
+ else if (e.name.endsWith(".md")) {
216
+ const text = fs.readFileSync(full, "utf8");
217
+ for (const sec of text.split(/\n(?=## )/)) {
218
+ const low = sec.toLowerCase();
219
+ const score = terms.reduce((s, t) => s + (low.includes(t) ? 1 : 0), 0);
220
+ if (score === 0) continue;
221
+ const heading = sec.match(/^## (.+)$/m)?.[1] ?? path.basename(full);
222
+ hits.push({ file: path.relative(vault.root, full), heading, excerpt: sec.replace(/^## .+\n/, "").trim().slice(0, 400), score });
223
+ }
224
+ }
225
+ }
226
+ };
227
+ walk(archiveRoot(vault));
228
+ return hits.sort((a, b) => b.score - a.score).slice(0, k).map(({ score: _s, ...h }) => h);
229
+ }
230
+ function dirBytes(p, exclude) {
231
+ return sizeOf(p) - (exclude ? sizeOf(exclude) : 0);
232
+ }
233
+ var LAST_CLEAN = "last-clean";
234
+ function autoCleanDue(vault) {
235
+ try {
236
+ const t = fs.statSync(path.join(vault.cache, LAST_CLEAN)).mtimeMs;
237
+ return Date.now() - t > 7 * 864e5;
238
+ } catch {
239
+ return true;
240
+ }
241
+ }
242
+ function markCleaned(vault) {
243
+ try {
244
+ fs.mkdirSync(vault.cache, { recursive: true });
245
+ fs.writeFileSync(path.join(vault.cache, LAST_CLEAN), (/* @__PURE__ */ new Date()).toISOString());
246
+ } catch {
247
+ }
248
+ }
249
+
250
+ export {
251
+ ARCHIVE_DIR,
252
+ planClean,
253
+ applyClean,
254
+ searchArchive,
255
+ dirBytes,
256
+ autoCleanDue,
257
+ markCleaned
258
+ };
@@ -21,7 +21,8 @@ var NOTE_TYPES = [
21
21
  "task",
22
22
  "verification",
23
23
  "lesson",
24
- "solution"
24
+ "solution",
25
+ "archive"
25
26
  ];
26
27
  var SKIP_DIRS = /* @__PURE__ */ new Set([".obsidian", ".vault", ".trash", ".git", "node_modules"]);
27
28
  function extractWikilinks(content) {
@@ -37,9 +38,16 @@ function extractWikilinks(content) {
37
38
  function slugify(text) {
38
39
  return text.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "nota";
39
40
  }
40
- function listMarkdownFiles(root) {
41
+ function isoDate(v) {
42
+ if (v === void 0 || v === null || v === "") return void 0;
43
+ const d = v instanceof Date ? v : new Date(String(v));
44
+ return isNaN(d.getTime()) ? String(v) : d.toISOString();
45
+ }
46
+ function listMarkdownFiles(root, skip = []) {
41
47
  const out = [];
48
+ const skipSet = new Set(skip.map((d) => path.resolve(d)));
42
49
  const walk = (dir) => {
50
+ if (skipSet.has(path.resolve(dir))) return;
43
51
  let entries;
44
52
  try {
45
53
  entries = fs.readdirSync(dir, { withFileTypes: true });
@@ -70,7 +78,7 @@ function parseNote(root, absPath) {
70
78
  type,
71
79
  status,
72
80
  tags,
73
- created: data.created ? String(data.created) : void 0,
81
+ created: isoDate(data.created),
74
82
  hits: typeof data.hits === "number" ? data.hits : 1,
75
83
  content,
76
84
  links: extractWikilinks(content)
@@ -212,6 +220,7 @@ var VaultIndex = class _VaultIndex {
212
220
  const meta = JSON.parse(fs2.readFileSync(idx.metaPath, "utf8"));
213
221
  if (meta.version === 1 && meta.model === MODEL_ID) {
214
222
  idx.meta = meta;
223
+ for (const n of Object.values(meta.notes)) n.created = isoDate(n.created);
215
224
  try {
216
225
  const buf = fs2.readFileSync(idx.embPath);
217
226
  const arr = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);
@@ -286,7 +295,7 @@ var VaultIndex = class _VaultIndex {
286
295
  * `withEmbeddings=false` → índice keyword-only (sin cargar modelo).
287
296
  */
288
297
  async refresh(withEmbeddings = modelPresent(), force = false) {
289
- const files = listMarkdownFiles(this.vault.root);
298
+ const files = listMarkdownFiles(this.vault.root, [path2.join(this.vault.managed, "archive")]);
290
299
  const onDisk = /* @__PURE__ */ new Map();
291
300
  for (const abs of files) {
292
301
  const rel = path2.relative(this.vault.root, abs).split(path2.sep).join("/");
@@ -390,8 +399,8 @@ ${c.text}`),
390
399
  this.save();
391
400
  if (this.emb !== null) this.clearNeedsRebuild();
392
401
  else if (this.meta.chunks.length > 0 && modelPresent()) this.markNeedsRebuild();
393
- try {
394
- const { writeStaticGraph } = await import("./viewer-JQCSWJ3C.js");
402
+ if (!isHookProcess()) try {
403
+ const { writeStaticGraph } = await import("./viewer-OU4TB3X5.js");
395
404
  writeStaticGraph(this);
396
405
  } catch {
397
406
  }
@@ -456,7 +465,7 @@ ${c.text}`),
456
465
  if (!this._tagIndex) {
457
466
  const m = /* @__PURE__ */ new Map();
458
467
  for (const n of Object.values(this.meta.notes)) {
459
- for (const k of [n.type, ...n.tags]) {
468
+ for (const k of /* @__PURE__ */ new Set([n.type, ...n.tags])) {
460
469
  const arr = m.get(k);
461
470
  if (arr) arr.push(n.rel);
462
471
  else m.set(k, [n.rel]);
@@ -481,6 +490,7 @@ ${c.text}`),
481
490
 
482
491
  export {
483
492
  slugify,
493
+ isoDate,
484
494
  createNote,
485
495
  setNoteStatus,
486
496
  touchNote,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-QB37UGO6.js";
4
+ } from "./chunk-3CB7GRFJ.js";
5
5
 
6
6
  // src/graph/viewer.ts
7
7
  import fs from "fs";
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-QB37UGO6.js";
4
+ } from "./chunk-3CB7GRFJ.js";
5
5
  import {
6
6
  dot,
7
7
  embed,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  hybridSearch
4
- } from "./chunk-UWB6RKVN.js";
4
+ } from "./chunk-FPKJVQ2X.js";
5
5
 
6
6
  // src/core/planning.ts
7
7
  var MAX_ITEMS = 2;
@@ -138,7 +138,9 @@ function registerMcpGlobal(portable = false) {
138
138
  try {
139
139
  execFileSync("claude", ["mcp", "add", "--scope", "user", "alexandria", "--", command, ...args], {
140
140
  stdio: "pipe",
141
- timeout: 15e3
141
+ timeout: 15e3,
142
+ shell: process.platform === "win32"
143
+ // en Windows los binarios globales de npm son shims .cmd/.ps1
142
144
  });
143
145
  return true;
144
146
  } catch {
@@ -173,6 +175,7 @@ export {
173
175
  planContext,
174
176
  planQualityHints,
175
177
  architectBlock,
178
+ distDir,
176
179
  registerHooks,
177
180
  unregisterHooks,
178
181
  projectSettingsPath,