@fabersep/memory 0.4.0 → 0.5.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  All notable changes to `@fabersep/memory`. Versions follow [Semantic Versioning](https://semver.org/).
4
4
 
5
+ ## [0.5.1](https://github.com/fabersep/memory/compare/v0.5.0...v0.5.1) (2026-12-03)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * stage agent rules and preferences in the startup index ([#23](https://github.com/fabersep/memory/issues/23)) ([6fc3d5a](https://github.com/fabersep/memory/commit/6fc3d5a4eaa58ce1b46cd0a2f7a384d7b46f4094))
11
+
12
+ ## [0.5.0](https://github.com/fabersep/memory/compare/v0.4.0...v0.5.0) (2026-12-03)
13
+
14
+
15
+ ### Features
16
+
17
+ * save memories the user dictates directly, always in the startup index ([#19](https://github.com/fabersep/memory/issues/19)) ([edbbc0c](https://github.com/fabersep/memory/commit/edbbc0c209a2c4eea5ebc2952bd9b273b8670193))
18
+
5
19
  ## 0.4.0 (2026-12-02)
6
20
 
7
21
  ### Added
package/README.md CHANGED
@@ -1,164 +1,116 @@
1
1
  <h1><img src="docs/assets/logo.svg" alt="" width="28" height="28" align="absmiddle"> FaberSEP Memory</h1>
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/@fabersep/memory.svg)](https://www.npmjs.com/package/@fabersep/memory)
4
+ [![tests](https://github.com/fabersep/memory/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/fabersep/memory/actions/workflows/test.yml)
4
5
  [![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE)
5
6
 
6
- **Your AI coding tools shouldn't each have their own siloed memory — and your team shouldn't repeat the same rules in every chat. FaberSEP Memory gives every tool and every teammate one shared memory you can read, approve and keep in Git.**
7
+ **One memory for every AI coding agent you use, on every machine you use it. Agents propose, you approve, Git keeps it.**
7
8
 
8
9
  <p align="center">
9
- <img src="docs/assets/solo-memory.svg" alt="In the morning using Claude Code, you say we use pnpm not npm and approve the proposed memory into your local Git folder ~/.faber/memory. In the afternoon you switch to Antigravity and in the evening to Codex on the same machine — both read use-pnpm automatically and run pnpm commands without being told again." width="920">
10
+ <img src="docs/assets/one-memory-hero.svg" alt="One memory for every AI tool: FaberSEP Memory in the center, connected to Claude Code, Antigravity, Cursor, Codex, Claude Desktop, agents on a server, teammates and any MCP client." width="920">
10
11
  </p>
11
12
 
12
13
  ---
13
14
 
14
- ## The problem you already know
15
+ ## Why it exists
15
16
 
16
- It's Monday. You tell your AI assistant: *"We use pnpm here, not npm."* It says "Got it!" and does a great job.
17
+ AI coding agents remember things now. Claude Code writes its own memory files, Antigravity keeps its own knowledge, Cursor has rules. But each one remembers **for itself, on one machine**.
17
18
 
18
- Later the same day you open a new chat — or switch from Claude Code to Antigravity, Codex or Cursor — and it runs `npm install`. Meanwhile, your teammate hits the exact same mistake in their editor because every assistant's built-in memory stays trapped inside one tool on one machine.
19
+ FaberSEP Memory started from a common setup: several AI tools on a workstation, plus agents running unattended on a server. Without a shared layer, a rule settled with one tool stays unknown to the others, and every machine drifts on its own. FaberSEP Memory gives all of them **one** memory: a rule approved once is known to every tool on every machine, and nothing becomes a rule without the owner's approval.
19
20
 
20
- So teams copy rules into long instruction files that grow to 300 lines nobody maintains, or let tools "remember" things silently until a wrong rule sneaks in.
21
+ ## How it differs from an agent's built-in memory
21
22
 
22
- ## What changes with FaberSEP Memory
23
+ | | Built-in agent memory | FaberSEP Memory |
24
+ | :--- | :--- | :--- |
25
+ | **Who can read it** | The one tool that wrote it | Claude Code, Antigravity, Cursor, Claude Desktop, Codex (manual setup) |
26
+ | **Where it lives** | One machine | A Git repo you can clone to any machine, a server included (read-only there) |
27
+ | **Who writes it** | The agent, silently | What you tell it to remember is saved at once; what the agent decides on its own waits for your approval |
28
+ | **History and undo** | Usually none | Every change is a Git commit |
29
+ | **Team use** | Not shareable | Optional private team repo |
30
+ | **Context cost** | Grows with the file | A fixed-size index (max ~1,500 tokens); details fetched on demand |
23
31
 
24
- The same Monday, with FaberSEP Memory:
32
+ If you use one tool on one machine and are happy with its memory, you don't need this.
25
33
 
26
- 1. **Your assistant notices a lesson** ("we use pnpm") and *proposes* saving it. Nothing is saved silently.
27
- 2. **You approve it with one click** in the local Web UI (`faber-memory web`) — or with one key press in the terminal (`faber-memory review`).
28
- 3. **Every tool on your machine knows it**: switch from Claude Code to Antigravity, Codex, Cursor or Claude Desktop — every assistant reads the same local Git-backed memory.
34
+ ## What `init` changes, and how your agent finds it
29
35
 
30
- Your memory is a folder of short Markdown notes kept in Git so every change has history and can be undone. Nothing goes to a third-party cloud service, and you don't need an account, a database or an API key.
36
+ There is **no background service and no account**. `faber-memory` is a CLI plus a small MCP server that your AI tool starts by itself (stdio) when a chat opens.
31
37
 
32
- ## Review and browse in the local Web UI
38
+ `faber-memory init` does three things:
33
39
 
34
- Run `faber-memory web` to open a clean, zero-dependency local UI in your browser (`127.0.0.1` only). Approve, edit, reject or batch-commit proposals in one click, search and edit active memories in **Browse**, and check setup health — all without touching raw files.
40
+ 1. **Creates your memory folder** at `~/.faber/memory`: plain Markdown notes in a Git repo.
41
+ 2. **Adds one marked block** to each tool's global instruction file. For Claude Code, in `~/.claude/CLAUDE.md`:
35
42
 
36
- <p align="center">
37
- <img src="docs/assets/web-ui-review.png" alt="FaberSEP Memory local Web UI showing pending memory proposals with Approve, Edit, Reject, Skip and Commit Batch controls alongside Browse and Health tabs." width="920">
38
- </p>
39
-
40
- ## Share one memory across your whole team
41
-
42
- When you connect a private Git repository as a team memory, one approved rule syncs to every teammate — no matter which AI coding tool each person prefers.
43
-
44
- <p align="center">
45
- <img src="docs/assets/team-memory.svg" alt="Maya tells Claude Code that the team uses pnpm. The assistant proposes a memory instead of saving silently. Maya approves it with one click in the local FaberSEP Memory Web UI, committing it to the shared team Git memory. Instantly, Maya in Cursor, Alex in Antigravity, and Sam in Codex all read use-pnpm and run pnpm install." width="920">
46
- </p>
43
+ ```markdown
44
+ <!-- faber-memory:start -->
45
+ @/Users/you/.config/faber-memory/state/MEMORY.md
46
+ Use the faber-memory MCP tools: memory_search and memory_get for the details behind these lines; when you learn a durable rule, decision, lesson or preference, call memory_propose (the user approves it later; never edit memory files directly). When the user explicitly asks you to remember something, call memory_propose with source "user" and their exact words in user_quote; it is saved at once.
47
+ <!-- faber-memory:end -->
48
+ ```
47
49
 
48
- ## Why teams use it
50
+ `MEMORY.md` is a short index compiled from your notes, so the agent knows what exists from the first message.
51
+ 3. **Registers the MCP server** `faber-memory` in each tool's MCP config. It gives the agent three tools: `memory_search`, `memory_get` and `memory_propose`. Agents can only propose; they never write active memory.
49
52
 
50
- - **Works across all your AI tools.** Claude Code, Antigravity, Codex, Cursor, Claude Desktop — switch tools anytime on the same machine without re-explaining your setup.
51
- - **One memory for your whole team.** Share rules through a private Git repository so one approval keeps every teammate's assistant in sync.
52
- - **Simple local Web UI.** Review proposals, browse and search active memories, edit or delete entries, and check health in your browser with `faber-memory web`.
53
- - **Nothing gets in without your OK.** Assistants can only propose. You approve what stays, and secrets or machine-specific paths are blocked automatically.
54
- - **Fast and cheap.** Assistants load a tiny startup index and look up details only when needed, keeping chats fast and prompt caches warm.
53
+ | Tool | Instruction file | MCP config |
54
+ | :--- | :--- | :--- |
55
+ | Claude Code | `~/.claude/CLAUDE.md` | `~/.claude.json` |
56
+ | Antigravity | `~/.gemini/GEMINI.md` | `~/.gemini/config/mcp_config.json` |
57
+ | Cursor | none | `~/.cursor/mcp.json` |
58
+ | Claude Desktop | none | `claude_desktop_config.json` (`--engine claude-desktop`) |
59
+ | Codex | none | add the MCP server by hand |
55
60
 
56
- ---
61
+ Every touched file gets a `.bak` backup. `init --preview` shows the exact diff first, and `init --undo` removes the block and the MCP entry and leaves your notes alone. Details: [Connecting engines](docs/guide.md#connecting-engines-init).
57
62
 
58
- ## Get started (about 2 minutes)
63
+ ## Get started
59
64
 
60
- You need **Node.js 20 or newer** and **Git**. To check, run `node -v` and `git --version` in a terminal.
61
-
62
- **1. Install it once**
65
+ You need Node.js 20+ and Git.
63
66
 
64
67
  ```bash
65
68
  npm install -g @fabersep/memory
69
+ faber-memory init # add --preview to see the changes first
70
+ faber-memory doctor # every line should say PASS
66
71
  ```
67
72
 
68
- This gives you one short command, `faber-memory`, that you can run from any folder. Check it with `faber-memory --version`.
69
-
70
- **2. Set it up**
71
-
72
- ```bash
73
- faber-memory init
74
- ```
75
-
76
- This creates your memory folder (`~/.faber/memory`, with its own Git history), finds the AI assistants on your computer and connects them. It keeps a backup of every file it touches, and you can undo it at any time with `faber-memory init --undo`.
77
-
78
- Want your notes in another folder? Give its path:
73
+ Open a **new** chat and tell your agent something it would otherwise get wrong, for example *"In this project we run the tests with `make test`. Remember that."* Because you asked, it is saved at once, and the agent tells you how to undo it (`faber-memory undo <id>`).
79
74
 
80
- ```bash
81
- faber-memory init ~/my-notes
82
- ```
83
-
84
- **3. Check that everything is connected**
75
+ When the agent learns something on its own (say, from a failed build), it only *proposes* a memory. Approve those in the review page:
85
76
 
86
77
  ```bash
87
- faber-memory doctor
78
+ faber-memory web # local review UI on 127.0.0.1 (or: faber-memory review)
88
79
  ```
89
80
 
90
- You should see `PASS` lines. Each `WARN` or `FAIL` line comes with a one-line hint on how to fix it.
81
+ Either way, any connected tool knows it from its next new chat.
91
82
 
92
- **4. Start a new chat in your assistant**
93
-
94
- Tell it something about your project that it would otherwise get wrong, for example:
83
+ <p align="center">
84
+ <img src="docs/assets/web-ui-review.png" alt="FaberSEP Memory local Web UI showing pending memory proposals with Approve, Edit, Reject, Skip and Commit Batch controls alongside Browse and Health tabs." width="820">
85
+ </p>
95
86
 
96
- > *"In this project we run the tests with `make test`, never `npm test`. Please remember that."*
87
+ Already have rules in `AGENTS.md`, `CLAUDE.md` or Cursor rules? [Import them](docs/guide.md#importing-existing-notes); they go through the same review.
97
88
 
98
- It should suggest saving this as a memory. (If it doesn't, ask it: *"Propose this as a memory."*)
89
+ ## More than one machine
99
90
 
100
- **5. Approve what you want to keep**
91
+ Your memory is a Git repo, so push it to a **private** remote and clone it elsewhere:
101
92
 
102
93
  ```bash
103
- faber-memory web
94
+ faber-memory remote add git@github.com:<you>/<private-repo>.git # on your main machine
95
+ faber-memory setup --read-only <repo-url> # on a server that runs agents
96
+ faber-memory init # then connect that server's agents
104
97
  ```
105
98
 
106
- This opens a clean local Web UI in your browser (`127.0.0.1` only) where you can review, edit, approve, or reject proposals in one click — and browse or search your active memories. Prefer the terminal? Run `faber-memory review` instead (`a` to approve, `e` to edit, `r` to reject, `s` to skip, `q` to save and quit).
107
-
108
- Now open a **new** chat (in the same tool or a different one) and ask: *"How do I run the tests here?"* Your assistant answers `make test`, without you telling it again.
109
-
110
- > **Already have notes?** If you keep rules in an `AGENTS.md`, a `CLAUDE.md`, Cursor rules or a folder of Markdown files, you can bring them in. They go to the same review step first. See [Importing existing notes](docs/guide.md#importing-existing-notes).
111
-
112
- ---
113
-
114
- ## A normal day with it
115
-
116
- - **While you work:** nothing to do. Every connected assistant reads the same compact memory index at startup and searches details as needed.
117
- - **When it learns something:** it proposes a memory. The proposal waits in a "to review" box (`pre-memory`) and changes nothing yet.
118
- - **When you have a minute:** run `faber-memory web` (or `faber-memory review` in the terminal). All your approvals are saved together in one Git commit.
119
- - **Changed your mind?** Edit or delete any memory right from the Web UI's Browse tab — or edit the Markdown file in `~/.faber/memory` and run `faber-memory compile`. Git keeps the full history.
120
-
121
- A memory file looks like this:
122
-
123
- ```markdown
124
- ---
125
- id: use-pnpm
126
- type: rule
127
- summary: Use pnpm, not npm, in this team's projects.
128
- ---
129
-
130
- Run `pnpm install` and `pnpm test`. Never commit a package-lock.json.
131
- ```
132
-
133
- ---
134
-
135
- ## Common questions
136
-
137
- **Doesn't my AI tool already have memory?**
138
- Some do, but it stays inside that one tool, and the tool can write to it without asking you. FaberSEP Memory works across tools, and only you can approve what goes in. More in [Why FaberSEP Memory?](docs/why-faber-memory.md)
139
-
140
- **Does it cost anything or send my data anywhere?**
141
- No. It's free and open source (Apache-2.0), and it runs on your computer. Your notes go only where you push them yourself, for example to a private team repository.
142
-
143
- **Can I use it on my phone?**
144
- Not directly yet. If you control a computer or server from your phone (for example with Claude Remote Control), memory works in that session.
99
+ A read-only host pulls on start and serves the same memory to its agents; proposals and approvals stay on your main machine. See [Personal remote and a second machine](docs/guide.md#personal-remote-and-a-second-machine).
145
100
 
146
- **How do I update or remove it?**
147
- `npm install -g @fabersep/memory@latest` installs the newest version; `faber-memory --version` shows which one you have. `faber-memory init --undo` disconnects your assistants and leaves your notes in place. `npm uninstall -g @fabersep/memory` removes the command. See [Updating and cleaning up](docs/guide.md#updating-and-cleaning-up).
101
+ ## Teams
148
102
 
149
- **Something went wrong.**
150
- Run `faber-memory doctor` first. Then check [Troubleshooting](docs/troubleshooting.md) or [open an issue](https://github.com/fabersep/memory/issues).
103
+ Connect a private team repo and one approved rule reaches every teammate, whatever tool each person uses. See [Team mode](docs/guide.md#team-mode-shared-private-repo).
151
104
 
152
105
  ---
153
106
 
154
- ## Going further
107
+ ## Learn more
155
108
 
156
- - **[User guide and reference](docs/guide.md):** how it works inside, team setup, importing, every command, the MCP tools and where files live.
157
- - **[Why FaberSEP Memory?](docs/why-faber-memory.md):** comparisons with built-in memory and vector databases, and why the design keeps prompt caching cheap.
158
- - **[Troubleshooting](docs/troubleshooting.md):** every warning, explained.
159
- - **[Contributing](CONTRIBUTING.md)** and **[Changelog](CHANGELOG.md)**.
109
+ - **[User guide and reference](docs/guide.md):** how it works inside, every command, the MCP tools, where files live, updating and removing.
110
+ - **[Why FaberSEP Memory?](docs/why-faber-memory.md):** comparisons with built-in memory, one big `AGENTS.md` and vector databases.
111
+ - **[Troubleshooting](docs/troubleshooting.md)**, **[Contributing](CONTRIBUTING.md)**, **[Changelog](CHANGELOG.md)**.
160
112
 
161
- FaberSEP Memory is part of [FaberSEP](https://github.com/fabersep), open-source tools that help AI coding assistants work with more discipline.
113
+ Free and open source, runs on your computer, no account or API key. Part of [FaberSEP](https://github.com/fabersep).
162
114
 
163
115
  ## License
164
116
 
package/dist/src/cli.js CHANGED
@@ -4,6 +4,7 @@ import * as path from 'node:path';
4
4
  import * as readline from 'node:readline';
5
5
  import { compileGlobalL0 } from './compiler.js';
6
6
  import { generateUuid, getCompiledL0Path, getDefaultPersonalPath, getHomeDir, loadConfig, saveConfig, } from './config.js';
7
+ import { countRecentDirectSaves, DIRECT_SAVE_RECENT_DAYS, isDirectUserSaveOn, undoDirectSave, } from './direct-save.js';
7
8
  import { formatDoctorReport, runDoctor } from './doctor.js';
8
9
  import { getDefaultBranch, getHeadSha, gitCloneTeamRepo, gitInitSoloRepo, gitSync, isGitRepo, } from './git.js';
9
10
  import { runImport } from './importer.js';
@@ -293,6 +294,19 @@ async function main() {
293
294
  console.log(c.green(`Updated personal push mode to ${mode}`));
294
295
  return 0;
295
296
  }
297
+ if (sub === 'set-direct-save') {
298
+ const value = positional[1];
299
+ if (value !== 'on' && value !== 'off') {
300
+ console.error('Usage: faber-memory config set-direct-save <on|off>');
301
+ return 1;
302
+ }
303
+ config.directUserSave = value === 'on';
304
+ saveConfig(config, homeDir);
305
+ console.log(c.green(value === 'on'
306
+ ? 'Direct save is on: memories you ask the agent to remember are saved to personal memory at once.'
307
+ : 'Direct save is off: memories you ask the agent to remember wait for review like any proposal.'));
308
+ return 0;
309
+ }
296
310
  if (sub === 'unset') {
297
311
  const scope = positional[1];
298
312
  if (!scope || !['personal', 'team'].includes(scope)) {
@@ -392,6 +406,25 @@ async function main() {
392
406
  }
393
407
  return 0;
394
408
  }
409
+ if (cmd === 'undo') {
410
+ const config = loadConfig(homeDir);
411
+ const entryId = positional[0];
412
+ if (!entryId) {
413
+ console.error('Usage: faber-memory undo <entry-id> (undo a memory saved directly on your word)');
414
+ return 1;
415
+ }
416
+ const res = undoDirectSave(config, entryId, homeDir);
417
+ for (const m of res.messages)
418
+ console.log(m);
419
+ if (!res.ok) {
420
+ for (const e of res.errors)
421
+ printErrorWithHelp(e);
422
+ return 1;
423
+ }
424
+ const ask = isInteractive() && !flags.yes ? (q) => promptLine(q) : undefined;
425
+ await afterPersonalCommit(config, homeDir, ask);
426
+ return 0;
427
+ }
395
428
  if (cmd === 'reject') {
396
429
  if (flags.all) {
397
430
  const proposals = reconcileAwaitingCommitProposals(homeDir);
@@ -590,6 +623,9 @@ async function main() {
590
623
  if (p.forceNew && p.reason) {
591
624
  console.log(`${c.yellow('force_new reason:')} ${p.reason}`);
592
625
  }
626
+ if (p.source === 'user') {
627
+ console.log(`${c.green('User asked:')} "${p.userQuote || ''}"`);
628
+ }
593
629
  console.log(c.dim(hr('─', 68)));
594
630
  const bodyLines = p.body.split('\n');
595
631
  if (!showFull && bodyLines.length > MAX_PREVIEW_LINES) {
@@ -724,6 +760,7 @@ async function main() {
724
760
  const reminder = getUnpushedReminder(config, homeDir);
725
761
  if (reminder)
726
762
  console.log(c.yellow(` ${reminder}`));
763
+ console.log(` Direct save: ${isDirectUserSaveOn(config) ? 'on' : 'off'} (${countRecentDirectSaves(homeDir)} in the last ${DIRECT_SAVE_RECENT_DAYS} days)`);
727
764
  }
728
765
  console.log(` Project root: ${projectRes.projectRoot || 'none'} (source: ${projectRes.source})`);
729
766
  if (loaded.uncommittedWarnings.length > 0) {
@@ -740,6 +777,8 @@ async function main() {
740
777
  const flagsList = [p.status];
741
778
  if (isStale)
742
779
  flagsList.push(`STALE (${ageDays}d > ${config.staleDays}d)`);
780
+ if (p.source === 'user')
781
+ flagsList.push('user asked');
743
782
  console.log(` - ${p.id} [${p.scope}/${p.action}] (${flagsList.join(', ')}): ${p.summary}`);
744
783
  if (p.status === 'awaiting_commit' && p.targetFilePath) {
745
784
  console.log(` file: ${p.targetFilePath} — run "git add ${p.targetFilePath} && git commit" to activate`);
@@ -954,7 +993,7 @@ Commands:
954
993
  setup --read-only <git-url> [path] (a host that only reads, e.g. a server)
955
994
  remote add <git-url> [--allow-public] | remote remove
956
995
  push
957
- config [set-path <personal|team> <new-path> | set-submit-mode <auto|pr> | set-push-mode <ask|auto|never> | unset <personal|team>]
996
+ config [set-path <personal|team> <new-path> | set-submit-mode <auto|pr> | set-push-mode <ask|auto|never> | set-direct-save <on|off> | unset <personal|team>]
958
997
  init [folder] [--remote <git-url>] [--preview | --undo] [--engine claude-code,antigravity,claude-desktop,cursor,codex] [--project-hint]
959
998
  compile [--check] [--repo <dir>]
960
999
  sync [--timeout <ms>]
@@ -965,6 +1004,7 @@ Commands:
965
1004
  web [--port <n>] [--no-open] [--idle-timeout <min>] [--read-only]
966
1005
  approve <proposal-id> [...] [--mode auto|pr] [--yes]
967
1006
  reject <proposal-id> | reject --all [--yes]
1007
+ undo <entry-id> [--yes] (undo a memory saved directly on your word)
968
1008
  reset [--include-personal-repo] [--yes]
969
1009
  import --from <markdown-dir|claude-memory|agents-md|cursor-rules> <path> [--scope personal|team|project] [--split-headings] [--normalize-paths] [--approve]
970
1010
  serve
@@ -67,6 +67,7 @@ export function loadConfig(homeDir = getHomeDir()) {
67
67
  ? raw.similarityThreshold
68
68
  : DEFAULT_SIMILARITY_THRESHOLD,
69
69
  ...(typeof raw.similarityHintFloor === 'number' ? { similarityHintFloor: raw.similarityHintFloor } : {}),
70
+ ...(typeof raw.directUserSave === 'boolean' ? { directUserSave: raw.directUserSave } : {}),
70
71
  roots: raw.roots || {},
71
72
  };
72
73
  }
@@ -0,0 +1,53 @@
1
+ import { Proposal, ProposalAction, StagedReason, UserConfig } from './types.js';
2
+ /** 06 FR-06: direct saves allowed per MCP server process; later ones are staged. */
3
+ export declare const DIRECT_SAVE_SESSION_CAP = 5;
4
+ /** 06 FR-01: longest accepted `user_quote`. */
5
+ export declare const MAX_USER_QUOTE_CHARS = 1000;
6
+ export declare const DIRECT_SAVE_RECENT_DAYS = 7;
7
+ export interface DirectSaveRecord {
8
+ type: 'save' | 'undo';
9
+ ts: string;
10
+ entryId: string;
11
+ /** Full SHA of the direct-save commit (for `undo`, the commit that was reverted). */
12
+ commit: string;
13
+ action?: ProposalAction;
14
+ summary?: string;
15
+ quote?: string;
16
+ /** `undo` only: the revert commit. */
17
+ revertCommit?: string;
18
+ }
19
+ export declare function getDirectSaveLogPath(homeDir?: string): string;
20
+ export declare function isDirectUserSaveOn(config: UserConfig): boolean;
21
+ export declare function readDirectSaveRecords(homeDir?: string): DirectSaveRecord[];
22
+ /** Latest direct save per entry id that has not been undone. */
23
+ export declare function getActiveDirectSaves(homeDir?: string): Map<string, DirectSaveRecord>;
24
+ export declare function countRecentDirectSaves(homeDir?: string, days?: number, now?: number): number;
25
+ export type DirectSaveResult = {
26
+ ok: true;
27
+ commit: string;
28
+ estimatedTokens: number;
29
+ budget: number;
30
+ } | {
31
+ ok: false;
32
+ stagedReason: StagedReason;
33
+ errors: string[];
34
+ };
35
+ /**
36
+ * 06 FR-02: write the entry, make one commit, recompile L0 once. On a failed recompile the
37
+ * commit is undone and the caller stages the proposal instead. Pull and push are the caller's.
38
+ */
39
+ export declare function directSavePersonal(config: UserConfig, proposal: Proposal, homeDir?: string): DirectSaveResult;
40
+ /**
41
+ * After a push that rebased the direct-save commit onto origin (03 FR-04), point the log at
42
+ * the rebased commit and recompile L0 (remote entries may have come in underneath).
43
+ * Returns the new full SHA, or null when the commit did not move.
44
+ */
45
+ export declare function followRebasedDirectSave(config: UserConfig, commit: string, homeDir?: string): string | null;
46
+ export interface UndoResult {
47
+ ok: boolean;
48
+ messages: string[];
49
+ errors: string[];
50
+ revertCommit?: string;
51
+ }
52
+ /** 06 FR-06: revert the latest direct-save commit of an entry in one commit and recompile L0. */
53
+ export declare function undoDirectSave(config: UserConfig, entryId: string, homeDir?: string): UndoResult;
@@ -0,0 +1,226 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { getHomeDir, getStateDir } from './config.js';
4
+ import { compileGlobalL0 } from './compiler.js';
5
+ import { ensureGitIdentity, gitCommitFiles, gitSync, readHeadFile } from './git.js';
6
+ import { appendMetric } from './metrics.js';
7
+ import { isReadOnlyRoot, READ_ONLY_MESSAGE } from './personal-remote.js';
8
+ import { applyProposalFilesToDir } from './proposals.js';
9
+ // Feature 06: user-dictated memory saved directly to the personal root.
10
+ /** 06 FR-06: direct saves allowed per MCP server process; later ones are staged. */
11
+ export const DIRECT_SAVE_SESSION_CAP = 5;
12
+ /** 06 FR-01: longest accepted `user_quote`. */
13
+ export const MAX_USER_QUOTE_CHARS = 1000;
14
+ export const DIRECT_SAVE_RECENT_DAYS = 7;
15
+ export function getDirectSaveLogPath(homeDir = getHomeDir()) {
16
+ return path.join(getStateDir(homeDir), 'direct-saves.jsonl');
17
+ }
18
+ export function isDirectUserSaveOn(config) {
19
+ return config.directUserSave !== false;
20
+ }
21
+ function appendRecord(record, homeDir) {
22
+ fs.mkdirSync(getStateDir(homeDir), { recursive: true });
23
+ fs.appendFileSync(getDirectSaveLogPath(homeDir), `${JSON.stringify(record)}\n`, 'utf8');
24
+ }
25
+ export function readDirectSaveRecords(homeDir = getHomeDir()) {
26
+ let raw = '';
27
+ try {
28
+ raw = fs.readFileSync(getDirectSaveLogPath(homeDir), 'utf8');
29
+ }
30
+ catch {
31
+ return [];
32
+ }
33
+ const out = [];
34
+ for (const line of raw.split('\n')) {
35
+ if (!line.trim())
36
+ continue;
37
+ try {
38
+ const rec = JSON.parse(line);
39
+ if ((rec.type === 'save' || rec.type === 'undo') && rec.entryId && rec.commit)
40
+ out.push(rec);
41
+ }
42
+ catch {
43
+ // Skip a malformed line.
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ /** Latest direct save per entry id that has not been undone. */
49
+ export function getActiveDirectSaves(homeDir = getHomeDir()) {
50
+ const active = new Map();
51
+ for (const rec of readDirectSaveRecords(homeDir)) {
52
+ if (rec.type === 'save')
53
+ active.set(rec.entryId, rec);
54
+ else if (active.get(rec.entryId)?.commit === rec.commit)
55
+ active.delete(rec.entryId);
56
+ }
57
+ return active;
58
+ }
59
+ export function countRecentDirectSaves(homeDir = getHomeDir(), days = DIRECT_SAVE_RECENT_DAYS, now = Date.now()) {
60
+ const since = now - days * 24 * 60 * 60 * 1000;
61
+ return readDirectSaveRecords(homeDir).filter((r) => r.type === 'save' && Date.parse(r.ts) >= since).length;
62
+ }
63
+ function headSha(repoDir) {
64
+ return gitSync(['-C', repoDir, 'rev-parse', 'HEAD']).stdout.trim();
65
+ }
66
+ /** Undo the last commit and restore the touched files, leaving other working-tree edits alone. */
67
+ function rollbackLastCommit(repoDir, touched, priorHead) {
68
+ if (priorHead) {
69
+ gitSync(['-C', repoDir, 'reset', '--mixed', '--quiet', priorHead]);
70
+ }
71
+ else {
72
+ gitSync(['-C', repoDir, 'update-ref', '-d', 'HEAD']);
73
+ gitSync(['-C', repoDir, 'rm', '-r', '--cached', '--quiet', '--', ...touched]);
74
+ }
75
+ for (const rel of touched) {
76
+ if (priorHead && readHeadFile(repoDir, rel) !== null) {
77
+ gitSync(['-C', repoDir, 'checkout', 'HEAD', '--', rel]);
78
+ }
79
+ else {
80
+ fs.rmSync(path.join(repoDir, rel), { force: true });
81
+ }
82
+ }
83
+ }
84
+ /**
85
+ * 06 FR-02: write the entry, make one commit, recompile L0 once. On a failed recompile the
86
+ * commit is undone and the caller stages the proposal instead. Pull and push are the caller's.
87
+ */
88
+ export function directSavePersonal(config, proposal, homeDir = getHomeDir()) {
89
+ const root = config.roots.personal;
90
+ if (!root)
91
+ return { ok: false, stagedReason: 'compile_error', errors: ['Personal memory root is not configured.'] };
92
+ const priorHead = headSha(root.path);
93
+ const touched = applyProposalFilesToDir(root.path, '', proposal);
94
+ const subject = `memory(${proposal.action}): ${proposal.entryId} [user]`;
95
+ const quote = (proposal.userQuote || '').replace(/\s+/g, ' ').trim();
96
+ try {
97
+ gitCommitFiles(root.path, touched, `${subject}\n\nUser asked: "${quote}"`);
98
+ }
99
+ catch (err) {
100
+ // Nothing was committed: put the touched files back as they were.
101
+ if (headSha(root.path) === priorHead) {
102
+ for (const rel of touched) {
103
+ gitSync(['-C', root.path, 'reset', '--quiet', '--', rel]);
104
+ if (priorHead && readHeadFile(root.path, rel) !== null) {
105
+ gitSync(['-C', root.path, 'checkout', 'HEAD', '--', rel]);
106
+ }
107
+ else {
108
+ fs.rmSync(path.join(root.path, rel), { force: true });
109
+ }
110
+ }
111
+ }
112
+ throw err;
113
+ }
114
+ const commit = headSha(root.path);
115
+ const comp = compileGlobalL0(config, { homeDir, trigger: 'approve' });
116
+ if (!comp.ok) {
117
+ rollbackLastCommit(root.path, touched, priorHead);
118
+ const budget = comp.errors.some((e) => e.includes('exceeds token budget'));
119
+ return { ok: false, stagedReason: budget ? 'l0_budget' : 'compile_error', errors: comp.errors };
120
+ }
121
+ appendRecord({
122
+ type: 'save',
123
+ ts: new Date().toISOString(),
124
+ entryId: proposal.entryId,
125
+ commit,
126
+ action: proposal.action,
127
+ summary: proposal.summary,
128
+ quote,
129
+ }, homeDir);
130
+ return { ok: true, commit, estimatedTokens: comp.estimatedTokens, budget: comp.budget };
131
+ }
132
+ /**
133
+ * After a push that rebased the direct-save commit onto origin (03 FR-04), point the log at
134
+ * the rebased commit and recompile L0 (remote entries may have come in underneath).
135
+ * Returns the new full SHA, or null when the commit did not move.
136
+ */
137
+ export function followRebasedDirectSave(config, commit, homeDir = getHomeDir()) {
138
+ const root = config.roots.personal;
139
+ if (!root)
140
+ return null;
141
+ const head = headSha(root.path);
142
+ if (!head || head === commit)
143
+ return null;
144
+ const message = gitSync(['-C', root.path, 'log', '-1', '--format=%B', commit]);
145
+ if (!message.ok)
146
+ return null;
147
+ const candidates = gitSync(['-C', root.path, 'log', '-n', '50', '--format=%H', 'HEAD']);
148
+ if (!candidates.ok)
149
+ return null;
150
+ let moved = null;
151
+ for (const sha of candidates.stdout.split('\n').map((l) => l.trim()).filter(Boolean)) {
152
+ if (sha === commit)
153
+ return null; // still in history: it was not rewritten
154
+ const body = gitSync(['-C', root.path, 'log', '-1', '--format=%B', sha]);
155
+ if (body.ok && body.stdout === message.stdout) {
156
+ moved = sha;
157
+ break;
158
+ }
159
+ }
160
+ if (!moved)
161
+ return null;
162
+ const logPath = getDirectSaveLogPath(homeDir);
163
+ try {
164
+ const raw = fs.readFileSync(logPath, 'utf8');
165
+ fs.writeFileSync(logPath, raw.split(`"commit":"${commit}"`).join(`"commit":"${moved}"`), 'utf8');
166
+ }
167
+ catch {
168
+ // The log is advisory; undo then explains that it cannot find the commit.
169
+ }
170
+ compileGlobalL0(config, { homeDir, trigger: 'approve' });
171
+ return moved;
172
+ }
173
+ /** 06 FR-06: revert the latest direct-save commit of an entry in one commit and recompile L0. */
174
+ export function undoDirectSave(config, entryId, homeDir = getHomeDir()) {
175
+ const root = config.roots.personal;
176
+ if (!root)
177
+ return { ok: false, messages: [], errors: ['Personal memory root is not configured.'] };
178
+ if (isReadOnlyRoot(root))
179
+ return { ok: false, messages: [], errors: [READ_ONLY_MESSAGE] };
180
+ const rec = getActiveDirectSaves(homeDir).get(entryId);
181
+ if (!rec) {
182
+ return {
183
+ ok: false,
184
+ messages: [],
185
+ errors: [`No direct save of "${entryId}" to undo. To remove another entry, use the web UI (faber-memory web).`],
186
+ };
187
+ }
188
+ const files = gitSync(['-C', root.path, 'show', '--name-only', '--format=', rec.commit]);
189
+ if (!files.ok) {
190
+ return { ok: false, messages: [], errors: [`Commit ${rec.commit.slice(0, 7)} is not in the personal root.`] };
191
+ }
192
+ for (const rel of files.stdout.split('\n').map((s) => s.trim()).filter(Boolean)) {
193
+ const last = gitSync(['-C', root.path, 'log', '-1', '--format=%H', '--', rel]).stdout.trim();
194
+ if (last && last !== rec.commit) {
195
+ return {
196
+ ok: false,
197
+ messages: [],
198
+ errors: [`${rel} changed in a later commit (${last.slice(0, 7)}); undo it by hand or edit the entry instead.`],
199
+ };
200
+ }
201
+ }
202
+ ensureGitIdentity(root.path);
203
+ const priorHead = headSha(root.path);
204
+ const revert = gitSync(['-C', root.path, 'revert', '--no-edit', rec.commit]);
205
+ if (!revert.ok) {
206
+ gitSync(['-C', root.path, 'revert', '--abort']);
207
+ return { ok: false, messages: [], errors: [`git revert failed: ${revert.stderr.trim()}`] };
208
+ }
209
+ const revertCommit = headSha(root.path);
210
+ const comp = compileGlobalL0(config, { homeDir, trigger: 'approve' });
211
+ if (!comp.ok) {
212
+ // Keep HEAD and the compiled L0 in step: drop the revert commit again.
213
+ const reverted = gitSync(['-C', root.path, 'show', '--name-only', '--format=', revertCommit]);
214
+ rollbackLastCommit(root.path, reverted.stdout.split('\n').map((l) => l.trim()).filter(Boolean), priorHead);
215
+ return {
216
+ ok: false,
217
+ messages: [],
218
+ errors: [`Undo stopped: the startup index would not compile without this save. Nothing was changed.`, ...comp.errors],
219
+ };
220
+ }
221
+ appendRecord({ type: 'undo', ts: new Date().toISOString(), entryId, commit: rec.commit, revertCommit }, homeDir);
222
+ appendMetric({ type: 'review_outcome', ts: new Date().toISOString(), scope: 'personal', outcome: 'undone' }, homeDir);
223
+ const messages = [`Undid the direct save of ${entryId} (revert commit ${revertCommit.slice(0, 7)}).`];
224
+ messages.push(`Recompiled L0 (${comp.estimatedTokens}/${comp.budget} tokens); it applies to new sessions.`);
225
+ return { ok: true, messages, errors: [], revertCommit };
226
+ }