renor-engine 1.4.0 → 1.4.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/README.md CHANGED
@@ -1,143 +1,133 @@
1
- [Português (Brasil) → README.pt-BR.md](README.pt-BR.md)
1
+ <div align="center">
2
2
 
3
- # Renor
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/renor-logo-light.svg">
5
+ <img alt="Renor" src="docs/assets/renor-logo-dark.svg" width="420">
6
+ </picture>
4
7
 
5
- ![Claude Code saves a decision to Renor; a fresh Codex session recalls it](docs/assets/renor-readme-demo.gif)\
6
- *Self-hosted Renor, real session: Claude Code saves a decision, a fresh Codex session recalls it. Waiting time sped up.*
8
+ <h3>Shared memory for coding agents, over MCP.</h3>
7
9
 
8
- [![engine-public-ci](https://github.com/renorai/renor-engine/actions/workflows/engine-public-ci.yml/badge.svg?branch=main)](https://github.com/renorai/renor-engine/actions/workflows/engine-public-ci.yml)
10
+ What one agent learns in a session, every agent knows in the next.
9
11
 
10
- **Renor is memory for coding agents: it keeps what you tell Claude Code, Codex or Cursor in a folder of Markdown files on your machine, and serves it back to any of them over MCP.**
12
+ </div>
11
13
 
12
- Every new agent session starts from zero: you re-explain the project, last week's decision and why, the thing you corrected twice. With Renor, one agent saves it and the next one finds it. The memory is plain files you own. It runs locally, needs no account or API key, and sends nothing off your machine unless you configure a model or send anonymous usage numbers (on by default, with a first-run notice; `renor-engine telemetry off` or `DO_NOT_TRACK=1` turns them off). Your memory text is shared only if you say yes to that separately. A hosted version with no install is at <https://renor.cloud>.
14
+ ## How it works
13
15
 
14
- Renor needs Node.js 22.16 or later (22.16+ or 24+). On an older Node, `renor-engine` prints one message saying so and exits.
16
+ 1. **Tell one agent once:** a decision, a root cause, a correction.
17
+ 2. **Renor saves it** as plain Markdown you own.
18
+ 3. **Every agent recalls it** in its next session: Claude Code, Codex, Cursor, Grok, Gemini, VS Code, OpenCode, Pi or any MCP client.
15
19
 
16
20
  ## Quickstart
17
21
 
18
- Requires Node.js 22.16 or later (22.16+ or 24+); older Node prints a one-line message and exits.
22
+ Two ways in. Both take under a minute.
19
23
 
20
- You need **Node 22** and git. The install is the only step that needs the network.
24
+ ### Hosted: the easiest path
21
25
 
22
26
  ```bash
23
- git clone https://github.com/renorai/renor-engine.git
24
- cd renor-engine
25
- node -v # v22.16 or newer
26
- npm ci && npm run build
27
- node scripts/smoke-self-hosted.mjs
27
+ npx renor connect --client claude-code
28
28
  ```
29
29
 
30
- The last command starts the MCP server, saves one fact (`Ada favorite_color cerulean`), searches for it three ways and stops. It works in a temporary folder that it deletes afterwards, so it never touches your notes. It ends with:
30
+ `--client` is `claude-code`, `codex`, `cursor`, `grok`, `gemini`, `vscode`, `opencode` or `pi`. One command adds Renor to that app, signs you in through the app's own flow (no token to copy), writes the memory rule below, and ends with a live check that your workspace answers. Search is hybrid (keywords and meaning). Sign up at [renor.cloud](https://renor.cloud).
31
31
 
32
- ```text
33
- PASS: self-hosted stdio MCP can remember and retrieve a current fact.
34
- ```
35
-
36
- Downloaded a ZIP instead of cloning? It has no git history to stamp the build with, so build with `RENOR_BUILD_COMMIT=0000000 npm run build` instead. A wrong Node version or skipped install scripts: see [Troubleshooting](docs/self-hosting.md#troubleshooting).
32
+ ### Self-hosted: the private path
37
33
 
38
- ## Connect your agent
39
-
40
- **Without a clone.** With Node 22 installed, one line registers the published package. Your notes go to a hidden `.renor` folder in your home directory (`~/.renor`, printed on stderr at start; it never reuses an existing `renor` folder); to use another folder, add `-e VAULT_PATH=/absolute/path` to the `claude` line or `--env VAULT_PATH=/absolute/path` to the `codex` line. The first start downloads about 12 MB and takes about 3 seconds (measured on a clean npm cache); if your agent shows one failed connection, restart it. Search is by keyword by default; the optional local meaning-search model is a separate one-time download, only when `EMBEDDING_PROVIDER=local`.
34
+ Your memory stays in a folder on your machine. No account, no API key. You need Node.js 22.16 or later (22.16+ or 24+); on an older Node, `renor-engine` prints one line saying so and exits.
41
35
 
42
36
  ```bash
43
37
  claude mcp add --scope user renor-local -- npx -y renor-engine mcp
44
38
  codex mcp add renor-local -- npx -y renor-engine mcp
45
39
  ```
46
40
 
47
- **Grok.** Register it for the project (Grok does not start project-scope servers in a folder it does not trust, and the session that ran this command does not have them):
41
+ Restart the agent. The first start downloads about 12 MB, and the first Renor call works about 3 seconds after an empty start. Notes go to `~/.renor` (set `VAULT_PATH` to use another folder).
48
42
 
49
- ```bash
50
- grok mcp add --scope project renor -- npx -y renor-engine mcp
51
- ```
43
+ **Then add [the memory rule](#the-memory-rule)** to the agent's instructions file, so it saves on its own.
52
44
 
53
- Trust the folder in Grok, then restart Grok. Check it in three steps: (1) ask Grok to save a real decision from your project (for example, "remember that we use Postgres 16 for the orders service"); (2) restart Grok; (3) in the new session ask "which database does the orders service use?" and it should answer from Renor. To turn telemetry off, set `DO_NOT_TRACK=1` in the environment Grok runs in.
54
-
55
- For Cursor or any other client, the server is the command `npx` with the arguments `-y renor-engine mcp`. In Cursor or VS Code (GitHub Copilot), one click adds it:
45
+ **Cursor or VS Code**, one click:
56
46
 
57
47
  [![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/install-mcp?name=renor-local&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsInJlbm9yLWVuZ2luZSIsIm1jcCJdfQ%3D%3D)
58
48
  [![Add to VS Code](https://img.shields.io/badge/VS_Code-Add_renor--local-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect/mcp/install?name=renor-local&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22renor-engine%22%2C%22mcp%22%5D%7D)
59
49
 
60
- `claude mcp remove renor-local` and `codex mcp remove renor-local` undo the two lines above. The rest of this section is the same thing from a clone, which also lets you change the code.
61
-
62
- **From a clone.**
63
-
64
- Pick a folder for your memory (a new, empty one is fine; an Obsidian vault works too) and index it. Run this, and the commands below, from the `renor-engine` directory in the same shell:
50
+ **Grok.** Grok starts project servers only in a folder it trusts, so register Renor in the project:
65
51
 
66
52
  ```bash
67
- export VAULT_PATH="$HOME/renor-notes" # absolute path; created if missing
68
- node dist/cli.js index
53
+ grok mcp add --scope project renor -- npx -y renor-engine mcp
69
54
  ```
70
55
 
71
- Each command below starts Renor with the Node 22 you are using now (`node -p process.execPath`), so the agent does not need Node 22 on its own `PATH`. In a new terminal, run the `export` line again first: each command stops with `VAULT_PATH: run the export line above first` rather than register a server that cannot start (an agent shows that only as "Connection closed").
56
+ Trust the folder in Grok, then restart Grok. To check it: ask Grok to save a real decision from your project, restart Grok, and ask about it in the new session. To turn telemetry off, set `DO_NOT_TRACK=1` in the environment Grok runs in. Paste [the memory rule](#the-memory-rule) into the project's `AGENTS.md`.
57
+
58
+ **Any other MCP client:** the command is `npx` with the arguments `-y renor-engine mcp` (stdio).
72
59
 
73
- **Claude Code**
60
+ **Check it works:**
74
61
 
75
62
  ```bash
76
- claude mcp add --scope user renor-local -e VAULT_PATH="${VAULT_PATH:?run the export line above first}" -- "$(node -p process.execPath)" "$PWD/dist/cli.js" mcp
63
+ npx renor-engine status
77
64
  ```
78
65
 
79
- Restart Claude Code; `/mcp` lists `renor-local` in every project. `claude mcp remove renor-local` undoes it.
66
+ Then tell your agent a real decision ("remember that the orders service uses Postgres 16"), start a new session, and ask about it.
80
67
 
81
- **Codex**
68
+ Running it on a server or with Docker: [docs/self-hosting.md](docs/self-hosting.md).
82
69
 
83
- ```bash
84
- codex mcp add renor-local --env VAULT_PATH="${VAULT_PATH:?run the export line above first}" -- "$(node -p process.execPath)" "$PWD/dist/cli.js" mcp
85
- ```
70
+ Several agents on one memory: start each with its own `RENOR_CONNECTION_NAME` and they get the multi-agent ("hive") tools ([details](docs/self-hosting.md)).
86
71
 
87
- Restart Codex; `codex mcp list` shows it. `codex mcp remove renor-local` undoes it.
72
+ ## The memory rule
88
73
 
89
- **Cursor**
74
+ Five lines that make agents save decisions, corrections and facts on their own. In our Grok test (grok-4.7, renor-engine 1.4.0, 3 Nov 2026), agents with the rule saved in 8 of 8 sessions and the next session recalled 5 of 5 project facts.
90
75
 
91
- Cursor reads MCP servers from `~/.cursor/mcp.json` (every project) or `.cursor/mcp.json` (one project). This prints the entry:
76
+ `renor connect` writes it for you. Self-hosted, paste it into `~/.claude/CLAUDE.md` (Claude Code), `~/.codex/AGENTS.md` (Codex) or the project's `AGENTS.md` (Grok):
92
77
 
93
- ```bash
94
- VAULT_PATH="${VAULT_PATH:?run the export line above first}" node -e 'console.log(JSON.stringify({ mcpServers: { "renor-local": { command: process.execPath,
95
- args: [process.cwd() + "/dist/cli.js", "mcp"], env: { VAULT_PATH: process.env.VAULT_PATH } } } }, null, 2))'
96
- ```
78
+ ```md
79
+ ## Renor memory
97
80
 
98
- Put it in that file, or merge the `renor-local` entry into an existing `mcpServers`, then check that `renor-local` is enabled in Cursor's MCP settings. (The `cursor-plugin/` folder of this repository is the Cursor plugin for the hosted service at renor.cloud, which needs a Renor account; it does not connect to this engine.)
99
-
100
- **Any other MCP client:** the command is `node dist/cli.js mcp` (stdio) with `VAULT_PATH` set.
81
+ Renor is connected to this app and remembers across sessions.
82
+ - Before deciding anything non-trivial, recall first: one get_context call is usually enough.
83
+ - Save with remember when the user makes a decision, corrects you, or states a fact that should outlive this chat. Include the reason.
84
+ - Save the specific value (a port, a name, a path), not a summary of it.
85
+ - Do not save secrets, or things that are already in the code.
86
+ ```
101
87
 
102
- Then ask your agent to remember something, and ask about it in a new session. What an agent saves is searchable at once. A Markdown file you add or edit by hand is searchable after you run `node dist/cli.js index` again.
88
+ Self-hosted, the local tools are `search`, `remember_fact` and `note`; agents map the rule onto them ([tool list](skill/SKILL.md#stdio-renor-engine-mcp)).
103
89
 
104
- ## Run it on a server
90
+ ## What runs on your machine
105
91
 
106
- One container serves your memory over HTTP to every agent, from any machine, with OAuth sign-in for you alone. It needs no model or key; the memory stays on a volume you own.
92
+ - **Your memory is plain Markdown** in one folder you own. Edit it with anything; back it up like any folder.
93
+ - **SQLite** holds the search index, next to the notes. It is rebuilt from the Markdown at any time.
94
+ - **No embedding model needed.** Search is by keyword; when the exact words miss, it retries with word stems. Hybrid search (keywords and meaning) is the hosted default; self-hosters can opt in to OpenAI or a local model ([details](docs/self-hosting.md#embeddings)).
95
+ - **Small:** a 1.8 MB package, about 5 MB installed. About 143 MB of memory with 1,000 saved memories.
96
+ - **Telemetry:** anonymous usage numbers (never text, names or paths) are on by default, with a notice on first run. `renor-engine telemetry off` or `DO_NOT_TRACK=1` turns them off. Your memory text is never shared unless you say yes to that separately. Every field: [docs/TELEMETRY.md](docs/TELEMETRY.md).
107
97
 
108
- [![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/renorai/renor-engine)
98
+ ## Benchmarks
109
99
 
110
- ```bash
111
- docker build -t renor-engine https://github.com/renorai/renor-engine.git
112
- docker run -d --name renor -p 127.0.0.1:3471:3471 -v renor-data:/data \
113
- -e MVP_OWNER_EMAIL=you@example.com -e MVP_OWNER_PASSWORD="$(openssl rand -base64 18)" \
114
- -e MVP_ALLOWED_CALLBACK_URIS=http://localhost:39472/callback renor-engine
115
- claude mcp add --transport http --scope user --callback-port 39472 renor http://localhost:3471/mcp
116
- ```
100
+ | Benchmark | Renor | Setup |
101
+ | --- | --- | --- |
102
+ | LongMemEval-S | **98.4%** (492/500) | Deep search, off by default |
103
+ | LongMemEval-S | **94.4%** (472/500) | Default settings |
104
+ | LoCoMo (categories 1 to 4) | **96.7%** (1,489/1,540) | Deep search |
105
+ | BEAM 128K / 1M / 10M | **76.2 / 74.7 / 60.2** | Deep search, score out of 100 |
106
+ | ConvoMem | **88.4%** (191/216) | Default search, 100 conversations per memory |
117
107
 
118
- Sign in from `/mcp` in Claude Code with that email and password (`docker exec renor printenv MVP_OWNER_PASSWORD`). Railway (`railway.toml`) and Fly.io (`fly.toml`) work the same way; [Docker and one-click hosts](docs/self-hosting.md#docker-and-one-click-hosts) has the steps for each.
108
+ Claude Opus 5.5 answers LongMemEval, LoCoMo and BEAM; DeepSeek V4.1 Flash answers ConvoMem (a research run). One run each, Oct 2026. Deep search is top-K 50 with a 4,000-token budget (`RENOR_TOPK_SCALES_BUDGET=1`). Judges and methods for every run: [renor.cloud/research](https://renor.cloud/research).
119
109
 
120
- ## What is stored where
110
+ ## Build from source
121
111
 
122
- | What | Where |
123
- | --- | --- |
124
- | Your notes | Any Markdown files in `$VAULT_PATH`. Renor reads them; edit them with anything. |
125
- | What agents save | Appended as Markdown in the same folder: facts to `System/Memory Events Ledger.md`, notes to `Memory/Daily/<date>.md`. |
126
- | Search index | SQLite at `$VAULT_PATH/.semantic-memory/index.db`. Derived: `node dist/cli.js index` rebuilds it from the Markdown. |
112
+ You need Node.js 22.16 or later and git.
127
113
 
128
- Everything Renor keeps is in that one folder, so back it up, sync it or move it like any other folder. Nothing leaves your machine unless you set a model key: `EMBEDDING_PROVIDER=openai` sends your notes' text to OpenAI to embed it, and `RENOR_EVIDENCE_MODE=auto` or `always` with an evidence-model key (`RENOR_EVIDENCE_API_KEY` or an `OLLAMA_*` key) makes search send the notes it matched to that model. The evidence pass is off unless `RENOR_EVIDENCE_MODE` is set, so a key alone sends nothing. Every setting and its default: [docs/ENVIRONMENT-VARIABLES.md](docs/ENVIRONMENT-VARIABLES.md).
114
+ ```bash
115
+ git clone https://github.com/renorai/renor-engine.git
116
+ cd renor-engine
117
+ npm ci && npm run build
118
+ node scripts/smoke-self-hosted.mjs
119
+ ```
129
120
 
130
- **Search without embeddings.** With nothing set, Renor uses no embedding model, so a note is found by its exact words: `blue notebook` finds "The blue notebook is on the desk", but `where is my notebook?` does not. Saved facts are found either way. For search by meaning, set `EMBEDDING_PROVIDER=openai` with `OPENAI_API_KEY`, or `local` to download a model once and run it on this machine, then run `node dist/cli.js rebuild` so existing notes are embedded ([details](docs/self-hosting.md#embeddings)).
121
+ The last command starts the MCP server in a temporary folder, saves one fact, finds it again and ends with `PASS: self-hosted stdio MCP can remember and retrieve a current fact.` It never touches your notes. Downloaded a ZIP instead of cloning? Build with `RENOR_BUILD_COMMIT=0000000 npm run build`. Connecting a local build to each agent: [docs/self-hosting.md](docs/self-hosting.md).
131
122
 
132
- ## More
123
+ ## Learn more
133
124
 
134
- - [docs/self-hosting.md](docs/self-hosting.md): troubleshooting, embeddings, the HTTP server with OAuth sign-in, connecting agents over HTTP, the tool lists, owner names, multi-agent ("hive") tools (set `RENOR_CONNECTION_NAME` per agent), and how the vault is protected.
135
- - [skill/SKILL.md](skill/SKILL.md): instructions to give your agent so it recalls and saves memory without being asked. Most of it names the hosted tools (`get_context`, `remember`); the `renor-local` server above has other names (`search`, `remember_fact`, `note`), listed in its [Stdio section](skill/SKILL.md#stdio-renor-engine-mcp).
125
+ [Docs](https://renor.mintlify.app) · [Self-hosting, servers and Docker](docs/self-hosting.md) · [Every setting](docs/ENVIRONMENT-VARIABLES.md) · [Telemetry](docs/TELEMETRY.md)
136
126
 
137
- Renor is a single-owner engine: one person's notes, one set of agents. It is not a multi-user product.
127
+ ## License and contributing
138
128
 
139
- ## Contributing, license, security
129
+ The engine is **Apache-2.0** ([LICENSE](LICENSE)); 1.0.0 was released under AGPL-3.0; 1.1.0 and later are Apache-2.0; files imported from the upstream project stay ISC ([NOTICE](NOTICE), [UPSTREAM.md](UPSTREAM.md)). The `renor` CLI, the SDKs and the integrations are MIT.
140
130
 
141
- Contributions are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) covers setup and tests and lists good first issues. Renor's own code is **Apache-2.0** ([LICENSE](LICENSE)); 1.0.0 was released under AGPL-3.0; 1.1.0 and later are Apache-2.0; files imported from the upstream project stay ISC ([NOTICE](NOTICE), [UPSTREAM.md](UPSTREAM.md)). Report vulnerabilities privately as described in [SECURITY.md](SECURITY.md), not in a public issue.
131
+ Contributions are welcome: [CONTRIBUTING.md](CONTRIBUTING.md) has setup, tests and good first issues. Sign off each commit with the [DCO](https://developercertificate.org/) (`git commit -s`); there is no CLA. Report vulnerabilities privately as described in [SECURITY.md](SECURITY.md).
142
132
 
143
133
  If Renor saves you re-explaining, a [⭐](https://github.com/renorai/renor-engine) helps other developers find it.
package/dist/BUILD.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
- "commit": "ae7264eabb05e0db74a71a978702631f78b86e52",
2
+ "commit": "f41ea2e63d368d5d0d38a9c0aa78b09b283d2670",
3
3
  "branch": "unknown",
4
4
  "dirty": null,
5
- "builtAt": "2026-11-03T15:32:19.048Z"
5
+ "builtAt": "2026-11-04T01:16:56.927Z"
6
6
  }
package/dist/cli.js CHANGED
@@ -1309,14 +1309,35 @@ CREATE INDEX IF NOT EXISTS outcomes_at ON outcomes (at);
1309
1309
  `):[...common,"LEVEL: share data for training",' Sent: everything in "share signals", plus the TEXT of the examples: the query behind a retrieval, the text of the memories it returned,'," and the statements that were saved. Renor may use that text to train and evaluate its own models."," Memories can contain other people's personal data and information about you. A text that looks like a secret (key, password, token)"," is left out, but no scanner is perfect: choose this only if you accept that."," Every field is listed by `renor-engine telemetry fields data`, and `renor-engine telemetry preview` prints exactly what would be sent."].join(`
1310
1310
  `)}function defaultWording(){return[notice_1.NOTICE_LINE," Every field is listed by `renor-engine telemetry fields signals`, and `renor-engine telemetry preview` prints exactly what would be sent."," They are stored under a random install identifier that stays the same until you turn sharing off."," Turning it off stops recording and sending at once, and Renor is asked to delete what it holds for this install."," Sharing your memory text to help train Renor is a separate choice, never on unless you say yes: ask your agent, or run `renor-engine telemetry data`.",` (words: ${fields_1.DEFAULT_WORDING_VERSION})`].join(`
1311
1311
  `)}exports2.ADULT_LINE="I am 18 or older and I choose this myself.";function fieldList(level){return(0,fields_1.fieldsAtLevel)(level).join(`
1312
- `)}}});var require_cli=__commonJS({"dist/sharing/cli.js"(exports2){"use strict";var __importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.TELEMETRY_ACTIONS=void 0;exports2.runTelemetry=runTelemetry;var node_fs_1=__importDefault(require("node:fs")),settings_1=require_settings(),store_1=require_store(),fields_1=require_fields(),send_1=require_send2(),state_1=require_state(),wording_1=require_wording();exports2.TELEMETRY_ACTIONS=["status","signals","data","off","delete","preview","send","fields"];function memoryDirOf(options2,env){let value=(options2.memoryDir??env.MVP_MEMORY_DIR??"").trim();return value===""?null:value}async function runTelemetry(action,argument,options2,io){let env=io.env,memoryDir=memoryDirOf(options2,env),dir=(0,state_1.sharingDirFor)(memoryDir,env,options2.dir),common={dir,env,fetch:io.fetch,now:io.now,hosted:(0,state_1.hostedEngine)(env)};try{switch(action){case"status":{let own=(0,state_1.readConsent)(dir,env),record=(0,state_1.consentFor)(dir,env),state=(0,state_1.readState)(dir),override=(0,state_1.envOverride)(env),level=(0,state_1.effectiveLevel)(dir,env),fallback=(0,state_1.defaultLevel)(env),byDefault=(0,state_1.defaultInForce)(dir,env);if(io.out(`sharing: ${level}${override!==null&&level!==(record?.level??fallback)?` (lowered by the environment from ${record?.level??fallback})`:""}${byDefault?" (the default: you have not chosen)":""}`),record===null&&(0,state_1.hasChosen)(dir,env)?io.out("choice: a record is there but cannot be read, so it counts as off"):record===null&&(0,state_1.foreignConsent)(dir,env)?io.out("choice: a record is there, but it was made on another install (copied or synced in), so it counts as no choice here"):record===null&&fallback==="off"?io.out("choice: none made (the default is off; nothing is recorded for sharing or sent)"):record===null?(io.out("choice: none made (the default is usage numbers, on until you turn them off)"),io.out((0,wording_1.defaultWording)())):io.out(`choice: ${record.level}, chosen ${record.changedAt} via ${record.source}, wording ${record.wording}, 18 or older: ${record.adult?"yes":"no"}${own===null?" (this install's answer at `renor setup`, which this memory folder follows)":""}`),io.out(`folder: ${dir}`),io.out(`endpoint: ${(0,send_1.sharingEndpoint)(env)}`),state?.paused?.code==="sharing_closed"?io.out("sending: paused, Renor has closed sharing; nothing is sent until it is open again"):state?.paused?.code==="consent_required"&&io.out("sending: paused, Renor refused the consent record; choose a level again to resume"),io.out(`debug mode: ${(0,send_1.debugOn)(env)?"on (RENOR_SHARING_DEBUG): nothing is sent, bodies are printed":"off"}`),memoryDir===null)io.out("learning log: not found (set MVP_MEMORY_DIR or pass --memory-dir; sharing sends rows made from it)");else{let file=(0,settings_1.learningDbPath)(memoryDir);if(!node_fs_1.default.existsSync(file))io.out(`learning log: none at ${file}`);else{let log=store_1.LearningLog.open(file,{retentionDays:(0,settings_1.learningRetentionDays)(env),rawQueries:!1,create:!1});try{io.out(`learning log: ${file}`),log&&io.out(` rows inside the retention window: ${JSON.stringify(log.counts())}`)}finally{log?.close()}}}return state&&io.out(`sent before: ${state.everSent?"yes":"no"}${state.deletePending?"; a deletion is owed to the endpoint and will be retried":""}`),0}case"fields":{let wanted=argument===void 0?["signals","data"]:[argument];for(let level of wanted){if(level!=="signals"&&level!=="data")return io.err("usage: renor-engine telemetry fields [signals|data]"),2;io.out(`# fields sent at level ${level}`);for(let field of(0,fields_1.fieldsAtLevel)(level))io.out(field)}return 0}case"signals":case"data":{let level=action;if(io.out((0,wording_1.wordingFor)(level)),io.out(""),options2.yes!==!0){let answer=await io.ask(`${wording_1.ADULT_LINE} Share at this level? [y/N] `);if(answer===null)return io.err("No terminal to ask on: nothing was changed. Run it in a terminal, or add --yes if you have read the words above."),1;if(!answer)return io.out("Nothing was changed."),0}let result=await(0,send_1.chooseLevel)({...common,level,wording:wording_1.CLI_WORDING_VERSION,adult:!0,source:"cli"});return io.out(result.changed?`Sharing is now: ${level}. Recorded ${result.record?.changedAt}.`:`Sharing was already: ${level}.`),memoryDir===null&&io.out("Note: no learning log folder is set (MVP_MEMORY_DIR), so there is nothing to share yet."),0}case"off":{let result=await(0,send_1.chooseLevel)({...common,level:"off",wording:wording_1.CLI_WORDING_VERSION,adult:!0,source:"cli"});return result.changed?io.out("Sharing is now: off. Recording for sharing has stopped."):io.out("Sharing was already off."),io.out("Off is recorded as your choice, so a later change of the default does not turn it back on."),result.remoteDeleted===!0?io.out("Renor was asked to delete what it holds, and has."):result.deleteOwedUnderDoNotTrack?io.out("DO_NOT_TRACK=1 forbids any request, so Renor has not been asked yet to delete what it holds. The deletion is recorded here and sent the first time the engine runs without DO_NOT_TRACK=1."):result.remoteDeleted===!1&&io.out(`Renor could not be reached to delete what it holds (${result.reason??"unknown"}). The deletion is kept and retried when the service next runs.`),result.remoteDeleted===!1?1:0}case"delete":{let result=await(0,send_1.deleteAllShared)(common);if(!result.remote.ok)return io.err(result.remote.owedUnderDoNotTrack?"DO_NOT_TRACK=1 forbids any request, so Renor has not been asked yet to delete what it holds; nothing was removed here. The deletion is recorded and sent the first time the engine runs without DO_NOT_TRACK=1.":`Renor could not be reached (${result.remote.reason??"unknown"}); nothing was removed here, and the deletion is kept to retry.`),1;if(io.out(result.remote.requested?"Renor deleted what it held for this install.":"Nothing had ever been sent, so Renor holds nothing."),io.out("The local sharing files (state, saved example texts) were removed. Your choice is unchanged."),options2.local){if(memoryDir===null)return io.err("--local needs MVP_MEMORY_DIR or --memory-dir: the learning log was not touched."),1;let file=(0,settings_1.learningDbPath)(memoryDir),log=node_fs_1.default.existsSync(file)?store_1.LearningLog.open(file,{retentionDays:(0,settings_1.learningRetentionDays)(env),rawQueries:!1,create:!1}):null;if(log){try{log.deleteAll()}finally{log.close()}io.out("The local learning log was emptied.")}else io.out("There was no local learning log.")}return 0}case"preview":case"send":{if(action==="preview"&&argument!==void 0&&argument!=="signals"&&argument!=="data")return io.err("usage: renor-engine telemetry preview [signals|data]"),2;let result=await(0,send_1.shareNow)({...common,memoryDir,debug:action==="preview"?!0:void 0,previewLevel:action==="preview"&&(argument==="signals"||argument==="data")?argument:void 0});if(action==="send"&&await(0,send_1.settlePendingDelete)(common),result.status==="debug"){io.out(`# debug: nothing was sent and nothing was changed. These ${result.batches} request body(ies) are exactly what would be sent to ${(0,send_1.sharingEndpoint)(env)}:`);for(let payload of result.payloads??[])io.out(JSON.stringify(payload,null,2))}else io.out(`status: ${result.status}; level: ${result.level}; rows: ${result.rows}; batches: ${result.batches}${result.skipped?`; skipped (failed their own contract): ${result.skipped}`:""}${result.reason?`; ${result.reason}`:""}`);return result.status==="failed"?1:0}default:return io.err(`usage: renor-engine telemetry <${exports2.TELEMETRY_ACTIONS.join(" | ")}>`),2}}catch(err){return io.err(err instanceof Error?err.message:String(err)),1}}}});var require_status=__commonJS({"dist/status.js"(exports2){"use strict";var __importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.StatusError=void 0;exports2.engineStatus=engineStatus;exports2.statusLines=statusLines;var node_fs_1=__importDefault(require("node:fs")),client_js_1=require_client(),config_js_1=require_config(),walker_js_1=require_walker(),state_js_1=require_state(),buildIdentity_js_1=require_buildIdentity(),StatusError=class extends Error{};exports2.StatusError=StatusError;async function engineStatus(env=process.env){let config=(0,config_js_1.loadConfig)(),isDir=!1;try{isDir=node_fs_1.default.statSync(config.vaultPath).isDirectory()}catch{}if(!isDir)throw new StatusError(`the memory folder ${config.vaultPath} does not exist or is not a folder (set VAULT_PATH, or save a first memory)`);let files=await(0,walker_js_1.walkVault)(config.vaultPath),notes=0,facts=0,stale=files.length,lastSaved=null;if(node_fs_1.default.existsSync(config.dbPath)){let db;try{db=(0,client_js_1.openReadOnlyDb)(config.dbPath)}catch(err){throw new StatusError(`the index ${config.dbPath} cannot be opened: ${err instanceof Error?err.message:String(err)}`)}try{let rows=db.prepare("SELECT path, note_hash, modified_at FROM notes").all(),onDisk=new Set(files),byPath=new Map(rows.map(r=>[r.path,r]));notes=rows.length,facts=db.prepare("SELECT COUNT(*) AS c FROM facts").get().c,stale=0;for(let file of files){let row=byPath.get(file),mtime="";try{mtime=node_fs_1.default.statSync(file).mtime.toISOString()}catch{}(!row||row.note_hash===""||row.modified_at!==mtime)&&stale++}for(let row of rows)onDisk.has(row.path)||stale++}catch(err){throw new StatusError(`the index ${config.dbPath} cannot be read: ${err instanceof Error?err.message:String(err)}`)}finally{db.close()}}for(let file of files)try{let t=node_fs_1.default.statSync(file).mtime.toISOString();(lastSaved===null||t>lastSaved)&&(lastSaved=t)}catch{}let memoryDir=(env.MVP_MEMORY_DIR??"").trim();return{engineVersion:buildIdentity_js_1.ENGINE_VERSION,nodeVersion:process.version,memoryFolder:config.vaultPath,notes,facts,lastSaved,indexCurrent:stale===0,staleNotes:stale,fix:stale===0?null:"renor-engine index",search:config.embeddingProvider==="none"?"keyword-only":"semantic",embeddingProvider:config.embeddingProvider,sharing:(0,state_js_1.effectiveLevel)((0,state_js_1.sharingDirFor)(memoryDir===""?null:memoryDir,env,void 0),env)}}function statusLines(s){let lines=[`renor-engine ${s.engineVersion}, node ${s.nodeVersion}`,`memory folder: ${s.memoryFolder}`];return s.notes===0&&s.staleNotes===0?lines.push("memories: 0 notes, 0 facts. Nothing saved yet: save your first memory (remember something in your AI tool, or add a .md note to the folder), then run `renor-engine index`."):lines.push(`memories: ${s.notes} notes, ${s.facts} facts; last saved ${s.lastSaved??"never"}`),lines.push(s.indexCurrent?"index: current":`index: stale (${s.staleNotes} note(s) differ from the folder); fix: ${s.fix}`),lines.push(s.search==="semantic"?`search: semantic (${s.embeddingProvider})`:"search: keyword-only (set EMBEDDING_PROVIDER=openai or local for semantic search)"),lines.push(`sharing: ${s.sharing}`),lines}}});Object.defineProperty(exports,"__esModule",{value:!0});var commander_1=require_commander(),config_1=require_config(),client_1=require_client(),schema_1=require_schema(),sqlite_1=require_sqlite(),lifecycle_1=require_lifecycle(),pipeline_1=require_pipeline(),watcher_1=require_watcher(),staleness_1=require_staleness(),orchestrator_1=require_orchestrator(),readerLayout_1=require_readerLayout(),readerEvents_1=require_readerEvents(),adviceLines_1=require_adviceLines(),ledgerPresentation_1=require_ledgerPresentation(),attach_1=require_attach(),options_1=require_options(),attach_2=require_attach(),vectorIndex_1=require_vectorIndex(),openai_1=require_openai2(),local_1=require_local(),server_1=require_server(),apiAuth_1=require_apiAuth(),cli_extractors_1=require_cli_extractors(),typedFacts_1=require_typedFacts(),eventExtractor_1=require_eventExtractor(),preferenceExtractor_1=require_preferenceExtractor(),composer_1=require_composer(),readHonesty_1=require_readHonesty(),server_2=require_server4(),engine_1=require_engine2(),hashEmbedding_1=require_hashEmbedding(),parser_1=require_parser4(),writer_1=require_writer2(),sessionRouter_1=require_sessionRouter(),cli_1=require_cli(),digests_1=require_digests(),buildIdentity_1=require_buildIdentity(),status_js_1=require_status();async function setup({serving=!1}={}){let config=(0,config_1.loadConfig)(),gate=(0,staleness_1.stalenessGate)(config.vaultPath);gate.stderrLines.forEach(l=>console.error(l)),gate.fatal&&(console.error("[staleness] RENOR_VAULT_STALENESS=fatal \u2014 refusing to serve a stale vault"),process.exit(1));let db=(0,client_1.openIndexDb)(config.dbPath,(0,lifecycle_1.resolveLedgerPath)(config.vaultPath,config.memoryLedger));(0,schema_1.runMigrations)(db);try{let replayed=await(0,lifecycle_1.replayLedger)(db,config.vaultPath,config.memoryLedger,{setTornTailAside:serving});replayed>0&&console.error(`[memory] replayed ${replayed} ledger event(s)`)}catch(err){console.error("[memory] ledger replay failed:",err instanceof Error?err.message:err),db.close(),process.exit(1)}let provider;config.embeddingProvider==="local"?provider=new local_1.LocalEmbeddingProvider(config.embeddingModel):config.embeddingProvider==="eval-hash"?provider=new hashEmbedding_1.EvalHashEmbeddingProvider:config.embeddingProvider==="openai"&&(provider=new openai_1.OpenAIEmbeddingProvider(config.openaiApiKey.split(",").map(k=>k.trim()).filter(Boolean),config.embeddingModel,config.embeddingBaseURL,config.embeddingDims)),provider||console.error("[embeddings] Semantic search is off; set EMBEDDING_PROVIDER=openai to turn it on.");let vectorIndex=provider?new vectorIndex_1.VectorIndex(db,provider.dimensions):void 0;vectorIndex?.initTable();let{factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor}=(0,cli_extractors_1.buildWritePathExtractors)(config);return{config,db,provider,vectorIndex,factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor}}function armedWithoutProvider(extractors){return[(0,typedFacts_1.typedFactsEnabled)()&&!extractors.numericFactExtractor?"RENOR_TYPED_FACTS":"",(0,eventExtractor_1.chronicleEnabled)()&&!extractors.eventExtractor?"RENOR_CHRONICLE":"",(0,preferenceExtractor_1.prefsEnabled)()&&!extractors.preferenceExtractor?"RENOR_PREFS":""].filter(Boolean)}function refuseArmedWithoutProvider(db,flags){flags.length!==0&&(console.error(`[extraction] armed without a provider: ${flags.join(", ")}`),db.close(),process.exit(1))}function refuseRouterWithoutProvider(db,router){!router||router.summaryChat||(console.error("[router] armed without a provider: RENOR_SESSION_ROUTER needs RENOR_ROUTER_API_KEY(S), RENOR_EVIDENCE_API_KEY(S) or an Ollama Cloud key"),db.close(),process.exit(1))}async function buildRouterSummaries(db,config,router){let stats=await(0,sessionRouter_1.summarizeForRouter)({db,config,options:router});return console.log(`[router] summaries ${JSON.stringify(stats)}`),stats.failed>0&&console.error(`[router] ${stats.failed} note(s) left without a summary; search will not route until they have one${stats.error?` (${stats.error})`:""}`),stats.failed}function refuseDigestsWithoutProvider(db,digests){!digests||digests.chat||digests.cacheOnly||(console.error("[digests] armed without a provider: RENOR_DIGESTS needs RENOR_DIGEST_BASE_URL and RENOR_DIGEST_API_KEY(S); it never uses the evidence provider or an Ollama Cloud key instead, so nothing was sent"),db.close(),process.exit(1))}function refuseDigestsWithoutEmbeddings(db,digests,provider){!digests||provider||(console.error("[digests] armed without an embedding provider: RENOR_DIGESTS writes and looks up digests by embedding, so it needs EMBEDDING_PROVIDER (for example openai); semantic search is off, so no digest was built or read"),db.close(),process.exit(1))}async function buildDigests(db,config,digests,provider){let stats=await(0,digests_1.digestIndexedNotes)({db,config,options:digests,provider});return console.log(`[digests] ${JSON.stringify(stats)}`),stats.failed>0&&console.error(`[digests] ${stats.failed} note(s) left without a digest; search will not read them until they have one${stats.error?` (${stats.error})`:""}`),stats.failed}function printNotIndexed(names,labelWidth,tooLarge=[]){if(tooLarge.length>0){console.log(` ${"not indexed".padEnd(labelWidth)}: ${tooLarge.length} Markdown file(s) over ${pipeline_1.MAX_NOTE_BYTES/(1024*1024)} MiB (not read); split them or move them out of the memory folder, then index again`);for(let name of tooLarge.slice(0,10))console.log(` ! ${name}`);tooLarge.length>10&&console.log(` ! \u2026and ${tooLarge.length-10} more`)}if(names.length!==0){console.log(` ${"not indexed".padEnd(labelWidth)}: ${names.length} Markdown file(s) whose file or folder name is not valid UTF-8 (bad bytes are shown as \\xNN); rename them to UTF-8 names, then index again`);for(let name of names.slice(0,10))console.log(` ! ${name}`);names.length>10&&console.log(` ! \u2026and ${names.length-10} more`)}}var program=new commander_1.Command().name("renor").version(buildIdentity_1.ENGINE_VERSION);program.command("index").description("Index full vault").action(async()=>{let{config,db,provider,vectorIndex,factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor}=await setup();refuseArmedWithoutProvider(db,armedWithoutProvider({numericFactExtractor,eventExtractor,preferenceExtractor}));let router=(0,sessionRouter_1.resolveSessionRouterOptions)(config);refuseRouterWithoutProvider(db,router);let digests=(0,digests_1.resolveDigestOptions)(config);refuseDigestsWithoutProvider(db,digests),refuseDigestsWithoutEmbeddings(db,digests,provider),console.log(`Indexing: ${config.vaultPath}`);let stats=await(0,pipeline_1.indexVault)(db,config.vaultPath,{embeddingProvider:provider,vectorIndex,chunkOptions:{maxTokens:config.chunkMaxTokens,overlapTokens:config.chunkOverlapTokens},factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor},config.indexConcurrency);console.log(`Done. ${stats.indexed}/${stats.total} indexed, ${stats.errors} errors.`),printNotIndexed(stats.skippedNonUtf8Names,15,stats.skippedTooLarge);let unsummarized=router?await buildRouterSummaries(db,config,router):0,undigested=digests&&provider?await buildDigests(db,config,digests,provider):0;db.close(),(stats.errors>0||unsummarized>0||undigested>0)&&process.exit(1)});program.command("search <query>").description("Semantic search").option("-k, --top-k <n>","results","20").option("--json","machine-readable JSON output (full hit text; the benchmark client transport)").action(async(query,opts)=>{let{config,db,provider,vectorIndex}=await setup(),vaultStaleness=(0,staleness_1.stalenessJsonField)((0,staleness_1.stalenessGate)(config.vaultPath).staleness),isLedger=(0,ledgerPresentation_1.ledgerNoteMatcher)({memoryDir:config.vaultPath,ledgerRelPath:config.memoryLedger??lifecycle_1.DEFAULT_LEDGER_REL}),probe=(0,readerEvents_1.readerEventsEnabled)()&&(0,readerEvents_1.isEventQuestion)(query)?{}:void 0,retrieved=await(0,orchestrator_1.retrieveContext)(db,vectorIndex,provider,query,Number(opts.topK),config.priorityPaths,{},{isLedgerNote:isLedger,...probe?{probe}:{}}),routed=await(0,sessionRouter_1.routeSearch)({db,config,query,retrieved}),evidence=(0,options_1.resolveEvidenceToolOptions)(config),result=await(0,attach_1.attachSearchEvidence)({query,hits:routed?routed.hits:retrieved.hits,vaultPath:config.vaultPath,options:evidence,extractor:(0,attach_1.searchEvidenceEnabled)()?(0,options_1.createEvidenceExtractor)(evidence):null}),digestOptions=(0,digests_1.resolveDigestOptions)(config);refuseDigestsWithoutEmbeddings(db,digestOptions,provider);let digested=digestOptions&&provider?await(0,digests_1.attachDigest)({db,query,hits:result.hits,options:digestOptions,provider,isLedgerNote:isLedger}):null,presented=(0,ledgerPresentation_1.presentLedgerEvents)(digested?digested.hits:result.hits,isLedger),notTable=p=>!isLedger(p)&&p!==attach_1.EVIDENCE_HIT_PATH&&p!==digests_1.DIGEST_HIT_PATH,conversationNote,hits=(0,adviceLines_1.withAdviceLines)((0,readerLayout_1.readerLayoutEnabledFor)(query)?(0,readerLayout_1.layoutHitsForReader)(presented,{rankedBy:retrieved.rankedBy,isLedger:p=>isLedger(p)||p===attach_1.EVIDENCE_HIT_PATH||p===digests_1.DIGEST_HIT_PATH,isConversation:(0,readerLayout_1.conversationNoteMatcher)(db),query,turnsOf:(0,readerEvents_1.readerEventsEnabled)()?(0,readerEvents_1.noteTurnsLoader)(db):void 0,scoreTurns:probe?.queryVector&&provider&&vectorIndex&&(0,readerEvents_1.vectorsMeanSomething)(provider.identity?.kind)?(0,readerEvents_1.turnScorer)(vectorIndex,probe.queryVector):void 0}):presented,{query,turnsOf:()=>(0,readerEvents_1.noteTurnsLoader)(db),isSource:h=>(h.chunkId??0)>0&&h.notePath!==""&&notTable(h.notePath)&&(conversationNote??=(0,readerLayout_1.conversationNoteMatcher)(db))(h.notePath)});if(opts.json){let composed=(0,composer_1.structuredContextEnabled)()?(0,composer_1.composeQueryContextFromDb)(db,{query,hits:hits.filter(h=>h.notePath!==attach_1.EVIDENCE_HIT_PATH),evidence:result.evidence}):void 0,shown=stored=>stored===attach_1.EVIDENCE_HIT_PATH||stored===digests_1.DIGEST_HIT_PATH?stored:(0,engine_1.clientPath)(config.vaultPath,stored),shownHits=hits.map(h=>({...h,notePath:shown(h.notePath)})),shownRouter=routed?.report.routed?{...routed.report,routed:routed.report.routed.map(r=>({...r,notePath:shown(r.notePath)}))}:routed?.report,shownDigest=digested?{...digested.report,items:digested.report.items.map(i=>({...i,notePath:shown(i.notePath)}))}:void 0,shownEvidence=result.evidence.sessions?{...result.evidence,sessions:result.evidence.sessions.map(s=>({...s,stem:shown(s.stem)}))}:result.evidence,honesty=(0,readHonesty_1.readHonestyEnabled)()?(0,readHonesty_1.readHonestyForItems)({db,query,items:shownHits,ledgerRelPath:config.memoryLedger??lifecycle_1.DEFAULT_LEDGER_REL}):void 0;console.log(JSON.stringify({hits:shownHits.map(h=>({notePath:h.notePath,score:h.score,reason:h.reason,text:h.text,...h.session_date?{session_date:h.session_date}:{},...honesty?{provenance:(0,readHonesty_1.noteProvenance)(h.notePath,h.session_date??null)}:{}})),...composed?{composedContext:composed}:{},...honesty?{readHonesty:honesty}:{},...shownRouter?{router:shownRouter}:{},...shownDigest?{digest:shownDigest}:{},...vaultStaleness,...result.evidence.reason==="flag-off"?{}:{evidence:(0,attach_2.productEvidenceReport)(shownEvidence)}}))}else{if(routed&&console.log(`[router] ${routed.report.status}${routed.report.reason?` (${routed.report.reason})`:""}`),(0,composer_1.structuredContextEnabled)()){let composed=(0,composer_1.composeQueryContextFromDb)(db,{query,hits,evidence:result.evidence});console.log(composed.text),console.log("")}hits.forEach(h=>{console.log(`
1312
+ `)}}});var require_cli=__commonJS({"dist/sharing/cli.js"(exports2){"use strict";var __importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.TELEMETRY_ACTIONS=void 0;exports2.runTelemetry=runTelemetry;var node_fs_1=__importDefault(require("node:fs")),settings_1=require_settings(),store_1=require_store(),fields_1=require_fields(),send_1=require_send2(),state_1=require_state(),wording_1=require_wording();exports2.TELEMETRY_ACTIONS=["status","signals","data","off","delete","preview","send","fields"];function memoryDirOf(options2,env){let value=(options2.memoryDir??env.MVP_MEMORY_DIR??"").trim();return value===""?null:value}async function runTelemetry(action,argument,options2,io){let env=io.env,memoryDir=memoryDirOf(options2,env),dir=(0,state_1.sharingDirFor)(memoryDir,env,options2.dir),common={dir,env,fetch:io.fetch,now:io.now,hosted:(0,state_1.hostedEngine)(env)};try{switch(action){case"status":{let own=(0,state_1.readConsent)(dir,env),record=(0,state_1.consentFor)(dir,env),state=(0,state_1.readState)(dir),override=(0,state_1.envOverride)(env),level=(0,state_1.effectiveLevel)(dir,env),fallback=(0,state_1.defaultLevel)(env),byDefault=(0,state_1.defaultInForce)(dir,env);if(io.out(`sharing: ${level}${override!==null&&level!==(record?.level??fallback)?` (lowered by the environment from ${record?.level??fallback})`:""}${byDefault?" (the default: you have not chosen)":""}`),record===null&&(0,state_1.hasChosen)(dir,env)?io.out("choice: a record is there but cannot be read, so it counts as off"):record===null&&(0,state_1.foreignConsent)(dir,env)?io.out("choice: a record is there, but it was made on another install (copied or synced in), so it counts as no choice here"):record===null&&fallback==="off"?io.out("choice: none made (the default is off; nothing is recorded for sharing or sent)"):record===null?(io.out("choice: none made (the default is usage numbers, on until you turn them off)"),io.out((0,wording_1.defaultWording)())):io.out(`choice: ${record.level}, chosen ${record.changedAt} via ${record.source}, wording ${record.wording}, 18 or older: ${record.adult?"yes":"no"}${own===null?" (this install's answer at `renor setup`, which this memory folder follows)":""}`),io.out(`folder: ${dir}`),io.out(`endpoint: ${(0,send_1.sharingEndpoint)(env)}`),state?.paused?.code==="sharing_closed"?io.out("sending: paused, Renor has closed sharing; nothing is sent until it is open again"):state?.paused?.code==="consent_required"&&io.out("sending: paused, Renor refused the consent record; choose a level again to resume"),io.out(`debug mode: ${(0,send_1.debugOn)(env)?"on (RENOR_SHARING_DEBUG): nothing is sent, bodies are printed":"off"}`),memoryDir===null)io.out("learning log: not found (set MVP_MEMORY_DIR or pass --memory-dir; sharing sends rows made from it)");else{let file=(0,settings_1.learningDbPath)(memoryDir);if(!node_fs_1.default.existsSync(file))io.out(`learning log: none at ${file}`);else{let log=store_1.LearningLog.open(file,{retentionDays:(0,settings_1.learningRetentionDays)(env),rawQueries:!1,create:!1});try{io.out(`learning log: ${file}`),log&&io.out(` rows inside the retention window: ${JSON.stringify(log.counts())}`)}finally{log?.close()}}}return state&&io.out(`sent before: ${state.everSent?"yes":"no"}${state.deletePending?"; a deletion is owed to the endpoint and will be retried":""}`),0}case"fields":{let wanted=argument===void 0?["signals","data"]:[argument];for(let level of wanted){if(level!=="signals"&&level!=="data")return io.err("usage: renor-engine telemetry fields [signals|data]"),2;io.out(`# fields sent at level ${level}`);for(let field of(0,fields_1.fieldsAtLevel)(level))io.out(field)}return 0}case"signals":case"data":{let level=action;if(io.out((0,wording_1.wordingFor)(level)),io.out(""),options2.yes!==!0){let answer=await io.ask(`${wording_1.ADULT_LINE} Share at this level? [y/N] `);if(answer===null)return io.err("No terminal to ask on: nothing was changed. Run it in a terminal, or add --yes if you have read the words above."),1;if(!answer)return io.out("Nothing was changed."),0}let result=await(0,send_1.chooseLevel)({...common,level,wording:wording_1.CLI_WORDING_VERSION,adult:!0,source:"cli"});return io.out(result.changed?`Sharing is now: ${level}. Recorded ${result.record?.changedAt}.`:`Sharing was already: ${level}.`),memoryDir===null&&io.out("Note: no learning log folder is set (MVP_MEMORY_DIR), so there is nothing to share yet."),0}case"off":{let result=await(0,send_1.chooseLevel)({...common,level:"off",wording:wording_1.CLI_WORDING_VERSION,adult:!0,source:"cli"});return result.changed?io.out("Sharing is now: off. Recording for sharing has stopped."):io.out("Sharing was already off."),io.out("Off is recorded as your choice, so a later change of the default does not turn it back on."),result.remoteDeleted===!0?io.out("Renor was asked to delete what it holds, and has."):result.deleteOwedUnderDoNotTrack?io.out("DO_NOT_TRACK=1 forbids any request, so Renor has not been asked yet to delete what it holds. The deletion is recorded here and sent the first time the engine runs without DO_NOT_TRACK=1."):result.remoteDeleted===!1&&io.out(`Renor could not be reached to delete what it holds (${result.reason??"unknown"}). The deletion is kept and retried when the service next runs.`),result.remoteDeleted===!1?1:0}case"delete":{let result=await(0,send_1.deleteAllShared)(common);if(!result.remote.ok)return io.err(result.remote.owedUnderDoNotTrack?"DO_NOT_TRACK=1 forbids any request, so Renor has not been asked yet to delete what it holds; nothing was removed here. The deletion is recorded and sent the first time the engine runs without DO_NOT_TRACK=1.":`Renor could not be reached (${result.remote.reason??"unknown"}); nothing was removed here, and the deletion is kept to retry.`),1;if(io.out(result.remote.requested?"Renor deleted what it held for this install.":"Nothing had ever been sent, so Renor holds nothing."),io.out("The local sharing files (state, saved example texts) were removed. Your choice is unchanged."),options2.local){if(memoryDir===null)return io.err("--local needs MVP_MEMORY_DIR or --memory-dir: the learning log was not touched."),1;let file=(0,settings_1.learningDbPath)(memoryDir),log=node_fs_1.default.existsSync(file)?store_1.LearningLog.open(file,{retentionDays:(0,settings_1.learningRetentionDays)(env),rawQueries:!1,create:!1}):null;if(log){try{log.deleteAll()}finally{log.close()}io.out("The local learning log was emptied.")}else io.out("There was no local learning log.")}return 0}case"preview":case"send":{if(action==="preview"&&argument!==void 0&&argument!=="signals"&&argument!=="data")return io.err("usage: renor-engine telemetry preview [signals|data]"),2;let result=await(0,send_1.shareNow)({...common,memoryDir,debug:action==="preview"?!0:void 0,previewLevel:action==="preview"&&(argument==="signals"||argument==="data")?argument:void 0});if(action==="send"&&await(0,send_1.settlePendingDelete)(common),result.status==="debug"){io.out(`# debug: nothing was sent and nothing was changed. These ${result.batches} request body(ies) are exactly what would be sent to ${(0,send_1.sharingEndpoint)(env)}:`);for(let payload of result.payloads??[])io.out(JSON.stringify(payload,null,2))}else io.out(`status: ${result.status}; level: ${result.level}; rows: ${result.rows}; batches: ${result.batches}${result.skipped?`; skipped (failed their own contract): ${result.skipped}`:""}${result.reason?`; ${result.reason}`:""}`);return result.status==="failed"?1:0}default:return io.err(`usage: renor-engine telemetry <${exports2.TELEMETRY_ACTIONS.join(" | ")}>`),2}}catch(err){return io.err(err instanceof Error?err.message:String(err)),1}}}});var require_status=__commonJS({"dist/status.js"(exports2){"use strict";var __importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.StatusError=void 0;exports2.engineStatus=engineStatus;exports2.statusLines=statusLines;var node_fs_1=__importDefault(require("node:fs")),client_js_1=require_client(),config_js_1=require_config(),walker_js_1=require_walker(),state_js_1=require_state(),buildIdentity_js_1=require_buildIdentity(),StatusError=class extends Error{};exports2.StatusError=StatusError;async function engineStatus(env=process.env){let config=(0,config_js_1.loadConfig)(),isDir=!1;try{isDir=node_fs_1.default.statSync(config.vaultPath).isDirectory()}catch{}if(!isDir)throw new StatusError(`the memory folder ${config.vaultPath} does not exist or is not a folder (set VAULT_PATH, or save a first memory)`);let files=await(0,walker_js_1.walkVault)(config.vaultPath),notes=0,facts=0,stale=files.length,lastSaved=null;if(node_fs_1.default.existsSync(config.dbPath)){let db;try{db=(0,client_js_1.openReadOnlyDb)(config.dbPath)}catch(err){throw new StatusError(`the index ${config.dbPath} cannot be opened: ${err instanceof Error?err.message:String(err)}`)}try{let rows=db.prepare("SELECT path, note_hash, modified_at FROM notes").all(),onDisk=new Set(files),byPath=new Map(rows.map(r=>[r.path,r]));notes=rows.length,facts=db.prepare("SELECT COUNT(*) AS c FROM facts").get().c,stale=0;for(let file of files){let row=byPath.get(file),mtime="";try{mtime=node_fs_1.default.statSync(file).mtime.toISOString()}catch{}(!row||row.note_hash===""||row.modified_at!==mtime)&&stale++}for(let row of rows)onDisk.has(row.path)||stale++}catch(err){throw new StatusError(`the index ${config.dbPath} cannot be read: ${err instanceof Error?err.message:String(err)}`)}finally{db.close()}}for(let file of files)try{let t=node_fs_1.default.statSync(file).mtime.toISOString();(lastSaved===null||t>lastSaved)&&(lastSaved=t)}catch{}let memoryDir=(env.MVP_MEMORY_DIR??"").trim();return{engineVersion:buildIdentity_js_1.ENGINE_VERSION,nodeVersion:process.version,memoryFolder:config.vaultPath,notes,facts,lastSaved,indexCurrent:stale===0,staleNotes:stale,fix:stale===0?null:"renor-engine index",search:config.embeddingProvider==="none"?"keyword-only":"semantic",embeddingProvider:config.embeddingProvider,sharing:(0,state_js_1.effectiveLevel)((0,state_js_1.sharingDirFor)(memoryDir===""?null:memoryDir,env,void 0),env)}}function statusLines(s){let lines=[`renor-engine ${s.engineVersion}, node ${s.nodeVersion}`,`memory folder: ${s.memoryFolder}`];return s.notes===0&&s.staleNotes===0?lines.push("memories: 0 notes, 0 facts. Nothing saved yet: save your first memory (remember something in your AI tool, or add a .md note to the folder), then run `renor-engine index`."):lines.push(`memories: ${s.notes} notes, ${s.facts} facts; last saved ${s.lastSaved??"never"}`),lines.push(s.indexCurrent?"index: current":`index: stale (${s.staleNotes} note(s) differ from the folder); fix: ${s.fix}`),lines.push(s.search==="semantic"?`search: semantic (${s.embeddingProvider})`:"search: keyword-only (set EMBEDDING_PROVIDER=openai or local for semantic search)"),lines.push(`sharing: ${s.sharing}`),lines}}});var require_connect=__commonJS({"dist/connect.js"(exports2){"use strict";var __importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.APPS=exports2.RULE_TEXT=exports2.RULE_TOOLS=exports2.RULE_END=exports2.RULE_START=void 0;exports2.isApp=isApp;exports2.rulePath=rulePath;exports2.mcpEntry=mcpEntry;exports2.installRule=installRule;exports2.removeRule=removeRule;var node_fs_1=__importDefault(require("node:fs")),node_os_1=__importDefault(require("node:os")),node_path_1=__importDefault(require("node:path"));exports2.RULE_START="<!-- renor:rule:start -->";exports2.RULE_END="<!-- renor:rule:end -->";exports2.RULE_TOOLS=["search","remember_fact"];exports2.RULE_TEXT=`## Renor memory
1313
+
1314
+ Renor is connected to this app and remembers across sessions.
1315
+ - Before deciding anything non-trivial, recall first: one search call is usually enough.
1316
+ - Save with remember_fact when the user makes a decision, corrects you, or states a fact that should outlive this chat. Include the reason.
1317
+ - Save the specific value (a port, a name, a path), not a summary of it.
1318
+ - Do not save secrets, or things that are already in the code.`;var BLOCK=`${exports2.RULE_START}
1319
+ ${exports2.RULE_TEXT}
1320
+ ${exports2.RULE_END}
1321
+ `;exports2.APPS=["claude-code","codex","grok","gemini","pi","vscode"];function isApp(id){return exports2.APPS.includes(id)}function homeDir(env){return env.HOME||env.USERPROFILE||node_os_1.default.homedir()}function rulePath(app,env,cwd){let home=homeDir(env);switch(app){case"claude-code":return node_path_1.default.join(env.CLAUDE_CONFIG_DIR||node_path_1.default.join(home,".claude"),"CLAUDE.md");case"codex":return node_path_1.default.join(env.CODEX_HOME||node_path_1.default.join(home,".codex"),"AGENTS.md");case"grok":return node_path_1.default.join(cwd,"AGENTS.md");case"gemini":return node_path_1.default.join(home,".gemini","GEMINI.md");case"pi":return node_path_1.default.join(home,".pi","agent","AGENTS.md");case"vscode":return node_path_1.default.join(cwd,".github","copilot-instructions.md")}}function find(text){let start=text.indexOf(exports2.RULE_START),end=start<0?-1:text.indexOf(exports2.RULE_END,start);return start>=0&&end>=0?[start,end+exports2.RULE_END.length]:null}function mcpEntry(){return{command:"renor-engine",args:["mcp"]}}function installRule(app,env,cwd){let file=rulePath(app,env,cwd),before=node_fs_1.default.existsSync(file)?node_fs_1.default.readFileSync(file,"utf8"):"",span=find(before),after;return span?after=before.slice(0,span[0])+BLOCK.trimEnd()+before.slice(span[1]):after=before+(before&&!before.endsWith(`
1322
+ `)?`
1323
+ `:"")+(before?`
1324
+ `:"")+BLOCK,after===before?{path:file,state:"unchanged"}:(node_fs_1.default.mkdirSync(node_path_1.default.dirname(file),{recursive:!0}),node_fs_1.default.writeFileSync(file,after),{path:file,state:span?"updated":"added"})}function removeRule(app,env,cwd){let file=rulePath(app,env,cwd);if(!node_fs_1.default.existsSync(file))return{path:file,state:"absent"};let before=node_fs_1.default.readFileSync(file,"utf8"),span=find(before);if(!span)return{path:file,state:"absent"};let head=before.slice(0,span[0]).replace(/\n+$/,`
1325
+ `),tail=before.slice(span[1]).replace(/^\n/,""),after=head===`
1326
+ `?tail:head+(tail&&head?`
1327
+ `:"")+tail;return node_fs_1.default.writeFileSync(file,after),{path:file,state:"removed"}}}});Object.defineProperty(exports,"__esModule",{value:!0});var commander_1=require_commander(),config_1=require_config(),client_1=require_client(),schema_1=require_schema(),sqlite_1=require_sqlite(),lifecycle_1=require_lifecycle(),pipeline_1=require_pipeline(),watcher_1=require_watcher(),staleness_1=require_staleness(),orchestrator_1=require_orchestrator(),readerLayout_1=require_readerLayout(),readerEvents_1=require_readerEvents(),adviceLines_1=require_adviceLines(),ledgerPresentation_1=require_ledgerPresentation(),attach_1=require_attach(),options_1=require_options(),attach_2=require_attach(),vectorIndex_1=require_vectorIndex(),openai_1=require_openai2(),local_1=require_local(),server_1=require_server(),apiAuth_1=require_apiAuth(),cli_extractors_1=require_cli_extractors(),typedFacts_1=require_typedFacts(),eventExtractor_1=require_eventExtractor(),preferenceExtractor_1=require_preferenceExtractor(),composer_1=require_composer(),readHonesty_1=require_readHonesty(),server_2=require_server4(),engine_1=require_engine2(),hashEmbedding_1=require_hashEmbedding(),parser_1=require_parser4(),writer_1=require_writer2(),sessionRouter_1=require_sessionRouter(),cli_1=require_cli(),digests_1=require_digests(),buildIdentity_1=require_buildIdentity(),status_js_1=require_status(),connect_js_1=require_connect();async function setup({serving=!1}={}){let config=(0,config_1.loadConfig)(),gate=(0,staleness_1.stalenessGate)(config.vaultPath);gate.stderrLines.forEach(l=>console.error(l)),gate.fatal&&(console.error("[staleness] RENOR_VAULT_STALENESS=fatal \u2014 refusing to serve a stale vault"),process.exit(1));let db=(0,client_1.openIndexDb)(config.dbPath,(0,lifecycle_1.resolveLedgerPath)(config.vaultPath,config.memoryLedger));(0,schema_1.runMigrations)(db);try{let replayed=await(0,lifecycle_1.replayLedger)(db,config.vaultPath,config.memoryLedger,{setTornTailAside:serving});replayed>0&&console.error(`[memory] replayed ${replayed} ledger event(s)`)}catch(err){console.error("[memory] ledger replay failed:",err instanceof Error?err.message:err),db.close(),process.exit(1)}let provider;config.embeddingProvider==="local"?provider=new local_1.LocalEmbeddingProvider(config.embeddingModel):config.embeddingProvider==="eval-hash"?provider=new hashEmbedding_1.EvalHashEmbeddingProvider:config.embeddingProvider==="openai"&&(provider=new openai_1.OpenAIEmbeddingProvider(config.openaiApiKey.split(",").map(k=>k.trim()).filter(Boolean),config.embeddingModel,config.embeddingBaseURL,config.embeddingDims)),provider||console.error("[embeddings] Semantic search is off; set EMBEDDING_PROVIDER=openai to turn it on.");let vectorIndex=provider?new vectorIndex_1.VectorIndex(db,provider.dimensions):void 0;vectorIndex?.initTable();let{factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor}=(0,cli_extractors_1.buildWritePathExtractors)(config);return{config,db,provider,vectorIndex,factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor}}function armedWithoutProvider(extractors){return[(0,typedFacts_1.typedFactsEnabled)()&&!extractors.numericFactExtractor?"RENOR_TYPED_FACTS":"",(0,eventExtractor_1.chronicleEnabled)()&&!extractors.eventExtractor?"RENOR_CHRONICLE":"",(0,preferenceExtractor_1.prefsEnabled)()&&!extractors.preferenceExtractor?"RENOR_PREFS":""].filter(Boolean)}function refuseArmedWithoutProvider(db,flags){flags.length!==0&&(console.error(`[extraction] armed without a provider: ${flags.join(", ")}`),db.close(),process.exit(1))}function refuseRouterWithoutProvider(db,router){!router||router.summaryChat||(console.error("[router] armed without a provider: RENOR_SESSION_ROUTER needs RENOR_ROUTER_API_KEY(S), RENOR_EVIDENCE_API_KEY(S) or an Ollama Cloud key"),db.close(),process.exit(1))}async function buildRouterSummaries(db,config,router){let stats=await(0,sessionRouter_1.summarizeForRouter)({db,config,options:router});return console.log(`[router] summaries ${JSON.stringify(stats)}`),stats.failed>0&&console.error(`[router] ${stats.failed} note(s) left without a summary; search will not route until they have one${stats.error?` (${stats.error})`:""}`),stats.failed}function refuseDigestsWithoutProvider(db,digests){!digests||digests.chat||digests.cacheOnly||(console.error("[digests] armed without a provider: RENOR_DIGESTS needs RENOR_DIGEST_BASE_URL and RENOR_DIGEST_API_KEY(S); it never uses the evidence provider or an Ollama Cloud key instead, so nothing was sent"),db.close(),process.exit(1))}function refuseDigestsWithoutEmbeddings(db,digests,provider){!digests||provider||(console.error("[digests] armed without an embedding provider: RENOR_DIGESTS writes and looks up digests by embedding, so it needs EMBEDDING_PROVIDER (for example openai); semantic search is off, so no digest was built or read"),db.close(),process.exit(1))}async function buildDigests(db,config,digests,provider){let stats=await(0,digests_1.digestIndexedNotes)({db,config,options:digests,provider});return console.log(`[digests] ${JSON.stringify(stats)}`),stats.failed>0&&console.error(`[digests] ${stats.failed} note(s) left without a digest; search will not read them until they have one${stats.error?` (${stats.error})`:""}`),stats.failed}function printNotIndexed(names,labelWidth,tooLarge=[]){if(tooLarge.length>0){console.log(` ${"not indexed".padEnd(labelWidth)}: ${tooLarge.length} Markdown file(s) over ${pipeline_1.MAX_NOTE_BYTES/(1024*1024)} MiB (not read); split them or move them out of the memory folder, then index again`);for(let name of tooLarge.slice(0,10))console.log(` ! ${name}`);tooLarge.length>10&&console.log(` ! \u2026and ${tooLarge.length-10} more`)}if(names.length!==0){console.log(` ${"not indexed".padEnd(labelWidth)}: ${names.length} Markdown file(s) whose file or folder name is not valid UTF-8 (bad bytes are shown as \\xNN); rename them to UTF-8 names, then index again`);for(let name of names.slice(0,10))console.log(` ! ${name}`);names.length>10&&console.log(` ! \u2026and ${names.length-10} more`)}}var program=new commander_1.Command().name("renor").version(buildIdentity_1.ENGINE_VERSION);program.command("index").description("Index full vault").action(async()=>{let{config,db,provider,vectorIndex,factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor}=await setup();refuseArmedWithoutProvider(db,armedWithoutProvider({numericFactExtractor,eventExtractor,preferenceExtractor}));let router=(0,sessionRouter_1.resolveSessionRouterOptions)(config);refuseRouterWithoutProvider(db,router);let digests=(0,digests_1.resolveDigestOptions)(config);refuseDigestsWithoutProvider(db,digests),refuseDigestsWithoutEmbeddings(db,digests,provider),console.log(`Indexing: ${config.vaultPath}`);let stats=await(0,pipeline_1.indexVault)(db,config.vaultPath,{embeddingProvider:provider,vectorIndex,chunkOptions:{maxTokens:config.chunkMaxTokens,overlapTokens:config.chunkOverlapTokens},factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor},config.indexConcurrency);console.log(`Done. ${stats.indexed}/${stats.total} indexed, ${stats.errors} errors.`),printNotIndexed(stats.skippedNonUtf8Names,15,stats.skippedTooLarge);let unsummarized=router?await buildRouterSummaries(db,config,router):0,undigested=digests&&provider?await buildDigests(db,config,digests,provider):0;db.close(),(stats.errors>0||unsummarized>0||undigested>0)&&process.exit(1)});program.command("search <query>").description("Semantic search").option("-k, --top-k <n>","results","20").option("--json","machine-readable JSON output (full hit text; the benchmark client transport)").action(async(query,opts)=>{let{config,db,provider,vectorIndex}=await setup(),vaultStaleness=(0,staleness_1.stalenessJsonField)((0,staleness_1.stalenessGate)(config.vaultPath).staleness),isLedger=(0,ledgerPresentation_1.ledgerNoteMatcher)({memoryDir:config.vaultPath,ledgerRelPath:config.memoryLedger??lifecycle_1.DEFAULT_LEDGER_REL}),probe=(0,readerEvents_1.readerEventsEnabled)()&&(0,readerEvents_1.isEventQuestion)(query)?{}:void 0,retrieved=await(0,orchestrator_1.retrieveContext)(db,vectorIndex,provider,query,Number(opts.topK),config.priorityPaths,{},{isLedgerNote:isLedger,...probe?{probe}:{}}),routed=await(0,sessionRouter_1.routeSearch)({db,config,query,retrieved}),evidence=(0,options_1.resolveEvidenceToolOptions)(config),result=await(0,attach_1.attachSearchEvidence)({query,hits:routed?routed.hits:retrieved.hits,vaultPath:config.vaultPath,options:evidence,extractor:(0,attach_1.searchEvidenceEnabled)()?(0,options_1.createEvidenceExtractor)(evidence):null}),digestOptions=(0,digests_1.resolveDigestOptions)(config);refuseDigestsWithoutEmbeddings(db,digestOptions,provider);let digested=digestOptions&&provider?await(0,digests_1.attachDigest)({db,query,hits:result.hits,options:digestOptions,provider,isLedgerNote:isLedger}):null,presented=(0,ledgerPresentation_1.presentLedgerEvents)(digested?digested.hits:result.hits,isLedger),notTable=p=>!isLedger(p)&&p!==attach_1.EVIDENCE_HIT_PATH&&p!==digests_1.DIGEST_HIT_PATH,conversationNote,hits=(0,adviceLines_1.withAdviceLines)((0,readerLayout_1.readerLayoutEnabledFor)(query)?(0,readerLayout_1.layoutHitsForReader)(presented,{rankedBy:retrieved.rankedBy,isLedger:p=>isLedger(p)||p===attach_1.EVIDENCE_HIT_PATH||p===digests_1.DIGEST_HIT_PATH,isConversation:(0,readerLayout_1.conversationNoteMatcher)(db),query,turnsOf:(0,readerEvents_1.readerEventsEnabled)()?(0,readerEvents_1.noteTurnsLoader)(db):void 0,scoreTurns:probe?.queryVector&&provider&&vectorIndex&&(0,readerEvents_1.vectorsMeanSomething)(provider.identity?.kind)?(0,readerEvents_1.turnScorer)(vectorIndex,probe.queryVector):void 0}):presented,{query,turnsOf:()=>(0,readerEvents_1.noteTurnsLoader)(db),isSource:h=>(h.chunkId??0)>0&&h.notePath!==""&&notTable(h.notePath)&&(conversationNote??=(0,readerLayout_1.conversationNoteMatcher)(db))(h.notePath)});if(opts.json){let composed=(0,composer_1.structuredContextEnabled)()?(0,composer_1.composeQueryContextFromDb)(db,{query,hits:hits.filter(h=>h.notePath!==attach_1.EVIDENCE_HIT_PATH),evidence:result.evidence}):void 0,shown=stored=>stored===attach_1.EVIDENCE_HIT_PATH||stored===digests_1.DIGEST_HIT_PATH?stored:(0,engine_1.clientPath)(config.vaultPath,stored),shownHits=hits.map(h=>({...h,notePath:shown(h.notePath)})),shownRouter=routed?.report.routed?{...routed.report,routed:routed.report.routed.map(r=>({...r,notePath:shown(r.notePath)}))}:routed?.report,shownDigest=digested?{...digested.report,items:digested.report.items.map(i=>({...i,notePath:shown(i.notePath)}))}:void 0,shownEvidence=result.evidence.sessions?{...result.evidence,sessions:result.evidence.sessions.map(s=>({...s,stem:shown(s.stem)}))}:result.evidence,honesty=(0,readHonesty_1.readHonestyEnabled)()?(0,readHonesty_1.readHonestyForItems)({db,query,items:shownHits,ledgerRelPath:config.memoryLedger??lifecycle_1.DEFAULT_LEDGER_REL}):void 0;console.log(JSON.stringify({hits:shownHits.map(h=>({notePath:h.notePath,score:h.score,reason:h.reason,text:h.text,...h.session_date?{session_date:h.session_date}:{},...honesty?{provenance:(0,readHonesty_1.noteProvenance)(h.notePath,h.session_date??null)}:{}})),...composed?{composedContext:composed}:{},...honesty?{readHonesty:honesty}:{},...shownRouter?{router:shownRouter}:{},...shownDigest?{digest:shownDigest}:{},...vaultStaleness,...result.evidence.reason==="flag-off"?{}:{evidence:(0,attach_2.productEvidenceReport)(shownEvidence)}}))}else{if(routed&&console.log(`[router] ${routed.report.status}${routed.report.reason?` (${routed.report.reason})`:""}`),(0,composer_1.structuredContextEnabled)()){let composed=(0,composer_1.composeQueryContextFromDb)(db,{query,hits,evidence:result.evidence});console.log(composed.text),console.log("")}hits.forEach(h=>{console.log(`
1313
1328
  [${h.score.toFixed(3)}] ${(0,engine_1.clientPath)(config.vaultPath,h.notePath)} (${h.reason})`),console.log(h.text.substring(0,200))})}db.close()});program.command("watch").description("Watch vault for changes").action(async()=>{let{config,db,provider,vectorIndex,factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor}=await setup();refuseArmedWithoutProvider(db,armedWithoutProvider({numericFactExtractor,eventExtractor,preferenceExtractor})),console.log(`Watching: ${config.vaultPath}`),(0,watcher_1.startWatcher)(config.vaultPath,db,{embeddingProvider:provider,vectorIndex,factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor})});program.command("serve").description("Start HTTP API").option("-p, --port <n>","port","3456").action(async opts=>{let apiToken;try{apiToken=(0,apiAuth_1.requireApiToken)()}catch(err){console.error(`[serve] ${err.message}`),process.exit(1)}let{config,db,provider,vectorIndex}=await setup({serving:!0});(0,server_1.createServer)(db,vectorIndex,provider,config.vaultPath,config.priorityPaths,config.memoryDir,config.memoryLedger,{apiToken}).listen(Number(opts.port),"127.0.0.1",()=>console.log(`Listening on http://127.0.0.1:${opts.port}`))});program.command("rebuild").description("Clear derived data and reindex from scratch").action(async()=>{let{config,db,provider,vectorIndex,factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor}=await setup();refuseArmedWithoutProvider(db,armedWithoutProvider({numericFactExtractor,eventExtractor,preferenceExtractor}));let router=(0,sessionRouter_1.resolveSessionRouterOptions)(config);refuseRouterWithoutProvider(db,router);let digests=(0,digests_1.resolveDigestOptions)(config);refuseDigestsWithoutProvider(db,digests),refuseDigestsWithoutEmbeddings(db,digests,provider);let rebuildErrors=0;try{db.prepare("DROP TABLE IF EXISTS chunk_embeddings").run(),vectorIndex?.initTable(),db.transaction(()=>{["facts","relations","entities","chunks","notes","applied_ledger_events"].forEach(t=>db.prepare(`DELETE FROM ${t}`).run())})();let replayed=await(0,lifecycle_1.replayLedger)(db,config.vaultPath,config.memoryLedger);console.log(`Cleared. Replayed ${replayed} ledger event(s). Reindexing...`);let rebuildStats=await(0,pipeline_1.indexVault)(db,config.vaultPath,{embeddingProvider:provider,vectorIndex,chunkOptions:{maxTokens:config.chunkMaxTokens,overlapTokens:config.chunkOverlapTokens},factExtractor,numericFactExtractor,eventExtractor,preferenceExtractor},config.indexConcurrency);console.log(`Rebuild complete. ${rebuildStats.indexed}/${rebuildStats.total} indexed, ${rebuildStats.errors} errors.`),printNotIndexed(rebuildStats.skippedNonUtf8Names,17,rebuildStats.skippedTooLarge),rebuildErrors=rebuildStats.errors+(router?await buildRouterSummaries(db,config,router):0)+(digests&&provider?await buildDigests(db,config,digests,provider):0)}catch(err){console.error("[memory] rebuild failed:",err instanceof Error?err.message:err),db.close(),process.exit(1)}db.close(),rebuildErrors>0&&process.exit(1)});program.command("mcp").description("Start MCP server (stdio transport) for agent connectivity").action(async()=>{let{config,db,provider,vectorIndex}=await setup({serving:!0});process.env.VAULT_PATH||process.stderr.write(`Renor memory: ${config.vaultPath}
1314
1329
  `);try{await(0,server_2.startMcpServer)(db,vectorIndex,provider,config)}catch(err){process.stderr.write(`renor-engine mcp: ${err.message}
1315
1330
  `),process.exit(1)}});program.command("status").description("Show in a few lines whether the setup works: folder, notes, index, search, sharing. Makes no network call.").option("--json","print the same fields as one JSON object").action(async opts=>{try{let status=await(0,status_js_1.engineStatus)(process.env);opts.json?process.stdout.write(`${JSON.stringify(status)}
1316
1331
  `):(0,status_js_1.statusLines)(status).forEach(l=>process.stdout.write(`${l}
1317
1332
  `))}catch(err){if(!(err instanceof status_js_1.StatusError))throw err;opts.json&&process.stdout.write(`${JSON.stringify({ok:!1,error:err.message})}
1318
1333
  `),process.stderr.write(`renor-engine status: ${err.message}
1319
- `),process.exit(1)}});program.command("telemetry <action> [argument]").description("Choose what to share with Renor: off, anonymous usage numbers (signals, the default) or everything incl. memory text (data): status | signals | data | off | delete | preview [level] | send | fields [level]").option("--yes","do not ask: you have read the words shown and confirm you are 18 or older").option("--local","delete: also empty the local learning log").option("--dir <path>","the sharing folder (default: RENOR_SHARING_DIR, else ~/.config/renor)").option("--memory-dir <path>","the memory folder whose learning log is read (default: MVP_MEMORY_DIR)").action(async(action,argument,opts)=>{let readline=await import("node:readline"),code=await(0,cli_1.runTelemetry)(action,argument,opts,{out:line=>process.stdout.write(`${line}
1334
+ `),process.exit(1)}});program.command("connect <app>").description(`Connect a local app to this engine: print its MCP entry and write the memory rule into its instructions file. Apps: ${connect_js_1.APPS.join(", ")}`).option("--no-rule","print the MCP entry only; do not touch the instructions file").option("--remove","remove the memory rule block (by its markers) and nothing else").action((app,opts)=>{(0,connect_js_1.isApp)(app)||(process.stderr.write(`renor-engine connect: unknown app "${app}". Apps: ${connect_js_1.APPS.join(", ")}
1335
+ `),process.exit(1));let cwd=process.cwd();if(opts.remove){let r2=(0,connect_js_1.removeRule)(app,process.env,cwd);process.stdout.write(`${r2.state==="removed"?"Removed the Renor memory rule from":"No Renor memory rule in"} ${r2.path}
1336
+ `);return}if(process.stdout.write(`Add this MCP server to ${app}:
1337
+ ${JSON.stringify({renor:(0,connect_js_1.mcpEntry)()},null,2)}
1338
+ `),!opts.rule){process.stdout.write(`Memory rule skipped (--no-rule). It would go in ${(0,connect_js_1.rulePath)(app,process.env,cwd)}
1339
+ `);return}let r=(0,connect_js_1.installRule)(app,process.env,cwd);process.stdout.write(`Memory rule ${r.state}: ${r.path}
1340
+ `)});program.command("telemetry <action> [argument]").description("Choose what to share with Renor: off, anonymous usage numbers (signals, the default) or everything incl. memory text (data): status | signals | data | off | delete | preview [level] | send | fields [level]").option("--yes","do not ask: you have read the words shown and confirm you are 18 or older").option("--local","delete: also empty the local learning log").option("--dir <path>","the sharing folder (default: RENOR_SHARING_DIR, else ~/.config/renor)").option("--memory-dir <path>","the memory folder whose learning log is read (default: MVP_MEMORY_DIR)").action(async(action,argument,opts)=>{let readline=await import("node:readline"),code=await(0,cli_1.runTelemetry)(action,argument,opts,{out:line=>process.stdout.write(`${line}
1320
1341
  `),err:line=>process.stderr.write(`${line}
1321
1342
  `),env:process.env,ask:question=>{if(!process.stdin.isTTY)return Promise.resolve(null);let rl=readline.createInterface({input:process.stdin,output:process.stdout});return new Promise(resolve=>rl.question(question,answer=>{rl.close(),resolve(/^y(es)?$/i.test(answer.trim()))}))}});process.exit(code)});program.command("log-conversation").description("Log a Claude Code session to Obsidian vault (invoked by Stop hook)").action(async()=>{let vaultPath=process.env.VAULT_PATH,conversationsDir=process.env.CONVERSATIONS_DIR??"Claude Code/Conversations";vaultPath||(process.stderr.write(`log-conversation: VAULT_PATH not set
1322
1343
  `),process.exit(0));let chunks=[];for await(let chunk of process.stdin)chunks.push(chunk);let raw=Buffer.concat(chunks).toString("utf8").trim(),sessionId,cwd;try{let payload=JSON.parse(raw);sessionId=payload.session_id,cwd=payload.cwd}catch{process.stderr.write(`log-conversation: invalid JSON on stdin
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "renor-engine",
3
- "version": "1.4.0",
3
+ "version": "1.4.1",
4
4
  "description": "Local-first semantic memory — indexing, multi-signal retrieval, MCP",
5
5
  "main": "dist/cli.js",
6
6
  "bin": {