@gamaze/hicortex 0.27.1 → 0.27.3

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.
@@ -33,6 +33,19 @@
33
33
  * tool × 9 → the hicortex_* tools as direct REST proxies with
34
34
  * plain-object args (no zod — verified live).
35
35
  *
36
+ * #600: the workspace folder basename IS the agent name. Every read call
37
+ * (the /recall-index body + the /search, /memory,
38
+ * /recent, /learnings, /graph tool queries) carries
39
+ * agent=<sanitized basename of the request's
40
+ * directory> so a rostered workspace reads as a
41
+ * confidential-circle member server-side; a
42
+ * null-sanitizing basename omits the param
43
+ * (fail-closed non-member). The tool executes get no
44
+ * input of their own, so they read the LAST_AGENT the
45
+ * per-prompt hooks resolved (strict rule: only a
46
+ * genuine session directory names the agent — never
47
+ * the process.cwd fallback `project` uses).
48
+ *
36
49
  * Capture is NOT the plugin's job — the nightly reader on the server machine
37
50
  * distills ~/.local/share/opencode/opencode.db centrally
38
51
  * (opencode-transcript-reader).
@@ -274,22 +287,56 @@ function renderLessonsBlock(data: LessonsResponse | null, maxLessons: number): s
274
287
  return parts.join("\n");
275
288
  }
276
289
 
290
+ /**
291
+ * Dependency-free twin of sanitizeAgentId (identity-store.ts): lowercase →
292
+ * collapse every [^a-z0-9_-]+ run to `-` → strip leading `-`/`_` → truncate to
293
+ * 64 → must match the section/agent allowlist `^[a-z0-9][a-z0-9_-]*$` (1..64
294
+ * chars), else null. identity-store.ts is the SOURCE OF TRUTH — keep the two
295
+ * in sync (this file cannot import package code; same duplication precedent
296
+ * as resolveOpencodeConfig).
297
+ */
298
+ function sanitizeAgentId(raw: string): string | null {
299
+ if (typeof raw !== "string") return null;
300
+ const cleaned = raw
301
+ .toLowerCase()
302
+ .replace(/[^a-z0-9_-]+/g, "-")
303
+ .replace(/^[-_]+/, "")
304
+ .slice(0, 64);
305
+ return /^[a-z0-9][a-z0-9_-]*$/.test(cleaned) ? cleaned : null;
306
+ }
307
+
308
+ /**
309
+ * #600: the workspace-scoped agent id sent on every read call — the sanitized
310
+ * basename of the working directory (the same basename `project` is derived
311
+ * from; the folder name IS the agent name). null
312
+ * when the basename sanitizes to nothing → the caller omits `agent` entirely
313
+ * (fail-closed: the request reads as a non-member, never an id the server
314
+ * would 400 on and a fail-soft path would silently swallow).
315
+ */
316
+ function workspaceAgentId(cwd: string): string | null {
317
+ return sanitizeAgentId(basename(cwd ?? ""));
318
+ }
319
+
277
320
  /**
278
321
  * Build the /recall-index request body, or null when there is nothing to
279
322
  * send (no session id, or an empty prompt). Mirrors the CC hook's
280
323
  * buildHookRequest: project = basename(working directory) so retrieval can
281
324
  * apply the soft project-affinity boost (retrieval-scoping: opencode is a
282
- * cwd-based client and must send `project`).
325
+ * cwd-based client and must send `project`), and agent = the sanitized
326
+ * workspace basename threaded by the caller (#600 — from the input's OWN
327
+ * directory via currentAgent, never the process.cwd fallback `project` uses).
283
328
  */
284
329
  function buildRecallBody(
285
330
  sessionId: string,
286
331
  prompt: string,
287
332
  cwd: string,
333
+ agent: string | null,
288
334
  ): Record<string, unknown> | null {
289
335
  if (!sessionId || !prompt) return null;
290
336
  const body: Record<string, unknown> = { session_id: sessionId, prompt };
291
337
  const project = basename(cwd ?? "");
292
338
  if (project) body.project = project;
339
+ if (agent) body.agent = agent;
293
340
  return body;
294
341
  }
