@gamaze/hicortex 0.26.3 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +21 -13
  2. package/assets/dashboard.html +95 -3
  3. package/dist/backfill-privacy.d.ts +109 -0
  4. package/dist/backfill-privacy.js +304 -0
  5. package/dist/capture.d.ts +60 -0
  6. package/dist/capture.js +90 -1
  7. package/dist/classification.d.ts +315 -0
  8. package/dist/classification.js +525 -0
  9. package/dist/classify-domains.js +24 -7
  10. package/dist/cli.js +80 -0
  11. package/dist/cluster.d.ts +15 -8
  12. package/dist/cluster.js +10 -3
  13. package/dist/confidential-marker.d.ts +103 -0
  14. package/dist/confidential-marker.js +285 -0
  15. package/dist/consolidate.d.ts +65 -5
  16. package/dist/consolidate.js +275 -48
  17. package/dist/dashboard.d.ts +32 -0
  18. package/dist/dashboard.js +33 -0
  19. package/dist/db.js +49 -1
  20. package/dist/dedup.d.ts +5 -3
  21. package/dist/dedup.js +26 -12
  22. package/dist/distill-queue.d.ts +34 -1
  23. package/dist/distill-queue.js +57 -10
  24. package/dist/graph.d.ts +28 -3
  25. package/dist/graph.js +46 -4
  26. package/dist/hermes-transcript-reader.js +5 -0
  27. package/dist/init.d.ts +18 -9
  28. package/dist/init.js +111 -81
  29. package/dist/marker-key-api.d.ts +79 -0
  30. package/dist/marker-key-api.js +96 -0
  31. package/dist/mcp-server.js +317 -32
  32. package/dist/nightly.js +36 -7
  33. package/dist/opencode-transcript-reader.js +3 -0
  34. package/dist/pi-transcript-reader.js +3 -0
  35. package/dist/prompts.d.ts +33 -1
  36. package/dist/prompts.js +37 -2
  37. package/dist/recall-index.d.ts +19 -9
  38. package/dist/recall-index.js +14 -4
  39. package/dist/recall-precision.js +3 -1
  40. package/dist/reconsolidation.d.ts +10 -0
  41. package/dist/reconsolidation.js +80 -17
  42. package/dist/redact.d.ts +9 -1
  43. package/dist/redact.js +32 -1
  44. package/dist/rescore-importance.js +21 -4
  45. package/dist/retrieval.d.ts +23 -6
  46. package/dist/retrieval.js +41 -15
  47. package/dist/seed-lesson.js +3 -1
  48. package/dist/storage.d.ts +23 -4
  49. package/dist/storage.js +43 -11
  50. package/dist/transcript-reader.d.ts +10 -0
  51. package/dist/transcript-reader.js +13 -0
  52. package/dist/type-classify.js +22 -7
  53. package/dist/types.d.ts +117 -15
  54. package/dist/uninstall.js +6 -5
  55. package/hermes-plugin/hicortex/README.md +4 -0
  56. package/hermes-plugin/hicortex/client.py +36 -9
  57. package/hermes-plugin/hicortex/plugin.yaml +1 -1
  58. package/hermes-plugin/hicortex/provider.py +28 -6
  59. package/package.json +1 -1
  60. package/server.json +2 -2
