memories-dev
Developer guide for contributing to the memories.sh monorepo.
Project Structure
memories/
├── packages/
│ ├── cli/ # @memories.sh/cli (npm package)
│ │ ├── src/
│ │ │ ├── commands/ # CLI commands (Commander.js)
│ │ │ ├── lib/ # Core: db, memory, auth, embeddings, git
│ │ │ └── mcp/ # MCP server (stdio + HTTP)
│ │ ├── tsup.config.ts # Build config
│ │ └── package.json
│ └── web/ # Next.js marketing + dashboard
│ ├── src/app/ # App Router pages + API routes
│ ├── src/components/ # UI components (shadcn/ui)
│ ├── src/lib/ # Auth, Stripe, Supabase, Turso
│ └── content/docs/ # Fumadocs documentation
├── supabase/ # Database migrations
├── skills/ # Distributable skills (this directory)
└── pnpm-workspace.yaml
Architecture Overview
Dependency Graph
db.ts (SQLite/libSQL, migrations, FTS5)
↓
memory.ts (CRUD, context, lifecycle sessions, compaction, consolidation, streaming)
↑ ↑ ↑
openclaw-memory.ts reminders.ts embeddings.ts (Xenova/Transformers, cosine similarity)
↑ ↑
git.ts openclaw.ts command bridge
↓
Commands ← auth.ts, turso.ts, config.ts, setup.ts
↓
MCP Server (stdio + StreamableHTTP transports)
↳ registerCoreTools (core + lifecycle + consolidation + reminders)
↳ registerStreamingTools (SSE chunk pipelines)
Key Lib Files
| File |
Purpose |
db.ts |
SQLite via libSQL. Schema migrations, FTS5 triggers, getDb() singleton |
memory.ts |
Memory operations: add/search/list/forget/update, getContext, sessions, compaction checkpoints, consolidation, streaming |
openclaw-memory.ts |
OpenClaw file-mode contract (memory.md, daily logs, snapshots), workspace path resolution, read/write helpers |
embeddings.ts |
Local embeddings via Xenova/Transformers. generateEmbedding(), cosine similarity |
git.ts |
getProjectId() — derives project ID from git remote URL |
auth.ts |
Cloud auth token storage, device code flow helpers |
turso.ts |
Turso embedded replica sync (cloud ↔ local) |
config.ts |
YAML config read/write (~/.config/memories/) |
setup.ts |
Tool detection (Cursor, Claude, Windsurf, VS Code), MCP config setup |
templates.ts |
Built-in memory templates (decision, error-fix, api-endpoint, etc.) |
ui.ts |
Terminal styling: chalk, figlet, gradient, boxen |
Database Schema
SQLite with FTS5 full-text search:
- memories — Main table: id, content, type, tags, scope, project_id, created_at, updated_at, deleted_at
- memories_fts — FTS5 virtual table, synced via triggers
- memory_embeddings — Vector storage: memory_id, embedding (JSON float array), model
- memory_links — Bidirectional links: id1, id2, link_type
- memory_history — Version tracking: memory_id, version, content, tags, change_type
- memory_sessions — Explicit session state (scope, status, last activity, metadata)
- memory_session_events — Session turn/checkpoint/event log with meaningful flag
- memory_session_snapshots — Raw markdown transcript snapshots keyed by trigger/slug
- memory_compaction_events — Write-ahead compaction audit trail
- memory_consolidation_runs — Consolidation run metadata and counts
Lifecycle Model (Current)
- Session start:
startMemorySession() creates memory_sessions row and can preload OpenClaw bootstrap context when file mode is enabled.
- Checkpointing:
checkpointMemorySession() records meaningful events in memory_session_events.
- Compaction guard:
writeAheadCompactionCheckpoint() writes a checkpoint before destructive context compaction and logs memory_compaction_events.
- Snapshots:
createMemorySessionSnapshot() stores raw markdown snapshots in DB and optionally mirrors to OpenClaw snapshot files.
- Consolidation:
consolidateMemories() merges duplicates/supersedes stale entries and records memory_consolidation_runs.
Adding a New CLI Command
- Create
packages/cli/src/commands/mycommand.ts:
import { Command } from "commander";
export const myCommand = new Command("mycommand")
.description("What it does")
.argument("<required>", "Description")
.option("-f, --flag <value>", "Description", "default")
.action(async (required, opts) => {
// Use lib functions from ../lib/
// Use ui.ts for styled output
});
- Register in
packages/cli/src/index.ts:
import { myCommand } from "./commands/mycommand.js";
program.addCommand(myCommand);
- Add tests in
packages/cli/src/commands/mycommand.test.ts.
Adding a New MCP Tool
Edit packages/cli/src/mcp/tools.ts (and streaming-tools.ts for chunked ingestion):
server.tool(
"tool_name",
"Description of what the tool does",
{
param: z.string().describe("Parameter description"),
},
async ({ param }) => {
// Implementation
return {
content: [{ type: "text", text: "Result" }],
};
}
);
Parameters use Zod schemas. Return { isError: true } for errors.
Notes:
- Register in
registerCoreTools() for standard/lifecycle tools.
- Keep cloud-vs-local behavior explicit when adding tools that rely on local-only tables or file paths.
Adding a New Generation Target
- Add template to
packages/cli/src/lib/templates.ts
- Register in the generation targets map
- Add detection in
packages/cli/src/lib/setup.ts
- Add docs page in
packages/web/content/docs/integrations/
Build & Test
pnpm build # Build all packages
pnpm typecheck # TypeScript checks
pnpm test # Run all tests (vitest)
# CLI-specific
cd packages/cli
pnpm dev # Watch mode (tsup)
pnpm test # CLI tests only
# Web-specific
cd packages/web
pnpm dev # Next.js dev server
pnpm build # Production build
Tech Stack
| Layer |
Technology |
| CLI framework |
Commander.js |
| Database |
libSQL (SQLite-compatible) |
| Full-text search |
FTS5 |
| Embeddings |
Xenova/Transformers (local) |
| MCP SDK |
@modelcontextprotocol/sdk |
| Build |
tsup (CLI), Next.js (web) |
| Web framework |
Next.js 15 (App Router) |
| Auth |
Supabase Auth |
| Cloud sync |
Turso embedded replicas |
| Payments |
Stripe |
| Docs |
Fumadocs |
| UI |
shadcn/ui, Tailwind CSS v4 |
| Testing |
Vitest |
Reference Files
- Architecture deep-dive: See references/architecture.md for detailed module descriptions and data flow
1---2name: memories-dev3description: Developer guide for contributing to and extending the memories.sh codebase. Use when: (1) Understanding the memories.sh architecture and lifecycle model, (2) Adding new CLI commands or MCP tools, (3) Modifying the memory storage layer (SQLite/libSQL), (4) Working on the web dashboard (Next.js/Supabase), (5) Adding new generation targets for AI tools, (6) Extending cloud sync, session compaction, or embeddings functionality, (7) Debugging build, test, or deployment issues in the monorepo.4---56# memories-dev78Developer guide for contributing to the memories.sh monorepo.910## Project Structure1112```13memories/14├── packages/15│ ├── cli/ # @memories.sh/cli (npm package)16│ │ ├── src/17│ │ │ ├── commands/ # CLI commands (Commander.js)18│ │ │ ├── lib/ # Core: db, memory, auth, embeddings, git19│ │ │ └── mcp/ # MCP server (stdio + HTTP)20│ │ ├── tsup.config.ts # Build config21│ │ └── package.json22│ └── web/ # Next.js marketing + dashboard23│ ├── src/app/ # App Router pages + API routes24│ ├── src/components/ # UI components (shadcn/ui)25│ ├── src/lib/ # Auth, Stripe, Supabase, Turso26│ └── content/docs/ # Fumadocs documentation27├── supabase/ # Database migrations28├── skills/ # Distributable skills (this directory)29└── pnpm-workspace.yaml30```3132## Architecture Overview3334### Dependency Graph3536```37db.ts (SQLite/libSQL, migrations, FTS5)38 ↓39memory.ts (CRUD, context, lifecycle sessions, compaction, consolidation, streaming)40 ↑ ↑ ↑41openclaw-memory.ts reminders.ts embeddings.ts (Xenova/Transformers, cosine similarity)42 ↑ ↑43git.ts openclaw.ts command bridge44 ↓45Commands ← auth.ts, turso.ts, config.ts, setup.ts46 ↓47MCP Server (stdio + StreamableHTTP transports)48 ↳ registerCoreTools (core + lifecycle + consolidation + reminders)49 ↳ registerStreamingTools (SSE chunk pipelines)50```5152### Key Lib Files5354| File | Purpose |55|------|---------|56| `db.ts` | SQLite via libSQL. Schema migrations, FTS5 triggers, `getDb()` singleton |57| `memory.ts` | Memory operations: add/search/list/forget/update, `getContext`, sessions, compaction checkpoints, consolidation, streaming |58| `openclaw-memory.ts` | OpenClaw file-mode contract (`memory.md`, daily logs, snapshots), workspace path resolution, read/write helpers |59| `embeddings.ts` | Local embeddings via Xenova/Transformers. `generateEmbedding()`, cosine similarity |60| `git.ts` | `getProjectId()` — derives project ID from git remote URL |61| `auth.ts` | Cloud auth token storage, device code flow helpers |62| `turso.ts` | Turso embedded replica sync (cloud ↔ local) |63| `config.ts` | YAML config read/write (`~/.config/memories/`) |64| `setup.ts` | Tool detection (Cursor, Claude, Windsurf, VS Code), MCP config setup |65| `templates.ts` | Built-in memory templates (decision, error-fix, api-endpoint, etc.) |66| `ui.ts` | Terminal styling: chalk, figlet, gradient, boxen |6768### Database Schema6970SQLite with FTS5 full-text search:7172- **memories** — Main table: id, content, type, tags, scope, project_id, created_at, updated_at, deleted_at73- **memories_fts** — FTS5 virtual table, synced via triggers74- **memory_embeddings** — Vector storage: memory_id, embedding (JSON float array), model75- **memory_links** — Bidirectional links: id1, id2, link_type76- **memory_history** — Version tracking: memory_id, version, content, tags, change_type77- **memory_sessions** — Explicit session state (scope, status, last activity, metadata)78- **memory_session_events** — Session turn/checkpoint/event log with meaningful flag79- **memory_session_snapshots** — Raw markdown transcript snapshots keyed by trigger/slug80- **memory_compaction_events** — Write-ahead compaction audit trail81- **memory_consolidation_runs** — Consolidation run metadata and counts8283### Lifecycle Model (Current)84851. **Session start**: `startMemorySession()` creates `memory_sessions` row and can preload OpenClaw bootstrap context when file mode is enabled.862. **Checkpointing**: `checkpointMemorySession()` records meaningful events in `memory_session_events`.873. **Compaction guard**: `writeAheadCompactionCheckpoint()` writes a checkpoint before destructive context compaction and logs `memory_compaction_events`.884. **Snapshots**: `createMemorySessionSnapshot()` stores raw markdown snapshots in DB and optionally mirrors to OpenClaw snapshot files.895. **Consolidation**: `consolidateMemories()` merges duplicates/supersedes stale entries and records `memory_consolidation_runs`.9091## Adding a New CLI Command92931. Create `packages/cli/src/commands/mycommand.ts`:9495```typescript96import { Command } from "commander";9798export const myCommand = new Command("mycommand")99 .description("What it does")100 .argument("<required>", "Description")101 .option("-f, --flag <value>", "Description", "default")102 .action(async (required, opts) => {103 // Use lib functions from ../lib/104 // Use ui.ts for styled output105 });106```1071082. Register in `packages/cli/src/index.ts`:109110```typescript111import { myCommand } from "./commands/mycommand.js";112program.addCommand(myCommand);113```1141153. Add tests in `packages/cli/src/commands/mycommand.test.ts`.116117## Adding a New MCP Tool118119Edit `packages/cli/src/mcp/tools.ts` (and `streaming-tools.ts` for chunked ingestion):120121```typescript122server.tool(123 "tool_name",124 "Description of what the tool does",125 {126 param: z.string().describe("Parameter description"),127 },128 async ({ param }) => {129 // Implementation130 return {131 content: [{ type: "text", text: "Result" }],132 };133 }134);135```136137Parameters use Zod schemas. Return `{ isError: true }` for errors.138139Notes:140- Register in `registerCoreTools()` for standard/lifecycle tools.141- Keep cloud-vs-local behavior explicit when adding tools that rely on local-only tables or file paths.142143## Adding a New Generation Target1441451. Add template to `packages/cli/src/lib/templates.ts`1462. Register in the generation targets map1473. Add detection in `packages/cli/src/lib/setup.ts`1484. Add docs page in `packages/web/content/docs/integrations/`149150## Build & Test151152```bash153pnpm build # Build all packages154pnpm typecheck # TypeScript checks155pnpm test # Run all tests (vitest)156157# CLI-specific158cd packages/cli159pnpm dev # Watch mode (tsup)160pnpm test # CLI tests only161162# Web-specific163cd packages/web164pnpm dev # Next.js dev server165pnpm build # Production build166```167168## Tech Stack169170| Layer | Technology |171|-------|-----------|172| CLI framework | Commander.js |173| Database | libSQL (SQLite-compatible) |174| Full-text search | FTS5 |175| Embeddings | Xenova/Transformers (local) |176| MCP SDK | @modelcontextprotocol/sdk |177| Build | tsup (CLI), Next.js (web) |178| Web framework | Next.js 15 (App Router) |179| Auth | Supabase Auth |180| Cloud sync | Turso embedded replicas |181| Payments | Stripe |182| Docs | Fumadocs |183| UI | shadcn/ui, Tailwind CSS v4 |184| Testing | Vitest |185186## Reference Files187188- **Architecture deep-dive**: See [references/architecture.md](references/architecture.md) for detailed module descriptions and data flow