@ureck/alexandria 1.5.0 → 1.6.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
@@ -63,7 +63,7 @@ Verify:
63
63
 
64
64
  ```bash
65
65
  $ ale --version
66
- 1.5.0
66
+ 1.6.0
67
67
  ```
68
68
 
69
69
  ## Getting started
@@ -156,6 +156,30 @@ From any agent, the MCP tools `doc_ingest` (returns a ~200-token section outline
156
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
157
  - `ale stats` shows the **measured** document savings: tokens of the originals vs tokens actually served.
158
158
 
159
+ ### Manage the context window (1.6)
160
+
161
+ Most tokens don't go into your prompt — they go into **tool output** and **re-reading**. Alexandria trims both, locally, without a proxy and without rewriting history (which would break the provider's prompt cache):
162
+
163
+ ```bash
164
+ ale run -- npm test # exit code preserved; agent gets errors + summary + tail
165
+ ale run show last --grep "FAIL|Error" # the full output stays on disk
166
+ ale code outline src/ # symbols per file, no bodies
167
+ ale code symbol src/cli.ts runClean # just that function, with line numbers
168
+ ale context # what was injected per session, and what was saved
169
+ ale supersede "Decision - MySQL" "Decision - Postgres"
170
+ ```
171
+
172
+ | Feature | What it does | Measured |
173
+ |---|---|---|
174
+ | **Folded command output** | Large outputs of tests/builds/installs/logs → errors (with stack location) + test summary + tail; full output in `~/.cache/alexandria/runs`. Automatic in Claude Code (`PostToolUse` on Bash, successful commands) and OpenCode (plugin, also failures); `ale run -- <cmd>` everywhere else. Commands that *read* (`cat`, `git diff`, `grep`…) are never folded | test suite 12.1 KB → 1.4 KB; failing run 12.6 KB → 561 B keeping the failing test, assertion and `file:line` |
175
+ | **Code map** | `code_outline` (signatures + line ranges, classes → methods, top-level constants) and `code_symbol` (one body). JS/TS, Python, PHP, Go, Java, C#, Kotlin, Rust — heuristic, no native deps | `src/cli.ts` ~13,600 tokens → outline ~253 |
176
+ | **No re-injection** | A note already injected in this session is referenced in one line instead of re-sent (toggle `context.dedupe`) | shown in `ale context` / `ale stats` |
177
+ | **Anti-compaction capsule** | Before compacting, a capsule (goal, last request, files edited/read, recent commands, what was saved, open plans) is built **without an LLM** and re-injected right after | real 8.4 MB transcript → ~576 tokens |
178
+ | **Facts that expire** | `vault_save(..., supersedes: [...])` / `ale supersede`: the old note is marked, linked and no longer injected — never deleted | |
179
+ | **Duplicate suggestions** | `ale clean` lists near-identical lessons/notes (cosine ≥ 0.96); applied only with `--dedupe` | |
180
+ | **Context meter** | `ale context [--session id]`: injections, tokens, notes, folded runs, savings per session | |
181
+ | **Docs by URL** | `doc_ingest`/`ale ingest` accept `https://…`: one page, fetched once, reused 7 days — the only network access, and only when asked | |
182
+
159
183
  ### Control what spends tokens (`ale toggles`)
160
184
 
161
185
  Every token-spending behavior is opt-out — before or after installing (the config is global, independent of the vault):
@@ -166,7 +190,7 @@ ale init --off architect.enrich,digest.map # disable from the start
166
190
  ale config set tokens.solutionCache false # scriptable, one by one
167
191
  ```
168
192
 
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.
193
+ 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`), folding large command output (`run.fold`), not re-injecting notes already in context (`context.dedupe`), 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.
170
194
 
171
195
  ### Deep project context (`ale scan`)
172
196
 
@@ -314,6 +338,7 @@ AI agent session
314
338
  │ └─ near-identical prompt already solved → injects the solution (cache)
315
339
  ├─ MCP tools ─────► vault_search · vault_save · vault_related · vault_link (all agents)
