brain-memory 0.1.0-beta.34 → 0.1.0-beta.36

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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,80 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.1.0-beta.36] - 2026-08-07
10
+
11
+ ### Added
12
+
13
+ - **Trust-weighted recall — origin now decides how far a memory's score can
14
+ reach.** beta.34 labelled every write with an origin and capped what
15
+ untrusted origins may claim; this release closes the read side. Recall
16
+ multiplies each memory's composite score by an origin trust factor (`user`
17
+ 1.0, `agent-inferred` 0.95, `tool-output` 0.85, `external` 0.75), and
18
+ spreading-activation *sources* are damped by the same factor — so a clique
19
+ of co-tagged planted memories (which auto-link through tag overlap) cannot
20
+ amplify itself past something the user said directly. Trust bounds volume,
21
+ not relevance: a genuinely more relevant external memory can still win; it
22
+ just can't win on bulk. Missing origin weighs as the memorize default, so
23
+ pre-provenance brains rank exactly as before.
24
+ - **Low-trust results are visibly marked.** `brain recall` and
25
+ `brain session-start` return `origin` and a `low_trust` flag on every
26
+ result, and receipts for `tool-output`/`external` memories carry a trailing
27
+ warning — `◉ memory: "…" (learning, 3d ago, ⚠ external)` — so a fact
28
+ absorbed from a web page can never quietly pass as something you said.
29
+ Trusted receipts are byte-identical to the existing format.
30
+ - **Connector: `brain_memorize` accepts `origin`.** The remote MCP tool passes
31
+ a validated origin through to the engine, with tool-description guidance
32
+ that `user` is reserved for facts the human explicitly stated or asked to
33
+ remember.
34
+ - **`brain restore` — an undo button for the whole brain.**
35
+ `brain restore --list` shows restore points; `--to <point>` rolls
36
+ `~/.brain/` back to one. Two sources: the Git sync history
37
+ (`--from git`, default — one point per push) and Brain Cloud's server-side
38
+ pre-push snapshots (`--from cloud`, listed via the new
39
+ `GET /api/brains/{id}/versions` endpoint). Every restore is undoable:
40
+ the git path first commits the current state as a safety snapshot (unsynced
41
+ work included), the cloud path writes a local backup under
42
+ `~/.brain/.cloud/`. `audit.log` is deliberately carried *forward* through
43
+ restores — the append-only trail records history through a rollback, never
44
+ gets rolled back by one — and each restore is itself logged there.
45
+
46
+ ## [0.1.0-beta.35] - 2026-08-01
47
+
48
+ ### Added
49
+
50
+ - **`/brain:import` — cold-start a brain from transcripts your agents already
51
+ wrote.** A new brain is empty, and an empty brain is worth nothing until
52
+ something fills it; meanwhile every coding agent has been keeping months of
53
+ local history. `brain import` harvests it: session titles, user prompts,
54
+ projects, branches and edited files, with harness wrappers
55
+ (`<system-reminder>`, slash-command tags, command output), subagent sidechain
56
+ traffic, and bare acknowledgements filtered out. The digest is bounded on
57
+ three axes (sessions, prompts per session, total characters) and
58
+ round-robins across projects, so one busy repo cannot consume the whole
59
+ budget — on a real 261-session history that lifted project coverage from 5
60
+ to 13 within the same ~15k tokens.
61
+
62
+ The CLI harvests; the **agent distills**. Extracting meaning is a semantic
63
+ judgement, and making it in the CLI would mean shipping an embedding model
64
+ or calling an LLM — the two things Brain exists to avoid. So the harvester
65
+ reports facts and never infers, and distilled memories go through the
66
+ ordinary `brain memorize` path as `agent-inferred`: an import inherits the
67
+ existing provenance ceilings for free and can never pin, entrench, or
68
+ outrank something the user said directly.
69
+
70
+ Import is incremental — a cursor at `~/.brain/.import/state.json` records
71
+ which sessions have been read so re-runs offer only new ones (`--all`
72
+ overrides). `--mark` validates ids against the source's real sessions and
73
+ exits non-zero on any that match nothing: silently accepting a truncated or
74
+ mistyped id would report a session as retired while the cursor never matches
75
+ it, re-offering that session forever. Scope with `--project`,
76
+ `--since 30d|6m|2026-01-01`, `--limit`.
77
+ `brain import --sources` lists detected history stores. `brain import` only
78
+ ever reads and prints; no memory is written without the agent.
79
+
80
+ Claude Code is the first source adapter; the registry in `src/harvest.js`
81
+ takes additional agents without changes downstream.
82
+
9
83
  ## [0.1.0-beta.34] - 2026-07-26
