@gamaze/hicortex 0.26.3 → 0.27.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +21 -13
  2. package/assets/dashboard.html +95 -3
  3. package/dist/backfill-privacy.d.ts +109 -0
  4. package/dist/backfill-privacy.js +304 -0
  5. package/dist/capture.d.ts +60 -0
  6. package/dist/capture.js +90 -1
  7. package/dist/classification.d.ts +315 -0
  8. package/dist/classification.js +525 -0
  9. package/dist/classify-domains.js +24 -7
  10. package/dist/cli.js +80 -0
  11. package/dist/cluster.d.ts +15 -8
  12. package/dist/cluster.js +10 -3
  13. package/dist/confidential-marker.d.ts +103 -0
  14. package/dist/confidential-marker.js +285 -0
  15. package/dist/consolidate.d.ts +65 -5
  16. package/dist/consolidate.js +275 -48
  17. package/dist/dashboard.d.ts +32 -0
  18. package/dist/dashboard.js +33 -0
  19. package/dist/db.js +49 -1
  20. package/dist/dedup.d.ts +5 -3
  21. package/dist/dedup.js +26 -12
  22. package/dist/distill-queue.d.ts +34 -1
  23. package/dist/distill-queue.js +57 -10
  24. package/dist/graph.d.ts +28 -3
  25. package/dist/graph.js +46 -4
  26. package/dist/hermes-transcript-reader.js +5 -0
  27. package/dist/init.d.ts +18 -9
  28. package/dist/init.js +111 -81
  29. package/dist/marker-key-api.d.ts +79 -0
  30. package/dist/marker-key-api.js +96 -0
  31. package/dist/mcp-server.js +317 -32
  32. package/dist/nightly.js +36 -7
  33. package/dist/opencode-transcript-reader.js +3 -0
  34. package/dist/pi-transcript-reader.js +3 -0
  35. package/dist/prompts.d.ts +33 -1
  36. package/dist/prompts.js +37 -2
  37. package/dist/recall-index.d.ts +19 -9
  38. package/dist/recall-index.js +14 -4
  39. package/dist/recall-precision.js +3 -1
  40. package/dist/reconsolidation.d.ts +10 -0
  41. package/dist/reconsolidation.js +80 -17
  42. package/dist/redact.d.ts +9 -1
  43. package/dist/redact.js +32 -1
  44. package/dist/rescore-importance.js +21 -4
  45. package/dist/retrieval.d.ts +23 -6
  46. package/dist/retrieval.js +41 -15
  47. package/dist/seed-lesson.js +3 -1
  48. package/dist/storage.d.ts +23 -4
  49. package/dist/storage.js +43 -11
  50. package/dist/transcript-reader.d.ts +10 -0
  51. package/dist/transcript-reader.js +13 -0
  52. package/dist/type-classify.js +22 -7
  53. package/dist/types.d.ts +117 -15
  54. package/dist/uninstall.js +6 -5
  55. package/hermes-plugin/hicortex/README.md +4 -0
  56. package/hermes-plugin/hicortex/client.py +36 -9
  57. package/hermes-plugin/hicortex/plugin.yaml +1 -1
  58. package/hermes-plugin/hicortex/provider.py +28 -6
  59. package/package.json +1 -1
  60. package/server.json +2 -2
package/README.md CHANGED
@@ -145,20 +145,21 @@ npx @gamaze/hicortex rescore-importance --reset # restart from the beginning
145
145
 
146
146
  The run is resumable — interrupt it any time and it continues where it stopped. New memories are classified automatically by the nightly; the backfill is only needed once for a pre-existing corpus or after you reshape your domain list.
147
147
 
148
- ## Agent Tools (MCP)
148
+ ## Tools
149
149
 
150
150
  10 canonical tools available via MCP (plus `hicortex_lessons` as a backcompat alias of `hicortex_learnings`):
151
151
 
152
- - **hicortex_search** — Semantic search across all stored memories
153
- - **hicortex_get** — Fetch one memory's full content by id (0.14) — the lazy-load counterpart of the recall index; fetching marks the memory as used
154
- - **hicortex_recent** — Get recent decisions and project state (queryless recall; renamed in 0.12)
155
- - **hicortex_ingest** — Store a memory directly
156
- - **hicortex_learnings** — Get actionable Learnings from reflection (`hicortex_lessons` is kept as a backcompat alias)
157
- - **hicortex_index** — Get the knowledge domain index (what topics are stored)
158
- - **hicortex_graph** — Graph traversal: neighbors, hubs, shortest paths
159
- - **hicortex_update** — Fix incorrect memories (re-embeds on content change)
160
- - **hicortex_delete** — Remove memories with cascade cleanup
161
- - **hicortex_identity** — Fetch your standing identity layer on demand (all sections, or one by name; pass `agent` on multi-agent installs to scope to a specific agent)
152
+ - **hicortex_search** — Search shared long-term memory (all agents, all sessions)
153
+ - **hicortex_get** — Fetch ONE memory's full content by id — lazy-load from the recall index or search results; fetching marks the memory as used
154
+ - **hicortex_recent** — Get recent memories, optionally filtered by project
155
+ - **hicortex_ingest** — Store a new memory in long-term storage (explicitly requested learnings only — capture is otherwise automatic)
156
+ - **hicortex_learnings** — Get actionable Learnings — auto-generated insights about mistakes to avoid
157
+ - **hicortex_lessons** — Alias for `hicortex_learnings`
158
+ - **hicortex_index** — Get the knowledge domain index — what topics and projects are stored in memory, grouped by domain
159
+ - **hicortex_graph** — Query the memory knowledge graph — find connected memories, hub nodes, or paths between memories
160
+ - **hicortex_update** — Update an existing memory (re-computes the embedding when content changes)
161
+ - **hicortex_delete** — Permanently delete a memory and its links
162
+ - **hicortex_identity** — Fetch your standing identity — the hand-edited 'who you are + how you work' layer (personality, rules, preferences)
162
163
 
