@ureck/alexandria 1.5.0 → 1.6.1

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.
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ isoDate,
4
+ supersedeNote
5
+ } from "./chunk-44QPE5IM.js";
2
6
  import {
3
7
  charsToTokens
4
- } from "./chunk-POA77JSS.js";
8
+ } from "./chunk-X4V6SYYA.js";
5
9
  import {
6
10
  isHarnessInjected
7
- } from "./chunk-CEHNXDUE.js";
8
- import {
9
- isoDate
10
- } from "./chunk-BV2KJV5W.js";
11
+ } from "./chunk-YICWI3U3.js";
11
12
  import {
12
13
  MODEL_ID,
14
+ dot,
13
15
  modelCacheDir
14
16
  } from "./chunk-EDYBSJSS.js";
15
17
 
@@ -19,6 +21,8 @@ import path from "path";
19
21
  import matter from "gray-matter";
20
22
  var ARCHIVE_DIR = "archive";
21
23
  var STATS_KEEP_DAYS = 90;
24
+ var DUPLICATE_COSINE = 0.96;
25
+ var DEDUPE_TYPES = ["lesson", "note", "solution"];
22
26
  function archiveRoot(vault) {
23
27
  return path.join(vault.managed, ARCHIVE_DIR);
24
28
  }
@@ -100,7 +104,30 @@ function planClean(vault, notes, opts) {
100
104
  }
101
105
  } catch {
102
106
  }
103
- return { bundles, noise, tmpFiles, staleModels, statsLinesToRotate: oldStatsLines(vault).length };
107
+ return { bundles, noise, tmpFiles, staleModels, statsLinesToRotate: oldStatsLines(vault).length, duplicates: findDuplicates(opts) };
108
+ }
109
+ function findDuplicates(opts) {
110
+ if (opts.dedupe === false || !opts.idx) return [];
111
+ const vecs = opts.idx.noteVectors(DEDUPE_TYPES);
112
+ const rels = [...vecs.keys()];
113
+ const used = /* @__PURE__ */ new Set();
114
+ const out = [];
115
+ for (let i = 0; i < rels.length; i++) {
116
+ for (let j = i + 1; j < rels.length; j++) {
117
+ const a = rels[i];
118
+ const b = rels[j];
119
+ if (used.has(a) || used.has(b)) continue;
120
+ const na = opts.idx.meta.notes[a];
121
+ const nb = opts.idx.meta.notes[b];
122
+ if (!na || !nb || na.type !== nb.type) continue;
123
+ const cos = dot(vecs.get(a), vecs.get(b));
124
+ if (cos < DUPLICATE_COSINE) continue;
125
+ const [older, newer] = (na.created ?? "") <= (nb.created ?? "") ? [na, nb] : [nb, na];
126
+ out.push({ older, newer, cos: Math.round(cos * 1e3) / 1e3 });
127
+ used.add(older.rel);
128
+ }
129
+ }
130
+ return out;
104
131
  }
