openclaude-memory
CLAUDE.md2 starsChanged 5 days agoMITView on GitHub
Guidance for AI agents working in this repository. An opencode plugin (@openlines/openclaude-memory) giving agents persistent markdown memory across sessions. Plain ES JavaScript + Markdown — no TypeScript, no bundler, no lint, no formatter, zero runtime dependencies. Supports OpenCode V1 (floor 1.18.29) and V2 (2.2.7) from the same entrypoints. No build / typecheck / lint / format. No single-test runner: smoke-test.mjs runs the whole suite (node:assert, order-dependent). Three plugin files in .opencode/plugins/, all dual V1/V2: The two entry-point files stay separate:…
- Installs packages
The file
We split this CLAUDE.md into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 21
No build / typecheck / lint / format.
- Very specific: line 62
Removals are tombstoned in
.ocl-removed: before index references drop. - Very specific: line 94
Use experimental.session.compacting({}, makeCompactOutput()) for a forced full refresh, not an injection-state reset.
≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
Guidance for AI agents working in this repository.
What this is
An opencode plugin (@openlines/openclaude-memory) giving agents persistent markdown memory across sessions. Plain ES JavaScript + Markdown — no TypeScript, no bundler, no lint, no formatter, zero runtime dependencies. Supports OpenCode V1 (floor 1.18.29) and V2 (2.2.7) from the same entrypoints.
Commands
npm test # 126 sequential smoke checks + real-process shared writers
npm run test:host:v1 # real OpenCode 1.18.x server + local fake model (needs OPENCODE_BIN)
npm run test:host:v2 # real OpenCode 2.0.x server + local fake model
node tests/shared-store-test.mjs /absolute/path/to/openpi-memory/extensions/memory-core.mjs
for file in .opencode/plugins/*.mjs tests/*.mjs; do node --check "$file" || exit; done
# run INSIDE .opencode/ (not root) for @opencode-ai/plugin + @opencode/plugin type hints
cd .opencode && npm installNo build / typecheck / lint / format. No single-test runner: smoke-test.mjs runs the whole suite (node:assert, order-dependent).
Architecture
Three plugin files in .opencode/plugins/, all dual V1/V2:
ocl-memory.mjs— server plugin. Default-exports{ id, setup, server }: V2 callssetup(performs allregisterV2*registrations), V1 callsserver(input)→buildV1Hooks(input)(the legacy hook object). Published entryexports["."].ocl-memory-tui.mjs— TUI browser (ctrl+alt+m). Default-exports{ id, setup, tui }: V2 uses promise dialogs + akeymap.layer, V1 uses the callbacktui(api)interface. Published entryexports["./tui"].ocl-memory-shared.mjs— pure logic, NO plugin hooks; imported by both. Path/config resolution,withLock/acquireLock/releaseLock+LockContendedError, atomic writes, carry-over,parseIndexLine,isSafeFilename,stripJsonc,readMemoryRules.
The two entry-point files stay separate: the type system forbids a server plugin exporting tui and a TUI plugin exporting server (TuiPluginModule.server?: never / PluginModule.tui?: never). The shared module is exempt (exports no hooks).
Storage: index at ~/.config/opencode/memory/MEMORY.md (or ~/.agents/memory/ when shared_dir), config at ~/.config/opencode/memory.jsonc; resolved from XDG_CONFIG_HOME/os.homedir() at module load.
V2 directory-path loading (a real gotcha). When the repo is referenced as a plugin path ("plugins": ["/abs/path/openclaude-memory"]), V2 resolves the server entrypoint from <dir>/index.mjs and the CLI entrypoint from <dir>/tui.mjs — it does not read the directory's package.json exports. The published npm package loads through exports fine, but a bare directory reference silently loads nothing without those files. The root index.mjs / tui.mjs re-export shims (export { default } from './.opencode/plugins/ocl-memory.mjs' / .../ocl-memory-tui.mjs') close that gap; keep them one-line re-exports, never logic. They sit outside files so they are not published.
Module-level state (no reset API between tests): ocl-memory.mjs _cache (config/content/stamps) and _requestCount; ocl-memory-shared.mjs _carryOverChecked (set only after success) and _carryOverPending.
Key paths
| Path | Role |
.opencode/plugins/ocl-memory.mjs | Server plugin — hooks/tools/injection/consolidation (exports["."]) |
.opencode/plugins/ocl-memory-shared.mjs | Pure shared logic, no hooks |
.opencode/plugins/ocl-memory-tui.mjs | TUI browser (exports["./tui"]) |
index.mjs / tui.mjs | Root re-export shims for V2 directory-path plugin loading (server / CLI entrypoints) |
.opencode/command/memory.md | Static /memory fallback; dynamic registration overrides at runtime |
skills/memory/SKILL.md | Agent skill, on-demand; carries version: frontmatter |
package.json | Root manifest, published; files: ["skills/", ".opencode/"] |
tests/smoke-test.mjs / shared-store-test.mjs / host-test.mjs / host-test-v2.mjs | test suites |
docs/ | User-facing prose; behavior-coupled, update on behavior changes |
Invariants (each was a real bug — do not "simplify" away)
- No zod — flat args map required.
args={ topic: {type:'string'}, ... }per param. opencode'slegacyJsonSchema()fallback needs FLAT. Wrapping in{ type:'object', properties }makestype/required/propertiesbe read as param names → every argundefined(the 0.5.1 outage). V2 derives its object schema from the SAME flat map viatoObjectSchema(inverse companion — do not mix them up). - Tool arg guards return a string, never throw. Validate
topicnon-empty string,content/summaryas strings first. Empty content/summary allowed; fs failures may throw.repair_memorytakes no args. Native flat-schema calls must passpinandmodeexplicitly. pincoerced viapin === true || pin === 'true', never JS truthiness (string"false"is truthy). Applied inwrite_memory/pin_memory.findIndexEntryis exact-wins / ambiguous-refuses. Exact case-insensitive name-or-filename wins; a single substring match is returned; MULTIPLE substring matches →{ambiguous, names}and the caller refuses. Never regress to first-substring-wins.write_memorycollapses + capssummaryat 500 chars (MAX_SUMMARY_LENGTH) intocleanSummaryBEFORE first use, so frontmatter description, index line, and result message are identical.isSafeFilename()guards filenames read back fromMEMORY.md.toSlug()only sanitizes NEW write filenames; it is never a validator on read. Guards at every read-time path boundary (write_memory/remove_memory/maintainIndex/mergeLocalIntoSharedDir/TUIparseIndex+read/mutate). Since 0.6.5 also rejects a leading.and[]().write_memoryguards its own generated slug too (else punctuation-only topic →.md, then a silent orphan).write_memoryslug-collision fallback. New topic whose slug hits a file owned by a DIFFERENT topic → bump-2,-3… before touching (pre-fix cross-topic corruption). Same-name rewrite reuses the file.- Removals are tombstoned in
.ocl-removedbefore index references drop; topic file preserved. Re-store reclaims only on matching frontmatter identity; unrelated slugs get a numeric suffix. Clear tombstone only after successful publication. Every mutation stays insidewithLock. stripJsoncis string-literal-aware. A naive//strip truncates URL values; since 0.6.5 also strips/* … */block comments.parseRules/readMemoryRulesconsole.errorbefore default-fallback. Do not revert to a regex one-liner.- Index lines are one physical record —
sanitizeIndexField. A topic is one- [name](file.md) date -- summaryline; sanitize collapses\r\nand strips[]().write_memorysanitizestopic→cleanTopicONCE at the top ofexecute()so slug/match/frontmatter/index line all agree. Topic-file CONTENT is NOT sanitized (newlines are normal markdown). - 50 KB injection cap is enforced line-by-line.
readMemoryIndex()keeps only whole lines fittingMAX_BYTES(neverlines.slice(0, maxLines)after a byte overflow). readMemoryIndex()never writes on the read path. Absent → returnsINITIAL_MEMORYin-memory only (else an unlocked write undershared_dircould clobber a co-tenant's fresh index).MEMORY.mdfirst materializes on a locked write.write_memorytimestamp bump is frontmatter-scoped. Both modes extract the^---\n...\n---\nblock and regex only inside it (else a body line beginninglast_updated:gets rewritten and frontmatter never stamped).- Two
package.jsonfiles. Root is published;.opencode/package.jsonis gitignored (withnode_modules,bun.lock) and holds only type hints (@opencode-ai/pluginV1 +@opencode/pluginV2).
shared_dir, locking, cache
memory.jsoncis the single local config source. Publish a missing config exclusively before renaming legacymemory/RULES.jsoncto.bak; preserve a racing creator + existing backups; failed publication keeps the legacy original.getMemoryDir(config)/getMemoryIndex(config)resolve the active directory; capture before the mutation lock. Stamp checks detect config/path changes before cache reuse; TUI resolves on open and/memoryrefreshes before executing. No restart for ordinary edits.- Carry-over is merge-aware + double-guarded.
maybeCarryOverToSharedDir()runs once ever per install:_carryOverCheckedshort-circuits in-process only after full success;CARRY_OVER_SENTINEL(.shared-dir-migrated) across restarts. MERGES (never skips when sharedMEMORY.mdexists): copy originals under original name; identical bytes → skip; different →-oclmsuffix. Respects both removal lists (tombstones); an identical pre-existing shared file still gets its missing index line appended so it stays discoverable. One-way copy, no re-run on toggle.parseIndexLine/INITIAL_MEMORYlive in the shared module. withLockis the single mutation entry point, fail-closed. Local waits ~500 ms; shared 2 s + 1 s delay + another 2 s, thenLockContendedError/BUSY_MESSAGE. Capture each acquisition token synchronously before awaiting; release verifies it.EPERMmeans alive; stale reclaim checks PID + inode/mtime; unknown payloads use a 60 s threshold. No atomic compare-and-unlink — not a strict lease guarantee.- Repair is additive-only and idempotent. Scan safe regular
.mdfiles missing from the index/removal list; append[stale?]entries dated from frontmatter; never delete/reorder. Report pre-existing vs added separately. Drift notes above five non-tombstoned missing topics; never auto-repair a co-tenant's possible in-flight write. - Recap topic is
ocl-last-session-recap.md("OCL Last Session Recap"), NOTlast-session-recap(openpi reserves that slug and strips it every session). Set in bothCONSOLIDATION_PROMPTandbuildCompactConsolidationPrompt. Do not rename to a parenthetical. - Topic frontmatter uses quoted names/descriptions (
JSON.stringify). Both modes refresh name/description/last_updated, preservingcreated+ unknown fields. Migration compares whole-file bytes. .invalidateis computed from the active directory and never consumed. TUI writes it atomically; each server cache stamps independently; notification failure must report the index already committed.
Injection & consolidation
- Always attach memory/rules. V1 injects via
experimental.chat.system.transform; V2 viactx.session.hook("context")pushing{type:'text',text}SystemParts. Fresh output every request (other sessions, internal calls) — no first-turn gate._requestCount/inject_every_n_turnscontrol forced disk refresh, not injection. - Per-file durability: no-follow reads verify regular descriptors; UI/injection reads bounded before allocation; atomic writes (exclusive temp, flush, cleanup); ordinary publish failures attempt rollback (report paths if rollback fails). Directory entries not fsynced — recoverable drift on abrupt termination.
- Reads never block on special files: nonblocking open before verifying regular descriptor. Store reads reject final-component symlinks; trusted config symlinks supported (target stamps in cache).
- Compaction forces
getCache(true)intooutput.context(V1experimental.session.compacting; V2ctx.session.hook("compaction")). consolidate_on_compact: V1 runs viaexperimental.compaction.autocontinue(capturesclientfrominput.client; seeds fromfetchLatestCompactionSummary→ latest assistant withinfo.summary===true,res.data||res; fallback full-scanCONSOLIDATION_PROMPT). Queues withnoReply: true, retains agent/model/variant; SDK errors retain native continuation. V2 has no continuation hook — asession.compactedevent loop enqueues an additional queued prompt; it cannot replace the running loop (documented limitation).autocontinuenever fires on manual/compact(upstream gates oninput.auto; manual isauto:false). Consolidation only on automatic compaction; manual consolidation is/memory consolidate.
Testing quirks
XDG_CONFIG_HOME(→ temp) andOCL_SHARED_MEMORY_HOMEmust be set at the TOP ofsmoke-test.mjsBEFORE the pluginimports —MEMORY_DIR/SHARED_MEMORY_DIRare fixed at module load. Both plugin files import the same cached shared module (one shared state instance).- State (
_cache,_requestCount,_carryOverChecked,_carryOverPending) is process-global with no reset API; test order is load-bearing. - Use
experimental.session.compacting({}, makeCompactOutput())for a forced full refresh, not an injection-state reset. - Cross-process lock tests wait for child IPC readiness (no fixed sleeps); held-lock check ≥150 ms and below the 2 s window.
Releasing
- Version bump touches 3 files with NO single source of truth:
package.json(version),skills/memory/SKILL.md(version:), a dated## [X.Y.Z]entry inCHANGELOG.md. Publish CI checks consistency. Current worktree version is 0.7.0. - CI publishes on a
v*tag;publish.ymlscrapes the release body fromCHANGELOG.mdby matching the## [<version>]heading, so that heading MUST equal the tag version (minusv).NODE_AUTH_TOKEN: ''is intentional (OIDC Trusted Publishing) — never put a real token there. - CI gates:
test.ymlrunsnode --check+npm test+ the real-V2 host test (test:host:v2, pinned@opencode/cli@2.2.7) on every push/PR and is reusable viaworkflow_call.publish.yml'spublishjobneedsthat Test workflow (so the full suite, including real-V2 integration, must pass first) before running the 3-way version-consistency check and publishing. Still runnpm test+node --checklocally before tagging.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

