@gamaze/hicortex 0.27.4 → 0.29.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 (94) hide show
  1. package/assets/dashboard.html +1898 -3211
  2. package/assets/viz.html +229 -2
  3. package/dist/backfill-privacy.d.ts +68 -45
  4. package/dist/backfill-privacy.js +236 -145
  5. package/dist/calibration.d.ts +67 -68
  6. package/dist/calibration.js +75 -78
  7. package/dist/capture-health.d.ts +2 -2
  8. package/dist/capture-health.js +2 -2
  9. package/dist/classification.d.ts +141 -12
  10. package/dist/classification.js +214 -27
  11. package/dist/classify-domains.d.ts +1 -1
  12. package/dist/classify-domains.js +2 -2
  13. package/dist/cli-args.d.ts +5 -3
  14. package/dist/cli-args.js +7 -3
  15. package/dist/cli.d.ts +2 -0
  16. package/dist/cli.js +64 -16
  17. package/dist/cluster.d.ts +12 -9
  18. package/dist/cluster.js +9 -6
  19. package/dist/consolidate.d.ts +93 -43
  20. package/dist/consolidate.js +255 -119
  21. package/dist/dashboard.d.ts +48 -5
  22. package/dist/dashboard.js +55 -3
  23. package/dist/db.js +27 -6
  24. package/dist/dedup.d.ts +2 -3
  25. package/dist/dedup.js +2 -3
  26. package/dist/distill-queue.d.ts +36 -4
  27. package/dist/distill-queue.js +80 -18
  28. package/dist/distiller.d.ts +1 -1
  29. package/dist/distiller.js +13 -12
  30. package/dist/domain-classify.d.ts +8 -9
  31. package/dist/domain-classify.js +6 -7
  32. package/dist/graph.d.ts +15 -5
  33. package/dist/graph.js +46 -13
  34. package/dist/hermes-transcript-reader.d.ts +1 -1
  35. package/dist/hermes-transcript-reader.js +1 -1
  36. package/dist/init.d.ts +30 -2
  37. package/dist/init.js +48 -3
  38. package/dist/llm.d.ts +1 -1
  39. package/dist/llm.js +5 -5
  40. package/dist/mcp-server.js +323 -59
  41. package/dist/memory-instructions.d.ts +2 -2
  42. package/dist/memory-instructions.js +2 -2
  43. package/dist/nightly.d.ts +1 -1
  44. package/dist/nightly.js +64 -5
  45. package/dist/nofit.d.ts +2 -2
  46. package/dist/nofit.js +2 -2
  47. package/dist/observed-agents.d.ts +54 -0
  48. package/dist/observed-agents.js +78 -0
  49. package/dist/project-canonicalize.d.ts +6 -5
  50. package/dist/project-canonicalize.js +6 -5
  51. package/dist/prompts.d.ts +29 -8
  52. package/dist/prompts.js +39 -16
  53. package/dist/quality-scoreboard.d.ts +1 -1
  54. package/dist/recall-hook-cli.d.ts +1 -1
  55. package/dist/recall-hook-cli.js +2 -2
  56. package/dist/recall-index.d.ts +28 -14
  57. package/dist/recall-index.js +22 -10
  58. package/dist/recall-precision.d.ts +3 -3
  59. package/dist/recall-precision.js +5 -4
  60. package/dist/reconcile-projects.d.ts +2 -2
  61. package/dist/reconcile-projects.js +2 -2
  62. package/dist/reconsolidation.d.ts +9 -2
  63. package/dist/reconsolidation.js +48 -31
  64. package/dist/relink.d.ts +2 -2
  65. package/dist/relink.js +4 -4
  66. package/dist/rescore-importance.d.ts +2 -2
  67. package/dist/rescore-importance.js +22 -3
  68. package/dist/retrieval.d.ts +14 -0
  69. package/dist/retrieval.js +11 -11
  70. package/dist/schema-prototypes.d.ts +1 -1
  71. package/dist/schema-prototypes.js +1 -1
  72. package/dist/seed-lesson.js +4 -2
  73. package/dist/spaces-api.d.ts +104 -0
  74. package/dist/spaces-api.js +193 -0
  75. package/dist/spaces-cli.d.ts +90 -0
  76. package/dist/spaces-cli.js +245 -0
  77. package/dist/spaces.d.ts +187 -0
  78. package/dist/spaces.js +360 -0
  79. package/dist/storage.d.ts +47 -10
  80. package/dist/storage.js +74 -17
  81. package/dist/sweep-volatile.d.ts +2 -2
  82. package/dist/sweep-volatile.js +2 -2
  83. package/dist/telemetry-cli.d.ts +1 -1
  84. package/dist/telemetry-cli.js +1 -1
  85. package/dist/type-classify.d.ts +1 -1
  86. package/dist/type-classify.js +1 -1
  87. package/dist/type-labels.d.ts +1 -1
  88. package/dist/type-labels.js +1 -1
  89. package/dist/types.d.ts +43 -20
  90. package/dist/wrapper-prompt.d.ts +2 -2
  91. package/dist/wrapper-prompt.js +2 -2
  92. package/opencode-plugin/hicortex/index.ts +562 -364
  93. package/package.json +2 -2
  94. package/server.json +2 -2
@@ -177,6 +177,34 @@ export interface DashboardSnapshot {
177
177
  run_at: string;
178
178
  metrics: DashboardMetrics;
179
179
  }
