@snoai/mem-claude 1.6.0 → 1.7.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
@@ -6,7 +6,7 @@ start of every session.
6
6
 
7
7
  ## What you get
8
8
 
9
- - **It remembers without being asked.** Every completed turn is captured in the background.
9
+ - **It remembers without being asked.** Each session is captured in the background once it has been quiet for 30 minutes or has ended.
10
10
  Relevant memories come back when a session starts and before each prompt.
11
11
  - **Say it, and it is stored.** `remember` saves a fact right now, `recall` looks one up, and
12
12
  `get` opens a full entry by id.
@@ -51,7 +51,7 @@ Daily use and troubleshooting: [usage guide](https://github.com/sno-ai/sno-stati
51
51
 
52
52
  **Local First** (what the memory service setup selects) needs no model and no API key: capture is
53
53
  verbatim and everything stays on your machine. **Agent Native** lets Claude Code itself do the
54
- memory work on your existing subscription, and **REM Enhanced** adds Sno's own memory models to REM, the overnight step where your agents dream: it strengthens their memory and settles what they learned. It runs at most once a day for each part of your memory: usually overnight, or earlier the same day once about 100 new memories have piled up. Sno's models also write down what matters from each conversation when the session ends. It needs a Sno key in `settings.json`. In that mode your memory text and lessons go to your own space in Sno's cloud, which works like your own cloud drive: a Sno program processes it for you alone, and you can delete or keep it as you like. Change the mode in
54
+ memory work on your existing subscription, and **REM Enhanced** adds Sno's own memory models to REM, the overnight step where your agents dream: it strengthens their memory and settles what they learned. It runs at most once a day for each part of your memory: usually overnight, or earlier the same day once about 100 new memories have piled up. Sno's models also write down what matters from each conversation once the session has been quiet for 30 minutes or has ended. It needs a Sno key in `settings.json`. In that mode your memory text and lessons go to your own space in Sno's cloud, which works like your own cloud drive: a Sno program processes it for you alone, and you can delete or keep it as you like. Change the mode in
55
55
  `~/.sno/settings.json`, and keep the existing encryption key.
56
56
 
57
57
  ## Under the hood
package/dist/hooks.js CHANGED
@@ -11,7 +11,7 @@ import { hookScope, workspaceRoot } from "./scope.js";
11
11
  import { reportSessionActivity } from "./session-activity.js";
12
12
  import { readSkillRuns } from "./skill-runs.js";
13
13
  import { startWorkerDetached } from "./worker.js";
14
- import { appendSpool, readLastSession, readSession, recordDegraded, recordInjection, recordInvocation, recordLookup, recordSkip, writeLastSession, updateSession, writeSession, } from "./session-state.js";
14
+ import { appendSpool, markSessionEnded, readLastSession, readSession, recordDegraded, recordInjection, recordInvocation, recordLookup, recordSkip, writeLastSession, updateSession, writeSession, } from "./session-state.js";
15
15
  const baseHookSchema = z.object({
16
16
  session_id: z.string().min(1),
17
17
  cwd: z.string().min(1),
@@ -66,6 +66,11 @@ export async function sessionStart(raw) {
66
66
  const previous = await readLastSession(project);
67
67
  // A fresh session ends the previous one as "new"; /clear is sent from SessionEnd.
68
68
  if (input.source === "startup" && previous && previous.sessionId !== input.session_id) {
69
+ // Its queued turns are captured now instead of after the quiet window.
70
+ if (readCaptureSettings().ambient) {
71
+ await markSessionEnded(previous.sessionId);
72
+ startWorkerDetached();
73
+ }
69
74
  try {
70
75
  const boundaryClient = await withinDeadline(connectMemory(), Math.max(1, recall.sessionStart.timeoutMs - (performance.now() - started)));
71
76
  if (!isDegradedConnection(boundaryClient)) {
@@ -354,6 +359,10 @@ export async function sessionEnd(raw) {
354
359
  return;
355
360
  }
356
361
  await sendSessionActivity(input, "SessionEnd");
362
+ if (readCaptureSettings().ambient) {
363
+ await markSessionEnded(input.session_id);
364
+ startWorkerDetached();
365
+ }
357
366
  const state = await readSession(input.session_id);
358
367
  try {
359
368
  const rows = await readSkillRuns(input);
package/dist/paths.d.ts CHANGED
@@ -2,6 +2,9 @@ export declare function profileRoot(): string;
2
2
  export declare function appStateRoot(): string;
3
3
  export declare function sessionPath(sessionId: string): string;
4
4
  export declare function spoolDirectory(): string;
5
+ /** One empty file per ended session, named by the session id's hash; the worker then captures that session at once. */
6
+ export declare function endedSessionsDirectory(): string;
7
+ export declare function endedSessionPath(sessionId: string): string;
5
8
  export declare function workerLockPath(): string;
6
9
  export declare function workerLogPath(): string;
7
10
  export declare function importDirectory(): string;
package/dist/paths.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { homedir } from "node:os";
2
3
  import { join, resolve } from "node:path";
3
4
  import { APP_NAME } from "./constants.js";
@@ -15,6 +16,13 @@ export function sessionPath(sessionId) {
15
16
  export function spoolDirectory() {
16
17
  return join(appStateRoot(), "spool");
17
18
  }
19
+ /** One empty file per ended session, named by the session id's hash; the worker then captures that session at once. */
20
+ export function endedSessionsDirectory() {
21
+ return join(appStateRoot(), "ended");
22
+ }
23
+ export function endedSessionPath(sessionId) {
24
+ return join(endedSessionsDirectory(), createHash("sha256").update(sessionId).digest("hex"));
25
+ }
18
26
  export function workerLockPath() {
19
27
  return join(appStateRoot(), "worker.lock");
20
28
  }
@@ -52,4 +52,6 @@ export interface SpoolRecord {
52
52
  state: "pending" | "failed";
53
53
  }
54
54
  export declare function appendSpool(record: Omit<SpoolRecord, "attempts" | "state">): Promise<string>;
55
+ /** Marks a session ended, so the worker captures its queued turns now instead of after the quiet window. */
56
+ export declare function markSessionEnded(sessionId: string): Promise<void>;
55
57
  export {};
@@ -1,11 +1,11 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { mkdir, readFile } from "node:fs/promises";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { setTimeout as sleep } from "node:timers/promises";
5
5
  import { activityCursorSchema } from "@snoai/memory/coding-skin";
6
6
  import { z } from "zod";
7
7
  import { acquirePidFileLock, writeJsonAtomic } from "./files.js";
8
- import { appStateRoot, sessionPath, spoolDirectory } from "./paths.js";
8
+ import { appStateRoot, endedSessionPath, endedSessionsDirectory, sessionPath, spoolDirectory } from "./paths.js";
9
9
  const lastSessionSchema = z.object({ sessionId: z.string().min(1), transcriptPath: z.string().min(1) });
10
10
  function lastSessionPath(project) {
11
11
  return join(appStateRoot(), "last-session", `${createHash("sha256").update(project).digest("hex")}.json`);
@@ -112,3 +112,8 @@ export async function appendSpool(record) {
112
112
  await writeJsonAtomic(path, { ...record, attempts: 0, state: "pending" });
113
113
  return path;
114
114
  }
115
+ /** Marks a session ended, so the worker captures its queued turns now instead of after the quiet window. */
116
+ export async function markSessionEnded(sessionId) {
117
+ await mkdir(endedSessionsDirectory(), { recursive: true, mode: 0o700 });
118
+ await writeFile(endedSessionPath(sessionId), "", { mode: 0o600 });
119
+ }
package/dist/worker.d.ts CHANGED
@@ -1,4 +1,28 @@
1
1
  import type { MemoryClient } from "@snoai/memory/client";
2
+ import { z } from "zod";
3
+ declare const spoolSchema: z.ZodObject<{
4
+ sessionId: z.ZodString;
5
+ turnId: z.ZodString;
6
+ project: z.ZodString;
7
+ childCwd: z.ZodString;
8
+ user: z.ZodString;
9
+ assistant: z.ZodOptional<z.ZodString>;
10
+ kind: z.ZodOptional<z.ZodEnum<{
11
+ import: "import";
12
+ turn: "turn";
13
+ }>>;
14
+ importReceipt: z.ZodOptional<z.ZodObject<{
15
+ path: z.ZodString;
16
+ file: z.ZodString;
17
+ }, z.core.$strip>>;
18
+ at: z.ZodNumber;
19
+ attempts: z.ZodNumber;
20
+ state: z.ZodEnum<{
21
+ failed: "failed";
22
+ pending: "pending";
23
+ }>;
24
+ retryAt: z.ZodOptional<z.ZodNumber>;
25
+ }, z.core.$strip>;
2
26
  export interface WorkerDependencies {
3
27
  connect(): Promise<MemoryClient>;
4
28
  runChild(prompt: string, cwd: string, timeoutMs?: number): Promise<{
@@ -37,5 +61,20 @@ export declare function runClaudeChild(prompt: string, cwd: string, timeoutMs?:
37
61
  category: "transport";
38
62
  message: string;
39
63
  }>;
40
- export declare function hasActionableSpool(): Promise<boolean>;
64
+ type SpoolEntry = {
65
+ path: string;
66
+ record: z.infer<typeof spoolSchema>;
67
+ };
68
+ /**
69
+ * The next capture: a session's turns once it has ended or been quiet for the window, always before import blocks, then
70
+ * its consecutive records that share the first one's scope and tries, up to the input budget. `nextDueAt` is when the
71
+ * earliest waiting session turns due.
72
+ */
73
+ export declare function nextCapture(entries: readonly SpoolEntry[], ended: ReadonlySet<string>, now: number): {
74
+ batch: SpoolEntry[];
75
+ nextDueAt: number | undefined;
76
+ };
77
+ /** True when a capture is due now or a queued session turns due later, so a worker started now has work or waits for it. */
78
+ export declare function hasActionableSpool(now?: number): Promise<boolean>;
41
79
  export declare function runWorker(dependencies?: WorkerDependencies): Promise<"drained" | "locked" | "failed">;
80
+ export {};
package/dist/worker.js CHANGED
@@ -4,14 +4,13 @@ import { closeSync, mkdirSync, openSync } from "node:fs";
4
4
  import { createServer } from "node:http";
5
5
  import { userInfo } from "node:os";
6
6
  import { readFile, readdir, rm } from "node:fs/promises";
7
- import { join } from "node:path";
8
- import { CODING_SKIN_CHILD_DEADLINE_MS, CODING_SKIN_CHILD_MAX_BUFFER_BYTES, CODING_SKIN_IMPORT_INTERVAL_MS, CODING_SKIN_MAX_ATTEMPTS, CODING_SKIN_MAX_PENDING_CAPTURES, CODING_SKIN_RETRY_DELAYS_MS, CODING_SKIN_WORKER_LIFETIME_MS, HOST_MODEL_CALLBACK_HOST, HOST_MODEL_CALLBACK_PATH, HOST_MODEL_DEADLINE_HEADER, } from "@snoai/memory/coding-skin";
7
+ import { basename, join } from "node:path";
8
+ import { CODING_SKIN_CAPTURE_MAX_INPUT_TOKENS, CODING_SKIN_CAPTURE_QUIET_MS, CODING_SKIN_CHILD_DEADLINE_MS, CODING_SKIN_CHILD_MAX_BUFFER_BYTES, CODING_SKIN_IMPORT_INTERVAL_MS, CODING_SKIN_MAX_ATTEMPTS, CODING_SKIN_MAX_PENDING_CAPTURES, CODING_SKIN_RETRY_DELAYS_MS, CODING_SKIN_WORKER_LIFETIME_MS, HOST_MODEL_CALLBACK_HOST, HOST_MODEL_CALLBACK_PATH, HOST_MODEL_DEADLINE_HEADER, } from "@snoai/memory/coding-skin";
9
9
  import { z } from "zod";
10
10
  import { MODEL_ID, SKIN_ID } from "./constants.js";
11
11
  import { acquirePidFileLock, writeJsonAtomic } from "./files.js";
12
12
  import { connectMemory, isDegradedConnection } from "./memory-client.js";
13
- import { withinDeadline } from "./recall.js";
14
- import { appStateRoot, profileRoot, spoolDirectory, workerLockPath, workerLogPath } from "./paths.js";
13
+ import { appStateRoot, endedSessionPath, endedSessionsDirectory, profileRoot, spoolDirectory, workerLockPath, workerLogPath } from "./paths.js";
15
14
  const spoolSchema = z.object({
16
15
  sessionId: z.string().min(1),
17
16
  turnId: z.string().min(1),
@@ -222,13 +221,67 @@ async function readSpoolNames() {
222
221
  remaining: names.length, reason: "capacity" }));
223
222
  return names;
224
223
  }
225
- export async function hasActionableSpool() {
226
- const names = await readSpoolNames();
227
- for (const name of names) {
228
- if (await readSpool(join(spoolDirectory(), name)))
229
- return true;
224
+ async function readSpoolEntries() {
225
+ const entries = [];
226
+ for (const name of await readSpoolNames()) {
227
+ const path = join(spoolDirectory(), name);
228
+ const record = await readSpool(path);
229
+ if (record)
230
+ entries.push({ path, record });
230
231
  }
231
- return false;
232
+ return entries;
233
+ }
234
+ /** The queued sessions that have ended; markers of sessions with nothing queued are removed. */
235
+ async function readEndedSessions(entries) {
236
+ const queued = new Map(entries.map(({ record }) => [basename(endedSessionPath(record.sessionId)), record.sessionId]));
237
+ const ended = new Set();
238
+ for (const name of await readdir(endedSessionsDirectory()).catch(() => [])) {
239
+ const sessionId = queued.get(name);
240
+ if (sessionId === undefined)
241
+ await rm(join(endedSessionsDirectory(), name), { force: true });
242
+ else
243
+ ended.add(sessionId);
244
+ }
245
+ return ended;
246
+ }
247
+ /**
248
+ * The next capture: a session's turns once it has ended or been quiet for the window, always before import blocks, then
249
+ * its consecutive records that share the first one's scope and tries, up to the input budget. `nextDueAt` is when the
250
+ * earliest waiting session turns due.
251
+ */
252
+ export function nextCapture(entries, ended, now) {
253
+ const newest = new Map();
254
+ for (const { record } of entries) {
255
+ if (record.kind !== "import")
256
+ newest.set(record.sessionId, Math.max(newest.get(record.sessionId) ?? record.at, record.at));
257
+ }
258
+ const dueAt = (sessionId) => ended.has(sessionId) ? now : (newest.get(sessionId) ?? now) + CODING_SKIN_CAPTURE_QUIET_MS;
259
+ const waiting = [...newest.keys()].map(dueAt).filter(at => at > now);
260
+ const nextDueAt = waiting.length > 0 ? Math.min(...waiting) : undefined;
261
+ const head = entries.find(({ record }) => record.kind !== "import" && dueAt(record.sessionId) <= now)
262
+ ?? entries.find(({ record }) => record.kind === "import");
263
+ if (!head)
264
+ return { batch: [], nextDueAt };
265
+ const batch = [];
266
+ let tokens = 0;
267
+ for (const entry of entries) {
268
+ const { record } = entry;
269
+ if (record.sessionId !== head.record.sessionId || record.project !== head.record.project || record.childCwd !== head.record.childCwd
270
+ || record.attempts !== head.record.attempts || record.retryAt !== head.record.retryAt || (record.kind === "import") !== (head.record.kind === "import"))
271
+ continue;
272
+ const size = Buffer.byteLength(record.user + (record.assistant ?? "")) / 3;
273
+ if (batch.length > 0 && tokens + size > CODING_SKIN_CAPTURE_MAX_INPUT_TOKENS)
274
+ break;
275
+ batch.push(entry);
276
+ tokens += size;
277
+ }
278
+ return { batch, nextDueAt };
279
+ }
280
+ /** True when a capture is due now or a queued session turns due later, so a worker started now has work or waits for it. */
281
+ export async function hasActionableSpool(now = Date.now()) {
282
+ const entries = await readSpoolEntries();
283
+ const { batch, nextDueAt } = nextCapture(entries, await readEndedSessions(entries), now);
284
+ return batch.length > 0 || nextDueAt !== undefined;
232
285
  }
233
286
  export async function runWorker(dependencies = productionDependencies()) {
234
287
  const lock = await acquirePidFileLock(workerLockPath(), CODING_SKIN_WORKER_LIFETIME_MS);
@@ -247,7 +300,7 @@ export async function runWorker(dependencies = productionDependencies()) {
247
300
  let handoff = false;
248
301
  try {
249
302
  mkdirSync(childCwd, { recursive: true, mode: 0o700 });
250
- const callback = await callbackServer(credential, () => currentCwd ?? childCwd, () => currentImport, () => { lastCallbackAt = now(); }, (prompt, cwd, requesterMs) => dependencies.runChild(prompt, cwd, Math.min(CODING_SKIN_CHILD_DEADLINE_MS, CODING_SKIN_WORKER_LIFETIME_MS - (now() - workerStartedAt), requesterMs ?? Infinity)));
303
+ const callback = await callbackServer(credential, () => currentCwd ?? childCwd, () => currentImport, () => { lastCallbackAt = now(); }, (prompt, cwd, requesterMs) => dependencies.runChild(prompt, cwd, Math.min(CODING_SKIN_CHILD_DEADLINE_MS, requesterMs ?? Infinity)));
251
304
  server = callback.server;
252
305
  await readSpoolNames();
253
306
  const client = await dependencies.connect();
@@ -257,25 +310,12 @@ export async function runWorker(dependencies = productionDependencies()) {
257
310
  });
258
311
  console.log(JSON.stringify({ event: "worker-registered" }));
259
312
  while (true) {
260
- const spoolNames = await readSpoolNames();
261
- console.log(JSON.stringify({ event: "spool-scan", count: spoolNames.length }));
313
+ const entries = await readSpoolEntries();
314
+ console.log(JSON.stringify({ event: "spool-scan", count: entries.length }));
315
+ const { batch, nextDueAt } = nextCapture(entries, await readEndedSessions(entries), now());
262
316
  let actionable = 0;
263
- for (const name of spoolNames.slice(0, 1)) {
264
- const path = join(spoolDirectory(), name);
265
- let record = await readSpool(path);
266
- if (!record)
267
- continue;
268
- const batch = [{ path, record }];
269
- if (record.kind !== "import")
270
- for (const pendingName of spoolNames.slice(1)) {
271
- const pendingPath = join(spoolDirectory(), pendingName);
272
- const pending = await readSpool(pendingPath);
273
- if (pending && pending.sessionId === record.sessionId && pending.project === record.project
274
- && pending.childCwd === record.childCwd && pending.attempts === record.attempts
275
- && pending.retryAt === record.retryAt && pending.kind !== "import")
276
- batch.push({ path: pendingPath, record: pending });
277
- }
278
- batch.sort((left, right) => left.record.at - right.record.at);
317
+ for (const head of batch.slice(0, 1)) {
318
+ let record = head.record;
279
319
  actionable += 1;
280
320
  drainedAt = undefined;
281
321
  while (record.attempts < CODING_SKIN_MAX_ATTEMPTS) {
@@ -304,12 +344,15 @@ export async function runWorker(dependencies = productionDependencies()) {
304
344
  { role: "user", content: turn.user, at: turn.at },
305
345
  { role: "assistant", content: turn.assistant ?? "", at: turn.at },
306
346
  ]);
307
- const result = await withinDeadline(client.capture({ turnId: record.turnId, rewindEpoch: 0, messages }, { principal, project: record.project, session: record.sessionId, host: { sessionId: record.sessionId, workspace: record.project } }), CODING_SKIN_WORKER_LIFETIME_MS - (now() - workerStartedAt));
347
+ // A capture in flight is never abandoned for the lifetime: the sidecar would go on extracting it while this
348
+ // worker's model callback is gone. Its route deadline bounds it, and the lifetime is checked before the next one.
349
+ const result = await client.capture({ turnId: record.turnId, rewindEpoch: 0, messages }, { principal, project: record.project, session: record.sessionId, host: { sessionId: record.sessionId, workspace: record.project } });
308
350
  if (result.degraded)
309
351
  throw new Error(result.reason);
310
352
  if (!result.committed && !result.accepted && !result.skipped && !result.partial)
311
353
  throw new Error("capture not committed");
312
- await updateImportReceipt(record.importReceipt, result.committed || result.accepted || result.partial ? "committed" : "skipped");
354
+ for (const entry of batch)
355
+ await updateImportReceipt(entry.record.importReceipt, result.committed || result.accepted || result.partial ? "committed" : "skipped");
313
356
  for (const entry of batch) {
314
357
  console.log(JSON.stringify({ event: result.partial ? "capture-partial" : result.committed ? "capture-committed" : result.accepted ? "capture-accepted" : "capture-skipped", turnId: entry.record.turnId, committed: result.committed }));
315
358
  await rm(entry.path, { force: true });
@@ -317,7 +360,8 @@ export async function runWorker(dependencies = productionDependencies()) {
317
360
  break;
318
361
  }
319
362
  catch (error) {
320
- await updateImportReceipt(record.importReceipt, "failures");
363
+ for (const entry of batch)
364
+ await updateImportReceipt(entry.record.importReceipt, "failures");
321
365
  const attempts = record.attempts + 1;
322
366
  for (const entry of batch)
323
367
  console.log(JSON.stringify({ event: "capture-failed", turnId: entry.record.turnId, attempt: attempts,
@@ -355,12 +399,14 @@ export async function runWorker(dependencies = productionDependencies()) {
355
399
  drainedAt ??= now();
356
400
  const remainingLifetime = CODING_SKIN_WORKER_LIFETIME_MS - (now() - workerStartedAt);
357
401
  const remainingIdle = 2 * 60_000 - (now() - Math.max(drainedAt, lastCallbackAt));
358
- if (remainingLifetime <= 0 || remainingIdle <= 0) {
402
+ // A waiting session is waited for however far off, so it is captured when its quiet window ends; the lifetime
403
+ // bounds busy work only, and a capture turning due past it is handed to a fresh worker.
404
+ if (nextDueAt === undefined && (remainingLifetime <= 0 || remainingIdle <= 0)) {
359
405
  handoff = true;
360
406
  return "drained";
361
407
  }
362
408
  // Short slices, so a turn spooled while idle is captured within seconds instead of after the window.
363
- await sleep(Math.min(remainingLifetime, remainingIdle, 5_000));
409
+ await sleep(Math.min(nextDueAt === undefined ? Math.min(remainingLifetime, remainingIdle) : nextDueAt - now(), 5_000));
364
410
  }
365
411
  }
366
412
  }
@@ -372,7 +418,7 @@ export async function runWorker(dependencies = productionDependencies()) {
372
418
  if (handoff)
373
419
  await dependencies.beforeLockRelease?.();
374
420
  await lock.release();
375
- if (handoff && await hasActionableSpool()) {
421
+ if (handoff && await hasActionableSpool(now())) {
376
422
  if (dependencies.handoff)
377
423
  await dependencies.handoff();
378
424
  else
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snoai/mem-claude",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "license": "Apache-2.0",
5
5
  "publishConfig": { "access": "public" },
6
6
  "repository": {
@@ -25,7 +25,7 @@
25
25
  "lint:fix": "biome check --write src/"
26
26
  },
27
27
  "dependencies": {
28
- "@snoai/memory": "^1.2.0",
28
+ "@snoai/memory": "^1.7.0",
29
29
  "fs-native-extensions": "^1.5.1",
30
30
  "zod": "^4.5.4"
31
31
  },