295
342
 
@@ -414,6 +461,41 @@ function cwdFromInput(input: unknown): string {
414
461
  return process.cwd();
415
462
  }
416
463
 
464
+ /**
465
+ * #600: the working directory a hook input carries — STRICT (no process.cwd()
466
+ * fallback): only a genuine session directory names the workspace agent; the
467
+ * gateway process's cwd is not a workspace. `project` keeps the looser
468
+ * cwdFromInput fallback above (unchanged behavior).
469
+ */
470
+ function strictCwd(input: unknown): string | null {
471
+ const i = input as { directory?: unknown; cwd?: unknown } | null | undefined;
472
+ if (typeof i?.directory === "string" && i.directory) return i.directory;
473
+ if (typeof i?.cwd === "string" && i.cwd) return i.cwd;
474
+ return null;
475
+ }
476
+
477
+ /**
478
+ * #600: the last workspace agent id a per-prompt hook resolved. The tool
479
+ * executes receive no input of their own, so the five read proxies read this
480
+ * directly. Multi-session gateways interleave — a tool read may carry a
481
+ * sibling session's id; bounded by the trust model (the agent param is
482
+ * self-asserted, the bearer token is the boundary) and it fails toward the
483
+ * standard pool in the common case.
484
+ */
485
+ let LAST_AGENT: string | null = null;
486
+
487
+ /**
488
+ * The workspace agent for a hook input: the sanitized basename of its
489
+ * directory when it carries one (updating LAST_AGENT), else the last-known
490
+ * id — a null-sanitizing basename never overwrites a known id.
491
+ */
492
+ function currentAgent(input: unknown): string | null {
493
+ const cwd = strictCwd(input);
494
+ const id = cwd ? workspaceAgentId(cwd) : null;
495
+ if (id) LAST_AGENT = id;
496
+ return id ?? LAST_AGENT;
497
+ }
498
+
417
499
  /** Best-effort session id from a hook input (shape not stable upstream). */
