pm-rlm
pm is context management for agents. Recursive Language Models keep a large context in an environment, inspect it through tools, delegate subgoals, and compose the results. pm-rlm makes a pm workspace that environment and its durable execution ledger. Each recursive call is a visible Task with its parent, model, digest, usage, claim and result evidence.
Model weights are separate from the package. The deterministic model exists only in the test suite.
The host requires Node 22.18 or newer. npm/npx and Bun/bunx packed consumers are verified by npm run test:install: each creates a real SDK run and queries its closed call through the installed pm rlm tree --json command. pm package install performs extension discovery; npm or Bun dependency installation alone is not the activation step.
| Command |
Example |
Result |
run |
pm rlm run "Count open Issues" --scope '{"type":"Issue"}' --max-depth 3 --max-calls 32 --budget-tokens 300000 |
Answer, run id, calls, reservations and reported-or-estimated model usage |
tree |
pm rlm tree run-id |
One compact row per call: parent, depth, status, tokens and result excerpt |
tree --full |
pm rlm tree run-id --full --json |
Entire ledger checkpoint, including snapshot and recorded outputs |
resume |
pm rlm resume run-id |
Recovered answer; completed digests and recorded model responses are reused |
replay |
pm rlm replay run-id --json |
Re-executed recorded actions and verified byte-identical answer, without inference or writes |
Install and release approval
In an initialized pm project, choose npm or Bun to install and activate the extension from the registry.
npm install pm-rlm @unbrained/pm-cli
npx --no-install pm package install ./node_modules/pm-rlm
bun add pm-rlm @unbrained/pm-cli
bunx --bun --no-install pm package install ./node_modules/pm-rlm
If the pm host is already installed, it can install and activate the extension directly.
pm package install npm:pm-rlm
pm rlm --help
Local archive
To evaluate a source commit, start in the checkout and install the packed archive in a fresh consumer directory.
(
npm ci || exit 1
tarball=$(npm pack --silent) && test -n "$tarball" && test -f "$tarball" || exit 1
packed_version=$(node -p 'require("./package.json").version') || exit 1
archive="$(pwd)/$tarball"
consumer=$(mktemp -d -t pm-rlm.XXXXXX) && test -n "$consumer" && cd "$consumer" || exit 1
npm install "$archive" @unbrained/pm-cli || exit 1
npx --no-install pm init rlm --defaults --agent-guidance skip || exit 1
npx --no-install pm package install ./node_modules/pm-rlm || exit 1
npx --no-install pm rlm --help || exit 1
installed_version=$(node -p 'require("./node_modules/pm-rlm/package.json").version') || exit 1
test "$installed_version" = "$packed_version" || {
printf 'Expected version %s, installed %s.\n' "$packed_version" "$installed_version" >&2
exit 1
}
)
Automated npm publication requires the maintainer to configure a GitHub Actions
trusted publisher for this repository
with workflow filename release.yml and select npm publish under Allowed actions.
Trusted publishers created after September 3, 2026 default to
npm stage publish only. PM_RELEASE_APPROVED=true gates daily and manual
releases on main. The trusted publisher authorizes the workflow to publish to npm through OIDC. The workflow publishes with provenance.
The package exports its SDK through main and types and registers commands
with pm. It has no standalone bin: use npx pm or bunx --bun pm through
the installed host. npm/Bun dependency installation alone does not activate it.
Ledger storage
New root checkpoints contain a v2 manifest: run id, the single reserved_tokens coordinate, and SHA-256 references to snapshot and transcript blobs. Durable JSON payloads live in rlm-blobs/ inside the tracker. Snapshots deduplicate across runs with identical scoped source bytes. Prompts, responses, observations, slices and call records are immutable separate payloads; unchanged strings are reused across checkpoint revisions. Every referenced blob is hashed as raw bytes before strict UTF-8 decoding and use. Missing, corrupt or invalid payloads refuse with incomplete.
Back up or transport the whole tracker, including rlm-blobs/. Copying only item rows and history is insufficient for v2 runs. Earlier package builds that understand only v1 cannot read new v2 roots; keep a complete tracker backup for rollback. Full tree, resume and replay hydrate the same public RlmState shape, preserving independent JSON values when different steps share a payload digest. Existing v1 checkpoints read without writes; the next explicit save migrates the active checkpoint, leaving append-only history unchanged. Parser and aggregate versions keep their original semantics.
For explicit garbage collection:
import { RlmLedger } from 'pm-rlm';
const collected = await new RlmLedger('.agents/pm').gc();
console.log(collected.removed, collected.bytes);
Collection shares a process-owned storage lease with publication. Verified historical reachability pins committed versions, allowing hydration and replay without read-side lease writes. It verifies current and historical references before sweeping orphan blobs and abandoned blob temporary files. Verified history retains old payloads, so ordinary GC does not erase audit evidence or reclaim reachable historical transcripts. Invalid history, unknown storage versions or missing referenced data aborts collection before deletion. No background collector runs. Writers publish complete blobs before the atomic SDK manifest update; an interrupted prepublication write leaves the preceding coordinate intact. SIGKILL recovery does not establish power-loss durability. Older supported SDKs retain killed item writers' TTL locks; resume must follow the tracker's existing stale-lock recovery policy. Crash fixtures use a one-second item-lock TTL with automatic stale recovery, without forcing locks.
SDK versions before 2026.10.31 can also leave a fresh commit-fence cleanup gate when a writer is killed inside its lock fence (unbraind/pm-cli#1609); that gate blocks dead-owner lock takeover for about ten seconds while the default item-lock wait is three seconds. Every ledger mutation therefore treats a lock conflict whose recorded owner process is provably dead as retryable, with bounded backoff and jitter inside a fifteen-second budget configurable as RlmLedgerOptions.deadOwnerRetryMs; lock conflicts with live owners and every other error still fail fast with the SDK's typed error. Every attempt checks a monotonic deadline, and each sleep is capped by the SDK hint, two-second backoff ceiling and remaining budget. Zero budget refuses with a typed lock_conflict before starting any mutation. An SDK call already in progress can finish after the deadline; the budget prevents starting further calls and does not cancel an in-flight write. This bounded retry preserves compatibility with supported older SDKs; pm-cli 2026.10.31 includes the upstream recovery fix.
See the storage measurements for the public eval corpora at 10, 100 and 500 runs, methodology and remaining scale limits.
Without git
Environment reads, recursive run, tree, resume, replay, evidence-directed repair and its recovery, executable answer checks, lazy storage migration and blob GC work in a plain-directory tracker without a Git executable. They need no Git repository. The eval command works without Git; preparing verified public source revisions needs Git and GitHub; repository changelog and release tooling also use Git.
Environment and execution
Every command uses the host's TOON renderer by default and supports --json. --model overrides the saved default on run. Scope is a JSON object supporting exact type, status, parent, tag and ids predicates plus a case-insensitive text substring over the complete item. Predicates intersect; omitted predicates match all. Ledger call and generated question items are excluded from source context.
CLI numeric operands use unsigned decimal digits and must fit the settings bounds; signs, exponent/hex forms, fractions, surrounding whitespace and unsafe integers are input errors. All string operands must contain non-whitespace text. Nonblank questions, model names and scope JSON are preserved verbatim; JSON may contain its normal surrounding whitespace.
The exported environment works independently of the built-in loop:
import { createRlmContext, RlmError } from 'pm-rlm';
const ctx = await createRlmContext({
workspace: '.agents/pm',
scope: { type: 'Issue', status: 'open' },
budget: 50000,
});
try {
const candidates = ctx.search('coverage', 10);
for (const item of candidates.data) {
const evidence = ctx.get(item.id, ['title', 'acceptance_criteria', 'comments']);
// Feed selected typed evidence to your own recursive loop.
console.log(evidence.data, evidence.estimated_tokens);
}
} catch (error) {
if (!(error instanceof RlmError)) throw error;
console.log(error.code); // e.g. budget, scope, incomplete
}
| Environment API |
Data and budget behavior |
list(filter = {}) |
Every matching full item from a certified snapshot |
search(query, limit) |
Explicitly bounded text matches from that complete snapshot |
get(id, fields = []) |
Selected fields; empty selection returns the full item |
history(id, {start, end}) |
Verified append-only history in a half-open version range, capped at the snapshot timestamp |
peek(id, field, start, end) |
Half-open UTF-16 substring of text or serialized structured data |
partition(filter, maxTokens) |
Lossless JSON fragments packed into slices; each slice fits its advertised estimate |
remaining |
Remaining budget for this environment instance |
Each read returns {data, estimated_tokens, complete_list}. The certificate describes the complete source corpus before scope and selection. SDK read and history parsing failures become typed incomplete refusals. Incomplete scans fail closed; budget refusal never silently truncates a complete read. Returned objects are copies. Linked file/doc metadata and comments are available through get; arbitrary linked file contents are not opened. That keeps reads inside the selected tracker.
Token estimates use one token per UTF-8 byte, minimum one, as a conservative and reproducible accounting unit, not a model tokenizer. The estimate covers the operation's data; its receipt is control metadata. A slice's estimate covers the serialized fragments including ids and offsets, excluding the estimate field. A complete partition response must also fit the environment's remaining budget. Oversized items split into escaped JSON fragments with exact UTF-16 offsets; concatenate fragments in order to recover the original item. A budget too small for a fragment header refuses.
The built-in model loop is accessible through runRlm(question, options), resumeRlm(workspace, run), replayRlm(workspace, run) and treeRlm(workspace, run, full). RlmLedger, RlmEngine, reserveStep, promptDigest, estimateTokens, typed contracts and errors are also exported for embedded tooling. Pass question_item to link an existing question; otherwise a generated question Task is created. RlmEngine.spawn(parentId, subgoal, slice) provides digest-based child reuse for custom orchestrators; custom orchestration must hold ledger.lease(run) for its entire read/modify/write sequence and await calls sequentially. snapshot() returns an independent state copy. The built-in runner acquires that lease automatically and reloads the checkpoint after acquisition.
Run and tree outputs include token_usage: reported_or_estimated: input/output counters come from the provider when supplied and conservative byte estimates otherwise. Reserved totals are accounting charges that also include pending worst-case reservations and delivered-read byte estimates. Call/depth counters are exact ledger values; settings numbers are configured limits. These values do not establish provider billing.
Implement RlmModel to supply a third-party model. Its complete({prompt, max_output_tokens, context_tokens}) method returns {text, tokens_in, tokens_out} and its stable name is recorded in the ledger. The JSON action protocol supports list, search, get, history, peek, partition, spawn, and finish. For example:
{"action":"search","query":"coverage","limit":5}
{"action":"finish","answer":"3"}
The model receives the protocol, subgoal, selected slice and recorded observations. partition returns compact {partition_step,index,estimated_tokens} references in the model protocol. spawn takes {subgoal,slice:{partition_step:0,index:0}}, where the step is the zero-based transcript index of a successful partition. The engine resolves the reference to lossless authorized fragments without requiring the parent to copy their text. Explicit fragment slices are also accepted. The exported environment API continues to return full slices. Child tools can access only whole items completely represented by their slice; partial JSON fragments remain visible in the child prompt and can be subdivided for descendants. Invalid JSON, unknown actions, invalid ranges and denied reads become recorded refusals and consume a reserved model step. Depth, call count, total estimated tokens and per-prompt context all bound execution. There is no unrestricted shell, JavaScript execution, filesystem tool or hidden agent delegation.
Configure the model with the audited SDK settings API (host SDK 2026.11.4 or later):
import { writeRlmSettings } from 'pm-rlm';
await writeRlmSettings('.agents/pm', {
adapter: 'ollama',
endpoint: 'http://localhost:11434',
model: 'gemma4:e4b',
max_depth: 3,
max_calls: 32,
budget_tokens: 300000,
context_tokens: 32768,
output_tokens: 512,
timeout_ms: 120000,
}, 'my-agent');