@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
@@ -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
  */
package/dist/storage.js CHANGED
@@ -39,6 +39,7 @@ var __importStar = (this && this.__importStar) || (function () {
39
39
  Object.defineProperty(exports, "__esModule", { value: true });
40
40
  exports.FTS_MATCH_MAX_TOKENS = void 0;
41
41
  exports.embedToBlob = embedToBlob;
42
+ exports.normalizeStoredPrivacy = normalizeStoredPrivacy;
42
43
  exports.sanitizeSourceMachine = sanitizeSourceMachine;
43
44
  exports.insertMemory = insertMemory;
44
45
  exports.resolveMemoryId = resolveMemoryId;
@@ -89,6 +90,17 @@ function embedToBlob(embedding) {
89
90
  function rowToMemory(row) {
90
91
  return row;
91
92
  }
93
+ /**
94
+ * Normalize any wire/unknown privacy value into the #332 classification
95
+ * vocabulary — the insert-boundary guard that keeps legacy values ('WORK',
96
+ * 'PERSONAL', blank, NULL, wrong type) out of the column after migration
97
+ * v27 normalized history. 'confidential' passes through (it is only ever
98
+ * server-derived by the time it reaches storage); everything else becomes
99
+ * 'standard' (the fail-closed default class).
100
+ */
101
+ function normalizeStoredPrivacy(v) {
102
+ return v === "confidential" ? "confidential" : "standard";
103
+ }
92
104
  // ---------------------------------------------------------------------------
93
105
  // Single memory CRUD
94
106
  // ---------------------------------------------------------------------------
@@ -122,9 +134,17 @@ function insertMemory(db, content, embedding, opts = {}) {
122
134
  .prepare(`INSERT OR IGNORE INTO memories
123
135
  (id, content, base_strength, last_accessed, access_count,
124
136
  created_at, ingested_at, source_agent, source_agent_id, source_session,
125
- source_domain, project, privacy, memory_type, source_machine)
126
- VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
127
- .run(id, content, opts.baseStrength ?? 0.5, ts, ts, ingestedTs, opts.sourceAgent ?? "default", opts.sourceAgentId ?? null, sourceSession, opts.sourceDomain ?? null, opts.project ?? null, opts.privacy ?? null, opts.memoryType ?? "experience", opts.sourceMachine ?? null);
137
+ source_domain, workspace_path, project, privacy, memory_type, source_machine)
138
+ VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
139
+ .run(id, content, opts.baseStrength ?? 0.5, ts, ts, ingestedTs, opts.sourceAgent ?? "default", opts.sourceAgentId ?? null, sourceSession, opts.sourceDomain ?? null,
140
+ // #609: the workspace path rides the row (metadata for the
141
+ // confidentialPaths match + backfill); null when the delivery had none.
142
+ opts.workspacePath ?? null, opts.project ?? null,
143
+ // #332: 'standard' is the fail-closed default class — a NULL here would
144
+ // pre-date migration v27's normalization and force every read gate to
145
+ // keep a NULL arm forever. Confidential rows always carry an explicit
146
+ // server-derived 'confidential'.
147
+ opts.privacy ?? "standard", opts.memoryType ?? "experience", opts.sourceMachine ?? null);
128
148
  if (result.changes > 0) {
129
149
  // New row — store its vector.
130
150
  db.prepare("INSERT INTO memory_vectors (id, embedding) VALUES (?, ?)").run(id, embedToBlob(embedding));
@@ -641,9 +661,8 @@ function deleteLinks(db, memoryId) {
641
661
  * Batch insert memories. Returns count inserted.
642
662
  */
643
663
  function insertMemoriesBatch(db, memories) {
644
- // privacy default is null (0.16.x: the distiller no longer sets WORK — the
645
- // column is vestigial, never filtered, and goes NULL unless a caller sends
646
- // an explicit value).
664
+ // #332: privacy defaults to 'standard' (the class carrier) — same default
665
+ // as insertMemory; see the comment there.
647
666
  const insertMem = db.prepare(`INSERT INTO memories
648
667
  (id, content, base_strength, last_accessed, access_count,
649
668
  created_at, ingested_at, source_agent, source_agent_id, source_session,
@@ -655,7 +674,7 @@ function insertMemoriesBatch(db, memories) {
655
674
  for (const mem of memories) {
656
675
  const id = (0, node_crypto_1.randomUUID)();
657
676
  const ts = nowIso();
658
- insertMem.run(id, mem.content, mem.baseStrength ?? 0.5, ts, ts, ts, mem.sourceAgent ?? "default", mem.sourceAgentId ?? null, mem.sourceSession ?? null, mem.sourceDomain ?? null, mem.project ?? null, mem.privacy ?? null, mem.memoryType ?? "experience");
677
+ insertMem.run(id, mem.content, mem.baseStrength ?? 0.5, ts, ts, ts, mem.sourceAgent ?? "default", mem.sourceAgentId ?? null, mem.sourceSession ?? null, mem.sourceDomain ?? null, mem.project ?? null, mem.privacy ?? "standard", mem.memoryType ?? "experience");
659
678
  insertVec.run(id, embedToBlob(mem.embedding));
660
679
  count++;
661
680
  }
@@ -696,20 +715,33 @@ function getMemoriesSince(db, sinceIso) {
696
715
  }
697
716
  /**
698
717
  * Get lesson-type memories from the last N days.
699
- */
700
- function getLessons(db, days = 7, project) {
718
+ *
719
+ * #332: lessons inherit their pool's classification (confidential-pool
720
+ * reflection stamps them confidential at birth), and the SAME membership gate
721
+ * applies — `includeConfidential` defaults to FALSE (fail-closed: the
722
+ * agent-facing consumers — /learnings, the MCP lessons tools — serve standard
723
+ * lessons only unless the requester is a circle member). Server-internal
724
+ * consumers (nightly telemetry, the seed check, the recall-precision standing
725
+ * basis) pass true explicitly: they run inside the server, on the whole store.
726
+ */
727
+ function getLessons(db, days = 7, project, opts) {
701
728
  const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
729
+ // The hard-omit predicate — NULL-safe by construction (NULL privacy, the
730
+ // pre-v27 population, reads standard).
731
+ const classPredicate = opts?.includeConfidential === true
732
+ ? ""
733
+ : " AND (privacy IS NULL OR privacy != 'confidential')";
702
734
  if (project) {
703
735
  const rows = db
704
736
  .prepare(`SELECT * FROM memories
705
- WHERE memory_type = 'learnings' AND created_at > ? AND project = ?
737
+ WHERE memory_type = 'learnings' AND created_at > ? AND project = ?${classPredicate}
706
738
  ORDER BY created_at DESC`)
707
739
  .all(cutoff, project);
708
740
  return rows.map(rowToMemory);
709
741
  }
710
742
  const rows = db
711
743
  .prepare(`SELECT * FROM memories
712
- WHERE memory_type = 'learnings' AND created_at > ?
744
+ WHERE memory_type = 'learnings' AND created_at > ?${classPredicate}
713
745
  ORDER BY created_at DESC`)
714
746
  .all(cutoff);
715
747
  return rows.map(rowToMemory);
@@ -20,6 +20,16 @@ export interface TranscriptBatch {
20
20
  * `claude-code/<project>`. Lets per-harness readers stamp their own origin.
21
21
  */
22
22
  sourceAgent?: string;
23
+ /**
24
+ * The session's workspace path (#609) — the directory the capturing agent
25
+ * worked in (CC: the delta entries' `cwd`; Pi/OC: the session header `cwd`;
26
+ * opencode: `session.directory`). The nightly sends it on every segment
27
+ * POST (`workspace_path`) and walks the confidential marker from it.
28
+ * AUTHORITATIVE over `projectName`, which stays the lossy last-segment
29
+ * label. Null when the harness has no workspace (Hermes — per-profile
30
+ * conversations, no cwd in its store; never invented).
31
+ */
32
+ workspacePath?: string | null;
23
33
  /**
24
34
  * Per-session cursor key (`<prefix>:<sessionId>`) — the capture-cursors.json
25
35
  * key whose value gates and advances this session's incremental capture (#189).
@@ -144,6 +144,18 @@ function parseTranscriptFile(filePath, projectName, cursorKey, startCursor, gene
144
144
  if (timestamps[i])
145
145
  lastTimestamp = timestamps[i];
146
146
  }
147
+ // #609: the workspace path — the first non-empty `cwd` among the DELTA's
148
+ // entries (CC writes the session's cwd on every entry; the delta slice keeps
149
+ // the value authoritative for what THIS capture covers). projectName stays
150
+ // the lossy directory-name decode — it keeps serving only the label.
151
+ let workspacePath = null;
152
+ for (const entry of delta) {
153
+ const cwd = entry?.cwd;
154
+ if (typeof cwd === "string" && cwd) {
155
+ workspacePath = cwd;
156
+ break;
157
+ }
158
+ }
147
159
  return {
148
160
  sessionId: (0, node_path_1.basename)(filePath, ".jsonl"),
149
161
  projectName,
@@ -151,6 +163,7 @@ function parseTranscriptFile(filePath, projectName, cursorKey, startCursor, gene
151
163
  ? lastTimestamp.slice(0, 10)
152
164
  : new Date().toISOString().slice(0, 10),
153
165
  entries: delta,
166
+ workspacePath,
154
167
  cursorKey,
155
168
  startCursor: start,
156
169
  generation: gen,
@@ -44,7 +44,7 @@ const node_fs_1 = require("node:fs");
44
44
  const node_path_1 = require("node:path");
45
45
  const db_js_1 = require("./db.js");
46
46
  const state_js_1 = require("./state.js");
47
- const llm_js_1 = require("./llm.js");
47
+ const classification_js_1 = require("./classification.js");
48
48
  const type_labels_js_1 = require("./type-labels.js");
49
49
  const HICORTEX_HOME = (0, paths_js_1.hicortexHome)();
50
50
  /** Max chars of memory content fed to the classify prompt. */
@@ -194,17 +194,22 @@ async function runClassifyTypes(options = {}) {
194
194
  throw new Error("[hicortex] classify-types is server-mode only (it needs the local DB). " +
195
195
  `This machine is a client of ${config.serverUrl ?? "a remote server"} — run it on the server.`);
196
196
  }
197
- // Resolve the LLM (one model serves all phases — #231).
197
+ // Resolve the LLM (one model serves all phases — #231). #332: plus the
198
+ // confidential client — the type-classify prompt carries memory content, so
199
+ // each row picks the client matching its stamp; a confidential row without
200
+ // a client holds (infra-abort posture).
198
201
  let llm;
202
+ let confidentialLlm = null;
199
203
  if (options.llm) {
200
204
  llm = options.llm;
201
205
  }
202
206
  else {
203
- const resolved = (0, llm_js_1.resolveSavedLlmConfig)(config);
204
- if (!resolved.config) {
207
+ const resolved = (0, classification_js_1.resolveLlmPair)(config);
208
+ if (!resolved.pair) {
205
209
  throw new Error("[hicortex] classify-types: no LLM configured — run `npx @gamaze/hicortex init`.");
206
210
  }
207
- llm = new llm_js_1.LlmClient(resolved.config);
211
+ llm = resolved.pair.standard;
212
+ confidentialLlm = resolved.pair.confidential;
208
213
  }
209
214
  const dbPath = (0, db_js_1.resolveDbPath)(options.dbPath);
210
215
  const db = (0, db_js_1.initDb)(dbPath);
@@ -233,7 +238,7 @@ async function runClassifyTypes(options = {}) {
233
238
  const scopeSql = all
234
239
  ? "rowid > ? AND (memory_type IS NULL OR memory_type != 'learnings')"
235
240
  : "rowid > ? AND memory_type = 'experience'";
236
- const batchStmt = db.prepare(`SELECT rowid AS __rowid, id, content, memory_type FROM memories
241
+ const batchStmt = db.prepare(`SELECT rowid AS __rowid, id, content, memory_type, privacy FROM memories
237
242
  WHERE ${scopeSql} ORDER BY rowid ASC LIMIT ?`);
238
243
  // Set true when the classifier returns null (infra error): finish the
239
244
  // current batch's already-classified writes, commit, advance cursor to the
@@ -254,7 +259,17 @@ async function runClassifyTypes(options = {}) {
254
259
  // Classify (network) OUTSIDE the write transaction; collect results.
255
260
  const writes = [];
256
261
  for (const row of rows) {
257
- const result = await classifyMemoryType(row.content, llm);
262
+ // #332: per-row client selection — the classify prompt carries this
263
+ // row's content; a confidential row without a confidential client
264
+ // holds (infra-abort posture: untouched, retried).
265
+ const rowLlm = row.privacy === "confidential" ? confidentialLlm : llm;
266
+ if (!rowLlm) {
267
+ console.warn(`[hicortex] classify-types: confidential row ${row.id.slice(0, 8)} held — ` +
268
+ `no confidential model configured (llmConfidentialBaseUrl/ApiKey)`);
269
+ infraAbort = true;
270
+ break;
271
+ }
272
+ const result = await classifyMemoryType(row.content, rowLlm);
258
273
  if (result === null) {
259
274
  // Infra error OR two unparseable replies — stop scanning; leave this
260
275
  // row untouched for retry. (Two unparseable replies is rare; treating
package/dist/types.d.ts CHANGED
@@ -2,6 +2,21 @@
2
2
  * Type definitions for Hicortex OpenClaw plugin.
3
3
  * Ported from the Python hicortex codebase.
4
4
  */
5
+ /**
6
+ * The two-level memory classification (#332), carried by `memories.privacy`
7
+ * (resurrected from its vestigial 0.16.x role — the legacy PUBLIC/WORK/
8
+ * PERSONAL/SENSITIVE vocabulary is dead; migration v27 maps every legacy
9
+ * value and NULL to 'standard'). 'confidential' is ONLY ever set by the
10
+ * server: derived at intake from `source_agent` × the `confidentialAgents`
11
+ * config roster, a `confidentialPaths` workspace match (#609), or marker
12
+ * content validated against the server's `confidentialMarkerKey` (#614) — or
13
+ * stamped by the `backfill-privacy` owner command; the client only RELAYS
14
+ * raw inputs, it never declares the class. The class is a hard gate on every
15
+ * agent-facing read path (absent/unknown requester = non-member =
16
+ * confidential rows omitted, single fetch 404) and routes every LLM touch of
17
+ * confidential text to the separately configured confidential model.
18
+ */
19
+ export type MemoryPrivacy = "standard" | "confidential";
5
20
  /** A stored memory record. */
6
21
  export interface Memory {
7
22
  id: string;
@@ -29,7 +44,21 @@ export interface Memory {
29
44
  * above). NULL when the client declares none. Echoed back on /memory GET.
30
45
  */
31
46
  source_domain: string | null;
32
- privacy: ("PUBLIC" | "WORK" | "PERSONAL" | "SENSITIVE") | null;
47
+ /**
48
+ * The workspace path the capture ran in (#609, migration v28) — metadata
49
+ * for the confidentialPaths intake match and the path backfill. Optional
50
+ * because rowToMemory is a cast over SELECT * rows; NULL on every pre-v28
51
+ * row and on deliveries that carried no path (Hermes, pre-#609 clients).
52
+ */
53
+ workspace_path?: string | null;
54
+ /**
55
+ * The #332 two-level classification ('standard' | 'confidential'; see
56
+ * MemoryPrivacy). NULL only on rows written before migration v27 — the
57
+ * migration maps every legacy value to 'standard', and every insert site
58
+ * defaults to it, so a NULL-safe read gate (`privacy IS NULL OR
59
+ * privacy != 'confidential'`) treats them as standard.
60
+ */
61
+ privacy: MemoryPrivacy | null;
33
62
  memory_type: "experience" | "learnings" | "knowledge" | "decisions";
34
63
  updated_at: string | null;
35
64
  /**
@@ -162,6 +191,13 @@ export interface DeterministicMergeZoneReport {
162
191
  links_repointed: number;
163
192
  /** Clusters skipped — members disagree on project (#206 decision 2: the source_agent rail is removed). */
164
193
  skipped_project_mismatch: number;
194
+ /**
195
+ * #332: clusters skipped — members disagree on the standard|confidential
196
+ * classification (the pools never cross; the classification rail re-added
197
+ * where #206 removed the old privacy-value rail). Optional because
198
+ * pre-#332 reports predate it.
199
+ */
200
+ skipped_classification_mismatch?: number;
165
201
  /**
166
202
  * #393 guard-C: clusters skipped because a member pair holds a `conflicts`
167
203
  * link — a judge-flagged genuine conflict is never blended, both records
@@ -549,23 +585,23 @@ export interface HicortexConfig {
549
585
  */
550
586
  domains?: DomainDef[];
551
587
  /**
552
- * Success-cooldown (hours) for the CAPTURE watchdog (0.17). The capture
553
- * timer fires `nightly --watchdog` on a short interval (~20 min); the
554
- * watchdog captures only if MORE than this many hours have passed since the
555
- * last SUCCESSFUL capture (state `lastNightly`). A failed preflight retries
556
- * on the next tick (~20 min) — so a transient fire-instant network miss
557
- * costs minutes, not a day (#239). Default 6 (≈4 captures/day). Read at
558
- * runtime by the watchdog, not by `init`.
588
+ * Success-cooldown (hours) for capture-watchdog runs of the nightly (0.17,
589
+ * #239). The watchdog TIMER was retired in #596 — obsolete since the distill
590
+ * queue (#529): distillation runs on the server's scheduled drains, so
591
+ * capture-arrival latency serves nothing. The `--watchdog` flag remains a
592
+ * manual mode: when used, it captures only if MORE than this many hours have
593
+ * passed since the last SUCCESSFUL capture (state `lastNightly`); a failed
594
+ * preflight simply retries on the next manual run. Default 6. Read at
595
+ * runtime by the nightly, not by `init`.
559
596
  */
560
597
  captureCooldownHours?: number;
561
598
  /**
562
599
  * Hours (0–23, local time) for the CONSOLIDATION timer — the full nightly
563
600
  * (capture + distill + score + reflect + link), installed by `init` for
564
601
  * server/co-located mode ONLY (0.17). Default [10, 22]: the 22:00 evening
565
- * slot runs after the day's capture waves (same-day results); the 10:00
566
- * morning slot runs AFTER the morning's wake-up capture so it catches those
567
- * pushes. Omitted on client installs (no local DB → no timer). Validated by
568
- * parseHours.
602
+ * slot distills the day's sessions the same day; the 10:00 morning slot
603
+ * catches the night's and the previous evening's tail. Omitted on client
604
+ * installs (no local DB → no timer). Validated by parseHours.
569
605
  */
570
606
  consolidationHours?: number[];
571
607
  /**
@@ -812,6 +848,60 @@ export interface HicortexConfig {
812
848
  orgName?: string;
813
849
  /** Plan/tier label rendered as a small badge (e.g. "Cloud · Early bird"). */
814
850
  planLabel?: string;
851
+ /**
852
+ * #332 — the confidential-circle roster: agent ids (the same sanitized id
853
+ * namespace as `identityAgents` / `?agent=`) whose captures are stamped
854
+ * `confidential` at intake (matched by `source_agent` with the first
855
+ * `<harness>/` segment stripped, so a Hermes profile `nano` capturing as
856
+ * `hermes/nano` matches the roster entry `nano`) and whose read requests
857
+ * (the optional `agent` param on every agent-facing read path) see both
858
+ * pools. Absent/empty (the default) = no circle: every capture is
859
+ * standard, nothing is ever omitted, zero behavior change. Deploy-time
860
+ * CONTENT — the mechanism ships in code, the roster is the operator's.
861
+ * Boot-time (restart to apply).
862
+ */
863
+ confidentialAgents?: string[];
864
+ /**
865
+ * #614 — the confidential marker key: the owner-set secret the workspace
866
+ * marker `.hicortex-confidential` must carry (as its single-line content)
867
+ * for a client-marked folder to stamp `confidential` at intake. The client
868
+ * RELAYS the marker's content (`client_marker` on /distill); the server
869
+ * compares it timing-safe against this key — the pre-#614 empty marker (and
870
+ * the `client_confidential` boolean) were a client-writable classification
871
+ * channel any token holder could set, and the key closes it: forgery
872
+ * requires a secret token possession alone does not grant. Distributed
873
+ * like `authToken` — mirror the server's value into each client machine's
874
+ * config.json (the `hicortex confidential` command reads it there) or its
875
+ * env mirror HICORTEX_CONFIDENTIAL_MARKER_KEY (which overrides config on
876
+ * both ends). Absent/blank (the default) = markers INERT, fail-closed both
877
+ * directions: marker-carrying deliveries stamp standard and a boot note
878
+ * names the key when the circle is otherwise active. Boot-time (restart to
879
+ * apply). This is the N=1 form of the per-space key (#613); the marker
880
+ * content evolves to space-id + key without a wire change.
881
+ */
882
+ confidentialMarkerKey?: string;
883
+ /**
884
+ * #332 — the confidential model's endpoint. With `llmConfidentialApiKey`
885
+ * (both required; `llmConfidentialModel` optional, `llmConfidentialProvider`
886
+ * selects the request dialect like `llmProvider`), this configures the
887
+ * second LLM client that handles EVERY touch of confidential text:
888
+ * distillation, importance scoring, reflection, contradiction checks, domain
889
+ * classification, and reconsolidation verdicts. When absent while the circle
890
+ * is active, confidential work HOLDS (queued deliveries stay queued,
891
+ * sync-mode deliveries answer 503) — it never falls back to the main model.
892
+ * Env mirrors: HICORTEX_LLM_CONFIDENTIAL_BASE_URL/API_KEY/MODEL.
893
+ */
894
+ llmConfidentialBaseUrl?: string;
895
+ /** #332 — the confidential model's API key (see llmConfidentialBaseUrl). */
896
+ llmConfidentialApiKey?: string;
897
+ /** #332 — the confidential model's id (see llmConfidentialBaseUrl). */
898
+ llmConfidentialModel?: string;
899
+ /**
900
+ * #332 — explicit request dialect for the confidential model's
901
+ * OpenAI-compatible path (the `llmProvider` precedent; today only "azure").
902
+ * Absent/empty → URL detection.
903
+ */
904
+ llmConfidentialProvider?: string;
815
905
  }
816
906
  /** A config-owned life-sphere domain (see HicortexConfig.domains). */
817
907
  export interface DomainDef {
@@ -877,10 +967,22 @@ export interface InsertMemoryOptions {
877
967
  * only — stamped by the nightly (config `machineName` ?? os.hostname()),
878
968
  * accepted optionally from /distill + /ingest. Null on pre-v15 rows. */
879
969
  sourceMachine?: string | null;
970
+ /**
971
+ * The delivery's workspace path (#609) — the directory the capturing agent
972
+ * worked in. Metadata only: matched at intake against `confidentialPaths`
973
+ * and stored so `hicortex backfill-privacy` can re-plan by path; never
974
+ * distilled into prompt text. Null on pre-v28 rows, Hermes deliveries (no
975
+ * workspace), and clients that predate the wire field.
976
+ */
977
+ workspacePath?: string | null;
880
978
  project?: string | null;
881
- /** 0.16.x: vestigial — stored but never filtered. null (or absent) when the
882
- * caller doesn't declare one; an explicit value is honored as-is. */
883
- privacy?: string | null;
979
+ /**
980
+ * #332 classification stamp. Absent → 'standard' (the fail-closed default;
981
+ * callers that distill a confidential pool pass 'confidential' explicitly).
982
+ * Server-derived only — the intake handlers pass the source_agent × roster
983
+ * derivation, never a client-declared value.
984
+ */
985
+ privacy?: MemoryPrivacy | null;
884
986
  memoryType?: string;
885
987
  baseStrength?: number;
886
988
  createdAt?: string;