418
500
  function inputSessionId(input: unknown): string | null {
419
501
  const i = input as { info?: { sessionID?: unknown }; sessionID?: unknown; session?: { id?: unknown } } | null | undefined;
@@ -435,11 +517,15 @@ function inputSessionId(input: unknown): string | null {
435
517
  * request (the OC plugin's #313 memoize-only-on-success rule). Bounded: a
436
518
  * long-lived opencode process accumulating sessions would otherwise grow the
437
519
  * maps forever.
520
+ *
521
+ * #600: the lessons cache stores the agent id the block was fetched UNDER
522
+ * (the lessons pool is member-gated) — see cachedAgentBlock. The identity
523
+ * cache is NOT agent-scoped (identity is global for opencode).
438
524
  */
439
525
  const RECALL_BLOCKS = new Map<string, string | null>();
440
526
  const PROMPT_KEYS = new Map<string, string>();
441
527
  const IDENTITY_BLOCKS = new Map<string, string | null>();
442
- const LESSONS_BLOCKS = new Map<string, string | null>();
528
+ const LESSONS_BLOCKS = new Map<string, { block: string | null; agent: string | null }>();
443
529
  /** In-flight / recently-fired dedup resets, keyed by session id (#316 ordering). */
444
530
  const PENDING_RESETS = new Map<string, Promise<void>>();
445
531
  const SESSION_STATE_CAP = 32;
@@ -482,6 +568,31 @@ async function cachedBlock(
482
568
  }
483
569
  }
484
570
 
571
+ /**
572
+ * #600: the lessons-cache identity guard — memoize the settled render UNDER
573
+ * the agent id it was fetched for. A later request that resolves a DIFFERENT
574
+ * (or newly known) workspace id re-fetches; without this, a system.transform
575
+ * firing before any directory is known would pin a standard-pool lessons
576
+ * block for a member's whole session. Same memoize-only-on-success rule as
577
+ * cachedBlock (a throw degrades to null and retries next request).
578
+ */
579
+ async function cachedAgentBlock(
580
+ cache: Map<string, { block: string | null; agent: string | null }>,
581
+ sessionId: string,
582
+ agent: string | null,
583
+ fetcher: () => Promise<string | null>,
584
+ ): Promise<string | null> {
585
+ const hit = cache.get(sessionId);
586
+ if (hit && hit.agent === agent) return hit.block;
587
+ try {
588
+ const block = await fetcher();
589
+ cache.set(sessionId, { block, agent });
590
+ return block;
591
+ } catch {
592
+ return null;
593
+ }
594
+ }
595
+
485
596
  // ---------------------------------------------------------------------------
486
597
  // Fetchers — every failure path THROWS to the caller's fail-soft catch
487
598
  // ---------------------------------------------------------------------------
@@ -491,8 +602,9 @@ async function fetchRecallBlock(
491
602
  sessionId: string,
492
603
  prompt: string,
493
604
  cwd: string,
605
+ agent: string | null,
494
606
  ): Promise<string | null> {
495
- const body = buildRecallBody(sessionId, prompt, cwd);
607
+ const body = buildRecallBody(sessionId, prompt, cwd, agent);
496
608
  if (!body) return null;
497
609
  const resp = await fetch(`${cfg.serverUrl}/recall-index`, {
498
610
  method: "POST",
@@ -517,11 +629,19 @@ async function fetchIdentityBlock(cfg: OpencodeConfig): Promise<string | null> {
517
629
  return gateAndRenderIdentity(await resp.json() as IdentityResponse);
518
630
  }
519
631
 
520
- async function fetchLessonsBlock(cfg: OpencodeConfig): Promise<string | null> {
521
- const resp = await fetch(`${cfg.serverUrl}/learnings`, {
522
- headers: authHeaders(cfg),
523
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
524
- });
632
+ /**
633
+ * #600: `agent` is the session's workspace id — the lessons pool is
634
+ * member-gated server-side, so the block must be fetched under the id it
635
+ * will be cached under (see cachedAgentBlock). null → bare /learnings.
636
+ */
637
+ async function fetchLessonsBlock(cfg: OpencodeConfig, agent: string | null): Promise<string | null> {
638
+ const resp = await fetch(
639
+ agent ? `${cfg.serverUrl}/learnings?agent=${encodeURIComponent(agent)}` : `${cfg.serverUrl}/learnings`,
640
+ {
641
+ headers: authHeaders(cfg),
642
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
643
+ },
644
+ );
525
645
  if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
526
646
  const block = renderLessonsBlock(await resp.json() as LessonsResponse, cfg.lessonsLimit);
527
647
  return block === null ? null : block;
@@ -665,6 +785,7 @@ function registerTools(): Record<string, unknown> {
665
785
  const params = new URLSearchParams({ query: String(args?.query ?? "") });
666
786
  if (args?.limit) params.set("limit", String(args.limit));
667
787
  if (args?.project) params.set("project", String(args.project));
788
+ if (LAST_AGENT) params.set("agent", LAST_AGENT);
668
789
  const { data, status } = await serverGet(cfg, `/search?${params}`);
669
790
  if (!data) return errorResult(`Search failed: ${describeGetFailure(status)}`);
670
791
  return formatSearchResults(data.results ?? []);
@@ -686,6 +807,7 @@ function registerTools(): Record<string, unknown> {
686
807
  const cfg = resolveOpencodeConfig();
687
808
  if (!cfg) return errorResult(NOT_CONFIGURED);
688
809
  const params = new URLSearchParams({ id: String(args.id) });
810
+ if (LAST_AGENT) params.set("agent", LAST_AGENT);
689
811
  const { data, status } = await serverGet(cfg, `/memory?${params}`);
690
812
  if (status === 404) {
691
813
  // Either no such memory (0.14+) or a pre-0.14 server with no
@@ -716,6 +838,7 @@ function registerTools(): Record<string, unknown> {
716
838
  const params = new URLSearchParams();
717
839
  if (args?.project) params.set("project", String(args.project));
718
840
  if (args?.limit) params.set("limit", String(args.limit));
841
+ if (LAST_AGENT) params.set("agent", LAST_AGENT);
719
842
  const qs = params.toString();
720
843
  const { data, status } = await serverGet(cfg, `/recent${qs ? `?${qs}` : ""}`);
721
844
  if (!data) return errorResult(`Recent recall failed: ${describeGetFailure(status)}`);
@@ -770,7 +893,10 @@ function registerTools(): Record<string, unknown> {
770
893
  try {
771
894
  const cfg = resolveOpencodeConfig();
772
895
  if (!cfg) return errorResult(NOT_CONFIGURED);
773
- const { data, status } = await serverGet(cfg, "/learnings");
896
+ const lessonsUrl = LAST_AGENT
897
+ ? `/learnings?agent=${encodeURIComponent(LAST_AGENT)}`
898
+ : "/learnings";
899
+ const { data, status } = await serverGet(cfg, lessonsUrl);
774
900
  if (!data) return errorResult(`Lessons fetch failed: ${describeGetFailure(status)}`);
775
901
  const lessons = data.lessons ?? [];
776
902
  if (lessons.length === 0) {
@@ -822,6 +948,7 @@ function registerTools(): Record<string, unknown> {
822
948
  if (args?.limit) params.set("limit", String(args.limit));
823
949
  if (args?.domain) params.set("domain", String(args.domain));
824
950
  if (args?.relationship) params.set("relationship", String(args.relationship));
951
+ if (LAST_AGENT) params.set("agent", LAST_AGENT);
825
952
  const { data, status } = await serverGet(cfg, `/graph?${params}`);
826
953
  if (!data) return errorResult(`Graph query failed: ${describeGetFailure(status)}`);
827
954
  return JSON.stringify(data);
@@ -941,6 +1068,10 @@ export const HicortexPlugin: any = async (_input: any): Promise<Record<string, u
941
1068
  const cfg = resolveOpencodeConfig();
942
1069
  if (!cfg) return;
943
1070
  pruneSessionState();
1071
+ // #600: resolve the workspace agent from the input's OWN directory
1072
+ // (strict — no process.cwd fallback); publishes to LAST_AGENT for
1073
+ // the tool proxies and rides the recall body.
1074
+ const agent = currentAgent(input);
944
1075
 
945
1076
  // Ordering (#316): a pending reset for THIS session registered
946
1077
  // before this fetch must complete first — bounded by the reset's
@@ -955,7 +1086,7 @@ export const HicortexPlugin: any = async (_input: any): Promise<Record<string, u
955
1086
  const promptKey = typeof last.msg.id === "string" && last.msg.id ? last.msg.id : prompt;
956
1087
  if (PROMPT_KEYS.get(sessionId) !== promptKey) {
957
1088
  const block = prompt
958
- ? await fetchRecallBlock(cfg, sessionId, prompt, cwdFromInput(input)).catch(() => null)
1089
+ ? await fetchRecallBlock(cfg, sessionId, prompt, cwdFromInput(input), agent).catch(() => null)
959
1090
  : null;
960
1091
  RECALL_BLOCKS.set(sessionId, block);
961
1092
  PROMPT_KEYS.set(sessionId, promptKey);
@@ -983,9 +1114,13 @@ export const HicortexPlugin: any = async (_input: any): Promise<Record<string, u
983
1114
  // versions — fall back to one process-wide cache key rather than
984
1115
  // skipping injection entirely.
985
1116
  const sessionId = inputSessionId(input) ?? FALLBACK_SESSION_KEY;
1117
+ // #600: the workspace agent for the lessons pool (member-gated) —
1118
+ // the input's own directory when it carries one, else the
1119
+ // last-known id a prompt hook resolved.
1120
+ const agent = currentAgent(input);
986
1121
  const [identityBlock, lessonsBlock] = await Promise.all([
987
1122
  cachedBlock(IDENTITY_BLOCKS, sessionId, () => fetchIdentityBlock(cfg)),
988
- cachedBlock(LESSONS_BLOCKS, sessionId, () => fetchLessonsBlock(cfg)),
1123
+ cachedAgentBlock(LESSONS_BLOCKS, sessionId, agent, () => fetchLessonsBlock(cfg, agent)),
989
1124
  ]);
990
1125
  const entry = renderContextEntry([identityBlock, lessonsBlock]);
991
1126
  if (entry) (system as unknown[]).push(entry);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gamaze/hicortex",
3
- "version": "0.27.1",
3
+ "version": "0.27.3",
4
4
  "description": "Persistent agent identity for AI agents \u2014 a hand-edited identity layer, nightly-distilled experience, and lessons injected every session, shared across your whole fleet. Works with Hermes, OpenClaw, Claude Code, Pi, and opencode.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -15,6 +15,16 @@
15
15
  * base prompt on any turn no extension returns one
16
16
  * (verified against pi 0.84.3), so the blocks are
17
17
  * re-applied EVERY turn from a session-scoped cache.
18
+ *
19
+ * #600: the workspace folder basename IS the agent name. Every read call
20
+ * (/recall-index body + the /search, /memory, /recent,
21
+ * /learnings, /graph tool queries) carries
22
+ * agent=<sanitized basename of the session cwd> so a
23
+ * rostered workspace reads as a confidential-circle
24
+ * member server-side; a null-sanitizing basename omits
25
+ * the param (fail-closed non-member). The tools have
26
+ * no per-request cwd, so they read the LAST_AGENT the
27
+ * per-prompt hook resolved.
18
28
  * session_start → POST /recall-index {reset:true} (fresh context
19
29
  * window — the server's per-session shown-set is
20
30
  * stale by definition) and drop the block caches.
@@ -249,11 +259,43 @@ export function renderLessonsBlock(data: LessonsResponse | null, maxLessons: num
249
259
  return parts.join("\n");
250
260
  }
251
261
 
262
+ /**
263
+ * Dependency-free twin of sanitizeAgentId (identity-store.ts): lowercase →
264
+ * collapse every [^a-z0-9_-]+ run to `-` → strip leading `-`/`_` → truncate to
265
+ * 64 → must match the section/agent allowlist `^[a-z0-9][a-z0-9_-]*$` (1..64
266
+ * chars), else null. identity-store.ts is the SOURCE OF TRUTH — keep the two
267
+ * in sync (this file cannot import package code; same duplication precedent
268
+ * as resolvePiConfig).
269
+ */
270
+ function sanitizeAgentId(raw: string): string | null {
271
+ if (typeof raw !== "string") return null;
272
+ const cleaned = raw
273
+ .toLowerCase()
274
+ .replace(/[^a-z0-9_-]+/g, "-")
275
+ .replace(/^[-_]+/, "")
276
+ .slice(0, 64);
277
+ return /^[a-z0-9][a-z0-9_-]*$/.test(cleaned) ? cleaned : null;
278
+ }
279
+
280
+ /**
281
+ * #600: the workspace-scoped agent id sent on every read call — the sanitized
282
+ * basename of the session cwd (the same basename `project` is derived from;
283
+ * the folder name IS the agent name). null when the
284
+ * basename sanitizes to nothing → the caller omits `agent` entirely
285
+ * (fail-closed: the request reads as a non-member, never an id the server
286
+ * would 400 on and a fail-soft path would silently swallow). Exported for
287
+ * tests like the other pure helpers.
288
+ */
289
+ export function workspaceAgentId(cwd: string): string | null {
290
+ return sanitizeAgentId(basename(cwd ?? ""));
291
+ }
292
+
252
293
  /**
253
294
  * Build the /recall-index request body, or null when there is nothing to
254
295
  * send (no session id, or an empty prompt). Mirrors the CC hook's
255
296
  * buildHookRequest: project = basename(cwd) so retrieval can apply the soft
256
- * project-affinity boost.
297
+ * project-affinity boost, and agent = the SANITIZED basename (#600) so the
298
+ * server's confidential-circle gate can recognize the session.
257
299
  */
258
300
  export function buildRecallBody(
259
301
  sessionId: string,
@@ -264,6 +306,8 @@ export function buildRecallBody(
264
306
  const body: Record<string, unknown> = { session_id: sessionId, prompt };
265
307
  const project = basename(cwd ?? "");
266
308
  if (project) body.project = project;
309
+ const agent = workspaceAgentId(project);
310
+ if (agent) body.agent = agent;
267
311
  return body;
268
312
  }
269
313
 
@@ -294,11 +338,22 @@ export function appendContextBlocks(
294
338
  * memoized for the session; a FAILED fetch is NOT — it retries next turn
295
339
  * (the OC plugin's #313 memoize-only-on-success rule). Bounded: a long-lived
296
340
  * pi process accumulating sessions would otherwise grow the maps forever.
341
+ *
342
+ * #600: the lessons cache stores the agent id the block was fetched UNDER
343
+ * (the lessons pool is member-gated) — see cachedAgentBlock. The identity
344
+ * cache is NOT agent-scoped (identity is global for pi).
297
345
  */
298
346
  const IDENTITY_BLOCKS = new Map<string, string | null>();
299
- const LESSONS_BLOCKS = new Map<string, string | null>();
347
+ const LESSONS_BLOCKS = new Map<string, { block: string | null; agent: string | null }>();
300
348
  /** In-flight / recently-fired dedup resets, keyed by session id (#316 ordering). */
301
349
  const PENDING_RESETS = new Map<string, Promise<void>>();
350
+ /**
351
+ * #600: the last workspace agent id a before_agent_start resolved from
352
+ * ctx.cwd. The tool executes receive no per-request cwd, so the five read
353
+ * proxies read this. Reset per turn from the turn's own cwd — a turn with no
354
+ * cwd clears it (the tools then omit agent: fail-closed).
355
+ */
356
+ let LAST_AGENT: string | null = null;
302
357
  const SESSION_STATE_CAP = 32;
303
358
 
304
359
  /** Test seam: wipe the module-level session state between cases. */
@@ -306,6 +361,7 @@ export function __resetSessionState(): void {
306
361
  IDENTITY_BLOCKS.clear();
307
362
  LESSONS_BLOCKS.clear();
308
363
  PENDING_RESETS.clear();
364
+ LAST_AGENT = null;
309
365
  }
310
366
 
311
367
  function pruneSessionState(): void {
@@ -345,6 +401,31 @@ async function cachedBlock(
345
401
  }
346
402
  }
347
403
 
404
+ /**
405
+ * #600: the lessons-cache identity guard — memoize the settled render UNDER
406
+ * the agent id it was fetched for. A later turn that resolves a DIFFERENT
407
+ * (or newly known) workspace id re-fetches; without this, a first turn whose
408
+ * cwd was unavailable would pin a standard-pool lessons block for a member's
409
+ * whole session. Same memoize-only-on-success rule as cachedBlock (a throw
410
+ * degrades to null and retries next turn).
411
+ */
412
+ async function cachedAgentBlock(
413
+ cache: Map<string, { block: string | null; agent: string | null }>,
414
+ sessionId: string,
415
+ agent: string | null,
416
+ fetcher: () => Promise<string | null>,
417
+ ): Promise<string | null> {
418
+ const hit = cache.get(sessionId);
419
+ if (hit && hit.agent === agent) return hit.block;
420
+ try {
421
+ const block = await fetcher();
422
+ cache.set(sessionId, { block, agent });
423
+ return block;
424
+ } catch {
425
+ return null;
426
+ }
427
+ }
428
+
348
429
  // ---------------------------------------------------------------------------
349
430
  // Fetchers — every failure path THROWS to the caller's fail-soft catch
350
431
  // ---------------------------------------------------------------------------
@@ -380,11 +461,19 @@ async function fetchIdentityBlock(cfg: PiConfig): Promise<string | null> {
380
461
  return gateAndRenderIdentity(await resp.json() as IdentityResponse);
381
462
  }
382
463
 
383
- async function fetchLessonsBlock(cfg: PiConfig): Promise<string | null> {
384
- const resp = await fetch(`${cfg.serverUrl}/learnings`, {
385
- headers: authHeaders(cfg),
386
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
387
- });
464
+ /**
465
+ * #600: `agent` is the session's workspace id — the lessons pool is
466
+ * member-gated server-side, so the block must be fetched under the id it
467
+ * will be cached under (see cachedAgentBlock). null → bare /learnings.
468
+ */
469
+ async function fetchLessonsBlock(cfg: PiConfig, agent: string | null): Promise<string | null> {
470
+ const resp = await fetch(
471
+ agent ? `${cfg.serverUrl}/learnings?agent=${encodeURIComponent(agent)}` : `${cfg.serverUrl}/learnings`,
472
+ {
473
+ headers: authHeaders(cfg),
474
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
475
+ },
476
+ );
388
477
  if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
389
478
  const block = renderLessonsBlock(await resp.json() as LessonsResponse, cfg.lessonsLimit);
390
479
  return block === null ? null : block;
@@ -537,6 +626,7 @@ function registerTools(pi: any): void {
537
626
  const params = new URLSearchParams({ query: String(args?.query ?? "") });
538
627
  if (args?.limit) params.set("limit", String(args.limit));
539
628
  if (args?.project) params.set("project", String(args.project));
629
+ if (LAST_AGENT) params.set("agent", LAST_AGENT);
540
630
  const { data, status } = await serverGet(cfg, `/search?${params}`);
541
631
  if (!data) return errorResult(`Search failed: ${describeGetFailure(status)}`);
542
632
  return formatSearchResults(data.results ?? []);
@@ -564,6 +654,7 @@ function registerTools(pi: any): void {
564
654
  const cfg = resolvePiConfig();
565
655
  if (!cfg) return errorResult(NOT_CONFIGURED);
566
656
  const params = new URLSearchParams({ id: String(args.id) });
657
+ if (LAST_AGENT) params.set("agent", LAST_AGENT);
567
658
  const { data, status } = await serverGet(cfg, `/memory?${params}`);
568
659
  if (status === 404) {
569
660
  // Either no such memory (0.14+) or a pre-0.14 server with no
@@ -600,6 +691,7 @@ function registerTools(pi: any): void {
600
691
  const params = new URLSearchParams();
601
692
  if (args?.project) params.set("project", String(args.project));
602
693
  if (args?.limit) params.set("limit", String(args.limit));
694
+ if (LAST_AGENT) params.set("agent", LAST_AGENT);
603
695
  const qs = params.toString();
604
696
  const { data, status } = await serverGet(cfg, `/recent${qs ? `?${qs}` : ""}`);
605
697
  if (!data) return errorResult(`Recent recall failed: ${describeGetFailure(status)}`);
@@ -665,7 +757,10 @@ function registerTools(pi: any): void {
665
757
  try {
666
758
  const cfg = resolvePiConfig();
667
759
  if (!cfg) return errorResult(NOT_CONFIGURED);
668
- const { data, status } = await serverGet(cfg, "/learnings");
760
+ const lessonsUrl = LAST_AGENT
761
+ ? `/learnings?agent=${encodeURIComponent(LAST_AGENT)}`
762
+ : "/learnings";
763
+ const { data, status } = await serverGet(cfg, lessonsUrl);
669
764
  if (!data) return errorResult(`Lessons fetch failed: ${describeGetFailure(status)}`);
670
765
  const lessons = data.lessons ?? [];
671
766
  if (lessons.length === 0) {
@@ -733,6 +828,7 @@ function registerTools(pi: any): void {
733
828
  if (args?.limit) params.set("limit", String(args.limit));
734
829
  if (args?.domain) params.set("domain", String(args.domain));
735
830
  if (args?.relationship) params.set("relationship", String(args.relationship));
831
+ if (LAST_AGENT) params.set("agent", LAST_AGENT);
736
832
  const { data, status } = await serverGet(cfg, `/graph?${params}`);
737
833
  if (!data) return errorResult(`Graph query failed: ${describeGetFailure(status)}`);
738
834
  return textResult(JSON.stringify(data));
@@ -874,9 +970,15 @@ export default function hicortexExtension(pi: any): void {
874
970
  if (pending) await pending;
875
971
 
876
972
  const prompt = typeof event?.prompt === "string" ? event.prompt : "";
973
+ const cwd = ctx?.cwd ?? "";
974
+ // #600: the workspace basename IS the agent id — resolved from the
975
+ // turn's cwd. Published to LAST_AGENT for the tool proxies (they get
976
+ // no cwd of their own); a turn with no cwd clears it (fail-closed).
977
+ const agent = workspaceAgentId(basename(cwd));
978
+ LAST_AGENT = agent;
877
979
  let message: { customType: string; content: string; display: boolean } | undefined;
878
980
  if (prompt) {
879
- const block = await fetchRecallBlock(cfg, sessionId, prompt, ctx?.cwd ?? "").catch(() => null);
981
+ const block = await fetchRecallBlock(cfg, sessionId, prompt, cwd).catch(() => null);
880
982
  if (block) {
881
983
  // display:false — the index is FOR the model; pi hides it from
882
984
  // the transcript UI but sends it alongside the user message.
@@ -886,10 +988,11 @@ export default function hicortexExtension(pi: any): void {
886
988
 
887
989
  // Identity + lessons: fetched once per session (independent
888
990
  // fail-soft), re-APPLIED every turn — pi resets a systemPrompt
889
- // override to base whenever no extension returns one.
991
+ // override to base whenever no extension returns one. The lessons
992
+ // block is cached UNDER the agent it was fetched for (#600).
890
993
  const [identityBlock, lessonsBlock] = await Promise.all([
891
994
  cachedBlock(IDENTITY_BLOCKS, sessionId, () => fetchIdentityBlock(cfg)),
892
- cachedBlock(LESSONS_BLOCKS, sessionId, () => fetchLessonsBlock(cfg)),
995
+ cachedAgentBlock(LESSONS_BLOCKS, sessionId, agent, () => fetchLessonsBlock(cfg, agent)),
893
996
  ]);
894
997
  const systemPrompt = appendContextBlocks(event?.systemPrompt, [identityBlock, lessonsBlock]);
895
998
 
package/server.json CHANGED
@@ -3,12 +3,12 @@
3
3
  "name": "io.github.gamaze-labs/hicortex",
4
4
  "title": "Hicortex \u2014 AI Fleet Memory",
5
5
  "description": "Shared fleet memory for AI agents: nightly self-correction, recall every prompt (supported agents).",
6
- "version": "0.27.1",
6
+ "version": "0.27.3",
7
7
  "packages": [
8
8
  {
9
9
  "registryType": "npm",
10
10
  "identifier": "@gamaze/hicortex",
11
- "version": "0.27.1",
11
+ "version": "0.27.3",
12
12
  "transport": {
13
13
  "type": "stdio",
14
14
  "command": "npx",