@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
@@ -1,40 +1,54 @@
1
1
  "use strict";
2
2
  /**
3
- * `hicortex backfill-privacy` (#332) — one-shot classification stamping for
4
- * EXISTING rows, by source agent, and (#609) by workspace path.
3
+ * `hicortex backfill-spaces` (#642 AC-14; the #332 `backfill-privacy` command
4
+ * generalized — the old name stays a hidden alias via resolveCommandAlias) —
5
+ * one-shot space stamping for EXISTING rows, by member roster and workspace
6
+ * path, PER SPACE.
5
7
  *
6
8
  * The intake derivation stamps every NEW delivery; this command heals history
7
- * when the roster or the path patterns change (an agent joins the circle, a
8
- * folder is listed, or the feature lands on a store that already has captures
9
- * from a now-covered birthplace). The plan is a pure function of the config ×
10
- * the rows' stored values:
11
- * - every memories/distill_queue row whose source_agent matches the roster
12
- * (isConfidentialSourceAgent — the same `<harness>/`-stripping matcher the
13
- * intake uses) AND whose privacy != 'confidential' → stamped confidential;
14
- * - #609: every row whose stored `workspace_path` matches a
15
- * `confidentialPaths` pattern (the same pure matcher the intake uses),
16
- * grouped per pattern. NULL-path rows are NEVER path-matched (pre-v28
17
- * rows have no path by construction; they are reported as unmatched, not
18
- * silently stamped). A row matching both a rostered agent and a pattern
19
- * flips once (agent groups claim it first; each remaining row joins its
20
- * first matching pattern so overlapping patterns never double-count);
21
- * - NOTHING is ever stamped BACK to standard (a roster/pattern removal is
22
- * not a demotion — memories stay confidential until the operator
9
+ * when a space's members or paths change (an agent joins a space, a folder
10
+ * tree is listed, or the feature lands on a store that already has captures
11
+ * from a now-covered birthplace). The plan is a pure function of the resolved
12
+ * spaces × the rows' stored values:
13
+ * - every memories/distill_queue row whose source_agent matches a space's
14
+ * members (isConfidentialSourceAgent — the same `<harness>/`-stripping
15
+ * matcher the intake uses) AND is still shared → stamped with that
16
+ * space's id, grouped per (space, stored source_agent);
17
+ * - every row whose stored `workspace_path` matches a space's path pattern
18
+ * (matchesConfidentialPath — the same pure matcher the intake uses),
19
+ * grouped per (space, pattern). NULL-path rows are NEVER path-matched
20
+ * (pre-v28 rows have no path by construction; they are reported as
21
+ * unmatched, not silently stamped);
22
+ * - CANDIDATES are ONLY rows with `privacy IS NULL OR privacy = 'standard'`
23
+ * — an already-stamped row NEVER moves (no demotion, no space→space);
24
+ * today's `!= 'confidential'` was the N=1 equivalent of this rule;
25
+ * - claim order: agent groups first (spaces in config order), then path
26
+ * groups (spaces in config order, patterns in entry order) — the FIRST
27
+ * matching space in config order claims a row (single flip, never
28
+ * double-counted);
29
+ * - NOTHING is ever stamped BACK to standard (a members/pattern removal is
30
+ * not a demotion — memories stay in their space until the operator
23
31
  * explicitly changes them; re-running with a smaller config is a no-op by
24
32
  * design).
25
33
  *
34
+ * A pure-legacy config (confidentialAgents/confidentialPaths, no `spaces`
35
+ * key) resolves to the MATERIALIZED confidential space — byte-identical
36
+ * legacy behavior: the same groups, the same 'confidential' stamps, the same
37
+ * report fields (roster/patterns stay the confidential space's).
38
+ *
26
39
  * Safety rails (the `hicortex dedup` / `reconcile-projects` pattern): dry run
27
40
  * by default (report only, zero writes); `--apply` takes a pre-apply DB
28
41
  * backup (abort all writes on failure), the single-flight capture lock
29
- * (waitMs 0 — busy aborts), and stamps in ONE transaction. The queue rows are
30
- * stamped too: a pre-upgrade queued segment from a covered birthplace would
31
- * otherwise distill as standard (migration v27 normalized it) — the backfill
32
- * closes that seam.
42
+ * (waitMs 0 — busy aborts), and stamps in ONE transaction, with the space id
43
+ * PARAMETERIZED (never interpolated into SQL). The queue rows are stamped
44
+ * too: a pre-upgrade queued segment from a covered birthplace would
45
+ * otherwise distill as standard — the backfill closes that seam.
33
46
  *
34
47
  * Idempotent by construction: a second run finds every covered row already
35
- * confidential and reports zero.
48
+ * stamped and reports zero.
36
49
  */
