@gamaze/hicortex 0.26.3 → 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 (44) hide show
  1. package/README.md +7 -2
  2. package/dist/backfill-privacy.d.ts +82 -0
  3. package/dist/backfill-privacy.js +193 -0
  4. package/dist/classification.d.ts +153 -0
  5. package/dist/classification.js +265 -0
  6. package/dist/classify-domains.js +24 -7
  7. package/dist/cli.js +31 -0
  8. package/dist/cluster.d.ts +15 -8
  9. package/dist/cluster.js +10 -3
  10. package/dist/consolidate.d.ts +31 -2
  11. package/dist/consolidate.js +193 -40
  12. package/dist/db.js +26 -1
  13. package/dist/dedup.d.ts +5 -3
  14. package/dist/dedup.js +26 -12
  15. package/dist/distill-queue.d.ts +25 -1
  16. package/dist/distill-queue.js +47 -7
  17. package/dist/graph.d.ts +28 -3
  18. package/dist/graph.js +46 -4
  19. package/dist/init.d.ts +18 -9
  20. package/dist/init.js +111 -81
  21. package/dist/mcp-server.js +186 -32
  22. package/dist/nightly.js +33 -7
  23. package/dist/recall-index.d.ts +19 -9
  24. package/dist/recall-index.js +14 -4
  25. package/dist/recall-precision.js +3 -1
  26. package/dist/reconsolidation.d.ts +10 -0
  27. package/dist/reconsolidation.js +80 -17
  28. package/dist/redact.d.ts +9 -1
  29. package/dist/redact.js +32 -1
  30. package/dist/rescore-importance.js +21 -4
  31. package/dist/retrieval.d.ts +23 -6
  32. package/dist/retrieval.js +41 -15
  33. package/dist/seed-lesson.js +3 -1
  34. package/dist/storage.d.ts +23 -4
  35. package/dist/storage.js +38 -9
  36. package/dist/type-classify.js +22 -7
  37. package/dist/types.d.ts +81 -15
  38. package/dist/uninstall.js +6 -5
  39. package/hermes-plugin/hicortex/README.md +4 -0
  40. package/hermes-plugin/hicortex/client.py +36 -9
  41. package/hermes-plugin/hicortex/plugin.yaml +1 -1
  42. package/hermes-plugin/hicortex/provider.py +28 -6
  43. package/package.json +1 -1
  44. package/server.json +2 -2
