simple-memory 0.5.0 → 0.6.0

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
@@ -38,6 +38,17 @@ Prebuilt native Rust binaries ship through npm optional dependencies for macOS (
38
38
 
39
39
  Install globally with `npm install -g simple-memory` (not `npx`) before running `sm hooks print`, so hook and MCP configs point to a stable path. Make sure `node` is on the `PATH` seen by your hook and MCP hosts, or install the standalone native binary via `./scripts/install.sh` for minimal-`PATH` GUI hosts.
40
40
 
41
+ ### Upgrading
42
+
43
+ Check for a newer release or upgrade with `sm update`:
44
+
45
+ ```sh
46
+ sm update --check # check npm for a newer version and refresh the local cache
47
+ sm update # run npm install -g simple-memory@latest for npm installs, or print the source-upgrade command
48
+ ```
49
+
50
+ Interactive npm CLI runs also read `$SIMPLE_MEMORY_HOME/update-check.json` (refreshed in the background at most once every 24 hours) and print a one-line notice to stderr when a newer release exists. The reminder stays silent on non-TTY streams, CI, `mcp`, `hook`/`hooks`, `update`, `--format json`, `--version`/`-v`, `--help`/`-h`, or when `SM_NO_UPDATE_CHECK=1` is set.
51
+
41
52
  ### Build from source (Linux or custom Rust build)
42
53
 
43
54
  Requires [Rust (`rustup`)](https://rustup.rs/). `rust/rust-toolchain.toml` pins Rust `1.99.1`. Clone your repository copy and run:
@@ -92,7 +103,13 @@ sm query "connection pool ADR-004"
92
103
  next: sm show m_01M7R350TK1Z1DKWVWT4NSF8MQ m_01M7R350W6QV508RDWBHA9S45W; sm related m_01M7R350TK1Z1DKWVWT4NSF8MQ
93
104
  ```
94
105
 
95
- Open full body and provenance with `sm show`, update metadata or text append-only with `sm amend`, retire obsolete items with `sm retire`, or replace outdated facts with `--supersedes` (`sm supersede OLD NEW`):
106
+ `sm query` (alias `sm search`) also accepts unquoted multi-word terms, `-term` or `-"exact phrase"` exclusions (quote the query or use `--` when starting with `-` or excluding multi-word phrases in a shell), and relative `--since` / `--until` bounds (`30m`, `24h`, `7d`, `2w`):
107
+
108
+ ```sh
109
+ sm search connection pool -staging --since 7d
110
+ ```
111
+
112
+ Open full body and provenance with `sm show` (or `sm show --format json`), update metadata or text append-only with `sm amend`, retire obsolete items with `sm retire`, or replace outdated facts with `--supersedes` (`sm supersede OLD NEW`):
96
113
 
97
114
  ```sh
98
115
  sm show m_01M7R350TK1Z1DKWVWT4NSF8MQ
@@ -140,19 +157,22 @@ Example output of `sm hooks print claude-code`:
140
157
 
141
158
  1. Skips slash commands, machine-wrapped notifications, and prompts under 3 words.
142
159
  2. Uses `claude -p` (Haiku, with hooks, tools, and MCP servers off) to turn the prompt into keywords or `NONE`. Set `[prompt_hook] model = "none"` for offline IDF local-keyword search with zero model calls.
143
- 3. Falls back to local-keyword search on missing `claude`, error, or timeout (with a 10-minute cooldown after two consecutive failures), skipping built-in English stopwords plus `[prompt_hook] extra_stopwords`.
144
- 4. Injects at most 4 short lines carrying repo, kind, evidence tag, date, compact refs, and title, and tracks shown IDs per session (per compaction epoch in Claude Code, per `conversationId` in `agy`). When the prompt or rewritten query names a configured `[prompt_hook.projects]` code mapped in `[scopes]`, those scope matchers union additively with the current repo AND apply automatic `scope:<path>` bias (`+0.3` via `BIAS_BOOST`) on both the Haiku and local paths so cross-repo project notes surface without dropping local matches (opt out of automatic scope bias with `[query] default_bias = ["relevance"]`). On scopes with at least 20 active items, the Haiku path drops low-information hits whose matched-term IDF sum falls below `[prompt_hook] min_idf` (default `3.0`; `0.0` disables via `run_query`; exact ref hits bypass; dropped IDs log under `floor_dropped`). Disable per invocation with `SM_PROMPT_HOOK=0`.
160
+ 3. Falls back to local-keyword search on missing `claude`, error, or timeout (with a 10-minute cooldown after two consecutive failures that clears automatically when `claude_bin`, `model`, or `timeout` changes), skipping built-in English stopwords plus `[prompt_hook] extra_stopwords`.
161
+ 4. Injects at most 4 short lines carrying repo, kind, evidence tag, date, compact refs, and title (including `--in <scopes>` in the follow-up hint when project scopes match), and tracks shown IDs per session (per compaction epoch in Claude Code, per `conversationId` in `agy`). When the prompt or rewritten query names a configured `[prompt_hook.projects]` code mapped in `[scopes]`, those scope matchers union additively with the current repo and apply automatic `scope:<path>` bias (`+0.3` via `BIAS_BOOST`) on both the Haiku and local paths so cross-repo project notes surface without dropping local matches (opt out of automatic scope bias with `[query] default_bias = ["relevance"]`). On scopes with at least 20 active items, the Haiku path drops low-information hits whose matched-term IDF sum falls below `[prompt_hook] min_idf` (default `3.0`; `0.0` disables via `run_query`; exact ref hits bypass; dropped IDs log under `floor_dropped`). The local fallback applies `[prompt_hook] local_min_idf` (default `8.0`; `0.0` disables) as its local IDF floor. Disable per invocation with `SM_PROMPT_HOOK=0`.
145
162
 
146
163
  ### MCP server (`sm mcp`)
147
164
 
148
- Speaks JSON-RPC 2.0 over stdio (`MCP 2026-07-28` stateless metadata and `2024-11-05` through `2025-11-25` `initialize` handshakes) and serves five tools:
165
+ Speaks JSON-RPC 2.0 over stdio (`MCP 2026-07-28` stateless metadata and `2024-11-05` through `2025-11-25` `initialize` handshakes) and serves eight tools:
149
166
 
150
167
  | Tool | Arguments | Purpose |
151
168
  |---|---|---|
152
- | `memory_query` | `query`; optional `bias`, `kind`, `tag`, `in`, `limit`, `all_repos`, `repo` | Ranked search (`sm query --format json`); `bias` accepts `scope:<path>` |
169
+ | `memory_query` | `query`; optional `bias`, `kind`, `tag`, `source`, `since`, `until`, `recent`, `include_history`, `in`, `limit`, `all_repos`, `repo` | Ranked search (`sm query --format json`); `bias` accepts `scope:<path>` |
170
+ | `memory_list` | optional `limit`, `offset`, `kind`, `tag`, `source`, `since`, `until`, `status`, `include_history`, `all_repos`, `repo`, `in` | Browse items newest-first without a query |
153
171
  | `memory_show` | `ids` (non-empty array) | Full body, refs, and provenance per ID |
154
172
  | `memory_related` | `id`; optional `limit` | Supersede chain, shared refs, same session |
155
173
  | `memory_put` | `text`, `tag`; optional `kind`, `evidence`, `refs`, `supersedes`, `repo` | Store item, redact secrets, warn on overlaps |
174
+ | `memory_amend` | `id`; optional `text`, `title`, `kind`, `tag`, `evidence`, `repo`, `add_refs`, `remove_refs`, `refs`, `add_tags`, `remove_tags`, `tags`, `as_of` | Append-only update (creates a new item and supersedes `id`) |
175
+ | `memory_retire` | `id`; optional `reason` | Soft-retire an active item with no replacement |
156
176
  | `memory_supersede` | `old_id`, `new_id` | Retire `old_id` in favor of `new_id` |
157
177
 
158
178
  ## Ontology and retrieval gate
@@ -167,7 +187,7 @@ Both prompt-hook recall (`sm hook prompt`) and explicit lookup (`sm query` / `sm
167
187
  ![Ontology and retrieval gate](assets/ontology.svg)
168
188
 
169
189
  - **Hard scope filter (`--in`)**: `sm query "auth timeout" --in acme/globex` searches across all repos and keeps only items matching `acme/globex` or its descendants.
170
- - **Soft scope bias (`--bias scope:<path>`)**: `sm query "auth timeout" --bias scope:acme/globex` (or MCP `memory_query` `bias`, or `[query] default_bias`) keeps the normal repo result set, widens the FTS candidate pool to `100`, and adds `+0.3` (`BIAS_BOOST`) per matched scope without overriding exact `ref_hits`, `phrase`, or `accent` matches (reported as `why=...,bias:scope:acme/globex`). Stack parent and child paths (`--bias scope:acme,scope:acme/globex`) for hierarchical specificity.
190
+ - **Soft scope bias (`--bias scope:<path>`)**: `sm query "auth timeout" --bias scope:acme/globex` (or MCP `memory_query` `bias`, or `[query] default_bias`) keeps the normal repo result set, widens the FTS candidate pool to `100`, and adds `+0.3` (`BIAS_BOOST`) per matched scope without overriding exact `ref_hits`, `phrase`, or `accent` matches (reported as `why=...,bias:scope:acme/globex`). When `--bias` contains only `scope:<path>` tokens, they merge additively on top of `[query] default_bias` so durable kind, tag, and recency boosts stay active; pass `relevance` or another explicit kind/tag token (such as `--bias relevance,scope:acme/globex`) to replace the defaults. Stack parent and child paths (`--bias scope:acme,scope:acme/globex`) for hierarchical specificity.
171
191
  - **Automatic hook scope bias**: When `sm hook prompt` matches a `[prompt_hook.projects]` code to `[scopes]`, matched paths union additively into SQL and apply automatic `scope:<path>` bias on both the Haiku and local paths. Set `[query] default_bias = ["relevance"]` to opt out of automatic scope bias (along with recency and kind/tag bias) while keeping additive SQL scope inclusion.
172
192
 
173
193
  ## Multi-repo scopes and maintenance
@@ -181,7 +201,7 @@ Group related repos or project codes locally in `~/.simple-memory/config.toml` u
181
201
  "acme/globex/portal" = ["repo:globex-portal"]
182
202
  ```
183
203
 
184
- Filter hard across scopes with `sm query "auth timeout" --in acme/globex`, soft-boost a scope without filtering via `sm query "auth timeout" --bias scope:acme/globex`, and inspect store counts, recall open rates, catch-up runs, and scope totals with `sm stats` (`--days N`, `--format json`).
204
+ Filter hard across scopes with `sm query "auth timeout" --in acme/globex`, soft-boost a scope without filtering via `sm query "auth timeout" --bias scope:acme/globex`, and inspect active, superseded, and retired store counts, recall open rates, catch-up runs, and scope totals with `sm stats` (`--days N`, `--format json`).
185
205
 
186
206
  Check store health anytime:
187
207
 
@@ -193,10 +213,10 @@ sm backup # verified SQLite backup copy in ~/.simple-memory/backup
193
213
 
194
214
  ## Extending simple-memory
195
215
 
196
- Modules follow a downward architecture (`cli` -> `service` -> `store` / `sources` / `config` -> `core`, plus shared `py`, `clock`, `error`), with two explicit helper edges (`rust/src/config.rs` -> `service::capture` and `rust/src/config.rs` -> `sources`; `stands_as_word` lives in `rust/src/core/terms.rs`):
216
+ Modules follow a downward architecture (`cli` -> `service` -> `store` / `sources` / `config` -> `core`, plus shared `py`, `clock`, `error`), with three explicit helper edges (`rust/src/config.rs` -> `service::capture`, `rust/src/config.rs` -> `service::query::LOCAL_TAU`, and `rust/src/config.rs` -> `sources`; `stands_as_word` lives in `rust/src/core/terms.rs`):
197
217
 
198
218
  - **Custom stopwords and ranking defaults**: Set `[prompt_hook] extra_stopwords` for domain/language filler skipped by the local fallback, and `[query] default_bias` to override default ranking without recompiling.
199
- - **New import source**: Add a parser under `rust/src/sources/` returning `core::item::Item` records, register its subcommand in `rust/src/cli/args.rs` and `rust/src/service/import_.rs`, and wire it into `service/catchup.rs` + `service/doctor.rs` (`--imports`).
219
+ - **New import source**: Add a parser under `rust/src/sources/` returning `core::item::Item` records, register its subcommand in `rust/src/cli/args.rs` and `rust/src/service/import_.rs`, and wire it into `rust/src/service/catchup.rs` + `rust/src/service/doctor.rs` (`--imports`).
200
220
  - **New MCP tool or schema field**: Add tool schemas and handlers in `rust/src/service/mcp.rs` over shared `service/*` calls; place numbered `.sql` migrations under `rust/migrations/` and register them in `rust/src/store/connect.rs`.
201
221
  - **Additional redaction patterns**: Extend `rust/src/core/redact.rs` with linear-time regex patterns and unit tests.
202
222
 
@@ -208,8 +228,8 @@ Modules follow a downward architecture (`cli` -> `service` -> `store` / `sources
208
228
  | `sm init` | Create home dir, `memory.db`, and commented `config.toml` |
209
229
  | `sm config` | Print effective configuration (defaults plus `config.toml`) as TOML |
210
230
  | `sm put TEXT --tag TAG [...]` | Store item (`--kind`, `--evidence`, `--refs`, `--tags`, `--supersedes`, `--repo`, `--as-of`) |
211
- | `sm query TEXT [...]` | Ranked search (`--limit`, `--recent`, `--bias` including `scope:<path>`, `--kind`, `--tag`, `--source`, `--since`, `--until`, `--in`, `--all`, `--include-history`, `--format`) |
212
- | `sm show ID [ID ...]` | Print full text and provenance; exits 1 if any ID is missing |
231
+ | `sm query TEXT [...]` (alias `sm search`) | Ranked search with unquoted terms, `-term`/`-"phrase"` exclusions, relative `--since`/`--until` (`30m`, `24h`, `7d`, `2w`), additive `--bias scope:<path>`, `--limit`, `--recent`, `--kind`, `--tag`, `--source`, `--in` (mutually exclusive with `--repo`), `--all`, `--include-history`, `--format` |
232
+ | `sm show ID [ID ...] [--format text\|json]` | Print full text and provenance (`text` or `json` array); exits 1 if any ID is missing |
213
233
  | `sm related ID [...]` | Show supersede chain, shared-ref items, and same-session items |
214
234
  | `sm supersede OLD NEW` | Mark `OLD` superseded by `NEW` |
215
235
  | `sm retire ID [--reason TEXT]` | Soft-retire an active item with no replacement (default reason: `manual`) |
@@ -221,11 +241,12 @@ Modules follow a downward architecture (`cli` -> `service` -> `store` / `sources
221
241
  | `sm upkeep [--dry-run] [--report]` | Retire older/claimed session handoffs; `--report` flags near-duplicates and stale items |
222
242
  | `sm backup [--keep N]` | Checked SQLite backup in `backups/` |
223
243
  | `sm doctor [--rebuild-fts] [--backfill-refs] [--imports]` | Verify SQLite integrity, rebuild FTS5, backfill refs, or audit unimported files |
224
- | `sm stats [--days N] [--format text\|json]` | Store counts, recall open rate, catch-up runs, backups, and `[scopes]` rollup |
244
+ | `sm stats [--days N] [--format text\|json]` | Store counts (active, superseded, retired), recall open rate, catch-up runs, backups, and `[scopes]` rollup |
225
245
  | `sm hook prompt [--agy]` | Harness hook reading prompt JSON on stdin |
226
246
  | `sm hooks print claude-code\|agy\|mcp` | Print harness configuration JSON to stdout |
227
247
  | `sm mcp` | Run JSON-RPC 2.0 MCP server on stdio |
228
- | `sm --version` | Print installed binary version |
248
+ | `sm update [--check]` | Check npm for a newer release and upgrade npm installs (or print the source-upgrade command) |
249
+ | `sm --version`, `sm -v` | Print installed binary version |
229
250
 
230
251
  </details>
231
252
 
@@ -236,8 +257,8 @@ Modules follow a downward architecture (`cli` -> `service` -> `store` / `sources
236
257
 
237
258
  - `[repos] roots`: Parent directories whose direct children map workspace/transcript folders to repo keys (`[repo_aliases]` maps aliases such as worktrees).
238
259
  - `[keyword_aliases]`: Query term expansions (e.g. `"k8s" = "kubernetes"`).
239
- - `[query] default_bias`: Default is `["recency", "fact", "decision", "learning", "executed", "verified", "decided", "client-stated"]`. Accepts the same tokens as `--bias`, including `scope:<path>` (for example `"scope:acme/globex"`). Set `["relevance"]` to disable recency, kind/tag, and automatic prompt-hook scope bias.
240
- - `[prompt_hook]`: `enabled`, `model` (`"haiku"` or `"none"`), `timeout`, `limit`, `claude_bin`, `extra_stopwords`, `min_idf` (default `3.0`; `0.0` disables), and `[prompt_hook.projects]` project codes.
260
+ - `[query] default_bias`: Default is `["recency", "fact", "decision", "learning", "executed", "verified", "decided", "client-stated"]`. Accepts the same tokens as `--bias`, including `scope:<path>` (for example `"scope:acme/globex"`). Explicit `--bias` with only `scope:<path>` tokens merges on top of `default_bias`; set `["relevance"]` to disable recency, kind/tag, and automatic prompt-hook scope bias.
261
+ - `[prompt_hook]`: `enabled`, `model` (`"haiku"` or `"none"`), `timeout`, `limit`, `claude_bin`, `extra_stopwords`, `min_idf` (default `3.0`; `0.0` disables), `local_min_idf` (default `8.0`; `0.0` disables), and `[prompt_hook.projects]` project codes.
241
262
  - `[catch_up]`: `enabled`, `interval_minutes` (default `10`).
242
263
  - `[upkeep]`: `tasklog_roots` and `handoff_dirs`.
243
264
  - `[capture]`: `enabled`, `root` (`~/.claude/projects`), `idle_minutes`, `since_days`, `min_prompts`, `max_per_run`, `model`, `timeout`, `dialogue_chars`.
@@ -251,6 +272,7 @@ Environment variables:
251
272
  - `SM_PROMPT_HOOK=0`: Disable prompt-hook recall and background catch-up for one process tree (such as subagent runs).
252
273
  - `SM_BINARY_PATH`: Explicit path to a `sm` binary for the npm wrapper; exits with an error if the path does not exist instead of falling back.
253
274
  - `SM_SKIP_DOWNLOAD=1`: Skip the npm `postinstall` GitHub Release binary fallback download.
275
+ - `SM_NO_UPDATE_CHECK=1`: Disable the npm wrapper's 24-hour interactive update reminder.
254
276
 
255
277
  </details>
256
278
 
package/bin/sm.js CHANGED
@@ -3,10 +3,24 @@
3
3
 
4
4
  const { spawn } = require("node:child_process");
5
5
  const os = require("node:os");
6
+ const path = require("node:path");
6
7
  const { resolveBinary } = require("../lib/platform");
8
+ const { maybeNotifyAndRefresh } = require("../lib/update");
9
+ const { version: PACKAGE_VERSION } = require("../package.json");
7
10
 
8
11
  const FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
9
12
 
13
+ function spawnUpdateCheck(cachePath) {
14
+ const scriptPath = path.resolve(__dirname, "..", "scripts", "check-update.js");
15
+ const checker = spawn(process.execPath, [scriptPath, cachePath], {
16
+ detached: true,
17
+ stdio: "ignore",
18
+ env: process.env,
19
+ });
20
+ checker.on("error", () => {});
21
+ checker.unref();
22
+ }
23
+
10
24
  const resolved = resolveBinary();
11
25
  if (!resolved.ok) {
12
26
  process.stderr.write(
@@ -16,7 +30,11 @@ if (!resolved.ok) {
16
30
  process.exit(1);
17
31
  }
18
32
 
19
- const child = spawn(resolved.path, process.argv.slice(2), { stdio: "inherit" });
33
+ const argv = process.argv.slice(2);
34
+ const child = spawn(resolved.path, argv, {
35
+ stdio: "inherit",
36
+ env: { ...process.env, SM_INSTALL_METHOD: "npm" },
37
+ });
20
38
 
21
39
  const handlers = new Map();
22
40
  for (const sig of FORWARDED_SIGNALS) {
@@ -60,5 +78,13 @@ child.on("exit", (code, signal) => {
60
78
  const sigNum = os.constants.signals[signal] || 1;
61
79
  process.exit(128 + sigNum);
62
80
  }
81
+ maybeNotifyAndRefresh({
82
+ argv,
83
+ env: process.env,
84
+ currentVersion: PACKAGE_VERSION,
85
+ isStderrTTY: Boolean(process.stderr.isTTY),
86
+ stderr: process.stderr,
87
+ spawnRefresh: spawnUpdateCheck,
88
+ });
63
89
  process.exit(code === null ? 1 : code);
64
90
  });
package/lib/update.js ADDED
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const os = require("node:os");
5
+ const path = require("node:path");
6
+
7
+ // Semver = { major: number, minor: number, patch: number }
8
+ // UpdateCache = { checked_at: number, latest: string }
9
+ // NotifyResult = { notified: boolean, refreshed: boolean, latest: string | null }
10
+ const DEFAULT_TTL_MS = 86400_000;
11
+ const SKIP_SUBCOMMANDS = new Set(["mcp", "hook", "hooks", "update"]);
12
+ const SKIP_FLAGS = new Set(["--version", "-v", "-h", "--help"]);
13
+
14
+ function parseSemver(v) {
15
+ if (typeof v !== "string") {
16
+ return null;
17
+ }
18
+ const m = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(v);
19
+ if (!m) {
20
+ return null;
21
+ }
22
+ const major = Number(m[1]);
23
+ const minor = Number(m[2]);
24
+ const patch = Number(m[3]);
25
+ if (
26
+ !Number.isSafeInteger(major) ||
27
+ !Number.isSafeInteger(minor) ||
28
+ !Number.isSafeInteger(patch)
29
+ ) {
30
+ return null;
31
+ }
32
+ return { major, minor, patch };
33
+ }
34
+
35
+ function isNewerVersion(latest, current) {
36
+ const a = parseSemver(latest);
37
+ const b = parseSemver(current);
38
+ if (!a || !b) {
39
+ return false;
40
+ }
41
+ if (a.major !== b.major) {
42
+ return a.major > b.major;
43
+ }
44
+ if (a.minor !== b.minor) {
45
+ return a.minor > b.minor;
46
+ }
47
+ return a.patch > b.patch;
48
+ }
49
+
50
+ function shouldCheckUpdate(options = {}) {
51
+ const { argv = [], env = {}, isStderrTTY = false } = options;
52
+ if (isStderrTTY !== true) {
53
+ return false;
54
+ }
55
+ if (env && env.SM_NO_UPDATE_CHECK === "1") {
56
+ return false;
57
+ }
58
+ const ciRaw = env && typeof env.CI === "string" ? env.CI.trim().toLowerCase() : "";
59
+ if (ciRaw.length > 0 && ciRaw !== "0" && ciRaw !== "false") {
60
+ return false;
61
+ }
62
+ if (!Array.isArray(argv)) {
63
+ return false;
64
+ }
65
+ if (argv.length > 0 && SKIP_SUBCOMMANDS.has(argv[0])) {
66
+ return false;
67
+ }
68
+ for (let i = 0; i < argv.length; i += 1) {
69
+ const arg = argv[i];
70
+ if (arg === "--") {
71
+ break;
72
+ }
73
+ if (SKIP_FLAGS.has(arg)) {
74
+ return false;
75
+ }
76
+ if (arg === "--format=json") {
77
+ return false;
78
+ }
79
+ if (arg === "--format" && argv[i + 1] === "json") {
80
+ return false;
81
+ }
82
+ }
83
+ return true;
84
+ }
85
+
86
+ function expandTilde(p, homeDir) {
87
+ if (p === "~") {
88
+ return homeDir;
89
+ }
90
+ if (p.startsWith("~/") || p.startsWith("~\\")) {
91
+ return path.join(homeDir, p.slice(2));
92
+ }
93
+ return p;
94
+ }
95
+
96
+ function cachePathForEnv(env = process.env, homeDir = os.homedir()) {
97
+ const smHome =
98
+ env && typeof env.SIMPLE_MEMORY_HOME === "string" && env.SIMPLE_MEMORY_HOME.trim().length > 0
99
+ ? expandTilde(env.SIMPLE_MEMORY_HOME.trim(), homeDir)
100
+ : path.join(homeDir, ".simple-memory");
101
+ return path.join(smHome, "update-check.json");
102
+ }
103
+
104
+ function readUpdateCache(cachePath) {
105
+ if (typeof cachePath !== "string" || cachePath.length === 0) {
106
+ return null;
107
+ }
108
+ let raw;
109
+ try {
110
+ raw = fs.readFileSync(cachePath, "utf8");
111
+ } catch {
112
+ return null;
113
+ }
114
+ let parsed;
115
+ try {
116
+ parsed = JSON.parse(raw);
117
+ } catch {
118
+ return null;
119
+ }
120
+ if (
121
+ !parsed ||
122
+ typeof parsed !== "object" ||
123
+ typeof parsed.checked_at !== "number" ||
124
+ !Number.isFinite(parsed.checked_at) ||
125
+ parsed.checked_at < 0 ||
126
+ parseSemver(parsed.latest) === null
127
+ ) {
128
+ return null;
129
+ }
130
+ return { checked_at: parsed.checked_at, latest: parsed.latest };
131
+ }
132
+
133
+ function isCacheStale(cache, nowMs = Date.now(), ttlMs = DEFAULT_TTL_MS) {
134
+ if (!cache || typeof cache.checked_at !== "number" || !Number.isFinite(cache.checked_at)) {
135
+ return true;
136
+ }
137
+ return nowMs - cache.checked_at >= ttlMs;
138
+ }
139
+
140
+ function formatUpdateNotice(current, latest) {
141
+ return (
142
+ `Update available: ${current} -> ${latest}. ` +
143
+ "Run: sm update (or npm install -g simple-memory@latest; disable: SM_NO_UPDATE_CHECK=1)\n"
144
+ );
145
+ }
146
+
147
+ function maybeNotifyAndRefresh(options = {}) {
148
+ const {
149
+ argv = [],
150
+ env = process.env,
151
+ currentVersion = "",
152
+ isStderrTTY = false,
153
+ stderr = process.stderr,
154
+ spawnRefresh = null,
155
+ homeDir = os.homedir(),
156
+ nowMs = Date.now(),
157
+ ttlMs = DEFAULT_TTL_MS,
158
+ } = options;
159
+
160
+ if (!shouldCheckUpdate({ argv, env, isStderrTTY })) {
161
+ return { notified: false, refreshed: false, latest: null };
162
+ }
163
+
164
+ const cachePath = cachePathForEnv(env, homeDir);
165
+ const cache = readUpdateCache(cachePath);
166
+ let notified = false;
167
+ let refreshed = false;
168
+
169
+ if (cache && isNewerVersion(cache.latest, currentVersion)) {
170
+ try {
171
+ stderr.write(formatUpdateNotice(currentVersion, cache.latest));
172
+ notified = true;
173
+ } catch {
174
+ // Best-effort stderr notice must never alter command exit status.
175
+ }
176
+ }
177
+
178
+ if (isCacheStale(cache, nowMs, ttlMs) && typeof spawnRefresh === "function") {
179
+ try {
180
+ spawnRefresh(cachePath);
181
+ refreshed = true;
182
+ } catch {
183
+ // Best-effort background refresh must never alter command exit status.
184
+ }
185
+ }
186
+
187
+ return { notified, refreshed, latest: cache ? cache.latest : null };
188
+ }
189
+
190
+ module.exports = {
191
+ DEFAULT_TTL_MS,
192
+ parseSemver,
193
+ isNewerVersion,
194
+ shouldCheckUpdate,
195
+ cachePathForEnv,
196
+ readUpdateCache,
197
+ isCacheStale,
198
+ formatUpdateNotice,
199
+ maybeNotifyAndRefresh,
200
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "simple-memory",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Local single-file SQLite + FTS5 memory store and MCP server for coding agents",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -37,7 +37,7 @@
37
37
  "postinstall": "node scripts/postinstall.js"
38
38
  },
39
39
  "optionalDependencies": {
40
- "simple-memory-darwin-arm64": "0.5.0",
41
- "simple-memory-darwin-x64": "0.5.0"
40
+ "simple-memory-darwin-arm64": "0.6.0",
41
+ "simple-memory-darwin-x64": "0.6.0"
42
42
  }
43
43
  }
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const fs = require("node:fs");
5
+ const os = require("node:os");
6
+ const path = require("node:path");
7
+ const { cachePathForEnv, parseSemver } = require("../lib/update");
8
+
9
+ const DEFAULT_UPDATE_URL = "https://registry.npmjs.org/simple-memory/latest";
10
+ const DEFAULT_TIMEOUT_MS = 3000;
11
+ const MAX_RESPONSE_BYTES = 256 * 1024;
12
+
13
+ async function readTextWithLimit(body, maxBytes) {
14
+ if (!body) {
15
+ return "";
16
+ }
17
+ const chunks = [];
18
+ let total = 0;
19
+ for await (const chunk of body) {
20
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
21
+ total += buf.length;
22
+ if (total > maxBytes) {
23
+ if (typeof body.cancel === "function") {
24
+ await body.cancel().catch(() => {});
25
+ }
26
+ throw new Error("Response exceeded size limit");
27
+ }
28
+ chunks.push(buf);
29
+ }
30
+ return Buffer.concat(chunks, total).toString("utf8");
31
+ }
32
+
33
+ function writeCacheAtomic(cachePath, checkedAt, latest) {
34
+ const dir = path.dirname(cachePath);
35
+ fs.mkdirSync(dir, { recursive: true });
36
+ const nonce = `${process.pid}.${crypto.randomBytes(6).toString("hex")}`;
37
+ const tmpPath = path.join(dir, `.${path.basename(cachePath)}.tmp.${nonce}`);
38
+ const payload = JSON.stringify({ checked_at: checkedAt, latest }) + "\n";
39
+ try {
40
+ fs.writeFileSync(tmpPath, payload, { mode: 0o644 });
41
+ fs.renameSync(tmpPath, cachePath);
42
+ } finally {
43
+ try {
44
+ fs.unlinkSync(tmpPath);
45
+ } catch {
46
+ // Temp file was already renamed or never created.
47
+ }
48
+ }
49
+ }
50
+
51
+ async function fetchAndWriteUpdateCache(options = {}) {
52
+ const {
53
+ cachePath,
54
+ env = process.env,
55
+ url = (env && env.SM_UPDATE_CHECK_URL) || DEFAULT_UPDATE_URL,
56
+ timeoutMs = DEFAULT_TIMEOUT_MS,
57
+ fetchImpl = globalThis.fetch,
58
+ nowMs = null,
59
+ maxBytes = MAX_RESPONSE_BYTES,
60
+ } = options;
61
+
62
+ if (typeof cachePath !== "string" || cachePath.length === 0) {
63
+ return false;
64
+ }
65
+
66
+ try {
67
+ const res = await fetchImpl(url, {
68
+ headers: { accept: "application/json" },
69
+ signal: AbortSignal.timeout(timeoutMs),
70
+ });
71
+ if (!res || !res.ok) {
72
+ if (res && res.body && typeof res.body.cancel === "function") {
73
+ await res.body.cancel().catch(() => {});
74
+ }
75
+ return false;
76
+ }
77
+ const text = await readTextWithLimit(res.body, maxBytes);
78
+ const data = JSON.parse(text);
79
+ const version = data && typeof data.version === "string" ? data.version.trim() : "";
80
+ if (!parseSemver(version)) {
81
+ return false;
82
+ }
83
+ const checkedAt = typeof nowMs === "number" ? nowMs : Date.now();
84
+ writeCacheAtomic(cachePath, checkedAt, version);
85
+ return true;
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+
91
+ if (require.main === module) {
92
+ const cachePath = process.argv[2] || cachePathForEnv(process.env, os.homedir());
93
+ fetchAndWriteUpdateCache({ cachePath, env: process.env }).then(
94
+ () => process.exit(0),
95
+ () => process.exit(0)
96
+ );
97
+ }
98
+
99
+ module.exports = {
100
+ DEFAULT_UPDATE_URL,
101
+ DEFAULT_TIMEOUT_MS,
102
+ MAX_RESPONSE_BYTES,
103
+ fetchAndWriteUpdateCache,
104
+ };