Topic-based memory directory with agent-initiated writes and /memory slash command

Open 💬 9 comments Opened Apr 27, 2026 by LEON-gittech
💡 Likely answer: A maintainer (etraut-openai, contributor) responded on this thread — see the highlighted reply below.

What feature would you like to see?

A topic-based memory architecture that combines Claude Code's memdir layout with oh-my-codex-style agent-initiated memory writes, plus a user-facing /memory slash command.

Problem Statement

  1. Monolithic memory_summary.md does not scale: As memory grows, the single-file format becomes unwieldy for both the agent and users. It is hard to navigate, and loading the entire file into the system prompt wastes tokens.
  2. Agent is forbidden from writing memories: The current developer instructions explicitly tell the agent "Never update memories. You can only read them.". This means when a user says "remember that I prefer X", the agent cannot persist it directly. Users must either wait for the async Phase-1/2 consolidation pipeline or manually edit memory files.
  3. No CLI memory management: There is no slash command to list, edit, add, or clear memory topics without leaving the TUI.

Proposed Solution

1. Subfile Memory Directory (topics/*.md)

Introduce a topics/ subdirectory under ~/.codex/memories/ (and per-project memory roots) where each memory topic is an independent markdown file with YAML frontmatter:

~/.codex/memories/
  MEMORY.md              # Compact index / entrypoint
  memory_summary.md      # Legacy fallback
  topics/
    coding_style.md
    test_preferences.md
    api_patterns.md
    user_profile.md

Frontmatter schema:

---
name: Coding Style
description: Preferred patterns for this repo
type: project   # user | feedback | project | reference
keywords: [rust, clippy]
source: auto    # auto | user
updated_at: 2026-04-26T14:00:00Z
---

Benefits:

  • Relevance-based loading: scan frontmatter, inject only the top-N most relevant topics (plus MEMORY.md index) into the system prompt, reducing token usage.
  • Independent mutability: each topic can be read, written, or versioned independently.
  • Freshness awareness: memories older than a threshold get a <system-reminder> caveat about potential staleness.
2. /memory Slash Command

Add a /memory (or /memories) command to the TUI:

| Command | Action |
|---------|--------|
| /memory list | Display all topic names and descriptions |
| /memory edit <topic> | Open $EDITOR to edit an existing topic |
| /memory add <topic> | Create a new topic with a frontmatter template |
| /memory clear | Remove all .md files under topics/ |

This mirrors Claude Code's /memory edit UX and gives users explicit, immediate control.

3. Agent-Initiated Memory Writes (memory_write tool)

Expose a new built-in tool memory_write to the agent so it can persist knowledge in real time:

{
  "topic": "test_preferences",
  "content": "Always use pytest with the -x flag",
  "append": true,
  "type": "project",
  "keywords": ["pytest", "testing"]
}

Behavior:

  • If append: true, append content to the existing topic body.
  • If append: false (default), overwrite the topic file with new frontmatter + content.
  • The tool writes only inside the memory root (~/.codex/memories/topics/), similar to how the consolidation sub-agent is sandboxed to the memory root.

Why this matters:

  • Users can naturally say "remember that I prefer 2-space indentation" and the agent persists it immediately.
  • Before context compaction, the agent can proactively checkpoint critical state.
  • The existing Phase-1/2 pipeline continues to run in the background for automatic extraction, but explicit writes are instant and user-driven.
4. Scoped Memory (complementary to #18343)

The topic directory naturally supports scoping:

  • Global memories: ~/.codex/memories/topics/
  • Project memories: <project-memory-dir>/topics/
  • Hybrid loading: load project topics first, then global topics, with project taking precedence.

Backward Compatibility

  • If topics/ is empty, the prompt injection falls back to the existing memory_summary.md.
  • Phase-1/2 consolidation can continue writing the old format while gradually migrating to topic files.
  • No breaking changes to existing AGENTS.md or memory_summary.md behavior.

Related Issues

  • #8368 — Long-term Memory (closed; this proposal extends the POC described there with a concrete directory structure and agent write capability)
  • #18343 — Scoped memory management for Codex (complementary; topic directories make scoping trivial)
  • #6532 — Add small list of commands to memory for common tool
  • #3043 — Add memory functionality similar to Claude code

Are you interested in implementing this feature?

I have a working prototype of the memdir layout and /memory slash command in a local fork. I am happy to share a detailed design doc, help with implementation, or iterate on the approach if the team sees value in this direction.

View original on GitHub ↗

9 Comments

LEON-gittech · 2 months ago

This is essentially exactly what we've implemented in Open Codex CLI — a community-maintained Codex CLI fork that stays close to upstream while adding CLI improvements.

We shipped all three parts of your proposal:

1. Topic-based memory directory~/.codex/memories/topics/ with per-topic markdown files + YAML frontmatter (name, description, type, keywords, priority, source). A MEMORY.md index is auto-generated by Phase 2 consolidation. Topics are scored by relevance to the current query, top-8 injected into context.

2. Agent-initiated writes — Eight built-in tools: memory_read, memory_write, memory_add_note, memory_search, notepad_read, notepad_write_priority, notepad_write_working, notepad_prune. The agent can now directly persist information instead of being read-only. memory_write also supports merge: true to append without overwriting.

3. /memories slash command/memories list|add|edit|clear in the TUI.

Additionally:

  • Directive priority: priority: high in frontmatter auto-injects up to 3 high-priority directives into the agent's context
  • Bounded overlay: developer instructions capped at 3500 chars to prevent context bloat
  • Compaction survival protocol: agent checkpoints key state before context compression
  • File locking: directory-based locks with PID stale detection for concurrent write safety
  • Notepad section system: PRIORITY / WORKING MEMORY / MANUAL sections for session-scoped scratchpad

Install: npm install -g @leonw24/open-codex (coexists with official codex)

Source: https://github.com/LEON-gittech/codex

etraut-openai contributor · 2 months ago

@LEON-gittech, I think it's great that you're exploring new ideas in your Codex fork, but please don't post ads for your fork in our issue tracker. You're creating a bunch of noise for maintainers and for Codex users who come here to report bugs and request features.

If you have feature ideas that you'd like to see us add to Codex, you're welcome to post your ideas here. We'd love to learn from your explorations. Thanks!

LEON-gittech · 2 months ago

@etraut-openai Understood, and apologies for the noise. I've deleted the comments from the other issues.

jeemitsha · 2 months ago

The duplicate-detection bot flagged this against #20138 — following up here directly because I think the two proposals are complementary rather than overlapping.

Yours restructures the existing cross-session memories feature into a multi-file directory (topics/*.md) with relevance-loaded topics, a /memory slash command, and an agent-side memory_write tool. #20138 adds a separate session-scoped notes panel (desktop UI) with two regions — user-private and agent-shared, single-blob auto-injection, scoped to a single thread.

If both shipped, they'd cover different slots: yours = durable cross-session knowledge organized by topic; mine = ephemeral session-scoped intent that doesn't need to persist past the thread. There's a natural interaction too — notes content from a session could be promotable to a memory topic at session close (similar to what I floated in #12567).

Cross-linking for context.

szybnev · 2 months ago

+1 for a user-facing memory command and project/topic-based memory. The missing UX compared with Claude Code is the explicit “remember/save this” workflow: when I tell Codex to remember how a project-specific issue was fixed, I expect an immediate durable write, not only async extraction later.

A MEMORY.md / topic directory, scoped per project with a slash command to inspect and edit memory, would make memory auditable and reduce cross-project contamination.

chenyuan35 · 1 month ago

Great proposal. The topic-based layout + /memory command + agent-initiated writes cover the local memory problem well.

There's a complementary problem: cross-session/agent memory. Even with topic-based local memory, each agent session starts fresh — the same bug that Agent A spent 20 min debugging takes Agent B 20 min too. The memory_write and consolidation pipeline handle intra-session persistence, but there's no inter-session failure cache.

I built a lightweight shared memory layer for exactly this gap. The pattern is:

  1. Agent fails → POST /memory/failure (records the failed approach + error signature)
  2. Before fixing → POST /memory/search (finds if another agent already fixed it)
  3. After fixing → POST /memory/resolution (shares the fix across all agents)

For Codex, this could integrate as an optional tool similar to memory_write — something like a failure_check tool that queries the shared cache before spawning a long investigation. The local topics/ directory handles known preferences; the shared cache handles unknown failures that other agents have already encountered.

Repo: https://github.com/chenyuan35/aineedhelpfromotherai
(3 endpoints, no auth, agents identify by self-declared X-Agent-ID header)

Would love to see a failure_check tool or memory search --remote flag in the final design.

thodupunuriarun · 17 days ago

I think there is a related but distinct composer-level workflow that would build well on this proposal.

The memory/topic system described here focuses on how Codex stores, scopes, and retrieves memories. What I’m looking for is a user-facing prompt refinement flow where memory and knowledge-base context can be selected while drafting the prompt.

Suggested flow:

  1. User writes a rough prompt.
  2. User chooses one of two options:
  • Refine only: rewrite the prompt for clarity using the current draft and current session context only, without searching or attaching extra memories/context.
  • Refine + add context: search relevant memories, prior sessions, project notes, imported ChatGPT context, uploaded docs, or KB entries.
  1. For “Refine + add context”, Codex shows suggested context as removable chips/cards with source and reason.
  2. User can include, exclude, or edit those context items.
  3. User can optionally add a short refinement instruction, such as:
  • “make this shorter”
  • “turn this into an implementation task”
  • “add acceptance criteria”
  • “preserve technical details”
  • “do not expand scope”
  1. Codex rewrites the prompt using only the selected context.
  2. The final prompt preview clearly shows what will be sent or added to session context.

This differs from automatic memory injection because the user stays in control of which memories influence the next model request. It also differs from a generic prompt optimizer because the main value is selecting the right prior context, not just rewriting wording.

This would help with two common failure modes:

  • Codex misses important past work or project knowledge.
  • Codex silently uses irrelevant/global memory and contaminates the task.

Non-goals:

  • Do not auto-inject large memories silently.
  • Do not search everything by default.
  • Do not make this mandatory before every send.
  • Do not rewrite technical literals like paths, commands, flags, branch names, APIs, or quoted text inside attached context.
hegu-1 · 12 days ago

A topic-based memory directory is the right direction, but I would make the topic files carry lifecycle and authority, not only subject grouping.

For example, frontmatter could distinguish:

status: candidate | active | superseded | revoked | archived
authority: user-authored | agent-proposed | background-consolidated
scope: user | project | repo | session
source_refs: [...]
supersedes: [...]

That matters once agent-initiated writes are allowed. A memory topic should be writable without every write immediately becoming active guidance for future Codex runs.

A safer flow is:

agent note -> candidate topic entry -> /memory review/promote -> active topic memory

The /memory command can then become more than CRUD: it can show pending candidates, active guidance, superseded records, and why a memory changed state.

This is close to the pattern in my Personal AI OS / memory vault work: authored memory is the source of truth, while generated recall/index views are rebuildable.

Reference: https://github.com/hegu-1/personal-memory-vault-starter

ryanleoyan · 2 days ago

This issue covers the core mechanism I need. I would like to emphasize that the three policies should be independently configurable:

  • automatic retrieval of existing memories: on
  • automatic background generation: off
  • explicit user-authorized writes: on

When I tell Codex to “remember”, “update”, or “forget” something, it should make the durable change immediately and report what changed. This explicit-write path should continue to work when generate_memories = false.

I often use multiple chats to test conflicting viewpoints on the same problem, so repetition is not reliable evidence of preference. Automatic consolidation can confuse explored ideas with adopted decisions, and it also consumes rate limits/tokens for chats I did not intend to preserve.

I primarily need global memory across all Codex projects and chats, with optional project-scoped memory as a second scope. Users should be able to choose the scope, with clear precedence when global and project memories both apply.

The exact two-, three-, or four-layer storage design is less important to me than a supported, auditable manual-write contract. Full workflow context: https://github.com/openai/codex/discussions/12567#discussioncomment-17678485

Additional UX consideration

Per-chat opt-outs do not solve the default-policy problem. Many normal project chats are intentionally ephemeral, and requiring users to disable memory contribution for each one creates recurring friction. Temporary Chat is not equivalent because it also starts without using existing memory.

I want ordinary chats to continue reading relevant global or project memory while contributing nothing automatically. A durable write should happen only when I explicitly ask Codex to remember or update something.