@gamaze/hicortex 0.24.1 → 0.26.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.
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ /**
3
+ * `hicortex reconcile-projects` (#567) — one-shot project-label
4
+ * reconciliation for EXISTING rows.
5
+ *
6
+ * The server canonicalizes every project string at entry (project-
7
+ * canonicalize.ts, wired in mcp-server.ts); this command heals the corpus
8
+ * that predates it: the 5,544-row `hicortex`/`Hicortex` case split and the
9
+ * 14% junk-label share measured in #565 WS1. Dry run by default (report
10
+ * only, zero writes); `--apply` renames along the dedup rails.
11
+ *
12
+ * What a rename is: a pure function of the config alias map + the current
13
+ * labels — canonicalize(label) ≠ label. Same single-hop semantics as the
14
+ * entry-point fold, computed from the ORIGINAL labels BEFORE any write (the
15
+ * per-group `WHERE project = ?` updates are then order-independent). Touches
16
+ * `memories.project` and `distill_queue.project` (the inbox must not
17
+ * re-distill old labels post-rename) and NOTHING else:
18
+ * - no `memories.domain`, no `memory_tags` — tag-derived, recomputed
19
+ * nightly; a rename is not a re-classification;
20
+ * - no `dedup_log`, no new audit table — relabels are not destructive
21
+ * (dedup needed its log because merges absorb rows; the pre-apply
22
+ * backup IS the safety net here).
23
+ *
24
+ * Safety rails (the #100 `hicortex dedup` pattern): pre-apply DB backup via
25
+ * takePreDedupBackup (abort all writes on failure) → single-flight capture
26
+ * lock (waitMs 0 — a busy lock aborts, never waits) → ONE transaction per
27
+ * rename group, fail-soft per group. The FTS row syncs automatically: the
28
+ * `memories_fts_update` trigger (db.ts) fires `AFTER UPDATE OF … project`.
29
+ * SQLite's BINARY collation on `memories.project` makes the `WHERE
30
+ * project = ?` match case-sensitive — exactly what a case-split rename
31
+ * needs (`Hicortex` → `hicortex` rewrites only the variant rows).
32
+ *
33
+ * Idempotent by construction: a second run finds every label already
34
+ * canonical and reports zero groups.
35
+ */
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.runReconcileProjects = runReconcileProjects;
38
+ const paths_js_1 = require("./paths.js");
39
+ const node_fs_1 = require("node:fs");
40
+ const node_path_1 = require("node:path");
41
+ const db_js_1 = require("./db.js");
42
+ const capture_js_1 = require("./capture.js");
43
+ const dedup_js_1 = require("./dedup.js");
44
+ const project_canonicalize_js_1 = require("./project-canonicalize.js");
45
+ const HICORTEX_HOME = (0, paths_js_1.hicortexHome)();
46
+ function readConfig(stateDir) {
47
+ try {
48
+ return JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(stateDir, "config.json"), "utf-8"));
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ /** Distinct non-blank labels + row counts from one table's project column. */
55
+ function readLabels(db, table) {
56
+ const rows = db
57
+ .prepare(`SELECT project, COUNT(*) AS c FROM ${table} WHERE project IS NOT NULL AND project != '' GROUP BY project`)
58
+ .all();
59
+ const out = new Map();
60
+ for (const r of rows)
61
+ out.set(r.project, r.c);
62
+ return out;
63
+ }
64
+ /**
65
+ * Compute the FULL plan from the ORIGINAL labels, before any write:
66
+ * rename groups (canonical ≠ label) + the post-canonical surviving-label
67
+ * report. A blank/whitespace label canonicalizes to null — not a rename
68
+ * target (blank rows are excluded by the read; they predate this command
69
+ * and carry no identity either way).
70
+ */
71
+ function planReconcile(db, aliases) {
72
+ const memoryLabels = readLabels(db, "memories");
73
+ const queuedLabels = readLabels(db, "distill_queue");
74
+ const groups = [];
75
+ const canonicalRows = new Map();
76
+ for (const [label, rows] of memoryLabels) {
77
+ const canon = (0, project_canonicalize_js_1.canonicalizeProject)(label, aliases);
78
+ if (canon !== null)
79
+ canonicalRows.set(canon, (canonicalRows.get(canon) ?? 0) + rows);
80
+ if (canon !== null && canon !== label) {
81
+ groups.push({ from: label, to: canon, memoryRows: rows, queuedRows: queuedLabels.get(label) ?? 0 });
82
+ }
83
+ }
84
+ // Queue-only labels (memories row already renamed, inbox holds the old
85
+ // label — e.g. a reconcile run between delivery and drain) group too.
86
+ for (const [label, rows] of queuedLabels) {
87
+ const canon = (0, project_canonicalize_js_1.canonicalizeProject)(label, aliases);
88
+ if (canon !== null && canon !== label && !memoryLabels.has(label)) {
89
+ groups.push({ from: label, to: canon, memoryRows: 0, queuedRows: rows });
90
+ }
91
+ }
92
+ groups.sort((a, b) => b.memoryRows - a.memoryRows || a.from.localeCompare(b.from));
93
+ const labels = [...canonicalRows.entries()]
94
+ .map(([label, rows]) => ({ label, rows, numeric: /^\d+$/.test(label) }))
95
+ .sort((a, b) => b.rows - a.rows || a.label.localeCompare(b.label));
96
+ return { groups, labels };
97
+ }
98
+ /**
99
+ * Run `hicortex reconcile-projects`. Dry run by default (options.apply
100
+ * falsy) — plan + report only, zero writes. `options.apply` executes:
101
+ * backup, then one transaction per rename group. A busy capture lock is an
102
+ * abort with the dedup wording (reported as `lockBusy: true`, never a
103
+ * wait); a failed backup aborts all writes (throw, like dedup).
104
+ */
105
+ async function runReconcileProjects(options = {}) {
106
+ const stateDir = options.stateDir ?? HICORTEX_HOME;
107
+ const config = options.config !== undefined ? options.config : readConfig(stateDir);
108
+ const aliases = (0, project_canonicalize_js_1.parseProjectAliases)(config);
109
+ // Server-mode only — client installs have no local DB.
110
+ if (config?.mode === "client") {
111
+ throw new Error("[hicortex] reconcile-projects is server-mode only (it needs the local DB). " +
112
+ `This machine is a client of ${config.serverUrl ?? "a remote server"} — run reconcile-projects on the server.`);
113
+ }
114
+ const apply = options.apply ?? false;
115
+ const dbPath = (0, db_js_1.resolveDbPath)(options.dbPath);
116
+ const db = (0, db_js_1.initDb)(dbPath);
117
+ try {
118
+ console.log(`[hicortex] reconcile-projects starting (${apply ? "APPLY" : "dry-run"}): db ${dbPath}` +
119
+ (aliases ? `, ${Object.keys(aliases).length} alias(es)` : ", no aliases (mechanical fold only)"));
120
+ const { groups, labels } = planReconcile(db, aliases);
121
+ const numericLabels = labels.filter((l) => l.numeric).map((l) => l.label);
122
+ const report = { dryRun: !apply, groups, labels, numericLabels };
123
+ const totalMemories = groups.reduce((s, g) => s + g.memoryRows, 0);
124
+ const totalQueued = groups.reduce((s, g) => s + g.queuedRows, 0);
125
+ console.log(`[hicortex] reconcile-projects: ${groups.length} rename group(s), ` +
126
+ `${totalMemories} memory row(s)${totalQueued > 0 ? `, ${totalQueued} queued row(s)` : ""} ` +
127
+ `(${apply ? "applying" : "dry run — zero writes"})`);
128
+ for (const g of groups) {
129
+ console.log(`[hicortex] ${g.from} → ${g.to} (${g.memoryRows} row(s)${g.queuedRows > 0 ? `, ${g.queuedRows} queued` : ""})`);
130
+ }
131
+ // The unmapped-labels report: every SURVIVING post-canonical label with
132
+ // its row count, numerics flagged — the junk-curation evidence.
133
+ console.log(`[hicortex] surviving project labels (post-canonicalization): ${labels.length}`);
134
+ for (const l of labels) {
135
+ console.log(`[hicortex] ${l.label}: ${l.rows} row(s)${l.numeric ? " [NUMERIC — likely a junk label; consider an alias]" : ""}`);
136
+ }
137
+ if (!apply)
138
+ return report;
139
+ // --apply: single-flight capture lock (waitMs 0) so a concurrent
140
+ // nightly/capture run cannot race the renames. Busy → abort (reported,
141
+ // never a silent wait — a deliberate manual command is retried by the
142
+ // operator, like dedup).
143
+ const acquireLock = options.acquireLock ?? capture_js_1.acquireCaptureLock;
144
+ const releaseLock = await acquireLock(stateDir, 0);
145
+ if (!releaseLock) {
146
+ console.error("[hicortex] reconcile-projects --apply aborted: another capture/nightly run holds the lock. Retry when it finishes.");
147
+ report.lockBusy = true;
148
+ return report;
149
+ }
150
+ try {
151
+ // Backup FIRST — abort entirely (no renames attempted) if it fails.
152
+ let backupPath;
153
+ try {
154
+ backupPath = await (0, dedup_js_1.takePreDedupBackup)(db, stateDir, config);
155
+ }
156
+ catch (err) {
157
+ throw new Error(`[hicortex] reconcile-projects --apply aborted: backup failed (${err instanceof Error ? err.message : String(err)}). No renames attempted.`);
158
+ }
159
+ console.log(`[hicortex] Backup written: ${backupPath}`);
160
+ report.backupPath = backupPath;
161
+ const applied = { groups: 0, memories: 0, queued: 0, failed: 0 };
162
+ // ONE transaction per group: both table updates commit together, and a
163
+ // failed group rolls back whole (fail-soft — the rest proceed, the
164
+ // failed group is retried on a re-run; idempotency makes that safe).
165
+ for (const g of groups) {
166
+ try {
167
+ const renamed = db.transaction(() => {
168
+ const m = db
169
+ .prepare("UPDATE memories SET project = ? WHERE project = ?")
170
+ .run(g.to, g.from);
171
+ const q = db
172
+ .prepare("UPDATE distill_queue SET project = ? WHERE project = ?")
173
+ .run(g.to, g.from);
174
+ return { memories: m.changes, queued: q.changes };
175
+ })();
176
+ applied.groups++;
177
+ applied.memories += renamed.memories;
178
+ applied.queued += renamed.queued;
179
+ console.log(`[hicortex] renamed ${g.from} → ${g.to}: ${renamed.memories} memory row(s)${renamed.queued > 0 ? `, ${renamed.queued} queued` : ""}`);
180
+ }
181
+ catch (err) {
182
+ applied.failed++;
183
+ console.error(`[hicortex] rename FAILED (${g.from} → ${g.to}): ` +
184
+ `${err instanceof Error ? err.message : String(err)} — rolled back, left for a re-run`);
185
+ }
186
+ }
187
+ report.applied = applied;
188
+ console.log(`[hicortex] reconcile-projects complete: ${applied.groups} group(s) renamed, ` +
189
+ `${applied.memories} memory row(s), ${applied.queued} queued row(s)` +
190
+ (applied.failed > 0 ? `, ${applied.failed} group(s) FAILED (see errors above)` : ""));
191
+ return report;
192
+ }
193
+ finally {
194
+ releaseLock();
195
+ }
196
+ }
197
+ finally {
198
+ db.close();
199
+ }
200
+ }
package/dist/retrieval.js CHANGED
@@ -982,8 +982,9 @@ async function retrieve(db, embedFn, query, options) {
982
982
  source: t.source,
983
983
  }));
