owlmem 0.9.31 → 0.9.33

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.
Files changed (2) hide show
  1. package/owlmem.mjs +98 -14
  2. package/package.json +1 -1
package/owlmem.mjs CHANGED
@@ -44,7 +44,7 @@ import { fileURLToPath } from "node:url";
44
44
  import { spawn, spawnSync } from "node:child_process";
45
45
  import { createConnection } from "node:net";
46
46
 
47
- export const VERSION = "0.9.31";
47
+ export const VERSION = "0.9.33";
48
48
  const BASE = (process.env.OWLMEM_URL || "https://owlmem.com").replace(/\/$/, "");
49
49
  const DIR = process.env.OWLMEM_HOME || join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "owlmem");
50
50
  const enc = new TextEncoder(), dec = new TextDecoder();
@@ -517,12 +517,38 @@ async function mcpServe() {
517
517
  // ── hook: output for a Claude Code hook ──
518
518
  // `owlmem hook session-start` prints the SessionStart additionalContext: the first
519
519
  // step of every task is kb_find, before reading code. It runs at every session start,
520
- // so it must be fast and offline: no network, no sign-in, nothing on stderr, and it
521
- // ignores whatever Claude Code sends on stdin.
520
+ // so it must be fast and offline: no network, no sign-in, nothing on stderr. It reads
521
+ // only the session cwd from stdin (to name this project's handoff key) and ignores
522
+ // anything else Claude Code sends there.
522
523
  export const SESSION_START_CONTEXT = "Before reading any code or files, search OwlMem with kb_find: it is the first step of every task. In Claude Code, load it first with ToolSearch select:mcp__owlmem__kb_find. Then read code, run commands, and save reusable findings with kb_write.";
524
+ // The project this session runs in: the folder name of the git repository the cwd sits in
525
+ // (walk up to the first folder holding `.git`, a dir or a worktree's file), else the cwd's
526
+ // own folder name. No git binary, no network: just the filesystem.
527
+ function normalizeProjectName(name) {
528
+ return name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "project";
529
+ }
530
+ function projectName(cwd) {
531
+ const start = isAbsolute(cwd) ? cwd : join(process.cwd(), cwd);
532
+ let dir = start;
533
+ while (!existsSync(join(dir, ".git"))) {
534
+ const parent = dirname(dir);
535
+ if (parent === dir) return normalizeProjectName(basename(start));
536
+ dir = parent;
537
+ }
538
+ return normalizeProjectName(basename(dir));
539
+ }
540
+ // The hook's stdin JSON carries the session cwd; only read it when stdin isn't a TTY,
541
+ // and tolerate empty or bad input (fall back to the process cwd).
542
+ function hookStdinCwd() {
543
+ if (process.stdin.isTTY) return null;
544
+ try { const p = JSON.parse(readFileSync(0, "utf8")); return typeof p?.cwd === "string" && p.cwd ? p.cwd : null; }
545
+ catch { return null; }
546
+ }
523
547
  function hookCmd(sub) {
524
548
  if (sub !== "session-start") throw new Fail("Usage: owlmem hook session-start");
525
- console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: SESSION_START_CONTEXT } }));
549
+ const key = `<your name>-handoff-${projectName(hookStdinCwd() || process.cwd())}`;
550
+ const ctx = SESSION_START_CONTEXT + ` Handoff key for this project: \`${key}\` (kb_retain to save, kb_find to read; don't read another project's).`;
551
+ console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: ctx } }));
526
552
  }
527
553
 
528
554
  // ── install: connect the AI apps on this machine to OwlMem's MCP server ──
@@ -535,6 +561,7 @@ export const RULES = `## Team memory (OwlMem)
535
561
  creating a duplicate.
536
562
  - Store facts that change (prices, versions, status) with kb_retain and snapshot=true or an
537
563
  expiry, so they retire on their own.
564
+ - Save a handoff with kb_retain under \`<your name>-handoff-<project>\`, where <project> is the folder name of the git repo you work in (else the working folder).
538
565
  - Never put passwords or API keys in documents or memory. Use the OwlMem vault.`;
