@gamaze/hicortex 0.27.4 → 0.28.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 (92) hide show
  1. package/assets/dashboard.html +361 -100
  2. package/dist/backfill-privacy.d.ts +68 -45
  3. package/dist/backfill-privacy.js +236 -145
  4. package/dist/calibration.d.ts +67 -68
  5. package/dist/calibration.js +75 -78
  6. package/dist/capture-health.d.ts +2 -2
  7. package/dist/capture-health.js +2 -2
  8. package/dist/classification.d.ts +141 -12
  9. package/dist/classification.js +214 -27
  10. package/dist/classify-domains.d.ts +1 -1
  11. package/dist/classify-domains.js +2 -2
  12. package/dist/cli-args.d.ts +5 -3
  13. package/dist/cli-args.js +7 -3
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +64 -16
  16. package/dist/cluster.d.ts +12 -9
  17. package/dist/cluster.js +9 -6
  18. package/dist/consolidate.d.ts +93 -43
  19. package/dist/consolidate.js +255 -119
  20. package/dist/dashboard.d.ts +48 -5
  21. package/dist/dashboard.js +55 -3
  22. package/dist/db.js +27 -6
  23. package/dist/dedup.d.ts +2 -3
  24. package/dist/dedup.js +2 -3
  25. package/dist/distill-queue.d.ts +36 -4
  26. package/dist/distill-queue.js +80 -18
  27. package/dist/distiller.d.ts +1 -1
  28. package/dist/distiller.js +13 -12
  29. package/dist/domain-classify.d.ts +8 -9
  30. package/dist/domain-classify.js +6 -7
  31. package/dist/graph.d.ts +15 -5
  32. package/dist/graph.js +46 -13
  33. package/dist/hermes-transcript-reader.d.ts +1 -1
  34. package/dist/hermes-transcript-reader.js +1 -1
  35. package/dist/init.d.ts +2 -2
  36. package/dist/init.js +3 -3
  37. package/dist/llm.d.ts +1 -1
  38. package/dist/llm.js +5 -5
  39. package/dist/mcp-server.js +323 -59
  40. package/dist/memory-instructions.d.ts +2 -2
  41. package/dist/memory-instructions.js +2 -2
  42. package/dist/nightly.d.ts +1 -1
  43. package/dist/nightly.js +64 -5
  44. package/dist/nofit.d.ts +2 -2
  45. package/dist/nofit.js +2 -2
  46. package/dist/observed-agents.d.ts +54 -0
  47. package/dist/observed-agents.js +78 -0
  48. package/dist/project-canonicalize.d.ts +6 -5
  49. package/dist/project-canonicalize.js +6 -5
  50. package/dist/prompts.d.ts +29 -8
  51. package/dist/prompts.js +39 -16
  52. package/dist/quality-scoreboard.d.ts +1 -1
  53. package/dist/recall-hook-cli.d.ts +1 -1
  54. package/dist/recall-hook-cli.js +2 -2
  55. package/dist/recall-index.d.ts +28 -14
  56. package/dist/recall-index.js +22 -10
  57. package/dist/recall-precision.d.ts +3 -3
  58. package/dist/recall-precision.js +5 -4
  59. package/dist/reconcile-projects.d.ts +2 -2
  60. package/dist/reconcile-projects.js +2 -2
  61. package/dist/reconsolidation.d.ts +9 -2
  62. package/dist/reconsolidation.js +48 -31
  63. package/dist/relink.d.ts +2 -2
  64. package/dist/relink.js +4 -4
  65. package/dist/rescore-importance.d.ts +2 -2
  66. package/dist/rescore-importance.js +22 -3
  67. package/dist/retrieval.d.ts +14 -0
  68. package/dist/retrieval.js +11 -11
  69. package/dist/schema-prototypes.d.ts +1 -1
  70. package/dist/schema-prototypes.js +1 -1
  71. package/dist/seed-lesson.js +4 -2
  72. package/dist/spaces-api.d.ts +104 -0
  73. package/dist/spaces-api.js +193 -0
  74. package/dist/spaces-cli.d.ts +90 -0
  75. package/dist/spaces-cli.js +245 -0
  76. package/dist/spaces.d.ts +187 -0
  77. package/dist/spaces.js +360 -0
  78. package/dist/storage.d.ts +47 -10
  79. package/dist/storage.js +74 -17
  80. package/dist/sweep-volatile.d.ts +2 -2
  81. package/dist/sweep-volatile.js +2 -2
  82. package/dist/telemetry-cli.d.ts +1 -1
  83. package/dist/telemetry-cli.js +1 -1
  84. package/dist/type-classify.d.ts +1 -1
  85. package/dist/type-classify.js +1 -1
  86. package/dist/type-labels.d.ts +1 -1
  87. package/dist/type-labels.js +1 -1
  88. package/dist/types.d.ts +43 -20
  89. package/dist/wrapper-prompt.d.ts +2 -2
  90. package/dist/wrapper-prompt.js +2 -2
  91. package/package.json +1 -1
  92. package/server.json +2 -2
@@ -98,6 +98,9 @@ const project_canonicalize_js_1 = require("./project-canonicalize.js");
98
98
  const classification_js_1 = require("./classification.js");
99
99
  const init_js_1 = require("./init.js");
100
100
  const marker_key_api_js_1 = require("./marker-key-api.js");
101
+ const spaces_api_js_1 = require("./spaces-api.js");
102
+ const observed_agents_js_1 = require("./observed-agents.js");
103
+ const spaces_js_1 = require("./spaces.js");
101
104
  // ---------------------------------------------------------------------------