@@ -301,6 +301,9 @@ function createRecallRetrieveFn(deps) {
301
301
  project: filters?.project,
302
302
  missionDomains: filters?.mission_domains,
303
303
  queryEmbedding: queryVec,
304
+ // #332: the classification gate — hard omit unless the requesting
305
+ // agent is a circle member (the factory was built with membership).
306
+ includeConfidential: deps.includeConfidential === true,
304
307
  // #329: shared per-request FTS list. The recall path never passes
305
308
  // sourceAgent, so the memo is keyed on (query, fetchLimit) only —
306
309
  // exactly the two things retrieve() would pass to searchFts.
@@ -563,11 +566,12 @@ async function handleRecallIndex(deps, body) {
563
566
  * citation ids agents are taught must work here like on /update, /delete.
564
567
  * - A successful fetch is real use: access_count + 1 (strengthen).
565
568
  *
566
- * 0.16.x: the `privacy` filter gate was removed — the column is vestigial and
567
- * never filtered. Callers may still send a `privacy` field (backward compat)
568
- * but it is ignored.
569
+ * #332: `opts.includeConfidential` (default false) is the classification gate
570
+ * — a confidential memory fetched by a non-member answers 404 BEFORE any
571
+ * side effect (no strengthen, no precision event: existence is not revealed).
572
+ * Members (the adapter passes true) fetch both pools normally.
569
573
  */
570
- function handleMemoryGet(db, query, deps) {
574
+ function handleMemoryGet(db, query, deps, opts) {
571
575
  const id = typeof query.id === "string" ? query.id : "";
572
576
  if (!id)
573
577
  return { status: 400, body: { error: "Missing 'id'" } };
@@ -581,6 +585,12 @@ function handleMemoryGet(db, query, deps) {
581
585
  const mem = storage.getMemory(db, fullId);
582
586
  if (!mem)
583
587
  return notFound;
588
+ // #332: the gate fires BEFORE strengthenMemory + the fetch recorder — a
589
+ // refused fetch must leave no trace on the row and record no event (the
590
+ // same 404 shape an unknown id produces).
591
+ if (mem.privacy === "confidential" && opts?.includeConfidential !== true) {
592
+ return notFound;
593
+ }
584
594
  storage.strengthenMemory(db, fullId, new Date().toISOString());
585
595
  // #476: one kind='fetch' precision event per successful fetch (the use
586
596
  // signal for Level 2 / divergence). Fail-soft — the fetch result is never
@@ -216,7 +216,9 @@ function createStandingContextBasis(config) {
216
216
  // Read errors degrade to an empty lesson half — the basis is a reference,
217
217
  // not a ledger.
218
218
  try {
219
- for (const lesson of storage.getLessons(db, 30))
219
+ // #332: the basis is a server-internal redundancy reference over the
220
+ // whole lesson store (no agent sees it) — ungated by design.
221
+ for (const lesson of storage.getLessons(db, 30, null, { includeConfidential: true }))
220
222
  texts.push(lesson.content);
221
223
  }
222
224
  catch (err) {
@@ -158,6 +158,16 @@ export interface ReconsolidationOptions {
158
158
  * the real capture.ts lock. DedupOptions.acquireLock pattern.
159
159
  */
160
160
  acquireLock?: typeof acquireCaptureLock;
161
+ /**
162
+ * #332: the CONFIDENTIAL model client. Every LLM call in this stage carries
163
+ * memory content (scout shape, pair verdicts, rewrite prompts) — each call
164
+ * selects the client matching the memories it reads; when the confidential
165
+ * side is needed and absent, that pair/group holds (skipped_infra counts,
166
+ * retried next run), never judged on the main model. The deterministic
167
+ * merge zone needs no client but is class-pure via the classification rail
168
+ * (clusterMetadataMismatch).
169
+ */
170
+ confidentialLlm?: LlmClient | null;
161
171
  }
162
172
  /** The stage report (typed once, in ConsolidationReport — field list there). */
163
173
  export type ReconsolidationStageResult = NonNullable<ConsolidationReport["stages"]["reconsolidation"]>;
@@ -139,6 +139,7 @@ exports.bandForCosine = bandForCosine;
139
139
  exports.stageReconsolidation = stageReconsolidation;
140
140
  exports.rollbackHistoryRow = rollbackHistoryRow;
141
141
  exports.runHistoryCommand = runHistoryCommand;
142
+ const classification_js_1 = require("./classification.js");
142
143
  const retrieval_js_1 = require("./retrieval.js");
143
144
  const storage = __importStar(require("./storage.js"));
144
145
  const state_js_1 = require("./state.js");
@@ -577,9 +578,15 @@ function accumulateBandStat(cumulative, run) {
577
578
  */
578
579
  async function findOlderCorrectionNeighbors(db, candidate, embedFn, minSimilarity) {
579
580
  const embedding = storage.getStoredEmbedding(db, candidate.id) ?? (await embedFn(candidate.content));
581
+ // #332: pairing is class-pure — the KNN pool is unscoped, the filter
582
+ // narrows it to the candidate's own class (no reconsolidation pair ever
583
+ // mixes classes; NULL privacy reads standard).
584
+ const candidateConfidential = candidate.privacy === "confidential";
580
585
  return storage
581
586
  .vectorSearch(db, embedding, CORRECTION_NEIGHBOR_POOL, [candidate.id])
582
- .filter((n) => n.created_at < candidate.created_at && (0, retrieval_js_1.l2ToCosine)(n.distance) >= minSimilarity)
587
+ .filter((n) => (n.privacy === "confidential") === candidateConfidential &&
588
+ n.created_at < candidate.created_at &&
589
+ (0, retrieval_js_1.l2ToCosine)(n.distance) >= minSimilarity)
583
590
  .sort((a, b) => (0, retrieval_js_1.l2ToCosine)(b.distance) - (0, retrieval_js_1.l2ToCosine)(a.distance))
584
591
  .slice(0, CORRECTION_NEIGHBOR_TOP_K);
585
592
  }
@@ -600,8 +607,12 @@ function findScoutNeighbors(db, candidate, references, candidateEmbedding) {
600
607
  return [];
601
608
  try {
602
609
  const hits = storage.searchFts(db, references, CORRECTION_NEIGHBOR_POOL);
610
+ // #332: the scout source is class-pure too — same filter as the KNN
611
+ // source (the FTS pool is unscoped; the filter narrows it).
612
+ const candidateConfidential = candidate.privacy === "confidential";
603
613
  return hits
604
- .filter((m) => m.id !== candidate.id &&
614
+ .filter((m) => (m.privacy === "confidential") === candidateConfidential &&
615
+ m.id !== candidate.id &&
605
616
  m.created_at < candidate.created_at &&
606
617
  m.status !== "absorbed")
607
618
  .slice(0, CORRECTION_NEIGHBOR_TOP_K)
@@ -699,6 +710,16 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
699
710
  // hit() logs event=deadline_deferred once per stage name.
700
711
  const deadline = options.deadline;
701
712
  const deadlineHit = (stageLabel = exports.RECONSOLIDATION_STAGE_LABEL) => deadline?.hit(stageLabel) ?? false;
713
+ // ---- #332 per-pool client selection. Every LLM call below goes through
714
+ // clientFor(...); a null answer means "confidential text, no confidential
715
+ // model" — the pair/group HOLDS (skippedInfra, retried next run), never
716
+ // judged on the standard client. (Named llmPair — the merge-batch loop
717
+ // below has its own local `pair` per queued merge.)
718
+ const llmPair = { standard: llm, confidential: options.confidentialLlm ?? null };
719
+ const clientFor = (...mems) => {
720
+ const confidential = mems.some((m) => m.privacy === "confidential");
721
+ return (0, classification_js_1.clientForPool)(llmPair, confidential ? "confidential" : "standard");
722
+ };
702
723
  // Per-run verdict statistics by cosine band (#392) — report snapshot here,
703
724
  // cumulative series in state.json at stage end (never on dry-run).
704
725
  const bands = buildResolutionBands(minSimilarity, autoMergeThreshold);
@@ -933,7 +954,14 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
933
954
  explicitDivergent++; // mark's target is gone/invisible — retain link, nothing to upgrade
934
955
  continue;
935
956
  }
936
- const { verdict, usage } = await classifyPair(llm, target.content, candidate.content);
957
+ // #332: an explicit mark may legally cross classes (an agent marked
958
+ // across pools) — the verdict call selects its client by BOTH sides.
959
+ const markClient = clientFor(target, candidate);
960
+ if (!markClient) {
961
+ skippedInfra++; // held — no confidential model for a confidential side
962
+ continue;
963
+ }
964
+ const { verdict, usage } = await classifyPair(markClient, target.content, candidate.content);
937
965
  budget.recordUsage(exports.RECONSOLIDATION_STAGE_LABEL, usage);
938
966
  pairsEvaluated++;
939
967
  if (candidate.__rowid <= prevScannedRowid)
@@ -984,21 +1012,30 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
984
1012
  }
985
1013
  else {
986
1014
  scoutScanned++;
987
- try {
988
- const r = await llm.complete(buildScoutShapePrompt(candidate.content));
989
- budget.recordUsage(exports.RECONSOLIDATION_STAGE_LABEL, r.usage);
990
- const shape = parseScoutShape(r.text);
991
- if (!shape) {
992
- skippedInfra++;
1015
+ // #332: the shape call reads the candidate's content — pool-matched
1016
+ // client; held (skip the scout source for this memory, fail-soft like
1017
+ // a parse failure) when the confidential side is unconfigured.
1018
+ const scoutClient = clientFor(candidate);
1019
+ if (!scoutClient) {
1020
+ skippedInfra++;
1021
+ }
1022
+ else {
1023
+ try {
1024
+ const r = await scoutClient.complete(buildScoutShapePrompt(candidate.content));
1025
+ budget.recordUsage(exports.RECONSOLIDATION_STAGE_LABEL, r.usage);
1026
+ const shape = parseScoutShape(r.text);
1027
+ if (!shape) {
1028
+ skippedInfra++;
1029
+ }
1030
+ else if (shape.correction) {
1031
+ scoutCorrectionShaped++;
1032
+ scoutReferences = shape.references;
1033
+ }
993
1034
  }
994
- else if (shape.correction) {
995
- scoutCorrectionShaped++;
996
- scoutReferences = shape.references;
1035
+ catch {
1036
+ skippedInfra++;
997
1037
  }
998
1038
  }
999
- catch {
1000
- skippedInfra++;
1001
- }
1002
1039
  }
1003
1040
  }
1004
1041
  // ---- AC2: detection pairs against older neighbors — TWO sources (#393 B):
@@ -1077,7 +1114,15 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
1077
1114
  stopScan = true; // the boundary below still applies what this candidate already confirmed
1078
1115
  break;
1079
1116
  }
1080
- const { verdict, usage } = await classifyPair(llm, entry.mem.content, candidate.content);
1117
+ // #332: the verdict call reads BOTH memories — pool-matched client
1118
+ // (detection pairs are class-pure by construction, so the pool is one
1119
+ // value; a held pair counts skippedInfra and re-detects next run).
1120
+ const verdictClient = clientFor(entry.mem, candidate);
1121
+ if (!verdictClient) {
1122
+ skippedInfra++;
1123
+ continue;
1124
+ }
1125
+ const { verdict, usage } = await classifyPair(verdictClient, entry.mem.content, candidate.content);
1081
1126
  budget.recordUsage(exports.RECONSOLIDATION_STAGE_LABEL, usage);
1082
1127
  pairsEvaluated++;
1083
1128
  if (candidate.__rowid <= prevScannedRowid)
@@ -1242,6 +1287,13 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
1242
1287
  console.log(`[hicortex] Reconsolidation: merge of ${pair.oldId.slice(0, 8)} + ${pair.newId.slice(0, 8)} ` +
1243
1288
  `skipped (project mismatch) — both kept`);
1244
1289
  }
1290
+ else if (result.reason === "classification_mismatch") {
1291
+ // #332: the pools never cross — a cross-class pair (only
1292
+ // reachable via a legacy cross-class link) stays live on
1293
+ // both sides; the verdict was rendered, the cursor advances.
1294
+ console.log(`[hicortex] Reconsolidation: merge of ${pair.oldId.slice(0, 8)} + ${pair.newId.slice(0, 8)} ` +
1295
+ `skipped (classification mismatch) — both kept`);
1296
+ }
1245
1297
  else if (result.reason === "conflict_linked") {
1246
1298
  // #393 guard-C: the pair is conflicts-linked (operator-planted
1247
1299
  // or a prior verdict) — never blended; the cursor advances,
@@ -1285,8 +1337,19 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
1285
1337
  const triggersArg = group.triggers.map((t) => ({ id: t.id, content: t.memory.content }));
1286
1338
  let contract = null;
1287
1339
  let infraError = false;
1340
+ // #332: the rewrite prompt reads the target AND every trigger —
1341
+ // pool-matched client (groups are class-pure by construction: their
1342
+ // pairs came from the class-pure detection sources). Held when the
1343
+ // confidential side is unconfigured: the group defers untouched.
1344
+ const rewriteClient = clientFor(group.target, ...group.triggers.map((t) => t.memory));
1345
+ if (!rewriteClient) {
1346
+ skippedInfra++;
1347
+ rewritesDeferred = true;
1348
+ stopScan = true;
1349
+ break;
1350
+ }
1288
1351
  try {
1289
- const r = await llm.complete(buildRewritePrompt(group.target.content, triggersArg));
1352
+ const r = await rewriteClient.complete(buildRewritePrompt(group.target.content, triggersArg));
1290
1353
  contract = parseRewriteReply(r.text, group.triggers.map((t) => t.id), group.target.content);
1291
1354
  budget.recordUsage(exports.RECONSOLIDATION_STAGE_LABEL, r.usage);
1292
1355
  }
package/dist/redact.d.ts CHANGED
@@ -34,12 +34,20 @@ export interface RedactionConfig {
34
34
  extraPatterns?: string[];
35
35
  /** Replacement string. Default: "[REDACTED]". */
36
36
  replacement?: string;
37
+ /**
38
+ * #332: the confidential preset — DEFAULT_PATTERNS PLUS emails and phone
39
+ * numbers. Set by the /distill intake for confidential deliveries only;
40
+ * standard deliveries keep today's pattern set byte-identically.
41
+ */
42
+ extended?: boolean;
37
43
  }
38
44
  /**
39
45
  * Redact secrets and PII from text.
40
46
  *
41
47
  * @param text The raw transcript text to redact
42
- * @param config Optional configuration (extra patterns, replacement string)
48
+ * @param config Optional configuration (extra patterns, replacement string,
49
+ * and `extended: true` for the confidential preset — #332: DEFAULT_PATTERNS
50
+ * plus emails and phone numbers)
43
51
  * @returns The redacted text and count of redactions applied
44
52
  */
45
53
  export declare function redact(text: string, config?: RedactionConfig): RedactionResult;
package/dist/redact.js CHANGED
@@ -60,11 +60,31 @@ const DEFAULT_PATTERNS = [
60
60
  // Same lookbehind to avoid URL false positives
61
61
  { name: "linux_path", pattern: /(?<![:/])\/home\/[a-zA-Z0-9._-]+/g },
62
62
  ];
63
+ /**
64
+ * The CONFIDENTIAL preset (#332 redaction pilot, the #558 gap): everything in
65
+ * DEFAULT_PATTERNS plus emails and phone numbers. Confidential-pool content
66
+ * is the material an inner-circle agent captures (finance, medical, personal
67
+ * correspondence), so its intake redacts contact identifiers BEFORE queueing
68
+ * — standard deliveries keep today's set unchanged (the general email/phone
69
+ * fix for standard rows is deliberately out of scope, #332 non-goals).
70
+ */
71
+ const CONFIDENTIAL_PATTERNS = [
72
+ // Email addresses — local@domain with a TLD. The negative lookbehind keeps
73
+ // already-redacted [REDACTED] markers (no @) from re-matching; surrounding
74
+ // angle brackets (markdown autolinks) are not captured.
75
+ { name: "email", pattern: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g },
76
+ // Phone numbers — international E.164 (+4670...) and common dashed/dotted/
77
+ // spaced national forms, 7-15 digits total. Word-ish boundaries avoid
78
+ // matching inside longer digit runs (order ids, timestamps).
79
+ { name: "phone", pattern: /(?:\+\d{1,3}[\s.-]?)?(?:\(\d{1,4}\)[\s.-]?)?\d{2,4}(?:[\s.-]\d{2,4}){1,4}(?!\d)/g },
80
+ ];
63
81
  /**
64
82
  * Redact secrets and PII from text.
65
83
  *
66
84
  * @param text The raw transcript text to redact
67
- * @param config Optional configuration (extra patterns, replacement string)
85
+ * @param config Optional configuration (extra patterns, replacement string,
86
+ * and `extended: true` for the confidential preset — #332: DEFAULT_PATTERNS
87
+ * plus emails and phone numbers)
68
88
  * @returns The redacted text and count of redactions applied
69
89
  */
70
90
  function redact(text, config) {
@@ -82,6 +102,17 @@ function redact(text, config) {
82
102
  return replacement;
83
103
  });
84
104
  }
105
+ // #332: the confidential preset's extra patterns (emails + phones) — only
106
+ // when `extended` is set (confidential deliveries at /distill intake).
107
+ if (config?.extended) {
108
+ for (const { pattern } of CONFIDENTIAL_PATTERNS) {
109
+ pattern.lastIndex = 0;
110
+ result = result.replace(pattern, () => {
111
+ count++;
112
+ return replacement;
113
+ });
114
+ }
115
+ }
85
116
  // Apply user-configured extra patterns
86
117
  if (config?.extraPatterns) {
87
118
  for (const patternStr of config.extraPatterns) {
@@ -31,7 +31,7 @@ const paths_js_1 = require("./paths.js");
31
31
  const db_js_1 = require("./db.js");
32
32
  const state_js_1 = require("./state.js");
33
33
  const consolidate_js_1 = require("./consolidate.js");
34
- const llm_js_1 = require("./llm.js");
34
+ const classification_js_1 = require("./classification.js");
35
35
  const backup_js_1 = require("./backup.js");
36
36
  const config_read_js_1 = require("./config-read.js");
37
37
  const calibration_js_1 = require("./calibration.js");
@@ -121,15 +121,20 @@ async function runRescoreImportance(options = {}) {
121
121
  `This machine is a client of ${config.serverUrl ?? "a remote server"} — run it on the server.`);
122
122
  }
123
123
  let llm;
124
+ // #332: the confidential client — confidential rows in a slice score on it;
125
+ // without one they hold (the slice's cursor holds below them, retried when
126
+ // the model is configured).
127
+ let confidentialLlm = null;
124
128
  if (options.llm) {
125
129
  llm = options.llm;
126
130
  }
127
131
  else {
128
- const resolved = (0, llm_js_1.resolveSavedLlmConfig)(config);
129
- if (!resolved.config) {
132
+ const resolved = (0, classification_js_1.resolveLlmPair)(config);
133
+ if (!resolved.pair) {
130
134
  throw new Error("[hicortex] rescore-importance: no LLM configured — run `npx @gamaze/hicortex init`.");
131
135
  }
132
- llm = new llm_js_1.LlmClient(resolved.config);
136
+ llm = resolved.pair.standard;
137
+ confidentialLlm = resolved.pair.confidential;
133
138
  }
134
139
  const dbPath = (0, db_js_1.resolveDbPath)(options.dbPath);
135
140
  const db = (0, db_js_1.initDb)(dbPath);
@@ -178,10 +183,22 @@ async function runRescoreImportance(options = {}) {
178
183
  const sliceRows = chunk.slice(i, i + LLM_SLICE);
179
184
  const memories = memoriesForIds(db, sliceRows);
180
185
  const r = await (0, consolidate_js_1.scoreMemoriesImportance)(db, memories, llm, {
186
+ confidentialLlm,
181
187
  onBatch: (written, batchFailed) => {
182
188
  calls++;
183
189
  },
184
190
  });
191
+ if ((r.skipped_confidential ?? 0) > 0) {
192
+ // #332: confidential rows in this slice are held (no confidential
193
+ // model). Hold the cursor BELOW the slice — never advance past unscored
194
+ // rows; they retry once llmConfidential* is configured (the nightly's
195
+ // watermark pool also re-finds them).
196
+ aborted = true;
197
+ console.warn(`[hicortex] rescore-importance ABORTED: ${r.skipped_confidential} confidential row(s) ` +
198
+ `in the slice at rowid ${sliceRows[0].__rowid} need a confidential model ` +
199
+ `(llmConfidentialBaseUrl/ApiKey). Cursor held — re-run after configuring.`);
200
+ break;
201
+ }
185
202
  if (r.failed > 0) {
186
203
  // The slice's call threw (endpoint down) or a write failed — nothing
187
204
  // usable came out of it. Stop; the cursor stays at the last
@@ -285,12 +285,13 @@ export interface EmbedFn {
285
285
  *
286
286
  * #203 retrieval scoping: `project` and `missionDomains` are SOFT affinity
287
287
  * terms in computeScore (zero-boost neutral, never a penalty), NOT filters.
288
- * `privacy` is NOT a filter (0.16.x: the column is fully vestigial — stored,
289
- * never filtered; the distiller no longer sets it and retrieval ignores it
290
- * entirely). `sourceAgent` remains a hard filter (kept for completeness; no
291
- * production caller currently passes it). When neither project nor
292
- * missionDomains is sent, scoring is byte-identical to pre-#203 — the
293
- * kill-switch / no-op guarantee.
288
+ * `sourceAgent` remains a hard filter (kept for completeness; no production
289
+ * caller currently passes it). #332: `privacy` is a HARD filter again — the
290
+ * two-level classification gate (includeConfidential, default false = omit
291
+ * confidential rows on every channel; TRUE for circle-member requests). On an
292
+ * install with no confidential rows the gate is a no-op — byte-identical to
293
+ * pre-#332. When neither project nor missionDomains is sent, scoring is
294
+ * byte-identical to pre-#203 — the kill-switch / no-op guarantee.
294
295
  */
295
296
  export declare function retrieve(db: Database.Database, embedFn: EmbedFn, query: string, options?: {
296
297
  limit?: number;
@@ -328,6 +329,16 @@ export declare function retrieve(db: Database.Database, embedFn: EmbedFn, query:
328
329
  * the live clock (byte-identical to pre-#458). Mirrors the
329
330
  * injectable-clock idiom of run-deadline.ts; see eval/eval-clock.ts. */
330
331
  now?: Date;
332
+ /**
333
+ * #332 classification gate. FALSE (the default) = hard omit: confidential
334
+ * rows never enter the candidate set on ANY channel (vector, FTS, graph
335
+ * pull-in, belief-walk terminals) — they cannot consume a top-k slot
336
+ * either, because the filter runs at candidate-build time, not post-hoc.
337
+ * TRUE only for requests whose `agent` is a circle member (the additive
338
+ * circle: members see both pools). On an install with no confidential
339
+ * rows the predicate is a no-op — byte-identical behavior.
340
+ */
341
+ includeConfidential?: boolean;
331
342
  }): Promise<MemorySearchResult[]>;
332
343
  /**
333
344
  * Get recent context, optionally filtered by project.
@@ -335,4 +346,10 @@ export declare function retrieve(db: Database.Database, embedFn: EmbedFn, query:
335
346
  export declare function searchRecent(db: Database.Database, options?: {
336
347
  project?: string | null;
337
348
  limit?: number;
349
+ /**
350
+ * #332 classification gate — same contract as retrieve()'s: FALSE (the
351
+ * default) hard-omits confidential rows from the candidate set AND the
352
+ * belief-walk terminals; TRUE only for circle-member requests.
353
+ */
354
+ includeConfidential?: boolean;
338
355
  }): MemorySearchResult[];
package/dist/retrieval.js CHANGED
@@ -784,12 +784,13 @@ function reciprocalRankFusion(rankedLists, k = DEFAULT_RRF_K) {
784
784
  *
785
785
  * #203 retrieval scoping: `project` and `missionDomains` are SOFT affinity
786
786
  * terms in computeScore (zero-boost neutral, never a penalty), NOT filters.
787
- * `privacy` is NOT a filter (0.16.x: the column is fully vestigial — stored,
788
- * never filtered; the distiller no longer sets it and retrieval ignores it
789
- * entirely). `sourceAgent` remains a hard filter (kept for completeness; no
790
- * production caller currently passes it). When neither project nor
791
- * missionDomains is sent, scoring is byte-identical to pre-#203 — the
792
- * kill-switch / no-op guarantee.
787
+ * `sourceAgent` remains a hard filter (kept for completeness; no production
788
+ * caller currently passes it). #332: `privacy` is a HARD filter again — the
789
+ * two-level classification gate (includeConfidential, default false = omit
790
+ * confidential rows on every channel; TRUE for circle-member requests). On an
791
+ * install with no confidential rows the gate is a no-op — byte-identical to
792
+ * pre-#332. When neither project nor missionDomains is sent, scoring is
793
+ * byte-identical to pre-#203 — the kill-switch / no-op guarantee.
793
794
  */
794
795
  async function retrieve(db, embedFn, query, options) {
795
796
  const limit = options?.limit ?? recallDefaults.searchLimit;
@@ -797,6 +798,11 @@ async function retrieve(db, embedFn, query, options) {
797
798
  const sourceAgent = options?.sourceAgent;
798
799
  const missionDomains = options?.missionDomains;
799
800
  const now = options?.now ?? new Date();
801
+ // #332: hard-omit gate — confidential candidates are dropped on EVERY
802
+ // channel at candidate-build time (never post-hoc, so they never consume a
803
+ // top-k slot). `privacy !== 'confidential'` is NULL-safe by construction.
804
+ const includeConfidential = options?.includeConfidential === true;
805
+ const visible = (m) => includeConfidential || m.privacy !== "confidential";
800
806
  // #203 affinity scope — passed to computeScore for every candidate. Built
801
807
  // once; absent fields yield no boost (zero-boost neutral).
802
808
  const scope = project || (missionDomains && missionDomains.length > 0)
@@ -810,15 +816,18 @@ async function retrieve(db, embedFn, query, options) {
810
816
  // median project) ~1% of the corpus, starving every filtered query.
811
817
  // #203: project is NO LONGER a filter (soft affinity now), so it does not
812
818
  // trigger over-fetch; only sourceAgent still does (it remains a hard filter).
813
- // 0.16.x: privacy is no longer a filter either (column is vestigial).
819
+ // #332: the classification gate filters in JS after both lists return (the
820
+ // #192 post-filter pattern) — on the default no-confidential-rows install it
821
+ // costs one comparison per candidate and changes nothing.
814
822
  const filtered = Boolean(sourceAgent);
815
823
  const fetchLimit = filtered ? Math.min(limit * 20, 200) : limit * 3;
816
824
  let vecCandidates = storage.vectorSearch(db, queryEmbedding, fetchLimit, []);
817
825
  let ftsCandidates = [];
818
826
  try {
819
827
  // sourceAgent is pushed into the FTS SQL (hard filter). project is NOT (it
820
- // is a soft affinity boost in computeScore as of #203). privacy is NOT
821
- // (0.16.x: vestigial column, never filtered). With a caller-provided
828
+ // is a soft affinity boost in computeScore as of #203). privacy is NOT in
829
+ // the SQL — the #332 gate filters the returned rows once (below), so the
830
+ // shared #329 request memo stays provider-agnostic. With a caller-provided
822
831
  // provider (#329 request-level memo) the same list is shared across the
823
832
  // retrieves of one recall request instead of re-executed.
824
833
  ftsCandidates = options?.ftsCandidates
@@ -833,10 +842,14 @@ async function retrieve(db, embedFn, query, options) {
833
842
  }
834
843
  // Post-filter vector candidates (sqlite-vec can't filter). sourceAgent stays
835
844
  // a hard filter (see options doc); project is scored not filtered (#203);
836
- // privacy is no longer filtered (0.16.x — vestigial).
845
+ // #332: the classification gate is a hard filter on every channel.
846
+ vecCandidates = vecCandidates.filter(visible);
837
847
  if (sourceAgent) {
838
848
  vecCandidates = vecCandidates.filter((c) => c.source_agent === sourceAgent);
839
849
  }
850
+ // The FTS list carries the same gate (the /recall-index memo provider feeds
851
+ // from storage.searchFts — filter here so the shared memo is gated once).
852
+ ftsCandidates = ftsCandidates.filter((c) => visible(c));
840
853
  // 3. RRF fusion (#205: per-list weights + config-driven k). The vector list
841
854
  // carries the composite-side affinity in the next step, so we let it dominate
842
855
  // RRF too — the FTS list is down-weighted to break token-collision ties that
@@ -876,8 +889,11 @@ async function retrieve(db, embedFn, query, options) {
876
889
  if (mem.status === "absorbed")
877
890
  continue;
878
891
  // #203: project check removed — project is a soft affinity in computeScore,
879
- // not a filter. 0.16.x: privacy check removed — the column is vestigial,
880
- // never filtered. sourceAgent stays a hard filter.
892
+ // not a filter. sourceAgent stays a hard filter. #332: the classification
893
+ // gate applies to graph-discovered candidates exactly like the retrieval
894
+ // channels — a link into the confidential pool is not a side door.
895
+ if (!visible(mem))
896
+ continue;
881
897
  if (sourceAgent && mem.source_agent !== sourceAgent)
882
898
  continue;
883
899
  candidateMap.set(gid, { mem, distance: DEFAULT_GRAPH_DISTANCE, source: "graph" });
@@ -968,7 +984,10 @@ async function retrieve(db, embedFn, query, options) {
968
984
  // in retrieve(), and the walk must not bypass it — a terminal authored by
969
985
  // a different agent never slips into recall through its link entry
970
986
  // (mirrors the graph pull-in guard above; fail-soft: the ancestor keeps
971
- // its slot, demoted).
987
+ // its slot, demoted). #332: same for the classification gate — a
988
+ // confidential terminal never surfaces through a supersession chain.
989
+ if (!visible(mem))
990
+ return null;
972
991
  if (sourceAgent && mem.source_agent !== sourceAgent)
973
992
  return null;
974
993
  const connCount = storage.getLinks(db, terminalId, "both").length;
@@ -997,6 +1016,8 @@ function searchRecent(db, options) {
997
1016
  const limit = options?.limit ?? recallDefaults.recentLimit;
998
1017
  const project = options?.project;
999
1018
  const now = new Date();
1019
+ const includeConfidential = options?.includeConfidential === true;
1020
+ const visible = (m) => includeConfidential || m.privacy !== "confidential";
1000
1021
  // #192 breadth: 30 → 180-day default window (config recentWindowDays).
1001
1022
  // "Recent" for a long-lived corpus is a season, not a month; the narrow
1002
1023
  // window kept queryless recall re-serving the same few weeks.
@@ -1004,7 +1025,9 @@ function searchRecent(db, options) {
1004
1025
  if (project) {
1005
1026
  candidates = candidates.filter((c) => c.project === project);
1006
1027
  }
1007
- // 0.16.x: privacy filter removed — the column is vestigial, never filtered.
1028
+ // #332: the classification gate (hard omit at candidate-build time — a
1029
+ // confidential row never consumes a top-k slot).
1030
+ candidates = candidates.filter(visible);
1008
1031
  if (candidates.length === 0)
1009
1032
  return [];
1010
1033
  const allIds = candidates.map((c) => c.id);
@@ -1039,7 +1062,10 @@ function searchRecent(db, options) {
1039
1062
  // edges are discovered corpus-wide (no project predicate), so a terminal
1040
1063
  // in a different project never slips into project-scoped recall through
1041
1064
  // its link entry (mirrors retrieve()'s sourceAgent guard; fail-soft: the
1042
- // ancestor keeps its slot, demoted).
1065
+ // ancestor keeps its slot, demoted). #332: same for the classification
1066
+ // gate.
1067
+ if (!visible(mem))
1068
+ return null;
1043
1069
  if (project && mem.project !== project)
1044
1070
  return null;
1045
1071
  const connCount = storage.getLinks(db, terminalId, "both").length;
@@ -54,7 +54,9 @@ Use hicortex_lessons to check for new insights. If a lesson has high confidence,
54
54
  **Generated:** seed-lesson`;
55
55
  async function injectSeedLesson(database, log = console.log) {
56
56
  try {
57
- const existing = storage.getLessons(database, 365);
57
+ // #332: existence check over the whole lesson store (server-internal —
58
+ // the seed must never re-inject because the gate hid it).
59
+ const existing = storage.getLessons(database, 365, null, { includeConfidential: true });
58
60
  const hasSeed = existing.some((l) => l.content.includes("1% Daily Self-Improvement") ||
59
61
  l.source_agent === "hicortex/seed");
60
62
  if (hasSeed)
package/dist/storage.d.ts CHANGED
@@ -3,11 +3,20 @@
3
3
  * Ported from hicortex/storage.py. All functions are synchronous (better-sqlite3).
4
4
  */
5
5
  import type Database from "better-sqlite3";
6
- import type { Memory, MemoryLink, InsertMemoryOptions } from "./types.js";
6
+ import type { Memory, MemoryLink, InsertMemoryOptions, MemoryPrivacy } from "./types.js";
7
7
  /**
8
8
  * Serialize a Float32Array embedding to a Buffer for sqlite-vec.
9
9
  */
10
10
  export declare function embedToBlob(embedding: Float32Array): Buffer;
11
+ /**
12
+ * Normalize any wire/unknown privacy value into the #332 classification
13
+ * vocabulary — the insert-boundary guard that keeps legacy values ('WORK',
14
+ * 'PERSONAL', blank, NULL, wrong type) out of the column after migration
15
+ * v27 normalized history. 'confidential' passes through (it is only ever
16
+ * server-derived by the time it reaches storage); everything else becomes
17
+ * 'standard' (the fail-closed default class).
18
+ */
19
+ export declare function normalizeStoredPrivacy(v: unknown): MemoryPrivacy;
11
20
  /**
12
21
  * #421 machine × harness identity: optional capture-machine provenance on
13
22
  * /ingest + /distill. A string, trimmed, capped at 128 chars; anything else
@@ -269,7 +278,7 @@ export declare function insertMemoriesBatch(db: Database.Database, memories: Arr
269
278
  sourceDomain?: string | null;
270
279
  sourceSession?: string | null;
271
280
  project?: string | null;
272
- privacy?: string;
281
+ privacy?: MemoryPrivacy;
273
282
  memoryType?: string;
274
283
  baseStrength?: number;
275
284
  }>): number;
@@ -290,8 +299,18 @@ export declare function getRecentMemories(db: Database.Database, days?: number,
290
299
  export declare function getMemoriesSince(db: Database.Database, sinceIso: string): Memory[];
291
300
  /**
292
301
  * Get lesson-type memories from the last N days.
293
- */
294
- export declare function getLessons(db: Database.Database, days?: number, project?: string | null): Memory[];
302
+ *
303
+ * #332: lessons inherit their pool's classification (confidential-pool
304
+ * reflection stamps them confidential at birth), and the SAME membership gate
305
+ * applies — `includeConfidential` defaults to FALSE (fail-closed: the
306
+ * agent-facing consumers — /learnings, the MCP lessons tools — serve standard
307
+ * lessons only unless the requester is a circle member). Server-internal
308
+ * consumers (nightly telemetry, the seed check, the recall-precision standing
309
+ * basis) pass true explicitly: they run inside the server, on the whole store.
310
+ */
311
+ export declare function getLessons(db: Database.Database, days?: number, project?: string | null, opts?: {
312
+ includeConfidential?: boolean;
313
+ }): Memory[];
295
314
  /**
296
315
  * Get memories older than cutoff with zero access (prune candidates).
297
316
  */