539
566
  const MARK_START = "<!-- owlmem:start -->", MARK_END = "<!-- owlmem:end -->";
540
567
  const DOCS = "https://owlmem.com/docs#";
@@ -1421,18 +1448,29 @@ export function foregroundMethods(client, cfg = {}) {
1421
1448
  return [];
1422
1449
  }
1423
1450
 
1451
+ // The project directory a job routes by (0.9.32, #4596): a task or a note names it in its own text
1452
+ // (full trust only — outside work never picks a terminal); a reply routes by the task it answers,
1453
+ // never by its own text. Null means "any terminal, as before".
1454
+ export function foregroundDir(task, h = home()) {
1455
+ if (task.trust !== TRUST_FULL) return null;
1456
+ if (isReply(task)) return task.task_cwd ? taskDir("cwd: " + task.task_cwd, h) : null;
1457
+ return taskDir(task.body, h);
1458
+ }
1459
+
1424
1460
  // Short wake note for a foreground session: what arrived, and to read it with kb_inbox (that marks it
1425
1461
  // read). Not the full payload — the session reads the rest itself.
1426
1462
  export function foregroundNote(task, o = {}) {
1427
1463
  const mins = o.timeout_min || WAKE_DEFAULTS.timeout_min;
1428
1464
  if (isReply(task)) {
1429
1465
  const done = task.result === "done";
1430
- if (task.zh) return `奥麦自动唤醒:回信 #${task.id}——你派的任务 #${task.task_id}「${task.task_title || ""}」有了结果:${shortName(task.by)}${done ? "完成" : "拒绝"}了。用 kb_inbox 看这封回信(会标成已读);需要接着做(换人派、把结果告诉站长、自己补做)就做,没有要做的就结束,不要发消息。`;
1431
- return `OwlMem auto-wake: reply #${task.id} — the task you gave out, #${task.task_id} "${task.task_title || ""}", was ${done ? "finished" : "declined"} by ${shortName(task.by)}. Read it with kb_inbox (that marks it read); if something needs doing next, do it, otherwise just end and don't send any message.`;
1466
+ // 0.9.32 (#4596): name the one item (kb_inbox id=N), so the session reads and marks only that one —
1467
+ // a plain kb_inbox would read and mark another project's mail.
1468
+ if (task.zh) return `奥麦自动唤醒:回信 #${task.id}——你派的任务 #${task.task_id}「${task.task_title || ""}」有了结果:${shortName(task.by)}${done ? "完成" : "拒绝"}了。用 kb_inbox id=${task.id} 看这封回信(会标成已读);需要接着做(换人派、把结果告诉站长、自己补做)就做,没有要做的就结束,不要发消息。`;
1469
+ return `OwlMem auto-wake: reply #${task.id} — the task you gave out, #${task.task_id} "${task.task_title || ""}", was ${done ? "finished" : "declined"} by ${shortName(task.by)}. Read it with kb_inbox id=${task.id} (that marks it read); if something needs doing next, do it, otherwise just end and don't send any message.`;
1432
1470
  }
1433
1471
  if (isNote(task)) {
1434
- if (task.zh) return `奥麦自动唤醒:留言 #${task.id}——${shortName(task.from)}:${task.title}。用 kb_inbox 看这条留言(会标成已读);要你做事就做完、用 kb_send 回结果,不用做就结束,不要发消息。`;
1435
- return `OwlMem auto-wake: note #${task.id} from ${shortName(task.from)}: ${task.title}. Read it with kb_inbox (that marks it read); if it asks you to do something, do it and report back with kb_send, otherwise just end and don't send a message.`;
1472
+ if (task.zh) return `奥麦自动唤醒:留言 #${task.id}——${shortName(task.from)}:${task.title}。用 kb_inbox id=${task.id} 看这条留言(会标成已读);要你做事就做完、用 kb_send 回结果,不用做就结束,不要发消息。`;
1473
+ return `OwlMem auto-wake: note #${task.id} from ${shortName(task.from)}: ${task.title}. Read it with kb_inbox id=${task.id} (that marks it read); if it asks you to do something, do it and report back with kb_send, otherwise just end and don't send a message.`;
1436
1474
  }
1437
1475
  if (task.zh) return `奥麦自动唤醒:任务 #${task.id}「${task.title}」等你处理(${shortName(task.from)}派来)。用 kb_task_update 接(doing),做完标 done、做不了标 declined,结果写进 note。你有 ${mins} 分钟。`;
1438
1476
  return `OwlMem auto-wake: task #${task.id} "${task.title}" is waiting for you (from ${shortName(task.from)}). Take it with kb_task_update (doing), mark it done when finished or declined if you can't, with the result in the note. You have ${mins} minutes.`;
@@ -1473,7 +1511,12 @@ export function listClaudeSessions(o = {}) {
1473
1511
  if (!pid || !alivePid(pid, o)) continue;
1474
1512
  let mtime = 0;
1475
1513
  try { mtime = statSync(sock).mtimeMs; } catch {}
1476
- out.push({ pid, sock, name: typeof rec.name === "string" ? rec.name : "", updatedAt: Number(rec.updatedAt) || 0, mtime });
1514
+ // 0.9.32 (#4596): the session's working directory (realpath, "" when the record has none) and its
1515
+ // busy/idle status, so a woken job can be routed to the terminal working in its project.
1516
+ let cwd = "";
1517
+ if (typeof rec.cwd === "string" && rec.cwd) { try { cwd = realpathSync(rec.cwd); } catch {} }
1518
+ out.push({ pid, sock, name: typeof rec.name === "string" ? rec.name : "", updatedAt: Number(rec.updatedAt) || 0, mtime,
1519
+ cwd, status: typeof rec.status === "string" ? rec.status : "" });
1477
1520
  }
1478
1521
  out.sort((a, b) => (b.updatedAt - a.updatedAt) || (b.mtime - a.mtime) || (b.pid - a.pid));
1479
1522
  return out;
@@ -1531,12 +1574,47 @@ export async function sendClaudeSocket(sock, text, o = {}) {
1531
1574
  });
