@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.
@@ -99,6 +99,12 @@ function toggleEnabled(key) {
99
99
  const v = getConfigKey(key);
100
100
  return v !== false && v !== "false";
101
101
  }
102
+ function initScopeWarning(opts) {
103
+ if (opts.project || opts.global) return null;
104
+ return `\u26A0 No se indic\xF3 --project ni --global: este vault se comparte con TODAS tus sesiones (~/Alexandria).
105
+ Si quer\xEDas un vault aislado SOLO para este proyecto: Ctrl+C y corre \`ale init --project\` en su lugar.
106
+ `;
107
+ }
102
108
  var TOKEN_TOGGLES = [
103
109
  {
104
110
  key: "protocol",
@@ -141,6 +147,12 @@ var TOKEN_TOGGLES = [
141
147
  label: "Reparar el \xEDndice al cerrar sesi\xF3n",
142
148
  desc: "Si el \xEDndice qued\xF3 sin vectores, reconstruirlo en segundo plano al terminar la sesi\xF3n",
143
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)"
144
156
  }
145
157
  ];
146
158
  function writeProjectConfig(projectDir, vaultPath) {
@@ -151,6 +163,121 @@ function writeProjectConfig(projectDir, vaultPath) {
151
163
  return file;
152
164
  }
153
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
+
154
281
  export {
155
282
  globalConfigPath,
156
283
  defaultVaultPath,
@@ -162,6 +289,16 @@ export {
162
289
  setConfigKey,
163
290
  protocolEnabled,
164
291
  toggleEnabled,
292
+ initScopeWarning,
165
293
  TOKEN_TOGGLES,
166
- writeProjectConfig
294
+ writeProjectConfig,
295
+ charsToTokens,
296
+ logInjection,
297
+ readStats,
298
+ currentHarness,
299
+ normalizeInput,
300
+ formatContext,
301
+ defaultOutput,
302
+ lastExchange,
303
+ isHarnessInjected
167
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