@gamaze/hicortex 0.26.2 → 0.27.0

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 (45) hide show
  1. package/README.md +7 -2
  2. package/assets/dashboard.html +1 -1
  3. package/dist/backfill-privacy.d.ts +82 -0
  4. package/dist/backfill-privacy.js +193 -0
  5. package/dist/classification.d.ts +153 -0
  6. package/dist/classification.js +265 -0
  7. package/dist/classify-domains.js +24 -7
  8. package/dist/cli.js +31 -0
  9. package/dist/cluster.d.ts +15 -8
  10. package/dist/cluster.js +10 -3
  11. package/dist/consolidate.d.ts +31 -2
  12. package/dist/consolidate.js +193 -40
  13. package/dist/db.js +26 -1
  14. package/dist/dedup.d.ts +5 -3
  15. package/dist/dedup.js +26 -12
  16. package/dist/distill-queue.d.ts +25 -1
  17. package/dist/distill-queue.js +47 -7
  18. package/dist/graph.d.ts +28 -3
  19. package/dist/graph.js +46 -4
  20. package/dist/init.d.ts +18 -9
  21. package/dist/init.js +111 -81
  22. package/dist/mcp-server.js +186 -32
  23. package/dist/nightly.js +33 -7
  24. package/dist/recall-index.d.ts +19 -9
  25. package/dist/recall-index.js +14 -4
  26. package/dist/recall-precision.js +3 -1
  27. package/dist/reconsolidation.d.ts +10 -0
  28. package/dist/reconsolidation.js +80 -17
  29. package/dist/redact.d.ts +9 -1
  30. package/dist/redact.js +32 -1
  31. package/dist/rescore-importance.js +21 -4
  32. package/dist/retrieval.d.ts +23 -6
  33. package/dist/retrieval.js +41 -15
  34. package/dist/seed-lesson.js +3 -1
  35. package/dist/storage.d.ts +23 -4
  36. package/dist/storage.js +38 -9
  37. package/dist/type-classify.js +22 -7
  38. package/dist/types.d.ts +81 -15
  39. package/dist/uninstall.js +6 -5
  40. package/hermes-plugin/hicortex/README.md +4 -0
  41. package/hermes-plugin/hicortex/client.py +36 -9
  42. package/hermes-plugin/hicortex/plugin.yaml +1 -1
  43. package/hermes-plugin/hicortex/provider.py +28 -6
  44. package/package.json +1 -1
  45. package/server.json +2 -2