180
+ /**
181
+ * #642 AC-12 — the spaces management view's data: every configured space
182
+ * (resolveSpaces — SKIPPING NOTHING, the confidential space included) with
183
+ * its resolved members and counts, plus the observed-but-unassigned agents
184
+ * (first-prompt discovery, AC-11) that the page offers for one-click
185
+ * assignment. Purely informational block — the page DRIVES the AC-10 admin
186
+ * API for the writes; this payload only paints.
187
+ */
188
+ export interface SpacesFleetBlock {
189
+ /** Config order (resolveSpaces) — the page renders one lane per space. */
190
+ spaces: Array<{
191
+ id: string;
192
+ /** The resolved (sanitized) members list. */
193
+ members: string[];
194
+ /** Rows stamped with this space id (spaceOf-folded GROUP BY). */
195
+ memoryCount: number;
196
+ /** Queued rows stamped with this space id (distill_queue). */
197
+ queuedCount?: number;
198
+ }>;
199
+ /** Observed agents in NO space's members, newest last_seen first (the
200
+ * listObservedAgents order, filtered — the operator sees the freshest
201
+ * unknown workspace first). */
202
+ unassigned: Array<{
203
+ agent: string;
204
+ first_seen: string;
205
+ last_seen: string;
206
+ }>;
207
+ }
180
208
  /**
181
209
  * #601 — the confidential circle's VISIBILITY block: which agents are
182
210
  * confidential-circle and, for the observed ones, how many confidential
@@ -188,7 +216,7 @@ export interface AgentCircle {
188
216
  /** The sanitized roster (resolveConfidentialAgents — the one agent-id
189
217
  * namespace shared with `?agent=` and identityAgents). */
190
218
  roster: string[];
191
- /** OBSERVED source_agent values (e.g. "hermes/atlas") that match the
219
+ /** OBSERVED source_agent values (e.g. "hermes/nova") that match the
192
220
  * roster, each mapped to that agent's confidential memory count.
193
221
  * Membership is KEY PRESENCE (a rostered agent observed with 0
194
222
  * confidential rows is a member at 0); NULL source_agent never matches. */
