brain-memory 0.1.0-beta.33 → 0.1.0-beta.35
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 +79 -0
- package/README.md +17 -0
- package/bin/brain.js +8 -0
- package/bin/import.js +132 -0
- package/bin/memorize.js +167 -12
- package/commands/brain/import.md +125 -0
- package/commands/brain/memorize.md +17 -3
- package/package.json +2 -2
- package/prompts/antigravity.md +3 -0
- package/prompts/claude.md +3 -0
- package/prompts/copilot.md +3 -0
- package/prompts/kilo.md +3 -0
- package/prompts/openai.md +3 -0
- package/prompts/opencode.md +3 -0
- package/src/harvest.js +562 -0
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,85 @@ 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.35] - 2026-08-01
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **`/brain:import` — cold-start a brain from transcripts your agents already
|
|
14
|
+
wrote.** A new brain is empty, and an empty brain is worth nothing until
|
|
15
|
+
something fills it; meanwhile every coding agent has been keeping months of
|
|
16
|
+
local history. `brain import` harvests it: session titles, user prompts,
|
|
17
|
+
projects, branches and edited files, with harness wrappers
|
|
18
|
+
(`<system-reminder>`, slash-command tags, command output), subagent sidechain
|
|
19
|
+
traffic, and bare acknowledgements filtered out. The digest is bounded on
|
|
20
|
+
three axes (sessions, prompts per session, total characters) and
|
|
21
|
+
round-robins across projects, so one busy repo cannot consume the whole
|
|
22
|
+
budget — on a real 261-session history that lifted project coverage from 5
|
|
23
|
+
to 13 within the same ~15k tokens.
|
|
24
|
+
|
|
25
|
+
The CLI harvests; the **agent distills**. Extracting meaning is a semantic
|
|
26
|
+
judgement, and making it in the CLI would mean shipping an embedding model
|
|
27
|
+
or calling an LLM — the two things Brain exists to avoid. So the harvester
|
|
28
|
+
reports facts and never infers, and distilled memories go through the
|
|
29
|
+
ordinary `brain memorize` path as `agent-inferred`: an import inherits the
|
|
30
|
+
existing provenance ceilings for free and can never pin, entrench, or
|
|
31
|
+
outrank something the user said directly.
|
|
32
|
+
|
|
33
|
+
Import is incremental — a cursor at `~/.brain/.import/state.json` records
|
|
34
|
+
which sessions have been read so re-runs offer only new ones (`--all`
|
|
35
|
+
overrides). `--mark` validates ids against the source's real sessions and
|
|
36
|
+
exits non-zero on any that match nothing: silently accepting a truncated or
|
|
37
|
+
mistyped id would report a session as retired while the cursor never matches
|
|
38
|
+
it, re-offering that session forever. Scope with `--project`,
|
|
39
|
+
`--since 30d|6m|2026-01-01`, `--limit`.
|
|
40
|
+
`brain import --sources` lists detected history stores. `brain import` only
|
|
41
|
+
ever reads and prints; no memory is written without the agent.
|
|
42
|
+
|
|
43
|
+
Claude Code is the first source adapter; the registry in `src/harvest.js`
|
|
44
|
+
takes additional agents without changes downstream.
|
|
45
|
+
|
|
46
|
+
## [0.1.0-beta.34] - 2026-07-26
|
|
47
|
+
|
|
48
|
+
### Added
|
|
49
|
+
|
|
50
|
+
- **Memory provenance — every write is now labelled by origin.** Each memory
|
|
51
|
+
carries an `origin` (`user`, `agent-inferred`, `tool-output`, `external`)
|
|
52
|
+
recording *where the content came from*, which is a different question from
|
|
53
|
+
how much the agent believes it. Origin decides what a memory may claim:
|
|
54
|
+
non-user origins are capped below the 0.7 prune-exempt salience threshold,
|
|
55
|
+
capped on confidence so they stay flagged as uncertain at recall, may not
|
|
56
|
+
raise their own base strength, and decay faster — so a fact absorbed from
|
|
57
|
+
untrusted content fades and loses to a genuine one over time. Defaults to
|
|
58
|
+
`agent-inferred` when absent (the safe direction). Downgrades are never
|
|
59
|
+
silent: `brain memorize` reports every value it lowered under
|
|
60
|
+
`provenance_clamps`. Mitigates OWASP ASI06 (memory poisoning); see
|
|
61
|
+
MemGhost, [arXiv:2607.05189](https://arxiv.org/abs/2607.05189).
|
|
62
|
+
- **Append-only provenance log** at `~/.brain/audit.log` — one JSON object per
|
|
63
|
+
write, recorded before the caller sees success, so a fact that later proves
|
|
64
|
+
to be planted can be traced to the write that introduced it even if the
|
|
65
|
+
memory was since edited, consolidated, or deleted.
|
|
66
|
+
|
|
67
|
+
### Changed
|
|
68
|
+
|
|
69
|
+
- **Breaking (CLI):** born-pinning through `brain memorize` now requires
|
|
70
|
+
`origin: "user"`. Entrenchment — `pinned` (loaded into every session) and
|
|
71
|
+
`stable` (exempt from decay) — is a capability rather than a magnitude, so a
|
|
72
|
+
request from any other origin is refused with a non-zero exit rather than
|
|
73
|
+
quietly capped. Pin deliberately afterwards with `brain pin <id>` instead.
|
|
74
|
+
Only affects callers that drive the CLI directly; `/brain:memorize` already
|
|
75
|
+
proposed rather than assumed pinning.
|
|
76
|
+
|
|
77
|
+
### Fixed
|
|
78
|
+
|
|
79
|
+
- **Cache-honest token accounting in the benchmark harness.** `normalizeUsage`
|
|
80
|
+
now folds `cache_read`/`cache_creation` input tokens back into the input
|
|
81
|
+
count — the cached prefix was being undercounted, which deflated
|
|
82
|
+
tokens-per-successful-task on the DeepSeek endpoint. Cached tokens are
|
|
83
|
+
accumulated, logged, and persisted separately so the two can be compared.
|
|
84
|
+
Also: model-aware judge dispatch, `runs_per_scenario` raised to 10, tighter
|
|
85
|
+
needle-fact rubrics on scenarios A/B/C, and three amendment rows recording
|
|
86
|
+
all of it in `PREREGISTRATION.md`.
|
|
87
|
+
|
|
9
88
|
## [0.1.0-beta.33] - 2026-07-04
|
|
10
89
|
|
|
11
90
|
_Covers everything since v0.1.0-beta.31, including the changes first shipped in the changelog-less 0.1.0-beta.32._
|
package/README.md
CHANGED
|
@@ -242,10 +242,27 @@ The everyday loop is **ambient** — `remember` and `memorize` run automatically
|
|
|
242
242
|
| `/brain:status` | Dashboard with brain health metrics and recommendations |
|
|
243
243
|
| `/brain:pin [id\|query]` | Pin a memory to the always-present tier — loads every session, never decays. Toggles: also unpins (`--off`) |
|
|
244
244
|
| `/brain:forget [target]` | Decay, archive, or remove memories. `--deep` performs forensic erasure — traces and removes every reference |
|
|
245
|
+
| `/brain:import [--project P] [--since 30d]` | Cold-start a new brain from transcripts your agents already wrote. Incremental — safe to re-run |
|
|
245
246
|
| `/brain:sync [subcommand]` | Sync via Brain Cloud, Git remote, or export/import (auto-initializes the brain on first run) |
|
|
246
247
|
| `/brain:skills [list\|show\|add\|use\|remove\|export]` | Manage procedural skills — reusable how-to workflows with progressive disclosure |
|
|
247
248
|
| `/brain:sleep [scope]` | Full maintenance cycle — 9 neuroscience-inspired phases (replay, consolidation, review reinforcement, pruning, dreaming, …). Usually runs automatically/in the background |
|
|
248
249
|
|
|
250
|
+
## Cold Start
|
|
251
|
+
|
|
252
|
+
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.
|
|
253
|
+
|
|
254
|
+
```bash
|
|
255
|
+
brain import --sources # what history exists on this machine
|
|
256
|
+
brain import --project my-app # digest that project's past sessions
|
|
257
|
+
brain import --since 30d # or scope by time
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
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.
|
|
261
|
+
|
|
262
|
+
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.**
|
|
263
|
+
|
|
264
|
+
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.
|
|
265
|
+
|
|
249
266
|
## Session Lifecycle
|
|
250
267
|
|
|
251
268
|
Brain Memory works automatically in the background — no commands needed for basic context awareness.
|
package/bin/brain.js
CHANGED
|
@@ -33,6 +33,7 @@ const DELEGATED = {
|
|
|
33
33
|
pin: 'pin.js',
|
|
34
34
|
unpin: 'unpin.js',
|
|
35
35
|
skill: 'skill.js',
|
|
36
|
+
import: 'import.js',
|
|
36
37
|
};
|
|
37
38
|
|
|
38
39
|
// install.js finds its positional subcommand from process.argv itself, so it is
|
|
@@ -59,6 +60,13 @@ Memory
|
|
|
59
60
|
session-start [--project P] [--task T] [--top N]
|
|
60
61
|
Budget-bounded startup payload (agent-invoked)
|
|
61
62
|
|
|
63
|
+
Cold start
|
|
64
|
+
import [--source S] [--project P] [--since 30d] [--limit N] [--all]
|
|
65
|
+
Digest past agent transcripts into import candidates
|
|
66
|
+
import --sources List detected agent history stores
|
|
67
|
+
import --mark <id> [<id>...]
|
|
68
|
+
Record sessions as imported (incremental cursor)
|
|
69
|
+
|
|
62
70
|
Sync
|
|
63
71
|
cloud <login|logout|push|pull|status>
|
|
64
72
|
|
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
|
@@ -71,6 +71,38 @@ const COGNITIVE_ADJUSTMENTS = {
|
|
|
71
71
|
procedural: { strength_delta: -0.10, decay_multiplier: 1.003 },
|
|
72
72
|
};
|
|
73
73
|
|
|
74
|
+
// --- Provenance (OWASP ASI06: memory poisoning) ---
|
|
75
|
+
//
|
|
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;
|
|
105
|
+
|
|
74
106
|
// --- Args ---
|
|
75
107
|
|
|
76
108
|
function parseArgs(argv) {
|
|
@@ -83,7 +115,61 @@ function parseArgs(argv) {
|
|
|
83
115
|
|
|
84
116
|
// --- Helpers ---
|
|
85
117
|
|
|
86
|
-
|
|
118
|
+
/**
|
|
119
|
+
* Resolve a memory's origin and clamp its trust-bearing fields to what that
|
|
120
|
+
* origin is permitted to claim.
|
|
121
|
+
*
|
|
122
|
+
* Returns `{ origin, policy, mem, clamps }` where `mem` is a sanitized copy and
|
|
123
|
+
* `clamps` lists every explicit over-ask the policy lowered — surfaced in the
|
|
124
|
+
* CLI output so a downgrade is never silent. Returns `{ error }` for requests
|
|
125
|
+
* that have no benign reading.
|
|
126
|
+
*/
|
|
127
|
+
function applyOriginPolicy(mem) {
|
|
128
|
+
const origin = mem.origin || DEFAULT_ORIGIN;
|
|
129
|
+
const policy = ORIGIN_POLICY[origin];
|
|
130
|
+
if (!policy) {
|
|
131
|
+
return { error: `Unknown origin "${origin}" (expected one of: ${Object.keys(ORIGIN_POLICY).join(', ')})` };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Entrenchment — loading into every session, or exemption from decay — is a
|
|
135
|
+
// capability, not a magnitude. Tool output and inbound email have no benign
|
|
136
|
+
// reason to request it, so this is refused loudly rather than quietly capped.
|
|
137
|
+
if (!policy.allow_entrench && (mem.pinned || mem.stable)) {
|
|
138
|
+
const asked = [mem.pinned && 'pinned', mem.stable && 'stable'].filter(Boolean).join(' + ');
|
|
139
|
+
return {
|
|
140
|
+
error: `Origin "${origin}" may not set ${asked}. Entrenching a memory requires origin ` +
|
|
141
|
+
`"user" — or pin it deliberately afterwards with \`brain pin <id>\`.`,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const clamps = [];
|
|
146
|
+
const clamp = (field, requested, fallback, max) => {
|
|
147
|
+
const value = requested ?? fallback;
|
|
148
|
+
if (value <= max) return value;
|
|
149
|
+
// Only report a downgrade the caller actually asked for. A lowered default
|
|
150
|
+
// is the policy working as designed, not a rejected claim.
|
|
151
|
+
if (requested != null) clamps.push({ field, requested, allowed: max, origin });
|
|
152
|
+
return max;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
origin,
|
|
157
|
+
policy,
|
|
158
|
+
clamps,
|
|
159
|
+
mem: {
|
|
160
|
+
...mem,
|
|
161
|
+
salience: clamp('salience', mem.salience, 0.5, policy.max_salience),
|
|
162
|
+
confidence: clamp('confidence', mem.confidence, 0.7, policy.max_confidence),
|
|
163
|
+
// A non-user origin may lower a memory's base strength but never raise it.
|
|
164
|
+
strength_adjustment: clamp(
|
|
165
|
+
'strength_adjustment', mem.strength_adjustment, 0,
|
|
166
|
+
policy.allow_entrench ? Infinity : 0
|
|
167
|
+
),
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function computeStrengthAndDecay(type, cognitiveType, strengthAdjustment = 0, originDecayMultiplier = 1.0) {
|
|
87
173
|
const typeDefaults = TYPE_DEFAULTS[type] || TYPE_DEFAULTS.observation;
|
|
88
174
|
const cogAdj = COGNITIVE_ADJUSTMENTS[cognitiveType] || COGNITIVE_ADJUSTMENTS.semantic;
|
|
89
175
|
|
|
@@ -95,14 +181,20 @@ function computeStrengthAndDecay(type, cognitiveType, strengthAdjustment = 0) {
|
|
|
95
181
|
// over time (strength * decay_rate^days) — inverted decay. 0.9999/day is
|
|
96
182
|
// "extremely slow" (a memory loses ~3% of its strength per year) without ever
|
|
97
183
|
// inverting.
|
|
98
|
-
|
|
184
|
+
// The origin multiplier rides on top: memory sourced from untrusted content
|
|
185
|
+
// fades faster, so a planted fact loses to a genuine one over time even if
|
|
186
|
+
// nothing ever detects it as an attack.
|
|
187
|
+
const decay_rate = Math.min(
|
|
188
|
+
0.9999,
|
|
189
|
+
typeDefaults.decay_rate * cogAdj.decay_multiplier * originDecayMultiplier
|
|
190
|
+
);
|
|
99
191
|
|
|
100
192
|
return { strength: Math.round(strength * 100) / 100, decay_rate };
|
|
101
193
|
}
|
|
102
194
|
|
|
103
|
-
function buildMemoryFileContent(mem, id, now) {
|
|
195
|
+
function buildMemoryFileContent(mem, id, now, origin, originDecayMultiplier) {
|
|
104
196
|
const { strength, decay_rate } = computeStrengthAndDecay(
|
|
105
|
-
mem.type, mem.cognitive_type, mem.strength_adjustment
|
|
197
|
+
mem.type, mem.cognitive_type, mem.strength_adjustment, originDecayMultiplier
|
|
106
198
|
);
|
|
107
199
|
|
|
108
200
|
const fmLines = [
|
|
@@ -130,6 +222,7 @@ function buildMemoryFileContent(mem, id, now) {
|
|
|
130
222
|
fmLines.push(
|
|
131
223
|
`tags: [${(mem.tags || []).map(t => `"${t}"`).join(', ')}]`,
|
|
132
224
|
`related: [${(mem.related || []).map(r => `"${r}"`).join(', ')}]`,
|
|
225
|
+
`origin: "${origin}"`,
|
|
133
226
|
`source: "${mem.source || ''}"`,
|
|
134
227
|
`encoding_context:`,
|
|
135
228
|
` project: "${(mem.encoding_context && mem.encoding_context.project) || ''}"`,
|
|
@@ -144,7 +237,7 @@ function buildMemoryFileContent(mem, id, now) {
|
|
|
144
237
|
return { fileContent: frontmatter + mem.content + '\n', strength, decay_rate };
|
|
145
238
|
}
|
|
146
239
|
|
|
147
|
-
function buildIndexEntry(mem, id, strength, decayRate, now) {
|
|
240
|
+
function buildIndexEntry(mem, id, strength, decayRate, now, origin) {
|
|
148
241
|
const entry = {
|
|
149
242
|
title: mem.title,
|
|
150
243
|
path: mem.path,
|
|
@@ -155,6 +248,9 @@ function buildIndexEntry(mem, id, strength, decayRate, now) {
|
|
|
155
248
|
access_count: 0,
|
|
156
249
|
strength,
|
|
157
250
|
decay_rate: decayRate,
|
|
251
|
+
// Provenance travels with the index entry so recall can weigh and flag it
|
|
252
|
+
// without having to open every memory file.
|
|
253
|
+
origin,
|
|
158
254
|
salience: mem.salience ?? 0.5,
|
|
159
255
|
confidence: mem.confidence ?? 0.7,
|
|
160
256
|
tags: mem.tags || [],
|
|
@@ -173,6 +269,22 @@ function buildIndexEntry(mem, id, strength, decayRate, now) {
|
|
|
173
269
|
return entry;
|
|
174
270
|
}
|
|
175
271
|
|
|
272
|
+
/**
|
|
273
|
+
* Append-only provenance log, one JSON object per line.
|
|
274
|
+
*
|
|
275
|
+
* Written for every memory that reaches disk, including ones the policy
|
|
276
|
+
* downgraded, so a fact that later turns out to be planted can be traced to the
|
|
277
|
+
* write that introduced it — even if the memory file itself was since edited,
|
|
278
|
+
* consolidated by a sleep cycle, or deleted.
|
|
279
|
+
*/
|
|
280
|
+
function appendAuditLog(brainDir, record) {
|
|
281
|
+
fs.appendFileSync(
|
|
282
|
+
path.join(brainDir, 'audit.log'),
|
|
283
|
+
JSON.stringify(record) + '\n',
|
|
284
|
+
{ mode: 0o600 }
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
|
|
176
288
|
function updateMetaFiles(brainDir, memPath) {
|
|
177
289
|
const parts = memPath.split('/');
|
|
178
290
|
// Walk up the directory chain, updating _meta.json at each level
|
|
@@ -327,27 +439,42 @@ async function main() {
|
|
|
327
439
|
const results = [];
|
|
328
440
|
const newIds = [];
|
|
329
441
|
const pinnedToAdd = [];
|
|
442
|
+
const clampsReported = [];
|
|
443
|
+
const auditErrors = [];
|
|
330
444
|
|
|
331
|
-
for (const
|
|
445
|
+
for (const rawMem of input.memories) {
|
|
332
446
|
// Validate required fields
|
|
333
|
-
if (!
|
|
447
|
+
if (!rawMem.title || !rawMem.type || !rawMem.path || !rawMem.content) {
|
|
334
448
|
console.error(JSON.stringify({
|
|
335
|
-
error: `Memory missing required fields (title, type, path, content): ${JSON.stringify(
|
|
449
|
+
error: `Memory missing required fields (title, type, path, content): ${JSON.stringify(rawMem.title || 'untitled')}`,
|
|
336
450
|
}));
|
|
337
451
|
process.exit(1);
|
|
338
452
|
}
|
|
339
453
|
|
|
340
|
-
if (!TYPE_DEFAULTS[
|
|
341
|
-
console.error(JSON.stringify({ error: `Unknown memory type: ${
|
|
454
|
+
if (!TYPE_DEFAULTS[rawMem.type]) {
|
|
455
|
+
console.error(JSON.stringify({ error: `Unknown memory type: ${rawMem.type}` }));
|
|
456
|
+
process.exit(1);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// Provenance gate (ASI06) — decide what this origin is allowed to claim
|
|
460
|
+
// before anything reaches disk.
|
|
461
|
+
const policy = applyOriginPolicy(rawMem);
|
|
462
|
+
if (policy.error) {
|
|
463
|
+
console.error(JSON.stringify({ error: `${policy.error} — memory: ${JSON.stringify(rawMem.title)}` }));
|
|
342
464
|
process.exit(1);
|
|
343
465
|
}
|
|
466
|
+
const { origin } = policy;
|
|
467
|
+
const mem = policy.mem;
|
|
468
|
+
for (const c of policy.clamps) clampsReported.push({ ...c, title: rawMem.title });
|
|
344
469
|
|
|
345
470
|
// Generate ID
|
|
346
471
|
const id = generateId();
|
|
347
472
|
newIds.push(id);
|
|
348
473
|
|
|
349
474
|
// Compute strength/decay
|
|
350
|
-
const { fileContent, strength, decay_rate } = buildMemoryFileContent(
|
|
475
|
+
const { fileContent, strength, decay_rate } = buildMemoryFileContent(
|
|
476
|
+
mem, id, now, origin, policy.policy.decay_multiplier
|
|
477
|
+
);
|
|
351
478
|
|
|
352
479
|
// Create directories
|
|
353
480
|
const fullPath = path.join(brainDir, mem.path);
|
|
@@ -357,8 +484,31 @@ async function main() {
|
|
|
357
484
|
// Write memory file
|
|
358
485
|
atomicWriteSync(fullPath, fileContent);
|
|
359
486
|
|
|
487
|
+
// Record the write before reporting success. An audit failure is surfaced
|
|
488
|
+
// rather than thrown: the memory is already on disk, and silently dropping
|
|
489
|
+
// the trail would be the worse outcome of the two.
|
|
490
|
+
try {
|
|
491
|
+
appendAuditLog(brainDir, {
|
|
492
|
+
ts: now,
|
|
493
|
+
event: 'memorize',
|
|
494
|
+
id,
|
|
495
|
+
origin,
|
|
496
|
+
agent: HOST_AGENT,
|
|
497
|
+
type: mem.type,
|
|
498
|
+
path: mem.path,
|
|
499
|
+
title: mem.title,
|
|
500
|
+
salience: mem.salience ?? 0.5,
|
|
501
|
+
confidence: mem.confidence ?? 0.7,
|
|
502
|
+
decay_rate,
|
|
503
|
+
entrenched: Boolean(mem.pinned || mem.stable),
|
|
504
|
+
clamped: policy.clamps.map((c) => c.field),
|
|
505
|
+
});
|
|
506
|
+
} catch (err) {
|
|
507
|
+
auditErrors.push({ id, error: err.message });
|
|
508
|
+
}
|
|
509
|
+
|
|
360
510
|
// Update index
|
|
361
|
-
const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now);
|
|
511
|
+
const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now, origin);
|
|
362
512
|
addMemory(index, id, indexEntry);
|
|
363
513
|
|
|
364
514
|
// CoALA Phase 1: register a born-pinned memory in the pinned manifest
|
|
@@ -413,6 +563,7 @@ async function main() {
|
|
|
413
563
|
cognitive_type: mem.cognitive_type || 'semantic',
|
|
414
564
|
strength,
|
|
415
565
|
decay_rate,
|
|
566
|
+
origin,
|
|
416
567
|
salience: mem.salience ?? 0.5,
|
|
417
568
|
confidence: mem.confidence ?? 0.7,
|
|
418
569
|
tags: mem.tags || [],
|
|
@@ -441,6 +592,10 @@ async function main() {
|
|
|
441
592
|
stored: results,
|
|
442
593
|
total: results.length,
|
|
443
594
|
index_count: index.memory_count,
|
|
595
|
+
// Only present when the provenance policy actually lowered something, so
|
|
596
|
+
// the agent can tell the user a claim was downgraded and why.
|
|
597
|
+
...(clampsReported.length ? { provenance_clamps: clampsReported } : {}),
|
|
598
|
+
...(auditErrors.length ? { audit_errors: auditErrors } : {}),
|
|
444
599
|
};
|
|
445
600
|
|
|
446
601
|
// Sync if requested
|
|
@@ -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.
|