984
984
  // 7. Strengthen — skipped for pushed recall (#192): appearing in a pushed
985
- // index is exposure, not use; the /recall-index path records shown_count +
986
- // last_accessed via storage.touchMemoriesShown instead.
985
+ // index is exposure, not use; the /recall-index path records shown_count
986
+ // via storage.touchMemoriesShown instead (#569: exposure never touches the
987
+ // use clock, so no last_accessed write happens there either).
987
988
  if (!options?.noStrengthen) {
988
989
  strengthen(db, top.map((t) => t.mem), now);
989
990
  }
package/dist/state.d.ts CHANGED
@@ -136,6 +136,15 @@ export interface HicortexState {
136
136
  * (`stages.reconsolidation.band_stats`).
137
137
  */
138
138
  resolutionBandStats?: Record<string, ResolutionBandStat>;
139
+ /**
140
+ * #578 — the weekly quality-grade stage's ISO-week cursor ("YYYY-Www",
141
+ * UTC). Set to the week a pass COMPLETED (the supersessionCursor
142
+ * advance-past-confirmed-work convention): a capped, deadlined, or failed
143
+ * pass holds the cursor so the ungraded remainder retries on the next
144
+ * nightly — dup-over-loss, never a hole in the trend. Absent = the stage
145
+ * has never completed a week.
146
+ */
147
+ qualityGradeWeek?: string;
139
148
  }