102
105
  // Server state
103
106
  // ---------------------------------------------------------------------------
@@ -112,10 +115,21 @@ let llmConfig = null;
112
115
  // same funnel as the main client (boot), with the same tuning overlay.
113
116
  let confidentialLlm = null;
114
117
  let confidentialLlmConfig = null;
115
- // One-time-per-process deprecation warning for the `?privacy=` query param
116
- // (0.16.x: the column is vestigial, never filtered). Old clients/plugins still
117
- // send it; we accept it (backward compat) but warn ONCE so an operator relying
118
- // on privacy filtering discovers from the logs that it is now a no-op.
118
+ // #642: the per-space LLM clients/configs — buildSpaceLlms at the spaces boot
119
+ // seam below, one entry per configured space EXCEPT 'confidential' (its client
120
+ // keeps the dedicated fields above: explicit spaces.<id>.llm* wins, else the
121
+ // llmConfidential* endpoint is INHERITED as the same client object). A null or
122
+ // absent entry = the space has NO model: the SYNC /distill path refuses such a
123
+ // delivery (503 hold — see the /distill handler) and the nightly drain holds
124
+ // its queued items; never the main model.
125
+ let spaceClients = new Map();
126
+ let spaceConfigs = new Map();
127
+ // One-time-per-process deprecation warning for the `?privacy=` query param.
128
+ // Old clients/plugins still send it; we accept it (backward compat) but warn
129
+ // ONCE so an operator relying on client-side privacy filtering discovers from
130
+ // the logs that it is a no-op: the param is IGNORED — classification and
131
+ // visibility are server-derived (#332/#642: spaces are configured server-side
132
+ // from agent rosters and path patterns, never requested by clients).
119
133
  let privacyDeprecationWarned = false;
120
134
  function warnDeprecatedPrivacyParamIfPresent(query, route) {
121
135
  if (privacyDeprecationWarned)
@@ -124,8 +138,8 @@ function warnDeprecatedPrivacyParamIfPresent(query, route) {
124
138
  return;
125
139
  privacyDeprecationWarned = true;
126
140
  console.warn(`[hicortex] client sent ?privacy= on /${route}, which is ignored since 0.16.2 — ` +
127
- `privacy is no longer filtered server-side (the column is vestigial). ` +
128
- `Use a separate Hicortex server for isolation. (This warning fires once per process.)`);
141
+ `classification/visibility is server-derived, never client-requested (#332/#642). ` +
142
+ `(This warning fires once per process.)`);
129
143
  }
130
144
  let stateDir = "";
131
145
  // Resolved identityClients list (spec §2) — the harness names allowed to inject
@@ -167,6 +181,14 @@ let confidentialPathPatterns = [];
167
181
  // circle is otherwise active) — the attack surface ships disabled by
168
182
  // default. The compare itself lives in classification.ts (timing-safe).
169
183
  let confidentialMarkerKey = null;
184
+ // #642: the resolved spaces (the `spaces` config map + the legacy-materialized
185
+ // confidential space — see spaces.ts), resolved once at boot at the SAME
186
+ // confidential seam (restart to apply). Empty = zero-space install: intake
187
+ // stamping, read gates, and prompts stay byte-identical to the #332 release
188
+ // (AC-1). deriveIntakeSpace consumes the ordered list; knownSpaceIds feeds
189
+ // the write boundary's known set.
190
+ let resolvedSpaces = [];
191
+ let spaceById = new Map();
170
192
  /**
171
193
  * #567: fold ONE project string through the boot-resolved alias map — the
172
194
  * shared normalization for every project-string entry point in this file
@@ -179,15 +201,29 @@ let confidentialMarkerKey = null;
179
201
  */
180
202
  const canonProject = (v) => (0, project_canonicalize_js_1.canonicalizeProject)(typeof v === "string" ? v : null, projectAliases) ?? undefined;
181
203
  /**
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.
204
+ * #642 AC-5 (was #332's requestSeesConfidential boolean): resolve ONE
205
+ * request's visible SPACE SET from its `agent` param against the
206
+ * boot-resolved spaces — the ids of every space whose members list contains
207
+ * the sanitized agent. Absent/blank/unknown agent → EMPTY set (fail-closed:
208
+ * shared-only — no space's rows, exactly the old non-member boolean). The
209
+ * wire NEVER carries a space list — only `?agent=` / body `agent`; membership
210
+ * is server-configured, so client-declared visibility is a closed channel
211
+ * (#614's law). On a legacy confidential-only install the materialized
212
+ * confidential space makes this agree with the old boolean EXACTLY (member ⇔
213
+ * rostered). The `agent` self-asserts identity, exactly like the
214
+ * client-pushed project field — same trust level, documented in the spec
215
+ * (per-agent tokens are the known future fix). Shared by every agent-facing
216
+ * read route below.
217
+ *
218
+ * #642 AC-11 — first-prompt discovery rides the SAME seam (the one place
219
+ * every gated read already passes through): the sanitized agent id is
220
+ * recorded in the observed-agents store, fail-soft (a store hiccup must
221
+ * never break the read — the sighting is advisory, the gate input is not).
222
+ * Only reads carrying `agent` record; membership resolves from the SAME
223
+ * sanitized id that was recorded (spacesForMember re-sanitizes it — an
224
+ * idempotent no-op on an already-sanitized value).
189
225
  */