105
132
  function oldStatsLines(vault) {
106
133
  const cutoff = Date.now() - STATS_KEEP_DAYS * 864e5;
@@ -108,7 +135,7 @@ function oldStatsLines(vault) {
108
135
  return fs.readFileSync(path.join(vault.cache, "stats.jsonl"), "utf8").split("\n").filter((l) => {
109
136
  try {
110
137
  const o = JSON.parse(l);
111
- return o.t !== "summary" && o.kind !== "doc" && Date.parse(o.t ?? "") < cutoff;
138
+ return o.t !== "summary" && ["inject", "session-start", "solution-cache"].includes(o.kind ?? "inject") && Date.parse(o.t ?? "") < cutoff;
112
139
  } catch {
113
140
  return false;
114
141
  }
@@ -128,8 +155,8 @@ function section(n, text) {
128
155
  ${text}
129
156
  `;
130
157
  }
131
- function applyClean(vault, plan) {
132
- const res = { compacted: 0, dropped: 0, bundlesWritten: 0, removedDerived: 0, bytesFreed: 0 };
158
+ function applyClean(vault, plan, opts = {}) {
159
+ const res = { compacted: 0, dropped: 0, bundlesWritten: 0, removedDerived: 0, bytesFreed: 0, superseded: 0 };
133
160
  for (const [key, list] of plan.bundles) {
134
161
  const [proj, month] = key.split("/");
135
162
  const file = path.join(archiveRoot(vault), proj, `${month}.md`);
@@ -171,6 +198,13 @@ Proyecto: [[Mapa - ${proj}]]
171
198
  fs.rmSync(p, { recursive: true, force: true });
172
199
  res.removedDerived++;
173
200
  }
201
+ for (const d of opts.applyDuplicates ? plan.duplicates : []) {
202
+ try {
203
+ supersedeNote(path.join(vault.root, d.older.rel), d.newer.title);
204
+ res.superseded++;
205
+ } catch {
206
+ }
207
+ }
174
208
  rotateStats(vault);
175
209
  return res;
176
210
  }
@@ -4,7 +4,7 @@ import {
4
4
  defaultOutput,
5
5
  formatContext,
6
6
  normalizeInput
7
- } from "./chunk-CEHNXDUE.js";
7
+ } from "./chunk-YICWI3U3.js";
8
8
 
9
9
  // src/hooks/util.ts
10
10
  import fs from "fs";
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/stats.ts
4
+ import fs from "fs";
5
+ import path from "path";
6
+ var charsToTokens = (chars) => Math.round(chars / 4);
7
+ function logInjection(vault, line) {
8
+ try {
9
+ fs.mkdirSync(vault.cache, { recursive: true });
10
+ fs.appendFileSync(
11
+ path.join(vault.cache, "stats.jsonl"),
12
+ JSON.stringify({ t: (/* @__PURE__ */ new Date()).toISOString(), ...line }) + "\n"
13
+ );
14
+ } catch {
15
+ }
16
+ }
17
+ function logDocUse(vault, line) {
18
+ try {
19
+ fs.mkdirSync(vault.cache, { recursive: true });
20
+ fs.appendFileSync(path.join(vault.cache, "stats.jsonl"), JSON.stringify({ t: (/* @__PURE__ */ new Date()).toISOString(), kind: "doc", ...line }) + "\n");
21
+ } catch {
22
+ }
23
+ }
24
+ function logFold(vault, line) {
25
+ try {
26
+ fs.mkdirSync(vault.cache, { recursive: true });
27
+ fs.appendFileSync(path.join(vault.cache, "stats.jsonl"), JSON.stringify({ t: (/* @__PURE__ */ new Date()).toISOString(), kind: "fold", ...line }) + "\n");
28
+ } catch {
29
+ }
30
+ }
31
+ var EST_LOW = 3;
32
+ var EST_HIGH = 8;
33
+ function readStats(vault) {
34
+ const file = path.join(vault.cache, "stats.jsonl");
35
+ const summary = {
36
+ injections: 0,
37
+ solutionCacheHits: 0,
38
+ injectedTokens: 0,
39
+ cacheHitTokens: 0,
40
+ estSavedLow: 0,
41
+ estSavedHigh: 0,
42
+ docIngests: 0,
43
+ docReads: 0,
44
+ docTokensOriginal: 0,
45
+ docTokensServed: 0,
46
+ folds: 0,
47
+ foldTokensOriginal: 0,
48
+ foldTokensServed: 0,
49
+ dedupSavedTokens: 0
50
+ };
51
+ try {
52
+ for (const raw of fs.readFileSync(file, "utf8").split("\n")) {
53
+ if (!raw.trim()) continue;
54
+ try {
55
+ const line = JSON.parse(raw);
56
+ if (line.kind === "fold") {
57
+ const f = line;
58
+ summary.folds++;
59
+ summary.foldTokensOriginal += charsToTokens(f.originalChars ?? 0);
60
+ summary.foldTokensServed += charsToTokens(f.servedChars ?? 0);
61
+ continue;
62
+ }
63
+ if (line.kind === "doc") {
64
+ const d = line;
65
+ if (d.op === "ingest") summary.docIngests++;
66
+ else summary.docReads++;
67
+ summary.docTokensOriginal += d.tokensOriginal ?? 0;
68
+ summary.docTokensServed += d.tokensServed ?? 0;
69
+ continue;
70
+ }
71
+ const n = line.count ?? 1;
72
+ if (line.dedupSkippedChars) summary.dedupSavedTokens += charsToTokens(line.dedupSkippedChars);
73
+ summary.injections += n;
74
+ const tk = line.tokens ?? charsToTokens(line.injectedChars);
75
+ summary.injectedTokens += tk;
76
+ if (line.kind === "solution-cache") {
77
+ summary.solutionCacheHits += n;
78
+ summary.cacheHitTokens += tk;
79
+ }
80
+ } catch {
81
+ }
82
+ }
83
+ } catch {
84
+ }
85
+ summary.estSavedLow = summary.injectedTokens * EST_LOW;
86
+ summary.estSavedHigh = summary.injectedTokens * EST_HIGH;
87
+ return summary;
88
+ }
89
+ function readSessionUsage(vault) {
90
+ const by = /* @__PURE__ */ new Map();
91
+ let raw = "";
92
+ try {
93
+ raw = fs.readFileSync(path.join(vault.cache, "stats.jsonl"), "utf8");
94
+ } catch {
95
+ return [];
96
+ }
97
+ for (const l of raw.split("\n")) {
98
+ if (!l.trim()) continue;
99
+ let o;
100
+ try {
101
+ o = JSON.parse(l);
102
+ } catch {
103
+ continue;
104
+ }
105
+ if (!o.session || o.t === "summary") continue;
106
+ const u = by.get(o.session) ?? { session: o.session, first: o.t ?? "", last: o.t ?? "", injections: 0, injectedTokens: 0, dedupSavedTokens: 0, folds: 0, foldTokensOriginal: 0, foldTokensServed: 0, topNotes: [], notes: /* @__PURE__ */ new Map() };
107
+ if (o.t && o.t < u.first) u.first = o.t;
108
+ if (o.t && o.t > u.last) u.last = o.t;
109
+ if (o.kind === "fold") {
110
+ u.folds++;
111
+ u.foldTokensOriginal += charsToTokens(o.originalChars ?? 0);
112
+ u.foldTokensServed += charsToTokens(o.servedChars ?? 0);
113
+ } else if (o.kind !== "doc") {
114
+ u.injections++;
115
+ u.injectedTokens += charsToTokens(o.injectedChars ?? 0);
116
+ u.dedupSavedTokens += charsToTokens(o.dedupSkippedChars ?? 0);
117
+ for (const r of o.rels ?? []) u.notes.set(r, (u.notes.get(r) ?? 0) + 1);
118
+ }
119
+ by.set(o.session, u);
120
+ }
121
+ return [...by.values()].map(({ notes, ...u }) => ({ ...u, topNotes: [...notes].sort((a, b) => b[1] - a[1]).slice(0, 5) })).sort((a, b) => b.last.localeCompare(a.last));
122
+ }
123
+
124
+ export {
125
+ charsToTokens,
126
+ logInjection,
127
+ logDocUse,
128
+ logFold,
129
+ readStats,
130
+ readSessionUsage
131
+ };
@@ -154,6 +154,18 @@ var TOKEN_TOGGLES = [
154
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
155
  impact: "ahorra ~2,000 tokens por p\xE1gina de PDF; desact\xEDvalo si sueles necesitar ver im\xE1genes/gr\xE1ficas"
156
156
  },
157
+ {
158
+ key: "run.fold",
159
+ label: "Plegar salida grande de comandos",
160
+ desc: "Builds/tests/installs/logs largos: el agente recibe errores + resumen + final; la salida completa queda en disco (ale run show)",
161
+ impact: "ahorra la mayor parte de un build o test suite (miles de tokens por corrida); desact\xEDvalo si quieres ver siempre todo"
162
+ },
163
+ {
164
+ key: "context.dedupe",
165
+ label: "No reinyectar lo ya inyectado",
166
+ desc: "Si una nota ya se inyect\xF3 en esta sesi\xF3n, se manda una referencia de 1 l\xEDnea en vez del extracto completo",
167
+ impact: "ahorra hasta ~1500 tokens por prompt en conversaciones largas sobre el mismo tema"
168
+ },
157
169
  {
158
170
  key: "clean.auto",
159
171
  label: "Limpieza autom\xE1tica semanal",
@@ -185,7 +197,11 @@ function normalizeInput(raw) {
185
197
  answer: raw.last_assistant_message ?? raw.prompt_response ?? raw.text,
186
198
  compact: /^(PreCompact|PreCompress|preCompact)$/.test(event) || Boolean(raw.trigger),
187
199
  toolName: raw.tool_name,
188
- filePath: raw.tool_input?.file_path
200
+ filePath: raw.tool_input?.file_path,
201
+ command: typeof raw.tool_input?.command === "string" ? raw.tool_input.command : void 0,
202
+ toolResponse: raw.tool_response,
203
+ durationMs: raw.duration_ms,
204
+ source: raw.source
189
205
  };
190
206
  }
191
207
  function formatContext(harness, kind, text) {
@@ -234,7 +250,9 @@ function lastExchange(lines) {
234
250
  return { user, assistant };
235
251
  }
236
252
  function isHarnessInjected(prompt) {
237
- return /^<(task-notification|system-reminder|command-|local-command|user-prompt-submit-hook|ide_)/i.test(prompt.trim());
253
+ const p = prompt.trim();
254
+ return /^<(task-notification|system-reminder|command-|local-command|user-prompt-submit-hook|ide_)/i.test(p) || // mensajes que el arnés escribe como si fueran del usuario
255
+ /^(Tool loaded\.|Your response above was cut off|This session is being continued from a previous conversation|\[Request interrupted|Caveat: The messages below were generated)/i.test(p);
238
256
  }
239
257
 
240
258
  export {