@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
package/dist/cli.js CHANGED
@@ -337,6 +337,58 @@ switch (command) {
337
337
  });
338
338
  break;
339
339
  }
340
+ case "backfill-privacy": {
341
+ // One-shot classification stamping for EXISTING rows, by source agent
342
+ // (#332): every row whose source_agent matches the confidentialAgents
343
+ // roster flips to confidential. Mirrors `dedup`/`reconcile-projects`:
344
+ // dry-run default, --apply explicit (backup + capture lock + ONE
345
+ // transaction); flags parsed here, the runner lives in
346
+ // backfill-privacy.ts so this switch stays thin.
347
+ const args = process.argv.slice(3);
348
+ let dbPath;
349
+ try {
350
+ dbPath = (0, cli_args_js_1.readValueFlag)(args, "--db");
351
+ }
352
+ catch {
353
+ console.error("[hicortex] backfill-privacy: --db requires a path value");
354
+ process.exit(1);
355
+ }
356
+ const backfillOptions = { apply: args.includes("--apply"), dbPath };
357
+ import("./backfill-privacy.js").then(({ runBackfillPrivacy }) => {
358
+ runBackfillPrivacy(backfillOptions).catch((err) => {
359
+ console.error(err instanceof Error ? err.message : `[hicortex] backfill-privacy failed: ${err}`);
360
+ process.exit(1);
361
+ });
362
+ });
363
+ break;
364
+ }
365
+ case "confidential": {
366
+ // #609: mark/unmark a workspace folder confidential via the local
367
+ // .hicortex-confidential marker file; the nightly's marker walk reads the
368
+ // file at the next capture. #616: the marker key is provisioned in ONE
369
+ // command — no local key → fetch it from the server (or generate +
370
+ // register one there); --key <value> rotates (PUTs the new value).
371
+ // Precedent: backfill-privacy (thin switch, runner in its own module).
372
+ const args = process.argv.slice(3);
373
+ const off = args.includes("--off");
374
+ let key;
375
+ try {
376
+ key = (0, cli_args_js_1.readValueFlag)(args, "--key");
377
+ }
378
+ catch {
379
+ console.error("[hicortex] confidential: --key requires a value");
380
+ process.exit(1);
381
+ }
382
+ // Positional path: the first bare arg that is not a --key value pair.
383
+ const pathArg = args.find((a, i) => !a.startsWith("-") && args[i - 1] !== "--key");
384
+ import("./confidential-marker.js").then(({ runConfidentialCommand }) => {
385
+ runConfidentialCommand({ path: pathArg, off, key }).catch((err) => {
386
+ console.error(err instanceof Error ? err.message : `[hicortex] confidential failed: ${err}`);
387
+ process.exit(1);
388
+ });
389
+ });
390
+ break;
391
+ }
340
392
  case "sweep-volatile": {
341
393
  // One-shot store sweep of volatile GH-status/version rows (#489,
342
394
  // deliverable iii): reuses the distill path's deterministic gate over the
@@ -500,6 +552,13 @@ Commands:
500
552
  relink Resumable link-discovery pass over the ENTIRE corpus (server mode)
501
553
  dedup Cluster + merge near-duplicate memories (server mode; dry run by default)
502
554
  reconcile-projects Canonicalize existing project labels (server mode; dry run by default)
555
+ backfill-privacy Stamp history confidential by source agent (#332; server mode;
556
+ dry run by default — --apply executes: backup + capture lock + stamp)
557
+ confidential Mark a workspace folder confidential via a local marker file
558
+ (#616: the marker carries the server's confidentialMarkerKey,
559
+ provisioned by this very command — fetched from the server,
560
+ or generated + registered there on first use; --key <value>
561
+ rotates); confidential [path] writes, --off [path] removes
503
562
  history Show a memory's rewrite history, or roll one back (server mode)
504
563
  history <id> List rewrite events (read-only)
505
564
  history --rollback <row> Undo one rewrite + un-absorb its triggers
@@ -538,6 +597,27 @@ Options:
538
597
  reconcile-projects --apply Execute the project renames (default: dry run, report only)
539
598
  Backup first; renames memories + distill_queue only
540
599
  reconcile-projects --db <path> DB path override (defaults to the configured DB)
600
+ backfill-privacy --apply Execute the stamps (default: dry run, report only)
601
+ Backup + capture lock first; stamps memories + distill_queue;
602
+ never stamps back to standard (a roster removal is not a demotion)
603
+ #609: also plans/stamps per confidentialPaths pattern (rows' stored
604
+ workspace_path); NULL-path rows are never matched
605
+ backfill-privacy --db <path> DB path override (defaults to the configured DB)
606
+ confidential [path] Mark a folder confidential — writes .hicortex-confidential carrying
607
+ the server's confidentialMarkerKey at its root (default path: cwd).
608
+ ONE command, no manual key mirroring (#616): no local key → fetch
609
+ the server's, or generate + register one there on first use; the
610
+ fetched/generated key is saved into ~/.hicortex/config.json for
611
+ offline reuse. An env (HICORTEX_CONFIDENTIAL_MARKER_KEY) or config
612
+ key already on this machine is used as-is, no server contact.
613
+ Refuses when no key exists AND no server is reachable (an
614
+ unvalidated marker would be inert). A marked parent covers child
615
+ workspaces; unmarking never demotes already-captured memories
616
+ confidential --key <v> [path] ROTATION: register <v> as the server's confidentialMarkerKey
617
+ (PUT), save it locally, write the marker — markers carrying a
618
+ previous key then stamp standard. The server refuses (409) while
619
+ its HICORTEX_CONFIDENTIAL_MARKER_KEY env override is set
620
+ confidential --off [path] Remove the marker (succeeds when absent; no key needed, no network)
541
621
  history --rollback <row> Roll back history row <row>: restores prior content/status, un-absorbs triggers
542
622
  history --db <path> DB path override (defaults to the configured DB)
543
623
  backup --out <dir> Write the artifact into <dir> as hicortex-<ISO>.tar.gz (default: <home>/backups)
package/dist/cluster.d.ts CHANGED
@@ -25,12 +25,16 @@ export declare class UnionFind {
25
25
  export declare function clusterEdges(edges: Edge[], threshold: number): string[][];
26
26
  /** Excess = sum(cluster size − 1) — rows that would disappear if every cluster merged to one. */
27
27
  export declare function clusterExcess(clusters: string[][]): number;
28
- /** Metadata row shape for the merge-safety check. `privacy` and `source_agent`
29
- * are on the row (the columns still exist) but are NOT merge-safety fields:
30
- * privacy is vestigial since 0.16.2, and the agent rail was REMOVED by owner
31
- * decision (#206 decision 2, 2026-09-21) — cross-agent clusters merge, because
32
- * attribution survives on the retained absorbed-loser row and no recall path
33
- * filters by source_agent. Project is the only rail. */
28
+ /** Metadata row shape for the merge-safety check. `source_agent` is on the
29
+ * row (the column still exists) but is NOT a merge-safety field: the agent
30
+ * rail was REMOVED by owner decision (#206 decision 2, 2026-09-21) —
31
+ * cross-agent clusters merge, because attribution survives on the retained
32
+ * absorbed-loser row and no recall path filters by source_agent. Project is
33
+ * one rail; `privacy` (the #332 classification, standard | confidential) is
34
+ * the other — a cluster mixing classes is NEVER blended (the confidential
35
+ * pool must not absorb standard rows into hidden view, nor leak
36
+ * confidential content onto a standard canonical). This re-adds a
37
+ * classification-shaped rail #206 removed when the column was vestigial. */
34
38
  export interface ClusterMetaRow {
35
39
  project: string | null;
36
40
  privacy: string | null;
@@ -38,9 +42,12 @@ export interface ClusterMetaRow {
38
42
  }
39
43
  export interface ClusterMetadataMismatch {
40
44
  projectMismatch: boolean;
45
+ /** #332: members disagree on the standard|confidential classification. */
46
+ classificationMismatch: boolean;
41
47
  }
42
- /** Do cluster members disagree on project? (merge-safety input for #100/#206.)
43
- * Privacy and source_agent are intentionally NOT checked — see ClusterMetaRow. */
48
+ /** Do cluster members disagree on project or classification? (merge-safety
49
+ * input for #100/#206 + #332.) source_agent is intentionally NOT checked —
50
+ * see ClusterMetaRow. */
44
51
  export declare function clusterMetadataMismatch(members: ClusterMetaRow[]): ClusterMetadataMismatch;
45
52
  /**
46
53
  * Build the max-cosine edge set via top-K KNN on `memory_vectors`, keeping
package/dist/cluster.js CHANGED
@@ -69,11 +69,18 @@ function clusterEdges(edges, threshold) {
69
69
  function clusterExcess(clusters) {
70
70
  return clusters.reduce((sum, c) => sum + (c.length - 1), 0);
71
71
  }
72
- /** Do cluster members disagree on project? (merge-safety input for #100/#206.)
73
- * Privacy and source_agent are intentionally NOT checked — see ClusterMetaRow. */
72
+ /** Do cluster members disagree on project or classification? (merge-safety
73
+ * input for #100/#206 + #332.) source_agent is intentionally NOT checked —
74
+ * see ClusterMetaRow. */
74
75
  function clusterMetadataMismatch(members) {
75
76
  const projects = new Set(members.map((m) => m.project ?? "\u0000null"));
76
- return { projectMismatch: projects.size > 1 };
77
+ // The classification comparison treats NULL (pre-v27 rows) as 'standard' —
78
+ // the same normalization every read gate applies.
79
+ const classes = new Set(members.map((m) => (m.privacy === "confidential" ? "confidential" : "standard")));
80
+ return {
81
+ projectMismatch: projects.size > 1,
82
+ classificationMismatch: classes.size > 1,
83
+ };
77
84
  }
78
85
  // ---------------------------------------------------------------------------
79
86
  // KNN edge building
@@ -0,0 +1,103 @@
1
+ /**
2
+ * `hicortex confidential [path] [--key <value>|--off]` (#609/#614/#616) —
3
+ * mark or unmark a workspace folder confidential via the local marker file
4
+ * `.hicortex-confidential`.
5
+ *
6
+ * A marker in a PARENT directory covers child workspaces (the capture walk
7
+ * reads every ancestor up to /), and the marker rides folder renames/moves
8
+ * with the directory itself.
9
+ *
10
+ * #614: the marker CARRIES THE KEY. Its single-line content is the server's
11
+ * `confidentialMarkerKey`, validated SERVER-side at intake (an empty or
12
+ * mismatched marker stamps standard — the empty #609 marker was a
13
+ * client-writable classification channel anybody could replicate).
14
+ *
15
+ * #616: getting that key is ONE COMMAND. When this machine holds no key, the
16
+ * command contacts the server it already reports to (server URL + authToken
17
+ * from the local config, the SAME credential every other client call uses —
18
+ * resolveConfig): fetch the key (a second machine reuses the existing one,
19
+ * no second key), or generate `cmark-<32 hex>` and REGISTER it when the
20
+ * server has none, then persist it into `<hicortex-home>/config.json` for
21
+ * offline reuse. Explicit `--key <value>` is ROTATION: it PUTs the chosen
22
+ * value to the server (GET/PUT /confidential/marker-key, #616) before
23
+ * writing, so a deliberate key change propagates from ANY machine. The env
24
+ * (`HICORTEX_CONFIDENTIAL_MARKER_KEY`) and local-config layers stay pure
25
+ * offline fast paths — no server contact. Without any key AND without a
26
+ * reachable server the command REFUSES with instructions — a keyless marker
27
+ * would be inert server-side, and silently writing one would be a no-op
28
+ * disguised as success. `--off` needs no key and makes no network calls
29
+ * (removal is unconditional and never demotes already-captured memories).
30
+ *
31
+ * Future (#613): the content evolves to space-id + key; this writer and the
32
+ * capture reader (readConfidentialMarker) stay content-agnostic — first
33
+ * line, trimmed, relayed verbatim for the server to interpret.
34
+ */
35
+ /**
36
+ * The workspace confidentiality marker's filename (#609): a one-line file at
37
+ * the workspace root, written/removed by this command and read by the
38
+ * nightly's marker walk (readConfidentialMarker in capture.ts — the ONE
39
+ * definition lives here so the writer and the reader can never drift).
40
+ */
41
+ export declare const CONFIDENTIAL_MARKER_FILENAME = ".hicortex-confidential";
42
+ /**
43
+ * #616: the server transport the provisioning flow needs — GET the server's
44
+ * current key (null = none registered yet), PUT a new one (first provisioning
45
+ * or rotation). Injected by tests (the capture.ts `post` seam precedent);
46
+ * production builds it from resolveConfig() + fetch. PUT throws on ANY
47
+ * non-OK answer — a refused registration must never leave a local key or
48
+ * marker behind.
49
+ */
50
+ export interface MarkerKeyTransport {
51
+ get(): Promise<{
52
+ key: string | null;
53
+ }>;
54
+ put(key: string): Promise<void>;
55
+ }
56
+ export interface ConfidentialMarkerOptions {
57
+ /**
58
+ * Target folder. Default: the process cwd (the natural "mark the folder I
59
+ * am in" invocation). Relative paths resolve against the cwd; the command
60
+ * always reports and acts on the ABSOLUTE path.
61
+ */
62
+ path?: string;
63
+ /** Remove the marker instead of writing it. Succeeds when absent. No key, no network. */
64
+ off?: boolean;
65
+ /**
66
+ * Explicit marker key (#616 ROTATION, the CLI `--key` flag): PUT the chosen
67
+ * value to the server, persist it locally, then write the marker. Checked
68
+ * BEFORE env and config — an owner rotating deliberately pushes the new
69
+ * value, not the locally-cached old one.
70
+ */
71
+ key?: string;
72
+ /**
73
+ * #616 test seam: the server transport for the fetch-or-generate flow.
74
+ * Absent → the default transport from resolveConfig() (null when this
75
+ * machine reports to no server → the refusal error).
76
+ */
77
+ transport?: MarkerKeyTransport;
78
+ }
79
+ export interface ConfidentialMarkerResult {
80
+ /** The resolved absolute folder path the command acted on. */
81
+ folder: string;
82
+ /** The marker file's absolute path. */
83
+ markerPath: string;
84
+ /** True when the marker exists after the command ran. */
85
+ marked: boolean;
86
+ }
87
+ /**
88
+ * Write (or remove) the confidential marker. Fails EXPLICITLY when the
89
+ * target folder does not exist — a typo'd path must not silently mark the
90
+ * wrong directory (or nothing). `--off` is deliberately lenient: removing an
91
+ * absent marker is a no-op success (convergent, like the uninstall paths).
92
+ *
93
+ * ASYNC since #616: the key may need a server round-trip (fetch or
94
+ * generate-and-register) when no local layer holds it. The only callers are
95
+ * the cli.ts `confidential` case and tests.
96
+ *
97
+ * Note the classification asymmetry, mirrored in the output: marking takes
98
+ * effect from the NEXT capture (the nightly reads the marker then), and
99
+ * unmarking never demotes — already-captured memories keep their stamp (the
100
+ * #332 never-demotes rule; history heals via `hicortex backfill-privacy`
101
+ * only toward confidential).
102
+ */
103
+ export declare function runConfidentialCommand(opts?: ConfidentialMarkerOptions): Promise<ConfidentialMarkerResult>;
@@ -0,0 +1,285 @@
1
+ "use strict";
2
+ /**
3
+ * `hicortex confidential [path] [--key <value>|--off]` (#609/#614/#616) —
4
+ * mark or unmark a workspace folder confidential via the local marker file
5
+ * `.hicortex-confidential`.
6
+ *
7
+ * A marker in a PARENT directory covers child workspaces (the capture walk
8
+ * reads every ancestor up to /), and the marker rides folder renames/moves
9
+ * with the directory itself.
10
+ *
11
+ * #614: the marker CARRIES THE KEY. Its single-line content is the server's
12
+ * `confidentialMarkerKey`, validated SERVER-side at intake (an empty or
13
+ * mismatched marker stamps standard — the empty #609 marker was a
14
+ * client-writable classification channel anybody could replicate).
15
+ *
16
+ * #616: getting that key is ONE COMMAND. When this machine holds no key, the
17
+ * command contacts the server it already reports to (server URL + authToken
18
+ * from the local config, the SAME credential every other client call uses —
19
+ * resolveConfig): fetch the key (a second machine reuses the existing one,
20
+ * no second key), or generate `cmark-<32 hex>` and REGISTER it when the
21
+ * server has none, then persist it into `<hicortex-home>/config.json` for
22
+ * offline reuse. Explicit `--key <value>` is ROTATION: it PUTs the chosen
23
+ * value to the server (GET/PUT /confidential/marker-key, #616) before
24
+ * writing, so a deliberate key change propagates from ANY machine. The env
25
+ * (`HICORTEX_CONFIDENTIAL_MARKER_KEY`) and local-config layers stay pure
26
+ * offline fast paths — no server contact. Without any key AND without a
27
+ * reachable server the command REFUSES with instructions — a keyless marker
28
+ * would be inert server-side, and silently writing one would be a no-op
29
+ * disguised as success. `--off` needs no key and makes no network calls
30
+ * (removal is unconditional and never demotes already-captured memories).
31
+ *
32
+ * Future (#613): the content evolves to space-id + key; this writer and the
33
+ * capture reader (readConfidentialMarker) stay content-agnostic — first
34
+ * line, trimmed, relayed verbatim for the server to interpret.
35
+ */
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.CONFIDENTIAL_MARKER_FILENAME = void 0;
38
+ exports.runConfidentialCommand = runConfidentialCommand;
39
+ const node_fs_1 = require("node:fs");
40
+ const node_path_1 = require("node:path");
41
+ const node_crypto_1 = require("node:crypto");
42
+ const paths_js_1 = require("./paths.js");
43
+ const init_js_1 = require("./init.js");
44
+ const config_read_js_1 = require("./config-read.js");
45
+ const learnings_identity_js_1 = require("./learnings-identity.js");
46
+ /**
47
+ * The workspace confidentiality marker's filename (#609): a one-line file at
48
+ * the workspace root, written/removed by this command and read by the
49
+ * nightly's marker walk (readConfidentialMarker in capture.ts — the ONE
50
+ * definition lives here so the writer and the reader can never drift).
51
+ */
52
+ exports.CONFIDENTIAL_MARKER_FILENAME = ".hicortex-confidential";
53
+ /**
54
+ * The common refusal (#614/#616): no key is obtainable on this machine. The
55
+ * message names the two fixes — make the server reachable (so the one-command
56
+ * flow works), or set the key manually (env / config) — because either one
57
+ * unblocks the write. Never writes a marker alongside this error.
58
+ */
59
+ function markerKeyRefusal(detail) {
60
+ return new Error(`[hicortex] confidential: ${detail}\n` +
61
+ ` The marker must carry the server's confidentialMarkerKey or the server ignores it (#614).\n` +
62
+ ` Fix: start the Hicortex server this machine reports to (or re-run init so its URL + token\n` +
63
+ ` are in ~/.hicortex/config.json), or set the key manually — export HICORTEX_CONFIDENTIAL_MARKER_KEY\n` +
64
+ ` or add confidentialMarkerKey to ~/.hicortex/config.json — then re-run this command.`);
65
+ }
66
+ /** One timeout for both provisioning calls — a foreground CLI command waits, but not forever. */
67
+ const MARKER_KEY_TIMEOUT_MS = 10000;
68
+ /**
69
+ * The production transport (#616): resolveConfig() — the SAME resolution every
70
+ * other client-side fetch uses (client mode → config.serverUrl, else
71
+ * localhost:port, + authToken) — so the provisioning call and the nightly's
72
+ * capture POST can never disagree about which server owns the key. null when
73
+ * there is no usable config (fresh machine, no init): the caller refuses.
74
+ *
75
+ * Errors carry the DETAIL (URL, status, cause); the fetch-or-generate ladder
76
+ * in resolveMarkerKey wraps GET failures into the refusal that names the fix.
77
+ * PUT failures surface as their own explicit errors (a refused rotation is
78
+ * not a "no key" refusal — the operator chose a key and the server said no).
79
+ */
80
+ function defaultMarkerKeyTransport() {
81
+ const cfg = (0, learnings_identity_js_1.resolveConfig)();
82
+ if (!cfg)
83
+ return null;
84
+ const headers = { "Content-Type": "application/json" };
85
+ if (cfg.authToken)
86
+ headers["Authorization"] = `Bearer ${cfg.authToken}`;
87
+ const url = `${cfg.serverUrl}/confidential/marker-key`;
88
+ return {
89
+ async get() {
90
+ let resp;
91
+ try {
92
+ resp = await fetch(url, { headers, signal: AbortSignal.timeout(MARKER_KEY_TIMEOUT_MS) });
93
+ }
94
+ catch (e) {
95
+ throw new Error(`could not reach ${cfg.serverUrl} (${e instanceof Error ? e.message : String(e)})`);
96
+ }
97
+ if (!resp.ok) {
98
+ throw new Error(`the server at ${cfg.serverUrl} answered ${resp.status} for /confidential/marker-key ` +
99
+ `(check the auth token, or the server version — the endpoint needs #616+)`);
100
+ }
101
+ let body;
102
+ try {
103
+ body = await resp.json();
104
+ }
105
+ catch {
106
+ body = null;
107
+ }
108
+ // Shape-check the one field we consume — anything else is a version
109
+ // mismatch and must not masquerade as "no key" (which would mint a
110
+ // second key and orphan the first machine's markers).
111
+ if (body === null || typeof body !== "object" ||
112
+ !("key" in body) ||
113
+ (body.key !== null && typeof body.key !== "string")) {
114
+ throw new Error(`unexpected response shape from ${url} — is the server up to date (#616+)?`);
115
+ }
116
+ const key = body.key;
117
+ return { key: key === null ? null : key.trim() || null };
118
+ },
119
+ async put(key) {
120
+ let resp;
121
+ try {
122
+ resp = await fetch(url, {
123
+ method: "PUT",
124
+ headers,
125
+ body: JSON.stringify({ key }),
126
+ signal: AbortSignal.timeout(MARKER_KEY_TIMEOUT_MS),
127
+ });
128
+ }
129
+ catch (e) {
130
+ throw new Error(`[hicortex] confidential: could not reach ${cfg.serverUrl} to set the marker key ` +
131
+ `(${e instanceof Error ? e.message : String(e)}) — nothing was written`);
132
+ }
133
+ if (!resp.ok) {
134
+ // Surface the server's refusal VERBATIM (409 env-shadow, 400 shape)
135
+ // — the operator needs the reason, and nothing was written.
136
+ let reason = resp.statusText;
137
+ try {
138
+ const errBody = await resp.json();
139
+ if (errBody && typeof errBody.error === "string")
140
+ reason = errBody.error;
141
+ }
142
+ catch {
143
+ // non-JSON error body — keep statusText
144
+ }
145
+ throw new Error(`[hicortex] confidential: the server refused the marker key (HTTP ${resp.status}): ${reason} — nothing was written`);
146
+ }
147
+ },
148
+ };
149
+ }
150
+ /**
151
+ * Save the key into `<hicortex-home>/config.json` (#616): after a fetch or a
152
+ * generate-and-register, the NEXT run takes the offline fast path (no server
153
+ * needed). persistConfigUpdates is load-strict → merge → save: unrelated keys
154
+ * (authToken, serverUrl, …) survive, and a malformed existing config THROWS
155
+ * instead of being stubbed. On a server box this is the same file the
156
+ * endpoint's PUT just wrote — idempotent.
157
+ */
158
+ function persistLocalMarkerKey(key) {
159
+ (0, init_js_1.persistConfigUpdates)((0, node_path_1.join)((0, paths_js_1.hicortexHome)(), "config.json"), { confidentialMarkerKey: key });
160
+ }
161
+ /**
162
+ * Write (or remove) the confidential marker. Fails EXPLICITLY when the
163
+ * target folder does not exist — a typo'd path must not silently mark the
164
+ * wrong directory (or nothing). `--off` is deliberately lenient: removing an
165
+ * absent marker is a no-op success (convergent, like the uninstall paths).
166
+ *
167
+ * ASYNC since #616: the key may need a server round-trip (fetch or
168
+ * generate-and-register) when no local layer holds it. The only callers are
169
+ * the cli.ts `confidential` case and tests.
170
+ *
171
+ * Note the classification asymmetry, mirrored in the output: marking takes
172
+ * effect from the NEXT capture (the nightly reads the marker then), and
173
+ * unmarking never demotes — already-captured memories keep their stamp (the
174
+ * #332 never-demotes rule; history heals via `hicortex backfill-privacy`
175
+ * only toward confidential).
176
+ */
177
+ async function runConfidentialCommand(opts = {}) {
178
+ const folder = (0, node_path_1.resolve)(opts.path ?? process.cwd());
179
+ let isDir = false;
180
+ try {
181
+ isDir = (0, node_fs_1.statSync)(folder).isDirectory();
182
+ }
183
+ catch {
184
+ // fall through to the explicit error below
185
+ }
186
+ if (!isDir) {
187
+ throw new Error(`[hicortex] confidential: no such directory: ${folder} — pass the workspace folder's path`);
188
+ }
189
+ const markerPath = (0, node_path_1.join)(folder, exports.CONFIDENTIAL_MARKER_FILENAME);
190
+ if (opts.off) {
191
+ try {
192
+ (0, node_fs_1.unlinkSync)(markerPath);
193
+ console.log(`[hicortex] Removed the confidential marker: ${markerPath}`);
194
+ console.log("[hicortex] Already-captured memories keep their classification (nothing is ever demoted).");
195
+ }
196
+ catch {
197
+ console.log(`[hicortex] No confidential marker at ${markerPath} — nothing to remove.`);
198
+ }
199
+ return { folder, markerPath, marked: false };
200
+ }
201
+ // #616 key resolution ladder (each layer documented at its check):
202
+ const key = await resolveMarkerKey(opts);
203
+ // Single line, newline-terminated — exactly the shape the capture walk
204
+ // relays (readConfidentialMarker takes the trimmed first line). The key
205
+ // value is deliberately NOT echoed in the output lines below.
206
+ (0, node_fs_1.writeFileSync)(markerPath, key + "\n");
207
+ console.log(`[hicortex] Marked confidential: ${folder}`);
208
+ console.log("[hicortex] The marker carries this machine's confidentialMarkerKey; the next nightly capture in this");
209
+ console.log("[hicortex] folder (or any child folder) stamps its memories confidential when the server's key matches.");
210
+ console.log("[hicortex] To backfill HISTORY, add the folder to confidentialPaths on the server and run: hicortex backfill-privacy");
211
+ return { folder, markerPath, marked: true };
212
+ }
213
+ /**
214
+ * The #616 key ladder, in order:
215
+ *
216
+ * 1. `opts.key` (CLI `--key`) → ROTATION: PUT the chosen value to the server
217
+ * first (a refused PUT — e.g. 409 under the server's env override —
218
+ * surfaces verbatim and writes nothing), then persist locally.
219
+ * 2. env `HICORTEX_CONFIDENTIAL_MARKER_KEY` → the operator's manual layer:
220
+ * write, no network, no config persist (mirroring it under an explicit
221
+ * override would create drift).
222
+ * 3. local config `confidentialMarkerKey` → the offline fast path (yesterday's
223
+ * provisioning result): write, no network.
224
+ * 4. none of the above → the server: GET /confidential/marker-key. A key →
225
+ * reuse it (AC-2: the second machine never mints a second key). null →
226
+ * generate `cmark-` + 32 hex and PUT it (AC-1: first machine ever). Both
227
+ * branches persist locally for the next run's fast path.
228
+ *
229
+ * A set-but-blank layer is no key at every layer (blank never validates
230
+ * server-side) and the ladder falls through. No transport obtainable (no
231
+ * config at all) or an unreachable server → the refusal error naming the
232
+ * fixes — never an inert marker.
233
+ */
234
+ async function resolveMarkerKey(opts) {
235
+ // 1. Explicit --key = rotation (push to the server, then keep locally).
236
+ const explicit = typeof opts.key === "string" && opts.key.trim() ? opts.key.trim() : null;
237
+ if (explicit) {
238
+ const transport = opts.transport ?? defaultMarkerKeyTransport();
239
+ if (!transport) {
240
+ throw markerKeyRefusal("rotating with --key needs the server (the new value is registered there first) — " +
241
+ "no Hicortex server is configured on this machine");
242
+ }
243
+ await transport.put(explicit); // refusal surfaces verbatim; nothing written
244
+ persistLocalMarkerKey(explicit);
245
+ console.log("[hicortex] Registered the new confidentialMarkerKey with the server — markers carrying a previous");
246
+ console.log("[hicortex] key now stamp standard (re-run this command on machines that marked folders before).");
247
+ return explicit;
248
+ }
249
+ // 2. The env layer — operator-managed, offline, never mirrored into config.
250
+ const env = process.env.HICORTEX_CONFIDENTIAL_MARKER_KEY;
251
+ if (typeof env === "string" && env.trim())
252
+ return env.trim();
253
+ // 3. The local config layer — yesterday's provisioning result, offline.
254
+ // (loadConfigStrict THROWS on a broken config rather than reading "no
255
+ // key" off a file it could not parse — surfaced by the caller.)
256
+ const { config } = (0, init_js_1.loadConfigStrict)((0, node_path_1.join)((0, paths_js_1.hicortexHome)(), "config.json"));
257
+ const local = (0, config_read_js_1.readStringConfig)(config, "confidentialMarkerKey");
258
+ if (local)
259
+ return local;
260
+ // 4. The server: fetch, or generate-and-register.
261
+ const transport = opts.transport ?? defaultMarkerKeyTransport();
262
+ if (!transport) {
263
+ throw markerKeyRefusal("no confidentialMarkerKey on this machine and no Hicortex server configured to fetch one from");
264
+ }
265
+ let got;
266
+ try {
267
+ got = await transport.get();
268
+ }
269
+ catch (e) {
270
+ // Unreachable / refused / bad shape — one refined refusal naming the fix
271
+ // (never an inert marker, and never a raw network error without one).
272
+ throw markerKeyRefusal(e instanceof Error ? e.message : String(e));
273
+ }
274
+ if (got.key) {
275
+ persistLocalMarkerKey(got.key);
276
+ console.log("[hicortex] Using the server's existing confidentialMarkerKey (saved to this machine's config for offline use).");
277
+ return got.key;
278
+ }
279
+ const generated = `cmark-${(0, node_crypto_1.randomBytes)(16).toString("hex")}`; // single line, 32 hex
280
+ await transport.put(generated); // refusal surfaces; nothing written
281
+ persistLocalMarkerKey(generated);
282
+ console.log("[hicortex] Generated a new confidentialMarkerKey and registered it with the server (saved locally).");
283
+ console.log("[hicortex] Other machines running this command now fetch this key instead of generating their own.");
284
+ return generated;
285
+ }
@@ -4,7 +4,7 @@
4
4
  * Ported from hicortex/consolidate/ (stages.py, __init__.py, budget.py).
5
5
  */
6
6
  import type Database from "better-sqlite3";
7
- import type { Memory, ConsolidationReport } from "./types.js";
7
+ import type { Memory, ConsolidationReport, MemoryPrivacy } from "./types.js";
8
8
  import type { LlmClient } from "./llm.js";
9
9
  import type { EmbedFn } from "./retrieval.js";
10
10
  import { type DomainDef } from "./domain-classify.js";
@@ -43,6 +43,17 @@ export declare function resolveNightlyLlmCallBudget(config: Record<string, unkno
43
43
  export declare const CONSOLIDATE_LINK_THRESHOLD = 0.75;
44
44
  /** Max link candidates kept per memory (highest-cosine neighbors first). */
45
45
  export declare const CONSOLIDATE_LINK_TOP_K = 3;
46
+ /**
47
+ * Initial vector window for link-candidate discovery (#602). The fetch is
48
+ * UNFILTERED by class (see CONSOLIDATE_LINK_FETCH_MAX_K for why), so this is
49
+ * just the starting width of the adaptive escalation below.
50
+ */
51
+ export declare const CONSOLIDATE_LINK_FETCH_K = 10;
52
+ /**
53
+ * Hard cap on the escalated vector window (#602) — the same over-fetch cap
54
+ * #192 established for filtered recall queries.
55
+ */
56
+ export declare const CONSOLIDATE_LINK_FETCH_MAX_K = 200;
46
57
  /**
47
58
  * Minimum COSINE similarity for a CROSS-PROJECT link candidate.
48
59
  *
@@ -185,10 +196,30 @@ export declare function scoreMemoriesImportance(db: Database.Database, memories:
185
196
  deadline?: RunDeadline;
186
197
  dryRun?: boolean;
187
198
  onBatch?: (written: number, failed: number) => void;
199
+ /**
200
+ * #332: the confidential-pool client. The batch builder partitions the
201
+ * pool by class FIRST (buildImportanceBatches — batches are single-class
202
+ * by construction), so every LLM call carries one class of text to one
203
+ * client. Confidential batches without a client are SKIPPED (their rows
204
+ * keep importance_scored_at NULL — the watermark pool re-finds them next
205
+ * run; counted in skipped_confidential), never scored on the main model.
206
+ */
207
+ confidentialLlm?: LlmClient | null;
188
208
  }): Promise<{
189
209
  scored: number;
190
210
  failed: number;
191
211
  skipped_budget: number;
212
+ skipped_confidential?: number;
213
+ }>;
214
+ /**
215
+ * #332 — the importance batch builder: partition by classification, then
216
+ * slice into batches. Every batch is SINGLE-CLASS by construction (AC-10),
217
+ * so the scoring call site can route each batch to the client matching its
218
+ * pool with no per-item checks. Exported for the unit test.
219
+ */
220
+ export declare function buildImportanceBatches(memories: Memory[], batchSize?: number): Array<{
221
+ pool: MemoryPrivacy;
222
+ memories: Memory[];
192
223
  }>;
193
224
  /**
194
225
  * Rebuild moduleIndex from the configured domain set + live DB counts, and
@@ -211,9 +242,29 @@ export interface LinkCandidate {
211
242
  }
212
243
  /**
213
244
  * Discovery: find link candidates for one memory given its embedding.
214
- * Top-10 vector neighbors (excluding self), keep the CONSOLIDATE_LINK_TOP_K
215
- * highest-cosine neighbors above CONSOLIDATE_LINK_THRESHOLD, pre-compute the
216
- * heuristic relationship type.
245
+ * Vector neighbors (excluding self), keep the CONSOLIDATE_LINK_TOP_K
246
+ * highest-cosine SAME-CLASS neighbors above CONSOLIDATE_LINK_THRESHOLD,
247
+ * pre-compute the heuristic relationship type.
248
+ *
249
+ * #602 — ADAPTIVE CLASS-SCOPED FETCH. The pre-#602 code fetched a fixed
250
+ * top-10 UNFILTERED window and then dropped cross-class neighbors in the
251
+ * loop — the #192 filtered-over-fetch defect class. Starvation math: in a
252
+ * 22K-standard / 1K-confidential corpus a confidential memory's 10 nearest
253
+ * neighbors are usually ALL standard (the classes are topically distinct but
254
+ * the majority class is 22× larger), so the confidential pool systematically
255
+ * under-linked — its same-class neighbors never made the window. The fix
256
+ * escalates the window (k × 4 per step, capped at CONSOLIDATE_LINK_FETCH_MAX_K
257
+ * = the #192 over-fetch cap) until the window holds CONSOLIDATE_LINK_TOP_K
258
+ * same-class neighbors, comes back short (no more rows may exist), or hits
259
+ * the cap. Balanced corpora do ZERO extra queries (the first window already
260
+ * holds 3+ same-class neighbors).
261
+ *
262
+ * WHY the class is not denormalized into the vec0 table (a WHERE clause
263
+ * would make this a one-fetch query): memory_vectors carries only id +
264
+ * embedding, and privacy is MUTABLE post-insert (`hicortex backfill-privacy`
265
+ * and REST /update can reclassify a row) — a vec0-side class column would go
266
+ * stale the moment a row's class changed without a re-embed. The class is
267
+ * read live from memories, so it can never disagree with the row.
217
268
  *
218
269
  * Shared between the nightly `stageLinks` (which embeds via embedFn) and
219
270
  * `hicortex relink` (which reuses stored embeddings from memory_vectors).
@@ -369,4 +420,13 @@ reconsolidationOptions?: ReconsolidationOptions,
369
420
  * the report status becomes "deferred" — which keeps lastConsolidated
370
421
  * un-advanced so the next run re-finds the pending work.
371
422
  */
372
- deadline?: RunDeadline): Promise<ConsolidationReport>;
423
+ deadline?: RunDeadline,
424
+ /**
425
+ * #332: the CONFIDENTIAL model client. Every stage that can touch
426
+ * confidential text (importance batches, reflection, domain classification,
427
+ * reconsolidation verdicts/rewrites) selects per-pool — confidential work
428
+ * goes here; when null, that work HOLDS/skips, never falls back to `llm`.
429
+ * Optional so every pre-#332 caller (and corpora with no confidential
430
+ * rows) is byte-identical.
431
+ */
432
+ confidentialLlm?: LlmClient | null): Promise<ConsolidationReport>;