@ureck/alexandria 1.4.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 +60 -4
- package/dist/{chunk-3CB7GRFJ.js → chunk-44QPE5IM.js} +52 -4
- package/dist/{chunk-FPKJVQ2X.js → chunk-47S5I3D3.js} +2 -2
- package/dist/chunk-ADA25MTF.js +142 -0
- package/dist/chunk-BXVNQVLX.js +831 -0
- package/dist/chunk-I5H4BN3F.js +263 -0
- package/dist/chunk-OGVWOBYH.js +197 -0
- package/dist/{chunk-4ZSTD3CU.js → chunk-SSTG2NOO.js} +1 -1
- package/dist/{chunk-2ESJQAP4.js → chunk-WSVNMMNN.js} +45 -9
- package/dist/{chunk-U2U53TU2.js → chunk-WVZQGLRI.js} +1 -1
- package/dist/chunk-X4V6SYYA.js +131 -0
- package/dist/{chunk-MDGFK6UC.js → chunk-YICWI3U3.js} +28 -54
- package/dist/cli.js +240 -21
- package/dist/hooks/on-bash.js +45 -0
- package/dist/hooks/on-prompt.js +37 -13
- package/dist/hooks/on-read.js +70 -0
- package/dist/hooks/on-session-start.js +20 -9
- package/dist/hooks/on-stop.js +26 -7
- package/dist/mcp/server.js +118 -15
- package/dist/{viewer-OU4TB3X5.js → viewer-T2SEBP6Z.js} +2 -2
- package/package.json +15 -3
- package/dist/chunk-JI2L66DF.js +0 -189
package/README.md
CHANGED
|
@@ -63,7 +63,7 @@ Verify:
|
|
|
63
63
|
|
|
64
64
|
```bash
|
|
65
65
|
$ ale --version
|
|
66
|
-
1.
|
|
66
|
+
1.6.0
|
|
67
67
|
```
|
|
68
68
|
|
|
69
69
|
## Getting started
|
|
@@ -132,6 +132,54 @@ 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, Codex, Gemini CLI, Cursor and OpenCode session — `add` is for extra knowledge.)
|
|
134
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.
|
|
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
|
+
|
|
135
183
|
### Control what spends tokens (`ale toggles`)
|
|
136
184
|
|
|
137
185
|
Every token-spending behavior is opt-out — before or after installing (the config is global, independent of the vault):
|
|
@@ -142,7 +190,7 @@ ale init --off architect.enrich,digest.map # disable from the start
|
|
|
142
190
|
ale config set tokens.solutionCache false # scriptable, one by one
|
|
143
191
|
```
|
|
144
192
|
|
|
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.
|
|
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.
|
|
146
194
|
|
|
147
195
|
### Deep project context (`ale scan`)
|
|
148
196
|
|
|
@@ -289,6 +337,8 @@ AI agent session
|
|
|
289
337
|
├─ Every prompt ──► local hybrid search → injects only what's relevant (hooks)
|
|
290
338
|
│ └─ near-identical prompt already solved → injects the solution (cache)
|
|
291
339
|
├─ MCP tools ─────► vault_search · vault_save · vault_related · vault_link (all agents)
|
|
340
|
+
│ doc_ingest · doc_read (documents by section, token budget)
|
|
341
|
+
│ code_outline · code_symbol · run_output (code map, folded runs)
|
|
292
342
|
│ plan_create · task_verify · lesson_extract (the Protocol)
|
|
293
343
|
└─ Stop/PreCompact► saves the session outcome into the vault (hooks)
|
|
294
344
|
hooks: Claude Code · Codex · Gemini CLI · Cursor · OpenCode (one set of scripts, --harness=<id>)
|
|
@@ -320,11 +370,17 @@ AI agent session
|
|
|
320
370
|
| `ale config <get\|set> <key> [value]` | Configuration (e.g. `protocol` true/false) |
|
|
321
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 |
|
|
322
372
|
| `ale reindex [--force]` | Reindex (incremental by default) |
|
|
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`) |
|
|
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`) |
|
|
324
374
|
| `ale consolidate [--days n] [--dry]` | Alias of `ale clean --prompts-only` |
|
|
325
375
|
| `ale doctor [--project]` | Check & repair: model, hooks, MCP, index |
|
|
326
376
|
| `ale uninstall [--project]` | Remove hooks, MCP and instruction blocks from every agent (notes stay untouched) |
|
|
327
|
-
| `ale
|
|
377
|
+
| `ale ingest <paths...> [--force]` | Convert PDF/DOCX/XLSX/CSV/HTML/MD to markdown sections and store them in the vault |
|
|
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 |
|
|
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) |
|
|
328
384
|
| `ale --vault <path> <cmd>` | Run any command against another vault |
|
|
329
385
|
|
|
330
386
|
`alexandria` works as an alias of `ale`.
|
|
@@ -22,7 +22,8 @@ var NOTE_TYPES = [
|
|
|
22
22
|
"verification",
|
|
23
23
|
"lesson",
|
|
24
24
|
"solution",
|
|
25
|
-
"archive"
|
|
25
|
+
"archive",
|
|
26
|
+
"document"
|
|
26
27
|
];
|
|
27
28
|
var SKIP_DIRS = /* @__PURE__ */ new Set([".obsidian", ".vault", ".trash", ".git", "node_modules"]);
|
|
28
29
|
function extractWikilinks(content) {
|
|
@@ -70,7 +71,7 @@ function parseNote(root, absPath) {
|
|
|
70
71
|
const rel = path.relative(root, absPath).split(path.sep).join("/");
|
|
71
72
|
const title = typeof data.title === "string" && data.title || path.basename(absPath, ".md");
|
|
72
73
|
const type = NOTE_TYPES.includes(data.type) ? data.type : "note";
|
|
73
|
-
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;
|
|
74
75
|
const tags = Array.isArray(data.tags) ? data.tags.map(String) : [];
|
|
75
76
|
return {
|
|
76
77
|
rel,
|
|
@@ -80,6 +81,7 @@ function parseNote(root, absPath) {
|
|
|
80
81
|
tags,
|
|
81
82
|
created: isoDate(data.created),
|
|
82
83
|
hits: typeof data.hits === "number" ? data.hits : 1,
|
|
84
|
+
supersededBy: typeof data.superseded_by === "string" ? data.superseded_by : void 0,
|
|
83
85
|
content,
|
|
84
86
|
links: extractWikilinks(content)
|
|
85
87
|
};
|
|
@@ -134,6 +136,18 @@ function setNoteStatus(absPath, status) {
|
|
|
134
136
|
data.updated = (/* @__PURE__ */ new Date()).toISOString();
|
|
135
137
|
fs.writeFileSync(absPath, matter.stringify(content, data));
|
|
136
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
|
+
}
|
|
137
151
|
function touchNote(absPath) {
|
|
138
152
|
const raw = fs.readFileSync(absPath, "utf8");
|
|
139
153
|
const { data, content } = matter(raw);
|
|
@@ -295,7 +309,10 @@ var VaultIndex = class _VaultIndex {
|
|
|
295
309
|
* `withEmbeddings=false` → índice keyword-only (sin cargar modelo).
|
|
296
310
|
*/
|
|
297
311
|
async refresh(withEmbeddings = modelPresent(), force = false) {
|
|
298
|
-
const files = listMarkdownFiles(this.vault.root, [
|
|
312
|
+
const files = listMarkdownFiles(this.vault.root, [
|
|
313
|
+
path2.join(this.vault.managed, "archive"),
|
|
314
|
+
path2.join(this.vault.managed, "docs")
|
|
315
|
+
]);
|
|
299
316
|
const onDisk = /* @__PURE__ */ new Map();
|
|
300
317
|
for (const abs of files) {
|
|
301
318
|
const rel = path2.relative(this.vault.root, abs).split(path2.sep).join("/");
|
|
@@ -346,6 +363,7 @@ var VaultIndex = class _VaultIndex {
|
|
|
346
363
|
title: note.title,
|
|
347
364
|
type: note.type,
|
|
348
365
|
status: note.status,
|
|
366
|
+
supersededBy: note.supersededBy,
|
|
349
367
|
tags: note.tags,
|
|
350
368
|
created: note.created,
|
|
351
369
|
hits: note.hits,
|
|
@@ -400,7 +418,7 @@ ${c.text}`),
|
|
|
400
418
|
if (this.emb !== null) this.clearNeedsRebuild();
|
|
401
419
|
else if (this.meta.chunks.length > 0 && modelPresent()) this.markNeedsRebuild();
|
|
402
420
|
if (!isHookProcess()) try {
|
|
403
|
-
const { writeStaticGraph } = await import("./viewer-
|
|
421
|
+
const { writeStaticGraph } = await import("./viewer-T2SEBP6Z.js");
|
|
404
422
|
writeStaticGraph(this);
|
|
405
423
|
} catch {
|
|
406
424
|
}
|
|
@@ -475,6 +493,35 @@ ${c.text}`),
|
|
|
475
493
|
}
|
|
476
494
|
return (this._tagIndex.get(key) ?? []).map((rel) => this.meta.notes[rel]).filter(Boolean);
|
|
477
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
|
+
}
|
|
478
525
|
/** Vecinos directos de una nota en el grafo (sin releer archivos). */
|
|
479
526
|
neighbors(rel) {
|
|
480
527
|
const out = [];
|
|
@@ -493,6 +540,7 @@ export {
|
|
|
493
540
|
isoDate,
|
|
494
541
|
createNote,
|
|
495
542
|
setNoteStatus,
|
|
543
|
+
supersedeNote,
|
|
496
544
|
touchNote,
|
|
497
545
|
upsertNote,
|
|
498
546
|
appendToNote,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
VaultIndex
|
|
4
|
-
} from "./chunk-
|
|
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
|
+
};
|