package/README.md CHANGED
@@ -278,10 +278,15 @@ Config at `~/.hicortex/config.json`. Created by `init`. Key options:
278
278
  | `identityClients` | Which harnesses inject the [identity layer](#identity-layer) at session start (default `["cc"]`; `"all"` or any subset of `cc`/`hermes`/`oc`/`pi`/`opencode`) |
279
279
  | `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) |
280
280
  | `agentName` | This install's per-agent identity id sent as `?agent=`. **Unset by default** (CC shares the global identity — no `?agent=` sent). Explicit opt-in via `init --agent-name <name>`; `init --agent-name ""` clears it. An empty/whitespace value equals unset |
281
- | `captureCooldownHours` | Success-cooldown (hours) for the **capture watchdog** (0.17). The capture timer polls every ~20 min; the watchdog captures only if more than this has elapsed since the last *successful* capture (`state.lastNightly`). Default `6` (≈4 captures/day). A failed preflight retries on the next poll (~20 min) — so a transient fire-instant network miss costs minutes, not a day (#239) |
281
+ | `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 |
282
+ | `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` |
283
+ | `llmConfidentialApiKey` | The confidential model's API key (see `llmConfidentialBaseUrl`). **When the circle is active but this pair is unset, confidential work HOLDS**: queued deliveries stay in the distill inbox (standard deliveries keep draining) and sync-mode deliveries answer 503 — nothing confidential ever touches the main model, and a loud boot warning names the exposure |
284
+ | `llmConfidentialModel` | The confidential model's id (see `llmConfidentialBaseUrl`) |
285
+ | `llmConfidentialProvider` | Explicit request dialect for the confidential model's OpenAI-compatible path (the `llmProvider` precedent; today only `"azure"`). Absent/empty → detected from the base URL |
286
+ | `captureCooldownHours` | Success-cooldown (hours) for **manual capture-watchdog runs** (`nightly --watchdog`, 0.17 #239). The watchdog *timer* was retired (#596) — obsolete since the distill queue (#529): distillation runs on the server's scheduled drains, so capture-arrival latency serves nothing, and capture now lives in the nightly's capture phase (no separate capture timer exists). When the flag is run manually, it captures only if more than this has elapsed since the last *successful* capture (`state.lastNightly`). Default `6` |
282
287
  | `firstRunLookbackDays` | Days of session history the FIRST nightly run discovers (default `7`). A long-term AI user's entire session store is deliberately not distilled on night one — the first watermark is `now − this many days`, not the beginning of time. Already-running installs are unaffected (they have a real watermark). To import more history, run `hicortex nightly --recapture-window <days>` once — widening-only, per-session cursors keep the re-scan cheap. Invalid value → warn + default (#436) |
283
288
  | `recallCrossProjectMinSimilarity` | The cross-project recall fence bar (default `0.72`, fence **ON when the key is absent**). When a recall or search request carries a project, a memory from a *different* project must clear this similarity on a measured cosine to be admitted — pushed recall (`/recall-index`), `GET /search`, and the `hicortex_search` tool all fence identically; same-project and unscoped recall are unchanged. `0` or any value ≤ the recall floor (`0.62`) turns the fence off (today's scope-blind behavior). Clamped to `[0,1]`; a wrong type → warn + default. Boot-time (restart to apply) |
284
- | `consolidationHours` | Hours (0–23, local) for the **consolidation** timer — the full nightly (capture + distill + score + reflect + link). Installed for **server/co-located only** (clients have no local DB). Default `[10, 22]`: the 22:00 evening slot runs after the day's capture waves (same-day results); the 10:00 morning slot runs *after* the morning capture so wake-up pushes are caught. Omitted on clients |
289
+ | `consolidationHours` | Hours (0–23, local) for the **consolidation** timer — the full nightly (capture + distill + score + reflect + link). Installed for **server/co-located only** (clients have no local DB). Default `[10, 22]`: the 22:00 evening slot distills the day's sessions the same day; the 10:00 morning slot catches the night's and the previous evening's tail. Omitted on clients |
285
290
  | `timerJitterSeconds` | Max random delay (seconds) added to **generated** consolidation timers (#256), so a fleet doesn't all fire on the same minute (thundering-herd → LLM-backend contention). systemd: a single `RandomizedDelaySec=<n>`; launchd has no native equivalent so a per-install randomized `Minute` offset is baked into every `StartCalendarInterval` dict (sub-60s values no-op on launchd). Default `3600` (≈±30 min spread on the 2-slot/day cadence); `0` disables. Affects timers on the next `init` (re-init rewrites the unit files; installs that don't re-init keep their existing timers) |
286
291
  | `nightlyTimeBudgetMinutes` | The ONE wall-clock budget (minutes) for a nightly run: capture and every consolidation stage share one cooperative deadline, checked at safe boundaries (capture segments, stage boundaries, item loops, the merge zone). A run whose deadline fires reports consolidation `deferred` and resumes from its cursors next run — no work lost, none redone. Default `240`; `0`/invalid → default (a deadline always exists — there is no "off"). The systemd unit's `TimeoutStartSec` is derived from this (+60 min slack) at `init` |
287
292
  | `nightlyLlmCallBudget` | The ONE per-run ceiling on LLM calls across the whole pipeline. Consumed in run order — a stage that exhausts it defers its remainder via its cursor. Bounds money/load independent of latency: a fast metered or capacity-limited endpoint permits thousands of calls inside the wall-clock budget, so time alone cannot protect it. Default `5000`; `0`/invalid → default. `consolidateMaxLlmCalls` is a **deprecated alias** (honored one release when the new key is absent — rename it) |
@@ -462,7 +462,7 @@
462
462
  .rec-l1{ display:flex; flex-direction:column; gap:8px; min-width:0; }
463
463
  .rec-l1[hidden]{ display:none; } /* author display beats the UA's [hidden] — the #billing-banner idiom; without it the flex rule un-hides the container */
464
464
  .rec-l1 .l1stat{ display:grid; grid-template-columns:72px minmax(0,1fr) auto; column-gap:10px; align-items:baseline; min-width:0; white-space:nowrap; }
465
- .rec-l1 .l1v{ font-size:22px; font-weight:640; color:var(--text); text-align:right; font-variant-numeric:tabular-nums; line-height:1.05; min-width:0; }
465
+ .rec-l1 .l1v{ font-size:12px; font-weight:640; color:var(--text); text-align:right; font-variant-numeric:tabular-nums; line-height:1.15; min-width:0; }
466
466
  .rec-l1 .l1v .l1u{ font-style:normal; font-size:10.5px; font-weight:520; color:var(--dim); margin-left:2px; }
467
467
  .rec-l1 .l1l{ font-size:10.5px; color:var(--dim); overflow:hidden; text-overflow:ellipsis; min-width:0; }
468
468
  .rec-l1 .l1chip{ justify-self:end; font-size:10.5px; font-weight:620; line-height:1; padding:2.5px 8px; border-radius:999px; white-space:nowrap; color:var(--green-mid); background:color-mix(in srgb, var(--green-mid) 13%, transparent); }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * `hicortex backfill-privacy` (#332) — one-shot classification stamping for
3
+ * EXISTING rows, by source agent.
4
+ *
5
+ * The intake derivation stamps every NEW delivery; this command heals history
6
+ * when the roster changes (an agent joins the circle, or the feature lands on
7
+ * a store that already has captures from a now-rostered agent). The plan is a
8
+ * pure function of the roster × the rows' source_agent values:
9
+ * - every memories/distill_queue row whose source_agent matches the roster
10
+ * (isConfidentialSourceAgent — the same `<harness>/`-stripping matcher the
11
+ * intake uses) AND whose privacy != 'confidential' → stamped confidential;
12
+ * - NOTHING is ever stamped BACK to standard (a roster removal is not a
13
+ * demotion — memories stay confidential until the operator explicitly
14
+ * changes them; re-running with a smaller roster is a no-op by design).
15
+ *
16
+ * Safety rails (the `hicortex dedup` / `reconcile-projects` pattern): dry run
17
+ * by default (report only, zero writes); `--apply` takes a pre-apply DB
18
+ * backup (abort all writes on failure), the single-flight capture lock
19
+ * (waitMs 0 — busy aborts), and stamps in ONE transaction. The queue rows are
20
+ * stamped too: a pre-upgrade queued segment from a rostered agent would
21
+ * otherwise distill as standard (migration v27 normalized it) — the backfill
22
+ * closes that seam.
23
+ *
24
+ * Idempotent by construction: a second run finds every rostered row already
25
+ * confidential and reports zero.
26
+ */
27
+ import type Database from "better-sqlite3";
28
+ import { acquireCaptureLock } from "./capture.js";
29
+ /** One planned stamp group: rows from one rostered source agent. */
30
+ export interface BackfillGroup {
31
+ /** The DISTINCT source_agent value as stored (not the roster entry). */
32
+ sourceAgent: string;
33
+ /** Rows in `memories` that would flip to confidential. */
34
+ memoryRows: number;
35
+ /** Rows in `distill_queue` that would flip (distill as confidential). */
36
+ queuedRows: number;
37
+ }
38
+ export interface BackfillReport {
39
+ dryRun: boolean;
40
+ /** The roster entries the plan matched (subset of confidentialAgents). */
41
+ roster: string[];
42
+ /** Planned/executed stamp groups, largest first. */
43
+ groups: BackfillGroup[];
44
+ /** Total rows that would flip / flipped. */
45
+ totalMemories: number;
46
+ totalQueued: number;
47
+ /** --apply only: rows actually stamped (memories). */
48
+ appliedMemories?: number;
49
+ /** --apply only: queue rows actually stamped. */
50
+ appliedQueued?: number;
51
+ /** --apply only: path to the pre-apply backup. */
52
+ backupPath?: string;
53
+ /** --apply only: the capture lock was busy — zero writes, retried later. */
54
+ lockBusy?: boolean;
55
+ }
56
+ export interface BackfillOptions {
57
+ /** Execute the stamps. Default false = dry run (report only, zero writes). */
58
+ apply?: boolean;
59
+ /** DB path override (tests / snapshot verification). Defaults to resolveDbPath(). */
60
+ dbPath?: string;
61
+ /** State dir override (tests). Defaults to ~/.hicortex. */
62
+ stateDir?: string;
63
+ /** Config override (tests). Defaults to reading stateDir/config.json. */
64
+ config?: Record<string, unknown> | null;
65
+ /** Capture-lock acquirer override (tests). Defaults to the real capture.ts lock. */
66
+ acquireLock?: typeof acquireCaptureLock;
67
+ }
68
+ /**
69
+ * The pure plan: which stored source_agent values match the roster, and how
70
+ * many of their rows are not yet confidential. Roster matching uses the
71
+ * INTAKE matcher (isConfidentialSourceAgent — `<harness>/`-stripping) so the
72
+ * backfill and the intake can never disagree about who is rostered.
73
+ */
74
+ export declare function planBackfill(db: Database.Database, roster: string[]): BackfillGroup[];
75
+ /**
76
+ * Run `hicortex backfill-privacy`. Dry run by default (options.apply falsy) —
77
+ * plan + report only, zero writes. `options.apply` executes: backup, capture
78
+ * lock, ONE transaction stamping every planned row in BOTH tables. A busy
79
+ * lock is an abort (reported as `lockBusy: true`, never a wait); a failed
80
+ * backup aborts all writes (throw, like dedup/reconcile-projects).
81
+ */
82
+ export declare function runBackfillPrivacy(options?: BackfillOptions): Promise<BackfillReport>;
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ /**
3
+ * `hicortex backfill-privacy` (#332) — one-shot classification stamping for
4
+ * EXISTING rows, by source agent.
5
+ *
6
+ * The intake derivation stamps every NEW delivery; this command heals history
7
+ * when the roster changes (an agent joins the circle, or the feature lands on
8
+ * a store that already has captures from a now-rostered agent). The plan is a
9
+ * pure function of the roster × the rows' source_agent values:
10
+ * - every memories/distill_queue row whose source_agent matches the roster
11
+ * (isConfidentialSourceAgent — the same `<harness>/`-stripping matcher the
12
+ * intake uses) AND whose privacy != 'confidential' → stamped confidential;
13
+ * - NOTHING is ever stamped BACK to standard (a roster removal is not a
14
+ * demotion — memories stay confidential until the operator explicitly
15
+ * changes them; re-running with a smaller roster is a no-op by design).
16
+ *
17
+ * Safety rails (the `hicortex dedup` / `reconcile-projects` pattern): dry run
18
+ * by default (report only, zero writes); `--apply` takes a pre-apply DB
19
+ * backup (abort all writes on failure), the single-flight capture lock
20
+ * (waitMs 0 — busy aborts), and stamps in ONE transaction. The queue rows are
21
+ * stamped too: a pre-upgrade queued segment from a rostered agent would
22
+ * otherwise distill as standard (migration v27 normalized it) — the backfill
23
+ * closes that seam.
24
+ *
25
+ * Idempotent by construction: a second run finds every rostered row already
26
+ * confidential and reports zero.
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.planBackfill = planBackfill;
30
+ exports.runBackfillPrivacy = runBackfillPrivacy;
31
+ const paths_js_1 = require("./paths.js");
32
+ const node_fs_1 = require("node:fs");
33
+ const node_path_1 = require("node:path");
34
+ const db_js_1 = require("./db.js");
35
+ const capture_js_1 = require("./capture.js");
36
+ const dedup_js_1 = require("./dedup.js");
37
+ const classification_js_1 = require("./classification.js");
38
+ const HICORTEX_HOME = (0, paths_js_1.hicortexHome)();
39
+ function readConfig(stateDir) {
40
+ try {
41
+ return JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(stateDir, "config.json"), "utf-8"));
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ /** Distinct source_agent values (with row counts) from one table. */
48
+ function readSourceAgents(db, table) {
49
+ const column = table === "memories" ? "source_agent" : "source_agent";
50
+ const rows = db
51
+ .prepare(`SELECT ${column} AS agent, COUNT(*) AS c FROM ${table}
52
+ WHERE ${column} IS NOT NULL AND ${column} != '' GROUP BY ${column}`)
53
+ .all();
54
+ return new Map(rows.map((r) => [r.agent, r.c]));
55
+ }
56
+ /**
57
+ * The pure plan: which stored source_agent values match the roster, and how
58
+ * many of their rows are not yet confidential. Roster matching uses the
59
+ * INTAKE matcher (isConfidentialSourceAgent — `<harness>/`-stripping) so the
60
+ * backfill and the intake can never disagree about who is rostered.
61
+ */
62
+ function planBackfill(db, roster) {
63
+ const memoryAgents = readSourceAgents(db, "memories");
64
+ const queuedAgents = readSourceAgents(db, "distill_queue");
65
+ const groups = [];
66
+ for (const [agent, memoryRows] of memoryAgents) {
67
+ if (!(0, classification_js_1.isConfidentialSourceAgent)(agent, roster))
68
+ continue;
69
+ const pending = db
70
+ .prepare("SELECT COUNT(*) AS c FROM memories WHERE source_agent = ? AND privacy != 'confidential'")
71
+ .get(agent).c;
72
+ const queued = queuedAgents.has(agent)
73
+ ? db
74
+ .prepare("SELECT COUNT(*) AS c FROM distill_queue WHERE source_agent = ? AND privacy != 'confidential'")
75
+ .get(agent).c
76
+ : 0;
77
+ if (pending === 0 && queued === 0)
78
+ continue;
79
+ groups.push({ sourceAgent: agent, memoryRows: pending, queuedRows: queued });
80
+ }
81
+ // Queue-only groups (memories already stamped, inbox holds old rows).
82
+ for (const agent of queuedAgents.keys()) {
83
+ if (memoryAgents.has(agent))
84
+ continue;
85
+ if (!(0, classification_js_1.isConfidentialSourceAgent)(agent, roster))
86
+ continue;
87
+ const queued = db
88
+ .prepare("SELECT COUNT(*) AS c FROM distill_queue WHERE source_agent = ? AND privacy != 'confidential'")
89
+ .get(agent).c;
90
+ if (queued > 0)
91
+ groups.push({ sourceAgent: agent, memoryRows: 0, queuedRows: queued });
92
+ }
93
+ groups.sort((a, b) => b.memoryRows - a.memoryRows || a.sourceAgent.localeCompare(b.sourceAgent));
94
+ return groups;
95
+ }
96
+ /**
97
+ * Run `hicortex backfill-privacy`. Dry run by default (options.apply falsy) —
98
+ * plan + report only, zero writes. `options.apply` executes: backup, capture
99
+ * lock, ONE transaction stamping every planned row in BOTH tables. A busy
100
+ * lock is an abort (reported as `lockBusy: true`, never a wait); a failed
101
+ * backup aborts all writes (throw, like dedup/reconcile-projects).
102
+ */
103
+ async function runBackfillPrivacy(options = {}) {
104
+ const stateDir = options.stateDir ?? HICORTEX_HOME;
105
+ const config = options.config !== undefined ? options.config : readConfig(stateDir);
106
+ // The roster comes from the SAME resolution the server uses at boot
107
+ // (resolveConfidentialAgents) — one config shape, one id namespace.
108
+ const { resolveConfidentialAgents } = await import("./classification.js");
109
+ const roster = resolveConfidentialAgents(config).roster;
110
+ // Server-mode only — client installs have no local DB.
111
+ if (config?.mode === "client") {
112
+ throw new Error("[hicortex] backfill-privacy is server-mode only (it needs the local DB). " +
113
+ `This machine is a client of ${config.serverUrl ?? "a remote server"} — run backfill-privacy on the server.`);
114
+ }
115
+ const apply = options.apply ?? false;
116
+ const dbPath = (0, db_js_1.resolveDbPath)(options.dbPath);
117
+ const db = (0, db_js_1.initDb)(dbPath);
118
+ try {
119
+ console.log(`[hicortex] backfill-privacy starting (${apply ? "APPLY" : "dry-run"}): db ${dbPath}, ` +
120
+ `${roster.length} rostered agent(s)${roster.length > 0 ? ` (${roster.join(", ")})` : ""}`);
121
+ if (roster.length === 0) {
122
+ console.log("[hicortex] backfill-privacy: no confidentialAgents configured — nothing to stamp. " +
123
+ "Add agent ids to config.json confidentialAgents first.");
124
+ return { dryRun: !apply, roster, groups: [], totalMemories: 0, totalQueued: 0 };
125
+ }
126
+ const groups = planBackfill(db, roster);
127
+ const totalMemories = groups.reduce((s, g) => s + g.memoryRows, 0);
128
+ const totalQueued = groups.reduce((s, g) => s + g.queuedRows, 0);
129
+ const report = {
130
+ dryRun: !apply,
131
+ roster,
132
+ groups,
133
+ totalMemories,
134
+ totalQueued,
135
+ };
136
+ console.log(`[hicortex] backfill-privacy: ${groups.length} source agent(s) match the roster, ` +
137
+ `${totalMemories} memory row(s)${totalQueued > 0 ? `, ${totalQueued} queued row(s)` : ""} ` +
138
+ `→ confidential (${apply ? "applying" : "dry run — zero writes"})`);
139
+ for (const g of groups) {
140
+ console.log(`[hicortex] ${g.sourceAgent}: ${g.memoryRows} memory row(s)${g.queuedRows > 0 ? `, ${g.queuedRows} queued` : ""}`);
141
+ }
142
+ if (!apply)
143
+ return report;
144
+ // --apply: single-flight capture lock (waitMs 0) so a concurrent
145
+ // nightly/capture run cannot race the stamps. Busy → abort (reported,
146
+ // never a silent wait — a deliberate manual command is retried by the
147
+ // operator, like dedup/reconcile-projects).
148
+ const acquireLock = options.acquireLock ?? capture_js_1.acquireCaptureLock;
149
+ const releaseLock = await acquireLock(stateDir, 0);
150
+ if (!releaseLock) {
151
+ console.error("[hicortex] backfill-privacy --apply aborted: another capture/nightly run holds the lock. Retry when it finishes.");
152
+ report.lockBusy = true;
153
+ return report;
154
+ }
155
+ try {
156
+ // Backup FIRST — abort entirely (no stamps attempted) if it fails.
157
+ let backupPath;
158
+ try {
159
+ backupPath = await (0, dedup_js_1.takePreDedupBackup)(db, stateDir, config);
160
+ }
161
+ catch (err) {
162
+ throw new Error(`[hicortex] backfill-privacy --apply aborted: backup failed (${err instanceof Error ? err.message : String(err)}). No stamps attempted.`);
163
+ }
164
+ console.log(`[hicortex] Backup written: ${backupPath}`);
165
+ report.backupPath = backupPath;
166
+ // ONE transaction: every group's memory + queue stamps commit together
167
+ // (the plan is order-independent — pure source_agent predicates).
168
+ const stampMem = db.prepare("UPDATE memories SET privacy = 'confidential' WHERE source_agent = ? AND privacy != 'confidential'");
169
+ const stampQueue = db.prepare("UPDATE distill_queue SET privacy = 'confidential' WHERE source_agent = ? AND privacy != 'confidential'");
170
+ const applied = db.transaction(() => {
171
+ let memories = 0;
172
+ let queued = 0;
173
+ for (const g of groups) {
174
+ memories += stampMem.run(g.sourceAgent).changes;
175
+ queued += stampQueue.run(g.sourceAgent).changes;
176
+ }
177
+ return { memories, queued };
178
+ })();
179
+ report.appliedMemories = applied.memories;
180
+ report.appliedQueued = applied.queued;
181
+ console.log(`[hicortex] backfill-privacy complete: ${applied.memories} memory row(s) stamped confidential` +
182
+ (applied.queued > 0 ? `, ${applied.queued} queued row(s)` : "") +
183
+ " (nothing is ever stamped back to standard — a roster removal is not a demotion)");
184
+ return report;
185
+ }
186
+ finally {
187
+ releaseLock();
188
+ }
189
+ }
190
+ finally {
191
+ db.close();
192
+ }
193
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The confidential circle (#332) — the pure decision core for the two-level
3
+ * memory classification (`standard` | `confidential`, carried by
4
+ * `memories.privacy`; see MemoryPrivacy in types.ts).
5
+ *
6
+ * The model, in one paragraph: an operator lists inner-circle agents in
7
+ * config (`confidentialAgents`, the same agent-id namespace as
8
+ * `identityAgents` / `?agent=`). Captures whose `source_agent` is rostered
9
+ * are stamped `confidential` at intake — server-derived, deterministic, by
10
+ * birthplace; never a content judgment (content classification was rejected,
11
+ * #197) and never client-declared. Every agent-facing read path accepts an
12
+ * optional `agent` requester id: absent or unknown = non-member = HARD OMIT
13
+ * of confidential rows (fail-closed both ends — unrostered sources are
14
+ * standard, unknown requesters are non-members). The circle is ADDITIVE:
15
+ * members see both pools. Every LLM touch of confidential text routes to a
16
+ * separately configured second model (`llmConfidential*` config keys /
17
+ * `HICORTEX_LLM_CONFIDENTIAL_*` env) — when that model is absent, the work
18
+ * HOLDS (queue stays, deliveries refuse), never falls back to the main
19
+ * model. An install that configures nothing sees zero change: no roster, no
20
+ * confidential rows, no warning, no second client.
21
+ *
22
+ * All functions here are pure (no DB, no HTTP): the handlers in mcp-server.ts
23
+ * and the pipeline stages consume them, and the tests exercise the decisions
24
+ * directly.
25
+ */
26
+ import { LlmClient, type LlmConfig } from "./llm.js";
27
+ import type { MemoryPrivacy } from "./types.js";
28
+ /**
29
+ * Resolve the `confidentialAgents` config value into a clean roster of agent
30
+ * ids. Each entry is sanitized EXACTLY like `?agent=` (sanitizeAgentId —
31
+ * lowercase, collapse invalid runs to `-`, allowlist-validated) so the roster,
32
+ * the wire `agent` param, and capture's `<harness>/<id>` stamps live in one
33
+ * id namespace. Entries that sanitize to null are dropped and their raw
34
+ * values returned in `dropped` for a one-time boot warning (the
35
+ * resolveIdentityAgents pattern — a typo must surface, not silently drop an
36
+ * agent out of the circle).
37
+ */
38
+ export declare function resolveConfidentialAgents(config: Record<string, unknown> | null | undefined): {
39
+ roster: string[];
40
+ dropped: string[];
41
+ };
42
+ /**
43
+ * Normalize a capture-side `source_agent` for roster matching. Capture stamps
44
+ * harness-qualified ids (`hermes/nano`, `claude-code/myproject`), while the
45
+ * roster carries bare agent ids (the same ids the read side receives as
46
+ * `agent`) — ONE config list, no read-ids/capture-ids sync hazard. The match
47
+ * is exact, or exact after stripping the FIRST path segment (so `hermes/nano`
48
+ * matches roster `nano`, and a future `anything/nano` matches too — generic
49
+ * prefix, not a per-harness table). Case-insensitive on the id half via the
50
+ * roster's sanitized (lowercased) form.
51
+ */
52
+ export declare function isConfidentialSourceAgent(sourceAgent: string | null | undefined, roster: string[]): boolean;
53
+ /**
54
+ * The intake-side derivation: which class a delivery from `sourceAgent`
55
+ * stores as. Fail-closed by construction — anything unattributed or
56
+ * unrostered is `standard` (the global pool).
57
+ */
58
+ export declare function deriveIntakePrivacy(sourceAgent: string | null | undefined, roster: string[]): MemoryPrivacy;
59
+ /**
60
+ * The read-side membership check: is the requester a circle member? Absent,
61
+ * blank, or unknown `agent` → false (fail-closed: an unknown id can never
62
+ * widen visibility, exactly like the identity layer's mode resolution). The
63
+ * `agent` value is sanitized first so a wire id arrives in the roster's
64
+ * namespace (`Nano` → `nano`); note sanitizeAgentId also collapses inner
65
+ * separators, so `hermes/nano` sent as a requester id reads as `hermes-nano`
66
+ * — the read side intentionally matches BARE ids only (plugins send their
67
+ * resolved profile name, not their capture-side qualified stamp).
68
+ */
69
+ export declare function isCircleMember(agent: string | null | undefined, roster: string[]): boolean;
70
+ /**
71
+ * Resolve the confidential model's CONFIG from explicit config keys or env —
72
+ * the same shape and precedence as the main model
73
+ * (resolveExplicitLlmConfig):
74
+ *
75
+ * 1. config `llmConfidentialBaseUrl` + `llmConfidentialApiKey` (both
76
+ * required; `llmConfidentialModel` optional; `llmConfidentialProvider`
77
+ * selects the request dialect, else URL detection — the llmProvider
78
+ * precedent);
79
+ * 2. env `HICORTEX_LLM_CONFIDENTIAL_BASE_URL` +
80
+ * `HICORTEX_LLM_CONFIDENTIAL_API_KEY` (both required;
81
+ * `HICORTEX_LLM_CONFIDENTIAL_MODEL` optional) — mirroring the main
82
+ * model's HICORTEX_LLM_* env pattern.
83
+ *
84
+ * null when nothing explicit is set — the caller holds/skips confidential
85
+ * work and warns (never falls back to the main model).
86
+ *
87
+ * Deliberately NOT routed through the named backends (claude-cli / ollama):
88
+ * the confidential model is a full explicit-config surface by spec — a
89
+ * second claude-cli subprocess or a local ollama alias would silently be the
90
+ * SAME trust domain as the main model.
91
+ */
92
+ export declare function resolveConfidentialLlmConfig(savedConfig: Record<string, unknown> | null | undefined): LlmConfig | null;
93
+ /**
94
+ * Build the confidential LlmClient for a resolved config — the daemon
95
+ * funnel's construction half. Applies the SAME tuning overlay as the main
96
+ * client (applyTierTuningOverlay, the both-sites discipline: maxTokens,
97
+ * timeouts, single-flight apply per-process at construction) so the second
98
+ * model is not a second-class client.
99
+ */
100
+ export declare function buildConfidentialLlm(savedConfig: Record<string, unknown> | null | undefined): {
101
+ llm: LlmClient;
102
+ config: LlmConfig;
103
+ } | null;
104
+ /**
105
+ * The two clients a pipeline run needs. `standard` is the main model (always
106
+ * present when the run does LLM work at all); `confidential` is null when the
107
+ * circle is active but the second model is unconfigured — callers HOLD
108
+ * confidential work in that case (clientForPool returns null), never fall
109
+ * back.
110
+ */
111
+ export interface LlmPair {
112
+ standard: LlmClient;
113
+ confidential: LlmClient | null;
114
+ }
115
+ /**
116
+ * Resolve the full pair for a pipeline process (the nightly/CLI funnel —
117
+ * resolveSavedLlmConfig for the standard client, buildConfidentialLlm for
118
+ * the confidential one). Returns the pair plus both configs (the drain and
119
+ * the /distill sync path need the config for chunk-size detection/probing),
120
+ * and passes through resolveSavedLlmConfig's `reason` so callers keep their
121
+ * claude-binary-missing logging.
122
+ */
123
+ export declare function resolveLlmPair(savedConfig: Record<string, unknown> | null | undefined): {
124
+ pair: LlmPair | null;
125
+ standardConfig: LlmConfig | null;
126
+ confidentialConfig: LlmConfig | null;
127
+ reason?: "claude_binary_missing";
128
+ };
129
+ /**
130
+ * The per-pool selection every stage call site goes through: the client that
131
+ * MUST serve a memory class, or null when the confidential pool has no
132
+ * client configured (the caller holds/skips that pool's work — the
133
+ * structurally-hard guarantee that confidential text can never reach the
134
+ * standard model: there is no code path that answers "give me SOME client
135
+ * for confidential").
136
+ */
137
+ export declare function clientForPool(pair: LlmPair, privacy: MemoryPrivacy | null | undefined): LlmClient | null;
138
+ /**
139
+ * The ONE loud boot warning when the circle is ACTIVE (a roster is
140
+ * configured, OR confidential rows exist, OR confidential items sit queued)
141
+ * but the confidential model is not. Called at daemon boot and nightly start;
142
+ * prints once per call site (the callers are once-per-process). The wording
143
+ * names the exposure and the HOLD behavior — the operator learns from the
144
+ * logs that deliveries are piling up, not silently distilling on the main
145
+ * model. Returns whether the warning fired (tests + callers that compose
146
+ * their own log lines).
147
+ */
148
+ export declare function warnIfCircleUnconfigured(opts: {
149
+ roster: string[];
150
+ confidentialLlm: LlmClient | LlmConfig | null;
151
+ confidentialRows: number;
152
+ queueConfidential: number;
153
+ }): boolean;