@gamaze/hicortex 0.27.1 → 0.27.2
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/README.md +2 -2
- package/dist/learnings-identity.d.ts +26 -3
- package/dist/learnings-identity.js +54 -17
- package/dist/recall-hook-cli.d.ts +3 -0
- package/dist/recall-hook-cli.js +14 -1
- package/opencode-plugin/hicortex/index.ts +146 -11
- package/package.json +1 -1
- package/pi-extension/hicortex/index.ts +114 -11
- package/server.json +2 -2
package/README.md
CHANGED
|
@@ -278,8 +278,8 @@ Config at `~/.hicortex/config.json`. Created by `init`. Key options:
|
|
|
278
278
|
| `lessonsLimit` | Max lessons injected into an agent's session-start context (default: 10). Lessons are ranked per session by project/domain affinity + recency + strength + access, so each session sees its most-relevant slice. Lower = leaner system prompts. |
|
|
279
279
|
| `identityClients` | Which harnesses inject the [identity layer](#identity-layer) at session start (default `["cc"]`; `"all"` or any subset of `cc`/`hermes`/`oc`/`pi`/`opencode`) |
|
|
280
280
|
| `identityAgents` | Per-agent identity modes (0.13): `{ "<id>": "override" \| "global" \| "off" }`. Absent + no `agents/<id>/` dir → every agent gets the global set. Boot-time (restart to apply) — see [Per-agent identity](#per-agent-identity-013) |
|
|
281
|
-
| `agentName` | This install's
|
|
282
|
-
| `confidentialAgents` | The **confidential circle** roster (#332): agent ids (same sanitized namespace as `identityAgents`/`?agent=`; `"finance-bot"`, not `"hermes/finance-bot"` — the first `<harness>/` segment is stripped when matching captures). Captures from rostered agents are stamped `confidential` at intake, server-derived (client-declared privacy is ignored); only rostered agents — sending their id as the optional `agent` param on `/recall-index`, `/search`, `/recent`, `/memory`, `/learnings`, `/graph` — see those memories (absent/unknown agent = omitted, single fetch 404). Members see both pools. **Empty by default = no circle, zero change.** Boot-time (restart to apply); `hicortex backfill-privacy` (dry run by default) stamps history by source agent |
|
|
281
|
+
| `agentName` | This install's configured identity name, reported by `hicortex status` (#600: no longer sent on the wire — the hooks identify by the workspace folder basename instead; see `confidentialAgents`). **Unset by default** (CC shares the global identity). Explicit opt-in via `init --agent-name <name>`; `init --agent-name ""` clears it. An empty/whitespace value equals unset |
|
|
282
|
+
| `confidentialAgents` | The **confidential circle** roster (#332): agent ids (same sanitized namespace as `identityAgents`/`?agent=`; `"finance-bot"`, not `"hermes/finance-bot"` — the first `<harness>/` segment is stripped when matching captures). Captures from rostered agents are stamped `confidential` at intake, server-derived (client-declared privacy is ignored); only rostered agents — sending their id as the optional `agent` param on `/recall-index`, `/search`, `/recent`, `/memory`, `/learnings`, `/graph` — see those memories (absent/unknown agent = omitted, single fetch 404). Members see both pools. **Reads need an identifying client:** Hermes plugin 0.7.11+ sends its profile id (plugin installs are pinned at install — update if older); CC/Pi/opencode identify by the workspace folder NAME — roster the folder's basename (sessions under `~/Agents/nano/` are the agent `nano`; npx clients auto-update, the copied Pi/opencode extension files need a re-`init` or manual copy); OpenClaw sends no id (non-member reads). Older client versions are safe — fail-closed, standard pool only — they simply appear anonymous. **Empty by default = no circle, zero change.** Boot-time (restart to apply); `hicortex backfill-privacy` (dry run by default) stamps history by source agent |
|
|
283
283
|
| `confidentialPaths` | Workspace-path patterns for the confidential circle (#609) — the **advanced** arm for the two jobs a local marker cannot do: retroactive backfill (with `hicortex backfill-privacy`) and central fleet management (one config edit covers every machine, no command to run). A capture made in a matching folder is stamped `confidential` at intake **regardless of agent id** (Claude Code agent ids are folder-derived generics — the roster alone misses a sensitive folder captured by an unrostered id). Entries are absolute paths in three forms — exact (`/home/me/finance`), `*` as a full segment (`/home/*/finance`), trailing `/**` subtree *including* the prefix itself (`/home/me/**`) — plus a leading `~/` that matches any user's home structurally (`/home/<user>/…` or `/Users/<user>/…`, so one entry covers a multi-OS fleet). Separators normalize to `/` and comparison is case-insensitive (over-match is the safe direction); invalid entries (relative, `**` mid-path) are dropped at boot with a warning naming them. Every nightly delivery carries the session's workspace path (`workspace_path`) plus the relayed workspace-marker content (`client_marker`, see `confidentialMarkerKey` below), and the path is stored on the row — so `hicortex backfill-privacy` reports and stamps history **per pattern** too (rows stored before the column exists have no path and are never path-matched). Prefer marking a folder right where you are? `hicortex confidential` (optionally `[path]`, `--off` to unmark) writes a local `.hicortex-confidential` marker carrying the server's `confidentialMarkerKey` — and provisions that key itself (see the next row); the nightly relays the marker's content and the server validates it. Add the folder here to backfill its history. **Empty by default = zero change.** Boot-time (restart to apply) |
|
|
284
284
|
| `confidentialMarkerKey` | The owner-set key a workspace marker must carry (#614): `hicortex confidential` writes it into the `.hicortex-confidential` marker file (single line), the nightly relays that content as `client_marker`, and the server stamps `confidential` only when the content **matches this key** — compared timing-safe, server-side, at intake. This closes the client-writable classification channel: the pre-#614 empty marker (and the `client_confidential` boolean) let any capture client mark its own deliveries confidential, and a client sending `client_confidential: true` without valid marker content is now ignored. **Provisioned by that very command (#616) — no manual key mirroring**: on a machine with no local key the command fetches the server's existing key, or generates one and registers it there (`GET`/`PUT /confidential/marker-key`, token-gated), then caches it in this machine's `~/.hicortex/config.json` for offline reuse; `confidential --key <value>` rotates (the server applies the new key to the next delivery, no restart; markers carrying a previous key then stamp standard). An env or config key already on the machine is used as-is, no server contact; the command refuses when no key exists AND no server is reachable. **Absent/blank (default) = markers are INERT, fail-closed both directions** — marker-carrying deliveries stamp standard, and a boot note names the key when the circle is otherwise active. Operators can still set it by hand: config (restart to apply) or the env mirror `HICORTEX_CONFIDENTIAL_MARKER_KEY`, which overrides config — and while that env is set on the server, rotation PUTs answer `409` instead of shadow-writing |
|
|
285
285
|
| `llmConfidentialBaseUrl` | The confidential model's endpoint (#332). With `llmConfidentialApiKey` (both required; `llmConfidentialModel` optional; `llmConfidentialProvider` selects the dialect like `llmProvider`), a second model handles **every** LLM touch of confidential text — distillation, importance scoring, reflection, contradiction checks, domain classification, reconsolidation verdicts. Env mirrors: `HICORTEX_LLM_CONFIDENTIAL_BASE_URL`/`_API_KEY`/`_MODEL` |
|
|
@@ -17,6 +17,10 @@
|
|
|
17
17
|
* GET /lessons → episodic memory lessons + memory index, rendered as the
|
|
18
18
|
* existing `## Hicortex Memory` block.
|
|
19
19
|
*
|
|
20
|
+
* #600: both fetches carry `?agent=<sanitized basename of the session cwd>` —
|
|
21
|
+
* the workspace folder name IS the agent name, so a rostered workspace reads
|
|
22
|
+
* as a confidential-circle member server-side (fail-closed otherwise).
|
|
23
|
+
*
|
|
20
24
|
* The two fetches run in Promise.all, each with its OWN 3 s timeout and
|
|
21
25
|
* INDEPENDENT fail-soft: an /identity failure must never cost the lessons
|
|
22
26
|
* block, and vice versa. Sequential fetches would double worst-case
|
|
@@ -43,7 +47,10 @@ export interface ResolvedConfig {
|
|
|
43
47
|
serverUrl: string;
|
|
44
48
|
authToken: string | undefined;
|
|
45
49
|
home: string;
|
|
46
|
-
/**
|
|
50
|
+
/** The resolved config `agentName` (0.13). #600: CONFIG/STATUS-REPORTED
|
|
51
|
+
* ONLY — the hooks no longer send it (the workspace basename is the agent
|
|
52
|
+
* identity on the wire now); `hicortex status` reports it via its own
|
|
53
|
+
* resolveAgentIdentity call. null → unset/invalid config value. */
|
|
47
54
|
agentName: string | null;
|
|
48
55
|
/** Max lessons to inject (config.lessonsLimit, default 10). */
|
|
49
56
|
lessonsLimit?: number;
|
|
@@ -71,6 +78,19 @@ export declare function resolveConfig(): ResolvedConfig | null;
|
|
|
71
78
|
* plus this function are the whole client-side seam).
|
|
72
79
|
*/
|
|
73
80
|
export declare function deriveHookProject(cwd: string, aliases?: Readonly<Record<string, string>> | null): string | null;
|
|
81
|
+
/**
|
|
82
|
+
* #600: the workspace-scoped agent id a CC client sends on its read calls —
|
|
83
|
+
* the SANITIZED basename of the session's working directory (owner ruling
|
|
84
|
+
* 2026-11-17: the workspace folder name IS the agent name, the same basename
|
|
85
|
+
* `project` is derived from; no precedence chain, no configured-name
|
|
86
|
+
* override). The server's confidential-circle gate matches rostered BARE ids
|
|
87
|
+
* here. null when the basename sanitizes to nothing (e.g. "!!!" or "/") → the
|
|
88
|
+
* caller omits the `agent` param entirely, never sending an id the server
|
|
89
|
+
* would 400 on (the fail-soft hook would silently swallow that and drop the
|
|
90
|
+
* whole block). Reuses the package's sanitizeAgentId so client and server
|
|
91
|
+
* agree on the id grammar by construction.
|
|
92
|
+
*/
|
|
93
|
+
export declare function workspaceAgentId(cwd: string): string | null;
|
|
74
94
|
/**
|
|
75
95
|
* Title-case a section name for its heading: split on `-`/`_`, capitalize each
|
|
76
96
|
* word ("user" → "User", "my_notes" → "My Notes").
|
|
@@ -163,9 +183,12 @@ export declare function gateAndRenderIdentity(data: IdentityResponse, harness: s
|
|
|
163
183
|
* Fetch identity + lessons concurrently and return the combined Markdown block,
|
|
164
184
|
* or null when neither yields anything (nothing to inject; caller prints
|
|
165
185
|
* nothing and exits 0). The `## Identity` block is prepended before the existing
|
|
166
|
-
* `## Hicortex Memory` block.
|
|
186
|
+
* `## Hicortex Memory` block. #600: `cwd` is the session's working directory
|
|
187
|
+
* (default process.cwd()) — its sanitized basename is the workspace-scoped
|
|
188
|
+
* agent id both fetches send; the optional parameter is the test seam,
|
|
189
|
+
* mirroring buildHookRequest.
|
|
167
190
|
*/
|
|
168
|
-
export declare function fetchLessonsIdentity(): Promise<string | null>;
|
|
191
|
+
export declare function fetchLessonsIdentity(cwd?: string): Promise<string | null>;
|
|
169
192
|
/** Backcompat alias (#264). */
|
|
170
193
|
export declare const fetchLessonsContext: typeof fetchLessonsIdentity;
|
|
171
194
|
/** Backcompat aliases (#264) for the renamed symbols. */
|
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
* GET /lessons → episodic memory lessons + memory index, rendered as the
|
|
19
19
|
* existing `## Hicortex Memory` block.
|
|
20
20
|
*
|
|
21
|
+
* #600: both fetches carry `?agent=<sanitized basename of the session cwd>` —
|
|
22
|
+
* the workspace folder name IS the agent name, so a rostered workspace reads
|
|
23
|
+
* as a confidential-circle member server-side (fail-closed otherwise).
|
|
24
|
+
*
|
|
21
25
|
* The two fetches run in Promise.all, each with its OWN 3 s timeout and
|
|
22
26
|
* INDEPENDENT fail-soft: an /identity failure must never cost the lessons
|
|
23
27
|
* block, and vice versa. Sequential fetches would double worst-case
|
|
@@ -31,6 +35,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
31
35
|
exports.gateAndRenderContext = exports.renderContextBlock = exports.fetchLessonsContext = void 0;
|
|
32
36
|
exports.resolveConfig = resolveConfig;
|
|
33
37
|
exports.deriveHookProject = deriveHookProject;
|
|
38
|
+
exports.workspaceAgentId = workspaceAgentId;
|
|
34
39
|
exports.titleCaseSection = titleCaseSection;
|
|
35
40
|
exports.orderSectionNames = orderSectionNames;
|
|
36
41
|
exports.renderIdentityBlock = renderIdentityBlock;
|
|
@@ -67,11 +72,11 @@ function resolveConfig() {
|
|
|
67
72
|
const serverUrl = config.mode === "client" && typeof config.serverUrl === "string"
|
|
68
73
|
? config.serverUrl.replace(/\/+$/, "")
|
|
69
74
|
: `http://127.0.0.1:${config.port ?? DEFAULT_PORT}`;
|
|
70
|
-
// Per-agent identity id (0.13) via the shared resolver, so
|
|
71
|
-
// always matches what `hicortex status` reports.
|
|
72
|
-
//
|
|
73
|
-
// identity
|
|
74
|
-
//
|
|
75
|
+
// Per-agent identity id (0.13) via the shared resolver, so what an install
|
|
76
|
+
// has CONFIGURED always matches what `hicortex status` reports. #600: the
|
|
77
|
+
// hooks no longer send this id — the workspace basename is the agent
|
|
78
|
+
// identity on the wire (see workspaceAgentId); agentName stays
|
|
79
|
+
// config/status-reported only.
|
|
75
80
|
const agentName = (0, identity_store_js_1.resolveAgentIdentity)(config).agentId;
|
|
76
81
|
return {
|
|
77
82
|
serverUrl,
|
|
@@ -98,6 +103,21 @@ function authHeaders(authToken) {
|
|
|
98
103
|
function deriveHookProject(cwd, aliases) {
|
|
99
104
|
return (0, project_canonicalize_js_1.canonicalizeProject)((0, node_path_1.basename)(cwd), aliases);
|
|
100
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* #600: the workspace-scoped agent id a CC client sends on its read calls —
|
|
108
|
+
* the SANITIZED basename of the session's working directory (owner ruling
|
|
109
|
+
* 2026-11-17: the workspace folder name IS the agent name, the same basename
|
|
110
|
+
* `project` is derived from; no precedence chain, no configured-name
|
|
111
|
+
* override). The server's confidential-circle gate matches rostered BARE ids
|
|
112
|
+
* here. null when the basename sanitizes to nothing (e.g. "!!!" or "/") → the
|
|
113
|
+
* caller omits the `agent` param entirely, never sending an id the server
|
|
114
|
+
* would 400 on (the fail-soft hook would silently swallow that and drop the
|
|
115
|
+
* whole block). Reuses the package's sanitizeAgentId so client and server
|
|
116
|
+
* agree on the id grammar by construction.
|
|
117
|
+
*/
|
|
118
|
+
function workspaceAgentId(cwd) {
|
|
119
|
+
return (0, identity_store_js_1.sanitizeAgentId)((0, node_path_1.basename)(cwd));
|
|
120
|
+
}
|
|
101
121
|
/**
|
|
102
122
|
* Trust framing + provenance for the injected lessons block (#516). The
|
|
103
123
|
* fence + two lines are byte-identical on every client surface (CC hook,
|
|
@@ -112,9 +132,17 @@ const MEMORY_PROVENANCE = "Provenance: auto-distilled by Hicortex from this memo
|
|
|
112
132
|
/**
|
|
113
133
|
* Fetch /lessons and build the `## Hicortex Memory` block, or null on any
|
|
114
134
|
* failure (missing/non-2xx/parse). Preserves the pre-0.12 behavior exactly.
|
|
135
|
+
* #600: `cwd` is the session's working directory (default process.cwd()) —
|
|
136
|
+
* the sanitized basename rides the request as `?agent=` (confidential lessons
|
|
137
|
+
* are member-gated server-side) and feeds the project fold. A null-sanitizing
|
|
138
|
+
* basename → bare /lessons (non-member, fail-closed).
|
|
115
139
|
*/
|
|
116
|
-
async function fetchLessonsBlock(cfg) {
|
|
117
|
-
const
|
|
140
|
+
async function fetchLessonsBlock(cfg, cwd = process.cwd()) {
|
|
141
|
+
const agent = workspaceAgentId(cwd);
|
|
142
|
+
const url = agent
|
|
143
|
+
? `${cfg.serverUrl}/lessons?agent=${encodeURIComponent(agent)}`
|
|
144
|
+
: `${cfg.serverUrl}/lessons`;
|
|
145
|
+
const resp = await fetch(url, {
|
|
118
146
|
headers: authHeaders(cfg.authToken),
|
|
119
147
|
signal: AbortSignal.timeout(3000),
|
|
120
148
|
});
|
|
@@ -129,7 +157,7 @@ async function fetchLessonsBlock(cfg) {
|
|
|
129
157
|
// This enables in-project + same-domain lesson boosting on the CC path.
|
|
130
158
|
// #567: folded through the shared canonicalizer so the local label
|
|
131
159
|
// compares equal to the canonical server corpus (see deriveHookProject).
|
|
132
|
-
const project = deriveHookProject(
|
|
160
|
+
const project = deriveHookProject(cwd, cfg.projectAliases);
|
|
133
161
|
const selected = await (0, extensions_js_1.getLessonSelector)().select(data.lessons, { maxLessons, moduleIndex, project });
|
|
134
162
|
const lessonLines = selected.map((l) => {
|
|
135
163
|
const typeMatch = l.content.match(/\*\*Type:\*\* (\w+)/);
|
|
@@ -296,14 +324,20 @@ function gateAndRenderIdentity(data, harness, opts) {
|
|
|
296
324
|
* Fetch /identity and build the `## Identity` block, or null when nothing should
|
|
297
325
|
* be injected: non-2xx, this harness not in `clients`, no sections, or all
|
|
298
326
|
* sections empty. Throws propagate to the caller's fail-soft catch.
|
|
327
|
+
* #600: `cwd` is the session's working directory (default process.cwd()) —
|
|
328
|
+
* its sanitized basename is the workspace-scoped identity sent as `?agent=`.
|
|
299
329
|
*/
|
|
300
|
-
async function fetchIdentityBlock(cfg) {
|
|
330
|
+
async function fetchIdentityBlock(cfg, cwd = process.cwd()) {
|
|
301
331
|
// Send ?agent= only when we have a valid id; the server does the merge and
|
|
302
332
|
// returns the resolved sections, so the hook stays dumb (no client-side mode
|
|
303
|
-
// logic).
|
|
304
|
-
//
|
|
305
|
-
|
|
306
|
-
|
|
333
|
+
// logic). #600: the id is the SANITIZED WORKSPACE BASENAME (owner ruling
|
|
334
|
+
// 2026-11-17: the folder name IS the agent name — it replaces the configured
|
|
335
|
+
// agentName on the hook path, which stays config/status-reported only). A
|
|
336
|
+
// null id (a basename that sanitizes to nothing) → bare /identity → the
|
|
337
|
+
// shared global set.
|
|
338
|
+
const id = workspaceAgentId(cwd);
|
|
339
|
+
const url = id
|
|
340
|
+
? `${cfg.serverUrl}/identity?agent=${encodeURIComponent(id)}`
|
|
307
341
|
: `${cfg.serverUrl}/identity`;
|
|
308
342
|
const resp = await fetch(url, {
|
|
309
343
|
headers: authHeaders(cfg.authToken),
|
|
@@ -323,9 +357,12 @@ async function fetchIdentityBlock(cfg) {
|
|
|
323
357
|
* Fetch identity + lessons concurrently and return the combined Markdown block,
|
|
324
358
|
* or null when neither yields anything (nothing to inject; caller prints
|
|
325
359
|
* nothing and exits 0). The `## Identity` block is prepended before the existing
|
|
326
|
-
* `## Hicortex Memory` block.
|
|
360
|
+
* `## Hicortex Memory` block. #600: `cwd` is the session's working directory
|
|
361
|
+
* (default process.cwd()) — its sanitized basename is the workspace-scoped
|
|
362
|
+
* agent id both fetches send; the optional parameter is the test seam,
|
|
363
|
+
* mirroring buildHookRequest.
|
|
327
364
|
*/
|
|
328
|
-
async function fetchLessonsIdentity() {
|
|
365
|
+
async function fetchLessonsIdentity(cwd = process.cwd()) {
|
|
329
366
|
const cfg = resolveConfig();
|
|
330
367
|
if (!cfg)
|
|
331
368
|
return null;
|
|
@@ -333,8 +370,8 @@ async function fetchLessonsIdentity() {
|
|
|
333
370
|
// other. Promise.all runs them concurrently — each carries its own 3 s
|
|
334
371
|
// timeout, so worst-case latency stays ~3 s, not ~6 s (spec §7).
|
|
335
372
|
const [identityBlock, lessonsBlock] = await Promise.all([
|
|
336
|
-
fetchIdentityBlock(cfg).catch(() => null),
|
|
337
|
-
fetchLessonsBlock(cfg).catch(() => null),
|
|
373
|
+
fetchIdentityBlock(cfg, cwd).catch(() => null),
|
|
374
|
+
fetchLessonsBlock(cfg, cwd).catch(() => null),
|
|
338
375
|
]);
|
|
339
376
|
const blocks = [identityBlock, lessonsBlock].filter((b) => b !== null && b !== "");
|
|
340
377
|
if (blocks.length === 0)
|
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
* dispatches on the payload):
|
|
6
6
|
* - UserPromptSubmit: POST the prompt to the server's /recall-index; print
|
|
7
7
|
* the returned index block to stdout (CC injects hook stdout as context).
|
|
8
|
+
* #600: the body carries `agent` = the sanitized basename of the session
|
|
9
|
+
* cwd (the workspace folder name IS the agent name) so the server's
|
|
10
|
+
* confidential-circle gate can recognize the session.
|
|
8
11
|
* - SessionStart (startup/resume/clear/compact): POST a reset so the
|
|
9
12
|
* server's per-session shown-set matches the fresh context window.
|
|
10
13
|
*
|
package/dist/recall-hook-cli.js
CHANGED
|
@@ -6,6 +6,9 @@
|
|
|
6
6
|
* dispatches on the payload):
|
|
7
7
|
* - UserPromptSubmit: POST the prompt to the server's /recall-index; print
|
|
8
8
|
* the returned index block to stdout (CC injects hook stdout as context).
|
|
9
|
+
* #600: the body carries `agent` = the sanitized basename of the session
|
|
10
|
+
* cwd (the workspace folder name IS the agent name) so the server's
|
|
11
|
+
* confidential-circle gate can recognize the session.
|
|
9
12
|
* - SessionStart (startup/resume/clear/compact): POST a reset so the
|
|
10
13
|
* server's per-session shown-set matches the fresh context window.
|
|
11
14
|
*
|
|
@@ -58,7 +61,17 @@ function buildHookRequest(payload, cwd = process.cwd()) {
|
|
|
58
61
|
// soft project-affinity boost. basename(cwd) matches capture's
|
|
59
62
|
// decodeProjectDirName for non-hyphenated dirs (the common case); a hyphen
|
|
60
63
|
// edge case is a pre-existing capture bug, filed separately.
|
|
61
|
-
|
|
64
|
+
// #600: the same basename IS the agent id — sent SANITIZED so the server's
|
|
65
|
+
// confidential-circle gate can recognize the session (a rostered workspace
|
|
66
|
+
// reads as a member). A basename that sanitizes to null omits the field
|
|
67
|
+
// entirely (non-member, fail-closed — never an id the server would 400 on).
|
|
68
|
+
// The SessionStart reset above deliberately carries NO agent: a reset
|
|
69
|
+
// returns no rows, so there is nothing to gate.
|
|
70
|
+
const body = { session_id: sessionId, prompt, project: (0, node_path_1.basename)(cwd) };
|
|
71
|
+
const agent = (0, learnings_identity_js_1.workspaceAgentId)(cwd);
|
|
72
|
+
if (agent)
|
|
73
|
+
body.agent = agent;
|
|
74
|
+
return body;
|
|
62
75
|
}
|
|
63
76
|
async function runRecallHook() {
|
|
64
77
|
const cfg = (0, learnings_identity_js_1.resolveConfig)();
|
|
@@ -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, owner ruling 2026-11-17). 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
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
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
|
|
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
|
-
|
|
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.
|
|
3
|
+
"version": "0.27.2",
|
|
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, owner ruling 2026-11-17). 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
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
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
|
|
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,
|
|
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
|
-
|
|
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.
|
|
6
|
+
"version": "0.27.2",
|
|
7
7
|
"packages": [
|
|
8
8
|
{
|
|
9
9
|
"registryType": "npm",
|
|
10
10
|
"identifier": "@gamaze/hicortex",
|
|
11
|
-
"version": "0.27.
|
|
11
|
+
"version": "0.27.2",
|
|
12
12
|
"transport": {
|
|
13
13
|
"type": "stdio",
|
|
14
14
|
"command": "npx",
|