@gamaze/hicortex 0.27.0 → 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.
@@ -0,0 +1,103 @@
1
+ /**
2
+ * `hicortex confidential [path] [--key <value>|--off]` (#609/#614/#616) —
3
+ * mark or unmark a workspace folder confidential via the local marker file
4
+ * `.hicortex-confidential`.
5
+ *
6
+ * A marker in a PARENT directory covers child workspaces (the capture walk
7
+ * reads every ancestor up to /), and the marker rides folder renames/moves
8
+ * with the directory itself.
9
+ *
10
+ * #614: the marker CARRIES THE KEY. Its single-line content is the server's
11
+ * `confidentialMarkerKey`, validated SERVER-side at intake (an empty or
12
+ * mismatched marker stamps standard — the empty #609 marker was a
13
+ * client-writable classification channel anybody could replicate).
14
+ *
15
+ * #616: getting that key is ONE COMMAND. When this machine holds no key, the
16
+ * command contacts the server it already reports to (server URL + authToken
17
+ * from the local config, the SAME credential every other client call uses —
18
+ * resolveConfig): fetch the key (a second machine reuses the existing one,
19
+ * no second key), or generate `cmark-<32 hex>` and REGISTER it when the
20
+ * server has none, then persist it into `<hicortex-home>/config.json` for
21
+ * offline reuse. Explicit `--key <value>` is ROTATION: it PUTs the chosen
22
+ * value to the server (GET/PUT /confidential/marker-key, #616) before
23
+ * writing, so a deliberate key change propagates from ANY machine. The env
24
+ * (`HICORTEX_CONFIDENTIAL_MARKER_KEY`) and local-config layers stay pure
25
+ * offline fast paths — no server contact. Without any key AND without a
26
+ * reachable server the command REFUSES with instructions — a keyless marker
27
+ * would be inert server-side, and silently writing one would be a no-op
28
+ * disguised as success. `--off` needs no key and makes no network calls
29
+ * (removal is unconditional and never demotes already-captured memories).
30
+ *
31
+ * Future (#613): the content evolves to space-id + key; this writer and the
32
+ * capture reader (readConfidentialMarker) stay content-agnostic — first
33
+ * line, trimmed, relayed verbatim for the server to interpret.
34
+ */
35
+ /**
36
+ * The workspace confidentiality marker's filename (#609): a one-line file at
37
+ * the workspace root, written/removed by this command and read by the
38
+ * nightly's marker walk (readConfidentialMarker in capture.ts — the ONE
39
+ * definition lives here so the writer and the reader can never drift).
40
+ */
41
+ export declare const CONFIDENTIAL_MARKER_FILENAME = ".hicortex-confidential";
42
+ /**
43
+ * #616: the server transport the provisioning flow needs — GET the server's
44
+ * current key (null = none registered yet), PUT a new one (first provisioning
45
+ * or rotation). Injected by tests (the capture.ts `post` seam precedent);
46
+ * production builds it from resolveConfig() + fetch. PUT throws on ANY
47
+ * non-OK answer — a refused registration must never leave a local key or
48
+ * marker behind.
49
+ */
50
+ export interface MarkerKeyTransport {
51
+ get(): Promise<{
52
+ key: string | null;
53
+ }>;
54
+ put(key: string): Promise<void>;
55
+ }
56
+ export interface ConfidentialMarkerOptions {
57
+ /**
58
+ * Target folder. Default: the process cwd (the natural "mark the folder I
59
+ * am in" invocation). Relative paths resolve against the cwd; the command
60
+ * always reports and acts on the ABSOLUTE path.
61
+ */
62
+ path?: string;
63
+ /** Remove the marker instead of writing it. Succeeds when absent. No key, no network. */
64
+ off?: boolean;
65
+ /**
66
+ * Explicit marker key (#616 ROTATION, the CLI `--key` flag): PUT the chosen
67
+ * value to the server, persist it locally, then write the marker. Checked
68
+ * BEFORE env and config — an owner rotating deliberately pushes the new
69
+ * value, not the locally-cached old one.
70
+ */
71
+ key?: string;
72
+ /**
73
+ * #616 test seam: the server transport for the fetch-or-generate flow.
74
+ * Absent → the default transport from resolveConfig() (null when this
75
+ * machine reports to no server → the refusal error).
76
+ */
77
+ transport?: MarkerKeyTransport;
78
+ }
79
+ export interface ConfidentialMarkerResult {
80
+ /** The resolved absolute folder path the command acted on. */
81
+ folder: string;
82
+ /** The marker file's absolute path. */
83
+ markerPath: string;
84
+ /** True when the marker exists after the command ran. */
85
+ marked: boolean;
86
+ }
87
+ /**
88
+ * Write (or remove) the confidential marker. Fails EXPLICITLY when the
89
+ * target folder does not exist — a typo'd path must not silently mark the
90
+ * wrong directory (or nothing). `--off` is deliberately lenient: removing an
91
+ * absent marker is a no-op success (convergent, like the uninstall paths).
92
+ *
93
+ * ASYNC since #616: the key may need a server round-trip (fetch or
94
+ * generate-and-register) when no local layer holds it. The only callers are
95
+ * the cli.ts `confidential` case and tests.
96
+ *
97
+ * Note the classification asymmetry, mirrored in the output: marking takes
98
+ * effect from the NEXT capture (the nightly reads the marker then), and
99
+ * unmarking never demotes — already-captured memories keep their stamp (the
100
+ * #332 never-demotes rule; history heals via `hicortex backfill-privacy`
101
+ * only toward confidential).
102
+ */
103
+ export declare function runConfidentialCommand(opts?: ConfidentialMarkerOptions): Promise<ConfidentialMarkerResult>;
@@ -0,0 +1,285 @@
1
+ "use strict";
2
+ /**
3
+ * `hicortex confidential [path] [--key <value>|--off]` (#609/#614/#616) —
4
+ * mark or unmark a workspace folder confidential via the local marker file
5
+ * `.hicortex-confidential`.
6
+ *
7
+ * A marker in a PARENT directory covers child workspaces (the capture walk
8
+ * reads every ancestor up to /), and the marker rides folder renames/moves
9
+ * with the directory itself.
10
+ *
11
+ * #614: the marker CARRIES THE KEY. Its single-line content is the server's
12
+ * `confidentialMarkerKey`, validated SERVER-side at intake (an empty or
13
+ * mismatched marker stamps standard — the empty #609 marker was a
14
+ * client-writable classification channel anybody could replicate).
15
+ *
16
+ * #616: getting that key is ONE COMMAND. When this machine holds no key, the
17
+ * command contacts the server it already reports to (server URL + authToken
18
+ * from the local config, the SAME credential every other client call uses —
19
+ * resolveConfig): fetch the key (a second machine reuses the existing one,
20
+ * no second key), or generate `cmark-<32 hex>` and REGISTER it when the
21
+ * server has none, then persist it into `<hicortex-home>/config.json` for
22
+ * offline reuse. Explicit `--key <value>` is ROTATION: it PUTs the chosen
23
+ * value to the server (GET/PUT /confidential/marker-key, #616) before
24
+ * writing, so a deliberate key change propagates from ANY machine. The env
25
+ * (`HICORTEX_CONFIDENTIAL_MARKER_KEY`) and local-config layers stay pure
26
+ * offline fast paths — no server contact. Without any key AND without a
27
+ * reachable server the command REFUSES with instructions — a keyless marker
28
+ * would be inert server-side, and silently writing one would be a no-op
29
+ * disguised as success. `--off` needs no key and makes no network calls
30
+ * (removal is unconditional and never demotes already-captured memories).
31
+ *
32
+ * Future (#613): the content evolves to space-id + key; this writer and the
33
+ * capture reader (readConfidentialMarker) stay content-agnostic — first
34
+ * line, trimmed, relayed verbatim for the server to interpret.
35
+ */
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.CONFIDENTIAL_MARKER_FILENAME = void 0;
38
+ exports.runConfidentialCommand = runConfidentialCommand;
39
+ const node_fs_1 = require("node:fs");
40
+ const node_path_1 = require("node:path");
41
+ const node_crypto_1 = require("node:crypto");
42
+ const paths_js_1 = require("./paths.js");
43
+ const init_js_1 = require("./init.js");
44
+ const config_read_js_1 = require("./config-read.js");
45
+ const learnings_identity_js_1 = require("./learnings-identity.js");
46
+ /**
47
+ * The workspace confidentiality marker's filename (#609): a one-line file at
48
+ * the workspace root, written/removed by this command and read by the
49
+ * nightly's marker walk (readConfidentialMarker in capture.ts — the ONE
50
+ * definition lives here so the writer and the reader can never drift).
51
+ */
52
+ exports.CONFIDENTIAL_MARKER_FILENAME = ".hicortex-confidential";
53
+ /**
54
+ * The common refusal (#614/#616): no key is obtainable on this machine. The
55
+ * message names the two fixes — make the server reachable (so the one-command
56
+ * flow works), or set the key manually (env / config) — because either one
57
+ * unblocks the write. Never writes a marker alongside this error.
58
+ */
59
+ function markerKeyRefusal(detail) {
60
+ return new Error(`[hicortex] confidential: ${detail}\n` +
61
+ ` The marker must carry the server's confidentialMarkerKey or the server ignores it (#614).\n` +
62
+ ` Fix: start the Hicortex server this machine reports to (or re-run init so its URL + token\n` +
63
+ ` are in ~/.hicortex/config.json), or set the key manually — export HICORTEX_CONFIDENTIAL_MARKER_KEY\n` +
64
+ ` or add confidentialMarkerKey to ~/.hicortex/config.json — then re-run this command.`);
65
+ }
66
+ /** One timeout for both provisioning calls — a foreground CLI command waits, but not forever. */
67
+ const MARKER_KEY_TIMEOUT_MS = 10000;
68
+ /**
69
+ * The production transport (#616): resolveConfig() — the SAME resolution every
70
+ * other client-side fetch uses (client mode → config.serverUrl, else
71
+ * localhost:port, + authToken) — so the provisioning call and the nightly's
72
+ * capture POST can never disagree about which server owns the key. null when
73
+ * there is no usable config (fresh machine, no init): the caller refuses.
74
+ *
75
+ * Errors carry the DETAIL (URL, status, cause); the fetch-or-generate ladder
76
+ * in resolveMarkerKey wraps GET failures into the refusal that names the fix.
77
+ * PUT failures surface as their own explicit errors (a refused rotation is
78
+ * not a "no key" refusal — the operator chose a key and the server said no).
79
+ */
80
+ function defaultMarkerKeyTransport() {
81
+ const cfg = (0, learnings_identity_js_1.resolveConfig)();
82
+ if (!cfg)
83
+ return null;
84
+ const headers = { "Content-Type": "application/json" };
85
+ if (cfg.authToken)
86
+ headers["Authorization"] = `Bearer ${cfg.authToken}`;
87
+ const url = `${cfg.serverUrl}/confidential/marker-key`;
88
+ return {
89
+ async get() {
90
+ let resp;
91
+ try {
92
+ resp = await fetch(url, { headers, signal: AbortSignal.timeout(MARKER_KEY_TIMEOUT_MS) });
93
+ }
94
+ catch (e) {
95
+ throw new Error(`could not reach ${cfg.serverUrl} (${e instanceof Error ? e.message : String(e)})`);
96
+ }
97
+ if (!resp.ok) {
98
+ throw new Error(`the server at ${cfg.serverUrl} answered ${resp.status} for /confidential/marker-key ` +
99
+ `(check the auth token, or the server version — the endpoint needs #616+)`);
100
+ }
101
+ let body;
102
+ try {
103
+ body = await resp.json();
104
+ }
105
+ catch {
106
+ body = null;
107
+ }
108
+ // Shape-check the one field we consume — anything else is a version
109
+ // mismatch and must not masquerade as "no key" (which would mint a
110
+ // second key and orphan the first machine's markers).
111
+ if (body === null || typeof body !== "object" ||
112
+ !("key" in body) ||
113
+ (body.key !== null && typeof body.key !== "string")) {
114
+ throw new Error(`unexpected response shape from ${url} — is the server up to date (#616+)?`);
115
+ }
116
+ const key = body.key;
117
+ return { key: key === null ? null : key.trim() || null };
118
+ },
119
+ async put(key) {
120
+ let resp;
121
+ try {
122
+ resp = await fetch(url, {
123
+ method: "PUT",
124
+ headers,
125
+ body: JSON.stringify({ key }),
126
+ signal: AbortSignal.timeout(MARKER_KEY_TIMEOUT_MS),
127
+ });
128
+ }
129
+ catch (e) {
130
+ throw new Error(`[hicortex] confidential: could not reach ${cfg.serverUrl} to set the marker key ` +
131
+ `(${e instanceof Error ? e.message : String(e)}) — nothing was written`);
132
+ }
133
+ if (!resp.ok) {
134
+ // Surface the server's refusal VERBATIM (409 env-shadow, 400 shape)
135
+ // — the operator needs the reason, and nothing was written.
136
+ let reason = resp.statusText;
137
+ try {
138
+ const errBody = await resp.json();
139
+ if (errBody && typeof errBody.error === "string")
140
+ reason = errBody.error;
141
+ }
142
+ catch {
143
+ // non-JSON error body — keep statusText
144
+ }
145
+ throw new Error(`[hicortex] confidential: the server refused the marker key (HTTP ${resp.status}): ${reason} — nothing was written`);
146
+ }
147
+ },
148
+ };
149
+ }
150
+ /**
151
+ * Save the key into `<hicortex-home>/config.json` (#616): after a fetch or a
152
+ * generate-and-register, the NEXT run takes the offline fast path (no server
153
+ * needed). persistConfigUpdates is load-strict → merge → save: unrelated keys
154
+ * (authToken, serverUrl, …) survive, and a malformed existing config THROWS
155
+ * instead of being stubbed. On a server box this is the same file the
156
+ * endpoint's PUT just wrote — idempotent.
157
+ */
158
+ function persistLocalMarkerKey(key) {
159
+ (0, init_js_1.persistConfigUpdates)((0, node_path_1.join)((0, paths_js_1.hicortexHome)(), "config.json"), { confidentialMarkerKey: key });
160
+ }
161
+ /**
162
+ * Write (or remove) the confidential marker. Fails EXPLICITLY when the
163
+ * target folder does not exist — a typo'd path must not silently mark the
164
+ * wrong directory (or nothing). `--off` is deliberately lenient: removing an
165
+ * absent marker is a no-op success (convergent, like the uninstall paths).
166
+ *
167
+ * ASYNC since #616: the key may need a server round-trip (fetch or
168
+ * generate-and-register) when no local layer holds it. The only callers are
169
+ * the cli.ts `confidential` case and tests.
170
+ *
171
+ * Note the classification asymmetry, mirrored in the output: marking takes
172
+ * effect from the NEXT capture (the nightly reads the marker then), and
173
+ * unmarking never demotes — already-captured memories keep their stamp (the
174
+ * #332 never-demotes rule; history heals via `hicortex backfill-privacy`
175
+ * only toward confidential).
176
+ */
177
+ async function runConfidentialCommand(opts = {}) {
178
+ const folder = (0, node_path_1.resolve)(opts.path ?? process.cwd());
179
+ let isDir = false;
180
+ try {
181
+ isDir = (0, node_fs_1.statSync)(folder).isDirectory();
182
+ }
183
+ catch {
184
+ // fall through to the explicit error below
185
+ }
186
+ if (!isDir) {
187
+ throw new Error(`[hicortex] confidential: no such directory: ${folder} — pass the workspace folder's path`);
188
+ }
189
+ const markerPath = (0, node_path_1.join)(folder, exports.CONFIDENTIAL_MARKER_FILENAME);
190
+ if (opts.off) {
191
+ try {
192
+ (0, node_fs_1.unlinkSync)(markerPath);
193
+ console.log(`[hicortex] Removed the confidential marker: ${markerPath}`);
194
+ console.log("[hicortex] Already-captured memories keep their classification (nothing is ever demoted).");
195
+ }
196
+ catch {
197
+ console.log(`[hicortex] No confidential marker at ${markerPath} — nothing to remove.`);
198
+ }
199
+ return { folder, markerPath, marked: false };
200
+ }
201
+ // #616 key resolution ladder (each layer documented at its check):
202
+ const key = await resolveMarkerKey(opts);
203
+ // Single line, newline-terminated — exactly the shape the capture walk
204
+ // relays (readConfidentialMarker takes the trimmed first line). The key
205
+ // value is deliberately NOT echoed in the output lines below.
206
+ (0, node_fs_1.writeFileSync)(markerPath, key + "\n");
207
+ console.log(`[hicortex] Marked confidential: ${folder}`);
208
+ console.log("[hicortex] The marker carries this machine's confidentialMarkerKey; the next nightly capture in this");
209
+ console.log("[hicortex] folder (or any child folder) stamps its memories confidential when the server's key matches.");
210
+ console.log("[hicortex] To backfill HISTORY, add the folder to confidentialPaths on the server and run: hicortex backfill-privacy");
211
+ return { folder, markerPath, marked: true };
212
+ }
213
+ /**
214
+ * The #616 key ladder, in order:
215
+ *
216
+ * 1. `opts.key` (CLI `--key`) → ROTATION: PUT the chosen value to the server
217
+ * first (a refused PUT — e.g. 409 under the server's env override —
218
+ * surfaces verbatim and writes nothing), then persist locally.
219
+ * 2. env `HICORTEX_CONFIDENTIAL_MARKER_KEY` → the operator's manual layer:
220
+ * write, no network, no config persist (mirroring it under an explicit
221
+ * override would create drift).
222
+ * 3. local config `confidentialMarkerKey` → the offline fast path (yesterday's
223
+ * provisioning result): write, no network.
224
+ * 4. none of the above → the server: GET /confidential/marker-key. A key →
225
+ * reuse it (AC-2: the second machine never mints a second key). null →
226
+ * generate `cmark-` + 32 hex and PUT it (AC-1: first machine ever). Both
227
+ * branches persist locally for the next run's fast path.
228
+ *
229
+ * A set-but-blank layer is no key at every layer (blank never validates
230
+ * server-side) and the ladder falls through. No transport obtainable (no
231
+ * config at all) or an unreachable server → the refusal error naming the
232
+ * fixes — never an inert marker.
233
+ */
234
+ async function resolveMarkerKey(opts) {
235
+ // 1. Explicit --key = rotation (push to the server, then keep locally).
236
+ const explicit = typeof opts.key === "string" && opts.key.trim() ? opts.key.trim() : null;
237
+ if (explicit) {
238
+ const transport = opts.transport ?? defaultMarkerKeyTransport();
239
+ if (!transport) {
240
+ throw markerKeyRefusal("rotating with --key needs the server (the new value is registered there first) — " +
241
+ "no Hicortex server is configured on this machine");
242
+ }
243
+ await transport.put(explicit); // refusal surfaces verbatim; nothing written
244
+ persistLocalMarkerKey(explicit);
245
+ console.log("[hicortex] Registered the new confidentialMarkerKey with the server — markers carrying a previous");
246
+ console.log("[hicortex] key now stamp standard (re-run this command on machines that marked folders before).");
247
+ return explicit;
248
+ }
249
+ // 2. The env layer — operator-managed, offline, never mirrored into config.
250
+ const env = process.env.HICORTEX_CONFIDENTIAL_MARKER_KEY;
251
+ if (typeof env === "string" && env.trim())
252
+ return env.trim();
253
+ // 3. The local config layer — yesterday's provisioning result, offline.
254
+ // (loadConfigStrict THROWS on a broken config rather than reading "no
255
+ // key" off a file it could not parse — surfaced by the caller.)
256
+ const { config } = (0, init_js_1.loadConfigStrict)((0, node_path_1.join)((0, paths_js_1.hicortexHome)(), "config.json"));
257
+ const local = (0, config_read_js_1.readStringConfig)(config, "confidentialMarkerKey");
258
+ if (local)
259
+ return local;
260
+ // 4. The server: fetch, or generate-and-register.
261
+ const transport = opts.transport ?? defaultMarkerKeyTransport();
262
+ if (!transport) {
263
+ throw markerKeyRefusal("no confidentialMarkerKey on this machine and no Hicortex server configured to fetch one from");
264
+ }
265
+ let got;
266
+ try {
267
+ got = await transport.get();
268
+ }
269
+ catch (e) {
270
+ // Unreachable / refused / bad shape — one refined refusal naming the fix
271
+ // (never an inert marker, and never a raw network error without one).
272
+ throw markerKeyRefusal(e instanceof Error ? e.message : String(e));
273
+ }
274
+ if (got.key) {
275
+ persistLocalMarkerKey(got.key);
276
+ console.log("[hicortex] Using the server's existing confidentialMarkerKey (saved to this machine's config for offline use).");
277
+ return got.key;
278
+ }
279
+ const generated = `cmark-${(0, node_crypto_1.randomBytes)(16).toString("hex")}`; // single line, 32 hex
280
+ await transport.put(generated); // refusal surfaces; nothing written
281
+ persistLocalMarkerKey(generated);
282
+ console.log("[hicortex] Generated a new confidentialMarkerKey and registered it with the server (saved locally).");
283
+ console.log("[hicortex] Other machines running this command now fetch this key instead of generating their own.");
284
+ return generated;
285
+ }
@@ -43,6 +43,17 @@ export declare function resolveNightlyLlmCallBudget(config: Record<string, unkno
43
43
  export declare const CONSOLIDATE_LINK_THRESHOLD = 0.75;
44
44
  /** Max link candidates kept per memory (highest-cosine neighbors first). */
45
45
  export declare const CONSOLIDATE_LINK_TOP_K = 3;
46
+ /**
47
+ * Initial vector window for link-candidate discovery (#602). The fetch is
48
+ * UNFILTERED by class (see CONSOLIDATE_LINK_FETCH_MAX_K for why), so this is
49
+ * just the starting width of the adaptive escalation below.
50
+ */
51
+ export declare const CONSOLIDATE_LINK_FETCH_K = 10;
52
+ /**
53
+ * Hard cap on the escalated vector window (#602) — the same over-fetch cap
54
+ * #192 established for filtered recall queries.
55
+ */
56
+ export declare const CONSOLIDATE_LINK_FETCH_MAX_K = 200;
46
57
  /**
47
58
  * Minimum COSINE similarity for a CROSS-PROJECT link candidate.
48
59
  *
@@ -231,9 +242,29 @@ export interface LinkCandidate {
231
242
  }
232
243
  /**
233
244
  * Discovery: find link candidates for one memory given its embedding.
234
- * Top-10 vector neighbors (excluding self), keep the CONSOLIDATE_LINK_TOP_K
235
- * highest-cosine neighbors above CONSOLIDATE_LINK_THRESHOLD, pre-compute the
236
- * heuristic relationship type.
245
+ * Vector neighbors (excluding self), keep the CONSOLIDATE_LINK_TOP_K
246
+ * highest-cosine SAME-CLASS neighbors above CONSOLIDATE_LINK_THRESHOLD,
247
+ * pre-compute the heuristic relationship type.
248
+ *
249
+ * #602 — ADAPTIVE CLASS-SCOPED FETCH. The pre-#602 code fetched a fixed
250
+ * top-10 UNFILTERED window and then dropped cross-class neighbors in the
251
+ * loop — the #192 filtered-over-fetch defect class. Starvation math: in a
252
+ * 22K-standard / 1K-confidential corpus a confidential memory's 10 nearest
253
+ * neighbors are usually ALL standard (the classes are topically distinct but
254
+ * the majority class is 22× larger), so the confidential pool systematically
255
+ * under-linked — its same-class neighbors never made the window. The fix
256
+ * escalates the window (k × 4 per step, capped at CONSOLIDATE_LINK_FETCH_MAX_K
257
+ * = the #192 over-fetch cap) until the window holds CONSOLIDATE_LINK_TOP_K
258
+ * same-class neighbors, comes back short (no more rows may exist), or hits
259
+ * the cap. Balanced corpora do ZERO extra queries (the first window already
260
+ * holds 3+ same-class neighbors).
261
+ *
262
+ * WHY the class is not denormalized into the vec0 table (a WHERE clause
263
+ * would make this a one-fetch query): memory_vectors carries only id +
264
+ * embedding, and privacy is MUTABLE post-insert (`hicortex backfill-privacy`
265
+ * and REST /update can reclassify a row) — a vec0-side class column would go
266
+ * stale the moment a row's class changed without a re-embed. The class is
267
+ * read live from memories, so it can never disagree with the row.
237
268
  *
238
269
  * Shared between the nightly `stageLinks` (which embeds via embedFn) and
239
270
  * `hicortex relink` (which reuses stored embeddings from memory_vectors).
@@ -38,7 +38,7 @@ var __importStar = (this && this.__importStar) || (function () {
38
38
  };
39
39
  })();
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
- exports.DEFAULT_MEMORY_SOFT_CAP = exports.BudgetTracker = exports.REFLECTION_CONTRADICTION_MIN_COSINE = exports.l2ToCosine = exports.CROSS_PROJECT_LINK_THRESHOLD = exports.CONSOLIDATE_LINK_TOP_K = exports.CONSOLIDATE_LINK_THRESHOLD = exports.DEFAULT_NIGHTLY_LLM_CALL_BUDGET = void 0;
41
+ exports.DEFAULT_MEMORY_SOFT_CAP = exports.BudgetTracker = exports.REFLECTION_CONTRADICTION_MIN_COSINE = exports.l2ToCosine = exports.CROSS_PROJECT_LINK_THRESHOLD = exports.CONSOLIDATE_LINK_FETCH_MAX_K = exports.CONSOLIDATE_LINK_FETCH_K = exports.CONSOLIDATE_LINK_TOP_K = exports.CONSOLIDATE_LINK_THRESHOLD = exports.DEFAULT_NIGHTLY_LLM_CALL_BUDGET = void 0;
42
42
  exports.resolveNightlyLlmCallBudget = resolveNightlyLlmCallBudget;
43
43
  exports.isContradictionCandidate = isContradictionCandidate;
44
44
  exports.warnUnmeteredTokensRun = warnUnmeteredTokensRun;
@@ -120,6 +120,17 @@ const CONSOLIDATE_PRUNE_MIN_AGE_DAYS = 90;
120
120
  exports.CONSOLIDATE_LINK_THRESHOLD = 0.75;
121
121
  /** Max link candidates kept per memory (highest-cosine neighbors first). */
122
122
  exports.CONSOLIDATE_LINK_TOP_K = 3;
123
+ /**
124
+ * Initial vector window for link-candidate discovery (#602). The fetch is
125
+ * UNFILTERED by class (see CONSOLIDATE_LINK_FETCH_MAX_K for why), so this is
126
+ * just the starting width of the adaptive escalation below.
127
+ */
128
+ exports.CONSOLIDATE_LINK_FETCH_K = 10;
129
+ /**
130
+ * Hard cap on the escalated vector window (#602) — the same over-fetch cap
131
+ * #192 established for filtered recall queries.
132
+ */
133
+ exports.CONSOLIDATE_LINK_FETCH_MAX_K = 200;
123
134
  /**
124
135
  * Minimum COSINE similarity for a CROSS-PROJECT link candidate.
125
136
  *
@@ -476,6 +487,15 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
476
487
  opts.onBatch?.(0, batch.memories.length);
477
488
  }
478
489
  }
490
+ // #602: the held count previously landed ONLY in the return value — a
491
+ // confidential pool silently unscored for weeks was invisible in
492
+ // nightly.log. ONE aggregate warn (not one per batch), mirroring
493
+ // stageReflection's held line below. Dry runs never reach the skip branch
494
+ // (they continue before client resolution), so no warn fires on dryRun.
495
+ if (skippedConfidential > 0) {
496
+ console.warn(`[hicortex] importance: ${skippedConfidential} confidential memories held — ` +
497
+ `no confidential model configured (llmConfidentialBaseUrl/ApiKey). Retried next run.`);
498
+ }
479
499
  return {
480
500
  scored,
481
501
  failed,
@@ -555,7 +575,10 @@ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
555
575
  const recentBlock = recentLessons.length > 0
556
576
  ? recentLessons.map(l => `- ${l.content.slice(0, 150)}`).join("\n")
557
577
  : undefined;
558
- const prompt = (0, prompts_js_1.reflection)(memoriesBlock, recentBlock);
578
+ // #602: pool-aware prompt — the confidential pool's reflection prompt swaps
579
+ // ONLY the privacy line (personal domains allowed at the process level;
580
+ // secrets still never), so the pool can actually generate its lessons.
581
+ const prompt = (0, prompts_js_1.reflection)(memoriesBlock, recentBlock, pool);
559
582
  if (dryRun) {
560
583
  return { generated: 0, skipped: false };
561
584
  }
@@ -567,6 +590,10 @@ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
567
590
  budget.recordUsage("reflection", r.usage);
568
591
  const lessons = parseJsonLenient(r.text, []);
569
592
  if (!Array.isArray(lessons)) {
593
+ // #602: this branch was silent — a pool could fail every night with
594
+ // nothing in nightly.log. All logging below sits after the dryRun
595
+ // early-return, so a dry run logs nothing by construction.
596
+ console.warn(`[hicortex] reflection (${pool} pool): LLM reply was not a JSON array — no lessons stored (retried next run)`);
570
597
  return { generated: 0, failed: true };
571
598
  }
572
599
  let generated = 0;
@@ -647,13 +674,23 @@ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
647
674
  generated++;
648
675
  }
649
676
  }
650
- catch {
651
- // Failed to store lesson
677
+ catch (err) {
678
+ // #602: was silent — an embed/insert failure dropped the lesson with
679
+ // no trace. Tagged with the pool so the nightly log shows WHICH pool
680
+ // is losing lessons.
681
+ console.warn(`[hicortex] reflection (${pool} pool): failed to store a lesson (embed/insert error): ` +
682
+ `${lessonText.slice(0, 80)} — ${err instanceof Error ? err.message : String(err)}`);
652
683
  }
653
684
  }
685
+ // #602: ONE per-pool success line so a healthy-empty (0 lessons from a
686
+ // clean cohort) is distinguishable from a broken run in nightly.log.
687
+ console.log(`[hicortex] reflection (${pool} pool): generated ${generated} lessons`);
654
688
  return { generated, failed: false };
655
689
  }
656
690
  catch {
691
+ // #602: was silent — the pool's whole run could fail (endpoint down,
692
+ // timeout) and nightly.log showed nothing but the report's failed flag.
693
+ console.warn(`[hicortex] reflection (${pool} pool): LLM call failed — no lessons generated (retried next run)`);
657
694
  return { generated: 0, failed: true };
658
695
  }
659
696
  }
@@ -1040,21 +1077,56 @@ async function stageDomainCuration(db, llm, budget, dryRun, stateDir) {
1040
1077
  }
1041
1078
  /**
1042
1079
  * Discovery: find link candidates for one memory given its embedding.
1043
- * Top-10 vector neighbors (excluding self), keep the CONSOLIDATE_LINK_TOP_K
1044
- * highest-cosine neighbors above CONSOLIDATE_LINK_THRESHOLD, pre-compute the
1045
- * heuristic relationship type.
1080
+ * Vector neighbors (excluding self), keep the CONSOLIDATE_LINK_TOP_K
1081
+ * highest-cosine SAME-CLASS neighbors above CONSOLIDATE_LINK_THRESHOLD,
1082
+ * pre-compute the heuristic relationship type.
1083
+ *
1084
+ * #602 — ADAPTIVE CLASS-SCOPED FETCH. The pre-#602 code fetched a fixed
1085
+ * top-10 UNFILTERED window and then dropped cross-class neighbors in the
1086
+ * loop — the #192 filtered-over-fetch defect class. Starvation math: in a
1087
+ * 22K-standard / 1K-confidential corpus a confidential memory's 10 nearest
1088
+ * neighbors are usually ALL standard (the classes are topically distinct but
1089
+ * the majority class is 22× larger), so the confidential pool systematically
1090
+ * under-linked — its same-class neighbors never made the window. The fix
1091
+ * escalates the window (k × 4 per step, capped at CONSOLIDATE_LINK_FETCH_MAX_K
1092
+ * = the #192 over-fetch cap) until the window holds CONSOLIDATE_LINK_TOP_K
1093
+ * same-class neighbors, comes back short (no more rows may exist), or hits
1094
+ * the cap. Balanced corpora do ZERO extra queries (the first window already
1095
+ * holds 3+ same-class neighbors).
1096
+ *
1097
+ * WHY the class is not denormalized into the vec0 table (a WHERE clause
1098
+ * would make this a one-fetch query): memory_vectors carries only id +
1099
+ * embedding, and privacy is MUTABLE post-insert (`hicortex backfill-privacy`
1100
+ * and REST /update can reclassify a row) — a vec0-side class column would go
1101
+ * stale the moment a row's class changed without a re-embed. The class is
1102
+ * read live from memories, so it can never disagree with the row.
1046
1103
  *
1047
1104
  * Shared between the nightly `stageLinks` (which embeds via embedFn) and
1048
1105
  * `hicortex relink` (which reuses stored embeddings from memory_vectors).
1049
1106
  */
1050
1107
  function discoverLinkCandidates(db, mem, embedding) {
1051
- const neighbors = storage.vectorSearch(db, embedding, 10, [mem.id]);
1052
- const candidates = [];
1053
1108
  // #332: class-pure link discovery — a candidate NEVER crosses the circle
1054
1109
  // (no memory_links row joins the two classes; a pre-#332 cross-class link
1055
1110
  // stays as historical data, but the stage creates none). NULL privacy (a
1056
1111
  // pre-v27 row) reads standard, the same normalization everywhere else uses.
1057
1112
  const memClass = mem.privacy === "confidential" ? "confidential" : "standard";
1113
+ const isSameClass = (m) => (m.privacy === "confidential" ? "confidential" : "standard") === memClass;
1114
+ // The excluded self (distance 0 — always the nearest stored row) occupies
1115
+ // one seat of the raw window, so each fetch asks for k + 1: a FULL window
1116
+ // then yields exactly k non-self neighbors and `neighbors.length === k`
1117
+ // means "more rows may exist beyond it".
1118
+ const fetchWindow = (k) => storage.vectorSearch(db, embedding, k + 1, [mem.id]);
1119
+ // #602 adaptive escalation: widen while the window starves the memory's
1120
+ // own class AND the corpus may hold more rows beyond it.
1121
+ let k = exports.CONSOLIDATE_LINK_FETCH_K;
1122
+ let neighbors = fetchWindow(k);
1123
+ while (neighbors.filter(isSameClass).length < exports.CONSOLIDATE_LINK_TOP_K &&
1124
+ neighbors.length === k &&
1125
+ k < exports.CONSOLIDATE_LINK_FETCH_MAX_K) {
1126
+ k = Math.min(k * 4, exports.CONSOLIDATE_LINK_FETCH_MAX_K);
1127
+ neighbors = fetchWindow(k);
1128
+ }
1129
+ const candidates = [];
1058
1130
  // vectorSearch orders by L2 distance ascending (`ORDER BY distance` in
1059
1131
  // storage.ts), and cosine is monotonically decreasing in L2 distance for
1060
1132
  // normalized vectors — so iterating in order and stopping at TOP_K keeps
@@ -1062,7 +1134,9 @@ function discoverLinkCandidates(db, mem, embedding) {
1062
1134
  for (const neighbor of neighbors) {
1063
1135
  if (candidates.length >= exports.CONSOLIDATE_LINK_TOP_K)
1064
1136
  break;
1065
- if ((neighbor.privacy === "confidential" ? "confidential" : "standard") !== memClass)
1137
+ // The in-loop class filter stays: it enforces purity (#332) and top-K
1138
+ // cosine order regardless of how wide the escalated window got (#602).
1139
+ if (!isSameClass(neighbor))
1066
1140
  continue;
1067
1141
  // sqlite-vec vec0 `distance` is L2, not a similarity. Embeddings are
1068
1142
  // L2-normalized (embedder.ts, normalize: true), so cos = 1 − d²/2.
@@ -177,6 +177,23 @@ export interface DashboardSnapshot {
177
177
  run_at: string;
178
178
  metrics: DashboardMetrics;
179
179
  }
180
+ /**
181
+ * #601 — the confidential circle's VISIBILITY block: which agents are
182
+ * inner-circle and, for the observed ones, how many confidential memories
183
+ * they carry. Purely informational (the dashboard is NOT gated — confidential
184
+ * content stays visible on the console by the standing ruling); the page
185
+ * renders amber pills on circle agents, nothing on standard ones.
186
+ */
187
+ export interface AgentCircle {
188
+ /** The sanitized roster (resolveConfidentialAgents — the one agent-id
189
+ * namespace shared with `?agent=` and identityAgents). */
190
+ roster: string[];
191
+ /** OBSERVED source_agent values (e.g. "hermes/nano") that match the
192
+ * roster, each mapped to that agent's confidential memory count.
193
+ * Membership is KEY PRESENCE (a rostered agent observed with 0
194
+ * confidential rows is a member at 0); NULL source_agent never matches. */
195
+ members: Record<string, number>;
196
+ }
180
197
  /** The /dashboard/data response — the full payload the page renders. */
181
198
  export interface DashboardData {
182
199
  /**
@@ -257,6 +274,9 @@ export interface DashboardData {
257
274
  * module doc for why recall traffic can never attribute). ALWAYS present;
258
275
  * empty arrays when nothing is recorded (fresh install). The page degrades
259
276
  * to the phase-2 rendering when the block is absent (pre-phase-3 server).
277
+ * #601 adds `circle` — the confidential-circle visibility block (roster +
278
+ * observed members with counts), also always present; the page degrades to
279
+ * the exact prior rendering when the key is absent (pre-#601 server).
260
280
  */
261
281
  fleet: {
262
282
  pauses: Array<{
@@ -270,6 +290,7 @@ export interface DashboardData {
270
290
  last_seen: string;
271
291
  last_outcome: string;
272
292
  }>;
293
+ circle: AgentCircle;
273
294
  };
274
295
  /**
275
296
  * #476 — the Memory Precision card: Level 1 (pushed-index precision
@@ -476,6 +497,17 @@ export declare function writeSnapshot(db: Database.Database, runAt: string, delt
476
497
  * so backfilled rows OMIT it (the page treats undefined as "no data").
477
498
  */
478
499
  export declare function backfillSnapshots(db: Database.Database): number;
500
+ /**
501
+ * #601 — compute fleet.circle: the sanitized roster plus the OBSERVED
502
+ * source_agent values that match it, each with its confidential memory count.
503
+ * Reuses the intake path's own decision core (resolveConfidentialAgents +
504
+ * isConfidentialSourceAgent from classification.ts — one id namespace, one
505
+ * match rule; no second matcher to drift). One GROUP BY over memories:
506
+ * membership is observed-and-rostered (a rostered agent seen with only
507
+ * standard rows is a member at 0), the value is the confidential row count.
508
+ * Pure: takes a db + config, returns the block; no side effects.
509
+ */
510
+ export declare function readAgentCircle(db: Database.Database, config: Record<string, unknown> | null | undefined): AgentCircle;
479
511
  /**
480
512
  * The pure data handler for GET /dashboard/data. Reads query params
481
513
  * (`range`, `date`, `digestLimit`) off the request, returns the DashboardData