190
- const requestSeesConfidential = (rawAgent) => (0, classification_js_1.isCircleMember)(typeof rawAgent === "string" && rawAgent ? rawAgent : null, confidentialRoster);
226
+ const requesterVisibleSpaces = (rawAgent) => (0, spaces_js_1.spacesForMember)(db ? (0, observed_agents_js_1.recordObservedAgentSighting)(db, rawAgent) : null, resolvedSpaces);
191
227
  // Cache detectChunkSize results keyed by "<provider>/<model>@<baseUrl>" so we
192
228
  // probe each endpoint once per server boot rather than once per /distill request.
193
229
  const chunkSizeCache = new Map();
@@ -335,8 +371,10 @@ function createMcpServer() {
335
371
  // #332: the MCP ingest path derives the stamp from its fixed
336
372
  // source_agent like every write path (a roster entry
337
373
  // "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),
374
+ // confidential; mechanical rule, no special case). #642: the same
375
+ // derivation now runs over the resolved spaces — value-identical on
376
+ // zero-space installs, space-aware when configured.
377
+ privacy: (0, classification_js_1.deriveIntakeSpace)("claude-code/manual", resolvedSpaces),
340
378
  });
341
379
  if (explicitMark)
342
380
  (0, reconsolidation_js_1.applyExplicitMark)(db, id, explicitMark);
