SLOPSHOPPER

lumberroom memory

lumberroom as Claude Code's memory: the digest in the system prompt, a periodic search-and-write reminder, optional per-prompt recall, built-in memory off.

guardcommandtoaststatuspromptmodel
★ 1v0.7.0Apache-2.0updated 2026-10-24lumberroom/lumberroom-claude-code
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · lumberroom-memory
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ lumberroom-memory │ ● lumberroom-memory: lumberroom: context_bootstrap gave timeout │ lumberroom unreachable: memory was not │ ● lumberroom-memory: lumberroom: context_bootstrap gave timeout │ checked. │ ⏺ Read(src/auth.ts) ╰────────────────────────────────────────────╯ ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /lr-import ⎿ lumberroom-memory: lr-import found no lumberroom credential. Run `lumberroom login` and pick the Full profile, which carries the ● lumberroom-memory: lumberroom: Claude Code's built-in guard (sec-default) holds this plugin's system-prompt hook, so the digest now rides on your prompts instead. For the full plugin, see the README section "Organization-managed Claude Code". ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ lumberroom-memory: lumberroom ~399 tokens in context: digest 399, reminders 0, tools 0 (0 calls)
README

lumberroom for Claude Code

lumberroom

lumberroom as Claude Code's memory, built as a Claude Code mod (a plugin of function hooks). The digest sits in the system prompt, a short reminder tells the model to search and to write, and Claude Code's own file memory is switched off. Recall with each prompt is available and off by default. It targets lumberroom.cloud or a self-hosted engine through an MCP server the plugin brings with it. The live sessions listed below ran against the hosted engine.

One memory for all your AI agents: Lumberroom in Claude Code

More videos: Lumberroom playlist

Built for Claude Code. The digest, the reminder, the status line and the memory guard are Claude Code hooks, so on claude.ai, the desktop app or Cowork only the bundled MCP server applies.

Status: The Claude Code mod API is early access (built and observed on 2.1.287) and may change between releases.

What it does

  • The digest in the system prompt. At session start the plugin calls context_bootstrap for the project and adds the digest and the write rule as one section of the system prompt. It does not edit CLAUDE.md or your settings. If you still run the old lumberroom bootstrap --hook shell hook, remove it from the SessionStart hooks in ~/.claude/settings.json, or the session gets the digest twice. When ~/.claude/CLAUDE.md or the project's CLAUDE.md already carries the write rule, the plugin leaves its own copy of the rule out of the section. The check reads ~/.claude/CLAUDE.md and <git root>/CLAUDE.md (the working directory when there is no git root) for a # Durable memory heading followed by memory_write.
  • The digest follows the first request. The conversation's first prompt of 12 characters or more goes to context_bootstrap as query, once, recall on or off. An engine with that argument answers with the facts related to the request and a profile ordered by relevance, and the section redraws. The system prompt then changes once, after that prompt. A timeout, an error or an engine without query keeps the session-start digest. digestQuery: false turns it off.
  • A reminder every reviewInterval prompts (8 by default). The plugin adds one line that tells the model to call memory_search before it answers from assumption and memory_write after the exchange settles something. It works with recall on or off. Slash commands do not count.
  • Recall with each prompt, off by default. Each recall block stays in context for every later turn and costs input tokens, and weak matches fill the context. Turn on recall and the plugin searches lumberroom with your prompt and attaches new hits for the model only. It skips prompts under 12 characters and drops hits whose similarity is below recallMinSimilarity. A hit goes out once, until /clear or a compaction empties the context that held it. The first prompt of a session can wait for the bootstrap plus the search (up to bootstrapTimeoutMs plus recallTimeoutMs); later prompts wait at most recallTimeoutMs. Three failures in a row pause recall for a minute.
  • One store. Claude Code's built-in memory section leaves the system prompt. The plugin refuses Read, Write, Edit, MultiEdit and NotebookEdit on ~/.claude/MEMORY.md and on anything under ~/.claude/projects/*/memory/, and Grep and Glob whose path is inside that folder. Bash is not guarded: cat or rm on a memory file goes through. /lr-import sends what those files already hold to the engine's proposal queue for you to review.
  • A token counter on the status line. The plugin draws an estimate, at four characters a token, of what lumberroom adds to the context: the digest section, the reminder and recall blocks, and the results of the model's own lumberroom tool calls. The line reads lumberroom ~2.4k tokens in context: digest 2.0k, reminders 30, tools 400 (2 calls). session.start and every prompt redraw it. Compaction and /clear zero the reminders and tools figures.
  • The rules as a skill, for Cowork. skills/lumberroom-memory carries the same read and write rules. In Claude Code the digest section already holds them; in Cowork, where only the MCP server and the skill load, the skill is what tells the model to bootstrap, search and write. The MCP server's own tool descriptions say what each tool does and give no orders.
  • /lr-review works the review queue. skills/lr-review settles dreaming proposals, conflicts and duplicates from the memories alone and asks you only about contradictions no date can order, in one list at the end.

The plugin writes nothing on its own unless you turn on the extractor. When on, the extractor calls memory_write directly. Otherwise the model writes when it calls memory_write.

Hooks

Every hook lives in hooks/register.ts. None answers a permission check, changes a permission mode, or rewrites a settings, agent, command or file-write event. The plugin runs no shell command, spawns no process or agent, and calls no shell tool. The one file it writes is your user settings.json, through /lr-setup, after you confirm.

HookWhat it does
session.startCalls context_bootstrap on the lumberroom server, caches the digest, registers /lr-import and /lr-setup and draws the status line
prompt.composeAdds the digest and the write rule to the system prompt as one section
prompt.section (memory)Removes Claude Code's built-in memory section when replaceBuiltinMemory is on
prompt.submitAdds the reminder every reviewInterval prompts; on the conversation's first eligible prompt, refetches the digest with that prompt as query; with recall on, calls memory_search and attaches the hits. Under an organization's guard, also attaches the digest once a conversation (Organization-managed Claude Code)
tool.callSee below
turn.complete, session.end, session.compactRun the extractor when it is on: a model call through Claude Code, then memory_search and memory_write. turn.complete also notes a finished turn that prompt.compose never saw
command.run (lr-import, lr-setup)Answers /lr-import and /lr-setup, the plugin's own commands; no other command reaches this hook

What tool.call does with the calls it sees. It reads the tool name and the path argument. With replaceBuiltinMemory on, it refuses Read, Write, Edit, MultiEdit, NotebookEdit, Grep and Glob when the path lands in ~/.claude/MEMORY.md or ~/.claude/projects/*/memory/, and answers with the reason. That refusal is the plugin's own rule, applied before your permission rules, and turning the option off removes it. For a call to a lumberroom tool it measures the length of the result for the token counter. It passes every other call on unchanged, and it never approves a call, never rewrites one and never sends what it sees anywhere.

What it calls and fetches

Tools the plugin calls itself, without the model asking. All three are lumberroom tools on the MCP server Claude Code connects ($.mcp.call), and Claude Code runs each one through your permission rules:

ToolWhen
context_bootstrapAt session start, retried for up to bootstrapTimeoutMs while the server connects; on later prompts until one answers, if session start got none; once more on the conversation's first prompt of 12 characters or more, with that prompt as query, within recallTimeoutMs, unless digestQuery is off
memory_searchWith each prompt from you when recall is on; with the extractor on, once before each extracted fact is written, to find the row it may replace
memory_writeWith the extractor on, once for each fact it extracted. Off by default

The tool names are fixed text in the code. The plugin calls no other tool. It also makes model calls through Claude Code ($.model.complete, on extractorModel) for the extractor, for the judge that decides whether a new fact replaces an old one, and for the namespace guess in /lr-import all.

Network requests. The plugin contacts two endpoints:

  • The MCP server, at https://mcp.lumberroom.cloud/mcp, or the lumberroom server you registered for a self-hosted engine. Claude Code makes these connections; the plugin only asks for the tool calls above.
  • The engine the lumberroom CLI points at, only when you run /lr-import or /lr-import confirm: LUMBERROOM_URL, else the url in the CLI's config file, else https://mcp.lumberroom.cloud. The plugin makes these requests itself with $.http.fetch, three kinds of POST carrying the credential described under Commands as a bearer: /admin/ingest/runs opens an ingest run, /admin/ingest/proposals sends the memory files as proposals in batches, and /admin/ingest/runs/<id>/close closes the run. It refuses an engine URL that is not https, except for localhost and 127.0.0.1.

The plugin fetches no code and no instructions: the engine's answers are the digest, search hits and ingest counts, and the plugin shows them to the model as data.

What it reads, what it sends, and where

Everything goes to the lumberroom engine, lumberroom.cloud by default or your own. Nothing goes to any other server.

From the conversation:

  • Your prompt text, clipped, with the project slug, in a memory_search call. Only when recall is on.
  • The conversation's first eligible prompt, up to 1,000 characters, with the project slug, in one context_bootstrap call, recall on or off. Once a conversation; digestQuery: false stops it.
  • The conversation's messages, when the extractor is on. A model call through Claude Code reads the turns since the last extraction and pulls out facts; that call runs on your Claude account, with no third party involved. The facts, not the transcript, go to the engine with memory_write, each preceded by a memory_search on the fact's text.
  • At session start, the project slug (the git root's folder name) in context_bootstrap. No conversation text goes with it until the first eligible prompt, above.

From your machine:

  • ~/.claude/CLAUDE.md and the project's CLAUDE.md, to see whether they already carry the write rule. Their text stays on your machine.
  • Claude Code's memory files under ~/.claude/projects/*/memory/, read and posted to the engine's proposal queue only when you run /lr-import or /lr-import confirm. /lr-import all lists the folders and posts nothing.
  • The lumberroom CLI's config file (LUMBERROOM_CONFIG, else ~/.config/lumberroom/config.json), read for its engine URL and bearer only when /lr-import or /lr-import confirm posts. The plugin never writes to it.
  • Your merged settings' permissions.allow and permissions.deny, read by /lr-setup to see which rules are missing. When you confirm, it adds the missing rules to permissions.allow in ~/.claude/settings.json (or $CLAUDE_CONFIG_DIR/settings.json) and keeps every other key.
  • For the memory guard, the path a file tool names and where its links resolve. The paths stay on your machine.

The model's own calls: when Claude calls memory_search, memory_write or another lumberroom tool, those calls go to the same engine under your permission rules.

The plugin keeps a digest cache, a duplicate guard for writes and the /lr-import plan in Claude Code's plugin storage. The only file it writes is your user settings.json, when you confirm /lr-setup. The hosted service's privacy policy is https://lumberroom.cloud/privacy; a self-hosted engine keeps everything on your own server.

Requirements

  • Built on Claude Code 2.1.287.
  • A lumberroom account on lumberroom.cloud, or a self-hosted engine.

Install

From the marketplace:

/plugin marketplace add lumberroom/lumberroom-claude-code
/plugin install lumberroom-memory@lumberroom

The plugin brings its own MCP server, connecting to https://mcp.lumberroom.cloud/mcp. It asks for no settings on install. Run /mcp once and sign in to plugin:lumberroom-memory:lumberroom. Its tools appear as mcp__plugin_lumberroom-memory_lumberroom__memory_search and so on, so a permission rule or agent definition that names mcp__lumberroom__* needs the new names.

Self-hosted engine

Register your engine as an MCP server named lumberroom, then restart Claude Code:

claude mcp add --scope user --transport http lumberroom https://lr.example.com/mcp

