@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
@@ -95,7 +95,9 @@ const capture_health_js_1 = require("./capture-health.js");
95
95
  const recall_precision_js_1 = require("./recall-precision.js");
96
96
  const capture_pause_js_1 = require("./capture-pause.js");
97
97
  const project_canonicalize_js_1 = require("./project-canonicalize.js");
98
+ const classification_js_1 = require("./classification.js");
98
99
  const init_js_1 = require("./init.js");
100
+ const marker_key_api_js_1 = require("./marker-key-api.js");
99
101
  // ---------------------------------------------------------------------------
100
102
  // Server state
101
103
  // ---------------------------------------------------------------------------
@@ -104,6 +106,12 @@ let llm = null;
104
106
  // llmConfig is module-level so the /distill handler can read numCtx without
105
107
  // re-resolving on every request. null when no LLM is configured.
106
108
  let llmConfig = null;
109
+ // #332: the CONFIDENTIAL model client (llmConfidential* config /
110
+ // HICORTEX_LLM_CONFIDENTIAL_* env). null when unconfigured — confidential
111
+ // work then refuses/holds, never falls back to the main client. Built at the
112
+ // same funnel as the main client (boot), with the same tuning overlay.
113
+ let confidentialLlm = null;
114
+ let confidentialLlmConfig = null;
107
115
  // One-time-per-process deprecation warning for the `?privacy=` query param
108
116
  // (0.16.x: the column is vestigial, never filtered). Old clients/plugins still
109
117
  // send it; we accept it (backward compat) but warn ONCE so an operator relying
@@ -144,6 +152,21 @@ let recallIndexOptions = {};
144
152
  let projectAliases = null;
145
153
  // Product-owned memory instructions (#192): on unless config says false.
146
154
  let memoryInstructionsEnabled = true;
155
+ // #332: the confidential-circle roster (config `confidentialAgents`),
156
+ // resolved once at boot like identityAgents (restart to apply). Empty = no
157
+ // circle: every delivery stamps standard, nothing is ever omitted from read
158
+ // paths — the zero-change default.
159
+ let confidentialRoster = [];
160
+ // #609: the workspace-path patterns (config `confidentialPaths`), resolved at
161
+ // the same boot seam as the roster (restart to apply). Empty = the path
162
+ // birthplace signal never fires; the matcher itself lives in classification.ts.
163
+ let confidentialPathPatterns = [];
164
+ // #614: the marker key (config `confidentialMarkerKey` / env
165
+ // HICORTEX_CONFIDENTIAL_MARKER_KEY), resolved at the same boot seam. Null =
166
+ // client workspace markers are INERT (ignored with a boot note when the
167
+ // circle is otherwise active) — the attack surface ships disabled by
168
+ // default. The compare itself lives in classification.ts (timing-safe).
169
+ let confidentialMarkerKey = null;
147
170
  /**
148
171
  * #567: fold ONE project string through the boot-resolved alias map — the
149
172
  * shared normalization for every project-string entry point in this file
@@ -155,6 +178,16 @@ let memoryInstructionsEnabled = true;
155
178
  * affinity, lesson selection, the dedup project rail) sees the same value.
156
179
  */
157
180
  const canonProject = (v) => (0, project_canonicalize_js_1.canonicalizeProject)(typeof v === "string" ? v : null, projectAliases) ?? undefined;
181
+ /**
182
+ * #332: resolve the classification visibility for ONE request's `agent` param
183
+ * against the boot-resolved roster. Absent/blank/unknown agent → FALSE
184
+ * (fail-closed non-member — confidential rows are hard-omitted); a rostered
185
+ * agent id → TRUE (the additive circle: members see both pools). The `agent`
186
+ * self-asserts identity, exactly like the client-pushed project field — same
187
+ * trust level, documented in the spec (per-agent tokens are the known future
188
+ * fix). Shared by every agent-facing read route below.
189
+ */
190
+ const requestSeesConfidential = (rawAgent) => (0, classification_js_1.isCircleMember)(typeof rawAgent === "string" && rawAgent ? rawAgent : null, confidentialRoster);
158
191
  // Cache detectChunkSize results keyed by "<provider>/<model>@<baseUrl>" so we
159
192
  // probe each endpoint once per server boot rather than once per /distill request.
160
193
  const chunkSizeCache = new Map();
@@ -299,6 +332,11 @@ function createMcpServer() {
299
332
  project: canonProject(project),
300
333
  // Normalize legacy raw enum to the canonical term the DB stores.
301
334
  memoryType: memory_type ? (0, type_labels_js_1.normalizeMemoryType)(memory_type) : "experience",
335
+ // #332: the MCP ingest path derives the stamp from its fixed
336
+ // source_agent like every write path (a roster entry
337
+ // "claude-code/manual" — or its bare "manual" — would stamp
338
+ // confidential; mechanical rule, no special case).
339
+ privacy: (0, classification_js_1.deriveIntakePrivacy)("claude-code/manual", confidentialRoster),
302
340
  });
303
341
  if (explicitMark)
304
342
  (0, reconsolidation_js_1.applyExplicitMark)(db, id, explicitMark);