@@ -509,9 +547,12 @@ function createMcpServer() {
509
547
  // hard-omitted, and a confidential center/endpoint id reads as not
510
548
  // found. Accepted in the spec: circle agents read through their
511
549
  // plugin's agent-threaded REST calls, not through MCP tools.
550
+ // #642 AC-6: shared-ONLY, generalized — a row of ANY space (confidential
551
+ // included) and any unknown space id reads as not found here; the
552
+ // graph ops below run opts-less (the shared-only default).
512
553
  const idVisible = (fullId) => {
513
554
  const row = db.prepare("SELECT privacy FROM memories WHERE id = ?").get(fullId);
514
- return row?.privacy !== "confidential";
555
+ return (row?.privacy ?? "standard") === "standard";
515
556
  };
516
557
  try {
517
558
  if (operation === "neighbors") {
@@ -1021,6 +1062,78 @@ async function startServer(options = {}) {
1021
1062
  confidentialRows: confidentialRowsCount,
1022
1063
  queueConfidential: queueConfidentialCount,
1023
1064
  });
1065
+ // #642 spaces: resolve the config map (plus the legacy confidential
1066
+ // materialization) at the SAME boot seam (restart to apply). Dropped
1067
+ // entries and warnings print ONCE here — the resolveIdentityAgents
1068
+ // pattern (a typo must surface, never silently match nothing). Zero-config
1069
+ // installs print NOTHING new (the AC-1 byte-identical boot), and a
1070
+ // pure-legacy install's materialized confidential space is already
1071
+ // announced by the "Confidential circle:" line above — so the status line
1072
+ // fires only when EXPLICIT spaces are configured.
1073
+ const spaceRes = (0, spaces_js_1.resolveSpaces)(savedConfig);
1074
+ resolvedSpaces = spaceRes.spaces;
1075
+ spaceById = spaceRes.byId;
1076
+ if (spaceRes.dropped.length > 0) {
1077
+ console.warn(`[hicortex] Ignoring invalid spaces entries: ${spaceRes.dropped.join(", ")} ` +
1078
+ `(ids must match ^[a-z0-9][a-z0-9_-]*$ like agent ids; entries must be objects; ` +
1079
+ `'standard' is never a space id — a dropped entry matches nothing)`);
1080
+ }
1081
+ for (const spaceWarning of spaceRes.warnings) {
1082
+ console.warn(`[hicortex] spaces: ${spaceWarning}`);
1083
+ }
1084
+ const rawSpacesConfig = savedConfig?.spaces;
1085
+ const explicitConfidentialSpace = rawSpacesConfig !== null && rawSpacesConfig !== undefined &&
1086
+ typeof rawSpacesConfig === "object" && !Array.isArray(rawSpacesConfig) &&
1087
+ "confidential" in rawSpacesConfig;
1088
+ if (spaceRes.spaces.some((s) => s.id !== "confidential") || explicitConfidentialSpace) {
1089
+ console.log(`[hicortex] Spaces: ${spaceRes.spaces.length} configured (${spaceRes.spaces.map((s) => s.id).join(", ")})`);
1090
+ }
1091
+ // #642 AC-7: stored space ids no configured space claims are INVISIBLE to
1092
+ // every requester (no members list can contain them — fail-closed, never
1093
+ // normalized to shared). ONE boot warning naming every id (per boot, not
1094
+ // per request) so the operator configures the space or re-stamps; the
1095
+ // nightly funnel mirrors this line so its log carries it too.
1096
+ const unknownSpaceIds = (0, spaces_js_1.unknownStoredSpaceIds)(db, (0, spaces_js_1.knownSpaceIds)({ byId: spaceRes.byId }));
1097
+ if (unknownSpaceIds.length > 0) {
1098
+ console.warn(`[hicortex] Unknown space ids stored in the DB: ${unknownSpaceIds.join(", ")} — ` +
1099
+ `no configured space claims them, so they are invisible to every requester ` +
1100
+ `until configured or re-stamped (#642 AC-7)`);
1101
+ }
1102
+ // #642 AC-9: per-space model resolution at the SAME boot seam — one line
1103
+ // per ACTIVE space with no effective client (no explicit spaces.<id>.llm*
1104
+ // and no llmConfidential* endpoint). Such a space's queued deliveries and
1105
+ // consolidation work HOLD (the nightly drain + pool-aware stages enforce
1106
+ // it; they build their own clients from the same config), never the main
1107
+ // model — this warning is how the operator learns from the log instead of
1108
+ // from a silently growing inbox. Gate on non-empty: a zero-space install
1109
+ // prints nothing (AC-1).
1110
+ {
1111
+ const spaceBundle = (0, classification_js_1.buildSpaceLlms)(savedConfig, spaceRes.spaces, confidentialBuilt);
1112
+ // Hoisted into the module vars so the SYNC /distill path reads the
1113
+ // boot-resolved per-space clients: the handler below routes a space-
1114
+ // stamped delivery by THIS map (the same selection the nightly drain
1115
+ // makes from its own resolveLlmPair — one resolution per boot).
1116
+ spaceClients = spaceBundle.clients;
1117
+ spaceConfigs = spaceBundle.configs;
1118
+ const rowsBySpace = new Map();
1119
+ const queueBySpace = new Map();
1120
+ for (const table of ["memories", "distill_queue"]) {
1121
+ const target = table === "memories" ? rowsBySpace : queueBySpace;
1122
+ for (const row of db
1123
+ .prepare(`SELECT privacy, COUNT(*) AS c FROM ${table} ` +
1124
+ `WHERE privacy IS NOT NULL AND privacy NOT IN ('standard', 'confidential') ` +
1125
+ `GROUP BY privacy`)
1126
+ .all()) {
1127
+ target.set(row.privacy, row.c);
1128
+ }
1129
+ }
1130
+ for (const warning of (0, classification_js_1.spaceHoldWarnings)(spaceRes.spaces, spaceBundle.clients, {
1131
+ rowsBySpace,
1132
+ queueBySpace,
1133
+ })) {
1134
+ console.warn(warning);
1135
+ }
1136
+ }
1024
1137
  // #264 dir migration: rename <hicortex-home>/context/ → identity/ on boot
1025
1138
  // when only the legacy dir exists. The fallback read in identity-store.ts
1026
1139
  // (readSectionsWithFallback) is the safety net for a partial/no migration.
@@ -1129,8 +1242,10 @@ async function startServer(options = {}) {
1129
1242
  return;
1130
1243
  }
1131
1244
  try {
1132
- const member = requestSeesConfidential(req.query.agent);
1133
- const lessons = storage.getLessons(db, 30, null, { includeConfidential: member });
1245
+ // #642 AC-5: the visible-SPACE-SET gate (was the #332 boolean) — the
1246
+ // requester's resolved membership; lessons of other spaces are omitted.
1247
+ const visible = requesterVisibleSpaces(req.query.agent);
1248
+ const lessons = storage.getLessons(db, 30, null, { visibleSpaces: visible });
1134
1249
  const totalCount = storage.countMemories(db);
1135
1250
  // Project index
1136
1251
  const projects = db
@@ -1230,7 +1345,9 @@ async function startServer(options = {}) {
1230
1345
  memoryType: normalizedType ?? "experience",
1231
1346
  // #332: server-derived stamp — same source_agent × roster rule as
1232
1347
  // /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),
1348
+ // #642: the derivation runs over the resolved spaces (agent-only, no
1349
+ // signals today — /ingest carries no workspace path or marker).
1350
+ privacy: (0, classification_js_1.deriveIntakeSpace)(typeof source_agent === "string" ? source_agent : null, resolvedSpaces),
1234
1351
  createdAt: session_date ? new Date(session_date).toISOString() : undefined,
1235
1352
  });
1236
1353
  if (explicitMark)
@@ -1278,10 +1395,12 @@ async function startServer(options = {}) {
1278
1395
  // otherwise).
1279
1396
  // #332: the optional `agent` param is the circle-membership gate —
1280
1397
  // absent/unknown = hard omit of confidential rows.
1281
- const member = requestSeesConfidential(req.query.agent);
1398
+ // #642 AC-5: generalized to the visible SPACE set — rows of spaces the
1399
+ // requester is not a member of are hard-omitted at candidate-build time.
1400
+ const visible = requesterVisibleSpaces(req.query.agent);
1282
1401
  const minSimilarity = resolveSearchSimilarityFloor(req.query.minSimilarity);
1283
1402
  try {
1284
- let results = await retrieval.retrieve(db, embedder_js_1.embed, query, { limit, project, includeConfidential: member });
1403
+ let results = await retrieval.retrieve(db, embedder_js_1.embed, query, { limit, project, visibleSpaces: visible });
1285
1404
  results = applySearchRelevanceGate(results, { minSimilarity, project, crossProjectMinSimilarity: recallCrossProjectBar });
1286
1405
  res.json({ results });
1287
1406
  }
@@ -1330,11 +1449,12 @@ async function startServer(options = {}) {
1330
1449
  // factory (built per request) carries it into retrieve() so the omit
1331
1450
  // happens at candidate-build time, not post-hoc. A client-declared
1332
1451
  // `privacy` body field remains ignored (0.16.x backcompat posture).
1452
+ // #642 AC-5: generalized to the visible SPACE set (requesterVisibleSpaces).
1333
1453
  const factory = (0, recall_index_js_1.createRecallRetrieveFn)({
1334
1454
  db,
1335
1455
  registry: recallRegistry,
1336
1456
  embedFn: embedder_js_1.embed,
1337
- includeConfidential: requestSeesConfidential(req.body?.agent),
1457
+ visibleSpaces: requesterVisibleSpaces(req.body?.agent),
1338
1458
  });
1339
1459
  const r = await (0, recall_index_js_1.handleRecallIndex)({
1340
1460
  db,
@@ -1364,8 +1484,10 @@ async function startServer(options = {}) {
1364
1484
  // #332: the optional `agent` param is the circle-membership gate — a
1365
1485
  // confidential id fetched by a non-member answers 404 (before any
1366
1486
  // strengthening side effect, inside handleMemoryGet).
1487
+ // #642 AC-5: generalized to the visible SPACE set — a row of a space the
1488
+ // requester is not a member of answers 404 the same way.
1367
1489
  try {
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) });
1490
+ const r = (0, recall_index_js_1.handleMemoryGet)(db, { id: req.query.id }, { recordFetch: recall_precision_js_1.recordRecallFetch }, { visibleSpaces: requesterVisibleSpaces(req.query.agent) });
1369
1491
  res.status(r.status).json(r.body);
1370
1492
  }
1371
1493
  catch (err) {
@@ -1385,11 +1507,12 @@ async function startServer(options = {}) {
1385
1507
  // default (#408 — was the recentLimit config key).
1386
1508
  // 0.16.x: `privacy` query param accepted but ignored (vestigial column).
1387
1509
  // #332: the optional `agent` param is the circle-membership gate.
1510
+ // #642 AC-5: generalized to the visible SPACE set (requesterVisibleSpaces).
1388
1511
  const limit = req.query.limit ? Number(req.query.limit) : undefined;
1389
1512
  warnDeprecatedPrivacyParamIfPresent(req.query, "recent");
1390
- const member = requestSeesConfidential(req.query.agent);
1513
+ const visible = requesterVisibleSpaces(req.query.agent);
1391
1514
  try {
1392
- const results = retrieval.searchRecent(db, { project, limit, includeConfidential: member });
1515
+ const results = retrieval.searchRecent(db, { project, limit, visibleSpaces: visible });
1393
1516
  res.json({ results });
1394
1517
  }
1395
1518
  catch (err) {
@@ -1551,6 +1674,88 @@ async function startServer(options = {}) {
1551
1674
  (0, health_js_1.logAndSendInternalError)(res, "confidential/marker-key", err);
1552
1675
  }
1553
1676
  });
1677
+ // GET /spaces + PUT /spaces/assign + PUT /spaces/unassign — the #642 AC-10
1678
+ // admin API behind the dashboard's space management (and, next slice, the
1679
+ // CLI). GET assembles the resolved spaces, per-space memory/queue counts
1680
+ // (SQL GROUP BY folded through spaceOf — NULL/''/'standard' count under
1681
+ // 'standard', which is never listed), the observed unassigned agents
1682
+ // (first-prompt discovery, AC-11), and whether each space's work has a
1683
+ // model (the EFFECTIVE client: boot spaceClients, or the confidential
1684
+ // fields for the reserved id). The PUTs run the pure handlers
1685
+ // (spaces-api.ts) against a FRESH config read, persist ONLY the `spaces`
1686
+ // key through persistConfigUpdates, then LIVE RE-RESOLVE — resolveSpaces
1687
+ // over the merged config reassigns resolvedSpaces/spaceById, so the read
1688
+ // gate flips on the NEXT request, no restart (the marker-key live-assign
1689
+ // precedent; boot and these routes are the only writers). The per-space
1690
+ // LLM maps (spaceClients/spaceConfigs) are NOT re-resolved: these routes
1691
+ // edit members lists only, and a space's llm config comes from the
1692
+ // entry's llm* fields or llmConfidential*, neither of which they write.
1693
+ // Server-mode only by construction — the routes exist only on this daemon.
1694
+ // Bearer-only: the standard auth middleware above, no exemption (writable
1695
+ // by any token holder — inherent to the single-token model, #642).
1696
+ app.get("/spaces", (_req, res) => {
1697
+ if (!db) {
1698
+ res.status(503).json({ error: "Server not initialized" });
1699
+ return;
1700
+ }
1701
+ try {
1702
+ const countsFor = (table) => {
1703
+ const out = {};
1704
+ for (const row of db
1705
+ .prepare(`SELECT privacy, COUNT(*) AS c FROM ${table} GROUP BY privacy`)
1706
+ .all()) {
1707
+ const key = (0, spaces_js_1.spaceOf)(row.privacy);
1708
+ out[key] = (out[key] ?? 0) + row.c;
1709
+ }
1710
+ return out;
1711
+ };
1712
+ const llmConfigured = new Set();
1713
+ for (const s of resolvedSpaces) {
1714
+ if (s.id === "confidential") {
1715
+ if (confidentialLlm)
1716
+ llmConfigured.add(s.id);
1717
+ }
1718
+ else if (spaceClients.get(s.id)) {
1719
+ llmConfigured.add(s.id);
1720
+ }
1721
+ }
1722
+ const r = (0, spaces_api_js_1.handleSpacesGet)({
1723
+ spaces: resolvedSpaces,
1724
+ counts: { memory: countsFor("memories"), queued: countsFor("distill_queue") },
1725
+ observed: (0, observed_agents_js_1.listObservedAgents)(db),
1726
+ llmConfigured,
1727
+ });
1728
+ res.status(r.status).json(r.body);
1729
+ }
1730
+ catch (err) {
1731
+ (0, health_js_1.logAndSendInternalError)(res, "spaces", err);
1732
+ }
1733
+ });
1734
+ const spacesWriteHandler = (verb) => (req, res) => {
1735
+ try {
1736
+ const fresh = readConfigFile(stateDir) ?? {};
1737
+ const r = verb === "assign"
1738
+ ? (0, spaces_api_js_1.handleSpacesAssign)(req.body ?? null, fresh)
1739
+ : (0, spaces_api_js_1.handleSpacesUnassign)(req.body ?? null, fresh);
1740
+ if (r.patch && r.applied) {
1741
+ const merged = (0, init_js_1.persistConfigUpdates)((0, node_path_1.join)(stateDir, "config.json"), r.patch);
1742
+ // LIVE RE-RESOLVE — the read gate + intake stamping flip on the next
1743
+ // request (resolvedSpaces is what requesterVisibleSpaces and
1744
+ // deriveIntakeSpace read; spaceById feeds the known-set boundary).
1745
+ const reResolved = (0, spaces_js_1.resolveSpaces)(merged);
1746
+ resolvedSpaces = reResolved.spaces;
1747
+ spaceById = reResolved.byId;
1748
+ console.log(`[hicortex] spaces: ${verb} '${r.applied.agent}' ${verb === "assign" ? "to" : "from"} ` +
1749
+ `space '${r.applied.space}' — applied live (persisted to config.json)`);
1750
+ }
1751
+ res.status(r.status).json(r.body);
1752
+ }
1753
+ catch (err) {
1754
+ (0, health_js_1.logAndSendInternalError)(res, `spaces/${verb}`, err);
1755
+ }
1756
+ };
1757
+ app.put("/spaces/assign", spacesWriteHandler("assign"));
1758
+ app.put("/spaces/unassign", spacesWriteHandler("unassign"));
1554
1759
  // REST /distill — canonical capture endpoint (0.9.0+).
1555
1760
  // Every machine (including the server itself) POSTs denoised session text here.
1556
1761
  // The server distills, embeds, stores. Body limit: see `distillBodyLimitMb`
@@ -1604,11 +1809,15 @@ async function startServer(options = {}) {
1604
1809
  // confidentialMarkerKey compared timing-safe against the relayed content
1605
1810
  // (an absent key makes every marker inert; a refused marker never reduces
1606
1811
  // a server rule).
1607
- const derivedPrivacy = (0, classification_js_1.deriveIntakePrivacy)(typeof source_agent === "string" ? source_agent : null, confidentialRoster, {
1812
+ // #642: the derivation is now space-aware (deriveIntakeSpace): per-space
1813
+ // PATH patterns first, then per-space MEMBER lists, then the confidential
1814
+ // marker arm — over the boot-resolved resolvedSpaces (on a zero-space
1815
+ // install the value is byte-identical: the materialized confidential
1816
+ // space answers every arm exactly as the old roster+paths call did).
1817
+ const derivedPrivacy = (0, classification_js_1.deriveIntakeSpace)(typeof source_agent === "string" ? source_agent : null, resolvedSpaces, {
1608
1818
  workspacePath,
1609
1819
  markerContent: clientMarker,
1610
1820
  markerKey: confidentialMarkerKey,
1611
- paths: confidentialPathPatterns,
1612
1821
  });
1613
1822
  // #614: the rate-limited refusal warn at the intake seam. Marker content
1614
1823
  // arrived and did NOT validate — no key configured (the arm is inert), or
@@ -1664,18 +1873,47 @@ async function startServer(options = {}) {
1664
1873
  // the delivery without any LLM call and the nightly drain defers until
1665
1874
  // an LLM is configured.
1666
1875
  }
1667
- // #332 sync-mode refusal: a CONFIDENTIAL delivery with no confidential
1668
- // model answers 503 — the client holds its cursor and retries (the
1876
+ // #642: the sync path's per-space client resolution — the drain's
1877
+ // selection (distill-queue.ts) mirrored at the HTTP boundary. 'standard'
1878
+ // → the main client; 'confidential' → the dedicated confidential fields;
1879
+ // any other stamp → the BOOT-RESOLVED per-space client (buildSpaceLlms at
1880
+ // the spaces seam: explicit spaces.<id>.llm* wins, else the inherited
1881
+ // llmConfidential* endpoint — the same client object the confidential pool
1882
+ // uses). Absent = HOLD, never a fallback: the main model is not a
1883
+ // representable answer for non-shared text.
1884
+ const deliverySpace = (0, spaces_js_1.spaceOf)(derivedPrivacy);
1885
+ const syncDeliveryPair = () => {
1886
+ if (deliverySpace === "confidential") {
1887
+ return confidentialLlm && confidentialLlmConfig
1888
+ ? { client: confidentialLlm, config: confidentialLlmConfig }
1889
+ : null;
1890
+ }
1891
+ if (deliverySpace !== "standard") {
1892
+ const client = spaceClients.get(deliverySpace);
1893
+ const config = spaceConfigs.get(deliverySpace);
1894
+ return client && config ? { client, config } : null;
1895
+ }
1896
+ return llm && llmConfig ? { client: llm, config: llmConfig } : null;
1897
+ };
1898
+ // #332/#642 sync-mode refusal: a NON-SHARED delivery whose space has no
1899
+ // client answers 503 — the client holds its cursor and retries (the
1669
1900
  // 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)) {
1901
+ // model. 'confidential' keeps its exact #332 wording; every other space
1902
+ // id gets the same hold naming itself and its config pointer. Queue mode
1903
+ // stores the delivery and the drain holds it instead (per-item
1904
+ // skip-and-continue); a fresh install's first delivery derives a space
1905
+ // only when members/paths are configured, and a space configured without
1906
+ // a model refuses HERE — the fresh-brain immediate-distill carve-out can
1907
+ // never route non-shared text to the main model either.
1908
+ if (!queueMode && deliverySpace !== "standard" && !syncDeliveryPair()) {
1675
1909
  (0, capture_health_js_1.recordDistillActivity)(db, capEntry(0, "held"));
1676
1910
  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.",
1911
+ error: deliverySpace === "confidential"
1912
+ ? "Confidential delivery held — no confidential model configured " +
1913
+ "(llmConfidentialBaseUrl/ApiKey). It will be retried; it is never distilled on the main model."
1914
+ : `Delivery held — space '${deliverySpace}' has no model configured ` +
1915
+ `(spaces.${deliverySpace}.llmBaseUrl + llmApiKey, or the llmConfidential* endpoint). ` +
1916
+ `It will be retried; it is never distilled on the main model.`,
1679
1917
  });
1680
1918
  return;
1681
1919
  }
@@ -1693,9 +1931,12 @@ async function startServer(options = {}) {
1693
1931
  // The messages branch already redacts via extractConversationText
1694
1932
  // (distiller.ts), which calls redact() as its final step. #332: it
1695
1933
  // receives the SAME redaction config (the extended preset for
1696
- // confidential deliveries) so both branches redact identically.
1934
+ // non-shared deliveries) so both branches redact identically.
1935
+ // #642: the preset keys on the delivery's SPACE, not the literal
1936
+ // 'confidential' — redaction strength follows the class (any private
1937
+ // pool's captures are the contact-identifier-rich kind).
1697
1938
  conversationText = (0, distiller_js_1.extractConversationText)(messages, {
1698
- extended: derivedPrivacy === "confidential",
1939
+ extended: deliverySpace !== "standard",
1699
1940
  });
1700
1941
  }
1701
1942
  else {
@@ -1716,9 +1957,11 @@ async function startServer(options = {}) {
1716
1957
  // (DEFAULT_PATTERNS + emails + phone numbers) — the material a
1717
1958
  // confidential-circle agent captures is exactly the contact-identifier-rich
1718
1959
  // kind (#558). Standard deliveries keep today's set byte-identically.
1960
+ // #642: the preset keys on the delivery's SPACE, not the literal
1961
+ // 'confidential' — every private pool's deliveries redact identically.
1719
1962
  if (fromTextBranch) {
1720
1963
  const { text: redacted, count } = (0, redact_js_1.redact)(conversationText, {
1721
- extended: derivedPrivacy === "confidential",
1964
+ extended: deliverySpace !== "standard",
1722
1965
  });
1723
1966
  if (count > 0) {
1724
1967
  console.log(`[hicortex] Redacted ${count} secret(s) from /distill text`);
@@ -1769,7 +2012,7 @@ async function startServer(options = {}) {
1769
2012
  // its log line when `queued` is present. NO LLM call: the probe gate,
1770
2013
  // chunk-size detection, and the token gate all live in the nightly's
1771
2014
  // drain now. Redaction already happened above, so the inbox never holds
1772
- // unredacted text (owner ruling 05.10.2026: same protection as the DB).
2015
+ // unredacted text (#529 ruling: same protection as the DB).
1773
2016
  // The enqueue's UNIQUE(session_id, segment_id) insert is idempotent — a
1774
2017
  // duplicate (only reachable via a racing identical POST; the prechecks
1775
2018
  // above already answered the sequential re-POST) returns the same
@@ -1789,9 +2032,12 @@ async function startServer(options = {}) {
1789
2032
  segment_id,
1790
2033
  session_date,
1791
2034
  // #332: the queue row carries the DERIVED stamp — the drain trusts it
1792
- // (and routes the item to the matching model).
2035
+ // (and routes the item to the matching model). #642: the third arg is
2036
+ // the boot-resolved known space set so a space stamp SURVIVES the
2037
+ // normalize boundary (the handler derives only ids resolvedSpaces
2038
+ // knows, so the fail-closed THROW of AC-7 never fires for them).
1793
2039
  privacy: derivedPrivacy,
1794
- });
2040
+ }, (0, spaces_js_1.knownSpaceIds)({ byId: spaceById }));
1795
2041
  (0, capture_health_js_1.recordDistillActivity)(db, capEntry(conversationText.length, duplicate ? "skipped" : "ok"));
1796
2042
  if (duplicate) {
1797
2043
  res.status(200).json({ skipped: true, existing_count: 0 });
@@ -1815,13 +2061,26 @@ async function startServer(options = {}) {
1815
2061
  res.status(503).json({ error: "No LLM configured — run npx @gamaze/hicortex init. Session will be retried." });
1816
2062
  return;
1817
2063
  }
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;
2064
+ // #332/#642 per-pool client selection (the sync path's mirror of the
2065
+ // drain's selection), routed by SPACE: standard → the main client;
2066
+ // 'confidential' → the confidential fields; any other stamp → its
2067
+ // boot-resolved per-space client. The refusal above guarantees the pair
2068
+ // exists by here ('standard' by the no-LLM guard just above) — the 503
2069
+ // backstop below is defensive only, but refusing beats a silent `!` if
2070
+ // that invariant ever breaks: there is no code path that answers "give me
2071
+ // SOME client for this space". The probe gate + chunk-size cache below
2072
+ // use the SELECTED endpoint's config.
2073
+ const syncPair = syncDeliveryPair();
2074
+ if (!syncPair) {
2075
+ (0, capture_health_js_1.recordDistillActivity)(db, capEntry(conversationText.length, "held"));
2076
+ res.status(503).json({
2077
+ error: "The model configured for this delivery's space vanished mid-request — " +
2078
+ "held; it is never distilled on the main model. It will be retried.",
2079
+ });
2080
+ return;
2081
+ }
2082
+ const syncLlm = syncPair.client;
2083
+ const syncLlmConfig = syncPair.config;
1825
2084
  // #337: readiness gate — cached minimal generation probe BEFORE
1826
2085
  // detectChunkSize + distillSession, so a dead endpoint never even pays the
1827
2086
  // chunk-size probe. Placed AFTER the dedup short-circuits (a duplicate
@@ -1864,8 +2123,9 @@ async function startServer(options = {}) {
1864
2123
  // server-side per-entry console.log in distillChunk stays as well.
1865
2124
  const dropped = [];
1866
2125
  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).
2126
+ // #332/#642: the per-pool selection — syncLlm is the delivery's
2127
+ // SPACE client (confidential fields for 'confidential', the per-space
2128
+ // client otherwise; guaranteed non-null by the refusal).
1869
2129
  syncLlm, conversationText, canonProjectVal ?? "unknown", date, chunkSize, dropped, (u) => {
1870
2130
  distillUsage.prompt += u.prompt_tokens ?? 0;
1871
2131
  distillUsage.completion += u.completion_tokens ?? 0;
@@ -2179,12 +2439,16 @@ async function startServer(options = {}) {
2179
2439
  // content-bearing ops). op=export stays UNGATED — it feeds /viz, which
2180
2440
  // is deliberately ungated (a show-confidential toggle is a separate
2181
2441
  // 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).
2442
+ // #642 AC-5: generalized to the visible SPACE set — non-visible rows are
2443
+ // omitted from every op's content, and a non-visible center/endpoint id
2444
+ // reads as not found.
2445
+ const visible = requesterVisibleSpaces(req.query.agent);
2446
+ // A non-visible endpoint/center id is invisible — same 404 contract as
2447
+ // GET /memory (existence is not revealed; the 404 fires BEFORE any side
2448
+ // effect — there is none on this route, the contract is the shape).
2185
2449
  const visibleId = (id) => {
2186
2450
  const row = db.prepare("SELECT privacy FROM memories WHERE id = ?").get(id);
2187
- return member || row?.privacy !== "confidential";
2451
+ return (0, spaces_js_1.isVisiblePrivacy)(row?.privacy ?? "standard", visible);
2188
2452
  };
2189
2453
  try {
2190
2454
  if (op === "neighbors") {
@@ -2198,12 +2462,12 @@ async function startServer(options = {}) {
2198
2462
  res.status(404).json({ error: `Memory not found: ${idParam}` });
2199
2463
  return;
2200
2464
  }
2201
- const neighbors = (0, graph_js_1.getNeighbors)(db, resolvedId, resultLimit, filterRelationship, { includeConfidential: member });
2465
+ const neighbors = (0, graph_js_1.getNeighbors)(db, resolvedId, resultLimit, filterRelationship, { visibleSpaces: visible });
2202
2466
  res.json({ results: neighbors });
2203
2467
  return;
2204
2468
  }
2205
2469
  if (op === "hubs") {
2206
- let hubs = (0, graph_js_1.detectHubs)(db, 2, 3, { includeConfidential: member });
2470
+ let hubs = (0, graph_js_1.detectHubs)(db, 2, 3, { visibleSpaces: visible });
2207
2471
  if (filterDomain) {
2208
2472
  hubs = hubs.filter((h) => h.domain === filterDomain || h.project === filterDomain);
2209
2473
  }
@@ -2223,7 +2487,7 @@ async function startServer(options = {}) {
2223
2487
  res.status(404).json({ error: "One or both memory IDs not found" });
2224
2488
  return;
2225
2489
  }
2226
- const path = (0, graph_js_1.shortestPath)(db, fromId, toId, 5, { includeConfidential: member });
2490
+ const path = (0, graph_js_1.shortestPath)(db, fromId, toId, 5, { visibleSpaces: visible });
2227
2491
  res.json({ path: path ?? null });
2228
2492
  return;
2229
2493
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Product-owned memory instructions (#192, owner decision 28.07.2026).
2
+ * Product-owned memory instructions (#192).
3
3
  *
4
4
  * The instructions for HOW agents use Hicortex are shipped BY the product,
5
5
  * versioned with the server, and injected as a synthetic read-only `memory`
@@ -31,7 +31,7 @@ export declare function renderMemoryInstructions(): string;
31
31
  * `instructions` field in the initialize result — the MCP-native
32
32
  * SessionStart. Passive MCP clients (Claude Desktop etc.) run no hooks and
33
33
  * see no injected sections, so this field is the ONLY product-owned
34
- * guidance their model ever receives; the 2026-09-10 field test showed the
34
+ * guidance their model ever receives; a field test showed the
35
35
  * memory going entirely unused without it. Compact by construction (same
36
36
  * ~120-token budget as the identity sibling) and shares the two policy
37
37
  * sentences verbatim — one source, two surfaces. Drops the hook-only
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  /**
3
- * Product-owned memory instructions (#192, owner decision 28.07.2026).
3
+ * Product-owned memory instructions (#192).
4
4
  *
5
5
  * The instructions for HOW agents use Hicortex are shipped BY the product,
6
6
  * versioned with the server, and injected as a synthetic read-only `memory`
@@ -54,7 +54,7 @@ function renderMemoryInstructions() {
54
54
  * `instructions` field in the initialize result — the MCP-native
55
55
  * SessionStart. Passive MCP clients (Claude Desktop etc.) run no hooks and
56
56
  * see no injected sections, so this field is the ONLY product-owned
57
- * guidance their model ever receives; the 2026-09-10 field test showed the
57
+ * guidance their model ever receives; a field test showed the
58
58
  * memory going entirely unused without it. Compact by construction (same
59
59
  * ~120-token budget as the identity sibling) and shares the two policy
60
60
  * sentences verbatim — one source, two surfaces. Drops the hook-only