@@ -0,0 +1,525 @@
1
+ "use strict";
2
+ /**
3
+ * The confidential circle (#332) — the pure decision core for the two-level
4
+ * memory classification (`standard` | `confidential`, carried by
5
+ * `memories.privacy`; see MemoryPrivacy in types.ts).
6
+ *
7
+ * The model, in one paragraph: an operator lists inner-circle agents in
8
+ * config (`confidentialAgents`, the same agent-id namespace as
9
+ * `identityAgents` / `?agent=`). Captures whose `source_agent` is rostered
10
+ * are stamped `confidential` at intake — server-derived, deterministic, by
11
+ * birthplace; never a content judgment (content classification was rejected,
12
+ * #197) and never client-declared. The workspace marker (#609/#614) is
13
+ * client-RELAYED but server-VALIDATED: the marker file carries the owner-set
14
+ * `confidentialMarkerKey` as its content, compared timing-safe at intake —
15
+ * marker content without the key never stamps (the client-writable
16
+ * classification channel #614 closes; an unkeyed install ignores markers
17
+ * entirely, fail-closed both directions). Every agent-facing read path accepts an
18
+ * optional `agent` requester id: absent or unknown = non-member = HARD OMIT
19
+ * of confidential rows (fail-closed both ends — unrostered sources are
20
+ * standard, unknown requesters are non-members). The circle is ADDITIVE:
21
+ * members see both pools. Every LLM touch of confidential text routes to a
22
+ * separately configured second model (`llmConfidential*` config keys /
23
+ * `HICORTEX_LLM_CONFIDENTIAL_*` env) — when that model is absent, the work
24
+ * HOLDS (queue stays, deliveries refuse), never falls back to the main
25
+ * model. An install that configures nothing sees zero change: no roster, no
26
+ * confidential rows, no warning, no second client.
27
+ *
28
+ * All functions here are pure (no DB, no HTTP): the handlers in mcp-server.ts
29
+ * and the pipeline stages consume them, and the tests exercise the decisions
30
+ * directly.
31
+ */
32
+ Object.defineProperty(exports, "__esModule", { value: true });
33
+ exports.resolveConfidentialAgents = resolveConfidentialAgents;
34
+ exports.isConfidentialSourceAgent = isConfidentialSourceAgent;
35
+ exports.resolveConfidentialPaths = resolveConfidentialPaths;
36
+ exports.matchesConfidentialPath = matchesConfidentialPath;
37
+ exports.safeMarkerKeyEqual = safeMarkerKeyEqual;
38
+ exports.resolveConfidentialMarkerKey = resolveConfidentialMarkerKey;
39
+ exports.deriveIntakePrivacy = deriveIntakePrivacy;
40
+ exports.isCircleMember = isCircleMember;
41
+ exports.resolveConfidentialLlmConfig = resolveConfidentialLlmConfig;
42
+ exports.buildConfidentialLlm = buildConfidentialLlm;
43
+ exports.resolveLlmPair = resolveLlmPair;
44
+ exports.clientForPool = clientForPool;
45
+ exports.warnIfCircleUnconfigured = warnIfCircleUnconfigured;
46
+ exports.confidentialMarkerKeyNote = confidentialMarkerKeyNote;
47
+ exports.resetRefusedMarkerWarn = resetRefusedMarkerWarn;
48
+ exports.warnRefusedMarker = warnRefusedMarker;
49
+ const node_crypto_1 = require("node:crypto");
50
+ const identity_store_js_1 = require("./identity-store.js");
51
+ const llm_js_1 = require("./llm.js");
52
+ const config_read_js_1 = require("./config-read.js");
53
+ // ---------------------------------------------------------------------------
54
+ // Roster
55
+ // ---------------------------------------------------------------------------
56
+ /**
57
+ * Resolve the `confidentialAgents` config value into a clean roster of agent
58
+ * ids. Each entry is sanitized EXACTLY like `?agent=` (sanitizeAgentId —
59
+ * lowercase, collapse invalid runs to `-`, allowlist-validated) so the roster,
60
+ * the wire `agent` param, and capture's `<harness>/<id>` stamps live in one
61
+ * id namespace. Entries that sanitize to null are dropped and their raw
62
+ * values returned in `dropped` for a one-time boot warning (the
63
+ * resolveIdentityAgents pattern — a typo must surface, not silently drop an
64
+ * agent out of the circle).
65
+ */
66
+ function resolveConfidentialAgents(config) {
67
+ const raw = config?.confidentialAgents;
68
+ if (!Array.isArray(raw))
69
+ return { roster: [], dropped: [] };
70
+ const roster = [];
71
+ const dropped = [];
72
+ for (const entry of raw) {
73
+ if (typeof entry !== "string") {
74
+ dropped.push(String(entry));
75
+ continue;
76
+ }
77
+ const id = (0, identity_store_js_1.sanitizeAgentId)(entry);
78
+ if (id && !roster.includes(id))
79
+ roster.push(id);
80
+ else if (!id)
81
+ dropped.push(entry);
82
+ }
83
+ return { roster, dropped };
84
+ }
85
+ /**
86
+ * Normalize a capture-side `source_agent` for roster matching. Capture stamps
87
+ * harness-qualified ids (`hermes/nano`, `claude-code/myproject`), while the
88
+ * roster carries bare agent ids (the same ids the read side receives as
89
+ * `agent`) — ONE config list, no read-ids/capture-ids sync hazard. The match
90
+ * is exact, or exact after stripping the FIRST path segment (so `hermes/nano`
91
+ * matches roster `nano`, and a future `anything/nano` matches too — generic
92
+ * prefix, not a per-harness table). Case-insensitive on the id half via the
93
+ * roster's sanitized (lowercased) form.
94
+ */
95
+ function isConfidentialSourceAgent(sourceAgent, roster) {
96
+ if (!sourceAgent || roster.length === 0)
97
+ return false;
98
+ const agent = sourceAgent.toLowerCase();
99
+ if (roster.includes(agent))
100
+ return true;
101
+ const slash = agent.indexOf("/");
102
+ if (slash < 0)
103
+ return false;
104
+ const bare = agent.slice(slash + 1);
105
+ const rest = bare.indexOf("/");
106
+ // Strip only the FIRST segment — `hermes/nano` → `nano`, but
107
+ // `a/b/nano` → `b/nano` (never a deep-suffix match; capture ids are
108
+ // single-qualified by construction).
109
+ return rest < 0 && roster.includes(bare);
110
+ }
111
+ /**
112
+ * Shared normalization for pattern and path sides: NFC, `\` → `/`, lowercase
113
+ * (the case-insensitive compare). Pure string prep — no fs, no symlinks.
114
+ */
115
+ function normalizePathForMatch(p) {
116
+ return p.normalize("NFC").replace(/\\/g, "/").toLowerCase();
117
+ }
118
+ /** Glob metacharacters a LITERAL segment must not contain (`*` alone is the
119
+ * one-segment wildcard; anything else is a typo, not a form). */
120
+ const SEGMENT_METACHARS = /[*?[\]{}]/;
121
+ /**
122
+ * Compile one raw config entry into a pattern, or null when the entry is not
123
+ * one of the three forms. Dropped kinds: relative entries (nothing to anchor
124
+ * a match on), a double-star anywhere but the end, a star that is not a whole
125
+ * segment (partial-segment wildcards), other metacharacters, blank, and
126
+ * ~user-style entries (whose home?). Dropped entries are reported by name at
127
+ * boot — a typo must surface, never silently match nothing.
128
+ */
129
+ function compileConfidentialPath(entry) {
130
+ const trimmed = entry.trim();
131
+ if (!trimmed)
132
+ return null;
133
+ let s = trimmed;
134
+ let home = false;
135
+ if (s.startsWith("~")) {
136
+ if (s === "~" || s.startsWith("~/")) {
137
+ home = true;
138
+ s = s === "~" ? "" : s.slice(2);
139
+ }
140
+ else {
141
+ return null; // "~user/…" — whose home? Not one of the forms.
142
+ }
143
+ }
144
+ if (!home && !s.startsWith("/"))
145
+ return null; // relative — no anchor
146
+ let subtree = false;
147
+ if (s.endsWith("/**")) {
148
+ subtree = true;
149
+ s = s.slice(0, -3);
150
+ }
151
+ if (s.includes("**"))
152
+ return null; // ** mid-path (incl. a second trailing one)
153
+ const segments = normalizePathForMatch(s)
154
+ .split("/")
155
+ .filter((seg) => seg !== "");
156
+ for (const seg of segments) {
157
+ if (seg === "*")
158
+ continue; // the one-segment wildcard
159
+ if (SEGMENT_METACHARS.test(seg))
160
+ return null;
161
+ }
162
+ return { raw: entry, home, subtree, segments };
163
+ }
164
+ /**
165
+ * Resolve the `confidentialPaths` config value into validated patterns.
166
+ * Entries that do not compile are dropped and their raw values returned in
167
+ * `dropped` for a one-time boot warning (a dropped pattern matches nothing —
168
+ * the operator learns from the log, not from a folder silently staying
169
+ * standard). Duplicates (same raw entry) collapse. Absent/non-array/empty →
170
+ * no patterns, nothing dropped — the zero-change default.
171
+ */
172
+ function resolveConfidentialPaths(config) {
173
+ const raw = config?.confidentialPaths;
174
+ if (!Array.isArray(raw))
175
+ return { patterns: [], dropped: [] };
176
+ const patterns = [];
177
+ const dropped = [];
178
+ for (const entry of raw) {
179
+ if (typeof entry !== "string") {
180
+ dropped.push(String(entry));
181
+ continue;
182
+ }
183
+ const compiled = compileConfidentialPath(entry);
184
+ if (!compiled) {
185
+ dropped.push(entry);
186
+ }
187
+ else if (!patterns.some((p) => p.raw === compiled.raw)) {
188
+ patterns.push(compiled);
189
+ }
190
+ }
191
+ return { patterns, dropped };
192
+ }
193
+ /**
194
+ * The pure matcher: does `workspacePath` fall under any resolved pattern?
195
+ * Empty pattern list matches nothing (and the zero-change default is exactly
196
+ * that); a null/empty path matches nothing (Hermes has no workspace — path
197
+ * signals never fire there). No fs access — callers pass the delivery's
198
+ * declared workspace path; the server decides (the client never knows the
199
+ * patterns).
200
+ */
201
+ function matchesConfidentialPath(workspacePath, patterns) {
202
+ if (!workspacePath || patterns.length === 0)
203
+ return false;
204
+ const pathSegs = normalizePathForMatch(workspacePath)
205
+ .split("/")
206
+ .filter((seg) => seg !== "");
207
+ return patterns.some((p) => patternMatchesSegments(p, pathSegs));
208
+ }
209
+ /** Segment-level match of one compiled pattern against a normalized path. */
210
+ function patternMatchesSegments(p, pathSegs) {
211
+ let rest = pathSegs;
212
+ if (p.home) {
213
+ // Any single home prefix: /home/<user>/… or /Users/<user>/… — structural,
214
+ // so `~/finance` covers the same folder on Linux and macOS fleets.
215
+ if (pathSegs.length < 2)
216
+ return false;
217
+ if (pathSegs[0] !== "home" && pathSegs[0] !== "users")
218
+ return false;
219
+ rest = pathSegs.slice(2);
220
+ }
221
+ // Subtree: the path equals the prefix OR extends it. Exact: lengths equal.
222
+ if (rest.length < p.segments.length)
223
+ return false;
224
+ if (!p.subtree && rest.length !== p.segments.length)
225
+ return false;
226
+ // "*" matches exactly ONE segment — never zero, never two.
227
+ return p.segments.every((seg, i) => seg === "*" || seg === rest[i]);
228
+ }
229
+ // ---------------------------------------------------------------------------
230
+ // The marker key (#614) — server-validated marker content
231
+ // ---------------------------------------------------------------------------
232
+ /**
233
+ * Constant-time marker-content × key comparison (#614) — the safeBearerMatch
234
+ * pattern (viz.ts auth). `crypto.timingSafeEqual` THROWS RangeError on
235
+ * mismatched buffer lengths, so the length check MUST gate the call; the
236
+ * short-circuit leaks only the CONTENT length, which is already visible on
237
+ * the wire (the delivery body carries the content verbatim) — the key bytes
238
+ * are never compared byte-by-byte through a timing side channel. Empty
239
+ * content never matches: an empty (pre-#614) marker file is inert by DESIGN,
240
+ * not by luck of the length gate.
241
+ */
242
+ function safeMarkerKeyEqual(markerContent, key) {
243
+ if (markerContent.length === 0)
244
+ return false;
245
+ const a = Buffer.from(markerContent);
246
+ const b = Buffer.from(key);
247
+ return a.length === b.length && (0, node_crypto_1.timingSafeEqual)(a, b);
248
+ }
249
+ /**
250
+ * Resolve the `confidentialMarkerKey` (#614) — the owner-set secret a
251
+ * workspace marker must carry for its folder to stamp confidential at
252
+ * intake. Precedence: env `HICORTEX_CONFIDENTIAL_MARKER_KEY` OVERRIDES the
253
+ * config value (the env-last-word ops override, so a restart-free rotation
254
+ * or override path exists beside the file), then the config value through
255
+ * the readStringConfig boundary (wrong type warns + null — never coerced;
256
+ * a JSON slip like a number cannot silently arm the arm). Blank/absent →
257
+ * null = the marker arm is INERT: no key configured means client markers
258
+ * are ignored entirely (fail-closed both directions — the empty-marker
259
+ * attack surface ships disabled by default, AC-1). Boot-time like the
260
+ * roster; restart to apply. Distributed like authToken: mirror the server's
261
+ * value into each client machine's config.json (or its env).
262
+ */
263
+ function resolveConfidentialMarkerKey(config) {
264
+ const env = process.env.HICORTEX_CONFIDENTIAL_MARKER_KEY;
265
+ if (typeof env === "string" && env.trim())
266
+ return env.trim();
267
+ return (0, config_read_js_1.readStringConfig)(config ?? {}, "confidentialMarkerKey");
268
+ }
269
+ /**
270
+ * The intake-side derivation: which class a delivery from `sourceAgent`
271
+ * stores as. Fail-closed by construction — anything unattributed or
272
+ * unrostered is `standard` (the global pool).
273
+ *
274
+ * #609/#614 composition invariant: confidential iff roster agent OR server
275
+ * path pattern OR VALIDATED marker content. The marker arm is key-gated
276
+ * (#614): the delivery's relayed marker CONTENT must equal the boot-resolved
277
+ * `confidentialMarkerKey` (timing-safe, server-side — a client-side match is
278
+ * never trusted, the client only relays). An absent key makes every marker
279
+ * inert (the empty-marker client-writable channel is closed), and a
280
+ * present-but-refused marker never reduces a server rule (markers only add,
281
+ * never subtract — safe because a token holder can already POST arbitrary
282
+ * content, the #599 F5 ruling, token = owner). The optional third argument
283
+ * keeps every existing caller byte-identical (no signals = the #332
284
+ * agent-only rule).
285
+ */
286
+ function deriveIntakePrivacy(sourceAgent, roster, signals) {
287
+ if (isConfidentialSourceAgent(sourceAgent, roster))
288
+ return "confidential";
289
+ if (typeof signals?.markerKey === "string" &&
290
+ signals.markerKey.length > 0 &&
291
+ typeof signals?.markerContent === "string" &&
292
+ safeMarkerKeyEqual(signals.markerContent, signals.markerKey)) {
293
+ return "confidential";
294
+ }
295
+ if (matchesConfidentialPath(signals?.workspacePath, signals?.paths ?? [])) {
296
+ return "confidential";
297
+ }
298
+ return "standard";
299
+ }
300
+ /**
301
+ * The read-side membership check: is the requester a circle member? Absent,
302
+ * blank, or unknown `agent` → false (fail-closed: an unknown id can never
303
+ * widen visibility, exactly like the identity layer's mode resolution). The
304
+ * `agent` value is sanitized first so a wire id arrives in the roster's
305
+ * namespace (`Nano` → `nano`); note sanitizeAgentId also collapses inner
306
+ * separators, so `hermes/nano` sent as a requester id reads as `hermes-nano`
307
+ * — the read side intentionally matches BARE ids only (plugins send their
308
+ * resolved profile name, not their capture-side qualified stamp).
309
+ */
310
+ function isCircleMember(agent, roster) {
311
+ if (!agent || roster.length === 0)
312
+ return false;
313
+ const id = (0, identity_store_js_1.sanitizeAgentId)(agent);
314
+ return id !== null && roster.includes(id);
315
+ }
316
+ // ---------------------------------------------------------------------------
317
+ // The confidential LLM client
318
+ // ---------------------------------------------------------------------------
319
+ /**
320
+ * Resolve the confidential model's CONFIG from explicit config keys or env —
321
+ * the same shape and precedence as the main model
322
+ * (resolveExplicitLlmConfig):
323
+ *
324
+ * 1. config `llmConfidentialBaseUrl` + `llmConfidentialApiKey` (both
325
+ * required; `llmConfidentialModel` optional; `llmConfidentialProvider`
326
+ * selects the request dialect, else URL detection — the llmProvider
327
+ * precedent);
328
+ * 2. env `HICORTEX_LLM_CONFIDENTIAL_BASE_URL` +
329
+ * `HICORTEX_LLM_CONFIDENTIAL_API_KEY` (both required;
330
+ * `HICORTEX_LLM_CONFIDENTIAL_MODEL` optional) — mirroring the main
331
+ * model's HICORTEX_LLM_* env pattern.
332
+ *
333
+ * null when nothing explicit is set — the caller holds/skips confidential
334
+ * work and warns (never falls back to the main model).
335
+ *
336
+ * Deliberately NOT routed through the named backends (claude-cli / ollama):
337
+ * the confidential model is a full explicit-config surface by spec — a
338
+ * second claude-cli subprocess or a local ollama alias would silently be the
339
+ * SAME trust domain as the main model.
340
+ */
341
+ function resolveConfidentialLlmConfig(savedConfig) {
342
+ const s = savedConfig ?? {};
343
+ const str = (v) => typeof v === "string" && v ? v : undefined;
344
+ const cfgBase = str(s.llmConfidentialBaseUrl);
345
+ const cfgKey = str(s.llmConfidentialApiKey);
346
+ // Both config keys required (the main model's contract). Called with BOTH
347
+ // set, resolveExplicitLlmConfig answers from them alone — it only falls to
348
+ // the MAIN HICORTEX_LLM_* env vars when its overrides are absent, which
349
+ // would silently configure the confidential client as the main model. The
350
+ // explicit guard keeps that branch unreachable here.
351
+ if (cfgBase && cfgKey) {
352
+ return (0, llm_js_1.resolveExplicitLlmConfig)({
353
+ llmBaseUrl: cfgBase,
354
+ llmApiKey: cfgKey,
355
+ llmModel: str(s.llmConfidentialModel),
356
+ llmProvider: str(s.llmConfidentialProvider),
357
+ });
358
+ }
359
+ const envBase = str(process.env.HICORTEX_LLM_CONFIDENTIAL_BASE_URL);
360
+ const envKey = str(process.env.HICORTEX_LLM_CONFIDENTIAL_API_KEY);
361
+ if (envBase && envKey) {
362
+ return (0, llm_js_1.resolveExplicitLlmConfig)({
363
+ llmBaseUrl: envBase,
364
+ llmApiKey: envKey,
365
+ llmModel: str(process.env.HICORTEX_LLM_CONFIDENTIAL_MODEL),
366
+ });
367
+ }
368
+ return null;
369
+ }
370
+ /**
371
+ * Build the confidential LlmClient for a resolved config — the daemon
372
+ * funnel's construction half. Applies the SAME tuning overlay as the main
373
+ * client (applyTierTuningOverlay, the both-sites discipline: maxTokens,
374
+ * timeouts, single-flight apply per-process at construction) so the second
375
+ * model is not a second-class client.
376
+ */
377
+ function buildConfidentialLlm(savedConfig) {
378
+ const config = resolveConfidentialLlmConfig(savedConfig);
379
+ if (!config)
380
+ return null;
381
+ (0, llm_js_1.applyTierTuningOverlay)(config, savedConfig ?? null);
382
+ return { llm: new llm_js_1.LlmClient(config), config };
383
+ }
384
+ /**
385
+ * Resolve the full pair for a pipeline process (the nightly/CLI funnel —
386
+ * resolveSavedLlmConfig for the standard client, buildConfidentialLlm for
387
+ * the confidential one). Returns the pair plus both configs (the drain and
388
+ * the /distill sync path need the config for chunk-size detection/probing),
389
+ * and passes through resolveSavedLlmConfig's `reason` so callers keep their
390
+ * claude-binary-missing logging.
391
+ */
392
+ function resolveLlmPair(savedConfig) {
393
+ const resolved = (0, llm_js_1.resolveSavedLlmConfig)(savedConfig ?? null);
394
+ const confidential = buildConfidentialLlm(savedConfig);
395
+ if (!resolved.config) {
396
+ return {
397
+ pair: null,
398
+ standardConfig: null,
399
+ confidentialConfig: confidential?.config ?? null,
400
+ reason: resolved.reason,
401
+ };
402
+ }
403
+ return {
404
+ pair: {
405
+ standard: new llm_js_1.LlmClient(resolved.config),
406
+ confidential: confidential?.llm ?? null,
407
+ },
408
+ standardConfig: resolved.config,
409
+ confidentialConfig: confidential?.config ?? null,
410
+ };
411
+ }
412
+ /**
413
+ * The per-pool selection every stage call site goes through: the client that
414
+ * MUST serve a memory class, or null when the confidential pool has no
415
+ * client configured (the caller holds/skips that pool's work — the
416
+ * structurally-hard guarantee that confidential text can never reach the
417
+ * standard model: there is no code path that answers "give me SOME client
418
+ * for confidential").
419
+ */
420
+ function clientForPool(pair, privacy) {
421
+ if (privacy === "confidential")
422
+ return pair.confidential;
423
+ return pair.standard;
424
+ }
425
+ // ---------------------------------------------------------------------------
426
+ // Boot warning
427
+ // ---------------------------------------------------------------------------
428
+ /**
429
+ * The ONE loud boot warning when the circle is ACTIVE (a roster OR
430
+ * confidentialPaths patterns are configured, OR confidential rows exist, OR
431
+ * confidential items sit queued) but the confidential model is not. Called at
432
+ * daemon boot and nightly start; prints once per call site (the callers are
433
+ * once-per-process). The wording names the exposure and the HOLD behavior —
434
+ * the operator learns from the logs that deliveries are piling up, not
435
+ * silently distilling on the main model. Returns whether the warning fired
436
+ * (tests + callers that compose their own log lines).
437
+ */
438
+ function warnIfCircleUnconfigured(opts) {
439
+ if (opts.confidentialLlm)
440
+ return false;
441
+ const active = opts.roster.length > 0 ||
442
+ (opts.patterns?.length ?? 0) > 0 ||
443
+ opts.confidentialRows > 0 ||
444
+ opts.queueConfidential > 0;
445
+ if (!active)
446
+ return false;
447
+ console.warn("");
448
+ console.warn("╔══════════════════════════════════════════════════════════════╗");
449
+ console.warn("║ CONFIDENTIAL CIRCLE ACTIVE WITHOUT A CONFIDENTIAL MODEL ║");
450
+ console.warn("║ ║");
451
+ console.warn("║ Confidential memories exist (or a confidentialAgents ║");
452
+ console.warn("║ roster / confidentialPaths patterns are set) but ║");
453
+ console.warn("║ llmConfidentialBaseUrl/ApiKey are not. ║");
454
+ console.warn("║ Confidential deliveries are HELD, not distilled — they ║");
455
+ console.warn("║ accumulate until a confidential model is configured ║");
456
+ console.warn("║ (they never fall back to the main model). Standard ║");
457
+ console.warn("║ capture and consolidation continue normally. ║");
458
+ console.warn("║ ║");
459
+ console.warn("║ Set llmConfidentialBaseUrl + llmConfidentialApiKey ║");
460
+ console.warn("║ (+ llmConfidentialModel) in config.json and restart. ║");
461
+ console.warn("╚══════════════════════════════════════════════════════════════╝");
462
+ console.warn("");
463
+ return true;
464
+ }
465
+ /**
466
+ * The boot note when the circle is ACTIVE but the marker key is not (#614):
467
+ * one line naming `confidentialMarkerKey` and that client workspace markers
468
+ * are IGNORED (inert) until it is set — an operator running a marked folder
469
+ * learns from the log why it stamps standard, not from silently
470
+ * unclassified captures. Fires ONLY when the key is absent AND the circle is
471
+ * otherwise active (the SAME active predicate as warnIfCircleUnconfigured:
472
+ * roster, confidentialPaths patterns, stored confidential rows, or queued
473
+ * confidential items); a zero-config install stays silent (the header's
474
+ * zero-change-default discipline). Pure — returns the note string, the
475
+ * caller prints it (testable without console spies). Null = say nothing.
476
+ */
477
+ function confidentialMarkerKeyNote(opts) {
478
+ if (opts.markerKey)
479
+ return null;
480
+ const active = opts.roster.length > 0 ||
481
+ (opts.patterns?.length ?? 0) > 0 ||
482
+ opts.confidentialRows > 0 ||
483
+ opts.queueConfidential > 0;
484
+ if (!active)
485
+ return null;
486
+ return ("[hicortex] confidentialMarkerKey is not set — client workspace markers are IGNORED " +
487
+ "(deliveries from marked folders stamp standard). Set confidentialMarkerKey in " +
488
+ "config.json (or the HICORTEX_CONFIDENTIAL_MARKER_KEY env var) and mirror it to the " +
489
+ "machines that mark folders, then restart.");
490
+ }
491
+ /**
492
+ * Module-level once-latch for the refused-marker warn — ONE line per process
493
+ * (that IS the rate limit: a fleet of nightly segments from a mis-keyed
494
+ * folder must not flood the daemon log). resetRefusedMarkerWarn re-arms it
495
+ * for tests.
496
+ */
497
+ let refusedMarkerWarned = false;
498
+ /** Test seam: re-arm the warnRefusedMarker once-latch. */
499
+ function resetRefusedMarkerWarn() {
500
+ refusedMarkerWarned = false;
501
+ }
502
+ /**
503
+ * The refused-marker warn (#614): a delivery carried marker content that did
504
+ * NOT validate at intake — present with NO key configured (the marker arm is
505
+ * inert) or present but NOT equal to the key (a stale pre-key marker, a
506
+ * rotated key, or a forgery attempt). The CALLER guards the call
507
+ * (`clientMarker !== null && clientMarker !== key` — one guard covers both
508
+ * reasons); the reason wording here distinguishes them for the operator.
509
+ * NEVER echoes the marker content or the key (log discipline — the secret
510
+ * and the guess both stay out of the logs); naming the workspace path is
511
+ * fine (it is the operator's own path, and it is what they need to fix).
512
+ * Returns whether the line printed (the once-latch ate it → false).
513
+ */
514
+ function warnRefusedMarker(opts) {
515
+ if (refusedMarkerWarned)
516
+ return false;
517
+ refusedMarkerWarned = true;
518
+ const reason = opts.markerKey
519
+ ? "does not match this server's confidentialMarkerKey"
520
+ : "arrived but no confidentialMarkerKey is configured (markers are inert)";
521
+ const where = opts.workspacePath ? ` (workspace ${opts.workspacePath})` : "";
522
+ console.warn(`[hicortex] Confidential marker refused${where}: marker content ${reason} — the delivery stamps standard. ` +
523
+ `Re-run \`hicortex confidential\` in that folder to rewrite the marker, or align the key.`);
524
+ return true;
525
+ }
@@ -75,7 +75,7 @@ const node_path_1 = require("node:path");
75
75
  const db_js_1 = require("./db.js");