163
164
  Explicit learnings: call `hicortex_ingest` directly (capture is otherwise automatic, nightly).
164
165
 
@@ -278,10 +279,17 @@ Config at `~/.hicortex/config.json`. Created by `init`. Key options:
278
279
  | `identityClients` | Which harnesses inject the [identity layer](#identity-layer) at session start (default `["cc"]`; `"all"` or any subset of `cc`/`hermes`/`oc`/`pi`/`opencode`) |
279
280
  | `identityAgents` | Per-agent identity modes (0.13): `{ "<id>": "override" \| "global" \| "off" }`. Absent + no `agents/<id>/` dir → every agent gets the global set. Boot-time (restart to apply) — see [Per-agent identity](#per-agent-identity-013) |
280
281
  | `agentName` | This install's per-agent identity id sent as `?agent=`. **Unset by default** (CC shares the global identity — no `?agent=` sent). Explicit opt-in via `init --agent-name <name>`; `init --agent-name ""` clears it. An empty/whitespace value equals unset |
281
- | `captureCooldownHours` | Success-cooldown (hours) for the **capture watchdog** (0.17). The capture timer polls every ~20 min; the watchdog captures only if more than this has elapsed since the last *successful* capture (`state.lastNightly`). Default `6` (≈4 captures/day). A failed preflight retries on the next poll (~20 min) — so a transient fire-instant network miss costs minutes, not a day (#239) |
282
+ | `confidentialAgents` | The **confidential circle** roster (#332): agent ids (same sanitized namespace as `identityAgents`/`?agent=`; `"finance-bot"`, not `"hermes/finance-bot"` — the first `<harness>/` segment is stripped when matching captures). Captures from rostered agents are stamped `confidential` at intake, server-derived (client-declared privacy is ignored); only rostered agents — sending their id as the optional `agent` param on `/recall-index`, `/search`, `/recent`, `/memory`, `/learnings`, `/graph` — see those memories (absent/unknown agent = omitted, single fetch 404). Members see both pools. **Empty by default = no circle, zero change.** Boot-time (restart to apply); `hicortex backfill-privacy` (dry run by default) stamps history by source agent |
283
+ | `confidentialPaths` | Workspace-path patterns for the confidential circle (#609) — the **advanced** arm for the two jobs a local marker cannot do: retroactive backfill (with `hicortex backfill-privacy`) and central fleet management (one config edit covers every machine, no command to run). A capture made in a matching folder is stamped `confidential` at intake **regardless of agent id** (Claude Code agent ids are folder-derived generics — the roster alone misses a sensitive folder captured by an unrostered id). Entries are absolute paths in three forms — exact (`/home/me/finance`), `*` as a full segment (`/home/*/finance`), trailing `/**` subtree *including* the prefix itself (`/home/me/**`) — plus a leading `~/` that matches any user's home structurally (`/home/<user>/…` or `/Users/<user>/…`, so one entry covers a multi-OS fleet). Separators normalize to `/` and comparison is case-insensitive (over-match is the safe direction); invalid entries (relative, `**` mid-path) are dropped at boot with a warning naming them. Every nightly delivery carries the session's workspace path (`workspace_path`) plus the relayed workspace-marker content (`client_marker`, see `confidentialMarkerKey` below), and the path is stored on the row — so `hicortex backfill-privacy` reports and stamps history **per pattern** too (rows stored before the column exists have no path and are never path-matched). Prefer marking a folder right where you are? `hicortex confidential` (optionally `[path]`, `--off` to unmark) writes a local `.hicortex-confidential` marker carrying the server's `confidentialMarkerKey` — and provisions that key itself (see the next row); the nightly relays the marker's content and the server validates it. Add the folder here to backfill its history. **Empty by default = zero change.** Boot-time (restart to apply) |
284
+ | `confidentialMarkerKey` | The owner-set key a workspace marker must carry (#614): `hicortex confidential` writes it into the `.hicortex-confidential` marker file (single line), the nightly relays that content as `client_marker`, and the server stamps `confidential` only when the content **matches this key** — compared timing-safe, server-side, at intake. This closes the client-writable classification channel: the pre-#614 empty marker (and the `client_confidential` boolean) let any capture client mark its own deliveries confidential, and a client sending `client_confidential: true` without valid marker content is now ignored. **Provisioned by that very command (#616) — no manual key mirroring**: on a machine with no local key the command fetches the server's existing key, or generates one and registers it there (`GET`/`PUT /confidential/marker-key`, token-gated), then caches it in this machine's `~/.hicortex/config.json` for offline reuse; `confidential --key <value>` rotates (the server applies the new key to the next delivery, no restart; markers carrying a previous key then stamp standard). An env or config key already on the machine is used as-is, no server contact; the command refuses when no key exists AND no server is reachable. **Absent/blank (default) = markers are INERT, fail-closed both directions** — marker-carrying deliveries stamp standard, and a boot note names the key when the circle is otherwise active. Operators can still set it by hand: config (restart to apply) or the env mirror `HICORTEX_CONFIDENTIAL_MARKER_KEY`, which overrides config — and while that env is set on the server, rotation PUTs answer `409` instead of shadow-writing |
285
+ | `llmConfidentialBaseUrl` | The confidential model's endpoint (#332). With `llmConfidentialApiKey` (both required; `llmConfidentialModel` optional; `llmConfidentialProvider` selects the dialect like `llmProvider`), a second model handles **every** LLM touch of confidential text — distillation, importance scoring, reflection, contradiction checks, domain classification, reconsolidation verdicts. Env mirrors: `HICORTEX_LLM_CONFIDENTIAL_BASE_URL`/`_API_KEY`/`_MODEL` |
286
+ | `llmConfidentialApiKey` | The confidential model's API key (see `llmConfidentialBaseUrl`). **When the circle is active but this pair is unset, confidential work HOLDS**: queued deliveries stay in the distill inbox (standard deliveries keep draining) and sync-mode deliveries answer 503 — nothing confidential ever touches the main model, and a loud boot warning names the exposure |
287
+ | `llmConfidentialModel` | The confidential model's id (see `llmConfidentialBaseUrl`) |
288
+ | `llmConfidentialProvider` | Explicit request dialect for the confidential model's OpenAI-compatible path (the `llmProvider` precedent; today only `"azure"`). Absent/empty → detected from the base URL |
289
+ | `captureCooldownHours` | Success-cooldown (hours) for **manual capture-watchdog runs** (`nightly --watchdog`, 0.17 #239). The watchdog *timer* was retired (#596) — obsolete since the distill queue (#529): distillation runs on the server's scheduled drains, so capture-arrival latency serves nothing, and capture now lives in the nightly's capture phase (no separate capture timer exists). When the flag is run manually, it captures only if more than this has elapsed since the last *successful* capture (`state.lastNightly`). Default `6` |
282
290
  | `firstRunLookbackDays` | Days of session history the FIRST nightly run discovers (default `7`). A long-term AI user's entire session store is deliberately not distilled on night one — the first watermark is `now − this many days`, not the beginning of time. Already-running installs are unaffected (they have a real watermark). To import more history, run `hicortex nightly --recapture-window <days>` once — widening-only, per-session cursors keep the re-scan cheap. Invalid value → warn + default (#436) |
283
291
  | `recallCrossProjectMinSimilarity` | The cross-project recall fence bar (default `0.72`, fence **ON when the key is absent**). When a recall or search request carries a project, a memory from a *different* project must clear this similarity on a measured cosine to be admitted — pushed recall (`/recall-index`), `GET /search`, and the `hicortex_search` tool all fence identically; same-project and unscoped recall are unchanged. `0` or any value ≤ the recall floor (`0.62`) turns the fence off (today's scope-blind behavior). Clamped to `[0,1]`; a wrong type → warn + default. Boot-time (restart to apply) |
284
- | `consolidationHours` | Hours (0–23, local) for the **consolidation** timer — the full nightly (capture + distill + score + reflect + link). Installed for **server/co-located only** (clients have no local DB). Default `[10, 22]`: the 22:00 evening slot runs after the day's capture waves (same-day results); the 10:00 morning slot runs *after* the morning capture so wake-up pushes are caught. Omitted on clients |
292
+ | `consolidationHours` | Hours (0–23, local) for the **consolidation** timer — the full nightly (capture + distill + score + reflect + link). Installed for **server/co-located only** (clients have no local DB). Default `[10, 22]`: the 22:00 evening slot distills the day's sessions the same day; the 10:00 morning slot catches the night's and the previous evening's tail. Omitted on clients |
285
293
  | `timerJitterSeconds` | Max random delay (seconds) added to **generated** consolidation timers (#256), so a fleet doesn't all fire on the same minute (thundering-herd → LLM-backend contention). systemd: a single `RandomizedDelaySec=<n>`; launchd has no native equivalent so a per-install randomized `Minute` offset is baked into every `StartCalendarInterval` dict (sub-60s values no-op on launchd). Default `3600` (≈±30 min spread on the 2-slot/day cadence); `0` disables. Affects timers on the next `init` (re-init rewrites the unit files; installs that don't re-init keep their existing timers) |
286
294
  | `nightlyTimeBudgetMinutes` | The ONE wall-clock budget (minutes) for a nightly run: capture and every consolidation stage share one cooperative deadline, checked at safe boundaries (capture segments, stage boundaries, item loops, the merge zone). A run whose deadline fires reports consolidation `deferred` and resumes from its cursors next run — no work lost, none redone. Default `240`; `0`/invalid → default (a deadline always exists — there is no "off"). The systemd unit's `TimeoutStartSec` is derived from this (+60 min slack) at `init` |
287
295
  | `nightlyLlmCallBudget` | The ONE per-run ceiling on LLM calls across the whole pipeline. Consumed in run order — a stage that exhausts it defers its remainder via its cursor. Bounds money/load independent of latency: a fast metered or capacity-limited endpoint permits thousands of calls inside the wall-clock budget, so time alone cannot protect it. Default `5000`; `0`/invalid → default. `consolidateMaxLlmCalls` is a **deprecated alias** (honored one release when the new key is absent — rename it) |
@@ -895,6 +895,18 @@
895
895
  .cap-stale{ color:var(--amber); margin-left:5px; }
896
896
  .cap-qrow .fill.warn{ background:var(--amber); }
897
897
  .cap-qrow.stale .cap-dot{ background:var(--amber); }
898
+ /* #601: the confidential-circle pill — the #593 chip language in the amber
899
+ family (restricted, not error — never red). One pill metric shared by the
900
+ Fleet rail (legend chip, bundle cards, context rows) and the capture
901
+ card's rows; standard agents render NO badge (honest absence). */
902
+ .conf-pill{ flex:none; display:inline-flex; align-items:center; justify-content:center; line-height:0; padding:3px; border-radius:999px; white-space:nowrap; color:var(--amber); background:color-mix(in srgb, var(--amber) 13%, transparent); }
903
+ .conf-pill svg{ display:block; width:10px; height:10px; stroke:var(--amber); fill:none; stroke-width:1.8; }
904
+ /* #601: the rail-header legend host — pushed right inside the .col-head;
905
+ [hidden] must win over the header's flex (author display beats the UA's
906
+ hidden — the .cap-qrow idiom) so no-roster / pre-#601 servers show
907
+ nothing. */
908
+ #ag-circle{ margin-left:auto; }
909
+ #ag-circle[hidden]{ display:none; }
898
910
 
899
911
  /* ================= the memory dropdown — opens UNDER the left search ================= */
900
912
  #panel{
@@ -1426,7 +1438,7 @@
1426
1438
 
1427
1439
  <!-- the agents rail — the only thing beside the brain -->
1428
1440
  <aside id="agentscol" aria-label="Connected agents">
1429
- <div class="col-head"><span class="t">Fleet</span><small id="ag-sub">0 &middot; auto-detected</small></div>
1441
+ <div class="col-head"><span class="t">Fleet</span><small id="ag-sub">0 &middot; auto-detected</small><span id="ag-circle" hidden></span></div>
1430
1442
  <div id="ag-list"></div>
1431
1443
  <!-- #506: the fleet rail's + connect-an-agent drawer lived here — REMOVED
1432
1444
  (owner 2026-09-24). Both surviving connect entries (the account-menu
@@ -4027,6 +4039,56 @@ function agoLabel(iso){
4027
4039
  const hrs=Math.max(0,(Date.now()-t)/3.6e6);
4028
4040
  return hrs<48?Math.round(hrs)+'h ago':Math.round(hrs/24)+'d ago';
4029
4041
  }
4042
+ /* ---------- #601: the confidential circle — fleet.circle rides the same
4043
+ /dashboard/data payload (ALWAYS present; roster [] when nothing is
4044
+ configured). VISIBILITY ONLY: the dashboard stays ungated (confidential
4045
+ content remains visible here — the standing ruling); standard agents
4046
+ render NO badge (honest absence — red would read as error, amber reads as
4047
+ restricted). D.fleet.circle is ABSENT on a pre-#601 server → every helper
4048
+ degrades to the exact prior rendering. members is keyed by the OBSERVED
4049
+ source_agent ids (the server already ran the roster match — membership is
4050
+ key presence, the value the confidential count). ---------- */
4051
+ function circleBlock(){
4052
+ return (D&&D.fleet&&D.fleet.circle)?D.fleet.circle:null;
4053
+ }
4054
+ /** The confidential count for one observed source_agent id — null when the
4055
+ id is not a circle member (not a members key). */
4056
+ function circleCount(agentId){
4057
+ const c=circleBlock();
4058
+ if(!c||typeof agentId!=='string'||!c.members) return null;
4059
+ const n=Object.prototype.hasOwnProperty.call(c.members,agentId)?c.members[agentId]:null;
4060
+ return typeof n==='number'?n:null;
4061
+ }
4062
+ /** Per-agent pill — '' for standard agents (no markup at all); the meaning
4063
+ and the count live in the tooltip (tech detail in tooltips). */
4064
+ function circlePill(agentId){
4065
+ const n=circleCount(agentId);
4066
+ if(n===null) return '';
4067
+ return '<span class="conf-pill" title="Inner circle — this agent\'s captures are confidential, hidden from other agents\' recall · '+n+' confidential '+(n===1?'memory':'memories')+'">confidential</span>';
4068
+ }
4069
+ /** Bundle-level pill (rail card header / capture rows) — the tooltip names
4070
+ every member agent + its count; '' when none of the ids are members. */
4071
+ function circleBundlePill(ids){
4072
+ if(!Array.isArray(ids)) return '';
4073
+ const hits=[];
4074
+ for(const id of ids){
4075
+ const n=circleCount(id);
4076
+ if(n!==null) hits.push(id+' ('+n+')');
4077
+ }
4078
+ if(!hits.length) return '';
4079
+ return '<span class="conf-pill" role="img" aria-label="confidential bundle" title="Confidential circle agents in this bundle: '+esc(hits.join(', '))+'"><svg viewBox="0 0 12 12" aria-hidden="true"><rect x="2.2" y="5.2" width="7.6" height="5.6" rx="1.2"/><path d="M4 5.2V3.8a2 2 0 0 1 4 0v1.4"/></svg></span>';
4080
+ }
4081
+ /** The rail-header legend chip — null when no roster exists (nothing
4082
+ rendered, honest empty state); the tooltip carries the ROSTER itself plus
4083
+ the capturing members (the issue's presence rule: the roster is visible
4084
+ somewhere minimal). */
4085
+ function circleLegend(){
4086
+ const c=circleBlock();
4087
+ if(!c||!Array.isArray(c.roster)||!c.roster.length) return null;
4088
+ const capturing=Object.keys(c.members||{});
4089
+ const title='Confidential circle — amber pills mark agents whose captures are confidential, visible only to circle members (this dashboard shows everything). Roster ('+c.roster.length+'): '+c.roster.join(', ')+(capturing.length?' · capturing: '+capturing.join(', '):'');
4090
+ return {html:'<span class="conf-pill" role="img" aria-label="confidential agent" title="'+esc(title)+'"><svg viewBox="0 0 12 12" aria-hidden="true"><rect x="2.2" y="5.2" width="7.6" height="5.6" rx="1.2"/><path d="M4 5.2V3.8a2 2 0 0 1 4 0v1.4"/></svg></span>', title};
4091
+ }
4030
4092
  function buildCapture(){
4031
4093
  const host=el('cap-rows');
4032
4094
  host.innerHTML='';
@@ -4072,11 +4134,14 @@ function buildCapture(){
4072
4134
  const harness=agent.split('/')[0]||agent;
4073
4135
  const key=(r.machine||'')+'|'+harness;
4074
4136
  let g=groups.get(key);
4075
- if(!g){ g={machine:r.machine||null, harness, posts:0, sessions:0, bytes:0, held:0, retried:0, agents:[]}; groups.set(key,g); }
4137
+ if(!g){ g={machine:r.machine||null, harness, posts:0, sessions:0, bytes:0, held:0, retried:0, agents:[], ids:[]}; groups.set(key,g); }
4076
4138
  g.posts+=r.posts||0; g.sessions+=r.sessions||0; g.bytes+=r.bytes||0;
4077
4139
  g.held+=r.held||0; g.retried+=r.retried||0;
4078
4140
  g.agents.push(agent+' — '+r.posts+' post'+(r.posts===1?'':'s')+' · '+r.sessions+' sess · '+mbFmt(r.bytes||0)
4079
4141
  +(r.held?' · '+r.held+' held':'')+(r.retried?' · '+r.retried+' retried':''));
4142
+ /* #601: the raw agent id rides alongside the display line — the circle
4143
+ pill matches observed ids, never the formatted tooltip text */
4144
+ g.ids.push(agent);
4080
4145
  }
4081
4146
  /* newest-night secondary: per-bundle sessions + held off capture_health
4082
4147
  rows (the newest day with rows). held keys the badge — a held post is
@@ -4098,6 +4163,9 @@ function buildCapture(){
4098
4163
  const pausedKeys=fleetPausesByKey();
4099
4164
  for(const g of gs2){
4100
4165
  const n=night.get((g.machine||'')+'|'+g.harness);
4166
+ /* #601: the bundle's circle member ids (observed × roster) feed the
4167
+ tooltip note + the amber pill in the .st cluster */
4168
+ const confIds=(g.ids||[]).filter(id=>circleCount(id)!==null);
4101
4169
  const row=document.createElement('div');
4102
4170
  row.className='cap-row2';
4103
4171
  const label=g.machine?g.machine+' · '+g.harness:g.harness;
@@ -4107,6 +4175,7 @@ function buildCapture(){
4107
4175
  +(g.retried>0?' · '+g.retried+' retried in window':'')
4108
4176
  +(n?' · '+nightLabel+': '+n.sessions+' sess'+(n.held>0?' ('+n.held+' held)':''):'')
4109
4177
  +(paused?' · CAPTURE PAUSED (posts are skipped — sessions are not backfilled)':'')
4178
+ +(confIds.length?' · confidential circle: '+confIds.join(', '):'')
4110
4179
  +':\n'+g.agents.join('\n');
4111
4180
  row.innerHTML='<span class="cap-dot"></span>'+
4112
4181
  '<span class="hn" title="'+esc(label)+'">'+esc(label)+'</span>'+
@@ -4114,6 +4183,7 @@ function buildCapture(){
4114
4183
  '<span class="st"><b>'+fmt(g.sessions)+'</b> sess · '+mbFmt(g.bytes)
4115
4184
  +(paused?'<span class="cap-paused" title="capture paused — posts are skipped (200) and sessions are not backfilled">PAUSED</span>':'')
4116
4185
  +(n&&n.held>0?'<span class="cap-held" title="'+nightLabel+' — failed posts the client will retry — cursor held">&#9888; '+n.held+' held</span>':'')
4186
+ +circleBundlePill(g.ids)
4117
4187
  +'</span>'
4118
4188
  /* the newest-night sub-line — a full-basis flex child, so it wraps
4119
4189
  UNDER the primary line (the suffix never fits beside it; see the
@@ -4135,16 +4205,21 @@ function buildCapture(){
4135
4205
  const harness=agent.split('/')[0]||agent;
4136
4206
  const key=(r.machine||'')+'|'+harness;
4137
4207
  let g=groups.get(key);
4138
- if(!g){ g={machine:r.machine||null, harness, posts:0, sessions:0, bytes:0, held:0, retried:0, agents:[]}; groups.set(key,g); }
4208
+ if(!g){ g={machine:r.machine||null, harness, posts:0, sessions:0, bytes:0, held:0, retried:0, agents:[], ids:[]}; groups.set(key,g); }
4139
4209
  g.posts+=r.posts||0; g.sessions+=r.sessions||0; g.bytes+=r.bytes||0;
4140
4210
  g.held+=r.held||0; g.retried+=r.retried||0;
4141
4211
  g.agents.push(agent+' — '+r.posts+' post'+(r.posts===1?'':'s')+' · '+r.sessions+' sess · '+mbFmt(r.bytes||0)
4142
4212
  +(r.held?' · '+r.held+' held':'')+(r.retried?' · '+r.retried+' retried':''));
4213
+ /* #601: the raw agent id rides alongside the display line — the circle
4214
+ pill matches observed ids, never the formatted tooltip text */
4215
+ g.ids.push(agent);
4143
4216
  }
4144
4217
  const gs2=[...groups.values()].sort((a,b)=>b.bytes-a.bytes);
4145
4218
  const maxB=gs2[0].bytes;
4146
4219
  const pausedKeys=fleetPausesByKey();
4147
4220
  for(const g of gs2){
4221
+ /* #601: circle member ids — tooltip note + pill (same as the window branch) */
4222
+ const confIds=(g.ids||[]).filter(id=>circleCount(id)!==null);
4148
4223
  const row=document.createElement('div');
4149
4224
  row.className='cap-row2';
4150
4225
  const label=g.machine?g.machine+' · '+g.harness:g.harness;
@@ -4153,6 +4228,7 @@ function buildCapture(){
4153
4228
  +(paused?' · CAPTURE PAUSED (posts are skipped — sessions are not backfilled)':'')
4154
4229
  +(g.held>0?' · '+g.held+' held (failed posts the client will retry — cursor held)':'')
4155
4230
  +(g.retried>0?' · '+g.retried+' retried':'')
4231
+ +(confIds.length?' · confidential circle: '+confIds.join(', '):'')
4156
4232
  +':\n'+g.agents.join('\n');
4157
4233
  row.innerHTML='<span class="cap-dot"></span>'+
4158
4234
  '<span class="hn" title="'+esc(label)+'">'+esc(label)+'</span>'+
@@ -4160,6 +4236,7 @@ function buildCapture(){
4160
4236
  '<span class="st"><b>'+fmt(g.sessions)+'</b> sess · '+mbFmt(g.bytes)
4161
4237
  +(paused?'<span class="cap-paused" title="capture paused — posts are skipped (200) and sessions are not backfilled">PAUSED</span>':'')
4162
4238
  +(g.held>0?'<span class="cap-held" title="failed posts the client will retry — cursor held">&#9888; '+g.held+' held</span>':'')
4239
+ +circleBundlePill(g.ids)
4163
4240
  +'</span>';
4164
4241
  host.appendChild(row);
4165
4242
  }
@@ -4173,6 +4250,9 @@ function buildCapture(){
4173
4250
  const totalMem=gs.reduce((a,g)=>a+g.mem,0);
4174
4251
  const pausedKeys=fleetPausesByKey();
4175
4252
  for(const g of gs){
4253
+ /* #601: circle member ids — tooltip note + pill (same as the live branches) */
4254
+ const ctxIds=g.contexts.map(c=>c.id);
4255
+ const confIds=ctxIds.filter(id=>circleCount(id)!==null);
4176
4256
  const row=document.createElement('div');
4177
4257
  row.className='cap-row2';
4178
4258
  const label=bundleLabel(g);
@@ -4184,12 +4264,14 @@ function buildCapture(){
4184
4264
  row.title=label+' — '+fmt(g.mem)+' memories across '+g.contexts.length
4185
4265
  +' context'+(g.contexts.length===1?'':'s')+(g.machine?'':' (pre-machine-stamp captures)')
4186
4266
  +(paused?' · CAPTURE PAUSED (posts are skipped — sessions are not backfilled)':'')
4267
+ +(confIds.length?' · confidential circle: '+confIds.join(', '):'')
4187
4268
  +':\n'+tail;
4188
4269
  row.innerHTML='<span class="cap-dot"></span>'+
4189
4270
  '<span class="hn" title="'+esc(label)+'">'+esc(label)+'</span>'+
4190
4271
  '<span class="cap-bar"><span class="fill" style="width:'+(g.mem/Math.max(totalMem,1)*100)+'%"></span></span>'+
4191
4272
  '<span class="st"><b>'+g.contexts.length+'</b> ctx · '+fmt(g.mem)+' mem'
4192
4273
  +(paused?'<span class="cap-paused" title="capture paused — posts are skipped (200) and sessions are not backfilled">PAUSED</span>':'')
4274
+ +circleBundlePill(ctxIds)
4193
4275
  +'</span>';
4194
4276
  host.appendChild(row);
4195
4277
  }
@@ -4209,6 +4291,13 @@ function lastNightByAgent(){
4209
4291
  }
4210
4292
  function buildAgents(){
4211
4293
  const listEl=el('ag-list'); listEl.innerHTML='';
4294
+ /* #601: the circle legend rides the rail header — rendered BEFORE the
4295
+ no-contexts early return (the circle exists even with no contexts yet);
4296
+ no roster / pre-#601 server → hidden, no markup (honest absence) */
4297
+ const legendEl=el('ag-circle');
4298
+ const legend=circleLegend();
4299
+ if(legend){ legendEl.innerHTML=legend.html; legendEl.title=legend.title; legendEl.hidden=false; }
4300
+ else{ legendEl.innerHTML=''; legendEl.title=''; legendEl.hidden=true; }
4212
4301
  const gs=contextGroups();
4213
4302
  /* #506: the "below" target (the rail drawer) is gone — the empty state
4214
4303
  points at the one remaining connect surface, the account menu */
@@ -4239,6 +4328,7 @@ function buildAgents(){
4239
4328
  (presence?'<span class="presence '+presence.cls+'" title="'+presence.label+' — last seen '+agoLabel(seen.last_seen)+' ('+(seen.last_outcome||'?')+' /distill)"></span>':'')+
4240
4329
  '<span class="ag-main"><b>'+esc(g.harness)+'</b>'+
4241
4330
  '<small>'+esc(bundleLabel(g))+' · '+g.contexts.length+' context'+(g.contexts.length===1?'':'s')+' · '+fmt(g.mem)+' memories</small></span>'+
4331
+ circleBundlePill(g.contexts.map(c=>c.id))+
4242
4332
  (fleetOk?'<button type="button" class="ag-pause" title="capture pause for '+esc(bundleLabel(g))+' — sessions while paused are NOT captured and will not be backfilled">'+(paused?'resume capture':'pause capture')+'</button>':'')+
4243
4333
  '</div>'+
4244
4334
  '<div class="last-night" title="last complete night: learned / enriched / merged (all '+esc(g.harness)+' contexts on '+esc(machineLabel(g)||'this store')+')">'+
@@ -4269,6 +4359,7 @@ function buildAgents(){
4269
4359
  const note=machineNote(c.machines);
4270
4360
  if(note) row.title=c.name+note; // property assignment — no HTML escaping needed
4271
4361
  row.innerHTML='<span class="cn">'+esc(c.name)+'<small>'+esc(c.id)+'</small></span>'+
4362
+ circlePill(c.id)+
4272
4363
  '<span class="cc">'+fmt(c.count)+' mem</span>';
4273
4364
  row.onclick=(e)=>{ e.stopPropagation(); selected=c; renderCtxList(); openContext(c); wake(); };
4274
4365
  listBox.appendChild(row);
@@ -4278,6 +4369,7 @@ function buildAgents(){
4278
4369
  detail.hidden=false;
4279
4370
  detail.innerHTML=
4280
4371
  '<div class="ctx-head"><b>'+esc(c.name)+'</b><small>'+esc(c.id)+'</small>'+
4372
+ circlePill(c.id)+
4281
4373
  '<span class="idscope" title="identity scope — applies immediately · survives restart">'+
4282
4374
  ['override','global','off'].map(m=>'<button type="button" class="idpill seg '+m+'" data-mode="'+m+'" aria-pressed="false">'+m+'</button>').join('')+
4283
4375
  '</span></div>'+
@@ -0,0 +1,109 @@
1
+ /**
2
+ * `hicortex backfill-privacy` (#332) — one-shot classification stamping for
3
+ * EXISTING rows, by source agent, and (#609) by workspace path.
4
+ *
5
+ * The intake derivation stamps every NEW delivery; this command heals history
6
+ * when the roster or the path patterns change (an agent joins the circle, a
7
+ * folder is listed, or the feature lands on a store that already has captures
8
+ * from a now-covered birthplace). The plan is a pure function of the config ×
9
+ * the rows' stored values:
10
+ * - every memories/distill_queue row whose source_agent matches the roster
11
+ * (isConfidentialSourceAgent — the same `<harness>/`-stripping matcher the
12
+ * intake uses) AND whose privacy != 'confidential' → stamped confidential;
13
+ * - #609: every row whose stored `workspace_path` matches a
14
+ * `confidentialPaths` pattern (the same pure matcher the intake uses),
15
+ * grouped per pattern. NULL-path rows are NEVER path-matched (pre-v28
16
+ * rows have no path by construction; they are reported as unmatched, not
17
+ * silently stamped). A row matching both a rostered agent and a pattern
18
+ * flips once (agent groups claim it first; each remaining row joins its
19
+ * first matching pattern so overlapping patterns never double-count);
20
+ * - NOTHING is ever stamped BACK to standard (a roster/pattern removal is
21
+ * not a demotion — memories stay confidential until the operator
22
+ * explicitly changes them; re-running with a smaller config is a no-op by
23
+ * design).
24
+ *
25
+ * Safety rails (the `hicortex dedup` / `reconcile-projects` pattern): dry run
26
+ * by default (report only, zero writes); `--apply` takes a pre-apply DB
27
+ * backup (abort all writes on failure), the single-flight capture lock
28
+ * (waitMs 0 — busy aborts), and stamps in ONE transaction. The queue rows are
29
+ * stamped too: a pre-upgrade queued segment from a covered birthplace would
30
+ * otherwise distill as standard (migration v27 normalized it) — the backfill
31
+ * closes that seam.
32
+ *
33
+ * Idempotent by construction: a second run finds every covered row already
34
+ * confidential and reports zero.
35
+ */
36
+ import type Database from "better-sqlite3";
37
+ import { acquireCaptureLock } from "./capture.js";
38
+ import { type ConfidentialPathPattern } from "./classification.js";
39
+ /** One planned stamp group: rows from one rostered source agent, or (#609)
40
+ * from one confidentialPaths pattern. */
41
+ export interface BackfillGroup {
42
+ /**
43
+ * The DISTINCT source_agent value as stored (not the roster entry) — or,
44
+ * for a #609 path group, the pattern's raw config entry (display label).
45
+ */
46
+ sourceAgent: string;
47
+ /** Rows in `memories` that would flip to confidential. */
48
+ memoryRows: number;
49
+ /** Rows in `distill_queue` that would flip (distill as confidential). */
50
+ queuedRows: number;
51
+ /**
52
+ * #609: the pattern this group matches — present on path groups only.
53
+ * Path groups stamp by exact row ids (the matcher is JS-side; SQL cannot
54
+ * express the three pattern forms); agent groups leave these unset and
55
+ * stamp by the source_agent predicate.
56
+ */
57
+ pattern?: ConfidentialPathPattern;
58
+ memoryIds?: string[];
59
+ queuedIds?: number[];
60
+ }
61
+ export interface BackfillReport {
62
+ dryRun: boolean;
63
+ /** The roster entries the plan matched (subset of confidentialAgents). */
64
+ roster: string[];
65
+ /** #609: the resolved confidentialPaths entries (raw strings). */
66
+ patterns: string[];
67
+ /** Planned/executed stamp groups, largest first. */
68
+ groups: BackfillGroup[];
69
+ /** Total rows that would flip / flipped. */
70
+ totalMemories: number;
71
+ totalQueued: number;
72
+ /** --apply only: rows actually stamped (memories). */
73
+ appliedMemories?: number;
74
+ /** --apply only: queue rows actually stamped. */
75
+ appliedQueued?: number;
76
+ /** --apply only: path to the pre-apply backup. */
77
+ backupPath?: string;
78
+ /** --apply only: the capture lock was busy — zero writes, retried later. */
79
+ lockBusy?: boolean;
80
+ }
81
+ export interface BackfillOptions {
82
+ /** Execute the stamps. Default false = dry run (report only, zero writes). */
83
+ apply?: boolean;
84
+ /** DB path override (tests / snapshot verification). Defaults to resolveDbPath(). */
85
+ dbPath?: string;
86
+ /** State dir override (tests). Defaults to ~/.hicortex. */
87
+ stateDir?: string;
88
+ /** Config override (tests). Defaults to reading stateDir/config.json. */
89
+ config?: Record<string, unknown> | null;
90
+ /** Capture-lock acquirer override (tests). Defaults to the real capture.ts lock. */
91
+ acquireLock?: typeof acquireCaptureLock;
92
+ }
93
+ /**
94
+ * The pure plan: which stored source_agent values match the roster, and how
95
+ * many of their rows are not yet confidential. Roster matching uses the
96
+ * INTAKE matcher (isConfidentialSourceAgent — `<harness>/`-stripping) so the
97
+ * backfill and the intake can never disagree about who is rostered. #609 adds
98
+ * the per-pattern groups (see planPathGroups) alongside the agent groups —
99
+ * same rails, same never-demotes rule.
100
+ */
101
+ export declare function planBackfill(db: Database.Database, roster: string[], patterns?: ConfidentialPathPattern[]): BackfillGroup[];
102
+ /**
103
+ * Run `hicortex backfill-privacy`. Dry run by default (options.apply falsy) —
104
+ * plan + report only, zero writes. `options.apply` executes: backup, capture
105
+ * lock, ONE transaction stamping every planned row in BOTH tables. A busy
106
+ * lock is an abort (reported as `lockBusy: true`, never a wait); a failed
107
+ * backup aborts all writes (throw, like dedup/reconcile-projects).
108
+ */
109
+ export declare function runBackfillPrivacy(options?: BackfillOptions): Promise<BackfillReport>;