@ureck/alexandria 1.3.3 → 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.
@@ -147,6 +147,12 @@ 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: "clean.auto",
153
+ label: "Limpieza autom\xE1tica semanal",
154
+ 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",
155
+ impact: "no gasta tokens; baja el \xEDndice y el ruido en la b\xFAsqueda (mejor contexto por prompt)"
150
156
  }
151
157
  ];
152
158
  function writeProjectConfig(projectDir, vaultPath) {
@@ -157,6 +163,121 @@ function writeProjectConfig(projectDir, vaultPath) {
157
163
  return file;
158
164
  }
159
165
 
166
+ // src/core/stats.ts
167
+ import fs2 from "fs";
168
+ import path2 from "path";
169
+ var charsToTokens = (chars) => Math.round(chars / 4);
170
+ function logInjection(vault, line) {
171
+ try {
172
+ fs2.mkdirSync(vault.cache, { recursive: true });
173
+ fs2.appendFileSync(
174
+ path2.join(vault.cache, "stats.jsonl"),
175
+ JSON.stringify({ t: (/* @__PURE__ */ new Date()).toISOString(), ...line }) + "\n"
176
+ );
177
+ } catch {
178
+ }
179
+ }
180
+ var EST_LOW = 3;
181
+ var EST_HIGH = 8;
182
+ function readStats(vault) {
183
+ const file = path2.join(vault.cache, "stats.jsonl");
184
+ const summary = {
185
+ injections: 0,
186
+ solutionCacheHits: 0,
187
+ injectedTokens: 0,
188
+ cacheHitTokens: 0,
189
+ estSavedLow: 0,
190
+ estSavedHigh: 0
191
+ };
192
+ try {
193
+ for (const raw of fs2.readFileSync(file, "utf8").split("\n")) {
194
+ if (!raw.trim()) continue;
195
+ try {
196
+ const line = JSON.parse(raw);
197
+ const n = line.count ?? 1;
198
+ summary.injections += n;
199
+ const tk = line.tokens ?? charsToTokens(line.injectedChars);
200
+ summary.injectedTokens += tk;
201
+ if (line.kind === "solution-cache") {
202
+ summary.solutionCacheHits += n;
203
+ summary.cacheHitTokens += tk;
204
+ }
205
+ } catch {
206
+ }
207
+ }
208
+ } catch {
209
+ }
210
+ summary.estSavedLow = summary.injectedTokens * EST_LOW;
211
+ summary.estSavedHigh = summary.injectedTokens * EST_HIGH;
212
+ return summary;
213
+ }
214
+
215
+ // src/hooks/adapters.ts
216
+ var HARNESSES = ["claude", "codex", "gemini", "cursor", "opencode"];
217
+ function currentHarness(argv = process.argv) {
218
+ const arg = argv.find((a) => a.startsWith("--harness="))?.slice("--harness=".length);
219
+ return HARNESSES.includes(arg ?? "") ? arg : "claude";
220
+ }
221
+ function normalizeInput(raw) {
222
+ const event = raw.hook_event_name ?? "";
223
+ return {
224
+ session_id: raw.session_id ?? raw.conversation_id,
225
+ transcript_path: raw.transcript_path ?? void 0,
226
+ cwd: raw.cwd ?? raw.workspace_roots?.[0],
227
+ prompt: raw.prompt,
228
+ answer: raw.last_assistant_message ?? raw.prompt_response ?? raw.text,
229
+ compact: /^(PreCompact|PreCompress|preCompact)$/.test(event) || Boolean(raw.trigger)
230
+ };
231
+ }
232
+ function formatContext(harness, kind, text) {
233
+ switch (harness) {
234
+ case "claude":
235
+ case "opencode":
236
+ return text;
237
+ case "codex":
238
+ return JSON.stringify({
239
+ hookSpecificOutput: { hookEventName: kind === "session" ? "SessionStart" : "UserPromptSubmit", additionalContext: text }
240
+ });
241
+ case "gemini":
242
+ return JSON.stringify({
243
+ hookSpecificOutput: { hookEventName: kind === "session" ? "SessionStart" : "BeforeAgent", additionalContext: text }
244
+ });
245
+ case "cursor":
246
+ return kind === "session" ? JSON.stringify({ additional_context: text }) : null;
247
+ }
248
+ }
249
+ function defaultOutput(harness, kind) {
250
+ if (harness === "cursor" && kind === "prompt") return JSON.stringify({ continue: true });
251
+ return null;
252
+ }
253
+ var TEXT_PARTS = /* @__PURE__ */ new Set(["text", "input_text", "output_text"]);
254
+ function textOf(content) {
255
+ if (typeof content === "string") return content;
256
+ if (!Array.isArray(content)) return "";
257
+ return content.filter((p) => TEXT_PARTS.has(p?.type) && typeof p?.text === "string").map((p) => p.text).join("\n");
258
+ }
259
+ function lastExchange(lines) {
260
+ let user = "";
261
+ let assistant = "";
262
+ for (const line of lines) {
263
+ let msg;
264
+ try {
265
+ msg = JSON.parse(line);
266
+ } catch {
267
+ continue;
268
+ }
269
+ const role = msg.message?.role ?? msg.payload?.role ?? msg.role ?? msg.type;
270
+ const text = textOf(msg.message?.content ?? msg.payload?.content ?? msg.content).trim();
271
+ if (!text) continue;
272
+ if (role === "user" && !text.startsWith("<")) user = text;
273
+ if (role === "assistant") assistant = text;
274
+ }
275
+ return { user, assistant };
276
+ }
277
+ function isHarnessInjected(prompt) {
278
+ return /^<(task-notification|system-reminder|command-|local-command|user-prompt-submit-hook|ide_)/i.test(prompt.trim());
279
+ }
280
+
160
281
  export {
161
282
  globalConfigPath,
162
283
  defaultVaultPath,
@@ -170,5 +291,14 @@ export {
170
291
  toggleEnabled,
171
292
  initScopeWarning,
172
293
  TOKEN_TOGGLES,
173
- writeProjectConfig
294
+ writeProjectConfig,
295
+ charsToTokens,
296
+ logInjection,
297
+ readStats,
298
+ currentHarness,
299
+ normalizeInput,
300
+ formatContext,
301
+ defaultOutput,
302
+ lastExchange,
303
+ isHarnessInjected
174
304
  };
@@ -1,4 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ currentHarness,
4
+ defaultOutput,
5
+ formatContext,
6
+ normalizeInput
7
+ } from "./chunk-MDGFK6UC.js";
2
8
 
3
9
  // src/hooks/util.ts
4
10
  import fs from "fs";
@@ -16,6 +22,15 @@ async function readStdinJson() {
16
22
  }
17
23
  }