316
340
  │ doc_ingest · doc_read (documents by section, token budget)
341
+ │ code_outline · code_symbol · run_output (code map, folded runs)
317
342
  │ plan_create · task_verify · lesson_extract (the Protocol)
318
343
  └─ Stop/PreCompact► saves the session outcome into the vault (hooks)
319
344
  hooks: Claude Code · Codex · Gemini CLI · Cursor · OpenCode (one set of scripts, --harness=<id>)
@@ -345,13 +370,17 @@ AI agent session
345
370
  | `ale config <get\|set> <key> [value]` | Configuration (e.g. `protocol` true/false) |
346
371
  | `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 |
347
372
  | `ale reindex [--force]` | Reindex (incremental by default) |
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`) |
373
+ | `ale clean [--yes] [--days n] [--backup f] [--keep-noise] [--dedupe]` | 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
374
  | `ale consolidate [--days n] [--dry]` | Alias of `ale clean --prompts-only` |
350
375
  | `ale doctor [--project]` | Check & repair: model, hooks, MCP, index |
351
376
  | `ale uninstall [--project]` | Remove hooks, MCP and instruction blocks from every agent (notes stay untouched) |
352
377
  | `ale ingest <paths...> [--force]` | Convert PDF/DOCX/XLSX/CSV/HTML/MD to markdown sections and store them in the vault |
353
378
  | `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) |
379
+ | `ale run -- <cmd>` / `ale run show <id\|last> [--grep re] [--lines a-b]` / `ale run list` | Run a command with folded output (same exit code) / read the full output |
380
+ | `ale code outline <file\|dir>` / `ale code symbol <file> <name>` | Code map: signatures without bodies / one symbol's body (`Class.method` works) |
381
+ | `ale context [--session id] [--last n]` | Context meter per agent session |
382
+ | `ale supersede <old> <new>` | Mark a note as replaced (stops being injected, never deleted) |
383
+ | `ale hook <session-start\|prompt\|stop\|read\|bash> [--harness id]` | Run a hook (used by the plugins) |
355
384
  | `ale --vault <path> <cmd>` | Run any command against another vault |
356
385
 
357
386
  `alexandria` works as an alias of `ale`.
@@ -71,7 +71,7 @@ function parseNote(root, absPath) {
71
71
  const rel = path.relative(root, absPath).split(path.sep).join("/");
72
72
  const title = typeof data.title === "string" && data.title || path.basename(absPath, ".md");
73
73
  const type = NOTE_TYPES.includes(data.type) ? data.type : "note";
74
- const status = ["active", "completed", "failed"].includes(data.status) ? data.status : void 0;
74
+ const status = ["active", "completed", "failed", "superseded"].includes(data.status) ? data.status : void 0;
75
75
  const tags = Array.isArray(data.tags) ? data.tags.map(String) : [];
76
76
  return {
77
77
  rel,
@@ -81,6 +81,7 @@ function parseNote(root, absPath) {
81
81
  tags,
82
82
  created: isoDate(data.created),
83
83
  hits: typeof data.hits === "number" ? data.hits : 1,
84
+ supersededBy: typeof data.superseded_by === "string" ? data.superseded_by : void 0,
84
85
  content,
85
86
  links: extractWikilinks(content)
86
87
  };
@@ -135,6 +136,18 @@ function setNoteStatus(absPath, status) {
135
136
  data.updated = (/* @__PURE__ */ new Date()).toISOString();
136
137
  fs.writeFileSync(absPath, matter.stringify(content, data));
137
138
  }
139
+ function supersedeNote(absPath, newTitle) {
140
+ const raw = fs.readFileSync(absPath, "utf8");
141
+ const { data, content } = matter(raw);
142
+ data.status = "superseded";
143
+ data.superseded_by = newTitle;
144
+ data.updated = (/* @__PURE__ */ new Date()).toISOString();
145
+ const marker = `> \u26A0 Reemplazada por [[${newTitle}]]`;
146
+ const body = content.includes(marker) ? content : `${marker}
147
+
148
+ ${content.trimStart()}`;
149
+ fs.writeFileSync(absPath, matter.stringify(body, data));
150
+ }
138
151
  function touchNote(absPath) {
139
152
  const raw = fs.readFileSync(absPath, "utf8");
140
153
  const { data, content } = matter(raw);
@@ -350,6 +363,7 @@ var VaultIndex = class _VaultIndex {
350
363
  title: note.title,
351
364
  type: note.type,
352
365
  status: note.status,
366
+ supersededBy: note.supersededBy,
353
367
  tags: note.tags,
354
368
  created: note.created,
355
369
  hits: note.hits,
@@ -404,7 +418,7 @@ ${c.text}`),
404
418
  if (this.emb !== null) this.clearNeedsRebuild();