37
50
  Object.defineProperty(exports, "__esModule", { value: true });
51
+ exports.runBackfillSpaces = void 0;
38
52
  exports.planBackfill = planBackfill;
39
53
  exports.runBackfillPrivacy = runBackfillPrivacy;
40
54
  const paths_js_1 = require("./paths.js");
@@ -44,6 +58,8 @@ const db_js_1 = require("./db.js");
44
58
  const capture_js_1 = require("./capture.js");
45
59
  const dedup_js_1 = require("./dedup.js");
46
60
  const classification_js_1 = require("./classification.js");
61
+ const spaces_js_1 = require("./spaces.js");
62
+ const prompts_js_1 = require("./prompts.js");
47
63
  const HICORTEX_HOME = (0, paths_js_1.hicortexHome)();
48
64
  function readConfig(stateDir) {
49
65
  try {
@@ -63,164 +79,236 @@ function readSourceAgents(db, table) {
63
79
  return new Map(rows.map((r) => [r.agent, r.c]));
64
80
  }
65
81
  /**
66
- * The pure plan: which stored source_agent values match the roster, and how
67
- * many of their rows are not yet confidential. Roster matching uses the
82
+ * The pre-#642 call shape — planBackfill(db, roster, patterns) — delegating
83
+ * to the generalized core with the roster+patterns materialized as the
84
+ * reserved confidential space (exactly what resolveSpaces does for a legacy
85
+ * config). The OLD tests pin this overload; it must keep answering the same
86
+ * groups (now carrying space: 'confidential').
87
+ */
88
+ function legacyConfidentialSpace(roster, patterns) {
89
+ return {
90
+ id: "confidential",
91
+ members: roster,
92
+ paths: patterns,
93
+ llm: null,
94
+ privacyLine: prompts_js_1.REFLECTION_PRIVACY_LINE_CONFIDENTIAL,
95
+ };
96
+ }
97
+ /** Discriminate the two planBackfill argument forms (string[] roster vs
98
+ * SpaceDef[]). A non-empty patterns argument means the LEGACY roster form
99
+ * (SpaceDef callers pass everything in arg 2); an empty first arg with no
100
+ * patterns is legacy-empty (and plans nothing as either shape); otherwise
101
+ * the first element's shape decides. */
102
+ function isSpaceDefList(v, patterns) {
103
+ if (patterns.length > 0)
104
+ return false;
105
+ if (v.length === 0)
106
+ return false;
107
+ return typeof v[0] === "object" && v[0] !== null && "id" in v[0];
108
+ }
109
+ /**
110
+ * The pure plan. #642 AC-14: `planBackfill(db, resolveSpaces(config).spaces)`
111
+ * plans per-space groups; the legacy `planBackfill(db, roster, patterns)`
112
+ * form delegates with the confidential space. Roster matching uses the
68
113
  * INTAKE matcher (isConfidentialSourceAgent — `<harness>/`-stripping) so the
69
- * backfill and the intake can never disagree about who is rostered. #609 adds
70
- * the per-pattern groups (see planPathGroups) alongside the agent groups —
71
- * same rails, same never-demotes rule.
114
+ * backfill and the intake can never disagree about who is a member; path
115
+ * matching uses the intake's pure matcher over the stored workspace_path.
116
+ * Candidates are ONLY still-shared rows (privacy IS NULL OR 'standard') — an
117
+ * already-stamped row never moves.
72
118
  */
73
- function planBackfill(db, roster, patterns = []) {
119
+ function planBackfill(db, rosterOrSpaces, patterns = []) {
120
+ const spaces = isSpaceDefList(rosterOrSpaces, patterns)
121
+ ? rosterOrSpaces
122
+ : [legacyConfidentialSpace(rosterOrSpaces, patterns)];
123
+ return planSpaceBackfill(db, spaces);
124
+ }
125
+ /** The generalized core: per-space agent groups (config order, first space
126
+ * claims) then per-space path groups. Shared rows only — never demotes. */
127
+ function planSpaceBackfill(db, spaces) {
74
128
  const memoryAgents = readSourceAgents(db, "memories");
75
129
  const queuedAgents = readSourceAgents(db, "distill_queue");
76
- // Row ids the agent groups below claim — the path groups skip them so a row
130
+ // Row ids the agent groups claim — the path groups skip them so a row
77
131
  // covered by BOTH a rostered agent and a pattern flips (and is counted)
78
132
  // exactly once.
79
133
  const agentClaimedMem = new Set();
80
134
  const agentClaimedQueue = new Set();
135
+ const pendingMemIds = db.prepare("SELECT id FROM memories WHERE source_agent = ? AND (privacy IS NULL OR privacy = 'standard')");
136
+ const pendingQueueIds = db.prepare("SELECT id FROM distill_queue WHERE source_agent = ? AND (privacy IS NULL OR privacy = 'standard')");
81
137
  const groups = [];
82
- for (const [agent, memoryRows] of memoryAgents) {
83
- if (!(0, classification_js_1.isConfidentialSourceAgent)(agent, roster))
84
- continue;
85
- const pending = db
86
- .prepare("SELECT COUNT(*) AS c FROM memories WHERE source_agent = ? AND privacy != 'confidential'")
87
- .get(agent).c;
88
- const queued = queuedAgents.has(agent)
89
- ? db
90
- .prepare("SELECT COUNT(*) AS c FROM distill_queue WHERE source_agent = ? AND privacy != 'confidential'")
91
- .get(agent).c
92
- : 0;
93
- if (pending === 0 && queued === 0)
94
- continue;
95
- if (pending > 0) {
96
- for (const r of db
97
- .prepare("SELECT id FROM memories WHERE source_agent = ? AND privacy != 'confidential'")
98
- .all(agent)) {
99
- agentClaimedMem.add(r.id);
100
- }
138
+ // AGENT GROUPS — spaces in CONFIG ORDER (the first space whose members
139
+ // match claims the row), one group per (space, observed source_agent).
140
+ for (const space of spaces) {
141
+ for (const [agent] of memoryAgents) {
142
+ if (!(0, classification_js_1.isConfidentialSourceAgent)(agent, space.members))
143
+ continue;
144
+ const memIds = pendingMemIds.all(agent)
145
+ .map((r) => r.id)
146
+ .filter((id) => !agentClaimedMem.has(id));
147
+ const queueIds = queuedAgents.has(agent)
148
+ ? pendingQueueIds.all(agent)
149
+ .map((r) => r.id)
150
+ .filter((id) => !agentClaimedQueue.has(id))
151
+ : [];
152
+ if (memIds.length === 0 && queueIds.length === 0)
153
+ continue;
154
+ for (const id of memIds)
155
+ agentClaimedMem.add(id);
156
+ for (const id of queueIds)
157
+ agentClaimedQueue.add(id);
158
+ groups.push({
159
+ space: space.id,
160
+ sourceAgent: agent,
161
+ memoryRows: memIds.length,
162
+ queuedRows: queueIds.length,
163
+ });
101
164
  }
102
- if (queued > 0) {
103
- for (const r of db
104
- .prepare("SELECT id FROM distill_queue WHERE source_agent = ? AND privacy != 'confidential'")
105
- .all(agent)) {
106
- agentClaimedQueue.add(r.id);
107
- }
108
- }
109
- groups.push({ sourceAgent: agent, memoryRows: pending, queuedRows: queued });
110
- }
111
- // Queue-only groups (memories already stamped, inbox holds old rows).
112
- for (const agent of queuedAgents.keys()) {
113
- if (memoryAgents.has(agent))
114
- continue;
115
- if (!(0, classification_js_1.isConfidentialSourceAgent)(agent, roster))
116
- continue;
117
- const queued = db
118
- .prepare("SELECT COUNT(*) AS c FROM distill_queue WHERE source_agent = ? AND privacy != 'confidential'")
119
- .get(agent).c;
120
- if (queued > 0) {
121
- groups.push({ sourceAgent: agent, memoryRows: 0, queuedRows: queued });
122
- for (const r of db
123
- .prepare("SELECT id FROM distill_queue WHERE source_agent = ? AND privacy != 'confidential'")
124
- .all(agent)) {
125
- agentClaimedQueue.add(r.id);
126
- }
165
+ // Queue-only groups (memories already stamped, inbox holds old rows).
166
+ for (const agent of queuedAgents.keys()) {
167
+ if (memoryAgents.has(agent))
168
+ continue;
169
+ if (!(0, classification_js_1.isConfidentialSourceAgent)(agent, space.members))
170
+ continue;
171
+ const queueIds = pendingQueueIds.all(agent)
172
+ .map((r) => r.id)
173
+ .filter((id) => !agentClaimedQueue.has(id));
174
+ if (queueIds.length === 0)
175
+ continue;
176
+ for (const id of queueIds)
177
+ agentClaimedQueue.add(id);
178
+ groups.push({ space: space.id, sourceAgent: agent, memoryRows: 0, queuedRows: queueIds.length });
127
179
  }
128
180
  }
129
- groups.push(...planPathGroups(db, patterns, agentClaimedMem, agentClaimedQueue));
181
+ groups.push(...planPathGroups(db, spaces, agentClaimedMem, agentClaimedQueue));
130
182
  groups.sort((a, b) => b.memoryRows - a.memoryRows || a.sourceAgent.localeCompare(b.sourceAgent));
131
183
  return groups;
132
184
  }
133
185
  /**
134
- * #609: the per-PATTERN stamp groups. Rows whose STORED `workspace_path`
135
- * matches a configured pattern flip to confidential — matched in JS with the
186
+ * The per-(space, pattern) stamp groups. Rows whose STORED `workspace_path`
187
+ * matches a configured pattern flip to that space — matched in JS with the
136
188
  * same pure matcher the intake uses (SQL cannot express the three forms),
137
- * over the not-yet-confidential rows that carry a path. NULL-path rows are
138
- * never matched (they have no path to match — reported as unmatched, never
189
+ * over the still-shared rows that carry a path. NULL-path rows are never
190
+ * matched (they have no path to match — reported as unmatched, never
139
191
  * silently stamped). Rows already claimed by an agent group are skipped
140
- * (single flip); each remaining row joins its FIRST matching pattern (config
141
- * order) so overlapping patterns never double-count.
192
+ * (single flip); each remaining row joins the FIRST matching (space,
193
+ * pattern) in config order so overlapping patterns never double-count.
142
194
  */
143
- function planPathGroups(db, patterns, agentClaimedMem, agentClaimedQueue) {
144
- if (patterns.length === 0)
195
+ function planPathGroups(db, spaces, agentClaimedMem, agentClaimedQueue) {
196
+ const withPaths = spaces.filter((s) => s.paths.length > 0);
197
+ if (withPaths.length === 0)
145
198
  return [];
146
- const claims = patterns.map(() => ({ memIds: [], queueIds: [] }));
199
+ // claims keyed by space id + pattern raw (patterns are deduped per space at
200
+ // resolution, so the pair is unique).
201
+ const claims = new Map();
202
+ const claimFor = (space, pattern) => {
203
+ const key = `${space.id}\u0000${pattern.raw}`;
204
+ let c = claims.get(key);
205
+ if (!c) {
206
+ c = { space, pattern, memIds: [], queueIds: [] };
207
+ claims.set(key, c);
208
+ }
209
+ return c;
210
+ };
147
211
  const memRows = db
148
- .prepare("SELECT id, workspace_path FROM memories WHERE privacy != 'confidential' AND workspace_path IS NOT NULL")
212
+ .prepare("SELECT id, workspace_path FROM memories WHERE (privacy IS NULL OR privacy = 'standard') AND workspace_path IS NOT NULL")
149
213
  .all();
150
214
  for (const row of memRows) {
151
215
  if (agentClaimedMem.has(row.id))
152
216
  continue;
153
- for (let p = 0; p < patterns.length; p++) {
154
- if ((0, classification_js_1.matchesConfidentialPath)(row.workspace_path, [patterns[p]])) {
155
- claims[p].memIds.push(row.id);
156
- break;
217
+ for (const space of withPaths) {
218
+ let claimed = false;
219
+ for (const pattern of space.paths) {
220
+ if ((0, classification_js_1.matchesConfidentialPath)(row.workspace_path, [pattern])) {
221
+ claimFor(space, pattern).memIds.push(row.id);
222
+ claimed = true;
223
+ break;
224
+ }
157
225
  }
226
+ if (claimed)
227
+ break;
158
228
  }
159
229
  }
160
230
  const queueRows = db
161
- .prepare("SELECT id, workspace_path FROM distill_queue WHERE privacy != 'confidential' AND workspace_path IS NOT NULL")
231
+ .prepare("SELECT id, workspace_path FROM distill_queue WHERE (privacy IS NULL OR privacy = 'standard') AND workspace_path IS NOT NULL")
162
232
  .all();
163
233
  for (const row of queueRows) {
164
234
  if (agentClaimedQueue.has(row.id))
165
235
  continue;
166
- for (let p = 0; p < patterns.length; p++) {
167
- if ((0, classification_js_1.matchesConfidentialPath)(row.workspace_path, [patterns[p]])) {
168
- claims[p].queueIds.push(row.id);
169
- break;
236
+ for (const space of withPaths) {
237
+ let claimed = false;
238
+ for (const pattern of space.paths) {
239
+ if ((0, classification_js_1.matchesConfidentialPath)(row.workspace_path, [pattern])) {
240
+ claimFor(space, pattern).queueIds.push(row.id);
241
+ claimed = true;
242
+ break;
243
+ }
170
244
  }
245
+ if (claimed)
246
+ break;
171
247
  }
172
248
  }
249
+ // Emit in (space config order, pattern entry order) — the deterministic
250
+ // claim order, before the caller's count sort.
173
251
  const groups = [];
174
- for (let p = 0; p < patterns.length; p++) {
175
- const { memIds, queueIds } = claims[p];
176
- if (memIds.length === 0 && queueIds.length === 0)
177
- continue;
178
- groups.push({
179
- // Display label: the pattern's raw config entry.
180
- sourceAgent: patterns[p].raw,
181
- pattern: patterns[p],
182
- memoryRows: memIds.length,
183
- queuedRows: queueIds.length,
184
- memoryIds: memIds,
185
- queuedIds: queueIds,
186
- });
252
+ for (const space of withPaths) {
253
+ for (const pattern of space.paths) {
254
+ const c = claims.get(`${space.id}\u0000${pattern.raw}`);
255
+ if (!c || (c.memIds.length === 0 && c.queueIds.length === 0))
256
+ continue;
257
+ groups.push({
258
+ space: space.id,
259
+ // Display label: the pattern's raw config entry.
260
+ sourceAgent: pattern.raw,
261
+ pattern,
262
+ memoryRows: c.memIds.length,
263
+ queuedRows: c.queueIds.length,
264
+ memoryIds: c.memIds,
265
+ queuedIds: c.queueIds,
266
+ });
267
+ }
187
268
  }
188
269
  return groups;
189
270
  }
190
271
  /**
191
- * Run `hicortex backfill-privacy`. Dry run by default (options.apply falsy) —
192
- * plan + report only, zero writes. `options.apply` executes: backup, capture
193
- * lock, ONE transaction stamping every planned row in BOTH tables. A busy
194
- * lock is an abort (reported as `lockBusy: true`, never a wait); a failed
195
- * backup aborts all writes (throw, like dedup/reconcile-projects).
272
+ * Run `hicortex backfill-spaces` (alias `backfill-privacy`). Dry run by
273
+ * default (options.apply falsy) — plan + report only, zero writes.
274
+ * `options.apply` executes: backup, capture lock, ONE transaction stamping
275
+ * every planned row in BOTH tables with its group's space id (parameterized
276
+ * SQL). A busy lock is an abort (reported as `lockBusy: true`, never a
277
+ * wait); a failed backup aborts all writes (throw, like
278
+ * dedup/reconcile-projects).
196
279
  */
197
280
  async function runBackfillPrivacy(options = {}) {
198
281
  const stateDir = options.stateDir ?? HICORTEX_HOME;
199
282
  const config = options.config !== undefined ? options.config : readConfig(stateDir);
200
- // The roster AND the path patterns come from the SAME resolutions the
201
- // server uses at boot (resolveConfidentialAgents / resolveConfidentialPaths)
202
- // — one config shape, one matcher, so the backfill can never disagree with
203
- // the intake about what is covered.
204
- const roster = (0, classification_js_1.resolveConfidentialAgents)(config).roster;
205
- const patterns = (0, classification_js_1.resolveConfidentialPaths)(config).patterns;
283
+ // The spaces come from the SAME resolution the server uses at boot
284
+ // (resolveSpaces) — one config shape, one matcher, so the backfill can
285
+ // never disagree with the intake about what is covered. A pure-legacy
286
+ // config materializes the confidential space here: byte-identical legacy
287
+ // behavior (same groups, same 'confidential' stamps, same report fields).
288
+ const resolved = (0, spaces_js_1.resolveSpaces)(config);
289
+ const spaces = resolved.spaces;
290
+ const conf = resolved.byId.get("confidential");
291
+ const roster = conf ? conf.members : [];
292
+ const patterns = conf ? conf.paths : [];
206
293
  // Server-mode only — client installs have no local DB.
207
294
  if (config?.mode === "client") {
208
- throw new Error("[hicortex] backfill-privacy is server-mode only (it needs the local DB). " +
209
- `This machine is a client of ${config.serverUrl ?? "a remote server"} — run backfill-privacy on the server.`);
295
+ throw new Error("[hicortex] backfill-spaces (alias backfill-privacy) is server-mode only (it needs the local DB). " +
296
+ `This machine is a client of ${config.serverUrl ?? "a remote server"} — run backfill-spaces on the server.`);
210
297
  }
211
298
  const apply = options.apply ?? false;
212
299
  const dbPath = (0, db_js_1.resolveDbPath)(options.dbPath);
213
300
  const db = (0, db_js_1.initDb)(dbPath);
214
301
  try {
215
- console.log(`[hicortex] backfill-privacy starting (${apply ? "APPLY" : "dry-run"}): db ${dbPath}, ` +
216
- `${roster.length} rostered agent(s)${roster.length > 0 ? ` (${roster.join(", ")})` : ""}` +
217
- `, ${patterns.length} path pattern(s)${patterns.length > 0 ? ` (${patterns.map((p) => p.raw).join(", ")})` : ""}`);
218
- if (roster.length === 0 && patterns.length === 0) {
219
- console.log("[hicortex] backfill-privacy: no confidentialAgents or confidentialPaths configured — nothing to stamp. " +
220
- "Add agent ids to config.json confidentialAgents and/or path patterns to confidentialPaths first.");
302
+ console.log(`[hicortex] backfill-spaces starting (${apply ? "APPLY" : "dry-run"}): db ${dbPath}, ` +
303
+ `${spaces.length} space(s)${spaces.length > 0 ? ` (${spaces.map((s) => s.id).join(", ")})` : ""}` +
304
+ (conf ? ` · confidential roster (${roster.length})${roster.length > 0 ? ` ${roster.join(", ")}` : ""}, ${patterns.length} path pattern(s)` : ""));
305
+ if (spaces.length === 0) {
306
+ console.log("[hicortex] backfill-spaces: no spaces configured — nothing to stamp. Add a spaces map " +
307
+ "(space id → { members, paths, optional llm }) to config.json, or the legacy confidentialAgents/" +
308
+ "confidentialPaths keys, then re-run.");
221
309
  return { dryRun: !apply, roster, patterns: [], groups: [], totalMemories: 0, totalQueued: 0 };
222
310
  }
223
- const groups = planBackfill(db, roster, patterns);
311
+ const groups = planBackfill(db, spaces);
224
312
  const totalMemories = groups.reduce((s, g) => s + g.memoryRows, 0);
225
313
  const totalQueued = groups.reduce((s, g) => s + g.queuedRows, 0);
226
314
  const report = {
@@ -231,12 +319,12 @@ async function runBackfillPrivacy(options = {}) {
231
319
  totalMemories,
232
320
  totalQueued,
233
321
  };
234
- console.log(`[hicortex] backfill-privacy: ${groups.length} group(s) match the config, ` +
322
+ console.log(`[hicortex] backfill-spaces: ${groups.length} group(s) match the config, ` +
235
323
  `${totalMemories} memory row(s)${totalQueued > 0 ? `, ${totalQueued} queued row(s)` : ""} ` +
236
- `→ confidential (${apply ? "applying" : "dry run — zero writes"})`);
324
+ `→ their spaces (${apply ? "applying" : "dry run — zero writes"})`);
237
325
  for (const g of groups) {
238
326
  const label = g.pattern ? `pattern ${g.pattern.raw}` : g.sourceAgent;
239
- console.log(`[hicortex] ${label}: ${g.memoryRows} memory row(s)${g.queuedRows > 0 ? `, ${g.queuedRows} queued` : ""}`);
327
+ console.log(`[hicortex] space '${g.space}' · ${label}: ${g.memoryRows} memory row(s)${g.queuedRows > 0 ? `, ${g.queuedRows} queued` : ""}`);
240
328
  }
241
329
  if (!apply)
242
330
  return report;
@@ -247,7 +335,7 @@ async function runBackfillPrivacy(options = {}) {
247
335
  const acquireLock = options.acquireLock ?? capture_js_1.acquireCaptureLock;
248
336
  const releaseLock = await acquireLock(stateDir, 0);
249
337
  if (!releaseLock) {
250
- console.error("[hicortex] backfill-privacy --apply aborted: another capture/nightly run holds the lock. Retry when it finishes.");
338
+ console.error("[hicortex] backfill-spaces --apply aborted: another capture/nightly run holds the lock. Retry when it finishes.");
251
339
  report.lockBusy = true;
252
340
  return report;
253
341
  }
@@ -258,40 +346,41 @@ async function runBackfillPrivacy(options = {}) {
258
346
  backupPath = await (0, dedup_js_1.takePreDedupBackup)(db, stateDir, config);
259
347
  }
260
348
  catch (err) {
261
- throw new Error(`[hicortex] backfill-privacy --apply aborted: backup failed (${err instanceof Error ? err.message : String(err)}). No stamps attempted.`);
349
+ throw new Error(`[hicortex] backfill-spaces --apply aborted: backup failed (${err instanceof Error ? err.message : String(err)}). No stamps attempted.`);
262
350
  }
263
351
  console.log(`[hicortex] Backup written: ${backupPath}`);
264
352
  report.backupPath = backupPath;
265
353
  // ONE transaction: every group's memory + queue stamps commit together
266
- // (the plan is order-independent — pure predicates). Agent groups stamp
267
- // by source_agent; #609 path groups stamp by exact row id (the JS-side
268
- // matcher planned them — SQL cannot express the pattern forms).
269
- const stampMem = db.prepare("UPDATE memories SET privacy = 'confidential' WHERE source_agent = ? AND privacy != 'confidential'");
270
- const stampQueue = db.prepare("UPDATE distill_queue SET privacy = 'confidential' WHERE source_agent = ? AND privacy != 'confidential'");
271
- const stampMemById = db.prepare("UPDATE memories SET privacy = 'confidential' WHERE id = ? AND privacy != 'confidential'");
272
- const stampQueueById = db.prepare("UPDATE distill_queue SET privacy = 'confidential' WHERE id = ? AND privacy != 'confidential'");
354
+ // (the plan is order-independent — pure predicates). The space id is a
355
+ // SQL PARAMETER everywhere (never interpolated). Agent groups stamp by
356
+ // source_agent; path groups stamp by exact row id (the JS-side matcher
357
+ // planned them — SQL cannot express the pattern forms).
358
+ const stampMem = db.prepare("UPDATE memories SET privacy = ? WHERE source_agent = ? AND (privacy IS NULL OR privacy = 'standard')");
359
+ const stampQueue = db.prepare("UPDATE distill_queue SET privacy = ? WHERE source_agent = ? AND (privacy IS NULL OR privacy = 'standard')");
360
+ const stampMemById = db.prepare("UPDATE memories SET privacy = ? WHERE id = ? AND (privacy IS NULL OR privacy = 'standard')");
361
+ const stampQueueById = db.prepare("UPDATE distill_queue SET privacy = ? WHERE id = ? AND (privacy IS NULL OR privacy = 'standard')");
273
362
  const applied = db.transaction(() => {
274
363
  let memories = 0;
275
364
  let queued = 0;
276
365
  for (const g of groups) {
277
366
  if (g.pattern) {
278
367
  for (const id of g.memoryIds ?? [])
279
- memories += stampMemById.run(id).changes;
368
+ memories += stampMemById.run(g.space, id).changes;
280
369
  for (const id of g.queuedIds ?? [])
281
- queued += stampQueueById.run(id).changes;
370
+ queued += stampQueueById.run(g.space, id).changes;
282
371
  }
283
372
  else {
284
- memories += stampMem.run(g.sourceAgent).changes;
285
- queued += stampQueue.run(g.sourceAgent).changes;
373
+ memories += stampMem.run(g.space, g.sourceAgent).changes;
374
+ queued += stampQueue.run(g.space, g.sourceAgent).changes;
286
375
  }
287
376
  }
288
377
  return { memories, queued };
289
378
  })();
290
379
  report.appliedMemories = applied.memories;
291
380
  report.appliedQueued = applied.queued;
292
- console.log(`[hicortex] backfill-privacy complete: ${applied.memories} memory row(s) stamped confidential` +
381
+ console.log(`[hicortex] backfill-spaces complete: ${applied.memories} memory row(s) stamped` +
293
382
  (applied.queued > 0 ? `, ${applied.queued} queued row(s)` : "") +
294
- " (nothing is ever stamped back to standard — a roster/pattern removal is not a demotion)");
383
+ " (nothing is ever stamped back to standard — a members/pattern removal is not a demotion)");
295
384
  return report;
296
385
  }
297
386
  finally {
@@ -302,3 +391,5 @@ async function runBackfillPrivacy(options = {}) {
302
391
  db.close();
303
392
  }
304
393
  }
394
+ /** #642: the canonical command name — same runner, clearer export. */
395
+ exports.runBackfillSpaces = runBackfillPrivacy;