18
24
  var expired = false;
25
+ var emitted = false;
26
+ function emitContext(kind, text) {
27
+ if (expired) return 0;
28
+ const out = formatContext(currentHarness(), kind, text);
29
+ if (out === null) return 0;
30
+ process.stdout.write(out);
31
+ emitted = true;
32
+ return text.length;
33
+ }
19
34
  function logHookError(kind, detail) {
20
35
  try {
21
36
  const dir = process.platform === "win32" && process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "alexandria") : path.join(os.homedir(), ".cache", "alexandria");
@@ -30,7 +45,7 @@ function logHookError(kind, detail) {
30
45
  } catch {
31
46
  }
32
47
  }
33
- function runHook(budgetMs, body) {
48
+ function runHook(budgetMs, body, kind = "stop") {
34
49
  process.env.ALEXANDRIA_HOOK = "1";
35
50
  const cleanup = async () => {
36
51
  try {
@@ -46,11 +61,13 @@ function runHook(budgetMs, body) {
46
61
  }, budgetMs);
47
62
  timer.unref();
48
63
  process.exitCode = 0;
49
- readStdinJson().then((input) => body(input)).catch((e) => {
64
+ readStdinJson().then((raw) => body(normalizeInput(raw))).catch((e) => {
50
65
  logHookError("error", e instanceof Error ? `${e.message}
51
66
  ${e.stack ?? ""}` : String(e));
52
67
  }).finally(() => {
53
68
  clearTimeout(timer);
69
+ const fallback = emitted ? null : defaultOutput(currentHarness(), kind);
70
+ if (fallback) process.stdout.write(fallback);
54
71
  void cleanup();
55
72
  });
56
73
  }
@@ -63,6 +80,7 @@ function truncate(text, max) {
63
80
  }
64
81
 
65
82
  export {
83
+ emitContext,
66
84
  runHook,
67
85
  projectName,
68
86
  truncate