@gamaze/hicortex 0.15.3 → 0.16.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.
package/dist/index.js CHANGED
@@ -163,10 +163,11 @@ async function buildLessonsBlock(project) {
163
163
  if (selected.length === 0)
164
164
  return null;
165
165
  const formatted = selected.map((l) => {
166
- const titleMatch = l.content.match(/## Lesson: (.+)/);
167
166
  const typeMatch = l.content.match(/\*\*Type:\*\* (\w+)/);
168
167
  const severityMatch = l.content.match(/\*\*Severity:\*\* (\w+)/);
169
- const title = titleMatch ? titleMatch[1] : l.content.slice(0, 150);
168
+ // First line, with any legacy `## Lesson:` prefix stripped — new lessons
169
+ // are stored topic-first without the prefix (memory_type carries the type).
170
+ const title = l.content.replace(/^##\s*Lesson:\s*/i, "").split("\n")[0].slice(0, 150);
170
171
  const meta = [severityMatch?.[1], typeMatch?.[1]].filter(Boolean).join(", ");
171
172
  return `- ${title}${meta ? ` (${meta})` : ""}`;
172
173
  });
@@ -184,7 +185,7 @@ async function buildLessonsBlock(project) {
184
185
  * plugin sends every turn and carries no tuning constants. A 404 flips the
185
186
  * module-level guard so an old server is probed once per gateway process.
186
187
  */
187
- async function fetchRecallIndexBlock(sessionId, prompt) {
188
+ async function fetchRecallIndexBlock(sessionId, prompt, project) {
188
189
  if (recallIndexLatched())
189
190
  return null;
190
191
  if (!sessionId || !prompt) {
@@ -201,7 +202,16 @@ async function fetchRecallIndexBlock(sessionId, prompt) {
201
202
  }
202
203
  return null;
203
204
  }
204
- const { ok, status, data } = await serverPost("/recall-index", { session_id: sessionId, prompt }, RECALL_TIMEOUT_MS);
205
+ // #203 scope: send the gateway-supplied project so retrieval can apply a soft
206
+ // project-affinity boost (no hard filter — "no hard filters in brains").
207
+ // Absent ⇒ no scope sent ⇒ no-op (preserves pre-#203 behavior).
208
+ const body = {
209
+ session_id: sessionId,
210
+ prompt,
211
+ };
212
+ if (project)
213
+ body.project = project;
214
+ const { ok, status, data } = await serverPost("/recall-index", body, RECALL_TIMEOUT_MS);
205
215
  if (status === 404) {
206
216
  recallIndexRetryAtMs = Date.now() + RECALL_REPROBE_INTERVAL_MS;
207
217
  return null;
@@ -317,7 +327,7 @@ exports.default = {
317
327
  const [contextBlock, lessonsBlock, recallBlock] = await Promise.all([
318
328
  fetchOcContextBlock(agentId).catch(() => null),
319
329
  buildLessonsBlock(ctx?.project).catch(() => null),
320
- fetchRecallIndexBlock(ctx?.sessionId, event?.prompt).catch(() => null),
330
+ fetchRecallIndexBlock(ctx?.sessionId, event?.prompt, ctx?.project).catch(() => null),
321
331
  ]);
322
332
  const blocks = [contextBlock, lessonsBlock, recallBlock].filter((b) => b !== null && b !== "");
323
333
  if (blocks.length === 0)
@@ -378,7 +388,7 @@ exports.default = {
378
388
  }), { name: "hicortex_search" });
379
389
  api.registerTool((_ctx) => ({
380
390
  name: "hicortex_get",
381
- description: "Fetch ONE memory's full content by id — use this to lazy-load entries from the '## Memory recall (auto)' index or from search results whose snippet was not enough. Fetching a memory marks it as used (strengthens it), so fetch entries that could change your action — not every shown one. When the memory shapes your answer, cite it as given in the response.",
391
+ description: "Fetch ONE memory's full content by id — use this to lazy-load entries from the '## Memory recall (auto)' index or from search results whose snippet was not enough. Fetching a memory marks it as used (strengthens it), so fetch entries that could change your action — not every shown one. When the memory shapes your answer, cite it as given in the response — mark a fetched memory `FETCHED` and a one-line entry cited unread `SNIPPET`; don't pass SNIPPET off as established.",
382
392
  parameters: {
383
393
  type: "object",
384
394
  properties: {
package/dist/init.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * - Register MCP server in CC settings
14
14
  * - Install CC SessionStart hook for query-time lessons
15
15
  * - Strip old static CLAUDE.md learnings block if present
16
- * - Install CC custom commands (/learn, /hicortex-activate)
16
+ * - Remove legacy pre-0.10 CC commands (/learn, /hicortex-activate) if present
17
17
  */
18
18
  import type { DomainDef } from "./types.js";
19
19
  /**
package/dist/init.js CHANGED
@@ -14,7 +14,7 @@
14
14
  * - Register MCP server in CC settings
15
15
  * - Install CC SessionStart hook for query-time lessons
16
16
  * - Strip old static CLAUDE.md learnings block if present
17
- * - Install CC custom commands (/learn, /hicortex-activate)
17
+ * - Remove legacy pre-0.10 CC commands (/learn, /hicortex-activate) if present
18
18
  */
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.GENERIC_DEFAULT_DOMAINS = void 0;
@@ -255,98 +255,50 @@ function allowHicortexTools() {
255
255
  console.log(` ✓ Added Hicortex tool permissions to ${CC_SETTINGS}`);
256
256
  }
257
257
  }
258
- function installCcCommands() {
259
- (0, node_fs_1.mkdirSync)(CC_COMMANDS_DIR, { recursive: true });
260
- // /learn command
261
- const learnContent = `---
262
- name: learn
263
- description: Save an explicit learning/insight to Hicortex long-term memory. Immediate storage, no nightly wait. Use when you discover something worth remembering across sessions.
264
- argument-hint: <learning to save>
265
- allowed-tools: mcp__hicortex__hicortex_ingest, mcp__hicortex__hicortex_search, mcp__hicortex__hicortex_recent, mcp__hicortex__hicortex_lessons
266
- ---
267
-
268
- # Save Learning to Hicortex
269
-
270
- When invoked with \`/learn <text>\`, store the learning in long-term memory via the Hicortex MCP tool.
271
-
272
- ## Steps
273
-
274
- 1. Parse the text after \`/learn\`
275
- 2. Clean it up into a clear, self-contained statement that will make sense months from now
276
- 3. Include the "why" when relevant
277
- 4. Add today's date for temporal context
278
- 5. Call the \`hicortex_ingest\` tool with:
279
- - \`content\`: The learning text prefixed with "LEARNING: " and suffixed with the date
280
- - \`project\`: "global" (unless clearly project-specific)
281
- - \`memory_type\`: "lesson"
282
- 6. Confirm what was saved (brief, one line)
283
-
284
- ## Example
285
-
286
- \`/learn always check provider docs before assuming an API uses the same auth scheme as OpenAI\`
287
-
288
- Becomes a call to hicortex_ingest with:
289
- - content: "LEARNING: always check provider docs before assuming an API uses the same auth scheme as OpenAI — header names and token formats vary widely (Bearer vs x-api-key vs custom)."
290
- - memory_type: "lesson"
291
- `;
292
- const learnPath = (0, node_path_1.join)(CC_COMMANDS_DIR, "learn.md");
293
- if ((0, node_fs_1.existsSync)(learnPath)) {
294
- // Check if it's ours (contains hicortex_ingest)
295
- const existing = (0, node_fs_1.readFileSync)(learnPath, "utf-8");
296
- if (!existing.includes("hicortex_ingest") && !existing.includes("hicortex")) {
297
- console.log(` ⚠ Skipping /learn — existing command found (not Hicortex). Won't overwrite.`);
258
+ function cleanupLegacyCcCommands() {
259
+ // Pre-0.10 installs wrote two CC slash commands that are now RETIRED:
260
+ // - /learn : manual immediate ingest. Capture has been automatic
261
+ // (nightly-from-logs) since 0.9; hicortex_ingest
262
+ // remains for *explicitly requested* learnings, but
263
+ // no longer warrants a slash command.
264
+ // - /hicortex-activate : registered a commercial license key. licenseKey
265
+ // gates nothing now (the per-install auth TOKEN is
266
+ // the credential, auto-generated at init), so the
267
+ // command is dead.
268
+ // Remove stale copies so upgraders don't keep dead commands. Idempotent —
269
+ // a best-effort cleanup of our own files; never throws.
270
+ for (const name of ["learn.md", "hicortex-activate.md"]) {
271
+ const p = (0, node_path_1.join)(CC_COMMANDS_DIR, name);
272
+ if (!(0, node_fs_1.existsSync)(p))
273
+ continue;
274
+ // Ownership guard: only remove a file we actually wrote. `learn.md` is a
275
+ // generic command name a user may own independently deleting by filename
276
+ // alone would silently destroy their file. The retired writer always
277
+ // embedded "hicortex" (the ingest tool + prose); mirror the same marker the
278
+ // old installer used before overwriting. Skip + warn on anything else.
279
+ try {
280
+ if (!(0, node_fs_1.readFileSync)(p, "utf-8").toLowerCase().includes("hicortex")) {
281
+ console.log(` ⚠ Skipping ${name} in ${CC_COMMANDS_DIR} — not a Hicortex file, left untouched`);
282
+ continue;
283
+ }
298
284
  }
299
- else {
300
- (0, node_fs_1.writeFileSync)(learnPath, learnContent);
285
+ catch {
286
+ // Unreadable — do not delete blind; leave it and move on.
287
+ continue;
288
+ }
289
+ try {
290
+ (0, node_fs_1.rmSync)(p);
291
+ console.log(` ✓ Removed legacy command ${name} from ${CC_COMMANDS_DIR} (retired pre-0.10)`);
292
+ }
293
+ catch (err) {
294
+ // ENOENT = already gone (fine, idempotent). Anything else (EACCES, EBUSY)
295
+ // is worth a line so a stuck stale file is diagnosable — but never fatal
296
+ // to init (best-effort cleanup of our own file).
297
+ if (err?.code !== "ENOENT") {
298
+ console.log(` ⚠ Could not remove legacy command ${name}: ${err?.message ?? err}`);
299
+ }
301
300
  }
302
301
  }
303
- else {
304
- (0, node_fs_1.writeFileSync)(learnPath, learnContent);
305
- }
306
- // /hicortex-activate command — registers a commercial license key for display in status
307
- const activateContent = `---
308
- name: hicortex-activate
309
- description: Register a Hicortex commercial license key. Personal and noncommercial use is free; commercial use requires a per-seat license from hicortex.gamaze.com.
310
- argument-hint: <license-key>
311
- allowed-tools: Bash(mkdir:*), Bash(echo:*), Bash(launchctl:*), Bash(systemctl:*), Bash(curl:*), mcp__hicortex__hicortex_ingest, mcp__hicortex__hicortex_search, mcp__hicortex__hicortex_recent, mcp__hicortex__hicortex_lessons
312
- ---
313
-
314
- # Register Hicortex Commercial License
315
-
316
- ## If key provided (e.g. /hicortex-activate hctx-abc123)
317
-
318
- 1. Write the key to the config file:
319
-
320
- \`\`\`bash
321
- mkdir -p ~/.hicortex
322
- echo '{ "licenseKey": "THE_KEY_HERE" }' > ~/.hicortex/config.json
323
- \`\`\`
324
-
325
- 2. Restart the server to apply:
326
-
327
- On macOS:
328
- \`\`\`bash
329
- launchctl kickstart -k gui/$(id -u)/com.gamaze.hicortex
330
- \`\`\`
331
-
332
- On Linux:
333
- \`\`\`bash
334
- systemctl --user restart hicortex
335
- \`\`\`
336
-
337
- 3. Verify the key is recognised:
338
- \`\`\`bash
339
- hicortex status
340
- \`\`\`
341
-
342
- 4. Tell the user: "Commercial license registered. The license tier will appear in \`hicortex status\`."
343
-
344
- ## If no key provided
345
-
346
- Tell them: "Hicortex is free for personal and noncommercial use. Commercial use requires a per-seat license — see https://hicortex.gamaze.com/. After purchase you will receive a key; pass it here and I'll register it."
347
- `;
348
- (0, node_fs_1.writeFileSync)((0, node_path_1.join)(CC_COMMANDS_DIR, "hicortex-activate.md"), activateContent);
349
- console.log(` ✓ Installed /learn and /hicortex-activate commands in ${CC_COMMANDS_DIR}`);
350
302
  }
351
303
  // ---------------------------------------------------------------------------
352
304
  // Hermes setup
@@ -1211,7 +1163,6 @@ async function runInit(options = {}) {
1211
1163
  actions.push("Register MCP server in CC settings");
1212
1164
  if (d.hermesFound)
1213
1165
  actions.push("Install Hermes plugin + configure");
1214
- actions.push("Install /learn and /hicortex-activate commands");
1215
1166
  actions.push("Install SessionStart hook (query-time lessons)");
1216
1167
  if (actions.length === 0) {
1217
1168
  console.log("Everything is already configured. Nothing to do.");
@@ -1294,8 +1245,8 @@ async function runInit(options = {}) {
1294
1245
  }
1295
1246
  // Ensure tool permissions are set (also needed for users upgrading from older versions)
1296
1247
  allowHicortexTools();
1297
- // Install CC commands
1298
- installCcCommands();
1248
+ // Remove legacy pre-0.10 CC commands (/learn, /hicortex-activate) if present
1249
+ cleanupLegacyCcCommands();
1299
1250
  // Setup Hermes if detected
1300
1251
  if (d.hermesFound) {
1301
1252
  // localhost bypass makes the token optional for co-located installs;
@@ -1325,13 +1276,15 @@ async function runInit(options = {}) {
1325
1276
  // failures are swallowed inside sendLifecycleEvent.
1326
1277
  await (0, telemetry_js_1.sendLifecycleEvent)("install", HICORTEX_HOME, readHomeConfig(HICORTEX_HOME), pkgVersion());
1327
1278
  console.log("Next steps:");
1328
- console.log(" 1. Restart Claude Code to pick up the new MCP server and SessionStart hook");
1279
+ // Counter-based so the list stays contiguous (1,2,3,4) whether or not Hermes
1280
+ // was detected — a conditional middle step used to leave a "1, 3, 4" gap.
1281
+ let step = 1;
1282
+ console.log(` ${step++}. Restart Claude Code to pick up the new MCP server and SessionStart hook`);
1329
1283
  if (d.hermesFound) {
1330
- console.log(" 2. Activate the Hermes plugin: run `hermes memory setup`, select 'hicortex', then restart the gateway(s)");
1284
+ console.log(` ${step++}. Activate the Hermes plugin: run \`hermes memory setup\`, select 'hicortex', then restart the gateway(s)`);
1331
1285
  }
1332
- console.log(" 3. Ask your agent: 'What Hicortex tools do you have?'");
1333
- console.log(" 4. Try /learn to save something to long-term memory");
1334
- console.log(` 5. Check server: curl ${serverUrl}/health`);
1286
+ console.log(` ${step++}. Ask your agent: 'What Hicortex tools do you have?'`);
1287
+ console.log(` ${step++}. Check server: curl ${serverUrl}/health`);
1335
1288
  }
1336
1289
  // ---------------------------------------------------------------------------
1337
1290
  // Client Mode Init
@@ -1470,8 +1423,8 @@ async function runClientInit(serverUrl, agentName) {
1470
1423
  registerCcMcp(serverUrl);
1471
1424
  }
1472
1425
  allowHicortexTools();
1473
- // Step 5: Install CC commands
1474
- installCcCommands();
1426
+ // Step 5: Remove legacy pre-0.10 CC commands if present
1427
+ cleanupLegacyCcCommands();
1475
1428
  // Step 6: Install SessionStart hook for query-time lessons + the #192
1476
1429
  // per-prompt pushed-recall hooks.
1477
1430
  installSessionStartHook();
@@ -90,10 +90,11 @@ async function fetchLessonsBlock(cfg) {
90
90
  const project = (0, node_path_1.basename)(process.cwd()) || null;
91
91
  const selected = await (0, extensions_js_1.getLessonSelector)().select(data.lessons, { maxLessons, moduleIndex, project });
92
92
  const lessonLines = selected.map((l) => {
93
- const titleMatch = l.content.match(/## Lesson: (.+)/);
94
93
  const typeMatch = l.content.match(/\*\*Type:\*\* (\w+)/);
95
94
  const severityMatch = l.content.match(/\*\*Severity:\*\* (\w+)/);
96
- const title = titleMatch ? titleMatch[1] : l.content.slice(0, 150);
95
+ // First line, with any legacy `## Lesson:` prefix stripped — new lessons
96
+ // are stored topic-first without the prefix (memory_type carries the type).
97
+ const title = l.content.replace(/^##\s*Lesson:\s*/i, "").split("\n")[0].slice(0, 150);
97
98
  const meta = [severityMatch?.[1], typeMatch?.[1]].filter(Boolean).join(", ");
98
99
  return `- ${title}${meta ? ` (${meta})` : ""}`;
99
100
  });
package/dist/llm.d.ts CHANGED
@@ -191,8 +191,10 @@ export declare class RateLimitError extends Error {
191
191
  }
192
192
  export declare class LlmClient {
193
193
  private config;
194
- private rateLimitedUntil;
195
194
  constructor(config: LlmConfig);
195
+ /** Endpoint identity for shared rate-limit state (provider + base URL). */
196
+ private get endpointKey();
197
+ private get rateLimitedUntil();
196
198
  /** Check if we're currently rate limited */
197
199
  get isRateLimited(): boolean;
198
200
  private handleRateLimit;
package/dist/llm.js CHANGED
@@ -466,12 +466,25 @@ class RateLimitError extends Error {
466
466
  }
467
467
  }
468
468
  exports.RateLimitError = RateLimitError;
469
+ // Rate-limit backoff is shared across all LlmClient instances that target the
470
+ // same endpoint, keyed by provider@baseUrl. completeWithOverride() spins up a
471
+ // throwaway client per call for the distill/reflect/classify override tiers;
472
+ // with per-instance state each throwaway started un-rate-limited and re-hit a
473
+ // 429'd provider immediately, defeating the backoff on exactly the configs
474
+ // (e.g. z.ai via distillBaseUrl/reflectBaseUrl) that route through those tiers.
475
+ const rateLimitedUntilByEndpoint = new Map();
469
476
  class LlmClient {
470
477
  config;
471
- rateLimitedUntil = 0;
472
478
  constructor(config) {
473
479
  this.config = config;
474
480
  }
481
+ /** Endpoint identity for shared rate-limit state (provider + base URL). */
482
+ get endpointKey() {
483
+ return `${this.config.provider}@${this.config.baseUrl ?? ""}`;
484
+ }
485
+ get rateLimitedUntil() {
486
+ return rateLimitedUntilByEndpoint.get(this.endpointKey) ?? 0;
487
+ }
475
488
  /** Check if we're currently rate limited */
476
489
  get isRateLimited() {
477
490
  return Date.now() < this.rateLimitedUntil;
@@ -482,9 +495,10 @@ class LlmClient {
482
495
  const retryMs = retryAfter
483
496
  ? parseInt(retryAfter, 10) * 1000
484
497
  : DEFAULT_RATE_LIMIT_RETRY_MS;
485
- this.rateLimitedUntil = Date.now() + retryMs;
486
- console.log(`[hicortex] Rate limited by LLM provider. ` +
487
- `Will retry after ${new Date(this.rateLimitedUntil).toISOString()}`);
498
+ const until = Date.now() + retryMs;
499
+ rateLimitedUntilByEndpoint.set(this.endpointKey, until);
500
+ console.log(`[hicortex] Rate limited by LLM provider (${this.endpointKey}). ` +
501
+ `Will retry after ${new Date(until).toISOString()}`);
488
502
  throw new RateLimitError(retryMs);
489
503
  }
490
504
  /**
@@ -128,27 +128,18 @@ function createMcpServer() {
128
128
  }
129
129
  });
130
130
  // -- hicortex_get --
131
- server.tool("hicortex_get", "Fetch ONE memory's full content by id — use this to lazy-load entries from the '## Memory recall (auto)' index or from search results whose snippet was not enough. Fetching a memory marks it as used (strengthens it), so fetch entries that could change your action — not every shown one. When the memory shapes your answer, cite it to the user (id + date + origin agent).", {
131
+ server.tool("hicortex_get", "Fetch ONE memory's full content by id — use this to lazy-load entries from the '## Memory recall (auto)' index or from search results whose snippet was not enough. Fetching a memory marks it as used (strengthens it), so fetch entries that could change your action — not every shown one. When the memory shapes your answer, cite it to the user (id + date + origin agent) — mark a fetched memory `FETCHED` and a one-line entry cited unread `SNIPPET`; don't pass SNIPPET off as established.", {
132
132
  id: zod_1.z.string().describe("Memory id (as shown in recall index/search results)"),
133
133
  }, async ({ id }) => {
134
134
  if (!db)
135
135
  return { content: [{ type: "text", text: "Hicortex not initialized" }], isError: true };
136
+ // Delegates to formatMemoryGetText → handleMemoryGet, so the citation
137
+ // (incl. the #204 FETCHED marker) is built in ONE place shared with the
138
+ // REST GET /memory path. CC reaches Hicortex through THIS MCP tool;
139
+ // before #207's fix it got a marker-less citation built inline here.
136
140
  try {
137
- // Prefix ids resolve (F6): citations show the 8-char id, so this tool
138
- // must accept it like /update and /delete do.
139
- const fullId = storage.resolveMemoryId(db, id);
140
- const mem = fullId ? storage.getMemory(db, fullId) : null;
141
- if (!mem)
142
- return { content: [{ type: "text", text: `No memory with id ${id}` }], isError: true };
143
- // Real use → full strengthen (access_count + hardening + prune shield).
144
- storage.strengthenMemory(db, mem.id, new Date().toISOString());
145
- // Provenance header (built-in citing norm, 0.14.1): id, type, project,
146
- // ORIGIN AGENT (shared brain — the memory may come from another
147
- // agent's session), and date, plus the explicit citation instruction.
148
- const date = (mem.created_at ?? "").slice(0, 10);
149
- const header = `[memory ${mem.id} | ${mem.memory_type ?? "episode"} | ${mem.project ?? "-"} | from ${mem.source_agent ?? "unknown"} | ${date}]\n` +
150
- `Cite as (memory ${String(mem.id).slice(0, 8)}, ${date}) where this shapes your answer; it may be stale — newer memories supersede older.`;
151
- return { content: [{ type: "text", text: `${header}\n\n${mem.content ?? ""}` }] };
141
+ const r = (0, recall_index_js_1.formatMemoryGetText)(db, { id });
142
+ return { content: [{ type: "text", text: r.text }], isError: r.status !== 200 };
152
143
  }
153
144
  catch (err) {
154
145
  return { content: [{ type: "text", text: `Get failed: ${err instanceof Error ? err.message : String(err)}` }], isError: true };
@@ -503,6 +494,7 @@ async function startServer(options = {}) {
503
494
  minSimilarity: savedConfig?.recallMinSimilarity,
504
495
  maxItems: savedConfig?.recallMaxItems,
505
496
  minPromptLength: savedConfig?.recallMinPromptChars,
497
+ titleChars: savedConfig?.recallTitleChars,
506
498
  };
507
499
  memoryInstructionsEnabled = savedConfig?.memoryInstructions !== false;
508
500
  if (resolvedAgents.dropped.length > 0) {
@@ -513,14 +505,24 @@ async function startServer(options = {}) {
513
505
  const app = (0, express_1.default)();
514
506
  // Raise the body limit — whole-session denoised transcripts exceed the 100 kB default.
515
507
  app.use(express_1.default.json({ limit: "25mb" }));
516
- // CORS: must be before auth so preflight OPTIONS requests get proper headers
508
+ // CORS: reflect ONLY explicitly-allowlisted origins (config.corsAllowedOrigins),
509
+ // and never send Access-Control-Allow-Credentials. Reflecting any origin with
510
+ // credentials — combined with the localhost auth bypass and the default 0.0.0.0
511
+ // bind — let any web page the user visits read/mutate the memory store via
512
+ // fetch() to localhost with no token (the browser connects from 127.0.0.1, so
513
+ // the bypass grants access, and the reflected Allow-Origin let the page read the
514
+ // response). The bundled UIs (/viz, /context/ui) are same-origin and need no CORS
515
+ // headers at all; cross-origin access is opt-in per the hosted plan (#110 §2).
516
+ // Must run before auth so allowlisted preflight OPTIONS get their headers.
517
+ const corsAllowedOrigins = Array.isArray(savedConfig?.corsAllowedOrigins)
518
+ ? savedConfig.corsAllowedOrigins.filter((o) => typeof o === "string")
519
+ : [];
517
520
  app.use((req, res, next) => {
518
521
  const origin = req.headers.origin;
519
- if (origin) {
522
+ if (origin && corsAllowedOrigins.includes(origin)) {
520
523
  res.setHeader("Access-Control-Allow-Origin", origin);
521
524
  res.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
522
525
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
523
- res.setHeader("Access-Control-Allow-Credentials", "true");
524
526
  res.setHeader("Vary", "Origin");
525
527
  }
526
528
  if (req.method === "OPTIONS") {
@@ -689,8 +691,11 @@ async function startServer(options = {}) {
689
691
  return retrieval.retrieve(db, embedder_js_1.embed, query, {
690
692
  limit,
691
693
  noStrengthen: true,
694
+ // #203: project + mission_domains are SOFT affinity (zero-boost
695
+ // neutral), threaded into computeScore. privacy stays a hard filter.
692
696
  project: filters?.project,
693
697
  privacy: filters?.privacy,
698
+ missionDomains: filters?.mission_domains,
694
699
  queryEmbedding: queryVec,
695
700
  });
696
701
  },
@@ -33,7 +33,7 @@ function renderMemoryInstructions() {
33
33
  "Your long-term memory is Hicortex — shared across all agents and sessions.",
34
34
  "- A `## Memory recall (auto)` index may arrive with prompts: it is a MENU, not content. Fetch a full memory with `hicortex_get(id)` when the entry could change how you handle the current task.",
35
35
  "- Recall before assuming: `hicortex_search` for prior decisions/facts/preferences, `hicortex_recent` to catch up on a project.",
36
- "- Cite any memory you rely on (id, date); on conflicts, newer memories supersede older.",
36
+ "- Cite any memory you rely on by id + date, and mark it `FETCHED` (you read the full memory via `hicortex_get`) or `SNIPPET` (the one-line entry only). Don't present a SNIPPET citation as established. On conflicts, newer memories supersede older.",
37
37
  "- Capture is automatic (nightly). Do not manually ingest routine content — `hicortex_ingest` is for explicitly requested learnings only.",
38
38
  "- Never inspect, test, or modify memory/plugin/gateway infrastructure (configs, services, tokens). If a memory tool seems missing or broken, say so and stop.",
39
39
  ].join("\n");
package/dist/prompts.js CHANGED
@@ -108,25 +108,39 @@ EXTRACT into this markdown format:
108
108
  ## Classification: [pick one: PUBLIC / WORK / PERSONAL / SENSITIVE]
109
109
 
110
110
  ### Decisions Made
111
- - [decision]: [reasoning] (${date})
111
+ - [SUBJECT]: [decision] — [reasoning] (${date})
112
112
 
113
113
  ### Facts Learned
114
- - [fact]: [context/source] (${date})
114
+ - [SUBJECT]: [fact] — [context/source] (${date})
115
115
 
116
116
  ### Problems & Solutions
117
- - [problem] → [solution that worked] (${date})
117
+ - [SUBJECT]: [problem] → [solution that worked] (${date})
118
118
 
119
119
  ### Project State Changes
120
- - [what changed]: [from → to] (${date})
120
+ - [SUBJECT]: [what changed], [from → to] (${date})
121
121
 
122
122
  ### Key Entities & Relationships
123
123
  - [entity A] → [relationship] → [entity B] (${date})
124
124
 
125
125
  ### Corrections & Rejections
126
- - [what AI proposed] → [why rejected/corrected] → [what user wanted instead] (${date})
126
+ - [SUBJECT]: [what AI proposed] → [why rejected/corrected] → [what user wanted instead] (${date})
127
127
  (Include: tool use denials, "no/wrong/redo", style feedback, approach rejections,
128
128
  user corrections of AI assumptions, quality complaints like "too verbose")
129
129
 
130
+ TOPIC-FIRST RULE (critical — read carefully):
131
+ Every item MUST begin with its [SUBJECT]: the concrete thing it is about — the
132
+ system, file, component, decision area, or entity. The subject is what a future
133
+ reader would search for.
134
+ - Write: "Electrical load calculation: don't bundle unknown loads into one figure — user rejected the estimate"
135
+ - NOT: "User rejected AI's bundling of unknown loads"
136
+ - Write: "Nightly capture (Hermes): cron sessions are excluded — source='cron' is skipped before distillation"
137
+ - NOT: "Discovered that cron sessions are filtered out"
138
+ Reason: each item's first words become the memory's one-line index entry AND
139
+ dominate its search embedding. An item that opens with a category label, a
140
+ sentiment ("Strong Negative"), or "User rejected…" is unfindable — it matches
141
+ every emotionally-similar prompt and no topically-relevant one. Front-load the
142
+ subject; put reaction, intensity and reasoning AFTER it.
143
+
130
144
  RULES:
131
145
  - Extract MAX 20 items total (quality over quantity)
132
146
  - Each must be useful if recalled in a future session
@@ -136,7 +150,9 @@ RULES:
136
150
  - PRIORITIZE Corrections & Rejections — these are high-value signals for learning
137
151
  what the user does NOT want. Even a single "no" or style correction is worth extracting.
138
152
  - Strong language or profanity from the user is a high-intensity signal — it indicates
139
- the correction matters deeply. Note the intensity in the extraction.
153
+ the correction matters deeply. Note the intensity AFTER the subject, never before it
154
+ (e.g. "Pricing tiers: strongly rejected per-agent billing — …", not
155
+ "[Strong Negative] User rejected per-agent billing"). The subject always comes first.
140
156
  - PRIVACY CLASSIFICATION (one of):
141
157
  - PUBLIC: general tech knowledge, open-source patterns, publicly available info
142
158
  - WORK: project-specific decisions, architecture choices, client/business context
@@ -23,6 +23,6 @@ interface HookPayload {
23
23
  * there is nothing to send (no session id, or an unhandled event). Exported
24
24
  * for tests.
25
25
  */
26
- export declare function buildHookRequest(payload: HookPayload): Record<string, unknown> | null;
26
+ export declare function buildHookRequest(payload: HookPayload, cwd?: string): Record<string, unknown> | null;
27
27
  export declare function runRecallHook(): Promise<void>;
28
28
  export {};
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.buildHookRequest = buildHookRequest;
18
18
  exports.runRecallHook = runRecallHook;
19
19
  const lessons_context_js_1 = require("./lessons-context.js");
20
+ const node_path_1 = require("node:path");
20
21
  const FETCH_TIMEOUT_MS = 1000;
21
22
  /** Read all of stdin (CC pipes the hook payload JSON). */
22
23
  async function readStdin() {
@@ -31,7 +32,7 @@ async function readStdin() {
31
32
  * there is nothing to send (no session id, or an unhandled event). Exported
32
33
  * for tests.
33
34
  */
34
- function buildHookRequest(payload) {
35
+ function buildHookRequest(payload, cwd = process.cwd()) {
35
36
  const sessionId = typeof payload.session_id === "string" && payload.session_id
36
37
  ? payload.session_id
37
38
  : null;
@@ -43,7 +44,11 @@ function buildHookRequest(payload) {
43
44
  const prompt = typeof payload.prompt === "string" ? payload.prompt : "";
44
45
  if (!prompt)
45
46
  return null;
46
- return { session_id: sessionId, prompt };
47
+ // #203 scope: derive project from the session cwd so retrieval can apply a
48
+ // soft project-affinity boost. basename(cwd) matches capture's
49
+ // decodeProjectDirName for non-hyphenated dirs (the common case); a hyphen
50
+ // edge case is a pre-existing capture bug, filed separately.
51
+ return { session_id: sessionId, prompt, project: (0, node_path_1.basename)(cwd) };
47
52
  }
48
53
  async function runRecallHook() {
49
54
  const cfg = (0, lessons_context_js_1.resolveConfig)();