@@ -466,12 +504,21 @@ function createMcpServer() {
466
504
  }, async ({ operation, id, target_id, limit: resultLimit, domain: filterDomain, relationship: filterRelationship }) => {
467
505
  if (!db)
468
506
  return { content: [{ type: "text", text: "Hicortex not initialized" }], isError: true };
507
+ // #332: MCP tools carry NO requester identity, so they are non-members
508
+ // by construction — confidential rows (incl. hub/neighbor content) are
509
+ // hard-omitted, and a confidential center/endpoint id reads as not
510
+ // found. Accepted in the spec: circle agents read through their
511
+ // plugin's agent-threaded REST calls, not through MCP tools.
512
+ const idVisible = (fullId) => {
513
+ const row = db.prepare("SELECT privacy FROM memories WHERE id = ?").get(fullId);
514
+ return row?.privacy !== "confidential";
515
+ };
469
516
  try {
470
517
  if (operation === "neighbors") {
471
518
  if (!id)
472
519
  return { content: [{ type: "text", text: "id is required for neighbors operation" }], isError: true };
473
520
  const resolvedId = resolveMemoryId(db, id);
474
- if (!resolvedId)
521
+ if (!resolvedId || !idVisible(resolvedId))
475
522
  return { content: [{ type: "text", text: `Memory not found: ${id}` }], isError: true };
476
523
  const neighbors = (0, graph_js_1.getNeighbors)(db, resolvedId, resultLimit ?? 10, filterRelationship);
477
524
  if (neighbors.length === 0)
@@ -494,7 +541,7 @@ function createMcpServer() {
494
541
  return { content: [{ type: "text", text: "id and target_id are required for path operation" }], isError: true };
495
542
  const fromId = resolveMemoryId(db, id);
496
543
  const toId = resolveMemoryId(db, target_id);
497
- if (!fromId || !toId)
544
+ if (!fromId || !toId || !idVisible(fromId) || !idVisible(toId))
498
545
  return { content: [{ type: "text", text: "One or both memory IDs not found" }], isError: true };
499
546
  const path = (0, graph_js_1.shortestPath)(db, fromId, toId);
500
547
  if (!path)
@@ -800,6 +847,17 @@ async function startServer(options = {}) {
800
847
  console.warn("╚══════════════════════════════════════════════════════════════╝");
801
848
  console.warn("");
802
849
  }
850
+ // #332: the confidential model — built at the SAME funnel (boot) with the
851
+ // same tuning overlay (buildConfidentialLlm). Absent is legal (standard-only
852
+ // installs never need it); the loud warning below fires only when the
853
+ // circle is actually active.
854
+ const confidentialBuilt = (0, classification_js_1.buildConfidentialLlm)(savedConfig);
855
+ confidentialLlm = confidentialBuilt?.llm ?? null;
856
+ confidentialLlmConfig = confidentialBuilt?.config ?? null;
857
+ if (confidentialLlmConfig) {
858
+ console.log(`[hicortex] Confidential LLM: ${confidentialLlmConfig.provider}/${confidentialLlmConfig.model}` +
859
+ ` — every touch of confidential text routes here`);
860
+ }
803
861
  // One-time migration of legacy state files (no-op if state.json exists)
804
862
  (0, state_js_1.migrateLegacyState)(stateDir);
805
863
  // License: read from options, config file, or env var, init feature cache
@@ -897,6 +955,72 @@ async function startServer(options = {}) {
897
955
  console.warn(`[hicortex] Ignoring invalid identityAgents entries: ${resolvedAgents.dropped.join(", ")} ` +
898
956
  `(keys must match ^[a-z0-9][a-z0-9_-]*$; modes must be override|global|off)`);
899
957
  }
958
+ // #332 confidential circle: resolve the roster (boot-time, like
959
+ // identityAgents — restart to apply). Every write path below derives the
960
+ // classification stamp from source_agent × this roster; the read paths
961
+ // membership-check the `agent` param against it. An empty roster is the
962
+ // zero-change default (deriveIntakePrivacy answers standard for everything).
963
+ const resolvedConfidential = (0, classification_js_1.resolveConfidentialAgents)(savedConfig);
964
+ confidentialRoster = resolvedConfidential.roster;
965
+ if (resolvedConfidential.dropped.length > 0) {
966
+ console.warn(`[hicortex] Ignoring invalid confidentialAgents entries: ${resolvedConfidential.dropped.join(", ")} ` +
967
+ `(ids must sanitize like ?agent= — a dropped id means that agent is NOT in the circle)`);
968
+ }
969
+ // #609: workspace-path patterns resolve at the SAME boot seam (restart to
970
+ // apply, like the roster). Dropped entries are named once — a dropped
971
+ // pattern matches nothing, so a typo must surface in the log, never as a
972
+ // folder silently staying standard.
973
+ const resolvedConfidentialPaths = (0, classification_js_1.resolveConfidentialPaths)(savedConfig);
974
+ confidentialPathPatterns = resolvedConfidentialPaths.patterns;
975
+ if (resolvedConfidentialPaths.dropped.length > 0) {
976
+ console.warn(`[hicortex] Ignoring invalid confidentialPaths entries: ${resolvedConfidentialPaths.dropped.join(", ")} ` +
977
+ `(entries must be absolute paths or ~/…, with * only as a full segment and ** only as a trailing /** — ` +
978
+ `a dropped pattern matches nothing)`);
979
+ }
980
+ // #614: resolve the marker key at the SAME boot seam (restart to apply).
981
+ // Null = client workspace markers are INERT — see the note below.
982
+ confidentialMarkerKey = (0, classification_js_1.resolveConfidentialMarkerKey)(savedConfig);
983
+ if (confidentialRoster.length > 0 || confidentialPathPatterns.length > 0) {
984
+ console.log(`[hicortex] Confidential circle: ${confidentialRoster.length} agent(s) rostered` +
985
+ `${confidentialPathPatterns.length > 0 ? `, ${confidentialPathPatterns.length} path pattern(s)` : ""}` +
986
+ // #614: name the marker arm's state on the same status line — a keyed
987
+ // marker is the third birthplace signal, and its being armed (or not)
988
+ // is exactly what an operator scanning the boot log needs to see.
989
+ (confidentialMarkerKey !== null ? ", workspace markers keyed" : ""));
990
+ }
991
+ // The two "is the circle active" counts, computed ONCE for the marker-key
992
+ // boot note below and the unconfigured-circle warning after it (the same
993
+ // active predicate, warnIfCircleUnconfigured's).
994
+ const confidentialRowsCount = db
995
+ .prepare("SELECT COUNT(*) AS c FROM memories WHERE privacy = 'confidential'")
996
+ .get().c;
997
+ const queueConfidentialCount = db
998
+ .prepare("SELECT COUNT(*) AS c FROM distill_queue WHERE privacy = 'confidential'")
999
+ .get().c;
1000
+ // #614: absent key + otherwise-active circle → the one-line inert note, so
1001
+ // a marked folder's standard stamps are explained in the log, never silent.
1002
+ // Zero-config installs stay silent (the classification zero-change rule).
1003
+ const markerKeyNote = (0, classification_js_1.confidentialMarkerKeyNote)({
1004
+ markerKey: confidentialMarkerKey,
1005
+ roster: confidentialRoster,
1006
+ patterns: confidentialPathPatterns,
1007
+ confidentialRows: confidentialRowsCount,
1008
+ queueConfidential: queueConfidentialCount,
1009
+ });
1010
+ if (markerKeyNote)
1011
+ console.warn(markerKeyNote);
1012
+ // #332: the ONE loud boot warning when the circle is active without the
1013
+ // confidential model. "Active" = roster set OR path patterns set (#609) OR
1014
+ // confidential rows already stored OR confidential items already queued —
1015
+ // on a zero-config install none of those hold and the warning stays silent
1016
+ // (AC-2).
1017
+ (0, classification_js_1.warnIfCircleUnconfigured)({
1018
+ roster: confidentialRoster,
1019
+ patterns: confidentialPathPatterns,
1020
+ confidentialLlm,
1021
+ confidentialRows: confidentialRowsCount,
1022
+ queueConfidential: queueConfidentialCount,
1023
+ });
900
1024
  // #264 dir migration: rename <hicortex-home>/context/ → identity/ on boot
901
1025
  // when only the legacy dir exists. The fallback read in identity-store.ts
902
1026
  // (readSectionsWithFallback) is the safety net for a partial/no migration.
@@ -996,13 +1120,17 @@ async function startServer(options = {}) {
996
1120
  // memory index for client CLAUDE.md injection. Both routes share ONE handler
997
1121
  // so the alias can never drift from the canonical shape. The legacy name is
998
1122
  // kept indefinitely (existing SessionStart hooks literally fetch /lessons).
999
- const learningsIndexHandler = (_req, res) => {
1123
+ // #332: the optional `agent` query param is the circle-membership gate —
1124
+ // confidential lessons (born in the confidential reflection pool) serve to
1125
+ // members only; non-members get today's shape minus those rows.
1126
+ const learningsIndexHandler = (req, res) => {
1000
1127
  if (!db) {
1001
1128
  res.status(503).json({ error: "Server not initialized" });
1002
1129
  return;
1003
1130
  }
1004
1131
  try {
1005
- const lessons = storage.getLessons(db, 30);
1132
+ const member = requestSeesConfidential(req.query.agent);
1133
+ const lessons = storage.getLessons(db, 30, null, { includeConfidential: member });
1006
1134
  const totalCount = storage.countMemories(db);
1007
1135
  // Project index
1008
1136
  const projects = db
@@ -1039,7 +1167,11 @@ async function startServer(options = {}) {
1039
1167
  res.status(503).json({ error: "Server not initialized" });
1040
1168
  return;
1041
1169
  }
1042
- const { content, source_agent, source_agent_id, source_domain, source_machine, project, memory_type, privacy, source_session, session_date, corrects, supersedes } = req.body ?? {};
1170
+ // NOTE (#332): a client-declared `privacy` field is IGNORED here too —
1171
+ // /ingest is a write path, and the stamp is server-derived from
1172
+ // source_agent × the roster (a lying legacy client cannot smuggle itself
1173
+ // into — or out of — the confidential class).
1174
+ const { content, source_agent, source_agent_id, source_domain, source_machine, project, memory_type, source_session, session_date, corrects, supersedes } = req.body ?? {};
1043
1175
  if (!content || typeof content !== "string") {
1044
1176
  res.status(400).json({ error: "Missing or invalid 'content' field" });
1045
1177
  return;
@@ -1096,9 +1228,9 @@ async function startServer(options = {}) {
1096
1228
  // un-upgraded client folds here too.
1097
1229
  project: canonProject(project),
1098
1230
  memoryType: normalizedType ?? "experience",
1099
- // 0.16.x: privacy defaults to null (vestigial column). A legacy client
1100
- // that sends an explicit value is honored; absent → null.
1101
- privacy: typeof privacy === "string" ? privacy : null,
1231
+ // #332: server-derived stamp — same source_agent × roster rule as
1232
+ // /distill, so the legacy write path is not a stamping bypass.
1233
+ privacy: (0, classification_js_1.deriveIntakePrivacy)(typeof source_agent === "string" ? source_agent : null, confidentialRoster),
1102
1234
  createdAt: session_date ? new Date(session_date).toISOString() : undefined,
1103
1235
  });
1104
1236
  if (explicitMark)
@@ -1144,9 +1276,12 @@ async function startServer(options = {}) {
1144
1276
  // the #409 floor is unchanged in effect; the fence applies only when the
1145
1277
  // request carries a project (applySearchRelevanceGate is identity
1146
1278
  // otherwise).
1279
+ // #332: the optional `agent` param is the circle-membership gate —
1280
+ // absent/unknown = hard omit of confidential rows.
1281
+ const member = requestSeesConfidential(req.query.agent);
1147
1282
  const minSimilarity = resolveSearchSimilarityFloor(req.query.minSimilarity);
1148
1283
  try {
1149
- let results = await retrieval.retrieve(db, embedder_js_1.embed, query, { limit, project });
1284
+ let results = await retrieval.retrieve(db, embedder_js_1.embed, query, { limit, project, includeConfidential: member });
1150
1285
  results = applySearchRelevanceGate(results, { minSimilarity, project, crossProjectMinSimilarity: recallCrossProjectBar });
1151
1286
  res.json({ results });
1152
1287
  }
@@ -1191,10 +1326,15 @@ async function startServer(options = {}) {
1191
1326
  // that searches unblended and touches no centroid state. Extracted so the
1192
1327
  // exact behavior is unit-testable without HTTP (blendQueryVector
1193
1328
  // precedent); this adapter stays thin.
1329
+ // #332: the optional body `agent` is the circle-membership gate — the
1330
+ // factory (built per request) carries it into retrieve() so the omit
1331
+ // happens at candidate-build time, not post-hoc. A client-declared
1332
+ // `privacy` body field remains ignored (0.16.x backcompat posture).
1194
1333
  const factory = (0, recall_index_js_1.createRecallRetrieveFn)({
1195
1334
  db,
1196
1335
  registry: recallRegistry,
1197
1336
  embedFn: embedder_js_1.embed,
1337
+ includeConfidential: requestSeesConfidential(req.body?.agent),
1198
1338
  });
1199
1339
  const r = await (0, recall_index_js_1.handleRecallIndex)({
1200
1340
  db,
@@ -1221,8 +1361,11 @@ async function startServer(options = {}) {
1221
1361
  return;
1222
1362
  }
1223
1363
  warnDeprecatedPrivacyParamIfPresent(req.query, "memory");
1364
+ // #332: the optional `agent` param is the circle-membership gate — a
1365
+ // confidential id fetched by a non-member answers 404 (before any
1366
+ // strengthening side effect, inside handleMemoryGet).
1224
1367
  try {
1225
- const r = (0, recall_index_js_1.handleMemoryGet)(db, { id: req.query.id }, { recordFetch: recall_precision_js_1.recordRecallFetch });
1368
+ const r = (0, recall_index_js_1.handleMemoryGet)(db, { id: req.query.id }, { recordFetch: recall_precision_js_1.recordRecallFetch }, { includeConfidential: requestSeesConfidential(req.query.agent) });
1226
1369
  res.status(r.status).json(r.body);
1227
1370
  }
1228
1371
  catch (err) {
@@ -1241,10 +1384,12 @@ async function startServer(options = {}) {
1241
1384
  // No hardcoded default: absent limit → the release-managed calibration
1242
1385
  // default (#408 — was the recentLimit config key).
1243
1386
  // 0.16.x: `privacy` query param accepted but ignored (vestigial column).
1387
+ // #332: the optional `agent` param is the circle-membership gate.
1244
1388
  const limit = req.query.limit ? Number(req.query.limit) : undefined;
1245
1389
  warnDeprecatedPrivacyParamIfPresent(req.query, "recent");
1390
+ const member = requestSeesConfidential(req.query.agent);
1246
1391
  try {
1247
- const results = retrieval.searchRecent(db, { project, limit });
1392
+ const results = retrieval.searchRecent(db, { project, limit, includeConfidential: member });
1248
1393
  res.json({ results });
1249
1394
  }
1250
1395
  catch (err) {
@@ -1366,6 +1511,46 @@ async function startServer(options = {}) {
1366
1511
  (0, health_js_1.logAndSendInternalError)(res, "identity/mode", err);
1367
1512
  }
1368
1513
  });
1514
+ // GET/PUT /confidential/marker-key — ONE-COMMAND marker-key provisioning
1515
+ // (#616). The pair behind `hicortex confidential`'s fetch-or-generate flow:
1516
+ // GET answers the EFFECTIVE key (the boot-resolved module var — the value
1517
+ // markers must carry) so a second machine reuses it instead of minting a
1518
+ // second key; PUT registers a generated/chosen key (first machine, or
1519
+ // rotation). Scoped to THIS key only — not a general config API (AC-4).
1520
+ //
1521
+ // Single-writer discipline, the PUT /identity/mode pattern: the key is
1522
+ // normally resolved once at boot, and THIS route is the one live writer.
1523
+ // On a successful PUT the adapter (1) persists through persistConfigUpdates
1524
+ // (survives restarts, unrelated keys untouched) and (2) assigns the
1525
+ // module-level confidentialMarkerKey to the SAME value — a rotation bites
1526
+ // at the NEXT /distill intake with no restart, where an old-marker relay
1527
+ // flips to standard + the #615 refusal warn. A PUT under the
1528
+ // HICORTEX_CONFIDENTIAL_MARKER_KEY env override 409s (the env would shadow
1529
+ // the write — no no-op success; the rule lives in the pure handler).
1530
+ // Bearer-only: the standard auth middleware above, no exemption — the key
1531
+ // is the confidential circle's secret, fetchable by token = owner (the
1532
+ // #616 accepted trade-off). Pure handlers in marker-key-api.ts.
1533
+ app.get("/confidential/marker-key", (_req, res) => {
1534
+ const r = (0, marker_key_api_js_1.handleMarkerKeyGet)(confidentialMarkerKey);
1535
+ res.status(r.status).json(r.body);
1536
+ });
1537
+ app.put("/confidential/marker-key", (req, res) => {
1538
+ try {
1539
+ const r = (0, marker_key_api_js_1.handleMarkerKeyPut)(req.body ?? null, process.env.HICORTEX_CONFIDENTIAL_MARKER_KEY);
1540
+ if (r.status === 200 && r.key !== undefined) {
1541
+ (0, init_js_1.persistConfigUpdates)((0, node_path_1.join)(stateDir, "config.json"), { confidentialMarkerKey: r.key });
1542
+ confidentialMarkerKey = r.key;
1543
+ // One line, never the key value — the operator sees THAT the key
1544
+ // rotated, not WHAT it is (same discipline as the CLI output).
1545
+ console.log("[hicortex] confidentialMarkerKey set — the next delivery with a matching marker stamps confidential; " +
1546
+ "markers carrying a previous key now stamp standard");
1547
+ }
1548
+ res.status(r.status).json(r.body);
1549
+ }
1550
+ catch (err) {
1551
+ (0, health_js_1.logAndSendInternalError)(res, "confidential/marker-key", err);
1552
+ }
1553
+ });
1369
1554
  // REST /distill — canonical capture endpoint (0.9.0+).
1370
1555
  // Every machine (including the server itself) POSTs denoised session text here.
1371
1556
  // The server distills, embeds, stores. Body limit: see `distillBodyLimitMb`
@@ -1383,13 +1568,57 @@ async function startServer(options = {}) {
1383
1568
  // attribution fields exist at EVERY exit incl. the 503 — capture-health
1384
1569
  // accounting records held posts there too. Nothing else reads them before
1385
1570
  // the guard, so semantics are unchanged.
1386
- const { text, messages, source_agent, source_agent_id, source_domain, source_machine, project, session_id, segment_id, session_date, privacy } = req.body ?? {};
1571
+ // NOTE (#332): a client-declared `privacy` body field is IGNORED — the
1572
+ // classification stamp is server-derived below from source_agent × the
1573
+ // roster. The field is deliberately not even destructured.
1574
+ // NOTE (#614): the pre-#614 `client_confidential` BOOLEAN is ignored the
1575
+ // same way (accepted-and-ignored, deliberately not destructured) — it was
1576
+ // the client-writable classification channel the marker key closes; only
1577
+ // the relayed marker CONTENT (`client_marker`), validated server-side
1578
+ // below, can stamp a delivery confidential from the client end.
1579
+ // #609/#614: `workspace_path` (the session's workspace) and `client_marker`
1580
+ // (the marker file's relayed content) join the destructure — the two
1581
+ // client-carried birthplace signals, composed below. An old client sends
1582
+ // neither; a new client against an old server is a no-op (unknown fields
1583
+ // are never read).
1584
+ const { text, messages, source_agent, source_agent_id, source_domain, source_machine, workspace_path, client_marker, project, session_id, segment_id, session_date } = req.body ?? {};
1585
+ // typeof guards at the one boundary — anything malformed reads as absent.
1586
+ const workspacePath = typeof workspace_path === "string" && workspace_path ? workspace_path : null;
1587
+ // #614: unlike workspace_path, an EMPTY string stays PRESENT — an empty
1588
+ // pre-#614 marker file relays as "" and is refused (warned) below, never
1589
+ // silently treated as "no marker".
1590
+ const clientMarker = typeof client_marker === "string" ? client_marker : null;
1387
1591
  // #567: fold the wire project ONCE, right after the destructure — the
1388
1592
  // queue enqueue, the sync distill prompt, and the insert opts below all
1389
1593
  // carry the canonical value, so an un-upgraded client's raw label never
1390
1594
  // lands as a stored variant (old npx clients, frozen plugin copies, and
1391
1595
  // un-refreshed extensions all canonicalize for free at the server).
1392
1596
  const canonProjectVal = canonProject(project);
1597
+ // #332: the classification stamp, derived ONCE per delivery from the
1598
+ // source agent × the boot-resolved roster (deterministic, by birthplace —
1599
+ // never a content judgment and never client-declared). Every downstream
1600
+ // landing (queue row, sync insert) carries THIS value.
1601
+ // #609: the derivation composes the birthplace signals — roster agent OR
1602
+ // confidentialPaths pattern OR the marker arm.
1603
+ // #614: the marker arm is now KEY-VALIDATED server-side — the boot-resolved
1604
+ // confidentialMarkerKey compared timing-safe against the relayed content
1605
+ // (an absent key makes every marker inert; a refused marker never reduces
1606
+ // a server rule).
1607
+ const derivedPrivacy = (0, classification_js_1.deriveIntakePrivacy)(typeof source_agent === "string" ? source_agent : null, confidentialRoster, {
1608
+ workspacePath,
1609
+ markerContent: clientMarker,
1610
+ markerKey: confidentialMarkerKey,
1611
+ paths: confidentialPathPatterns,
1612
+ });
1613
+ // #614: the rate-limited refusal warn at the intake seam. Marker content
1614
+ // arrived and did NOT validate — no key configured (the arm is inert), or
1615
+ // a mismatch (stale pre-key marker / rotated key / forgery). One guard
1616
+ // covers both cases; warnRefusedMarker itself is once-per-process and
1617
+ // never echoes the content or the key. A matching marker never warns; an
1618
+ // absent marker (null) never warns.
1619
+ if (clientMarker !== null && clientMarker !== confidentialMarkerKey) {
1620
+ (0, classification_js_1.warnRefusedMarker)({ markerKey: confidentialMarkerKey, workspacePath });
1621
+ }
1393
1622
  // #422 capture health: normalize the wire fields ONCE so every exit below
1394
1623
  // records with a one-liner (recordDistillActivity re-sanitizes machine/
1395
1624
  // agent — the builder only forwards + picks the byte count). bytes = the
@@ -1435,6 +1664,21 @@ async function startServer(options = {}) {
1435
1664
  // the delivery without any LLM call and the nightly drain defers until
1436
1665
  // an LLM is configured.
1437
1666
  }
1667
+ // #332 sync-mode refusal: a CONFIDENTIAL delivery with no confidential
1668
+ // model answers 503 — the client holds its cursor and retries (the
1669
+ // strict-mode watermark precedent). It is NEVER distilled on the main
1670
+ // model. Queue mode stores it and the drain holds it instead (per-item
1671
+ // skip-and-continue); a fresh install's first delivery can never be
1672
+ // confidential (no roster configured ⇒ nothing derives confidential), so
1673
+ // the fresh-brain immediate-distill carve-out is untouched.
1674
+ if (derivedPrivacy === "confidential" && !queueMode && (!confidentialLlm || !confidentialLlmConfig)) {
1675
+ (0, capture_health_js_1.recordDistillActivity)(db, capEntry(0, "held"));
1676
+ res.status(503).json({
1677
+ error: "Confidential delivery held — no confidential model configured " +
1678
+ "(llmConfidentialBaseUrl/ApiKey). It will be retried; it is never distilled on the main model.",
1679
+ });
1680
+ return;
1681
+ }
1438
1682
  // Resolve the conversation text from either the pre-denoised string or raw messages array.
1439
1683
  // `fromTextBranch` is captured once so the redaction gate below uses the SAME
1440
1684
  // discriminator as the resolution (avoids re-redacting the messages-derived
@@ -1447,8 +1691,12 @@ async function startServer(options = {}) {
1447
1691
  }
1448
1692
  else if (Array.isArray(messages) && messages.length > 0) {
1449
1693
  // The messages branch already redacts via extractConversationText
1450
- // (distiller.ts), which calls redact() as its final step.
1451
- conversationText = (0, distiller_js_1.extractConversationText)(messages);
1694
+ // (distiller.ts), which calls redact() as its final step. #332: it
1695
+ // receives the SAME redaction config (the extended preset for
1696
+ // confidential deliveries) so both branches redact identically.
1697
+ conversationText = (0, distiller_js_1.extractConversationText)(messages, {
1698
+ extended: derivedPrivacy === "confidential",
1699
+ });
1452
1700
  }
1453
1701
  else {
1454
1702
  res.status(400).json({ error: "Provide either 'text' (string) or 'messages' (array)" });
@@ -1464,8 +1712,14 @@ async function startServer(options = {}) {
1464
1712
  // negative lookahead, and format-specific patterns don't match it). The
1465
1713
  // messages branch is already covered above. Disable-resistance
1466
1714
  // (hostedMode) is Phase 0b.
1715
+ // #332 redaction pilot: CONFIDENTIAL deliveries use the extended preset
1716
+ // (DEFAULT_PATTERNS + emails + phone numbers) — the material an
1717
+ // inner-circle agent captures is exactly the contact-identifier-rich
1718
+ // kind (#558). Standard deliveries keep today's set byte-identically.
1467
1719
  if (fromTextBranch) {
1468
- const { text: redacted, count } = (0, redact_js_1.redact)(conversationText);
1720
+ const { text: redacted, count } = (0, redact_js_1.redact)(conversationText, {
1721
+ extended: derivedPrivacy === "confidential",
1722
+ });
1469
1723
  if (count > 0) {
1470
1724
  console.log(`[hicortex] Redacted ${count} secret(s) from /distill text`);
1471
1725
  }
@@ -1527,11 +1781,16 @@ async function startServer(options = {}) {
1527
1781
  source_agent_id,
1528
1782
  source_domain,
1529
1783
  source_machine,
1784
+ // #609: the workspace path rides the queue row so the drain's inserts
1785
+ // keep it and backfill-privacy can path-match queued rows.
1786
+ workspace_path: workspacePath,
1530
1787
  project: canonProjectVal,
1531
1788
  session_id,
1532
1789
  segment_id,
1533
1790
  session_date,
1534
- privacy,
1791
+ // #332: the queue row carries the DERIVED stamp — the drain trusts it
1792
+ // (and routes the item to the matching model).
1793
+ privacy: derivedPrivacy,
1535
1794
  });
1536
1795
  (0, capture_health_js_1.recordDistillActivity)(db, capEntry(conversationText.length, duplicate ? "skipped" : "ok"));
1537
1796
  if (duplicate) {
@@ -1549,20 +1808,27 @@ async function startServer(options = {}) {
1549
1808
  });
1550
1809
  return;
1551
1810
  }
1552
- // #529: from here on queueMode is false, so the no-LLM guard above has
1811
+ // #529: from here on queueMode is false, so the no-LLM guards above have
1553
1812
  // already answered 503 in every path that reaches this line. Restated so
1554
1813
  // the sync flow keeps its non-null llm/llmConfig typing unchanged.
1555
1814
  if (!llm || !llmConfig) {
1556
1815
  res.status(503).json({ error: "No LLM configured — run npx @gamaze/hicortex init. Session will be retried." });
1557
1816
  return;
1558
1817
  }
1818
+ // #332 per-pool client selection (the sync path's mirror of the drain's
1819
+ // selection): a confidential delivery distills on the CONFIDENTIAL client
1820
+ // — the refusal above guarantees it exists by here — and the probe gate +
1821
+ // chunk-size cache below use ITS endpoint. Standard deliveries are
1822
+ // byte-identical to today.
1823
+ const syncLlm = derivedPrivacy === "confidential" ? confidentialLlm : llm;
1824
+ const syncLlmConfig = derivedPrivacy === "confidential" ? confidentialLlmConfig : llmConfig;
1559
1825
  // #337: readiness gate — cached minimal generation probe BEFORE
1560
1826
  // detectChunkSize + distillSession, so a dead endpoint never even pays the
1561
1827
  // chunk-size probe. Placed AFTER the dedup short-circuits (a duplicate
1562
1828
  // costs nothing and must not trip the gate). On failure: 503 with the
1563
1829
  // diagnosis — the capture client treats non-201/200 as transient and holds
1564
1830
  // its cursor (capture.ts), so the segment is retried next run, never lost.
1565
- if (!(await resolveDistillProbeGate(llm, llmConfig))) {
1831
+ if (!(await resolveDistillProbeGate(syncLlm, syncLlmConfig))) {
1566
1832
  (0, capture_health_js_1.recordDistillActivity)(db, capEntry(conversationText.length, "held"));
1567
1833
  res.status(503).json({ error: "LLM endpoint not generating — session will be retried" });
1568
1834
  return;
@@ -1570,9 +1836,9 @@ async function startServer(options = {}) {
1570
1836
  // Cache detectChunkSize per endpoint so we probe at most once per server boot.
1571
1837
  // numCtx is passed so chunk size derives from the request's ACTUAL context
1572
1838
  // window (#231, #228) — the chunker and the request agree by construction.
1573
- const cacheKey = `${llmConfig.provider}/${llmConfig.model}@${llmConfig.baseUrl}`;
1839
+ const cacheKey = `${syncLlmConfig.provider}/${syncLlmConfig.model}@${syncLlmConfig.baseUrl}`;
1574
1840
  if (!chunkSizeCache.has(cacheKey)) {
1575
- chunkSizeCache.set(cacheKey, await (0, distiller_js_1.detectChunkSize)(llmConfig.provider, llmConfig.model, llmConfig.baseUrl, llmConfig.numCtx));
1841
+ chunkSizeCache.set(cacheKey, await (0, distiller_js_1.detectChunkSize)(syncLlmConfig.provider, syncLlmConfig.model, syncLlmConfig.baseUrl, syncLlmConfig.numCtx));
1576
1842
  }
1577
1843
  const chunkSize = chunkSizeCache.get(cacheKey);
1578
1844
  const date = typeof session_date === "string" && session_date ? session_date : new Date().toISOString().slice(0, 10);
@@ -1597,7 +1863,10 @@ async function startServer(options = {}) {
1597
1863
  // land in the caller's file-persisted nightly log (#156 audit trail); the
1598
1864
  // server-side per-entry console.log in distillChunk stays as well.
1599
1865
  const dropped = [];
1600
- const entries = await (0, distiller_js_1.distillSession)(llm, conversationText, canonProjectVal ?? "unknown", date, chunkSize, dropped, (u) => {
1866
+ const entries = await (0, distiller_js_1.distillSession)(
1867
+ // #332: the per-pool selection — syncLlm is the confidential client
1868
+ // for confidential deliveries (guaranteed non-null by the refusal).
1869
+ syncLlm, conversationText, canonProjectVal ?? "unknown", date, chunkSize, dropped, (u) => {
1601
1870
  distillUsage.prompt += u.prompt_tokens ?? 0;
1602
1871
  distillUsage.completion += u.completion_tokens ?? 0;
1603
1872
  distillUsage.total += u.total_tokens ?? 0;
@@ -1638,6 +1907,9 @@ async function startServer(options = {}) {
1638
1907
  // filtered. Default null for older clients that don't send them.
1639
1908
  sourceAgentId: typeof source_agent_id === "string" ? source_agent_id : null,
1640
1909
  sourceDomain: typeof source_domain === "string" ? source_domain : null,
1910
+ // #609: the workspace path (metadata for the path backfill +
1911
+ // attribution); null for deliveries that carried none.
1912
+ workspacePath,
1641
1913
  sourceMachine: storage.sanitizeSourceMachine(source_machine),
1642
1914
  // Per-chunk key: "<session_id>[#<segment_id>]#<i>". The prefix
1643
1915
  // matches the dedup checks above, so a re-run is idempotent.
@@ -1649,9 +1921,9 @@ async function startServer(options = {}) {
1649
1921
  // distiller.ts. Pre-#216 distiller output (no tag) defaults to
1650
1922
  // experience in the parser, so this is backward compatible.
1651
1923
  memoryType,
1652
- // 0.16.x: privacy defaults to null (vestigial column). A legacy
1653
- // client that sends an explicit value is honored; absent → null.
1654
- privacy: typeof privacy === "string" ? privacy : null,
1924
+ // #332: the DERIVED stamp — same value the queue branch would
1925
+ // have carried (client-declared privacy never reaches here).
1926
+ privacy: derivedPrivacy,
1655
1927
  createdAt,
1656
1928
  }));
1657
1929
  }
@@ -1696,7 +1968,11 @@ async function startServer(options = {}) {
1696
1968
  res.status(503).json({ error: "Server not initialized" });
1697
1969
  return;
1698
1970
  }
1699
- const { id, content, project, memory_type, privacy } = req.body ?? {};
1971
+ // NOTE (#332): `privacy` is no longer a writable field — classification is
1972
+ // server-derived at intake and changed only by the owner's
1973
+ // `hicortex backfill-privacy`. A body privacy field is ignored (kept out
1974
+ // of the destructure so the intent is structural).
1975
+ const { id, content, project, memory_type } = req.body ?? {};
1700
1976
  if (!id || typeof id !== "string") {
1701
1977
  res.status(400).json({ error: "Missing or invalid 'id' field" });
1702
1978
  return;
@@ -1723,8 +1999,6 @@ async function startServer(options = {}) {
1723
1999
  // label is junk), never a stored variant.
1724
2000
  if (project !== undefined)
1725
2001
  fields.project = (0, project_canonicalize_js_1.canonicalizeProject)(project, projectAliases);
1726
- if (privacy !== undefined)
1727
- fields.privacy = privacy;
1728
2002
  // Validate + normalize memory_type BEFORE adding to `fields` so the
1729
2003
  // empty-fields check below correctly counts a memory_type-only update.
1730
2004
  const validTypes = type_labels_js_1.ACCEPTED_MEMORY_TYPES;
@@ -1901,6 +2175,17 @@ async function startServer(options = {}) {
1901
2175
  const resultLimit = rawLimit && Number.isFinite(rawLimit) && rawLimit >= 1 ? Math.floor(rawLimit) : 10;
1902
2176
  const filterDomain = typeof req.query.domain === "string" && req.query.domain ? req.query.domain : undefined;
1903
2177
  const filterRelationship = typeof req.query.relationship === "string" && req.query.relationship ? req.query.relationship : undefined;
2178
+ // #332: the optional `agent` param gates neighbors/hubs/path (the
2179
+ // content-bearing ops). op=export stays UNGATED — it is the /viz owner
2180
+ // surface (owner ruling: dashboard/viz not gated in this build; a
2181
+ // show-confidential toggle is a separate later item).
2182
+ const member = requestSeesConfidential(req.query.agent);
2183
+ // A confidential endpoint/center id is invisible to non-members — same
2184
+ // 404 contract as GET /memory (existence is not revealed).
2185
+ const visibleId = (id) => {
2186
+ const row = db.prepare("SELECT privacy FROM memories WHERE id = ?").get(id);
2187
+ return member || row?.privacy !== "confidential";
2188
+ };
1904
2189
  try {
1905
2190
  if (op === "neighbors") {
1906
2191
  const idParam = typeof req.query.id === "string" ? req.query.id : "";
@@ -1909,16 +2194,16 @@ async function startServer(options = {}) {
1909
2194
  return;
1910
2195
  }
1911
2196
  const resolvedId = resolveMemoryId(db, idParam);
1912
- if (!resolvedId) {
2197
+ if (!resolvedId || !visibleId(resolvedId)) {
1913
2198
  res.status(404).json({ error: `Memory not found: ${idParam}` });
1914
2199
  return;
1915
2200
  }
1916
- const neighbors = (0, graph_js_1.getNeighbors)(db, resolvedId, resultLimit, filterRelationship);
2201
+ const neighbors = (0, graph_js_1.getNeighbors)(db, resolvedId, resultLimit, filterRelationship, { includeConfidential: member });
1917
2202
  res.json({ results: neighbors });
1918
2203
  return;
1919
2204
  }
1920
2205
  if (op === "hubs") {
1921
- let hubs = (0, graph_js_1.detectHubs)(db);
2206
+ let hubs = (0, graph_js_1.detectHubs)(db, 2, 3, { includeConfidential: member });
1922
2207
  if (filterDomain) {
1923
2208
  hubs = hubs.filter((h) => h.domain === filterDomain || h.project === filterDomain);
1924
2209
  }
@@ -1934,11 +2219,11 @@ async function startServer(options = {}) {
1934
2219
  }
1935
2220
  const fromId = resolveMemoryId(db, fromParam);
1936
2221
  const toId = resolveMemoryId(db, toParam);
1937
- if (!fromId || !toId) {
2222
+ if (!fromId || !toId || !visibleId(fromId) || !visibleId(toId)) {
1938
2223
  res.status(404).json({ error: "One or both memory IDs not found" });
1939
2224
  return;
1940
2225
  }
1941
- const path = (0, graph_js_1.shortestPath)(db, fromId, toId);
2226
+ const path = (0, graph_js_1.shortestPath)(db, fromId, toId, 5, { includeConfidential: member });
1942
2227
  res.json({ path: path ?? null });
1943
2228
  return;
1944
2229
  }