10
84
 
11
85
  ### Added
package/README.md CHANGED
@@ -41,6 +41,7 @@ Existing AI memory solutions use flat databases with tag-based retrieval. Brain
41
41
  - **Git-friendly** — Full version history of how memories evolve
42
42
  - **Strength + decay** — Recalled memories get stronger, forgotten ones fade. Just like your brain
43
43
  - **Recall receipts** — Memory that visibly fires: every answer shaped by a memory ends with a one-line attributable receipt (`◉ memory: "<title>" (<type>, <age>)`), minted by the engine so it can't be hallucinated
44
+ - **Provenance-bounded trust** — Every memory records where it came from (`user`, `agent-inferred`, `tool-output`, `external`), and recall weighs it: a fact planted by a web page or tool output is down-ranked, flagged `low_trust`, marked `⚠` on its receipt, and can never outrank what you said directly — no matter how many copies of it get written
44
45
  - **Associative network** — Memories link to each other with weighted connections. Recalling one activates related ones automatically
45
46
  - **Context-dependent recall** — Memories encoded in a similar context to the current session are scored higher
46
47
  - **Spaced reinforcement** — Memories recalled after longer intervals get bigger boosts, cramming produces diminishing returns
@@ -242,10 +243,27 @@ The everyday loop is **ambient** — `remember` and `memorize` run automatically
242
243
  | `/brain:status` | Dashboard with brain health metrics and recommendations |
243
244
  | `/brain:pin [id\|query]` | Pin a memory to the always-present tier — loads every session, never decays. Toggles: also unpins (`--off`) |
244
245
  | `/brain:forget [target]` | Decay, archive, or remove memories. `--deep` performs forensic erasure — traces and removes every reference |
246
+ | `/brain:import [--project P] [--since 30d]` | Cold-start a new brain from transcripts your agents already wrote. Incremental — safe to re-run |
245
247
  | `/brain:sync [subcommand]` | Sync via Brain Cloud, Git remote, or export/import (auto-initializes the brain on first run) |
246
248
  | `/brain:skills [list\|show\|add\|use\|remove\|export]` | Manage procedural skills — reusable how-to workflows with progressive disclosure |
247
249
  | `/brain:sleep [scope]` | Full maintenance cycle — 9 neuroscience-inspired phases (replay, consolidation, review reinforcement, pruning, dreaming, …). Usually runs automatically/in the background |
248
250
 
251
+ ## Cold Start
252
+
253
+ A new brain is empty, and an empty brain is worth nothing until something fills it. But your agents have been keeping local transcripts for months — decisions, preferences, corrections, conventions. `/brain:import` reads them.
254
+
255
+ ```bash
256
+ brain import --sources # what history exists on this machine
257
+ brain import --project my-app # digest that project's past sessions
258
+ brain import --since 30d # or scope by time
259
+ ```
260
+
261
+ The split matters. The CLI **harvests** — deterministic, budget-bounded, no model call: it extracts session titles, user prompts, projects, branches, and edited files, filters out harness noise and subagent traffic, and interleaves across projects so one busy repo can't eat the budget. The agent then **distills** that digest into memories through the ordinary `brain memorize` path.
262
+
263
+ That split is deliberate. Extracting meaning is a semantic judgement, and doing it in the CLI would mean shipping an embedding model or calling an LLM — the two things Brain exists to avoid. So the harvester reports facts and never infers, and every imported memory lands as `agent-inferred` provenance: it inherits the existing ceilings for free, and **an import can never pin, entrench, or outrank something you said directly.**
264
+
265
+ Import is incremental. A cursor in `~/.brain/.import/state.json` records which sessions have been read, so re-running only offers new ones (`--all` overrides). Nothing is written without you — `brain import` only ever reads and prints.
266
+
249
267
  ## Session Lifecycle
250
268
 
251
269
  Brain Memory works automatically in the background — no commands needed for basic context awareness.
@@ -605,6 +623,17 @@ export BRAIN_DIR="$HOME/Google Drive/brain" # or Dropbox, iCloud Drive, OneDri
605
623
 
606
624
  For one-off transfers, use `/brain:sync export` and `/brain:sync import <path>`.
607
625
 