1532
1575
  }
1533
1576
 
1534
- // claude-socket: newest live session first, then the next if that socket won't take it.
1577
+ // A directory's git repository, by its common git dir (0.9.32, #4596): the same repository from any
1578
+ // subfolder and from any of its worktrees resolves to the same realpath. Null when the directory is
1579
+ // not in a git repository (or doesn't exist). `git rev-parse --git-common-dir` prints a path relative
1580
+ // to the directory it ran in (".git", "../.git") or absolute (a worktree), so resolve it against `dir`.
1581
+ function gitCommonDir(dir, git = gitRun) {
1582
+ let st = null; try { st = statSync(dir); } catch {}
1583
+ if (!st || !st.isDirectory()) return null;
1584
+ const r = git(["-C", dir, "rev-parse", "--git-common-dir"]);
1585
+ if (!r.ok || !r.out) return null;
1586
+ const common = r.out.split("\n")[0].trim();
1587
+ if (!common) return null;
1588
+ const abs = isAbsolute(common) ? common : join(dir, common);
1589
+ try { return realpathSync(abs); } catch { return null; }
1590
+ }
1591
+
1592
+ // Is a session's working directory inside the job's project? A git repository counts as one project
1593
+ // across its subfolders and all its worktrees (same git-common-dir); a plain folder means that folder
1594
+ // or below it, matched on a path-segment boundary, so a sibling that only starts the same ("elsewhere"
1595
+ // vs "else") is not inside.
1596
+ function inProject(sessionCwd, dir, git = gitRun) {
1597
+ const dirGit = gitCommonDir(dir, git);
1598
+ if (dirGit) return gitCommonDir(sessionCwd, git) === dirGit;
1599
+ return sessionCwd === dir || sessionCwd.startsWith(dir + "/");
1600
+ }
1601
+
1602
+ // claude-socket: idle sessions before busy ones, then most recently active; the next if a socket won't
1603
+ // take it. With o.dir, only sessions working in that project; no session there fails and sends nothing
1604
+ // anywhere, so a job never lands in another project's terminal (#4596).
1535
1605
  export async function deliverClaudeSocket(note, o = {}) {
1536
1606
  const sessions = listClaudeSessions(o);
1537
- if (!sessions.length) return { ok: false, detail: "no live Claude Code session on this computer" };
1607
+ let dir = null;
1608
+ if (o.dir) { try { dir = realpathSync(o.dir); } catch { dir = o.dir; } }
1609
+ let pool = sessions;
1610
+ if (dir) {
1611
+ pool = sessions.filter((s) => s.cwd && inProject(s.cwd, dir));
1612
+ if (!pool.length) return { ok: false, detail: "no Claude Code session in " + dir };
1613
+ }
1614
+ if (!pool.length) return { ok: false, detail: "no live Claude Code session on this computer" };
1615
+ pool.sort((a, b) => ((a.status === "idle" ? 0 : 1) - (b.status === "idle" ? 0 : 1)) || (b.updatedAt - a.updatedAt) || (b.mtime - a.mtime) || (b.pid - a.pid));
1538
1616
  const tried = [];
1539
- for (const s of sessions) {
1617
+ for (const s of pool) {
1540
1618
  const r = await sendClaudeSocket(s.sock, note, o);
1541
1619
  if (r.ok) return { ok: true, detail: "Claude Code session " + (s.name || s.pid) };
1542
1620
  tried.push((s.name || s.pid) + ": " + r.detail);
@@ -1569,11 +1647,15 @@ export async function runForegroundCommand(method, text, o = {}) {
1569
1647
  }
1570
1648
 
1571
1649
  // Try the configured foreground methods in order; the first success counts as delivered.
1650
+ // The job's project directory (foregroundDir, or o.projectDir when the caller already worked it out)
1651
+ // is passed to the socket method, so it only goes to a session in that project (#4596); without one,
1652
+ // any session, as before. o.dir here is the wake directory, not the project — never pass it through.
1572
1653
  export async function deliverForeground(task, cfg, o = {}) {
1573
1654
  const note = o.note ?? foregroundNote(task, { timeout_min: cfg.timeout_min });
1655
+ const dir = o.projectDir !== undefined ? o.projectDir : foregroundDir(task, o.home);
1574
1656
  const tried = [];
1575
1657
  for (const m of foregroundMethods(task.client, cfg)) {
1576
- const r = m.type === "claude-socket" ? await deliverClaudeSocket(note, o) : await runForegroundCommand(m, note, o);
1658
+ const r = m.type === "claude-socket" ? await deliverClaudeSocket(note, { ...o, dir }) : await runForegroundCommand(m, note, o);
1577
1659
  if (r.ok) return { ok: true, method: m.type, detail: r.detail || "" };
1578
1660
  tried.push(m.type + ": " + (r.detail || "failed"));
1579
1661
  }
@@ -1638,7 +1720,9 @@ export async function runTask(task, cfg, o = {}) {
1638
1720
  const methods = foregroundMethods(task.client, cfg);
1639
1721
  if (task.foreground_tried) log("Foreground delivery was already tried for " + jobLabel(task) + "; starting a headless session."); // #1870:前台送过一次没接,这次直接无头
1640
1722
  else if (methods.length) {
1641
- const d = await deliverForeground(task, cfg, o);
1723
+ // #4596: the job's project directory rides along, so it only goes to a session in that project;
1724
+ // no session there fails the foreground step and the job starts headless, as before (one log line).
1725
+ const d = await deliverForeground(task, cfg, { ...o, projectDir: foregroundDir(task, o.home || home()) });
1642
1726
  if (d.ok) return { outcome: "foreground", detail: "delivered to the foreground (" + d.method + (d.detail ? ": " + d.detail : "") + ")" };
1643
1727
  log("Foreground delivery failed for " + jobLabel(task) + " (" + d.detail + "); starting a headless session.");
1644
1728
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "owlmem",
3
- "version": "0.9.31",
3
+ "version": "0.9.33",
4
4
  "description": "OwlMem command line: connect your AI apps to OwlMem in one command (npx -y owlmem install), an end-to-end encrypted vault for your AI agents, and a local MCP server.",
5
5
  "type": "module",
6
6
  "bin": { "owlmem": "owlmem.mjs" },