140
149
  /**
141
150
  * Load the state file. Returns an empty state if the file is missing
package/dist/storage.d.ts CHANGED
@@ -66,12 +66,17 @@ export declare function enrichMemory(db: Database.Database, memoryId: string, no
66
66
  } | null;
67
67
  /**
68
68
  * Record that memories appeared in a pushed recall index (#192): bump
69
- * shown_count and refresh last_accessed (a mild strengthen — the decay clock
70
- * resets so topically-live memories stop sinking) WITHOUT touching
71
- * access_count, which stays reserved for real use (the promotion signal
72
- * #448 + the prune shield).
73
- */
74
- export declare function touchMemoriesShown(db: Database.Database, memoryIds: string[], nowIsoStr: string): void;
69
+ * shown_count ONLY. #569 closed the exposure-refresh loop: last_accessed is
70
+ * the USE clock — the clock effectiveStrength decays on, i.e. the strength
71
+ * term of computeScore, the stageDecayPrune predicate, and the
72
+ * stageMemoryCapEviction ordering — and a memory the index keeps choosing
73
+ * must still age when nobody ever fetches it. Exposure is not use. It is
74
+ * written ONLY by insert (= created_at), strengthenMemory (real use),
75
+ * enrichMemory (owner corroboration), updateMemory (explicit), and the dedup
76
+ * canonical merge (max). access_count likewise stays reserved for real use
77
+ * (the promotion signal #448 + the adoption metric).
78
+ */
79
+ export declare function touchMemoriesShown(db: Database.Database, memoryIds: string[]): void;
75
80
  /**
76
81
  * Delete a memory, its vector, its tags, and all its links.
77
82
  */
package/dist/storage.js CHANGED
@@ -172,8 +172,9 @@ const ALLOWED_UPDATE_FIELDS = new Set([
172
172
  "last_accessed",
173
173
  "access_count",
174
174
  // shown_count is normally maintained by touchMemoriesShown (bulk +1 per
175
- // recall-index appearance); it's also allowed here so `hicortex dedup`
176
- // (#100) can sum a merged cluster's counters onto the canonical row.
175
+ // recall-index appearance — exposure only, never the use clock, #569); it's
176
+ // also allowed here so `hicortex dedup` (#100) can sum a merged cluster's
177
+ // counters onto the canonical row.
177
178
  "shown_count",
178
179
  "source_agent",
179
180
  "source_session",
@@ -258,20 +259,25 @@ function enrichMemory(db, memoryId, nowIsoStr) {
258
259
  }
259
260
  /**
260
261
  * Record that memories appeared in a pushed recall index (#192): bump
261
- * shown_count and refresh last_accessed (a mild strengthen — the decay clock
262
- * resets so topically-live memories stop sinking) WITHOUT touching
263
- * access_count, which stays reserved for real use (the promotion signal
264
- * #448 + the prune shield).
265
- */
266
- function touchMemoriesShown(db, memoryIds, nowIsoStr) {
262
+ * shown_count ONLY. #569 closed the exposure-refresh loop: last_accessed is
263
+ * the USE clock — the clock effectiveStrength decays on, i.e. the strength
264
+ * term of computeScore, the stageDecayPrune predicate, and the
265
+ * stageMemoryCapEviction ordering — and a memory the index keeps choosing
266
+ * must still age when nobody ever fetches it. Exposure is not use. It is
267
+ * written ONLY by insert (= created_at), strengthenMemory (real use),
268
+ * enrichMemory (owner corroboration), updateMemory (explicit), and the dedup
269
+ * canonical merge (max). access_count likewise stays reserved for real use
270
+ * (the promotion signal #448 + the adoption metric).
271
+ */
272
+ function touchMemoriesShown(db, memoryIds) {
267
273
  if (memoryIds.length === 0)
268
274
  return;
269
275
  const stmt = db.prepare(`UPDATE memories
270
- SET shown_count = COALESCE(shown_count, 0) + 1, last_accessed = ?
276
+ SET shown_count = COALESCE(shown_count, 0) + 1
271
277
  WHERE id = ?`);
272
278
  const run = db.transaction((ids) => {
273
279
  for (const id of ids)
274
- stmt.run(nowIsoStr, id);
280
+ stmt.run(id);
275
281
  });
276
282
  run(memoryIds);
277
283
  }
package/dist/types.d.ts CHANGED
@@ -661,6 +661,23 @@ export interface HicortexConfig {
661
661
  * value is ignored (warned), never coerced.
662
662
  */
663
663
  distillQueue?: boolean;
664
+ /**
665
+ * #582 explicit opt-in for the weekly recall-quality grading lane. Default
666
+ * OFF — the lane sends prompt-derived text to a third-party decisions
667
+ * endpoint, so it runs only when this is `true` AND `qualityGradeModel` is
668
+ * set AND the endpoint key resolves; anything missing fails CLOSED (the
669
+ * stage skips with a greppable health line, never an error). Read through
670
+ * readStrictBoolean — a non-boolean value is ignored (warned), never
671
+ * coerced, and the lane stays off.
672
+ */
673
+ qualityGrading?: boolean;
674
+ /**
675
+ * #582 the model id the weekly grading lane requests when `qualityGrading`
676
+ * is on. No default — an egress path never gets an implicit model choice;
677
+ * absent/blank (read through readStringConfig) the stage skips with its
678
+ * own health line.
679
+ */
680
+ qualityGradeModel?: string;
664
681
  /**
665
682
  * #529 optional interactive-yield signal: a URL the drain polls BETWEEN
666
683
  * items. A 2xx answer whose body is JSON with a truthy `busy` field — or
@@ -713,6 +730,18 @@ export interface HicortexConfig {
713
730
  * so these were not surfacing in the top-k anyway).
714
731
  */
715
732
  memorySoftCap?: number;
733
+ /**
734
+ * The cross-project recall fence bar (#566; default 0.72 — fence ON when
735
+ * the key is absent, owner ruling 2026-10-28). A memory from a different
736
+ * project than the request's must clear this bar on a measured cosine to be
737
+ * admitted into recall/search results; same-project and unscoped recall are
738
+ * unchanged. `0` or any value ≤ the recall floor (0.62) = fence off
739
+ * (today's scope-blind behavior). Clamped to [0,1]; a wrong type warns and
740
+ * keeps the default (readUnitIntervalConfig). The one #408 config-key
741
+ * exception (firstRunLookbackDays precedent) — a per-install posture dial,
742
+ * not corpus calibration. Resolved once at server boot (restart to apply).
743
+ */
744
+ recallCrossProjectMinSimilarity?: number;
716
745
  /**
717
746
  * Hosted-service mode (issue #110, #271 — spec 2026-07-27 §1-§2). When true,
718
747
  * the server enforces hosted-tenant constraints at boot: it refuses to start
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gamaze/hicortex",
3
- "version": "0.24.1",
3
+ "version": "0.26.0",
4
4
  "description": "Persistent agent identity for AI agents \u2014 a hand-edited identity layer, nightly-distilled experience, and lessons injected every session, shared across your whole fleet. Works with Hermes, OpenClaw, Claude Code, Pi, and opencode.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
package/server.json CHANGED
@@ -3,12 +3,12 @@
3
3
  "name": "io.github.gamaze-labs/hicortex",
4
4
  "title": "Hicortex \u2014 AI Fleet Memory",
5
5
  "description": "Shared fleet memory for AI agents: nightly self-correction, recall every prompt (supported agents).",
6
- "version": "0.24.1",
6
+ "version": "0.26.0",
7
7
  "packages": [
8
8
  {
9
9
  "registryType": "npm",
10
10
  "identifier": "@gamaze/hicortex",
11
- "version": "0.24.1",
11
+ "version": "0.26.0",
12
12
  "transport": {
13
13
  "type": "stdio",
14
14
  "command": "npx",