626
+ **Restore — an undo button for your whole brain.** Every push is a restore point, and the CLI can roll the entire brain back to any of them:
627
+
628
+ ```bash
629
+ brain restore --list # list restore points (the Git sync history)
630
+ brain restore --to <commit> # roll ~/.brain/ back to that point
631
+ brain restore --list --from cloud # list Brain Cloud's pre-push snapshots
632
+ brain restore --to <version> --from cloud # restore from a cloud snapshot
633
+ ```
634
+
635
+ Before touching anything, restore preserves your *current* state — the Git path commits it as a safety snapshot, the cloud path writes a local backup under `~/.brain/.cloud/` — so a restore is always undoable, even for work you never pushed. (Brain Cloud also snapshots the brain it's about to replace on every push, server-side.) The append-only `audit.log` is carried forward through restores (never rolled back), and every restore is itself logged there. Restore granularity follows push frequency: push often for finer-grained history.
636
+
608
637
  Sync state is stored locally in `~/.brain/.sync/` and is never pushed to the remote.
609
638
 
610
639
  ### Brain in Claude apps (web & mobile) — beta
package/bin/brain.js CHANGED
@@ -33,6 +33,8 @@ const DELEGATED = {
33
33
  pin: 'pin.js',
34
34
  unpin: 'unpin.js',
35
35
  skill: 'skill.js',
36
+ import: 'import.js',
37
+ restore: 'restore.js',
36
38
  };
37
39
 
38
40
  // install.js finds its positional subcommand from process.argv itself, so it is
@@ -59,8 +61,19 @@ Memory
59
61
  session-start [--project P] [--task T] [--top N]
60
62
  Budget-bounded startup payload (agent-invoked)
61
63
 
64
+ Cold start
65
+ import [--source S] [--project P] [--since 30d] [--limit N] [--all]
66
+ Digest past agent transcripts into import candidates
67
+ import --sources List detected agent history stores
68
+ import --mark <id> [<id>...]
69
+ Record sessions as imported (incremental cursor)
70
+
62
71
  Sync
63
72
  cloud <login|logout|push|pull|status>
73
+ restore --list [--from git|cloud]
74
+ List restore points (Git history or Cloud snapshots)
75
+ restore --to <point> [--from git|cloud]
76
+ Roll the whole brain back to a restore point
64
77
 
65
78
  Setup
66
79
  install Interactive installer (default when no command)
package/bin/import.js ADDED
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain import — cold-start a brain from transcripts your agents already wrote.
5
+ *
6
+ * Emits a deterministic, budget-bounded digest of past sessions. The agent reads
7
+ * that digest and writes memories through the ordinary `brain memorize` path, so
8
+ * imported memories go through the same provenance gate, scoring, and index as
9
+ * anything else. Nothing here writes a memory.
10
+ *
11
+ * Usage:
12
+ * brain import [--source claude-code] [--project P] [--since ISO] [--limit N] [--all]
13
+ * brain import --sources List detected history stores
14
+ * brain import --mark <id> [<id>...] Record sessions as imported
15
+ *
16
+ * The `--mark` step is what makes import incremental: the agent calls it after a
17
+ * successful memorize so the next run offers only new sessions.
18
+ */
19
+
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+
23
+ const { getBrainDir } = require('../src/index-manager');
24
+ const { harvest, availableSources, markImported } = require('../src/harvest');
25
+
26
+ function parseArgs(argv) {
27
+ const args = {
28
+ source: 'claude-code',
29
+ project: null,
30
+ since: null,
31
+ limit: null,
32
+ all: false,
33
+ sources: false,
34
+ mark: [],
35
+ };
36
+ for (let i = 0; i < argv.length; i++) {
37
+ switch (argv[i]) {
38
+ case '--source': args.source = argv[++i]; break;
39
+ case '--project': args.project = argv[++i]; break;
40
+ case '--since': args.since = argv[++i]; break;
41
+ case '--limit': args.limit = parseInt(argv[++i], 10) || null; break;
42
+ case '--all': args.all = true; break;
43
+ case '--sources': args.sources = true; break;
44
+ case '--mark':
45
+ // Consume every following non-flag token as a session id.
46
+ while (argv[i + 1] && !argv[i + 1].startsWith('--')) args.mark.push(argv[++i]);
47
+ break;
48
+ default: break;
49
+ }
50
+ }
51
+ return args;
52
+ }
53
+
54
+ /**
55
+ * Normalize `--since` into an ISO timestamp.
56
+ *
57
+ * Accepts a relative shorthand (`30d`, `6m`, `1y`) as well as any date string
58
+ * Date can parse, because "the last month of work" is the natural way to scope
59
+ * an import and computing that date by hand is friction.
60
+ */
61
+ function normalizeSince(value) {
62
+ if (!value) return null;
63
+ const relative = /^(\d+)([dmy])$/i.exec(value.trim());
64
+ if (relative) {
65
+ const amount = parseInt(relative[1], 10);
66
+ const date = new Date();
67
+ if (relative[2].toLowerCase() === 'd') date.setDate(date.getDate() - amount);
68
+ if (relative[2].toLowerCase() === 'm') date.setMonth(date.getMonth() - amount);
69
+ if (relative[2].toLowerCase() === 'y') date.setFullYear(date.getFullYear() - amount);
70
+ return date.toISOString();
71
+ }
72
+ const parsed = new Date(value);
73
+ if (Number.isNaN(parsed.getTime())) return null;
74
+ return parsed.toISOString();
75
+ }
76
+
77
+ function main(argv = process.argv.slice(2)) {
78
+ const args = parseArgs(argv);
79
+
80
+ if (args.sources) {
81
+ console.log(JSON.stringify({ sources: availableSources() }, null, 2));
82
+ return;
83
+ }
84
+
85
+ // A brain must exist before we offer to fill it — otherwise the agent gets a
86
+ // digest it has nowhere to write.
87
+ const brainDir = getBrainDir();
88
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
89
+ console.error(JSON.stringify({ error: 'Brain not initialized. Run `brain install` first.' }));
90
+ process.exit(1);
91
+ }
92
+
93
+ if (args.mark.length > 0) {
94
+ const result = markImported(args.source, args.mark);
95
+ console.log(JSON.stringify({
96
+ marked: args.mark.length - result.unknown.length,
97
+ ...result,
98
+ source: args.source,
99
+ ...(result.unknown.length
100
+ ? { warning: `${result.unknown.length} id(s) matched no ${args.source} session and were not recorded — check for a truncated or mistyped session id.` }
101
+ : {}),
102
+ }, null, 2));
103
+ // A partial mark is a real failure: the caller believes those sessions are
104
+ // done, and nothing else will ever tell them otherwise.
105
+ if (result.unknown.length > 0) process.exit(1);
106
+ return;
107
+ }
108
+
109
+ if (args.since && !normalizeSince(args.since)) {
110
+ console.error(JSON.stringify({ error: `Could not parse --since "${args.since}" (try 30d, 6m, or 2026-01-01)` }));
111
+ process.exit(1);
112
+ }
113
+
114
+ const digest = harvest({
115
+ source: args.source,
116
+ project: args.project,
117
+ since: normalizeSince(args.since),
118
+ limit: args.limit,
119
+ all: args.all,
120
+ });
121
+
122
+ if (digest.error) {
123
+ console.error(JSON.stringify({ error: digest.error }));
124
+ process.exit(1);
125
+ }
126
+
127
+ console.log(JSON.stringify(digest, null, 2));
128
+ }
129
+
130
+ if (require.main === module) main();
131
+
132
+ module.exports = { main, parseArgs, normalizeSince };
package/bin/memorize.js CHANGED
@@ -74,34 +74,11 @@ const COGNITIVE_ADJUSTMENTS = {
74
74
  // --- Provenance (OWASP ASI06: memory poisoning) ---
75
75
  //
76
76
  // Where a memory came from decides how much it is allowed to entrench itself.
77
- // The failure mode this defends against: content the agent *read* (an email, a
78
- // web page, a tool result) persuades it to write a fact, and that fact then
79
- // hardens — pinned into every session, exempt from decay, immune to pruning,
80
- // and never flagged as uncertain. See MemGhost (arXiv:2607.05189).
81
- //
82
- // `origin` is asserted by the caller, so it does not defend against a fully
83
- // hostile agent — but the dominant real case is an *honest* agent relaying
84
- // poisoned content, and there it holds. The pin/stable restriction is the part
85
- // that holds regardless: entrenchment is simply not reachable from this path
86
- // without an explicit user origin.
87
- const ORIGIN_POLICY = {
88
- // The user asked for this directly, in-session.
89
- user: { max_salience: 1.0, max_confidence: 1.0, allow_entrench: true, decay_multiplier: 1.0 },
90
- // The agent inferred or summarized it from session context. Default.
91
- 'agent-inferred': { max_salience: 0.6, max_confidence: 0.8, allow_entrench: false, decay_multiplier: 1.0 },
92
- // Derived from tool output — file reads, command results, MCP responses.
93
- 'tool-output': { max_salience: 0.5, max_confidence: 0.6, allow_entrench: false, decay_multiplier: 0.997 },
94
- // Derived from untrusted external content — email, web pages, issue text.
95
- external: { max_salience: 0.4, max_confidence: 0.4, allow_entrench: false, decay_multiplier: 0.99 },
96
- };
97
-
98
- // Absent origin means the agent didn't tell us — assume the weaker claim, never
99
- // the stronger one. A memory that deserves `user` is one keystroke away.
100
- const DEFAULT_ORIGIN = 'agent-inferred';
101
-
102
- // Salience >= 0.7 is exempt from auto-pruning, so every non-user ceiling sits
103
- // below it: an unattended poisoned memory must remain collectable.
104
- const PRUNE_EXEMPT_SALIENCE = 0.7;
77
+ // The policy table lives in src/provenance.js (shared with the recall-side
78
+ // trust weighting in src/scorer.js). The pin/stable restriction is the part
79
+ // that holds regardless of caller honesty: entrenchment is simply not
80
+ // reachable from this path without an explicit user origin.
81
+ const { ORIGIN_POLICY, DEFAULT_ORIGIN } = require('../src/provenance');
105
82
 
106
83
  // --- Args ---
107
84
 
package/bin/recall.js CHANGED
@@ -40,6 +40,7 @@ const {
40
40
  } = require('../src/scorer');
41
41
 
42
42
  const { receiptFor } = require('../src/receipt');
43
+ const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
43
44
 
44
45
  // Minimum relevance (or spreading bonus) for a memory to appear in explicit-
45
46
  // query results. Filters the zero/near-zero-relevance memories that would
@@ -144,6 +145,7 @@ function main() {
144
145
  const top = args.top || 10;
145
146
  const results = ranked.slice(0, top).map((mem) => {
146
147
  const title = mem.title || path.basename(mem.path, '.md');
148
+ const origin = mem.origin || DEFAULT_ORIGIN;
147
149
  return {
148
150
  id: mem.id,
149
151
  title,
@@ -155,6 +157,10 @@ function main() {
155
157
  context_match: mem.context_match,
156
158
  spreading_bonus: mem.spreading_bonus,
157
159
  confidence: mem.confidence,
160
+ // Provenance travels with every result so the agent can answer
161
+ // "where did you get that?" without opening the memory file.
162
+ origin,
163
+ ...(isLowTrust(origin) ? { low_trust: true } : {}),
158
164
  tags: mem.tags,
159
165
  // Recall receipt — the engine mints it, agents copy it verbatim when
160
166
  // this memory materially shapes an answer (so it can't be hallucinated).
package/bin/restore.js ADDED
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain restore — roll the whole brain back to a previous restore point.
5
+ *
6
+ * Two sources of restore points:
7
+ * git (default) Commits in the Git sync history (~/.brain/.sync/repo/) —
8
+ * one per push, plus a pre-restore safety snapshot taken
9
+ * automatically before every restore.
10
+ * cloud Brain Cloud's pre-overwrite snapshots — one is taken
11
+ * server-side before every `brain cloud push` commit.
12
+ *
13
+ * Usage:
14
+ * brain restore --list [--from git|cloud] [--limit N]
15
+ * brain restore --to <commit|version> [--from git|cloud] [--passphrase <p>]
16
+ *
17
+ * Both sources are undoable: git commits a safety snapshot first; cloud writes
18
+ * a local pre-restore backup under ~/.brain/.cloud/. audit.log is carried
19
+ * forward through every restore, and every restore is itself logged there.
20
+ * Output: JSON.
21
+ */
22
+
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+
26
+ const { listRestorePoints, restoreTo } = require('../src/git-sync');
27
+ const { getBrainDir, readIndex } = require('../src/index-manager');
28
+ const { readSearchIndex, writeSearchIndex, rebuildIndex, isSearchIndexStale } = require('../src/tfidf');
29
+
30
+ function parseArgs(argv) {
31
+ const args = { list: false, to: null, from: 'git', limit: 20, passphrase: null };
32
+ for (let i = 0; i < argv.length; i++) {
33
+ switch (argv[i]) {
34
+ case '--list': args.list = true; break;
35
+ case '--to': args.to = argv[++i]; break;
36
+ case '--from': args.from = argv[++i]; break;
37
+ case '--limit': args.limit = parseInt(argv[++i], 10) || 20; break;
38
+ case '--passphrase': args.passphrase = argv[++i]; break;
39
+ default: break;
40
+ }
41
+ }
42
+ return args;
43
+ }
44
+
45
+ /** Append-only audit trail — same format and mode as memorize's write log. */
46
+ function appendAuditLog(brainDir, record) {
47
+ fs.appendFileSync(
48
+ path.join(brainDir, 'audit.log'),
49
+ JSON.stringify(record) + '\n',
50
+ { mode: 0o600 }
51
+ );
52
+ }
53
+
54
+ /**
55
+ * The restored search index normally matches the restored index.json, but
56
+ * rebuild defensively when it drifted (matches recall.js's staleness rule).
57
+ */
58
+ function reindexIfStale(brainDir) {
59
+ try {
60
+ const index = readIndex();
61
+ let searchIndex = null;
62
+ try { searchIndex = readSearchIndex(brainDir); } catch { searchIndex = null; }
63
+ if (index && isSearchIndexStale(searchIndex, index)) {
64
+ writeSearchIndex(brainDir, rebuildIndex(brainDir, index));
65
+ return true;
66
+ }
67
+ } catch { /* index unreadable — surfaced by the next recall, not here */ }
68
+ return false;
69
+ }
70
+
71
+ async function main(argv) {
72
+ const args = parseArgs(argv || process.argv.slice(2));
73
+ const brainDir = getBrainDir();
74
+
75
+ if (args.from !== 'git' && args.from !== 'cloud') {
76
+ console.error(JSON.stringify({ error: `Unknown source "${args.from}" (expected git or cloud)` }));
77
+ process.exit(1);
78
+ }
79
+
80
+ try {
81
+ if (args.list) {
82
+ if (args.from === 'cloud') {
83
+ const cloud = require('../src/cloud-sync');
84
+ const versions = await cloud.listVersions(brainDir);
85
+ console.log(JSON.stringify({ source: 'cloud', restore_points: versions.slice(0, args.limit), total: versions.length }, null, 2));
86
+ } else {
87
+ const points = listRestorePoints(brainDir, args.limit);
88
+ console.log(JSON.stringify({ source: 'git', restore_points: points, total: points.length }, null, 2));
89
+ }
90
+ return;
91
+ }
92
+
93
+ if (!args.to) {
94
+ console.error(JSON.stringify({
95
+ error: 'Usage: brain restore --list [--from git|cloud] | brain restore --to <point> [--from git|cloud] [--passphrase <p>]',
96
+ }));
97
+ process.exit(1);
98
+ }
99
+
100
+ let result;
101
+ if (args.from === 'cloud') {
102
+ const cloud = require('../src/cloud-sync');
103
+ result = await cloud.restoreVersion(brainDir, args.to);
104
+ } else {
105
+ result = restoreTo(brainDir, args.to, args.passphrase || undefined);
106
+ }
107
+
108
+ const reindexed = reindexIfStale(brainDir);
109
+
110
+ appendAuditLog(brainDir, {
111
+ ts: new Date().toISOString(),
112
+ event: 'restore',
113
+ source: args.from,
114
+ ...(args.from === 'cloud'
115
+ ? { restored_version: result.restored_version, backup: result.backup }
116
+ : { restored_to: result.restored_to, safety_commit: result.safety_commit, restore_commit: result.restore_commit }),
117
+ });
118
+
119
+ console.log(JSON.stringify({ source: args.from, ...result, reindexed }, null, 2));
120
+ } catch (err) {
121
+ console.error(JSON.stringify({ error: err.message }));
122
+ process.exit(1);
123
+ }
124
+ }
125
+
126
+ if (require.main === module) {
127
+ main(process.argv.slice(2));
128
+ }
129
+
130
+ module.exports = { main, parseArgs };
@@ -43,6 +43,7 @@ const {
43
43
  const { rankMemories } = require('../src/scorer');
44
44
  const { advertisedSummaries } = require('../src/skills');
45
45
  const { receiptFor } = require('../src/receipt');
46
+ const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
46
47
 
47
48
  function parseArgs(argv) {
48
49
  const args = { project: null, topics: null, task: null, top: 5 };
@@ -235,12 +236,15 @@ function computeSessionStart(projectRoot, args = {}) {
235
236
  excluded++;
236
237
  continue;
237
238
  }
239
+ const origin = mem.origin || DEFAULT_ORIGIN;
238
240
  context_recall.push({
239
241
  id: mem.id,
240
242
  title,
241
243
  path: mem.path,
242
244
  type: mem.type,
243
245
  score: mem.score,
246
+ origin,
247
+ ...(isLowTrust(origin) ? { low_trust: true } : {}),
244
248
  token_estimate: est,
245
249
  receipt,
246
250
  });
@@ -0,0 +1,125 @@
1
+ ---
2
+ description: Cold-start your brain from transcripts your agents already wrote
3
+ argument-hint: "[--project P] [--since 30d] [--limit N]"
4
+ ---
5
+
6
+ # /brain:import — Cold-Start From Past Sessions
7
+
8
+ A new brain is empty. But your agents have been keeping transcripts for months — decisions, preferences, corrections, conventions. This command reads those transcripts and turns them into real memories.
9
+
10
+ **User input:** $ARGUMENTS
11
+
12
+ **Flags** (passed straight through to the CLI):
13
+ - `--source <id>` — Which history store to read (default `claude-code`; `--sources` lists what's detected)
14
+ - `--project <name>` — Only sessions from one project
15
+ - `--since <30d|6m|2026-01-01>` — Only sessions since then
16
+ - `--limit <N>` — Max sessions to consider (default 40)
17
+ - `--all` — Re-offer sessions already imported
18
+
19
+ ## Your role
20
+
21
+ The CLI harvests. **You distill.** It hands you a digest of past sessions — titles, prompts, projects, files touched, dates. It does not decide what matters. That is the entire job here, and it is a judgement call the CLI deliberately does not make.
22
+
23
+ ## Steps
24
+
25
+ ### 1. Harvest
26
+
27
+ ```bash
28
+ brain import $ARGUMENTS
29
+ ```
30
+
31
+ Returns `{ source, scanned, budget, sessions[] }`. Each session has `session_id`, `title`, `project`, `git_branch`, `started`/`ended`, `turns`, `files_touched`, and a sample of `prompts`.
32
+
33
+ Read `scanned` honestly when you report — the fields mean different things:
34
+ - `skipped` — sessions that held nothing readable (too few real prompts)
35
+ - `filtered` — sessions excluded by the user's own `--project`/`--since` scoping, **not** discarded as junk
36
+ - `already_imported` — sessions a previous run already covered
37
+ - `remaining` — candidates that did not fit this pass; the number to quote when suggesting a re-run
38
+
39
+ If `scanned.files` is 0, tell the user no history was found and stop.
40
+
41
+ ### 2. Check what the brain already knows
42
+
43
+ **Do not skip this on a brain that is already populated.** Import is most often run cold, but it is also run against a brain with hundreds of memories, and there the dominant failure is duplication — re-writing facts that are already stored, which inflates the brain and splits recall across near-identical entries.
44
+
45
+ Before distilling, recall against the themes you can see in the digest:
46
+
47
+ ```bash
48
+ brain recall "<theme from the digest>" --project <project> --top 4
49
+ ```
50
+
51
+ If a theme already scores well against an existing memory, drop it. Only write what is genuinely absent, or what materially *updates* something already stored — and if it's an update, say so in the content rather than filing a near-duplicate.
52
+
53
+ ### 3. Read for durable facts, not events
54
+
55
+ You are looking at what someone *did*, and trying to recover what is still *true*. Those are different things.
56
+
57
+ **Worth remembering** — things that outlive the session:
58
+ - Stated preferences and conventions ("always use X", "I hate Y", "we commit straight to main")
59
+ - Architecture and tooling decisions, with the rationale if it's visible
60
+ - Recurring corrections — if the user pushed back on the same thing three times, that is a preference
61
+ - The shape of each project: what it is, its stack, where it deploys
62
+ - Constraints, deadlines, ongoing goals
63
+
64
+ **Not worth remembering** — things that were only true that afternoon:
65
+ - "fix the failing test", "what does this function do", "run the build"
66
+ - Anything already recorded in the repo, git history, or a CLAUDE.md
67
+ - One-off debugging that ended when the bug was fixed
68
+ - Anything superseded by later work in the digest
69
+
70
+ A good import from 40 sessions is roughly **5–20 memories**, not 40. One memory per session means you transcribed instead of distilled.
71
+
72
+ ### 4. Prefer synthesis across sessions
73
+
74
+ The digest's real value is the pattern across sessions, which no single session contains. Six sessions in the same repo tell you what that project *is* — that is one strong `semantic` memory, worth more than six thin episodic ones.
75
+
76
+ Merge aggressively. Write the memory the user would want to find in six months.
77
+
78
+ ### 5. Classify and write
79
+
80
+ Use the classification rules in `/brain:memorize` — same types, same cognitive types, same hierarchy under `professional/` etc.
81
+
82
+ Two rules specific to import:
83
+
84
+ **`origin` is `agent-inferred`.** You are inferring durable facts from a transcript, not being told them. Do not use `user` — the CLI's provenance gate will reject any attempt to pin or entrench from this path, which is the intended behavior. If a fact deserves entrenchment, the user can `/brain:pin` it deliberately afterwards.
85
+
86
+ **Confidence should reflect the evidence.** A convention stated once in passing is not a convention you are sure about. Something the user repeated across four sessions is. Set `confidence` accordingly rather than defaulting everything to 0.7.
87
+
88
+ Set `encoding_context.project` to the digest's `project` field, and `source` to `"import:<source>:<session_id>"` so the memory traces back to the transcript it came from.
89
+
90
+ Then write them:
91
+
92
+ ```bash
93
+ brain memorize <<'EOF'
94
+ { "memories": [ ... ] }
95
+ EOF
96
+ ```
97
+
98
+ ### 6. Mark what you used
99
+
100
+ ```bash
101
+ brain import --mark <session_id> <session_id> ...
102
+ ```
103
+
104
+ Mark **every session you read**, including the ones you decided held nothing worth keeping — otherwise the next run offers them again and you re-litigate the same judgement. This cursor is what makes import incremental.
105
+
106
+ Use the **full** `session_id` from the digest, never a shortened form you printed for display. The CLI rejects ids that match no real session and exits non-zero; check the `unknown` array if it does.
107
+
108
+ ### 7. Report
109
+
110
+ ```
111
+ ◉ Imported <N> memories from <M> sessions across <P> projects
112
+
113
+ <type> <title>
114
+ ...
115
+
116
+ <scanned.remaining> sessions remain — re-run to continue.
117
+ ```
118
+
119
+ Quote `scanned.remaining` for the re-run line, and mention `scanned.filtered` only if the user passed a scoping flag.
120
+
121
+ ## Notes
122
+
123
+ - **Safe to re-run.** The cursor means a second run offers only new sessions. `--all` overrides it.
124
+ - **Start scoped if the history is large.** `--project <name>` or `--since 30d` gives a better first pass than trying to swallow a year at once.
125
+ - **Nothing is written without you.** `brain import` only ever reads and prints; every memory goes through `brain memorize` and its provenance gate.
@@ -39,7 +39,7 @@ If the brain-memory package is installed globally, use:
39
39
  brain recall "$ARGUMENTS" --project "<project>" --task "<task_type>" --top 10
40
40
  ```
41
41
 
42
- The engine computes **TF-IDF relevance** (cosine similarity between query and memory content), then combines it with decayed strength, recency, spreading activation, context match, and salience using the v4 formula. All scoring is deterministic — same query always produces the same ranking. Each result also carries a pre-minted `receipt` line (`◉ memory: "<title>" (<type>, <age>)`) — keep it for step 6.
42
+ The engine computes **TF-IDF relevance** (cosine similarity between query and memory content), then combines it with decayed strength, recency, spreading activation, context match, salience, and **origin trust** (memories sourced from tool output or external content are down-weighted and flagged `low_trust`) using the v4 formula. All scoring is deterministic — same query always produces the same ranking. Each result also carries a pre-minted `receipt` line (`◉ memory: "<title>" (<type>, <age>)`; low-trust origins add a trailing `⚠ <origin>` marker) — keep it for step 6.
43
43
 
44
44
  ### 3. Read Top Memories
45
45
 
@@ -85,7 +85,7 @@ This deterministically applies:
85
85
 
86
86
  ### 6. Present Results
87
87
 
88
- Format the output clearly. Include confidence indicators for low-confidence memories.
88
+ Format the output clearly. Include confidence indicators for low-confidence memories. When a result has `low_trust: true`, say so explicitly (e.g. "⚠ sourced from external content — verify before relying on it") rather than presenting it as established fact.
89
89
 
90
90
  ```
91
91
  ## Recalled Memory: <Title>