This document maps the codex-mem v1 specification to a Go-oriented implementation plan.
Audience:
- maintainers
- contributors designing or reviewing Go implementation structure
Use this when:
- deciding how the Go implementation should be structured
- reviewing package boundaries, service responsibilities, and delivery order
- checking whether a code change matches the intended architecture
Do not use this for:
- first-time user onboarding
- runtime troubleshooting
- registering a packaged binary with a client
It is not the normative product spec. Instead, it describes how a Go implementation can realize the required behavior in a maintainable and testable way.
Normative references:
The Go implementation should:
- satisfy the
codex-memv1 baseline - remain local-first
- work well as a single-binary local service
- support SQLite-backed durable memory
- expose the required MCP tool surface
- preserve room for future watcher/import extensions without forcing them into v1
Recommended shape:
- CLI entrypoint
- configuration loader
- storage layer
- domain services
- MCP adapter layer
- optional background jobs
Recommended runtime modes:
servefor the local MCP servermigratefor schema initialization and upgradesdoctorfor local diagnosticsagents installor equivalent for AGENTS template installation
Recommended configuration convention:
- load project-level configuration from the repository
configs/directory - use
viperas the Go configuration library for file loading and environment overrides - keep precedence as
defaults < config file < environment variables
Suggested layout:
cmd/
codex-mem/
main.go
internal/
app/
config/
db/
domain/
scope/
session/
memory/
handoff/
retrieval/
agents/
imports/
mcp/
observability/
privacy/
identity/
migrations/
templates/
docs/
cmd/keeps the binary entrypoint thininternal/keeps application logic encapsulateddomain/separates core behavior from transport and storagemigrations/makes schema evolution explicittemplates/already fits AGENTS template storage
Purpose:
- application wiring
- dependency construction
- lifecycle management
Responsibilities:
- load config
- open database
- initialize services
- register MCP tools
- start server mode
- expose reusable app-level workflows such as import ingestion for future in-process integrations
Purpose:
- configuration loading and validation
Responsibilities:
- product defaults
- config file parsing
- env var overrides
- runtime path resolution
- policy precedence helpers
Recommended implementation details:
- treat
configs/as the default home for repository-local configuration - let
viperload the config file and bind environment variables into the same config model - keep file parsing format-flexible through
viper, even if the first checked-in example uses JSON
Suggested outputs:
- storage path
- log level
- default bootstrap limits
- privacy settings
- AGENTS install defaults
Purpose:
- database connection and migration handling
Responsibilities:
- open SQLite connection
- configure pragmas
- run migrations
- expose transaction helpers
Recommended SQLite concerns:
- enable foreign keys
- configure WAL mode if appropriate
- use busy timeout
- support FTS5
Purpose:
- scope resolution and scope consistency validation
Responsibilities:
- resolve
system/project/workspace - apply identity evidence priority
- validate scope-chain consistency
- create missing scope records when policy allows
Purpose:
- session lifecycle management
Responsibilities:
- create sessions
- update session status
- enforce no revival of ended sessions
- query recent sessions when needed
Purpose:
- memory note write and read behavior
Responsibilities:
- validate note input
- normalize tags and file paths
- dedupe notes conservatively
- store and retrieve notes
Purpose:
- handoff write and continuity behavior
Responsibilities:
- validate handoff payloads
- enforce
next_steps - detect same-task open handoff conflicts
- store and retrieve handoffs
Purpose:
- retrieval orchestration and ranking
Responsibilities:
- bootstrap retrieval sequence
- search retrieval
- recent retrieval
- related-project expansion
- ranking and dedupe in result sets
- startup brief synthesis
Purpose:
- AGENTS template installation and file update policy
Responsibilities:
- choose target paths
- load templates
- fill placeholders
- apply create/append/overwrite modes
- report changed and skipped files
Purpose:
- provenance and dedupe support for imported artifacts
Responsibilities:
- store import records
- track external ids and payload hashes
- suppress duplicate imports
This package may be implemented lightly in v1 and expanded later.
Purpose:
- transport adapter for MCP tool registration and request handling
Responsibilities:
- define MCP tool handlers
- convert MCP input to domain requests
- map domain results to MCP responses
- preserve warning and error taxonomy
Purpose:
- logging, warnings, audit helpers, and optional debug traces
Responsibilities:
- structured logs
- provenance helpers
- optional retrieval trace assembly
Purpose:
- privacy and exclusion policy enforcement
Responsibilities:
- do-not-store checks
- exclusion markers
- optional redaction helpers
- search filtering for excluded records
Purpose:
- canonical identity normalization and repository fingerprint logic
Responsibilities:
- normalize repo remotes
- compare identity evidence
- detect rename/move continuity
- warn on conflicts
Recommended persistent tables:
systemsprojectsworkspacessessionsmemory_itemshandoffsproject_relationsimports
Recommended FTS:
memory_items_fts- optional later
handoffs_fts
Recommended split:
- repository interfaces in domain packages
- concrete SQLite repositories in
internal/dbor ainternal/store/sqlitepackage
Suggested style:
- domain services depend on interfaces
- SQLite implementation satisfies those interfaces
This keeps the core behavior portable and testable.
Recommended approach:
- define canonical request/response and entity structs close to the domain layer
- avoid transport-specific structs leaking into the core services
Suggested type families:
ScopeSessionMemoryNoteHandoffStartupBriefSearchResult- tool-specific request/response structs
Recommended enum handling:
- use typed string aliases for statuses and kinds
- validate at boundaries
Examples:
type SessionStatus stringtype NoteType stringtype HandoffStatus string
Recommended pattern:
- one service per major behavior area
- orchestration service for bootstrap and retrieval
Suggested services:
ScopeServiceSessionServiceMemoryServiceHandoffServiceRetrievalServiceAgentsServiceImportService
- keeps business rules centralized
- makes MCP handlers thin
- makes testing easier
- preserves portability if storage changes later
Recommended Go handler mapping:
memory_bootstrap_session->RetrievalService.BootstrapSessionmemory_resolve_scope->ScopeService.Resolvememory_start_session->SessionService.Startmemory_save_note->MemoryService.SaveNotememory_save_handoff->HandoffService.SaveHandoffmemory_search->RetrievalService.Searchmemory_get_recent->RetrievalService.GetRecentmemory_get_note->RetrievalService.GetRecordByIDmemory_install_agents->AgentsService.Install
Recommended internal sequence:
- MCP handler parses request
ScopeService.Resolveresolves or creates scopeSessionService.Startcreates new sessionRetrievalService.BootstrapSession:- get latest open workspace handoff
- fallback to project handoff
- get workspace notes
- fallback to project notes
- optionally fetch related-project notes
- synthesize startup brief
- MCP handler returns canonical response
Recommended implementation detail:
- keep bootstrap orchestration inside one service call so transaction and warning flow stay coherent
Recommended implementation split:
- SQL/FTS retrieves candidate rows
- Go ranking logic applies scope/state/importance/recency weighting
- Go layer applies dedupe and final result shaping
Why:
- SQL is efficient at candidate filtering
- Go is better for policy-heavy ranking logic that may evolve
Recommended ranking pipeline:
- candidate fetch by scope and text filter
- state filtering
- related-project policy gate
- score computation
- dedupe collapse
- result shaping with provenance labels
Recommended enforcement points:
- validate explicit private or do-not-store input
- reject or redact sensitive content before persistence
- ensure excluded records do not enter FTS
- exclude records not meant to be searchable
- label inferred or imported records clearly
Recommended design:
- centralize this in
privacyhelpers used by write and search services
Recommended implementation shape:
- read template files from
templates/ - resolve target paths
- inspect existing file state
- apply selected mode:
- create if missing
- append block
- overwrite template
- return structured result
Recommended file handling behavior:
- default to non-destructive
- preserve unresolved placeholders
- do not attempt complex markdown merging in v1
Recommended baseline:
- structured logger
- request-scoped warning collection
- audit fields for writes
- optional debug traces for retrieval
Recommended logging fields:
- tool name
- session id
- project id
- workspace id
- result counts
- warning codes
- error codes
Recommended caution:
- do not log private payload contents
Recommended test layers:
Focus:
- scope resolution logic
- state validation
- privacy filtering
- ranking and dedupe helpers
Focus:
- bootstrap flow
- note save flow
- handoff save flow
- AGENTS install modes
Focus:
- SQLite persistence
- FTS search behavior
- migration correctness
- foreign key and scope consistency behavior
Focus:
- scenarios from conformance-matrix.md
Recommended approach:
- keep language-neutral scenario names
- implement them as Go test cases
Recommended order:
- config + db initialization
- scope + identity services
- session service
- note and handoff persistence
- bootstrap flow
- search and recent retrieval
- privacy enforcement
- AGENTS installer
- conformance test coverage
This order mirrors the language-neutral backlog while fitting Go service construction well.
- database opens and migrates
- scope can be resolved
- sessions can be created
- notes and handoffs can be stored
- bootstrap works
- startup brief is produced
- later session can recover prior continuity
- search works
- recent retrieval works
- project isolation is enforced
- privacy exclusions are enforced
- AGENTS installation works
- warnings and provenance are visible
- conformance matrix passes
To preserve room for v2+ work:
- keep import support behind clear interfaces
- keep ranking logic outside raw SQL where possible
- keep provenance explicit in the core data model
- avoid coupling all behavior directly to MCP transport structs
- avoid assuming transcript capture exists
If Go is chosen, implement codex-mem as:
- a single local binary
- with SQLite as the durable store
- domain services at the core
- MCP handlers as adapters
- spec-driven behavior and conformance tests as the quality gate