76
76
  const state_js_1 = require("./state.js");
77
77
  const storage = __importStar(require("./storage.js"));
78
- const llm_js_1 = require("./llm.js");
78
+ const classification_js_1 = require("./classification.js");
79
79
  const domain_classify_js_1 = require("./domain-classify.js");
80
80
  const consolidate_js_1 = require("./consolidate.js");
81
81
  const schema_prototypes_js_1 = require("./schema-prototypes.js");
@@ -125,17 +125,22 @@ async function runClassifyDomains(options = {}) {
125
125
  const weakPrimaryFloor = Number.isFinite(floorRaw) && floorRaw > 0 && floorRaw < 1
126
126
  ? floorRaw
127
127
  : nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR;
128
- // Resolve the LLM (one model serves all phases — #231).
128
+ // Resolve the LLM (one model serves all phases — #231). #332: plus the
129
+ // confidential client — each row's classify call picks the client matching
130
+ // its stamp; a confidential row without a client holds (treated like the
131
+ // infra abort: untouched, retried).
129
132
  let llm;
133
+ let confidentialLlm = null;
130
134
  if (options.llm) {
131
135
  llm = options.llm;
132
136
  }
133
137
  else {
134
- const resolved = (0, llm_js_1.resolveSavedLlmConfig)(config);
135
- if (!resolved.config) {
138
+ const resolved = (0, classification_js_1.resolveLlmPair)(config);
139
+ if (!resolved.pair) {
136
140
  throw new Error("[hicortex] classify-domains: no LLM configured — run `npx @gamaze/hicortex init`.");
137
141
  }
138
- llm = new llm_js_1.LlmClient(resolved.config);
142
+ llm = resolved.pair.standard;
143
+ confidentialLlm = resolved.pair.confidential;
139
144
  }
140
145
  const dbPath = (0, db_js_1.resolveDbPath)(options.dbPath);
141
146
  const db = (0, db_js_1.initDb)(dbPath);
@@ -185,7 +190,7 @@ async function runClassifyDomains(options = {}) {
185
190
  : `rowid > ? AND COALESCE(status, '') != 'absorbed' ` +
186
191
  `AND (domain IS NULL OR domain NOT IN (${placeholders}) ` +
187
192
  `OR id NOT IN (SELECT DISTINCT memory_id FROM memory_tags))`;
188
- const batchStmt = db.prepare(`SELECT rowid AS __rowid, id, content, project, domain FROM memories
193
+ const batchStmt = db.prepare(`SELECT rowid AS __rowid, id, content, project, domain, privacy FROM memories
189
194
  WHERE ${scopeSql} ORDER BY rowid ASC LIMIT ?`);
190
195
  // Set true when the classifier returns null (infra error): finish the
191
196
  // current batch's already-classified writes, commit, advance cursor to the
@@ -209,7 +214,19 @@ async function runClassifyDomains(options = {}) {
209
214
  // the scan phase; only the writes are deferred to the transaction.
210
215
  const writes = [];
211
216
  for (const row of rows) {
212
- const result = await (0, domain_classify_js_1.classifyMemoryTags)(row.content, row.project, domains, llm);
217
+ // #332: per-row client selection — a confidential row classifies on
218
+ // the confidential client; without one it HOLDS (the infra-abort
219
+ // posture: untouched, retried next run).
220
+ const rowLlm = row.privacy === "confidential"
221
+ ? confidentialLlm
222
+ : llm;
223
+ if (!rowLlm) {
224
+ console.warn(`[hicortex] classify-domains: confidential row ${row.id.slice(0, 8)} held — ` +
225
+ `no confidential model configured (llmConfidentialBaseUrl/ApiKey)`);
226
+ infraAbort = true;
227
+ break;
228
+ }
229
+ const result = await (0, domain_classify_js_1.classifyMemoryTags)(row.content, row.project, domains, rowLlm);
213
230
  if (result === null) {
214
231
  // Infra error — stop scanning; leave this row untouched for retry.
215
232
  infraAbort = true;