@@ -249,7 +277,7 @@ export interface DashboardData {
249
277
  * recorded (fresh install / all rows pruned — the page degrades to the
250
278
  * phase-1 counts-only rows).
251
279
  *
252
- * #409 fix round 7 (owner ruling 2026-09-14: "the normal 30 day as the
280
+ * #409 fix round 7 ("the normal 30 day as the
253
281
  * other cards"): `day`/`rows` keep the NEWEST night with rows (secondary
254
282
  * info — the card's "tonight" suffix), while `window_days`/`window_rows`
255
283
  * carry the ROLLING capture window's per machine × agent sums — the card's
@@ -277,6 +305,9 @@ export interface DashboardData {
277
305
  * #601 adds `circle` — the confidential-circle visibility block (roster +
278
306
  * observed members with counts), also always present; the page degrades to
279
307
  * the exact prior rendering when the key is absent (pre-#601 server).
308
+ * #642 (AC-12) adds `spaces` — the management view's data (spaces +
309
+ * members + counts + observed unassigned), ALWAYS present the same way;
310
+ * `circle` STAYS for the page's pre-#642 degrade and the pill helpers.
280
311
  */
281
312
  fleet: {
282
313
  pauses: Array<{
@@ -291,6 +322,7 @@ export interface DashboardData {
291
322
  last_outcome: string;
292
323
  }>;
293
324
  circle: AgentCircle;
325
+ spaces: SpacesFleetBlock;
294
326
  };
295
327
  /**
296
328
  * #476 — the Memory Precision card: Level 1 (pushed-index precision
@@ -508,6 +540,17 @@ export declare function backfillSnapshots(db: Database.Database): number;
508
540
  * Pure: takes a db + config, returns the block; no side effects.
509
541
  */
510
542
  export declare function readAgentCircle(db: Database.Database, config: Record<string, unknown> | null | undefined): AgentCircle;
543
+ /**
544
+ * #642 AC-12 — compute fleet.spaces: every resolved space with its members
545
+ * and its memory/queue counts (SQL GROUP BY privacy folded through spaceOf —
546
+ * NULL/''/'standard' counts under 'standard', the fixed shared pool that is
547
+ * NEVER listed), plus the observed agents that appear in no space's members
548
+ * as unassigned (newest last_seen first — the first-prompt discovery lane).
549
+ * Pure: takes a db + config, returns the block; no side effects. The page
550
+ * hides the management section entirely when the block is absent (an older
551
+ * server) and when there is nothing to show (the zero-change dashboard).
552
+ */
553
+ export declare function readSpacesBlock(db: Database.Database, config: Record<string, unknown> | null | undefined): SpacesFleetBlock;
511
554
  /**
512
555
  * The pure data handler for GET /dashboard/data. Reads query params
513
556
  * (`range`, `date`, `digestLimit`) off the request, returns the DashboardData
@@ -586,7 +629,7 @@ export interface DashboardField {
586
629
  /** The thresholds the stages were derived with, echoed so the page paints
587
630
  * from the same constants the server scored with (calibration.ts is the
588
631
  * single home — the echo is display, not a second source). Recall grades
589
- * are GONE (#426 owner semantics ruling 2026-09-13: recall depends on the
632
+ * are GONE (#426 semantics ruling: recall depends on the
590
633
  * conversation, a graded scale implies a target that does not exist). */
591
634
  thresholds: {
592
635
  stage: {
@@ -601,8 +644,8 @@ export interface DashboardField {
601
644
  * a second source — same rule as the stage bands). Absent nothing: the
602
645
  * key always rides the payload; a pre-polish page ignores it. */
603
646
  recall_min_similarity: number;
604
- /** #426 final ruling 2026-09-13: the console's recall-level band edges
605
- * (RECALL_USES_* — PROVISIONAL, owner anchor 2026-09-13, pending fleet
647
+ /** #426 final ruling: the console's recall-level band edges
648
+ * (RECALL_USES_* — PROVISIONAL anchors, pending fleet
606
649
  * telemetry). Same echo rule as recall_min_similarity: calibration.ts is
607
650
  * the single home, the page never hardcodes the edges, and a page older
608
651
  * than this key simply ignores it (no band). These classify the console
package/dist/dashboard.js CHANGED
@@ -29,6 +29,7 @@ exports.computeStageCounts = computeStageCounts;
29
29
  exports.writeSnapshot = writeSnapshot;
30
30
  exports.backfillSnapshots = backfillSnapshots;
31
31
  exports.readAgentCircle = readAgentCircle;
32
+ exports.readSpacesBlock = readSpacesBlock;
32
33
  exports.handleDashboardData = handleDashboardData;
33
34
  exports.dashboardDataHandler = dashboardDataHandler;
34
35
  exports.accountHandler = accountHandler;
@@ -55,6 +56,8 @@ const quality_scoreboard_js_1 = require("./quality-scoreboard.js");
55
56
  const distill_queue_js_1 = require("./distill-queue.js");
56
57
  const capture_pause_js_1 = require("./capture-pause.js");
57
58
  const classification_js_1 = require("./classification.js");
59
+ const spaces_js_1 = require("./spaces.js");
60
+ const observed_agents_js_1 = require("./observed-agents.js");
58
61
  const state_js_1 = require("./state.js");
59
62
  const retrieval_js_1 = require("./retrieval.js");
60
63
  const stages_js_1 = require("./stages.js");
@@ -463,6 +466,52 @@ function readAgentCircle(db, config) {
463
466
  }
464
467
  return { roster, members };
465
468
  }
469
+ /**
470
+ * #642 AC-12 — compute fleet.spaces: every resolved space with its members
471
+ * and its memory/queue counts (SQL GROUP BY privacy folded through spaceOf —
472
+ * NULL/''/'standard' counts under 'standard', the fixed shared pool that is
473
+ * NEVER listed), plus the observed agents that appear in no space's members
474
+ * as unassigned (newest last_seen first — the first-prompt discovery lane).
475
+ * Pure: takes a db + config, returns the block; no side effects. The page
476
+ * hides the management section entirely when the block is absent (an older
477
+ * server) and when there is nothing to show (the zero-change dashboard).
478
+ */
479
+ function readSpacesBlock(db, config) {
480
+ const { spaces } = (0, spaces_js_1.resolveSpaces)(config);
481
+ // Counts per space id: one GROUP BY per table, folded through spaceOf so
482
+ // the shared pool (NULL/''/'standard') lands under 'standard' — a key the
483
+ // space list below never carries (it is not a space).
484
+ const countsFor = (table) => {
485
+ const out = {};
486
+ for (const row of db
487
+ .prepare(`SELECT privacy, COUNT(*) AS c FROM ${table} GROUP BY privacy`)
488
+ .all()) {
489
+ const key = row.privacy === null || row.privacy === "" ? "standard" : row.privacy;
490
+ out[key] = (out[key] ?? 0) + row.c;
491
+ }
492
+ return out;
493
+ };
494
+ const memoryCounts = countsFor("memories");
495
+ const queuedCounts = countsFor("distill_queue");
496
+ const assigned = new Set();
497
+ for (const s of spaces)
498
+ for (const m of s.members)
499
+ assigned.add(m);
500
+ // listObservedAgents is last_seen DESC (agent ASC tiebreak) — the filter
501
+ // keeps that order: freshest unknown workspace first.
502
+ const unassigned = (0, observed_agents_js_1.listObservedAgents)(db)
503
+ .filter((o) => !assigned.has(o.agent))
504
+ .map((o) => ({ agent: o.agent, first_seen: o.first_seen, last_seen: o.last_seen }));
505
+ return {
506
+ spaces: spaces.map((s) => ({
507
+ id: s.id,
508
+ members: s.members,
509
+ memoryCount: memoryCounts[s.id] ?? 0,
510
+ queuedCount: queuedCounts[s.id] ?? 0,
511
+ })),
512
+ unassigned,
513
+ };
514
+ }
466
515
  /**
467
516
  * The pure data handler for GET /dashboard/data. Reads query params
468
517
  * (`range`, `date`, `digestLimit`) off the request, returns the DashboardData
@@ -654,10 +703,13 @@ function handleDashboardData(db, query, config) {
654
703
  // for the rail's dots, toggles and the capture card's PAUSED badges.
655
704
  // #601: circle rides the same block — visibility only (roster +
656
705
  // observed members + counts), never a gate.
706
+ // #642 (AC-12): spaces rides it too — the management view's data;
707
+ // config is already threaded here (dashboardDigestLimit), reused.
657
708
  fleet: {
658
709
  pauses: (0, capture_pause_js_1.listCapturePauses)(db),
659
710
  last_seen: (0, capture_pause_js_1.readFleetLastSeen)(db),
660
711
  circle: readAgentCircle(db, config),
712
+ spaces: readSpacesBlock(db, config),
661
713
  },
662
714
  digest,
663
715
  },
@@ -775,9 +827,9 @@ function handleDashboardField(db) {
775
827
  status: 200,
776
828
  body: {
777
829
  generated_at: now.toISOString(),
778
- // #426 owner semantics ruling 2026-09-13: recall grades are REMOVED —
830
+ // #426 semantics ruling: recall grades are REMOVED —
779
831
  // recall depends on the conversation, higher is not a target. Only the
780
- // stage thresholds ride the echo (calibrated 2026-09-13), plus the two
832
+ // stage thresholds ride the echo, plus the two
781
833
  // #409/#426 display keys: the search floor and the recall-level band
782
834
  // edges (PROVISIONAL — see calibration.ts).
783
835
  thresholds: {
@@ -840,7 +892,7 @@ function dashboardFieldHandler(getDb) {
840
892
  }
841
893
  };
842
894
  }
843
- // #452 (owner directive 2026-09-16): the default window is 30 days for ALL
895
+ // #452: the default window is 30 days for ALL
844
896
  // views — longer ranges are opt-in via the page's selector. MAX stays 365:
845
897
  // it is the generic API cap and an explicit ?days= is honored up to it.
846
898
  const EVENTS_DEFAULT_DAYS = 30;
package/dist/db.js CHANGED
@@ -555,7 +555,7 @@ const MIGRATIONS = [
555
555
  version: 15,
556
556
  name: "source_machine",
557
557
  up: (db) => {
558
- // #421 owner direction (machine × harness identity): nullable, NO
558
+ // #421 direction (machine × harness identity): nullable, NO
559
559
  // backfill — honesty over guesses. Rows written before this column
560
560
  // stay NULL and group under "earlier captures" in the console; that
561
561
  // bucket shrinks as nights accumulate stamped captures. Stamped by the
@@ -704,8 +704,8 @@ const MIGRATIONS = [
704
704
  version: 22,
705
705
  name: "recall_precision_events",
706
706
  up: (db) => {
707
- // #476 — the Memory Precision card's event store (Option A, owner
708
- // decision 2026-09-19: per-push event rows incl. a ≤256-char prompt
707
+ // #476 — the Memory Precision card's event store (Option A,
708
+ // decision: per-push event rows incl. a ≤256-char prompt
709
709
  // excerpt — the exact-window Level-1 measures + the judge follow-up's
710
710
  // sample frame). Two sidecar tables, the v16 distill_activity pattern:
711
711
  // OPERATIONS telemetry, no memories FK — recall_events.memory_id is
@@ -750,7 +750,7 @@ const MIGRATIONS = [
750
750
  version: 23,
751
751
  name: "volatile_sweep_log",
752
752
  up: (db) => {
753
- // #489 — `hicortex sweep-volatile` audit trail (owner decision 3:
753
+ // #489 — `hicortex sweep-volatile` audit trail (decision 3:
754
754
  // one-shot store sweep, mark-not-delete). Every swept memory gets a row
755
755
  // here as it is absorbed: the sweep is inspectable forever, never
756
756
  // silent. The dedup_log precedent (a sidecar audit table, no memories
@@ -775,7 +775,7 @@ const MIGRATIONS = [
775
775
  // the REDACTED segment here and answers 201 immediately (no LLM call);
776
776
  // the nightly drain distills rows oldest-first and deletes each row in
777
777
  // the same transaction as its memory inserts. One table in the shared
778
- // SQLite DB — one store, same backup and tooling as the corpus (owner
778
+ // SQLite DB — one store, same backup and tooling as the corpus (design
779
779
  // decision; not files). The row carries every /distill wire field needed
780
780
  // to re-distill later (attribution, project, session_date, privacy) so
781
781
  // the drain reproduces the sync path's insert exactly.
@@ -847,7 +847,7 @@ const MIGRATIONS = [
847
847
  // source_machine precedent: pre-v26 rows stay NULL and attribute via
848
848
  // the `#`-prefix join on memories.source_session (which is
849
849
  // segment-scoped `<sessionId>#<segment>` — bare equality matches 0
850
- // rows, measured #578); the join covers 96%+ of pushes, and the
850
+ // rows, measured #578); the join covers nearly all pushes, and the
851
851
  // attribution COVERAGE % renders beside the cross-project share so the
852
852
  // gap is explicit, never silent.
853
853
  //
@@ -928,6 +928,27 @@ const MIGRATIONS = [
928
928
  }
929
929
  },
930
930
  },
931
+ {
932
+ version: 29,
933
+ name: "observed_agents",
934
+ up: (db) => {
935
+ // #642 AC-11/AC-15 — the observed-agents store. Read-side agent names
936
+ // were never persisted before (dashboard agent visibility was
937
+ // capture-time source_agent only), so a brand-new workspace was
938
+ // INVISIBLE to the dashboard until its first nightly capture. This
939
+ // store records an agent id the FIRST time it appears on a gated read
940
+ // (the requesterVisibleSpaces seam in mcp-server.ts) — a workspace
941
+ // shows as unassigned within seconds of its first prompt, before any
942
+ // capture exists. Additive only: NO migration touches memories.privacy
943
+ // (AC-15 — the widened space vocabulary rides v27's column as data,
944
+ // ids are values, never schema). Idempotent: IF NOT EXISTS.
945
+ db.exec(`CREATE TABLE IF NOT EXISTS observed_agents (
946
+ agent TEXT PRIMARY KEY,
947
+ first_seen TEXT NOT NULL,
948
+ last_seen TEXT NOT NULL
949
+ )`);
950
+ },
951
+ },
931
952
  ];
932
953
  /**
933
954
  * Run all pending migrations against the database.
package/dist/dedup.d.ts CHANGED
@@ -47,7 +47,7 @@
47
47
  *
48
48
  * A cluster whose members disagree on project is SKIPPED entirely and listed
49
49
  * for manual review (reason `project_mismatch`) — no --force in this release.
50
- * The source_agent rail was REMOVED (#206 decision 2, 2026-09-21): cross-agent
50
+ * The source_agent rail was REMOVED (#206 decision 2): cross-agent
51
51
  * clusters merge — attribution is preserved on the retained evidence row and
52
52
  * no recall path filters by agent.
53
53
  *
@@ -71,8 +71,7 @@ import type { DeterministicMergeZoneReport } from "./types.js";
71
71
  import type { RunDeadline } from "./run-deadline.js";
72
72
  /**
73
73
  * Default merge threshold — RELEASE-MANAGED since #408: the constant (with
74
- * its provenance: measured on the #191 mechanical audit corpus, 89 clusters /
75
- * 110 excess rows at 0.92, data/audit-20260729/eval-report.md) lives in
74
+ * its provenance: measured on the #191 mechanical audit corpus) lives in
76
75
  * calibration.ts. #392: also the deterministic/LLM boundary of the unified
77
76
  * resolution pass.
78
77
  */
package/dist/dedup.js CHANGED
@@ -48,7 +48,7 @@
48
48
  *
49
49
  * A cluster whose members disagree on project is SKIPPED entirely and listed
50
50
  * for manual review (reason `project_mismatch`) — no --force in this release.
51
- * The source_agent rail was REMOVED (#206 decision 2, 2026-09-21): cross-agent
51
+ * The source_agent rail was REMOVED (#206 decision 2): cross-agent
52
52
  * clusters merge — attribution is preserved on the retained evidence row and
53
53
  * no recall path filters by agent.
54
54
  *
@@ -122,8 +122,7 @@ const backup_js_1 = require("./backup.js");
122
122
  const HICORTEX_HOME = (0, paths_js_1.hicortexHome)();
123
123
  /**
124
124
  * Default merge threshold — RELEASE-MANAGED since #408: the constant (with
125
- * its provenance: measured on the #191 mechanical audit corpus, 89 clusters /
126
- * 110 excess rows at 0.92, data/audit-20260729/eval-report.md) lives in
125
+ * its provenance: measured on the #191 mechanical audit corpus) lives in
127
126
  * calibration.ts. #392: also the deterministic/LLM boundary of the unified
128
127
  * resolution pass.
129
128
  */
@@ -6,7 +6,7 @@
6
6
  * 201 immediately — no LLM call, no probe, no chunk-size detection, no token
7
7
  * gate (all of those move to the drain). The nightly's drain stage then
8
8
  * distills queued items oldest-first, round-robin per client, before
9
- * consolidation, so all distill LLM traffic happens inside the owner's
9
+ * consolidation, so all distill LLM traffic happens inside the server's
10
10
  * scheduled runs instead of on the clients' drifting capture grids.
11
11
  *
12
12
  * This module holds BOTH halves as pure units:
@@ -92,8 +92,14 @@ export interface EnqueueDistillInput {
92
92
  * a 200 skip) reports `{ duplicate: true }` and inserts nothing. Posts with
93
93
  * no session_id have no dedup key by construction and always insert (SQLite
94
94
  * unique indexes treat NULLs as distinct).
95
+ *
96
+ * #642: `knownSpaces` is the boot-resolved known space id set the /distill
97
+ * handler threads (knownSpaceIds) so a space-derived stamp SURVIVES the
98
+ * normalize boundary; omitted, only the fixed 'standard'/'confidential'
99
+ * stamps pass (every pre-#642 caller shape — a space stamp would THROW, the
100
+ * fail-closed write boundary of AC-7).
95
101
  */
96
- export declare function enqueueDistill(db: Database.Database, input: EnqueueDistillInput): {
102
+ export declare function enqueueDistill(db: Database.Database, input: EnqueueDistillInput, knownSpaces?: ReadonlySet<string>): {
97
103
  duplicate: boolean;
98
104
  };
99
105
  /**
@@ -129,7 +135,7 @@ export declare function readQueueStats(db: Database.Database, now?: number): Que
129
135
  */
130
136
  export declare function isFreshBrain(db: Database.Database): boolean;
131
137
  /**
132
- * The ONE branch condition into the sync flow (owner ruling #529: kill
138
+ * The ONE branch condition into the sync flow (#529 ruling: kill
133
139
  * switch and bootstrap carve-out share it — no third path):
134
140
  *
135
141
  * queueMode = distillQueue enabled && NOT a fresh brain
@@ -197,11 +203,31 @@ export interface DrainOptions {
197
203
  * on THIS client; when it is absent they are HELD — the row stays queued
198
204
  * (skip-and-continue, the no_llm precedent but per-item) and standard items
199
205
  * keep draining. There is NO fallback to `llm`: confidential text never
200
- * reaches the standard model, held beats exposed.
206
+ * reaches the standard model, held beats exposed. #642: the confidential
207
+ * SPACE keeps this exact role — it is never routed through spaceClients.
201
208
  */
202
209
  confidentialLlm?: DrainLlm | null;
203
210
  /** Its config — drives the confidential endpoint's own chunk-size cache. */
204
211
  confidentialLlmConfig?: LlmConfig | null;
212
+ /**
213
+ * #642 AC-9: per-space clients — every configured space except
214
+ * 'confidential'. An item stamped with one of those ids distills on ITS
215
+ * client (paired with its spaceConfigs entry); a null/absent entry HOLDS
216
+ * the item (row stays queued, counted in held_spaces, the warn names the
217
+ * id) — never the main `llm`.
218
+ */
219
+ spaceClients?: ReadonlyMap<string, DrainLlm | null>;
220
+ /** Their configs — one chunk-size cache entry per space endpoint. */
221
+ spaceConfigs?: ReadonlyMap<string, LlmConfig | null>;
222
+ /**
223
+ * #642 AC-7: the boot-resolved known space id set (knownSpaceIds at the
224
+ * nightly seam) for the insert-time normalize boundary. An item whose
225
+ * stored stamp no configured space claims (a retired space, an id from a
226
+ * config that changed) HOLDS instead of throwing out of the insert
227
+ * transaction — the row stays queued until the space returns or the
228
+ * operator re-stamps it (backfill-spaces).
229
+ */
230
+ knownSpaces?: ReadonlySet<string>;
205
231
  }
206
232
  export interface DrainReport {
207
233
  /**
@@ -229,6 +255,12 @@ export interface DrainReport {
229
255
  * per-run queue-growth signal.
230
256
  */
231
257
  held_confidential?: number;
258
+ /**
259
+ * #642: items HELD this run per space id — no client for that space, or a
260
+ * stored stamp no configured space claims (the normalize hold). Same
261
+ * posture as held_confidential: row stays queued, never the main model.
262
+ */
263
+ held_spaces?: Record<string, number>;
232
264
  /** Tokens metered this drain (incl. a failed item's partial usage). */
233
265
  usage: {
234
266
  prompt: number;
@@ -7,7 +7,7 @@
7
7
  * 201 immediately — no LLM call, no probe, no chunk-size detection, no token
8
8
  * gate (all of those move to the drain). The nightly's drain stage then
9
9
  * distills queued items oldest-first, round-robin per client, before
10
- * consolidation, so all distill LLM traffic happens inside the owner's
10
+ * consolidation, so all distill LLM traffic happens inside the server's
11
11
  * scheduled runs instead of on the clients' drifting capture grids.
12
12
  *
13
13
  * This module holds BOTH halves as pure units:
@@ -76,6 +76,7 @@ exports.isFreshBrain = isFreshBrain;
76
76
  exports.resolveQueueMode = resolveQueueMode;
77
77
  exports.drainDistillQueue = drainDistillQueue;
78
78
  const distiller_js_1 = require("./distiller.js");
79
+ const spaces_js_1 = require("./spaces.js");
79
80
  const calibration_js_1 = require("./calibration.js");
80
81
  const storage = __importStar(require("./storage.js"));
81
82
  const dedup_js_1 = require("./dedup.js");
@@ -91,8 +92,14 @@ function str(v) {
91
92
  * a 200 skip) reports `{ duplicate: true }` and inserts nothing. Posts with
92
93
  * no session_id have no dedup key by construction and always insert (SQLite
93
94
  * unique indexes treat NULLs as distinct).
95
+ *
96
+ * #642: `knownSpaces` is the boot-resolved known space id set the /distill
97
+ * handler threads (knownSpaceIds) so a space-derived stamp SURVIVES the
98
+ * normalize boundary; omitted, only the fixed 'standard'/'confidential'
99
+ * stamps pass (every pre-#642 caller shape — a space stamp would THROW, the
100
+ * fail-closed write boundary of AC-7).
94
101
  */
95
- function enqueueDistill(db, input) {
102
+ function enqueueDistill(db, input, knownSpaces) {
96
103
  const result = db
97
104
  .prepare(`INSERT OR IGNORE INTO distill_queue
98
105
  (session_id, segment_id, source_agent, source_agent_id, source_domain,
@@ -111,8 +118,9 @@ function enqueueDistill(db, input) {
111
118
  // (migration v27 normalized pre-existing rows the same way). The intake
112
119
  // handler derives the stamp from source_agent × roster before it gets
113
120
  // here, so a rostered agent's delivery is queued 'confidential' even
114
- // when the client declares nothing.
115
- storage.normalizeStoredPrivacy(input.privacy), input.text, new Date().toISOString());
121
+ // when the client declares nothing. #642: a space-derived stamp passes
122
+ // through the caller-threaded known set (unknown ids THROW — AC-7).
123
+ storage.normalizeStoredPrivacy(input.privacy, knownSpaces), input.text, new Date().toISOString());
116
124
  return { duplicate: result.changes === 0 };
117
125
  }
118
126
  /**
@@ -185,7 +193,7 @@ function isFreshBrain(db) {
185
193
  return queued.e === 0;
186
194
  }
187
195
  /**
188
- * The ONE branch condition into the sync flow (owner ruling #529: kill
196
+ * The ONE branch condition into the sync flow (#529 ruling: kill
189
197
  * switch and bootstrap carve-out share it — no third path):
190
198
  *
191
199
  * queueMode = distillQueue enabled && NOT a fresh brain
@@ -329,6 +337,25 @@ async function drainDistillQueue(db, opts) {
329
337
  console.log(`[hicortex] Distill inbox: ${rows.length} item(s) from ${queues.length} client(s) — draining`);
330
338
  const warned = { unreachable: false };
331
339
  let stopped;
340
+ // #642: per-space HOLD bookkeeping — one warn line per space id per run
341
+ // (the waitForYield once-per-run discipline), counted per item in the
342
+ // report's held_spaces.
343
+ const heldSpaces = {};
344
+ const warnedHeldSpaces = new Set();
345
+ const holdSpaceItem = (space, reason) => {
346
+ heldSpaces[space] = (heldSpaces[space] ?? 0) + 1;
347
+ report.held_spaces = heldSpaces;
348
+ if (warnedHeldSpaces.has(space))
349
+ return;
350
+ warnedHeldSpaces.add(space);
351
+ console.warn(`[hicortex] drain: item(s) stamped '${space}' HELD — ` +
352
+ (reason === "no_model"
353
+ ? `no model configured for that space (spaces.${space}.llmBaseUrl + llmApiKey, ` +
354
+ `or the llmConfidential* endpoint)`
355
+ : `no configured space claims that id (retired?) — re-add it to the spaces ` +
356
+ `config or re-stamp the rows (hicortex backfill-spaces)`) +
357
+ `. The row stays queued; it is never distilled on the main model.`);
358
+ };
332
359
  outer: while (queues.some((q) => q.length > 0)) {
333
360
  for (const q of queues) {
334
361
  if (q.length === 0)
@@ -374,22 +401,51 @@ async function drainDistillQueue(db, opts) {
374
401
  // — the caller records it against the monthly meter, same as the sync
375
402
  // path's finally.
376
403
  //
377
- // #332 per-pool client selection: a confidential item distills on the
378
- // CONFIDENTIAL client; without one it HOLDS here (skip-and-continue —
379
- // the row stays queued, standard items drain on, held count reported).
380
- // Standard items use the main client as before.
381
- if (item.privacy === "confidential") {
404
+ // #332/#642 per-space client selection, checked BEFORE any LLM call so
405
+ // an item that will hold never pays a distillation: a confidential item
406
+ // distills on the CONFIDENTIAL client; any other space-stamped item on
407
+ // ITS space client; a pool without its client HOLDS here
408
+ // (skip-and-continue — the row stays queued, standard items drain on,
409
+ // held counts reported). Standard items use the main client as before.
410
+ // There is no fallback to `llm` on any path.
411
+ const itemSpace = (0, spaces_js_1.spaceOf)(item.privacy);
412
+ if (itemSpace === "confidential") {
382
413
  if (!opts.confidentialLlm || !opts.confidentialLlmConfig) {
383
414
  report.held_confidential = (report.held_confidential ?? 0) + 1;
384
415
  continue;
385
416
  }
386
417
  }
387
- const itemLlm = (item.privacy === "confidential"
418
+ else if (itemSpace !== "standard") {
419
+ if (!opts.spaceClients?.get(itemSpace) || !opts.spaceConfigs?.get(itemSpace)) {
420
+ holdSpaceItem(itemSpace, "no_model");
421
+ continue;
422
+ }
423
+ }
424
+ // #642 AC-7 write-boundary hold: normalize the stored stamp ONCE per
425
+ // item, BEFORE distillation — a stamp no configured space claims (the
426
+ // nightly's knownSpaces set) would otherwise throw out of the insert
427
+ // transaction AFTER the LLM calls (misreported endpoint_down, retried
428
+ // forever). Instead the item HOLDS with the same posture as the
429
+ // no-model hold: row queued, space named, operator re-claims or
430
+ // re-stamps.
431
+ let storedPrivacy;
432
+ try {
433
+ storedPrivacy = storage.normalizeStoredPrivacy(item.privacy, opts.knownSpaces);
434
+ }
435
+ catch {
436
+ holdSpaceItem(String(item.privacy), "unclaimed_space");
437
+ continue;
438
+ }
439
+ const itemLlm = (itemSpace === "confidential"
388
440
  ? opts.confidentialLlm
389
- : opts.llm);
390
- const itemLlmConfig = item.privacy === "confidential"
441
+ : itemSpace === "standard"
442
+ ? opts.llm
443
+ : opts.spaceClients.get(itemSpace));
444
+ const itemLlmConfig = itemSpace === "confidential"
391
445
  ? opts.confidentialLlmConfig
392
- : opts.llmConfig;
446
+ : itemSpace === "standard"
447
+ ? opts.llmConfig
448
+ : opts.spaceConfigs.get(itemSpace);
393
449
  const chunkSize = await resolveDrainChunkSizeFor(opts, itemLlmConfig);
394
450
  const usage = { prompt: 0, completion: 0, total: 0 };
395
451
  const label = item.segment_id !== ""
@@ -446,10 +502,12 @@ async function drainDistillQueue(db, opts) {
446
502
  sourceSession: sourcePrefix ? `${sourcePrefix}#${i}` : undefined,
447
503
  project: canonProject ?? undefined,
448
504
  memoryType,
449
- // #332: the row's class stamp rides into the stored memories —
450
- // normalized defensively (a NULL from a pre-v27 row reads
451
- // standard, same as the read gates).
452
- privacy: storage.normalizeStoredPrivacy(item.privacy),
505
+ // #332/#642: the row's space stamp rides into the stored
506
+ // memories — normalized defensively (a NULL from a pre-v27 row
507
+ // reads standard, same as the read gates); the #642 known set
508
+ // was applied at the per-item hold check above, so this never
509
+ // throws inside the transaction.
510
+ privacy: storedPrivacy,
453
511
  createdAt,
454
512
  });
455
513
  }
@@ -486,6 +544,10 @@ async function drainDistillQueue(db, opts) {
486
544
  `${report.memories} memories, ${report.duplicates} duplicate skip(s)` +
487
545
  (report.held_confidential
488
546
  ? `, ${report.held_confidential} confidential item(s) HELD (no confidential model)`
547
+ : "") +
548
+ (report.held_spaces
549
+ ? `, ${Object.values(report.held_spaces).reduce((s, n) => s + n, 0)} item(s) HELD ` +
550
+ `across space(s) ${Object.keys(report.held_spaces).join(", ")}`
489
551
  : ""));
490
552
  }
491
553
  return report;
@@ -81,7 +81,7 @@ export declare function hasMinimalSubstance(entry: string): boolean;
81
81
  /**
82
82
  * True when the entry is a VOLATILE STATUS SHAPE — GH-ticket/workflow status,
83
83
  * version-bump status, or branch/commit state — and carries no durability
84
- * escape (#489, owner decisions 1+2). Runs in distillChunk's gate zone beside
84
+ * escape (#489, decisions 1+2). Runs in distillChunk's gate zone beside
85
85
  * hasMinimalSubstance; drops ride the SAME #156 dropped[] trail. Also reused
86
86
  * verbatim by `hicortex sweep-volatile` over the stored corpus — ONE gate,
87
87
  * one meaning.
package/dist/distiller.js CHANGED
@@ -18,9 +18,10 @@ const redact_js_1 = require("./redact.js");
18
18
  const calibration_js_1 = require("./calibration.js");
19
19
  const MAX_TRANSCRIPT_CHARS = 80_000;
20
20
  const MIN_CONVERSATION_CHARS = 200;
21
- // #339 (2026-08-24 postmortem): NO_EXTRACT over-firing visibility threshold.
22
- // Real summary-led segments that the model wrongly abandoned ran 38-64K
23
- // denoised chars; genuine pure-status noise is ~2.6K. A segment larger than
21
+ // #339 (postmortem): NO_EXTRACT over-firing visibility threshold.
22
+ // Real summary-led segments that the model wrongly abandoned ran tens of
23
+ // thousands of denoised chars; genuine pure-status noise is only a few
24
+ // thousand. A segment larger than
24
25
  // this whose every chunk returns an empty LLM verdict is far more likely the
25
26
  // model pattern-matching a bookkeeping-heavy OPENING to the ephemera gate than
26
27
  // a legitimately empty segment — so it gets a warning line. Warning ONLY: no
@@ -412,11 +413,11 @@ async function distillChunk(llm, transcript, projectName, date, onUsage) {
412
413
  substanceDropped.push(entry.content);
413
414
  continue;
414
415
  }
415
- // #489 volatility gate (owner decision 2: entry-level, deterministic,
416
+ // #489 volatility gate (decision 2: entry-level, deterministic,
416
417
  // beside the substance gate — cleanMessageContent untouched): GH-ticket /
417
418
  // version-bump / commit-state status shapes drop into the SAME #156
418
- // trail (owner decision 1: mark-and-skip, never silent). Kill-switch =
419
- // the release-managed calibration constant (owner decision 5).
419
+ // trail (decision 1: mark-and-skip, never silent). Kill-switch =
420
+ // the release-managed calibration constant (decision 5).
420
421
  if (calibration_js_1.VOLATILE_STATUS_FILTER && isVolatileStatusEntry(entry.content)) {
421
422
  volatileDropped.push(entry.content);
422
423
  continue;
@@ -527,12 +528,12 @@ function hasMinimalSubstance(entry) {
527
528
  }
528
529
  // ---------------------------------------------------------------------------
529
530
  // Volatility gate (#489) — deterministic, entry-level, beside the substance
530
- // gate. Owner directive (gold-set A adjudication): GitHub ticket/workflow
531
+ // gate. Design directive (gold-set A adjudication): GitHub ticket/workflow
531
532
  // states and version numbers churn faster than nightly consolidation retires
532
533
  // them — they arrive as supersession noise and inflate the store with
533
534
  // same-subject rows. The ephemera PROMPT already names these categories and
534
- // demonstrably under-fires (a month of it running, gold A still full of
535
- // GH-status/version rows) — so the filter is deterministic, catching entries
535
+ // demonstrably under-fires (gold set A stayed full of
536
+ // GH-status/version rows even after long runs) — so the filter is deterministic, catching entries
536
537
  // synthesized from ANY source prose.
537
538
  // ---------------------------------------------------------------------------
538
539
  /**
@@ -564,7 +565,7 @@ const VCS_STATE = /\b(?:pushed?|merged?|rebased?|force-?pushed?|updated?)\b/i;
564
565
  /**
565
566
  * True when the entry is a VOLATILE STATUS SHAPE — GH-ticket/workflow status,
566
567
  * version-bump status, or branch/commit state — and carries no durability
567
- * escape (#489, owner decisions 1+2). Runs in distillChunk's gate zone beside
568
+ * escape (#489, decisions 1+2). Runs in distillChunk's gate zone beside
568
569
  * hasMinimalSubstance; drops ride the SAME #156 dropped[] trail. Also reused
569
570
  * verbatim by `hicortex sweep-volatile` over the stored corpus — ONE gate,
570
571
  * one meaning.
@@ -645,8 +646,8 @@ function parseDistilledEntries(markdown) {
645
646
  // Skip all markdown headers (session title, section headings). Sections
646
647
  // are NOT prefixed onto entries: each bullet already starts with its type
647
648
  // tag + [SUBJECT] (topic-first, enforced by prompts.ts), and prepending
648
- // "[Section]" re-introduced the category-first prefix the 2026-08-02
649
- // corpus rewrite removed.
649
+ // "[Section]" re-introduced the category-first prefix the corpus
650
+ // rewrite removed.
650
651
  if (trimmed.startsWith("# ") ||
651
652
  trimmed.startsWith("## ") ||
652
653
  trimmed.startsWith("### ")) {