405
419
  else if (this.meta.chunks.length > 0 && modelPresent()) this.markNeedsRebuild();
406
420
  if (!isHookProcess()) try {
407
- const { writeStaticGraph } = await import("./viewer-WQQSQETT.js");
421
+ const { writeStaticGraph } = await import("./viewer-T2SEBP6Z.js");
408
422
  writeStaticGraph(this);
409
423
  } catch {
410
424
  }
@@ -479,6 +493,35 @@ ${c.text}`),
479
493
  }
480
494
  return (this._tagIndex.get(key) ?? []).map((rel) => this.meta.notes[rel]).filter(Boolean);
481
495
  }
496
+ /**
497
+ * Vector por nota = media normalizada de sus chunks (mismo cálculo que el
498
+ * grafo semántico). Para detectar notas casi duplicadas en `ale clean`.
499
+ */
500
+ noteVectors(types) {
501
+ const out = /* @__PURE__ */ new Map();
502
+ if (!this.emb) return out;
503
+ const byNote = /* @__PURE__ */ new Map();
504
+ this.meta.chunks.forEach((c, i) => {
505
+ const n = this.meta.notes[c.note];
506
+ if (!n || !types.includes(n.type) || n.status === "superseded") return;
507
+ const arr = byNote.get(c.note) ?? [];
508
+ arr.push(i);
509
+ byNote.set(c.note, arr);
510
+ });
511
+ for (const [rel, idxs] of byNote) {
512
+ const v = new Float32Array(this.meta.dim);
513
+ for (const i of idxs) {
514
+ const r = this.row(i);
515
+ for (let d = 0; d < this.meta.dim; d++) v[d] += r[d];
516
+ }
517
+ let norm = 0;
518
+ for (let d = 0; d < this.meta.dim; d++) norm += v[d] * v[d];
519
+ norm = Math.sqrt(norm) || 1;
520
+ for (let d = 0; d < this.meta.dim; d++) v[d] /= norm;
521
+ out.set(rel, v);
522
+ }
523
+ return out;
524
+ }
482
525
  /** Vecinos directos de una nota en el grafo (sin releer archivos). */
483
526
  neighbors(rel) {
484
527
  const out = [];
@@ -497,6 +540,7 @@ export {
497
540
  isoDate,
498
541
  createNote,
499
542
  setNoteStatus,
543
+ supersedeNote,
500
544
  touchNote,
501
545
  upsertNote,
502
546
  appendToNote,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-BV2KJV5W.js";
4
+ } from "./chunk-44QPE5IM.js";
5
5
  import {
6
6
  dot,
7
7
  embed,
@@ -48,7 +48,7 @@ var TYPE_BOOST = {
48
48
  };
49
49
  function recencyBoost(note) {
50
50
  if (!note) return 1;
51
- const typeBoost = TYPE_BOOST[note.type] ?? 1;
51
+ const typeBoost = (TYPE_BOOST[note.type] ?? 1) * (note.status === "superseded" ? 0.3 : 1);
52
52
  if (!note.created) return typeBoost;
53
53
  const age = (Date.now() - Date.parse(note.created)) / 864e5;
54
54
  if (Number.isNaN(age)) return typeBoost;
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ isHarnessInjected
4
+ } from "./chunk-YICWI3U3.js";
5
+
6
+ // src/core/capsule.ts
7
+ import fs from "fs";
8
+ import path from "path";
9
+ var MAX_SESSIONS = 30;
10
+ var CAPSULE_CHARS = 2400;
11
+ function injectedFile(cacheDir) {
12
+ return path.join(cacheDir, "injected.json");
13
+ }
14
+ function readStore(cacheDir) {
15
+ try {
16
+ return JSON.parse(fs.readFileSync(injectedFile(cacheDir), "utf8"));
17
+ } catch {
18
+ return {};
19
+ }
20
+ }
21
+ function injectedInSession(cacheDir, session) {
22
+ return new Set(readStore(cacheDir)[session]?.rels ?? []);
23
+ }
24
+ function rememberInjected(cacheDir, session, rels) {
25
+ if (!rels.length) return;
26
+ try {
27
+ const store = readStore(cacheDir);
28
+ const prev = store[session]?.rels ?? [];
29
+ store[session] = { rels: [.../* @__PURE__ */ new Set([...prev, ...rels])], t: (/* @__PURE__ */ new Date()).toISOString() };
30
+ const keys = Object.keys(store).sort((a, b) => store[a].t.localeCompare(store[b].t));
31
+ for (const k of keys.slice(0, Math.max(0, keys.length - MAX_SESSIONS))) delete store[k];
32
+ fs.mkdirSync(cacheDir, { recursive: true });
33
+ fs.writeFileSync(injectedFile(cacheDir), JSON.stringify(store));
34
+ } catch {
35
+ }
36
+ }
37
+ function forgetInjected(cacheDir, session) {
38
+ try {
39
+ const store = readStore(cacheDir);
40
+ if (!store[session]) return;
41
+ delete store[session];
42
+ fs.writeFileSync(injectedFile(cacheDir), JSON.stringify(store));
43
+ } catch {
44
+ }
45
+ }
46
+ var FILE_KEYS = ["file_path", "path", "notebook_path", "filePath"];
47
+ var TMP_PATH = /^(\/private)?\/tmp\/|^\/var\/folders\/|[\\/]scratchpad[\\/]|[\\/]tasks[\\/][^\\/]+\.output$/;
48
+ var EDIT_TOOLS = /^(Edit|Write|MultiEdit|NotebookEdit|apply_patch|edit|write)$/i;
49
+ function extractSession(lines) {
50
+ const out = { prompts: [], edited: [], read: [], commands: [], saved: [] };
51
+ for (const line of lines) {
52
+ let msg;
53
+ try {
54
+ msg = JSON.parse(line);
55
+ } catch {
56
+ continue;
57
+ }
58
+ const role = msg.message?.role ?? msg.type;
59
+ const content = msg.message?.content;
60
+ if (role === "user" && typeof content === "string") {
61
+ if (!content.trim().startsWith("<") && !isHarnessInjected(content)) out.prompts.push(content.trim());
62
+ continue;
63
+ }
64
+ if (!Array.isArray(content)) continue;
65
+ for (const b of content) {
66
+ if (role === "user" && b.type === "text" && b.text && !b.text.trim().startsWith("<") && !isHarnessInjected(b.text)) out.prompts.push(b.text.trim());
67
+ if (b.type !== "tool_use" || !b.input) continue;
68
+ const name = b.name ?? "";
69
+ const file = FILE_KEYS.map((k) => b.input[k]).find((v) => typeof v === "string" && /[\\/.]/.test(v));
70
+ if (file && !TMP_PATH.test(file)) (EDIT_TOOLS.test(name) ? out.edited : out.read).push(file);
71
+ if (/^(Bash|shell|bash)$/.test(name) && typeof b.input.command === "string") out.commands.push(b.input.command.split("\n")[0]);
72
+ if (/(vault_save|lesson_extract|plan_create)$/.test(name) && typeof b.input.title === "string") {
73
+ const prefix = name.endsWith("lesson_extract") ? "Lecci\xF3n - " : name.endsWith("plan_create") ? "Plan - " : "";
74
+ out.saved.push(prefix + b.input.title);
75
+ }
76
+ }
77
+ }
78
+ return out;
79
+ }
80
+ var one = (s, n) => {
81
+ const t = s.replace(/\s+/g, " ").trim();
82
+ return t.length > n ? t.slice(0, n) + "\u2026" : t;
83
+ };
84
+ var uniq = (xs) => [...new Set(xs)];
85
+ var short = (p, cwd) => cwd && p.startsWith(cwd) ? path.relative(cwd, p) || p : p;
86
+ function buildCapsule(ex, opts = {}) {
87
+ const parts = [];
88
+ if (ex.prompts.length) {
89
+ parts.push(`Objetivo inicial: ${one(ex.prompts[0], 300)}`);
90
+ if (ex.prompts.length > 1) parts.push(`\xDAltimo pedido: ${one(ex.prompts[ex.prompts.length - 1], 300)}`);
91
+ const mid = uniq(ex.prompts.slice(1, -1)).slice(-4);
92
+ if (mid.length) parts.push(`Pedidos intermedios:
93
+ ${mid.map((p) => `- ${one(p, 150)}`).join("\n")}`);
94
+ }
95
+ const edited = uniq(ex.edited.map((f) => short(f, opts.cwd))).slice(-12);
96
+ const read = uniq(ex.read.map((f) => short(f, opts.cwd))).filter((f) => !edited.includes(f)).slice(-6);
97
+ if (edited.length) parts.push(`Archivos editados: ${edited.join(", ")}`);
98
+ if (read.length) parts.push(`Archivos consultados: ${read.join(", ")}`);
99
+ const cmds = uniq(ex.commands.map((c) => one(c, 90))).slice(-4);
100
+ if (cmds.length) parts.push(`Comandos recientes:
101
+ ${cmds.map((c) => `- ${c}`).join("\n")}`);
102
+ if (ex.saved.length) parts.push(`Guardado en la b\xF3veda: ${uniq(ex.saved).slice(-8).join(" \xB7 ")}`);
103
+ if (opts.openPlans?.length) parts.push(`Planes abiertos: ${opts.openPlans.slice(0, 5).join(" \xB7 ")}`);
104
+ if (!parts.length) return "";
105
+ const body = parts.join("\n");
106
+ return `<alexandria-capsula>
107
+ C\xE1psula de esta sesi\xF3n guardada antes de compactar \u2014 recupera lo que la compactaci\xF3n pudo perder (no re-explores lo que ya est\xE1 aqu\xED):
108
+ ` + (body.length > CAPSULE_CHARS ? body.slice(0, CAPSULE_CHARS) + "\u2026" : body) + `
109
+ </alexandria-capsula>`;
110
+ }
111
+ function capsuleFile(cacheDir, session) {
112
+ return path.join(cacheDir, "capsules", `${session.replace(/[^\w.-]/g, "_")}.md`);
113
+ }
114
+ function saveCapsule(cacheDir, session, text) {
115
+ if (!text) return;
116
+ try {
117
+ const f = capsuleFile(cacheDir, session);
118
+ fs.mkdirSync(path.dirname(f), { recursive: true });
119
+ fs.writeFileSync(f, text);
120
+ const dir = path.dirname(f);
121
+ const files = fs.readdirSync(dir).map((n) => ({ n, t: fs.statSync(path.join(dir, n)).mtimeMs })).sort((a, b) => a.t - b.t);
122
+ for (const x of files.slice(0, Math.max(0, files.length - MAX_SESSIONS))) fs.rmSync(path.join(dir, x.n), { force: true });
123
+ } catch {
124
+ }
125
+ }
126
+ function loadCapsule(cacheDir, session) {
127
+ try {
128
+ return fs.readFileSync(capsuleFile(cacheDir, session), "utf8");
129
+ } catch {
130
+ return null;
131
+ }
132
+ }
133
+
134
+ export {
135
+ injectedInSession,
136
+ rememberInjected,
137
+ forgetInjected,
138
+ extractSession,
139
+ buildCapsule,
140
+ saveCapsule,
141
+ loadCapsule
142
+ };