Add --header "Authorization: Bearer <token>" if your engine accepts only static bearer tokens. The plugin tries the bundled server first and falls back to lumberroom, so it needs no option. The bundled server still points at lumberroom.cloud and shows as needing sign-in; disable plugin:lumberroom-memory:lumberroom in /mcp to hide it. For /lr-import, point the lumberroom CLI at the same engine (LUMBERROOM_URL=https://lr.example.com lumberroom login).

If you already registered a server at the same URL, or your claude.ai account has a connector for it, Claude Code keeps one copy and hides the others. The plugin asks which copy is live and talks to it. Remove a registered one (claude mcp remove lumberroom) to run on the bundled server alone.

The manifest is .claude-plugin/marketplace.json (marketplace lumberroom, plugin lumberroom-memory, source ./). npm run validate checks it and plugin.json.

From a local checkout, in a terminal:

claude --plugin-dir /path/to/lumberroom-claude-code

or, for development, link the folder into a session's mods folder (~/.claude/dev-mods/<session>/lumberroom-memory) and accept hot reloading when Claude Code asks.

Claude Code runs the plugin's own calls to context_bootstrap, memory_search and memory_write through your permission rules, so allow those three tools once: run /lr-setup, confirm, and the digest loads in the same session. docs/permissions.md has the rules if you would rather add them by hand. Until you do, the session starts without the digest and the plugin shows a toast that points at /lr-setup.

Organization-managed Claude Code

On a machine with managed settings, or under a Team or Enterprise /login, Claude Code seats a built-in guard, sec-default@builtin (cc-plugin-sec-default in /plugin and the debug log). Your users can't turn it off. A plugin installed from a GitHub marketplace runs in the user tier, and the guard sends some events past that tier, so three of this plugin's hooks never run:

Hook the guard skipsWhat you lose
prompt.composeThe digest section in the system prompt
prompt.section (memory)Removing Claude Code's built-in memory section. The tool.call guard on the memory files still works
session.compactThe extraction before compaction and the keep-facts line in the compaction instructions

session.start, prompt.submit, tool.call, turn.complete, session.end and the commands still run.

Best route: have your admin seat the plugin as the organization's. The guard leaves alone a plugin your organization seats in its own tier, so every hook runs. Claude Code counts a plugin as the organization's only when it loads in place from a local directory marketplace. A copy from GitHub, git, a URL or npm counts as a user's, even when managed enabledPlugins turns it on. Your admin:

  1. Copies this repository, lumberroom-claude-code, to the same path on every machine, in a directory only an administrator can write, for example /opt/acme/claude-plugins/plugins/lumberroom-memory.
  2. Writes /opt/acme/claude-plugins/.claude-plugin/marketplace.json, named lumberroom, that lists the plugin by a relative path:
   {
     "name": "lumberroom",
     "owner": { "name": "Acme" },
     "plugins": [{ "name": "lumberroom-memory", "source": "./plugins/lumberroom-memory" }]
   }
  1. Adds this to managed settings:
   {
     "extraKnownMarketplaces": {
       "lumberroom": { "source": { "source": "directory", "path": "/opt/acme/claude-plugins" } }
     },
     "enabledPlugins": { "lumberroom-memory@lumberroom": true },
     "appendPlugins": ["lumberroom-memory@lumberroom"]
   }

The managed marketplace named lumberroom replaces a user's own lumberroom marketplace entry, the GitHub one /plugin marketplace add registers, so each machine loads one copy. The repository root holds both the plugin and its own .claude-plugin/marketplace.json; nobody has yet tested that copy nested under another marketplace.

appendPlugins runs the plugin behind your users' mods, inside the guard. If you list it in prependPlugins instead, name sec-default@builtin in that list too, because the list replaces the whole prepend tier. To check, run claude --debug: the line hooks module lumberroom-memory@lumberroom loaded should say tier append. The admin steps come from Manage mods for your organization.

If managed settings turn on the guard's allowManagedModsOnly option, the guard refuses a user-tier copy outright: nothing runs, and the debug log names allowManagedModsOnly. The admin route is then the only one.

Without an admin: the plugin falls back to prompt context. When a turn finishes and the plugin's prompt.compose hook never ran, the plugin decides the guard holds it. It logs one line in the transcript and stores that in its plugin storage. From then on it attaches the digest and the write rule to your prompt once a conversation, as prompt context:

  • The first session on a machine gets the digest from its second prompt. An interactive session composes the system prompt after the first prompt goes out, so that prompt can't tell yet. Later sessions on the same machine attach it to the first prompt.
  • The copy waits for the query. On the first eligible prompt the plugin waits up to recallTimeoutMs for the digest fetched with that prompt as query, so the one copy carries the facts related to the request.
  • The copy stays in the transcript. It costs its tokens on every later turn, as the section does, but a refetched digest does not replace it. The status line counts it under digest.
  • /clear and compaction send it again. The guard hides compaction from the plugin too, so the plugin counts the conversation's messages at each prompt and at the end of each turn, and reads a drop as a compaction. The next prompt then carries a fresh copy and recall's duplicate check resets. A compaction in the middle of a turn that leaves more messages than the last count goes unnoticed.
  • The guard going away undoes it. As soon as prompt.compose runs again, the plugin clears the stored flag and the system prompt carries the digest. The digest can show up twice on that one turn.
  • A plugin loaded in the middle of a session can trip it once. Claude Code may have built the system prompt before the plugin loaded, so prompt.compose doesn't fire and the plugin takes the turn for the guard. The next session clears the flag on its first prompt.compose.

What the fallback can't bring back: Claude Code's built-in memory section stays in the system prompt, and nothing runs at compaction. Set extractor to turn or session-end, both of which still run under the guard, if you want automatic extraction.

Options

Set them in /config, or under pluginConfigs["lumberroom-memory"].options in ~/.claude/settings.json.

OptionDefaultRangeMeaning
projectautoauto uses the git root's folder name; none sends none; else the slug
recalloffsearch with each prompt; costs input tokens on every later turn
digestQueryonsend the conversation's first prompt of 12 characters or more to context_bootstrap as query, so the digest adds the facts related to it; the system prompt changes once, after that prompt
recallExtraProjectsemptyother project slugs to search with each prompt, separated by commas or whitespace. A bare slug applies everywhere; project=slug1+slug2 applies only in that project, for example lumberroom-cloud=lumberroom for a fork that shares its engine's decisions. Claude Code reads plugin options from user, --settings or managed settings only, never project settings, so a per-project value goes inside the option
recallLimit61 to 20hits asked for
recallMaxChars4000500 to 16000cap on the whole recall block: tags, note, hits and write reminder
recallMinSimilarity0.60 to 1drop hits below this similarity; hits with no similarity pass
recallTimeoutMs2500500 to 8000wait for memory_search
bootstrapTimeoutMs50005000 to 8000wait for context_bootstrap
digestMaxChars80001000 to 30000cap on the digest section
reviewInterval80 to 100search and write reminder every N prompts, recall on or off; 0 is off
replaceBuiltinMemoryondrop built-in memory and guard its files
extractoroffoff, turn, session-endturn or session-end to write facts automatically
extractorModelhaikumodel for the extractor
ingestTokenunsetoptional bearer with mayIngest for /lr-import, ahead of the CLI's credential; kept in secure storage, so /config does not list it (see Commands)

Numeric options are rounded to whole numbers and clamped to the range; a non-numeric value falls back to the default. recallMinSimilarity is clamped but not rounded.

Commands

An option edited in ~/.claude/settings.json by hand takes effect after /reload-plugins; a change through /config reloads the plugin itself.

  • /lr-setup: allow the plugin's own context_bootstrap, memory_search and memory_write calls. It names the rules for the server lumberroom runs under, asks before it changes anything, adds the missing ones to permissions.allow in your user settings.json, then fetches the digest. It leaves a file it cannot parse alone, and stops at a deny rule, which an allow rule cannot override. /lr-setup show prints the rules and changes nothing.
  • /lr-import: send this project's memory files to the proposal queue. Each call waits 15 s, the closing call 5 s, and the result line reports posted, new, reinforced, confirmed, refused and blocked counts. user and feedback memories always go to user:me.
  • /lr-import all: lists every folder under ~/.claude/projects that has memory files and proposes a namespace for each, in a numbered table. It posts nothing. A folder whose name decodes to an existing path takes that path's git root slug; any other folder gets one model guess (extractorModel), and an unusable answer becomes global.
  • /lr-import confirm <n|folder> [namespace]: posts that one folder with the proposed namespace, or the one you give (my-repo, project:my-repo or global). /lr-import confirm all posts every pending folder with its proposal. /lr-import skip <n> drops one. /lr-import plan shows the table again. Only these project and reference memories use the namespace; the plan needs no token, confirm does.

/lr-import and /lr-import confirm take their credential from the first of these that is set:

  1. The ingestToken option.
  2. LUMBERROOM_TOKEN in Claude Code's environme
Source 20 files
hooks/register.ts 1117 lines
1// Wiring only: every decision lives in ../src and every session value lives in $.state. The
2// closure variables below reset on a hot reload, which is safe because session.start runs again
3// on a reload and recomputes them.
4
5import { atom, read, update } from 'claude-code'
6import type { EngineInterface, Register } from 'claude-code'
7
8import { allow, CLOSED, failure, success } from '../src/breaker'
9import { DEFAULTS, extrasFor, readConfig } from '../src/config'
10import type { Config } from '../src/config'
11import { afterContextReset, estimateTokens, formatStatus, isServerTool, NO_COST } from '../src/cost'
12import type { Cost } from '../src/cost'
13import { buildSection, digestFrom, hasDurableMemoryBlock, SECTION_ID } from '../src/digest'
14import { GUARD_NOTICE, GUARD_SEEN_KEY, guardHeld } from '../src/fallback'
15import { buildExtractPrompt, buildJudgePrompt, parseFacts, parseJudge, turnsFrom } from '../src/extractor'
16import type { Turn } from '../src/extractor'
17import { GUARD_REASON, GUARDED_TOOLS, isBuiltinMemoryPath, normalizePath, parentOf, pathArg } from '../src/guard'
18import { checkBaseUrl, parseMemoryFile, postProposals, PROJECT_DIR_KEPT, projectDirMatches, projectDirName, toProposalFacts } from '../src/importer'
19import type { ImportReport, MemoryFile } from '../src/importer'
20import {
21  buildNamespacePrompt, decodeProjectDir, formatPlan, IMPORT_USAGE, namespaceLabel, parseImportArgs, parseNamespaceAnswer, parseNamespaceOverride, parsePlan, PLAN_KEY,
22} from '../src/importplan'
23import type { PlanEntry } from '../src/importplan'
24import { callTool, isOutage } from '../src/mcp'
25import { OWN_PLUGIN } from '../src/own'
26import { raceSleep } from '../src/race'
27import type { CallOutcome, McpDeps } from '../src/mcp'
28import { BUNDLED_KEY, SERVER_CANDIDATES } from '../src/server'
29import { cliConfigPath, resolveIngest, type IngestCredential } from '../src/credential'
30import { findGitRoot, resolveProject, slugFromPath } from '../src/project'
31import type { Exists } from '../src/project'
32import { buildRecallBlock, buildReminderBlock, clipQuery, hitsFrom, isEligible, isPersonPrompt, nudgeDue, PERMISSION_TOAST, searchNamespaces, selectHits, toRecalled, UNREACHABLE_TOAST } from '../src/recall'
33import { ADD_LABEL, CANCEL_LABEL, manualText, mergeAllow, missingRules, permissionLists, setupRules, SETUP_USAGE } from '../src/setup'
34import { writeFact } from '../src/writes'
35import type { Conflict, Fact, WriteDeps } from '../src/writes'
36import type { LumberroomDigest } from '../types'
37
38type Dollar = EngineInterface
39
40const PLUGIN = OWN_PLUGIN
41
42/** Spec 9.4. Compaction drops detail the extractor and the model have not yet written down. */
43export const COMPACT_LINE =
44  'Keep every decision, preference and durable fact the conversation established, with its identifiers, and note which were written to lumberroom.'
45
46// `claude plugin validate` reads these keys as literals, so each ref is spelled out here.
47const digestRef = atom({ plugin: 'lumberroom-memory', key: 'digest' } as const, null)
48const seenRef = atom({ plugin: 'lumberroom-memory', key: 'seen' } as const, [])
49const promptsRef = atom({ plugin: 'lumberroom-memory', key: 'prompts' } as const, 0)
50const breakerRef = atom({ plugin: 'lumberroom-memory', key: 'breaker' } as const, CLOSED)
51const lastRecallRef = atom({ plugin: 'lumberroom-memory', key: 'lastRecall' } as const, null)
52const statsRef = atom(
53  { plugin: 'lumberroom-memory', key: 'stats' } as const,
54  { recalls: 0, hitsAttached: 0, lastMs: null, offline: false, writes: 0 },
55)
56const extractedRef = atom({ plugin: 'lumberroom-memory', key: 'extractedThrough' } as const, 0)
57const costRef = atom({ plugin: 'lumberroom-memory', key: 'cost' } as const, NO_COST)
58const promptDigestRef = atom({ plugin: 'lumberroom-memory', key: 'promptDigest' } as const, false)
59const composedRef = atom({ plugin: 'lumberroom-memory', key: 'composed' } as const, false)
60const guardedRef = atom({ plugin: 'lumberroom-memory', key: 'guarded' } as const, false)
61const contextDigestRef = atom({ plugin: 'lumberroom-memory', key: 'contextDigest' } as const, { shown: false, messages: 0 })
62
63/** A session end gets about 1.5 s for the whole chain; a model call needs more than this. */
64const SESSION_END_MIN_MS = 1000
65const EXTRACT_MODEL_TIMEOUT_MS = 30_000
66const JUDGE_MODEL_TIMEOUT_MS = 8_000
67const WRITE_TIMEOUT_MS = 5_000
68/** Compaction waits this long, in all, for the extractor before it goes on without it. */
69const COMPACT_EXTRACT_BOUND_MS = 20_000
70/** A stored row at or above this similarity is a candidate old version of a new fact. Lower scores cost a judge call and mostly name unrelated rows. */
71const SIMILAR_MIN = 0.75
72
73const mcpDeps = ($: Dollar): McpDeps => ({
74  call: (server, tool, args) => $.mcp.call(server, tool, args),
75  sleep: (ms) => $.clock.sleep(ms),
76  now: () => $.clock.now(),
77})
78
79const messageOf = (err: unknown): string => (err instanceof Error ? err.message : String(err))
80
81let cfg: Config = DEFAULTS
82
83// Reset on every load: register() sets cfg, and session.start recomputes the rest.
84let hasRule = false
85/**
86 * True while the last engine call said the server is not connected: the digest section and the
87 * extractor stay off, and the next prompt tries again. Any other answer clears it.
88 */
89let serverAbsent = false
90/** Prompts in a row that found no connected server. The third toasts and stops the calls. */
91let notConnectedPrompts = 0
92/** Set by the third such prompt; only the next session.start clears it. */
93let recallStopped = false
94let toldNotConnected = false
95/** The permissions toast goes out once a session. */
96let toldDenied = false
97/** The candidate that last answered context_bootstrap; the other calls go to it. */
98let activeServer: string | undefined
99const serverName = (): string => activeServer ?? SERVER_CANDIDATES[0]
100/** Every name the plugin may call lumberroom under, for the token count. */
101const knownServers = (): string[] => [...new Set([...SERVER_CANDIDATES, ...triedServers])]
102/** Names serversToTry returned, counted before the first call answers. */
103let triedServers: readonly string[] = []
104
105/**
106 * The names to try, in order. In auto, $.mcp.connect on the bundled key answers with the name the
107 * session runs the server under (the bundled one, a registered duplicate, or a claude.ai connector
108 * with the same URL), and that name goes first.
109 */
110const serversToTry = async ($: Dollar): Promise<readonly string[]> => {
111  const base = SERVER_CANDIDATES
112  try {
113    const raced = await raceSleep($.mcp.connect(BUNDLED_KEY), (ms) => $.clock.sleep(ms), cfg.bootstrapTimeoutMs)
114    const answer = raced.timedOut ? undefined : raced.value
115    if (answer?.isConnected === true) {
116      const live = answer.server
117      return [live, ...base.filter((n) => n !== live)]
118    }
119  } catch (err) {
120    debug($, `$.mcp.connect failed: ${messageOf(err)}`)
121  }
122  return base
123}
124
125/** Gap between bootstrap attempts at session start, while MCP servers are still connecting. */
126const BOOTSTRAP_RETRY_MS = 500
127let isExtracting = false
128let projectMemo: { cwd: string; slug: string | undefined } | undefined
129const logged = new Set<string>()
130
131/** The first failure of a hook shows in the transcript; the rest go to the debug log. */
132const logFailure = ($: Dollar, hook: string, err: unknown): void => {
133  const text = `lumberroom: ${hook} failed, going on without it: ${messageOf(err)}`
134  try {
135    if (logged.has(hook)) $.ui.log(text, { to: 'debug' })
136    else {
137      logged.add(hook)
138      $.ui.log(text)
139    }
140  } catch {
141    // A failing log must not become the failure.
142  }
143}
144
145const debug = ($: Dollar, text: string): void => {
146  try {
147    $.ui.log(`lumberroom: ${text}`, { to: 'debug' })
148  } catch {
149    // As above.
150  }
151}
152
153const homeDir = async ($: Dollar): Promise<string> => {
154  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
155  return home.replace(/[\\/]+$/, '')
156}
157
158const existsOn = ($: Dollar): Exists => async (path) => {
159  try {
160    return await $.fs.exists(path)
161  } catch {
162    return false
163  }
164}
165
166const readText = async ($: Dollar, path: string): Promise<string> => {
167  try {
168    const text = await $.fs.read(path)
169    return typeof text === 'string' ? text : ''
170  } catch {
171    return ''
172  }
173}
174
175const projectFor = async ($: Dollar): Promise<string | undefined> => {
176  const cwd = await $.session.cwd()
177  if (projectMemo?.cwd === cwd) return projectMemo.slug
178  const slug = await resolveProject(cfg.project, cwd, existsOn($))
179  projectMemo = { cwd, slug }
180  return slug
181}
182
183/** True when the breaker lets a call go out now; stores the reset state of a cooled breaker. */
184const gate = async ($: Dollar): Promise<boolean> => {
185  const now = await $.clock.now()
186  const held = await read($, breakerRef)
187  const verdict = allow(held, now)
188  if (verdict.state.failures !== held.failures || verdict.state.openedAt !== held.openedAt) {
189    await update($, breakerRef, () => verdict.state)
190  }
191  return verdict.allowed
192}
193
194/** Feeds one engine outcome to the breaker and the stats; toasts once per outage. */
195const record = async ($: Dollar, outcome: CallOutcome): Promise<void> => {
196  if (isOutage(outcome)) {
197    const now = await $.clock.now()
198    const held = await read($, breakerRef)
199    const verdict = failure(held, now)
200    await update($, breakerRef, () => verdict.state)
201    await update($, statsRef, (s) => ({ ...s, offline: true }))
202    if (verdict.startsOutage) $.ui.toast(UNREACHABLE_TOAST)
203    return
204  }
205  if (outcome.kind === 'ok' || outcome.kind === 'tool_error') {
206    const held = await read($, breakerRef)
207    if (held.failures !== 0 || held.openedAt !== null) await update($, breakerRef, () => success())
208    const stats = await read($, statsRef)
209    if (stats.offline) await update($, statsRef, (s) => ({ ...s, offline: false }))
210    return
211  }
212  if (outcome.kind === 'not_connected') {
213    debug($, `the engine is not connected: ${outcome.error}`)
214    return
215  }
216  debug($, `the permission check refused an engine call: ${outcome.kind === 'denied' ? outcome.error : ''}`)
217  if (!toldDenied) {
218    toldDenied = true
219    $.ui.toast(PERMISSION_TOAST, { timeoutMs: 12_000 })
220  }
221}
222
223/** Applies `change` to the token estimate and shows the result on the status line. */
224const addCost = async ($: Dollar, change: (c: Cost) => Cost): Promise<void> => {
225  try {
226    $.ui.status(formatStatus(await update($, costRef, change)))
227  } catch (err) {
228    logFailure($, 'status line', err)
229  }
230}
231
232const sectionText = async ($: Dollar): Promise<string> => {
233  const digest = await read($, digestRef)
234  return buildSection(digest?.text ?? '', { includeRule: !hasRule, maxChars: cfg.digestMaxChars, project: digest?.project ?? null })
235}
236
237/** Forgets which hits this conversation has seen, and restarts the nudge count. */
238const resetDedup = async ($: Dollar): Promise<void> => {
239  try {
240    await update($, seenRef, () => [])
241    await update($, promptsRef, () => 0)
242  } catch (err) {
243    logFailure($, 'dedup reset', err)
244  }
245  await addCost($, afterContextReset)
246}
247
248/** One prompt found no connected server. No breaker failure: the server is absent, not down. */
249const noteNotConnectedPrompt = ($: Dollar): void => {
250  serverAbsent = true
251  notConnectedPrompts += 1
252  if (notConnectedPrompts < 3 || toldNotConnected) return
253  toldNotConnected = true
254  recallStopped = true
255  const names = SERVER_CANDIDATES.map((n) => `"${n}"`).join(' or ')
256  $.ui.toast(`${PLUGIN}: no ${names} MCP server with memory tools is connected. Check /mcp.`)
257}
258
259/** One context_bootstrap through the breaker, with the person's request as `query` when given. Stores the digest on success. */
260const bootstrap = async ($: Dollar, query?: string): Promise<'ok' | 'not_connected' | 'failed'> => {
261  const project = await projectFor($)
262  const args: Record<string, unknown> = {}
263  if (project !== undefined) args.project = project
264  if (query !== undefined) args.query = query
265  // Claude Code suppresses the bundled server when a registered one has its URL, and that one
266  // answers instead; the first candidate that is connected becomes the server for the session.
267  const candidates = await serversToTry($)
268  triedServers = candidates
269  let outcome: CallOutcome = { kind: 'not_connected', error: 'no server tried', ms: 0 }
270  for (const candidate of candidates) {
271    outcome = await callTool(mcpDeps($), candidate, 'context_bootstrap', args, cfg.bootstrapTimeoutMs)
272    if (outcome.kind !== 'not_connected') {
273      activeServer = candidate
274      break
275    }
276  }
277  await record($, outcome)
278  serverAbsent = outcome.kind === 'not_connected'
279  if (outcome.kind !== 'ok') {
280    debug($, `context_bootstrap gave ${outcome.kind}${"error" in outcome ? `: ${outcome.error}` : ""}`)
281    return outcome.kind === 'not_connected' ? 'not_connected' : 'failed'
282  }
283  const { text, memories } = digestFrom(outcome.data)
284  const before = await read($, digestRef)
285  const fetchedAt = await $.clock.now()
286  const fresh = { project: project ?? null, text, memories, fetchedAt }
287  await update($, digestRef, () => fresh)
288  try {
289    // The next session's fallback stays topic-neutral: a digest built for one request is not stored.
290    if (text.trim() !== '' && query === undefined) await $.store.set(cacheKey(project), fresh)
291  } catch (err) {
292    logFailure($, 'digest cache', err)
293  }
294  // The section text is cached per project; a different project needs a fresh render.
295  // A section rendered before the digest arrived is cached without it.
296  if (before === null || before.project !== (project ?? null)) $.ui.invalidate('prompt.section')
297  return 'ok'
298}
299
300/** The last digest fetched for a project, kept across sessions in $.store. It fills the section when the fresh bootstrap fails. */
301const cacheKey = (project: string | undefined): string => `digest-cache:${project ?? '-'}`
302
303const cachedDigest = async ($: Dollar): Promise<LumberroomDigest | null> => {
304  try {
305    const v = (await $.store.get(cacheKey(await projectFor($)))) as Partial<LumberroomDigest> | null | undefined
306    if (typeof v?.text !== 'string' || v.text.trim() === '') return null
307    return { project: typeof v.project === 'string' ? v.project : null, text: v.text, memories: typeof v.memories === 'number' ? v.memories : null, fetchedAt: typeof v.fetchedAt === 'number' ? v.fetchedAt : 0 }
308  } catch {
309    return null
310  }
311}
312
313/**
314 * Session start races the MCP connections: the server answers "no tool ... on a server named" for
315 * a moment and then connects. Retry for bootstrapTimeoutMs in total; a server that is still absent
316 * leaves the digest unset and the first prompt tries again.
317 */
318const bootstrapAtStart = async ($: Dollar): Promise<void> => {
319  const began = await $.clock.now()
320  while ((await bootstrap($)) === 'not_connected') {
321    if ((await $.clock.now()) - began >= cfg.bootstrapTimeoutMs) return
322    await $.clock.sleep(BOOTSTRAP_RETRY_MS)
323  }
324}
325
326
327
328
329
330
331/**
332 * The digest, fetched now when session start missed it. Runs before the recall gate so a server
333 * that connected late still gets its digest with recall off. Answers 'not_connected' when the
334 * server is absent; any other answer lets the caller go on. A `query` rides on that one call.
335 */
336const ensureDigest = async ($: Dollar, query?: string): Promise<'ok' | 'not_connected'> => {
337  if ((await read($, digestRef)) !== null) return 'ok'
338  if (!(await gate($))) return 'ok'
339  return (await bootstrap($, query)) === 'not_connected' ? 'not_connected' : 'ok'
340}
341
342/**
343 * Whether prompt.submit waits for the first-prompt digest before the turn goes out. False sends the
344 * turn at once and the redraw lands for turn 2. True would make every conversation's first prompt
345 * wait up to recallTimeoutMs, recall off included. It pays only where Claude Code composes the
346 * system prompt after prompt.submit returns: a probe mod on 2.1.309 saw prompt.compose after
347 * prompt.submit in an interactive session and before it under claude -p. The context digest
348 * (usesContextDigest) waits regardless, since it goes out once.
349 */
350const REFINE_BLOCKS_TURN = false
351
352/**
353 * Claims this conversation's one queried digest: the query when this prompt is the first eligible
354 * one, else undefined. The claim is stored before any call goes out, so the recall path and the
355 * refetch, which run side by side, never both send it.
356 */
357const claimPromptQuery = async ($: Dollar, text: string, originKind: string | undefined): Promise<string | undefined> => {
358  if (!cfg.digestQuery || recallStopped || !isEligible(text, originKind)) return undefined
359  if (await read($, promptDigestRef)) return undefined
360  // A held digest and no server: the refetch would cost a call and change nothing.
361  if (serverAbsent && (await read($, digestRef)) !== null) return undefined
362  await update($, promptDigestRef, () => true)
363  return clipQuery(text)
364}
365
366/**
367 * Refetches the held digest with the conversation's first eligible prompt as its query. An engine
368 * without `query` ignores it and answers the same text, which leaves the section cache alone. A
369 * timeout or an error keeps the session-start digest, with no retry. The call never feeds the
370 * breaker: the session-start digest is held, so a slow refetch is no outage, and recording it
371 * would toast "unreachable" beside a search that answered.
372 */
373const refineDigest = async ($: Dollar, query: string): Promise<void> => {
374  if (!(await gate($))) return
375  const project = await projectFor($)
376  const args: Record<string, unknown> = { query }
377  if (project !== undefined) args.project = project
378  const outcome = await callTool(mcpDeps($), serverName(), 'context_bootstrap', args, cfg.recallTimeoutMs)
379  if (outcome.kind !== 'ok') {
380    debug($, `context_bootstrap with a query gave ${outcome.kind}; keeping the session-start digest`)
381    return
382  }
383  const { text, memories } = digestFrom(outcome.data)
384  const held = await read($, digestRef)
385  if (text.trim() === '' || held === null || held.project !== (project ?? null) || held.text === text) return
386  const fetchedAt = await $.clock.now()
387  await update($, digestRef, () => ({ ...held, text, memories, fetchedAt }))
388  debug($, 'context_bootstrap with a query replaced the held digest')
389  $.ui.invalidate('prompt.section')
390}
391
392/**
393 * True when this prompt carries the digest itself: the guard held prompt.compose in this session,
394 * or in an earlier one on this machine by the store, and the compose hook has not run since.
395 */
396const usesContextDigest = async ($: Dollar, text: string, originKind: string | undefined): Promise<boolean> =>
397  isPersonPrompt(text, originKind) && (await guardOn($)) && !(await read($, composedRef))
398
399/**
400 * True while the guard holds prompt.compose. /clear gives the new conversation fresh $.state and
401 * raises no session.start, so the flag a past turn stored is read again here.
402 */
403const guardOn = async ($: Dollar): Promise<boolean> => {
404  if (await read($, guardedRef)) return true
405  if ((await read($, composedRef)) || (await $.store.get(GUARD_SEEN_KEY)) !== true) return false
406  await update($, guardedRef, () => true)
407  return true
408}
409
410/**
411 * The guard hides a compaction from session.compact too. The next request then holds fewer
412 * messages than the last prompt saw, and the digest and the recall hits it carried are gone. The
413 * plain transcript keeps the rows a compaction replaced, so the count reads the request's form.
414 */
415const noteContextShrink = async ($: Dollar): Promise<void> => {
416  const now = (await $.session.messages({ as: 'api' })).length
417  const held = await read($, contextDigestRef)
418  if (now < held.messages) {
419    await resetDedup($)
420    await update($, contextDigestRef, () => ({ shown: false, messages: now }))
421  } else if (now !== held.messages) {
422    await update($, contextDigestRef, (c) => ({ ...c, messages: now }))
423  }
424}
425
426/** The section text for the conversation's one context copy; '' once it went out, or with no digest held. */
427const contextDigest = async ($: Dollar): Promise<string> => {
428  if ((await read($, contextDigestRef)).shown || (await read($, digestRef)) === null) return ''
429  const text = await sectionText($)
430  if (text !== '') await update($, contextDigestRef, (c) => ({ ...c, shown: true }))
431  return text
432}
433
434/** `digestQuery` rides on the digest fetch when the digest is still missing. */
435const recallBlock = async ($: Dollar, text: string, originKind: string | undefined, digestQuery?: string): Promise<string> => {
436  if (recallStopped || !isPersonPrompt(text, originKind)) return ''
437  if ((await ensureDigest($, digestQuery)) === 'not_connected') {
438    noteNotConnectedPrompt($)
439    return ''
440  }
441
442  // The reminder keeps its own interval and does not depend on recall: every prompt from the person
443  // counts, a short one too. With no search to ride on it goes out in its own wrapper, since the
444  // recall wrapper's data note would tell the model to ignore it (spec 9.2).
445  const prompts = await update($, promptsRef, (n) => n + 1)
446  const nudge = nudgeDue(prompts, cfg.reviewInterval)
447  if (!cfg.recall || !isEligible(text, originKind)) return nudge ? buildReminderBlock() : ''
448
449  // A search that fails still carries the reminder, in the recall block with its data note.
450  const nudgeOnly = buildRecallBlock('', nudge)
451  if (!(await gate($))) return nudgeOnly
452
453  const project = await projectFor($)
454  const query = clipQuery(text)
455  const args: Record<string, unknown> = { query, limit: cfg.recallLimit }
456  if (project !== undefined) args.project = project
457  const namespaces = searchNamespaces(project, extrasFor(cfg.recallExtraProjects, project))
458  if (namespaces !== undefined) args.namespaces = namespaces
459  const outcome = await callTool(mcpDeps($), serverName(), 'memory_search', args, cfg.recallTimeoutMs)
460  await record($, outcome)
461  if (outcome.kind === 'not_connected') {
462    noteNotConnectedPrompt($)
463    return ''
464  }
465  if (outcome.kind !== 'ok') return nudgeOnly
466  serverAbsent = false
467  notConnectedPrompts = 0
468
469  const hits = hitsFrom(outcome.data)
470  const seen = new Set(await read($, seenRef))
471  const { block, kept } = selectHits(hits, seen, { maxChars: cfg.recallMaxChars, nudge, minSimilarity: cfg.recallMinSimilarity })
472  if (kept.length > 0) await update($, seenRef, (ids) => [...ids, ...kept.map((h) => h.id)])
473  const at = await $.clock.now()
474  await update($, lastRecallRef, () => ({ query, hits: kept.map(toRecalled), returned: hits.length, ms: outcome.ms, at }))
475  await update($, statsRef, (s) => ({ ...s, recalls: s.recalls + 1, hitsAttached: s.hitsAttached + kept.length, lastMs: outcome.ms }))
476  return buildRecallBlock(block, nudge)
477}
478
479
480/** Where a path lands once links resolve; undefined when it does not exist yet. */
481const realPathOf = ($: Dollar, target: string): Promise<string | undefined> =>
482  $.fs.stat(target, { resolve: true }).then(
483    (s) => s.realPath,
484    () => undefined,
485  )
486
487const guardsPath = async ($: Dollar, e: Readonly<Record<string, unknown>>): Promise<boolean> => {
488  const tool = String(e.tool)
489  if (!cfg.replaceBuiltinMemory || !GUARDED_TOOLS.has(tool)) return false
490  const path = pathArg(tool, e)
491  if (path === undefined) return false
492  const home = await homeDir($)
493  if (home === '') return false
494  const spelled = normalizePath(path, home, await $.session.cwd())
495  if (isBuiltinMemoryPath(spelled, home)) return true
496  // A link outside the folder can lead into it; stat answers where the path lands.
497  const real = await realPathOf($, path)
498  if (real !== undefined) return isBuiltinMemoryPath(real, home)
499  // A file about to be created has no stat; its folder may be the link.
500  const split = parentOf(path.startsWith('~') || !path.startsWith('/') ? spelled : path)
501  if (split === null || split.base === '' || split.base === '..') return false
502  const realParent = await realPathOf($, split.parent)
503  return realParent !== undefined && isBuiltinMemoryPath(`${realParent.replace(/\/+$/, '')}/${split.base}`, home)
504}
505
506
507/** Stored rows that read like `fact`; any failure answers [] so the write goes ahead plain. */
508const findSimilarRows = async ($: Dollar, fact: Fact): Promise<Conflict[]> => {
509  const outcome = await callTool(mcpDeps($), serverName(), 'memory_search', { query: fact.content, namespaces: [fact.namespace], limit: 3 }, cfg.recallTimeoutMs)
510  if (outcome.kind !== 'ok') return []
511  const out: Conflict[] = []
512  for (const hit of hitsFrom(outcome.data)) {
513    if (typeof hit.similarity === 'number' && hit.similarity >= SIMILAR_MIN) {
514      out.push({ id: hit.id, namespace: typeof hit.namespace === 'string' ? hit.namespace : fact.namespace, content: hit.content, similarity: hit.similarity })
515    }
516  }
517  return out
518}
519
520const extract = async ($: Dollar, signal?: AbortSignal): Promise<void> => {
521  if (isExtracting) return
522  isExtracting = true
523  try {
524    const all = await $.session.messages()
525    let from = await read($, extractedRef)
526    // The list shrinks after a /clear or a compaction; a stale index would skip new turns.
527    if (from > all.length) from = 0
528    // The plugin's own recall rows read as user turns; turnsFrom cuts them out.
529    const turns: Turn[] = turnsFrom(all.slice(from))
530    if (turns.length === 0) {
531      if (from !== all.length) await update($, extractedRef, () => all.length)
532      return
533    }
534
535    const project = (await projectFor($)) ?? null
536    const asked = await $.model.complete(
537      { model: cfg.extractorModel, prompt: buildExtractPrompt(turns, project), maxTokens: 2000, timeoutMs: EXTRACT_MODEL_TIMEOUT_MS },
538      signal === undefined ? undefined : { signal },
539    )
540    if (!asked.isAnswered) {
541      debug($, `the extractor model gave no answer: ${asked.reason}`)
542      return
543    }
544
545    const deps: WriteDeps = {
546      write: (args) => callTool(mcpDeps($), serverName(), 'memory_write', args, WRITE_TIMEOUT_MS),
547      store: { get: (key) => $.store.get(key), set: (key, value) => $.store.set(key, value) },
548      findSimilar: (fact) => findSimilarRows($, fact),
549      isOldVersion: async (fact, conflict) => {
550        const judged = await $.model.complete({ model: cfg.extractorModel, prompt: buildJudgePrompt(fact, conflict), maxTokens: 16, timeoutMs: JUDGE_MODEL_TIMEOUT_MS })
551        return judged.isAnswered && parseJudge(judged.text)
552      },
553      now: () => $.clock.now(),
554    }
555    let written = 0
556    let failed = 0
557    for (const fact of parseFacts(asked.text, project)) {
558      const result = await writeFact(deps, fact)
559      if (result.status === 'written') written += 1
560      if (result.status === 'refused') debug($, `the engine refused an extracted fact: ${result.error}`)
561      if (result.status === 'failed') {
562        failed += 1
563        debug($, `an extracted fact was not written: ${result.error}`)
564      }
565    }
566    if (written > 0) await update($, statsRef, (s) => ({ ...s, writes: s.writes + written }))
567    // A timeout or an unreachable server keeps the range open; the duplicate guard stops the others
568    // going out twice. A refused fact is terminal (the same text gets the same answer), so it
569    // does not hold the window.
570    if (failed === 0) await update($, extractedRef, () => all.length)
571  } finally {
572    isExtracting = false
573  }
574}
575
576const extractInBackground = ($: Dollar): void => {
577  // A dispatch's budget and signal end with it; a timer outlives it (reference.md, "Work that outlives a dispatch").
578  $.clock.after(0, () => {
579    extract($).catch((err: unknown) => logFailure($, 'extractor', err))
580  })
581}
582
583
584
585
586const importHint =
587  'lr-import found no lumberroom credential. Run `lumberroom login` and pick the Full profile, which carries the mayIngest grant, then run /lr-import again. Or save a token that has mayIngest: echo \'{"ingestToken":"<token>"}\' | claude plugin configure lumberroom-memory@lumberroom --values-stdin'
588const expiredHint = 'lr-import: the lumberroom CLI login has expired. Run `lumberroom whoami` to refresh it, then run /lr-import again.'
589
590/** The engine URL and bearer for /lr-import: the ingestToken option, else what the lumberroom CLI holds. */
591const ingestCredential = async ($: Dollar, home: string): Promise<IngestCredential | string> => {
592  const resolved = resolveIngest({
593    optionToken: cfg.ingestToken,
594    envUrl: await $.env.get('LUMBERROOM_URL'),
595    envToken: await $.env.get('LUMBERROOM_TOKEN'),
596    cliConfig: home === '' ? '' : await readText($, cliConfigPath(await $.env.get('LUMBERROOM_CONFIG'), home)),
597    now: await $.clock.now(),
598  })
599  if (resolved.ok) return resolved.credential
600  return resolved.reason === 'expired' ? expiredHint : importHint
601}
602
603/**
604 * Which folders under ~/.claude/projects belong to the current project: its root, cwd and git
605 * root, by name. A name over 200 characters carries a hash Claude Code adds, so those match on
606 * their first 200 characters.
607 */
608const currentMatcher = async ($: Dollar): Promise<{ current: string[]; isCurrent: (entry: string) => boolean }> => {
609  const cwd = await $.session.cwd()
610  const root = await $.session.root().catch(() => cwd)
611  const gitRoot = await findGitRoot(cwd, existsOn($))
612  const current = [...new Set([projectDirName(root), projectDirName(cwd), ...(gitRoot === null ? [] : [projectDirName(gitRoot)])])]
613  return { current, isCurrent: (entry) => current.some((name) => projectDirMatches(name, entry)) }
614}
615
616/** The current project's memory folders, found by listing ~/.claude/projects when a name is too long to spell. */
617const currentFolders = async ($: Dollar, home: string): Promise<{ dir: string; slug: string | null }[]> => {
618  const projects = `${home}/.claude/projects`
619  const slug = (await projectFor($)) ?? null
620  const { current } = await currentMatcher($)
621  const listed = current.some((name) => name.length > PROJECT_DIR_KEPT) ? await $.fs.list(projects).catch(() => []) : []
622  const names = listed.filter((entry) => entry.kind === 'dir').map((entry) => entry.name)
623  const folders = new Set(current.flatMap((name) => (name.length > PROJECT_DIR_KEPT ? names.filter((entry) => projectDirMatches(name, entry)) : [name])))
624  return [...folders].map((name) => ({ dir: `${projects}/${name}/memory`, slug }))
625}
626
627type FolderFiles = { path: string; file: MemoryFile }[]
628
629/** The parseable memory files in one memory folder; [] when the folder is absent. */
630const readMemoryFiles = async ($: Dollar, dir: string): Promise<FolderFiles> => {
631  const listed = await $.fs.list(dir).catch(() => [])
632  const files: FolderFiles = []
633  for (const entry of listed) {
634    if (entry.kind !== 'file' || !entry.name.endsWith('.md')) continue
635    const path = `${dir}/${entry.name}`
636    const file = parseMemoryFile(entry.name, await readText($, path))
637    if (file !== null) files.push({ path, file })
638  }
639  return files
640}
641
642/** One ingest run for the given groups. The proposal facts are built inside the run, once its id exists. */
643const postGroups = ($: Dollar, cred: IngestCredential, groups: { slug: string | null; files: FolderFiles }[], count: number) =>
644  postProposals(
645    {
646      fetch: async (url, init) => {
647        const r = await $.http.fetch(url, init)
648        return { status: r.status, ok: r.ok, text: r.text }
649      },
650      sleep: (ms) => $.clock.sleep(ms),
651    },
652    cred.baseUrl,
653    cred.token,
654    async (runId) => (await Promise.all(groups.map((g) => toProposalFacts(g.files, g.slug, runId)))).flat(),
655    count,
656  )
657
658const describeReport = (r: ImportReport): string =>
659  `${r.posted} posted (${r.proposalsNew} new, ${r.proposalsReinforced} reinforced, ${r.confirmations} confirmed, ${r.refused} refused, ${r.blocked} blocked) from ${r.files} files`
660
661/**
662 * The namespace to propose for one folder. A folder name does not say where a path segment ends,
663 * so the path is rebuilt first, with a bounded number of $.fs.exists probes, and its git root's
664 * slug wins. Only a folder with no findable path costs a model call, since the answer would lose
665 * to the path anyway. A bad model answer is global, never a guess the person did not see.
666 */
667const proposeNamespace = async ($: Dollar, folder: string, files: MemoryFile[]): Promise<Pick<PlanEntry, 'slug' | 'how' | 'reason'>> => {
668  const exists = existsOn($)
669  const decoded = folder.length > PROJECT_DIR_KEPT ? null : await decodeProjectDir(folder, exists)
670  if (decoded !== null) {
671    const root = (await findGitRoot(decoded, exists)) ?? decoded
672    const slug = slugFromPath(root)
673    if (slug !== '') return { slug, how: 'path', reason: root === decoded ? `found ${decoded}` : `found ${decoded}, git root ${root}` }
674  }
675  try {
676    const asked = await $.model.complete({
677      model: cfg.extractorModel,
678      prompt: buildNamespacePrompt(folder, files),
679      maxTokens: 32,
680      timeoutMs: JUDGE_MODEL_TIMEOUT_MS,
681    })
682    if (!asked.isAnswered) return { slug: null, how: 'fallback', reason: `no path found and the model gave no answer (${asked.reason}), so global` }
683    const answer = parseNamespaceAnswer(asked.text)
684    if (answer === null) return { slug: null, how: 'fallback', reason: 'no path found and the model answered with something other than a slug or global, so global' }
685    if (answer === 'global') return { slug: null, how: 'model', reason: 'no path found; the model judged these memories to belong to no one project' }
686    return { slug: answer, how: 'model', reason: `no path found; the model proposed ${answer}` }
687  } catch (err) {
688    return { slug: null, how: 'fallback', reason: `no path found and the model call failed (${messageOf(err)}), so global` }
689  }
690}
691
692/** Every folder under ~/.claude/projects with parseable memory files, in name order, each with a proposed namespace. */
693const buildPlan = async ($: Dollar, home: string): Promise<PlanEntry[]> => {
694  const projects = `${home}/.claude/projects`
695  const listed = await $.fs.list(projects).catch(() => [])
696  const names = listed.filter((entry) => entry.kind === 'dir').map((entry) => entry.name).sort()
697  const slug = (await projectFor($)) ?? null
698  const { isCurrent } = await currentMatcher($)
699  const entries: PlanEntry[] = []
700  for (const folder of names) {
701    const files = await readMemoryFiles($, `${projects}/${folder}/memory`)
702    if (files.length === 0) continue
703    const chosen = isCurrent(folder)
704      ? { slug, how: 'current' as const, reason: slug === null ? "this session's project (none is sent, so global)" : "this session's project" }
705      : await proposeNamespace($, folder, files.map((f) => f.file))
706    entries.push({ folder, files: files.length, ...chosen, status: 'pending' })
707  }
708  return entries
709}
710
711const NO_PLAN = 'lr-import: no plan yet. Run /lr-import all first.'
712
713/** The plan row a `confirm` or `skip` target names: a 1-based number or an exact folder name. -1 when none. */
714const findEntry = (entries: readonly PlanEntry[], target: string): number => {
715  if (/^\d+$/.test(target)) {
716    const i = Number(target) - 1
717    return i >= 0 && i < entries.length ? i : -1
718  }
719  return entries.findIndex((e) => e.folder === target)
720}
721
722/** Posts one plan folder, with `slug` for its project and reference memories. */
723const postFolder = async ($: Dollar, cred: IngestCredential, home: string, entry: PlanEntry, slug: string | null): Promise<{ ok: boolean; line: string }> => {
724  const files = await readMemoryFiles($, `${home}/.claude/projects/${entry.folder}/memory`)
725  const where = `${entry.folder} -> ${namespaceLabel(slug)}`
726  if (files.length === 0) return { ok: false, line: `${where}: no memory files left to send` }
727  const report = await postGroups($, cred, [{ slug, files }], files.length)
728  if (report.error !== undefined) return { ok: false, line: `${where}: stopped: ${report.error}. ${describeReport(report)}` }
729  return { ok: true, line: `${where}: ${describeReport(report)}` }
730}
731
732const runConfirm = async ($: Dollar, cred: IngestCredential, home: string, target: string, namespace: string | undefined): Promise<string> => {
733  const entries = parsePlan(await $.store.get(PLAN_KEY))
734  if (entries.length === 0) return NO_PLAN
735  const save = (): Promise<void> => $.store.set(PLAN_KEY, entries)
736
737  if (target === 'all') {
738    const lines: string[] = []
739    let stopped = false
740    for (const entry of entries) {
741      if (entry.status !== 'pending') continue
742      const result = await postFolder($, cred, home, entry, entry.slug)
743      lines.push(result.line)
744      if (!result.ok) {
745        stopped = true
746        break
747      }
748      entry.status = 'done'
749      await save()
750    }
751    if (lines.length === 0) return 'lr-import: nothing is pending. /lr-import plan shows the table.'
752    const left = entries.filter((e) => e.status === 'pending').length
753    const tail = stopped ? `Stopped at the first failure; ${left} still pending.` : 'They wait in the proposal queue for review.'
754    return ['lr-import confirm all:', ...lines, tail].join('\n')
755  }
756
757  const i = findEntry(entries, target)
758  const entry = entries[i]
759  if (entry === undefined) return `lr-import: "${target.slice(0, 80)}" is not in the plan. /lr-import plan shows the table.`
760  if (entry.status === 'done') return `lr-import: ${entry.folder} is already done. /lr-import all builds a new plan.`
761  let slug = entry.slug
762  if (namespace !== undefined) {
763    const parsed = parseNamespaceOverride(namespace)
764    if (!parsed.ok) return `lr-import: ${parsed.error}`
765    slug = parsed.slug
766  }
767  const result = await postFolder($, cred, home, entry, slug)
768  if (!result.ok) return `lr-import: ${result.line}`
769  entry.status = 'done'
770  await save()
771  return `lr-import: ${result.line}. They wait in the proposal queue for review.`
772}
773
774const runImport = async ($: Dollar, args: string): Promise<string> => {
775  const cmd = parseImportArgs(args)
776  if (cmd.kind === 'usage') return IMPORT_USAGE
777  const home = await homeDir($)
778  if (home === '') return 'lr-import: the home directory is unknown, so the memory folders cannot be found.'
779  // Building, showing and skipping a plan make no network call, so they need no credential.
780  const posts = cmd.kind === 'current' || cmd.kind === 'confirm'
781  const found = posts ? await ingestCredential($, home) : undefined
782  if (typeof found === 'string') return found
783  const unsafe = found === undefined ? null : checkBaseUrl(found.baseUrl)
784  if (unsafe !== null) return `lr-import: ${unsafe}`
785  const cred = found as IngestCredential
786
787  if (cmd.kind === 'build') {
788    const entries = await buildPlan($, home)
789    await $.store.set(PLAN_KEY, entries)
790    return formatPlan(entries)
791  }
792  if (cmd.kind === 'plan') {
793    const entries = parsePlan(await $.store.get(PLAN_KEY))
794    return entries.length === 0 ? NO_PLAN : formatPlan(entries)
795  }
796  if (cmd.kind === 'skip') {
797    const entries = parsePlan(await $.store.get(PLAN_KEY))
798    if (entries.length === 0) return NO_PLAN
799    const entry = entries[findEntry(entries, cmd.target)]
800    if (entry === undefined) return `lr-import: "${cmd.target.slice(0, 80)}" is not in the plan. /lr-import plan shows the table.`
801    if (entry.status === 'done') return `lr-import: ${entry.folder} is already done.`
802    entry.status = 'skipped'
803    await $.store.set(PLAN_KEY, entries)
804    return `lr-import: skipped ${entry.folder}. /lr-import confirm ${cmd.target} still posts it if you change your mind.`
805  }
806  if (cmd.kind === 'confirm') return runConfirm($, cred, home, cmd.target, cmd.namespace)
807
808  const groups: { slug: string | null; files: FolderFiles }[] = []
809  let count = 0
810  for (const { dir, slug } of await currentFolders($, home)) {
811    const files = await readMemoryFiles($, dir)
812    if (files.length > 0) groups.push({ slug, files })
813    count += files.length
814  }
815  if (count === 0) return 'lr-import: no memory files found to send.'
816
817  const report = await postGroups($, cred, groups, count)
818  const counts = describeReport(report)
819  if (report.error !== undefined) return `lr-import stopped: ${report.error}. ${counts}.`
820  return `lr-import: ${counts}. They wait in the proposal queue for review.`
821}
822
823
824/** How long /lr-setup keeps retrying context_bootstrap while Claude Code picks up the new rules. */
825const SETUP_RELOAD_MS = 3_000
826
827/** Fetches the digest after /lr-setup, retrying while the settings watcher catches up. */
828const loadDigestAfterSetup = async ($: Dollar): Promise<boolean> => {
829  const began = await $.clock.now()
830  while ((await bootstrap($)) !== 'ok') {
831    if ((await $.clock.now()) - began >= SETUP_RELOAD_MS) return false
832    await $.clock.sleep(BOOTSTRAP_RETRY_MS)
833  }
834  // A cached digest of the same project skips bootstrap's own invalidate.
835  $.ui.invalidate('prompt.section')
836  const section = estimateTokens(await sectionText($))
837  await addCost($, (c) => ({ ...c, section }))
838  return true
839}
840
841const runSetup = async ($: Dollar, rawArgs: string): Promise<string> => {
842  const args = rawArgs.trim()
843  if (args !== '' && args !== 'show') return SETUP_USAGE
844  const server = activeServer ?? (await serversToTry($))[0] ?? SERVER_CANDIDATES[0]
845  const rules = setupRules(server)
846  const configDir = ((await $.env.get('CLAUDE_CONFIG_DIR'))?.trim() || `${await homeDir($)}/.claude`).replace(/[\\/]+$/, '')
847  const path = `${configDir}/settings.json`
848  if (args === 'show') return `lr-setup: lumberroom runs as "${server}".\n${manualText(path, rules)}`
849
850  const merged = permissionLists(await $.settings.read())
851  const blocked = rules.filter((r) => missingRules([r], merged.deny).length === 0)
852  if (blocked.length > 0) return `lr-setup: a deny rule in your settings covers ${blocked.join(', ')}. An allow rule cannot override it; remove the deny rule in /permissions first.`
853
854  const missing = missingRules(rules, merged.allow)
855  if (missing.length > 0) {
856    let answer: string
857    try {
858      answer = await $.ui.ask(`Add ${missing.length} allow rule${missing.length === 1 ? '' : 's'} for lumberroom's own calls to ${path}?`, {
859        options: [ADD_LABEL, CANCEL_LABEL],
860        header: 'lr-setup',
861      })
862    } catch {
863      return `lr-setup: no one could be asked, so nothing changed.\n${manualText(path, missing)}`
864    }
865    if (answer !== ADD_LABEL) return `lr-setup: nothing changed.\n${manualText(path, missing)}`
866
867    let text = ''
868    if (await existsOn($)(path)) {
869      try {
870        const raw = await $.fs.read(path)
871        text = typeof raw === 'string' ? raw : ''
872      } catch (err) {
873        return `lr-setup: could not read ${path} (${messageOf(err)}), so nothing changed.\n${manualText(path, missing)}`
874      }
875    }
876    const result = mergeAllow(text, missing)
877    if (!result.ok) return `lr-setup: left ${path} alone because ${result.error}.\n${manualText(path, missing)}`
878    if (result.added.length > 0) await $.fs.write(path, result.text)
879  }
880
881  const added = missing.length === 0 ? 'The allow rules were already in place.' : `Added ${missing.join(', ')} to ${path}.`
882  if (await loadDigestAfterSetup($)) return `lr-setup: ${added} The digest is loaded and joins the system prompt from your next message.`
883  return `lr-setup: ${added} lumberroom has not answered yet. Start a new session; if the digest is still missing, check /mcp for "${server}".`
884}
885
886/** The compose hook runs, so the guard holds nothing here: the system prompt carries the digest from now on. */
887const composedOnce = async ($: Dollar): Promise<void> => {
888  await update($, composedRef, () => true)
889  if (!(await read($, guardedRef))) return
890  await update($, guardedRef, () => false)
891  try {
892    await $.store.delete(GUARD_SEEN_KEY)
893  } catch (err) {
894    logFailure($, 'guard flag', err)
895  }
896}
897
898/** A turn the guard answered past the plugin's compose hook: the digest moves to prompt.submit context. */
899const noteGuard = async ($: Dollar): Promise<void> => {
900  await update($, guardedRef, () => true)
901  $.ui.log(GUARD_NOTICE)
902  try {
903    await $.store.set(GUARD_SEEN_KEY, true)
904  } catch (err) {
905    logFailure($, 'guard flag', err)
906  }
907}
908
909export const register: Register = (on, options) => {
910  cfg = readConfig(options)
911
912  // Resolves the person's project, fetches the digest and registers /lr-import.
913  on('session.start', async ($, e, next) => {
914    const res = await next(e)
915    try {
916      serverAbsent = false
917      notConnectedPrompts = 0
918      recallStopped = false
919      toldNotConnected = false
920      toldDenied = false
921      projectMemo = undefined
922      activeServer = undefined
923      await update($, promptDigestRef, () => false)
924      // A guard seen on this machine before holds this session too, so its first prompt carries the digest.
925      try {
926        await guardOn($)
927      } catch (err) {
928        logFailure($, 'guard flag', err)
929      }
930      try {
931        await $.command.register({ name: 'lr-import', description: "Send Claude Code's memory files to lumberroom's proposal queue", argumentHint: '[all | plan | confirm <n|folder|all> [namespace] | skip <n>]' })
932        await $.command.register({ name: 'lr-setup', description: "Allow the plugin's own lumberroom calls, then load the digest", argumentHint: '[show]' })
933      } catch (err) {
934        logFailure($, 'command.register', err)
935      }
936
937      const home = await homeDir($)
938      const root = (await findGitRoot(e.cwd, existsOn($))) ?? e.cwd
939      const claudeMd = [home === '' ? '' : await readText($, `${home}/.claude/CLAUDE.md`), await readText($, `${root}/CLAUDE.md`)]
940      hasRule = claudeMd.some(hasDurableMemoryBlock)
941
942      await bootstrapAtStart($)
943      // A failed bootstrap leaves the cached digest in the section.
944      if ((await read($, digestRef)) === null) {
945        const cached = await cachedDigest($)
946        if (cached !== null) {
947          await update($, digestRef, () => cached)
948          $.ui.invalidate('prompt.section')
949        }
950      }
951      // The engine caches the section, so prompt.compose may not run again after a reload; the
952      // line has to be drawn here or it stays blank until a count changes.
953      const section = serverAbsent ? 0 : estimateTokens(await sectionText($))
954      await addCost($, (c) => ({ ...c, section }))
955    } catch (err) {
956      logFailure($, 'session.start', err)
957    }
958    return res
959  })
960
961  // The digest goes in the system prompt, once per render and cached. prompt.submit context would
962  // persist in the transcript and be sent again on every later turn (spec 2.1).
963  on('prompt.compose', async ($, e, next) => {
964    const res = await next(e)
965    try {
966      if (!(await read($, composedRef))) await composedOnce($)
967      if (res.sections.some((s) => s.id === SECTION_ID)) return res
968      // With no server, a cached digest still fills the section.
969      if (serverAbsent && (await read($, digestRef)) === null) return res
970      const text = await sectionText($)
971      await addCost($, (c) => ({ ...c, section: estimateTokens(text) }))
972      if (text === '') return res
973      return { sections: [...res.sections, { id: SECTION_ID, text, scope: 'session' as const }] }
974    } catch (err) {
975      logFailure($, 'prompt.compose', err)
976      return res
977    }
978  })
979
980  on('prompt.section', { name: 'memory' }, ($, e, next) => (cfg.replaceBuiltinMemory ? { text: null } : next(e)))
981
982  // next() sits outside the try block: a failure beneath the plugin must not run the chain twice.
983  on('prompt.submit', async ($, e, next) => {
984    let block = ''
985    let digest = ''
986    try {
987      const kind = e.origin?.kind
988      const viaContext = await usesContextDigest($, e.text, kind)
989      if (viaContext) await noteContextShrink($)
990      // The context copy goes out once, so it waits for the queried digest rather than miss it.
991      const blocks = REFINE_BLOCKS_TURN || (viaContext && !(await read($, contextDigestRef)).shown)
992      const query = await claimPromptQuery($, e.text, kind)
993      // With no digest held yet, ensureDigest sends the query on its own call, so a late server
994      // costs one call. With one held, the refetch runs on a timer unless REFINE_BLOCKS_TURN is set.
995      const held = query !== undefined && (await read($, digestRef)) !== null
996      const refine = (): Promise<void> =>
997        query === undefined ? Promise.resolve() : refineDigest($, query).catch((err: unknown) => logFailure($, 'digest refetch', err))
998      if (held && !blocks) $.clock.after(0, () => void refine())
999      const [recalled] = await Promise.all([recallBlock($, e.text, kind, held ? undefined : query), held && blocks ? refine() : undefined])
1000      block = recalled
1001      // The digest still missing means the query never reached a server; the next eligible prompt tries again.
1002      if (query !== undefined && !held && (await read($, digestRef)) === null) await update($, promptDigestRef, () => false)
1003      if (viaContext) digest = await contextDigest($)
1004    } catch (err) {
1005      logFailure($, 'prompt.submit', err)
1006    }
1007    // Every prompt redraws the line, so a status cleared by a reload comes back on the next prompt.
1008    await addCost($, (c) => ({
1009      ...c,
1010      section: digest === '' ? c.section : estimateTokens(digest),
1011      blocks: c.blocks + (block === '' ? 0 : estimateTokens(block)),
1012    }))
1013    const added = [digest, block].filter((t) => t !== '')
1014    if (added.length === 0) return next(e)
1015    return next({ ...e, context: [...(e.context ?? []), ...added] })
1016  })
1017
1018  on('tool.call', async ($, e, next) => {
1019    let isDenied = false
1020    try {
1021      isDenied = await guardsPath($, e as unknown as Readonly<Record<string, unknown>>)
1022    } catch (err) {
1023      logFailure($, 'tool.call', err)
1024    }
1025    if (isDenied) return { deny: GUARD_REASON }
1026    // The model's own lumberroom calls; the plugin's $.mcp.call results never enter the transcript.
1027    if (!knownServers().some((server) => isServerTool(e.tool, server)) || next.origin.plugin === PLUGIN) return next(e)
1028    const res = await next(e)
1029    if (res.deny === undefined) await addCost($, (c) => ({ ...c, tools: c.tools + estimateTokens(res.text ?? ''), toolCalls: c.toolCalls + 1 }))
1030    return res
1031  })
1032
1033  on('turn.complete', async ($, e, next) => {
1034    const res = await next(e)
1035    try {
1036      if (!(await guardOn($)) && guardHeld({ composed: await read($, composedRef), agentId: e.agentId, reason: e.reason })) await noteGuard($)
1037      // A turn's tool rows can grow the conversation well past the prompt's count before a compaction
1038      // cuts it, so the count is taken again here.
1039      if (e.agentId === undefined && (await read($, guardedRef)) && !(await read($, composedRef))) await noteContextShrink($)
1040      if (cfg.extractor === 'turn' && !serverAbsent && e.agentId === undefined && e.reason === 'answer') {
1041        // A review interval of 0 turns the nudge off; the extractor then runs at the default cadence.
1042        const every = cfg.reviewInterval > 0 ? cfg.reviewInterval : DEFAULTS.reviewInterval
1043        if ((await $.session.turns()) % every === 0) extractInBackground($)
1044      }
1045    } catch (err) {
1046      logFailure($, 'turn.complete', err)
1047    }
1048    return res
1049  })
1050
1051  on('session.end', async ($, e, next) => {
1052    try {
1053      if (cfg.extractor === 'session-end' && !serverAbsent && next.budget.remainingMs >= SESSION_END_MIN_MS) {
1054        await extract($, next.signal)
1055      }
1056    } catch (err) {
1057      logFailure($, 'session.end', err)
1058    }
1059    const res = await next(e)
1060    // /clear starts a conversation with no session.start. Hits sent before it are gone from the
1061    // model's context, so they may attach again, and the new conversation's first prompt sets the
1062    // digest's query again.
1063    if (e.reason === 'clear') {
1064      await resetDedup($)
1065      try {
1066        await update($, promptDigestRef, () => false)
1067        await update($, contextDigestRef, () => ({ shown: false, messages: 0 }))
1068      } catch (err) {
1069        logFailure($, 'digest query reset', err)
1070      }
1071    }
1072    return res
1073  })
1074
1075  on('session.compact', async ($, e, next) => {
1076    try {
1077      if (cfg.extractor !== 'off' && !serverAbsent && e.agentId === undefined && e.trigger !== 'precompute') {
1078        // The model call takes a signal; the wait for it does not count against the hook budget,
1079        // so a hung call would hold compaction. On the bound the window stays where it was and the
1080        // next extraction reads those turns again.
1081        const stop = typeof AbortController === 'undefined' ? undefined : new AbortController()
1082        const raced = await raceSleep(extract($, stop?.signal), (ms) => $.clock.sleep(ms), COMPACT_EXTRACT_BOUND_MS)
1083        if (raced.timedOut) {
1084          stop?.abort()
1085          debug($, `the extraction before compaction passed ${COMPACT_EXTRACT_BOUND_MS} ms, compacting without it`)
1086        }
1087      }
1088    } catch (err) {
1089      logFailure($, 'session.compact', err)
1090    }
1091    const res = await next({ ...e, instructions: [e.instructions, COMPACT_LINE].filter(Boolean).join('\n\n') })
1092    // Compaction replaces the transcript that held the recall blocks, so they may attach again.
1093    // A precompute installs nothing, a veto leaves the transcript as it was, and a subagent's
1094    // compaction is not the main conversation's.
1095    if (e.trigger !== 'precompute' && e.agentId === undefined && res.skip === undefined) await resetDedup($)
1096    return res
1097  })
1098
1099  on('command.run', { command: 'lr-setup' }, async ($, e) => {
1100    try {
1101      return { text: await runSetup($, e.args) }
1102    } catch (err) {
1103      logFailure($, 'command.run', err)
1104      return { text: `lr-setup failed: ${messageOf(err)}` }
1105    }
1106  })
1107
1108  on('command.run', { command: 'lr-import' }, async ($, e) => {
1109    try {
1110      return { text: await runImport($, e.args) }
1111    } catch (err) {
1112      logFailure($, 'command.run', err)
1113      return { text: `lr-import failed: ${messageOf(err)}` }
1114    }
1115  })
1116}
1117
src/breaker.ts 36 lines
1// The circuit breaker from lumberroom-openclaw src/recall.ts, as pure functions over plain data so
2// its state can live in $.state and survive a hot reload.
3
4import type { LumberroomBreaker } from '../types'
5
6export const BREAKER_THRESHOLD = 3
7export const BREAKER_COOLDOWN_MS = 60_000
8
9export const CLOSED: LumberroomBreaker = { failures: 0, openedAt: null }
10
11/**
12 * Whether a call may go out at `now`. An open breaker past its cooldown closes: the result then
13 * carries the reset state and `allowed: true`.
14 */
15export function allow(state: LumberroomBreaker, now: number): { allowed: boolean; state: LumberroomBreaker } {
16  if (state.openedAt === null) return { allowed: true, state }
17  if (now - state.openedAt >= BREAKER_COOLDOWN_MS) return { allowed: true, state: CLOSED }
18  return { allowed: false, state }
19}
20
21export function success(): LumberroomBreaker {
22  return CLOSED
23}
24
25/**
26 * Records a failure. `startsOutage` is true for the first failure after a success or a reset, so
27 * the caller tells the person once per outage. The breaker opens at BREAKER_THRESHOLD.
28 */
29export function failure(state: LumberroomBreaker, now: number): { state: LumberroomBreaker; startsOutage: boolean } {
30  const failures = state.failures + 1
31  return {
32    state: { failures, openedAt: failures >= BREAKER_THRESHOLD ? now : state.openedAt },
33    startsOutage: state.failures === 0,
34  }
35}
36
src/config.ts 132 lines
1// The plugin's options, read once per load. Every userConfig field has a default here too, so a
2// value the manifest's validation let through still lands inside its range.
3
4import { slugFromPath } from './project'
5
6export type ExtractorMode = 'off' | 'turn' | 'session-end'
7
8/**
9 * Parsed `recallExtraProjects`. Claude Code reads plugin options from user, --settings or managed
10 * settings only, never from project settings, so a per-project value lives inside the option.
11 */
12export interface RecallExtras {
13  /** Slugs searched in every project. */
14  everywhere: string[]
15  /** Project slug -> slugs searched only when that project is current. */
16  byProject: Record<string, string[]>
17}
18
19export interface Config {
20  /** `auto`, `none`, or a slug. */
21  project: string
22  /** Off by default: each recall block stays in context for the rest of the session (spec 2.1). */
23  recall: boolean
24  /** Sends the first eligible prompt to context_bootstrap as its query, once a conversation. */
25  digestQuery: boolean
26  /** Other projects to search with each prompt, in the engine's slug form, deduplicated. May hold the current project's own slug; `extrasFor` resolves it. */
27  recallExtraProjects: RecallExtras
28  recallLimit: number
29  recallMaxChars: number
30  /** Hits with a similarity below this are dropped. Hits that carry none pass. */
31  recallMinSimilarity: number
32  recallTimeoutMs: number
33  bootstrapTimeoutMs: number
34  digestMaxChars: number
35  reviewInterval: number
36  replaceBuiltinMemory: boolean
37  extractor: ExtractorMode
38  extractorModel: string
39  /** Absent when unset or blank. Without it /lr-import uses the lumberroom CLI's credential. */
40  ingestToken?: string
41}
42
43export const DEFAULTS: Config = {
44  project: 'auto',
45  recall: false,
46  digestQuery: true,
47  recallExtraProjects: { everywhere: [], byProject: {} },
48  recallLimit: 6,
49  recallMaxChars: 4000,
50  recallMinSimilarity: 0.6,
51  recallTimeoutMs: 2500,
52  bootstrapTimeoutMs: 5000,
53  digestMaxChars: 8000,
54  reviewInterval: 8,
55  replaceBuiltinMemory: true,
56  extractor: 'off',
57  extractorModel: 'haiku',
58}
59
60/**
61 * The extra slugs to search in `currentSlug`: `everywhere` plus that project's own entry,
62 * deduplicated, without the current slug itself. `currentSlug` is undefined with project `none`,
63 * so only `everywhere` applies.
64 */
65export function extrasFor(extras: RecallExtras, currentSlug: string | undefined): string[] {
66  // hasOwn keeps a project named `constructor` or `toString` from reading Object.prototype.
67  const own = currentSlug !== undefined && Object.hasOwn(extras.byProject, currentSlug) ? (extras.byProject[currentSlug] ?? []) : []
68  return [...new Set([...extras.everywhere, ...own])].filter((slug) => slug !== currentSlug)
69}
70
71/**
72 * Options as `register` receives them -> Config. A value of the wrong type, or a number outside
73 * the manifest's min and max, falls back to the default or is clamped. Never throws.
74 */
75export function readConfig(options: Readonly<Record<string, unknown>>): Config {
76  const str = (v: unknown, d: string): string => (typeof v === 'string' && v.trim() !== '' ? v.trim() : d)
77  const bool = (v: unknown, d: boolean): boolean => (typeof v === 'boolean' ? v : d)
78  // Mirrors min and max in .claude-plugin/plugin.json. Change both together.
79  const num = (v: unknown, d: number, min: number, max: number): number =>
80    typeof v === 'number' && Number.isFinite(v) ? Math.min(max, Math.max(min, Math.round(v))) : d
81
82  // Similarity is a fraction, so this one skips the rounding `num` does.
83  const frac = (v: unknown, d: number, min: number, max: number): number =>
84    typeof v === 'number' && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : d
85
86  // Split on commas and whitespace, then slug each entry the way the engine does, so a name the
87  // engine would reject or rewrite never reaches memory_search as a namespace. `a=b+c` scopes b
88  // and c to project a; a malformed entry (`=x`, `x=`, `a=b=c`) is dropped whole.
89  const extras = (v: unknown): RecallExtras => {
90    const everywhere = new Set<string>()
91    const scoped = new Map<string, Set<string>>()
92    for (const entry of typeof v === 'string' ? v.split(/[,\s]+/) : []) {
93      const sides = entry.split('=')
94      if (sides.length === 1) {
95        const slug = slugFromPath(entry)
96        if (slug !== '') everywhere.add(slug)
97        continue
98      }
99      if (sides.length !== 2) continue
100      const project = slugFromPath(sides[0] ?? '')
101      const slugsOf = (sides[1] ?? '').split('+').map(slugFromPath).filter((x) => x !== '')
102      if (project === '' || slugsOf.length === 0) continue
103      const set = scoped.get(project) ?? new Set<string>()
104      for (const slug of slugsOf) set.add(slug)
105      scoped.set(project, set)
106    }
107    // fromEntries defines own properties, so a project named `__proto__` stays plain data.
108    return { everywhere: [...everywhere], byProject: Object.fromEntries([...scoped].map(([k, set]) => [k, [...set]])) }
109  }
110
111  const extractor = options.extractor
112  const token = typeof options.ingestToken === 'string' ? options.ingestToken.trim() : ''
113  const config: Config = {
114    project: str(options.project, DEFAULTS.project),
115    recall: bool(options.recall, DEFAULTS.recall),
116    digestQuery: bool(options.digestQuery, DEFAULTS.digestQuery),
117    recallExtraProjects: extras(options.recallExtraProjects),
118    recallLimit: num(options.recallLimit, DEFAULTS.recallLimit, 1, 20),
119    recallMaxChars: num(options.recallMaxChars, DEFAULTS.recallMaxChars, 500, 16000),
120    recallMinSimilarity: frac(options.recallMinSimilarity, DEFAULTS.recallMinSimilarity, 0, 1),
121    recallTimeoutMs: num(options.recallTimeoutMs, DEFAULTS.recallTimeoutMs, 500, 8000),
122    bootstrapTimeoutMs: num(options.bootstrapTimeoutMs, DEFAULTS.bootstrapTimeoutMs, 5000, 8000),
123    digestMaxChars: num(options.digestMaxChars, DEFAULTS.digestMaxChars, 1000, 30000),
124    reviewInterval: num(options.reviewInterval, DEFAULTS.reviewInterval, 0, 100),
125    replaceBuiltinMemory: bool(options.replaceBuiltinMemory, DEFAULTS.replaceBuiltinMemory),
126    extractor: extractor === 'turn' || extractor === 'session-end' ? extractor : 'off',
127    extractorModel: str(options.extractorModel, DEFAULTS.extractorModel),
128  }
129  if (token !== '') config.ingestToken = token
130  return config
131}
132
src/cost.ts 45 lines
1// The token counter on the status line: what lumberroom adds to the context the model reads.
2// Counts are estimates at four characters a token. The mod API counts tokens only for whole
3// context categories, so a per-block count has to be estimated.
4
5import { toolPrefix } from './server'
6
7export interface Cost {
8  /** The system prompt section, sent with every request. */
9  section: number
10  /** Recall and reminder blocks attached to prompts since the context last emptied. */
11  blocks: number
12  /** Results of the model's own calls to lumberroom tools since the context last emptied. */
13  tools: number
14  toolCalls: number
15}
16
17export const NO_COST: Cost = { section: 0, blocks: 0, tools: 0, toolCalls: 0 }
18
19export const CHARS_PER_TOKEN = 4
20
21export function estimateTokens(text: string): number {
22  return Math.ceil(text.length / CHARS_PER_TOKEN)
23}
24
25/** True for an MCP tool name served by `server`, as Claude Code spells it. */
26export function isServerTool(tool: string, server: string): boolean {
27  return tool.startsWith(toolPrefix(server))
28}
29
30/** Compaction and /clear drop the transcript; the section comes back with the next request. */
31export function afterContextReset(cost: Cost): Cost {
32  return { ...NO_COST, section: cost.section }
33}
34
35function short(tokens: number): string {
36  return tokens < 1000 ? String(tokens) : `${(tokens / 1000).toFixed(1)}k`
37}
38
39/** `lumberroom ~2.4k tokens in context: digest 2.0k, reminders 30, tools 400 (2 calls)`. */
40export function formatStatus(cost: Cost): string {
41  const total = cost.section + cost.blocks + cost.tools
42  const parts = [`digest ${short(cost.section)}`, `reminders ${short(cost.blocks)}`, `tools ${short(cost.tools)} (${cost.toolCalls} ${cost.toolCalls === 1 ? 'call' : 'calls'})`]
43  return `lumberroom ~${short(total)} tokens in context: ${parts.join(', ')}`
44}
45
src/digest.ts 81 lines
1// The system-prompt section: the write rule and the engine's digest, and the check that keeps the
2// CLAUDE.md block from doubling the rule (spec 5).
3
4export const SECTION_ID = 'lumberroom-memory:memory'
5export const DIGEST_HEADING = '# Durable memory (lumberroom)'
6
7/** ENG client/CLAUDE.md.snippet without its markers and its own heading. Keep in step with it. */
8export const WRITE_RULE = `You have a shared memory service (MCP server \`lumberroom\`) that persists across sessions, machines,
9and clients. It is the same store every one of this user's agents reads and writes.
10
11**Read.** This section already carries a memory digest. When a task depends on a past
12decision, a preference, a host, a credential location, or "how do we usually do this", call
13\`memory_search\` before asking the user or assuming. Call \`registry_get\` for exact operational
14values (hosts, service endpoints, where a credential lives).
15
16**Write.** After any exchange that establishes a decision, a preference, a constraint, or a
17durable fact, call \`memory_write\`. Without asking. Without announcing it. One fact per call,
18phrased so it stands alone in six months, carrying the numbers, identifiers, paths and dates the
19fact needs, and the cause, scope qualifier and reversal condition whenever the fact turns on them.
20Cut the trail of how you came to believe it: the search you ran, the file you read on the way, the
21argument for the claim. No hedges, no evaluative words, no restated context, no inventory of what
22you left unchanged. A list or a timeline runs long and that is right; prose about a short fact
23runs long and that is bloat. Two facts from one exchange are two calls.
24
25- \`user:me\`: facts about this user and how they work
26- \`project:<slug>\`: facts scoped to one codebase
27- \`global\`: facts true everywhere: infrastructure, conventions, credential locations
28
29Do not write transient chatter, file contents, secrets, or anything you would not want repeated
30back next month.`
31
32/**
33 * context_bootstrap's parsed data -> { text, memories }. `text` is data.text when a string, else
34 * data itself when a string (an engine that answered markdown), else "". `memories` is
35 * data.counts.memories when a number.
36 */
37export function digestFrom(data: unknown): { text: string; memories: number | null } {
38  if (typeof data === 'string') return { text: data, memories: null }
39  if (typeof data !== 'object' || data === null || Array.isArray(data)) return { text: '', memories: null }
40  const obj = data as { text?: unknown; counts?: unknown }
41  const text = typeof obj.text === 'string' ? obj.text : ''
42  const counts = obj.counts
43  const memories =
44    typeof counts === 'object' && counts !== null && typeof (counts as { memories?: unknown }).memories === 'number'
45      ? (counts as { memories: number }).memories
46      : null
47  return { text, memories }
48}
49
50/**
51 * The section text: DIGEST_HEADING, the project line when `project`, WRITE_RULE when
52 * `includeRule`, then the digest clipped so the whole section fits `maxChars`, cut at the last
53 * whole line. "" when there is no digest and no rule.
54 */
55export function buildSection(digest: string, opts: { includeRule: boolean; maxChars: number; project: string | null }): string {
56  const body = digest.trim()
57  if (body === '' && !opts.includeRule) return ''
58  const parts = [DIGEST_HEADING]
59  if (opts.project) parts.push(`Project: ${opts.project}`)
60  if (opts.includeRule) parts.push(WRITE_RULE)
61  const prefix = parts.join('\n\n')
62  const room = opts.maxChars - prefix.length - 2
63  if (body === '' || room <= 0) return opts.includeRule ? prefix : ''
64  let clipped = body
65  if (body.length > room) {
66    // Cut at a newline so a fact is never sent half-written; a digest line that alone exceeds
67    // the room is dropped whole.
68    const cut = body.lastIndexOf('\n', room)
69    clipped = cut > 0 ? body.slice(0, cut).trimEnd() : ''
70  }
71  if (clipped === '') return opts.includeRule ? prefix : ''
72  return `${prefix}\n\n${clipped}`
73}
74
75/** True when a CLAUDE.md holds a `# Durable memory` heading and names memory_write after it. */
76export function hasDurableMemoryBlock(claudeMd: string): boolean {
77  const heading = /^# Durable memory\b.*$/m.exec(claudeMd)
78  if (!heading) return false
79  return claudeMd.slice(heading.index + heading[0].length).includes('memory_write')
80}
81
src/fallback.ts 20 lines
1// The digest's second route, for a machine where Claude Code's built-in guard (sec-default@builtin)
2// holds prompt.compose past the user tier. The guard seats itself with managed settings or a Team or
3// Enterprise login, and a plugin installed from a GitHub marketplace always sits in the user tier, so
4// the plugin's section never reaches the system prompt there. prompt.submit context still passes.
5
6/** $.store key, kept across sessions: a past session on this machine finished a turn with no prompt.compose. */
7export const GUARD_SEEN_KEY = 'guard-seen'
8
9export const GUARD_NOTICE =
10  "lumberroom: Claude Code's built-in guard (sec-default) holds this plugin's system-prompt hook, so the digest now rides on your prompts instead. For the full plugin, see the README section \"Organization-managed Claude Code\"."
11
12/**
13 * True when a finished turn shows the guard holds prompt.compose: the main conversation's model
14 * answered and the plugin's compose hook never ran this session. An interactive session raises
15 * prompt.compose after prompt.submit, so the first prompt cannot tell; the turn's end can.
16 */
17export function guardHeld(turn: { composed: boolean; agentId: string | undefined; reason: string }): boolean {
18  return !turn.composed && turn.agentId === undefined && turn.reason === 'answer'
19}
20
src/extractor.ts 168 lines
1// The optional extractor's prompts and parsers. Pure text in, text out; register.ts runs the model.
2
3import type { Conflict, Fact } from './writes'
4
5/** One message as $.session.messages() answers it, reduced to what the prompt reads. */
6export interface Turn {
7  role: 'user' | 'assistant'
8  text: string
9}
10
11/** The recall block and its tags, as src/recall.ts writes them. */
12const RECALL_BLOCK = /<lumberroom-recall>[\s\S]*?<\/lumberroom-recall>/gi
13const RECALL_UNCLOSED = /<lumberroom-recall>[\s\S]*$/i
14const RECALL_STRAY_CLOSE = /<\/lumberroom-recall>/gi
15const EMPTY_WRAPPER = /<([A-Za-z][\w-]*)>\s*<\/\1>/g
16
17/**
18 * Text with every `<lumberroom-recall>` block cut out. The plugin attaches that block as a hidden
19 * user row, so `$.session.messages()` hands it back as something the person said, and an
20 * extractor that reads it would write recalled memories back as new facts.
21 */
22export function stripRecall(text: string): string {
23  return text.replace(RECALL_BLOCK, '').replace(RECALL_UNCLOSED, '').replace(RECALL_STRAY_CLOSE, '').replace(EMPTY_WRAPPER, '')
24}
25
26/** Messages -> turns: recall blocks removed, rows left empty dropped. */
27export function turnsFrom(messages: ReadonlyArray<{ role: 'user' | 'assistant'; text: string }>): Turn[] {
28  const turns: Turn[] = []
29  for (const m of messages) {
30    const text = stripRecall(m.text).trim()
31    if (text !== '') turns.push({ role: m.role, text })
32  }
33  return turns
34}
35
36export const EXTRACT_MAX_INPUT_CHARS = 24_000
37export const EXTRACT_MAX_FACTS = 10
38
39/**
40 * The prompt for $.model.complete. It carries the write rule's standards (one fact per line,
41 * standalone, identifiers and dates kept, no chatter, no secrets, no file contents), the
42 * namespaces allowed (`user:me`, `global`, `project:<slug>` when `project`), and the turns, newest
43 * kept when they overflow EXTRACT_MAX_INPUT_CHARS. It asks for JSON Lines of
44 * {"content","namespace","tags"} and the single word NONE when nothing qualifies.
45 */
46export function buildExtractPrompt(turns: readonly Turn[], project: string | null): string {
47  const namespaces = allowedNamespaces(project)
48  const label = (t: Turn) => `${t.role === 'user' ? 'User' : 'Assistant'}: ${t.text}`
49  // Walk from the newest turn back: recent turns hold the facts not yet stored.
50  const kept: string[] = []
51  let used = 0
52  for (let i = turns.length - 1; i >= 0; i--) {
53    const entry = label(turns[i] as Turn)
54    const room = EXTRACT_MAX_INPUT_CHARS - used
55    if (entry.length <= room) {
56      kept.unshift(entry)
57      used += entry.length + 2
58    } else {
59      // A single turn over the cap keeps its tail only when nothing newer was kept.
60      if (kept.length === 0) kept.unshift(entry.slice(entry.length - EXTRACT_MAX_INPUT_CHARS))
61      break
62    }
63  }
64  return [
65    'You extract durable facts from a conversation for a long-term memory store.',
66    'Write a fact only for a decision, preference, constraint or durable technical fact the conversation established.',
67    'Each fact stands alone and makes sense in six months: name the subject and keep numbers, identifiers, paths and dates.',
68    'One fact per line. No chatter, no restated context, no secrets or credentials, no file contents.',
69    '',
70    `Allowed namespaces: ${namespaces.join(', ')}.`,
71    'Answer in JSON Lines, one object per line: {"content": "...", "namespace": "...", "tags": ["..."]}.',
72    'Answer with the single word NONE when nothing qualifies. Add no other text.',
73    '',
74    'Conversation:',
75    kept.join('\n\n'),
76  ].join('\n')}
77
78/**
79 * Model text -> facts. Reads each line that parses as a JSON object with a non-empty string
80 * content and a namespace in the allowed set; tags kept when an array of strings. Ignores code
81 * fences, prose and NONE. At most EXTRACT_MAX_FACTS. A content that matches a credential pattern
82 * (private key block, `lr_` token, AWS key id, `password=`/`token=` assignment, a known token
83 * prefix with its minimum tail, a connection string with a password) is dropped.
84 */
85export function parseFacts(text: string, project: string | null): Fact[] {
86  const allowed = allowedNamespaces(project)
87  const facts: Fact[] = []
88  for (const raw of text.split('\n')) {
89    const line = raw.trim()
90    if (!line.startsWith('{')) continue
91    let obj: unknown
92    try {
93      obj = JSON.parse(line)
94    } catch {
95      continue
96    }
97    if (typeof obj !== 'object' || obj === null) continue
98    const { content, namespace, tags } = obj as Record<string, unknown>
99    if (typeof content !== 'string' || content.trim() === '') continue
100    if (typeof namespace !== 'string' || !allowed.includes(namespace)) continue
101    if (looksLikeCredential(content)) continue
102    const fact: Fact = { content, namespace }
103    if (Array.isArray(tags) && tags.every((t) => typeof t === 'string')) fact.tags = tags as string[]
104    facts.push(fact)
105    if (facts.length === EXTRACT_MAX_FACTS) break
106  }
107  return facts}
108
109/** Asks whether `conflict` is the older version of the same fact as `fact`; answer YES or NO. */
110export function buildJudgePrompt(fact: Fact, conflict: Conflict): string {
111  return [
112    'Two memory entries follow. Decide whether the OLD entry is an earlier version of the same fact as the NEW entry, so that the NEW one replaces it.',
113    'Answer YES when both state the same thing and the NEW one is current. Answer NO when they describe different things or both stay true.',
114    'Answer with one word, YES or NO.',
115    '',
116    `NEW: ${fact.content}`,
117    `OLD: ${conflict.content}`,
118  ].join('\n')}
119
120/** True only when the first word of the trimmed answer is YES, any case. */
121export function parseJudge(text: string): boolean {
122  const first = text.trim().split(/[^A-Za-z]+/)[0] ?? ''
123  return first.toUpperCase() === 'YES'}
124
125function allowedNamespaces(project: string | null): string[] {
126  return project ? ['user:me', 'global', `project:${project}`] : ['user:me', 'global']
127}
128
129// A fact that reaches the store is read back into every client, so a leaked secret spreads. These
130// patterns are a floor, not a scanner: the model is also told to leave secrets out. The prefix
131// rules mirror ENG src/domain/tripwire.rs PREFIX_RULES with the same minimum tails, because that
132// file's own notes show a bare prefix fires on prose ("keys start with sk-"). The engine refuses
133// these at `open`; a refused extractor write would pin its window (src/writes.ts), so the plugin
134// drops them first.
135const CREDENTIAL_PATTERNS: readonly RegExp[] = [
136  /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
137  /\blr_[A-Za-z0-9_-]{8,}/,
138  /\bAKIA[0-9A-Z]{16}\b/,
139  /\b(?:password|passwd|token|secret|api[_-]?key)\s*=\s*\S+/i,
140  // Each prefix needs a boundary before it and a long enough tail of token bytes after it.
141  /(?:^|[^A-Za-z0-9_-])(?:sk-ant-[A-Za-z0-9_-]{24}|sk-[A-Za-z0-9_-]{20}|github_pat_[A-Za-z0-9_-]{40}|gh[pousr]_[A-Za-z0-9_-]{30}|glpat-[A-Za-z0-9_-]{20}|xox[bpa]-[A-Za-z0-9_-]{20}|(?:sk|rk)_live_[A-Za-z0-9_-]{16}|hf_[A-Za-z0-9_-]{30}|npm_[A-Za-z0-9_-]{30})/,
142]
143
144const URL_WITH_USERINFO = /(?:^|[^A-Za-z0-9_-])(?:postgres(?:ql)?|mongodb(?:\+srv)?|mysql|rediss?|amqps?):\/\/([^\s/?#,"'`<>)\]]*)/gi
145
146/** Empty, interpolated (`$`, `{`, `}`), `<bracketed>` or a run of `*`: the engine's placeholder test. */
147function isPlaceholderPassword(password: string): boolean {
148  return password === '' || /[${}]/.test(password) || (password.startsWith('<') && password.endsWith('>')) || /^\*+$/.test(password)
149}
150
151function hasUrlPassword(content: string): boolean {
152  for (const m of content.matchAll(URL_WITH_USERINFO)) {
153    const authority = m[1] ?? ''
154    // Userinfo ends at the last `@` and the password starts at the first `:`, as in the engine.
155    const at = authority.lastIndexOf('@')
156    if (at < 0) continue
157    const userinfo = authority.slice(0, at)
158    const colon = userinfo.indexOf(':')
159    if (colon < 0) continue
160    if (!isPlaceholderPassword(userinfo.slice(colon + 1))) return true
161  }
162  return false
163}
164
165function looksLikeCredential(content: string): boolean {
166  return CREDENTIAL_PATTERNS.some((re) => re.test(content)) || hasUrlPassword(content)
167}
168
src/guard.ts 62 lines
1// Which file-tool calls touch Claude Code's built-in memory (spec 8).
2
3export const GUARD_REASON =
4  "Claude Code's built-in memory is off in this session. Use lumberroom: memory_search to read, memory_write to record."
5
6// Grep and Glob take a search root in `path`. They are absent from the 2.1.287 tool table this
7// plugin was built against, so the names are compared as strings and the guard sits idle until a
8// build that has them arrives. Bash is not guarded: a command line has no path argument to read.
9export const GUARDED_TOOLS: ReadonlySet<string> = new Set(['Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'Grep', 'Glob'])
10
11/** The path argument of a guarded tool's input (`file_path`, `notebook_path`, or a search tool's `path`), else undefined. */
12export function pathArg(tool: string, input: Readonly<Record<string, unknown>>): string | undefined {
13  if (!GUARDED_TOOLS.has(tool)) return undefined
14  const value = tool === 'NotebookEdit' ? input.notebook_path : tool === 'Grep' || tool === 'Glob' ? input.path : input.file_path
15  return typeof value === 'string' ? value : undefined
16}
17
18/**
19 * The folder part and the last segment of an absolute path, cut on the text alone (a `..` stays
20 * for the file system to resolve). Null for a relative path, which has no parent to stat.
21 */
22export function parentOf(path: string): { parent: string; base: string } | null {
23  if (!path.startsWith('/')) return null
24  const trimmed = path.replace(/\/+$/, '')
25  const cut = trimmed.lastIndexOf('/')
26  return { parent: cut <= 0 ? '/' : trimmed.slice(0, cut), base: trimmed.slice(cut + 1) }
27}
28
29/**
30 * `~` expanded with `home`, `.` and `..` segments resolved, duplicate slashes collapsed. For a
31 * path that may not exist yet, where $.fs.stat cannot give realPath. Relative paths resolve
32 * against `cwd`.
33 */
34export function normalizePath(path: string, home: string, cwd: string): string {
35  let full = path
36  // Only a bare `~` or `~/` means home. `~bob` is a relative name in the shell's eyes too once
37  // the shell is not the one expanding it.
38  if (full === '~' || full.startsWith('~/')) full = home + full.slice(1)
39  if (!full.startsWith('/')) full = `${cwd}/${full}`
40  const out: string[] = []
41  for (const seg of full.split('/')) {
42    if (seg === '' || seg === '.') continue
43    if (seg === '..') out.pop()
44    else out.push(seg)
45  }
46  return `/${out.join('/')}`
47}
48
49/**
50 * True for `<home>/.claude/MEMORY.md` and for anything under `<home>/.claude/projects/<any>/memory/`
51 * (the folder itself included, MEMORY.md there too). A MEMORY.md anywhere else under `.claude` is
52 * some plugin's or skill's file and stays readable. `path` is absolute and normalised.
53 */
54export function isBuiltinMemoryPath(path: string, home: string): boolean {
55  // Match whole segments: a prefix test would pass `projects-old` and `memory-old`.
56  const claude = `${home.replace(/\/+$/, '')}/.claude/`
57  if (!path.startsWith(claude)) return false
58  const segs = path.slice(claude.length).split('/').filter(s => s !== '')
59  if (segs.length === 1 && segs[0] === 'MEMORY.md') return true
60  return segs[0] === 'projects' && segs.length >= 3 && segs[2] === 'memory'
61}
62
src/importer.ts 275 lines
1// /lr-import: Claude Code's memory files -> the engine's proposal queue, the way
2// lumberroom-hermes importer.py does it (HP/importer.py:62-115). Never the live store.
3
4import { raceSleep } from './race'
5
6export const EXTRACTOR = 'claude-code-builtin-import'
7/** Never auto-approves (ENG src/services/ingest.rs:97-106). */
8export const SPEAKER = 'main_model'
9export const IMPORT_TAG = 'claude-code-import'
10export const BATCH_SIZE = 100
11/** One ingest call may take this long before the import reports a timeout and moves on. */
12export const FETCH_TIMEOUT_MS = 15_000
13/** The close gets a shorter bound of its own, so a dead server costs at most one more wait. */
14export const CLOSE_TIMEOUT_MS = 5_000
15
16export interface MemoryFile {
17  name: string
18  description: string
19  /** user | feedback | project | reference, or another string as written. */
20  type: string
21  body: string
22}
23
24export interface ProposalFact {
25  content: string
26  namespace: string
27  tags: string[]
28  speaker: string
29  span_text: string
30  source: { file_path: string; entry_uuid: string; run_id: string }
31}
32
33export interface ImportReport {
34  runId: string | null
35  files: number
36  posted: number
37  proposalsNew: number
38  proposalsReinforced: number
39  /** Facts the store had already emitted: confirmed, no proposal made. */
40  confirmations: number
41  refused: number
42  blocked: number
43  /** Set when the run stopped: a missing token, a 403, a transport failure. */
44  error?: string
45}
46
47export interface HttpDeps {
48  fetch: (url: string, init: { method: string; headers: Record<string, string>; body?: string }) => Promise<{ status: number; ok: boolean; text: string }>
49  /** $.clock.sleep. $.http.fetch takes no timeout, so each call races this. */
50  sleep: (ms: number) => Promise<void>
51}
52
53/** The characters of a project folder name that survive Claude Code's truncation. */
54export const PROJECT_DIR_KEPT = 200
55
56/**
57 * Claude Code's folder name for a project: every character outside `[a-zA-Z0-9]` becomes `-`
58 * (2.1.287 runs `replace(/[^a-zA-Z0-9]/g, "-")`). The result can be longer than the folder: the
59 * binary cuts a name over PROJECT_DIR_KEPT characters and appends a hash this plugin cannot
60 * reproduce, so match folders with projectDirMatches.
61 */
62export function projectDirName(cwd: string): string {
63  return cwd.replace(/[^a-zA-Z0-9]/g, '-')
64}
65
66/**
67 * Whether the folder `entry` under ~/.claude/projects belongs to the project named `name`. A short
68 * name must match whole. A name over PROJECT_DIR_KEPT characters matches on its first
69 * PROJECT_DIR_KEPT, because the folder carries those and a hash after them.
70 */
71export function projectDirMatches(name: string, entry: string): boolean {
72  if (name.length <= PROJECT_DIR_KEPT) return entry === name
73  return entry.startsWith(name.slice(0, PROJECT_DIR_KEPT))
74}
75
76/**
77 * Null when `baseUrl` may carry the ingest token: https, or http to localhost or 127.0.0.1. The
78 * bearer travels in every request, so a plain-http remote host would send it in the clear.
79 */
80export function checkBaseUrl(baseUrl: string): string | null {
81  const m = /^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/.exec(baseUrl.trim())
82  const refusal = `the engine URL must be https (http is allowed for localhost and 127.0.0.1 only), so the ingest token is not sent in the clear. Got: ${baseUrl.trim().slice(0, 80) || '(empty)'}`
83  if (!m) return refusal
84  if ((m[1] as string).toLowerCase() === 'https') return null
85  if ((m[1] as string).toLowerCase() !== 'http') return refusal
86  // The host follows the last `@`, so userinfo naming localhost before it does not make the URL local.
87  const authority = m[2] as string
88  const host = authority.slice(authority.lastIndexOf('@') + 1).replace(/:\d*$/, '').toLowerCase()
89  return host === 'localhost' || host === '127.0.0.1' ? null : refusal
90}
91
92function unquote(value: string): string {
93  const v = value.trim()
94  if (v.length >= 2 && (v[0] === '"' || v[0] === "'") && v[v.length - 1] === v[0]) return v.slice(1, -1)
95  return v
96}
97
98/**
99 * A memory file (YAML-style frontmatter between `---` lines with name, description and either
100 * `type:` or `metadata:` -> `type:`) -> MemoryFile. Null for MEMORY.md, for a file with no
101 * frontmatter, or an empty body. A frontmatter-free fallback is not attempted.
102 */
103export function parseMemoryFile(fileName: string, text: string): MemoryFile | null {
104  const base = fileName.slice(fileName.lastIndexOf('/') + 1)
105  if (base === 'MEMORY.md') return null
106  const lines = text.replace(/\r\n?/g, '\n').replace(/^\uFEFF/, '').split('\n')
107  if (lines[0]?.trim() !== '---') return null
108  // The first `---` after the opener closes the block. A body may hold its own rule lines.
109  let close = -1
110  for (let i = 1; i < lines.length; i++) {
111    if ((lines[i] as string).trim() === '---') {
112      close = i
113      break
114    }
115  }
116  if (close < 0) return null
117
118  const top: Record<string, string> = {}
119  let metaType = ''
120  // Only `metadata:` is read as a nested block. A `type:` under any other key is not the type.
121  let block = ''
122  for (const line of lines.slice(1, close)) {
123    if (line.trim() === '') continue
124    const m = /^(\s*)([A-Za-z_][\w-]*):\s*(.*)$/.exec(line)
125    if (!m) continue
126    const indent = (m[1] as string).length
127    const key = m[2] as string
128    const value = unquote(m[3] as string)
129    if (indent === 0) {
130      block = value === '' ? key : ''
131      if (value !== '') top[key] = value
132    } else if (block === 'metadata' && key === 'type') {
133      metaType = value
134    }
135  }
136
137  const body = lines.slice(close + 1).join('\n').trim()
138  if (body === '') return null
139  const name = top.name ?? base.replace(/\.md$/, '')
140  return { name, description: top.description ?? '', type: metaType || top.type || '', body }
141}
142
143/** user and feedback -> user:me; project and reference -> project:<slug> (global with no slug); else global. */
144export function namespaceFor(type: string, slug: string | null): string {
145  const t = type.trim().toLowerCase()
146  if (t === 'user' || t === 'feedback') return 'user:me'
147  if (t === 'project' || t === 'reference') return slug ? `project:${slug}` : 'global'
148  return 'global'
149}
150
151/** Hex SHA-256 of the body through crypto.subtle. */
152export async function entryUuid(body: string): Promise<string> {
153  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(body))
154  return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('')
155}
156
157export async function toProposalFacts(files: ReadonlyArray<{ path: string; file: MemoryFile }>, slug: string | null, runId: string): Promise<ProposalFact[]> {
158  const facts: ProposalFact[] = []
159  for (const { path, file } of files) {
160    facts.push({
161      content: file.body,
162      namespace: namespaceFor(file.type, slug),
163      tags: [IMPORT_TAG],
164      speaker: SPEAKER,
165      span_text: file.body,
166      source: { file_path: path, entry_uuid: await entryUuid(file.body), run_id: runId },
167    })
168  }
169  return facts
170}
171
172const MISSING_GRANT =
173  'the credential lacks the mayIngest grant (HTTP 403). Run `lumberroom login --reregister` and pick the Full profile, or set the ingestToken option to a token with mayIngest.'
174
175function failure(status: number, text: string): string {
176  return status === 403 ? MISSING_GRANT : `lumberroom ingest call failed (HTTP ${status}): ${text.slice(0, 200)}`
177}
178
179function parseObject(text: string): Record<string, unknown> {
180  try {
181    const v: unknown = JSON.parse(text)
182    return typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : {}
183  } catch {
184    return {}
185  }
186}
187
188function count(obj: Record<string, unknown>, key: string): number {
189  const v = obj[key]
190  return typeof v === 'number' ? v : 0
191}
192
193function describeError(e: unknown): string {
194  return `lumberroom ingest call failed: ${e instanceof Error ? e.message : String(e)}`
195}
196
197/**
198 * POST {baseUrl}/admin/ingest/runs {extractor, scope:{tool:"claude-code"}} -> run_id; the facts
199 * in batches of BATCH_SIZE to /admin/ingest/proposals {extractor, facts}; then
200 * /admin/ingest/runs/{id}/close. Bearer `token`. A base URL that fails checkBaseUrl sends nothing.
201 * A 403 stops with an error naming mayIngest; any other non-2xx stops with the status and the first
202 * 200 characters of the body. Every call races FETCH_TIMEOUT_MS (the close, CLOSE_TIMEOUT_MS) and
203 * a timeout is reported like any failure. The run is closed even after a failed batch.
204 */
205export async function postProposals(deps: HttpDeps, baseUrl: string, token: string, build: (runId: string) => Promise<ProposalFact[]>, files: number): Promise<ImportReport> {
206  const root = baseUrl.replace(/\/+$/, '')
207  const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }
208  const report: ImportReport = { runId: null, files, posted: 0, proposalsNew: 0, proposalsReinforced: 0, confirmations: 0, refused: 0, blocked: 0 }
209  const unsafe = checkBaseUrl(baseUrl)
210  if (unsafe !== null) return { ...report, error: unsafe }
211
212  const send = async (path: string, body: unknown, bound: number) => {
213    const raced = await raceSleep(deps.fetch(`${root}${path}`, { method: 'POST', headers, body: JSON.stringify(body) }), deps.sleep, bound)
214    if (raced.timedOut) throw new ImportTimeout(`POST ${path} timed out after ${bound / 1000} s`)
215    return raced.value
216  }
217
218  let runId: string
219  try {
220    const res = await send('/admin/ingest/runs', { extractor: EXTRACTOR, scope: { tool: 'claude-code' } }, FETCH_TIMEOUT_MS)
221    if (!res.ok) return { ...report, error: failure(res.status, res.text) }
222    const id = parseObject(res.text).run_id
223    if (typeof id !== 'string' || id === '') return { ...report, error: 'lumberroom opened a run but returned no run_id.' }
224    runId = id
225  } catch (e) {
226    return { ...report, error: describeError(e) }
227  }
228  report.runId = runId
229
230  let seen = 0
231  try {
232    const facts = await build(runId)
233    seen = facts.length
234    for (let start = 0; start < facts.length; start += BATCH_SIZE) {
235      const batch = facts.slice(start, start + BATCH_SIZE)
236      const res = await send('/admin/ingest/proposals', { extractor: EXTRACTOR, facts: batch }, FETCH_TIMEOUT_MS)
237      if (!res.ok) {
238        report.error = failure(res.status, res.text)
239        break
240      }
241      const out = parseObject(res.text)
242      report.posted += batch.length
243      report.proposalsNew += count(out, 'proposals_new')
244      report.proposalsReinforced += count(out, 'proposals_reinforced')
245      report.confirmations += count(out, 'confirmations')
246      report.refused += count(out, 'refused')
247      report.blocked += count(out, 'blocked')
248    }
249  } catch (e) {
250    report.error = describeError(e)
251  }
252
253  // Close on every path: a run with no finished_at stays in flight and keeps its fence open.
254  try {
255    const res = await send(
256      `/admin/ingest/runs/${runId}/close`,
257      {
258        files_seen: files,
259        entries_seen: seen,
260        proposals_new: report.proposalsNew,
261        proposals_reinforced: report.proposalsReinforced,
262        confirmations: report.confirmations,
263      },
264      CLOSE_TIMEOUT_MS,
265    )
266    if (!res.ok && report.error === undefined) report.error = failure(res.status, res.text)
267  } catch (e) {
268    if (report.error === undefined) report.error = describeError(e)
269  }
270  return report
271}
272
273/** A call that outlived its bound; the message names the call. */
274class ImportTimeout extends Error {}
275
src/importplan.ts 208 lines
1// The plan behind `/lr-import all`: which namespace each memory folder's project and reference
2// memories should land in. A folder name such as `-home-u-work-my-repo` does not say where one path
3// segment ends, so the plan finds the path when it exists and asks the model when it does not. The
4// person confirms each folder before anything is posted.
5
6import { slugFromPath } from './project'
7import type { Exists } from './project'
8
9/** How the proposed namespace was chosen. `fallback` is global after an unusable model answer. */
10export type PlanHow = 'current' | 'path' | 'model' | 'fallback'
11export type PlanStatus = 'pending' | 'done' | 'skipped'
12
13/** One memory folder in the plan. Kept in `$.store` under PLAN_KEY, so it survives a reload. */
14export interface PlanEntry {
15  /** The folder's name under ~/.claude/projects. */
16  folder: string
17  /** Parseable memory files when the plan was built. */
18  files: number
19  /** The slug for project and reference memories; null is global. user and feedback never use it. */
20  slug: string | null
21  how: PlanHow
22  reason: string
23  status: PlanStatus
24}
25
26export const PLAN_KEY = 'lr-import:plan'
27
28/** The most `exists` calls one folder name may cost. A deep path with many dashes stays well under it. */
29export const DECODE_BUDGET = 300
30/** Memory files named in the model prompt. */
31export const PROMPT_FILES = 5
32const DESCRIPTION_MAX = 200
33
34/** Characters that Claude Code's folder naming turned into `-`, tried in this order when a dash was inside a segment. */
35const JOINERS = ['-', '_', '.', ' ']
36
37/**
38 * Reads a project folder name back into an existing absolute path, or null. The name came from
39 * `replace(/[^a-zA-Z0-9]/g, "-")`, so a dash can be a slash or a character inside a segment. The
40 * walk descends only into folders that exist, tries the shortest segment first, and stops after
41 * `budget` probes. A double dash is read as a hidden folder (`/.config`). Mixed joiners inside one
42 * segment (`my-app_v2`) are not tried: the model's guess covers what this does not find.
43 */
44export async function decodeProjectDir(name: string, exists: Exists, budget: number = DECODE_BUDGET): Promise<string | null> {
45  if (!name.startsWith('-')) return null
46  const tokens = name.slice(1).split('-')
47  let left = budget
48
49  const walk = async (dir: string, i: number): Promise<string | null> => {
50    if (i >= tokens.length) return dir
51    // An empty token is the dash a `.` left behind: the next segment starts with a dot.
52    const dotted = tokens[i] === ''
53    const start = dotted ? i + 1 : i
54    const lead = dotted ? '.' : ''
55    for (let end = start + 1; end <= tokens.length; end++) {
56      const parts = tokens.slice(start, end)
57      if (parts.some((p) => p === '')) break
58      for (const joiner of end - start === 1 ? ['-'] : JOINERS) {
59        if (left <= 0) return null
60        left -= 1
61        const candidate = `${dir}/${lead}${parts.join(joiner)}`
62        if (!(await exists(candidate))) continue
63        const found = await walk(candidate, end)
64        if (found !== null) return found
65      }
66    }
67    return null
68  }
69
70  return tokens.length === 0 ? null : walk('', 0)
71}
72
73const clip = (text: string, max: number): string => {
74  const flat = text.replace(/\s+/g, ' ').trim()
75  return flat.length > max ? `${flat.slice(0, max)}...` : flat
76}
77
78/**
79 * The one question put to the model for a folder whose path was not found. File names and
80 * descriptions are data; the answer is validated by parseNamespaceAnswer, so a hostile description
81 * can at worst pick a wrong slug, which the person sees in the table before anything is posted.
82 */
83export function buildNamespacePrompt(folder: string, files: ReadonlyArray<{ name: string; description: string }>): string {
84  const lines = files.slice(0, PROMPT_FILES).map((f) => `- ${clip(f.name, 80)}: ${clip(f.description, DESCRIPTION_MAX)}`)
85  return [
86    "Claude Code keeps a project's memory files in a folder named after the project's path, with every character outside a-z, A-Z and 0-9 turned into a dash.",
87    "Name the project this folder belongs to as a short slug: its own folder name, lowercase, using letters, digits, dots, underscores and single dashes. If the memories are not about one project, answer global.",
88    'Reply with the slug or global and nothing else.',
89    '',
90    `Folder: ${folder}`,
91    'Memory files:',
92    ...lines,
93  ].join('\n')
94}
95
96const asciiLower = (text: string): string => text.replace(/[A-Z]/g, (c) => c.toLowerCase())
97
98/**
99 * The model's reply -> `global`, a slug, or null when the reply is neither. A slug passes only when
100 * the engine's slug rule leaves it unchanged, so a sentence, a path or a name with a double dash
101 * never becomes a namespace. Surrounding quotes and backticks are dropped; case is folded.
102 */
103export function parseNamespaceAnswer(text: string): string | null {
104  let t = text.trim()
105  const quote = t[0]
106  if (t.length >= 2 && (quote === '`' || quote === '"' || quote === "'") && t[t.length - 1] === quote) t = t.slice(1, -1).trim()
107  const lower = asciiLower(t)
108  if (lower === 'global') return 'global'
109  const slug = slugFromPath(lower)
110  return slug !== '' && slug === lower ? slug : null
111}
112
113export type OverrideResult = { ok: true; slug: string | null } | { ok: false; error: string }
114
115/** The namespace a person types on `/lr-import confirm <n> <namespace>`: a slug, `project:<slug>` or `global`. */
116export function parseNamespaceOverride(input: string): OverrideResult {
117  const raw = input.trim().replace(/^project:/i, '')
118  const answer = parseNamespaceAnswer(raw)
119  if (answer === null) {
120    return { ok: false, error: `"${clip(input, 60)}" is not a namespace. Use global, a project slug such as my-repo, or project:my-repo.` }
121  }
122  return { ok: true, slug: answer === 'global' ? null : answer }
123}
124
125export type ImportCommand =
126  | { kind: 'current' }
127  | { kind: 'build' }
128  | { kind: 'plan' }
129  | { kind: 'confirm'; target: string; namespace?: string }
130  | { kind: 'skip'; target: string }
131  | { kind: 'usage' }
132
133export const IMPORT_USAGE =
134  'Usage: /lr-import | /lr-import all | /lr-import plan | /lr-import confirm <n|folder> [namespace] | /lr-import confirm all | /lr-import skip <n>. With no argument it reads this project; "all" lists every project folder and proposes a namespace for each, and nothing is posted until you confirm.'
135
136export function parseImportArgs(args: string): ImportCommand {
137  const tokens = args.trim().split(/\s+/).filter((t) => t !== '')
138  const verb = asciiLower(tokens[0] ?? '')
139  if (tokens.length === 0) return { kind: 'current' }
140  if (tokens.length === 1 && verb === 'all') return { kind: 'build' }
141  if (tokens.length === 1 && verb === 'plan') return { kind: 'plan' }
142  if (verb === 'skip' && tokens.length === 2) return { kind: 'skip', target: tokens[1] as string }
143  if (verb === 'confirm' && (tokens.length === 2 || tokens.length === 3)) {
144    const first = tokens[1] as string
145    const target = asciiLower(first) === 'all' ? 'all' : first
146    const namespace = tokens[2]
147    if (namespace === undefined) return { kind: 'confirm', target }
148    return target === 'all' ? { kind: 'usage' } : { kind: 'confirm', target, namespace }
149  }
150  return { kind: 'usage' }
151}
152
153const STATUSES: ReadonlySet<string> = new Set(['pending', 'done', 'skipped'])
154const HOWS: ReadonlySet<string> = new Set(['current', 'path', 'model', 'fallback'])
155
156/** The stored plan -> entries. A value that is not a plan answers [], so a stale or damaged store reads as no plan. */
157export function parsePlan(raw: unknown): PlanEntry[] {
158  if (!Array.isArray(raw)) return []
159  const out: PlanEntry[] = []
160  for (const item of raw) {
161    if (typeof item !== 'object' || item === null) return []
162    const e = item as Record<string, unknown>
163    if (
164      typeof e.folder !== 'string' ||
165      typeof e.files !== 'number' ||
166      !(e.slug === null || typeof e.slug === 'string') ||
167      typeof e.how !== 'string' ||
168      !HOWS.has(e.how) ||
169      typeof e.reason !== 'string' ||
170      typeof e.status !== 'string' ||
171      !STATUSES.has(e.status)
172    ) {
173      return []
174    }
175    out.push({ folder: e.folder, files: e.files, slug: e.slug, how: e.how as PlanHow, reason: e.reason, status: e.status as PlanStatus })
176  }
177  return out
178}
179
180export const namespaceLabel = (slug: string | null): string => (slug === null ? 'global' : `project:${slug}`)
181
182const HOW_LABEL: Record<PlanHow, string> = {
183  current: 'current project',
184  path: 'path found',
185  model: 'model guess',
186  fallback: 'model guess unusable',
187}
188
189/** The numbered table `all` and `plan` answer with. Numbers stay fixed as folders finish, so `skip 2` means the same row all session. */
190export function formatPlan(entries: readonly PlanEntry[]): string {
191  if (entries.length === 0) return 'lr-import: no memory folders with parseable files were found under ~/.claude/projects.'
192  const rows = [
193    ['#', 'folder', 'files', 'namespace', 'chosen by', 'status'],
194    ...entries.map((e, i) => [String(i + 1), e.folder, String(e.files), namespaceLabel(e.slug), HOW_LABEL[e.how], e.status]),
195  ]
196  const widths = rows[0]!.map((_, c) => Math.max(...rows.map((r) => (r[c] as string).length)))
197  const table = rows.map((r) => r.map((cell, c) => cell.padEnd(widths[c] as number)).join('  ').trimEnd())
198  return [
199    'lr-import plan. Nothing is posted until you confirm. The namespace applies to project and reference memories; user and feedback memories go to user:me.',
200    '',
201    ...table,
202    '',
203    ...entries.map((e, i) => `${i + 1}: ${e.reason}`),
204    '',
205    'Next: /lr-import confirm <n|folder> [namespace], /lr-import confirm all, /lr-import skip <n>, /lr-import plan.',
206  ].join('\n')
207}
208
src/mcp.ts 98 lines
1// Every engine call goes through callTool: a timeout the mod API does not give us, result parsing
2// that copes with the payload arriving as JSON text (spec 2.2), and one outcome type the hooks
3// branch on.
4
5/** The part of $.mcp.call's result this module reads. */
6export interface RawResult {
7  content: ReadonlyArray<{ type: string; text?: string }>
8  isError: boolean
9  structuredContent?: unknown
10}
11
12export interface McpDeps {
13  call: (server: string, tool: string, args: Record<string, unknown>) => Promise<RawResult>
14  /** $.clock.sleep: the one wait that counts against the hook budget. */
15  sleep: (ms: number) => Promise<void>
16  now: () => Promise<number>
17}
18
19export type CallOutcome =
20  | { kind: 'ok'; data: unknown; text: string; ms: number }
21  /** The engine answered with isError: a validation or conflict message in `text`. */
22  | { kind: 'tool_error'; text: string; ms: number }
23  | { kind: 'timeout'; ms: number }
24  /** The call threw: no server by that name, connection refused, transport failure. */
25  | { kind: 'unreachable'; error: string; ms: number }
26  /** The permission chain refused the call ("haven't granted it", "denied"). */
27  | { kind: 'denied'; error: string; ms: number }
28  /** The server is not (yet) connected, absent, or has its tools removed by the user's settings. */
29  | { kind: 'not_connected'; error: string; ms: number }
30
31/**
32 * structuredContent when present; else the first text block parsed as JSON; else `data` is the
33 * raw text (an engine that answers markdown). `text` is always the first text block, or "".
34 */
35export function parseResult(raw: RawResult): { isError: boolean; data: unknown; text: string } {
36  const block = raw.content.find((b) => b.type === 'text' && typeof b.text === 'string')
37  const text = block?.text ?? ''
38  if (raw.structuredContent !== undefined && raw.structuredContent !== null) {
39    return { isError: raw.isError, data: raw.structuredContent, text }
40  }
41  try {
42    return { isError: raw.isError, data: JSON.parse(text), text }
43  } catch {
44    return { isError: raw.isError, data: text, text }
45  }
46}
47
48/**
49 * Claude Code 2.1.287 throws this while MCP servers are still connecting, and for a server the
50 * user never configured or whose tools their settings disallow (a disallowed tool leaves the
51 * engine): `no tool "context_bootstrap" on a server named "lumberroom"; servers with tools: ...`.
52 */
53const NOT_CONNECTED = [/no (connected )?(mcp )?tool "[^"]+" on a server named/i, /no (mcp )?server (found )?(named|with name)/i]
54
55/** A thrown error from $.mcp.call: a permission refusal, a server that is not connected, or an outage. */
56export function classifyError(err: unknown): 'denied' | 'unreachable' | 'not_connected' {
57  const msg = err instanceof Error ? err.message : String(err ?? '')
58  // `$.mcp.call(server, tool) refused: <reason>` is Claude Code's wording for a permission refusal.
59  if (/permission|haven'?t granted|denied|\) refused: /i.test(msg)) return 'denied'
60  return NOT_CONNECTED.some((re) => re.test(msg)) ? 'not_connected' : 'unreachable'
61}
62
63/**
64 * Races deps.call against deps.sleep(timeoutMs). The losing call keeps running and its result,
65 * or its rejection, is swallowed. `ms` is measured with deps.now.
66 */
67export async function callTool(
68  deps: McpDeps,
69  server: string,
70  tool: string,
71  args: Record<string, unknown>,
72  timeoutMs: number,
73): Promise<CallOutcome> {
74  const start = await deps.now()
75  type Settled = { r: RawResult } | { e: unknown } | { timeout: true }
76  // Both arms resolve, never reject, so the losing call cannot raise an unhandled rejection later.
77  const call: Promise<Settled> = (async () => deps.call(server, tool, args))().then(
78    (r) => ({ r }),
79    (e: unknown) => ({ e }),
80  )
81  const timer: Promise<Settled> = deps.sleep(timeoutMs).then(() => ({ timeout: true as const }))
82  const won = await Promise.race([call, timer])
83  const ms = (await deps.now()) - start
84  if ('timeout' in won) return { kind: 'timeout', ms }
85  if ('e' in won) {
86    const error = won.e instanceof Error ? won.e.message : String(won.e)
87    return { kind: classifyError(won.e), error, ms }
88  }
89  const parsed = parseResult(won.r)
90  if (parsed.isError) return { kind: 'tool_error', text: parsed.text, ms }
91  return { kind: 'ok', data: parsed.data, text: parsed.text, ms }
92}
93
94/** True for the outcomes that count as an outage: the breaker records them. */
95export function isOutage(outcome: CallOutcome): boolean {
96  return outcome.kind === 'timeout' || outcome.kind === 'unreachable'
97}
98
src/own.ts 4 lines
1// The plugin's own name, as Claude Code reports it in next.origin.plugin.
2
3export const OWN_PLUGIN = 'lumberroom-memory'
4