Convert gitgram/ and aitimemachine/ from embedded git repos (which showed as opaque submodule gitlinks on GitHub) into fully-tracked first-party content. AITM now merges its 7 vendored repos as first-party engines: - memory: beads (Go task DAG) + context7 (docs SDK), unified into saved_contexts - git: vendored C git (bundled binary) + gitnexus (in-process code intelligence) - agentic: a2a (@a2a-js/sdk) + pal (AITM-managed Python subprocess) Includes the full session's product build: Gitgram web/mobile/backend features, AITM website/CLI/MCP, the unified memory layer, engine build tooling (scripts/build-engines.sh, Dockerfile, CI), docs (README, ENGINES.md, ARCHITECTURE.md), and extensive test suites. Build artifacts, node_modules, external/, and gemini-cli are gitignored. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
19 KiB
AITimeMachine: Three-Layer Architecture Plan
Vision: macOS Time Machine for AI coding - restore code AND chat to any point in time. Canonical reference:
../../../NORTH_STAR_PRD_ARCHITECTURE_V1.md. Canonical SQL source:../../../CANONICAL_SQL_SCHEMA_V1.sql.
๐ฏ The Core Vision
When AI breaks your code:
- Open AITimeMachine
- Select "before the error"
- Both code AND chat context are restored
- Continue from the clean state
<EFBFBD>๏ธ Backend-Heavy Architecture (Critical)
The Core Principle
The Backend is the Source of Truth. MCP/API act as thin clients with local cache/offline buffering.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ User's Environment โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โ โ VSCode โ โ Claude Code โ โ Cursor โ โ
โ โ + AITM MCP โ โ + AITM MCP โ โ + AITM MCP โ โ
โ โโโโโโโโฌโโโโโโโโ โโโโโโโโฌโโโโโโโโ โโโโโโโโฌโโโโโโโโ โ
โ โ โ โ โ
โ โโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ AITM MCP Server (Thin Client) โ โ
โ โ โข No canonical database โ โ
โ โ โข Local cache/offline buffer only โ โ
โ โ โข Forwards writes/reads to backend โ โ
โ โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HTTPS
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AITM Backend API Server โ
โ โข Authentication โ
โ โข Business logic โ
โ โข All data processing โ
โโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Neon Database (Postgres) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โข All chats (every message) โ โ
โ โ โข All code (every version) โ โ
โ โ โข All files (full content) โ โ
โ โ โข All folders (directory trees) โ โ
โ โ โข All changes (diffs) โ โ
โ โ โข All contexts (mental states) โ โ
โ โ โข All embeddings (for search) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Why Backend-Heavy?
- Reliability: User's machine can crash, backend stays up
- Cross-Device: Access from anywhere
- No Local DB: MCP doesn't manage databases
- Scalability: Backend handles heavy operations
- Security: Centralized auth and access control
What Gets Saved (Everything!)
// Every AI action triggers backend save
interface CaptureEvent {
// Chat
messages: Message[]; // Every user/AI message
toolCalls: ToolCall[]; // Every tool invocation
toolOutputs: ToolOutput[]; // Every result
// Code
files: FileSnapshot[]; // Full file content
folders: FolderTree[]; // Directory structure
diffs: FileDiff[]; // What changed
// Context
activeFiles: string[]; // What was open
cursorPosition: Position; // Where user was
currentTask: string; // What AI was doing
// Metadata
timestamp: Date;
checkpointId: string;
sessionId: string;
}
<EFBFBD>๐๏ธ Three-Layer Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AITimeMachine Layers โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Layer 1: โณ TIME LAYER (Git-Quality Storage) โ
โ โโ Checkpoints (every AI action) โ
โ โโ Content-addressable storage (deduplication) โ
โ โโ Delta compression (Git packfiles) โ
โ โโ Advanced diff algorithms (Myers, Histogram) โ
โ โ
โ Layer 2: ๐ง CONTEXT LAYER (The Memory) โ
โ โโ Full chat history (every message) โ
โ โโ Tool calls + outputs (what AI did) โ
โ โโ Mental state (active files, cursor, goals) โ
โ โโ Linked to checkpoints (restore chat with code) โ
โ โ
โ Layer 3: ๐ฎ AUGMENTED LAYER (The Intelligence) โ
โ โโ Code search (semantic + regex) โ
โ โโ Oracle agent (ask about history) โ
โ โโ Documentation indexing โ
โ โโ Universal search (code + docs + history) โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ MCP/API โ Backend Connection
MCP Server (Thin Client)
The MCP server runs locally with cache/offline buffering only; canonical state is in the backend.
// src/mcp-daemon.ts (Simplified)
class MCPDaemon {
private apiClient: AITMBackendClient;
constructor() {
// Connect to backend
this.apiClient = new AITMBackendClient({
baseUrl: process.env.AITM_BACKEND_URL || 'https://timemachine-api.gitgram.app',
apiKey: process.env.AITM_API_KEY
});
}
async handleToolCall(tool: string, args: any) {
switch (tool) {
case 'tm_checkpoint':
// Forward to backend
return await this.apiClient.post('/checkpoints', {
description: args.description,
files: await this.scanCurrentFiles(),
context: await this.getCurrentContext()
});
case 'tm_go_back':
// Get data from backend
const checkpoint = await this.apiClient.get(`/checkpoints/${args.id}`);
// Restore locally
await this.restoreFiles(checkpoint.files);
return checkpoint.context;
case 'before_action':
// Capture state and send to backend
const state = await this.captureCurrentState();
return await this.apiClient.post('/actions/before', state);
case 'after_action':
// Capture changes and send to backend
const changes = await this.captureChanges();
return await this.apiClient.post('/actions/after', changes);
}
}
}
Backend API Endpoints
// Backend handles ALL data operations
// Checkpoints
POST /api/checkpoints // Create checkpoint
GET /api/checkpoints // List checkpoints
GET /api/checkpoints/:id // Get checkpoint details
POST /api/checkpoints/:id/restore // Restore to checkpoint
DELETE /api/checkpoints/:id // Delete checkpoint
// Files (Full content storage)
POST /api/files // Save file content
GET /api/files/:hash // Get file by hash
GET /api/files/tree/:checkpoint // Get directory tree
POST /api/files/diff // Get diff between versions
// Chats
POST /api/chats/messages // Save message
GET /api/chats/messages // Get messages
GET /api/chats/sessions/:id // Get session history
POST /api/chats/context // Save context snapshot
// Actions (Tool calls)
POST /api/actions/before // Before AI action
POST /api/actions/after // After AI action
GET /api/actions/history // Get action history
// Search & Intelligence
POST /api/search/code // Search code
POST /api/search/chats // Search conversations
POST /api/oracle/ask // Ask Oracle
POST /api/oracle/research // Start research job
// Time Travel
POST /api/time/undo // Undo last action
POST /api/time/restore // Restore to point
GET /api/time/timeline // Get timeline
GET /api/time/diff // Get diff
Data Flow Example: AI Makes a Change
1. User: "Create an API endpoint"
โ
2. MCP captures message
POST /api/chats/messages
{
role: "user",
content: "Create an API endpoint",
sessionId: "sess_123"
}
โ
3. AI decides to use create_file tool
โ
4. MCP: before_action
POST /api/actions/before
{
action: "create_file",
args: {path: "src/api.ts"},
currentFiles: [...], // Full snapshot
currentContext: {...}
}
โ Backend saves checkpoint_before_abc123
โ
5. AI creates file
โ
6. MCP: after_action
POST /api/actions/after
{
action: "create_file",
result: "success",
newFiles: [...], // Full snapshot
diff: {...}
}
โ Backend saves checkpoint_after_abc123
โ Backend links: message โ before โ after
โ
7. Backend generates diff and saves
POST /api/files/diff
โ Stores in diffs table
โ
8. Backend generates embeddings (async)
โ Stores in embeddings table
Authentication Flow
// User authenticates once
const apiKey = await login(email, password);
// Store in environment
process.env.AITM_API_KEY = apiKey;
// MCP uses API key for all requests
headers: {
'Authorization': `Bearer ${process.env.AITM_API_KEY}`,
'Content-Type': 'application/json'
}
Layer 1: โณ Time Layer
Goal
Store every version of every file with Git-quality efficiency.
Components
1.1 Local Storage (.aitimemachine/)
- Content Store: SHA-256 hashed blobs (deduplicated)
- Packfiles: Delta-compressed archives
- Checkpoints: JSON snapshots of project state
- Index: Fast lookup of what changed when
1.2 Cloud Storage (Neon - Required)
-- Core tables
CREATE TABLE checkpoints (
id TEXT PRIMARY KEY,
project_id UUID,
timestamp TIMESTAMP,
description TEXT,
parent_id TEXT,
tree_hash TEXT -- Merkle tree root
);
CREATE TABLE blobs (
hash TEXT PRIMARY KEY,
content BYTEA,
size INTEGER,
compression TEXT
);
CREATE TABLE trees (
hash TEXT PRIMARY KEY,
entries JSONB -- [{name, type, hash, mode}]
);
MCP Tools
tm_checkpoint(description)- Create manual checkpointtm_go_back(time_or_id)- Restore to checkpointtm_undo_last()- Quick undotm_diff(from, to)- Show changestm_restore_file(path, checkpoint)- Selective restore
CLI Commands
aitm checkpoint "Before refactor"
aitm back 5m
aitm undo
aitm diff HEAD~1
aitm restore src/api.ts --from abc123
API Endpoints
POST /api/time/checkpoint
POST /api/time/restore
POST /api/time/undo
GET /api/time/diff/:from/:to
GET /api/time/timeline
Layer 2: ๐ง Context Layer
Goal
Capture and restore the AI's "mental state" - not just code, but the conversation and intent.
Components
2.1 Chat Storage
CREATE TABLE messages (
id UUID PRIMARY KEY,
project_id UUID,
session_id TEXT,
checkpoint_id TEXT, -- Link to code state
timestamp TIMESTAMP,
role TEXT, -- 'user' | 'assistant' | 'system'
content TEXT,
tool_calls JSONB,
tool_outputs JSONB
);
CREATE TABLE contexts (
id UUID PRIMARY KEY,
checkpoint_id TEXT,
summary TEXT,
active_files JSONB,
cursor_position JSONB,
current_task TEXT
);
2.2 Auto-Capture
Every AI action triggers:
- before_action: Checkpoint BEFORE change
- Tool execution: Capture inputs/outputs
- after_action: Checkpoint AFTER change
- Link: Connect chat message โ checkpoint
MCP Tools
tm_save_context(summary)- Save mental statetm_get_context(checkpoint_id)- Retrieve contexttm_restore_with_context(checkpoint_id)- Restore code + chat
CLI Commands
aitm context save "API design phase"
aitm context load abc123
aitm back --with-context
API Endpoints
POST /api/context/save
GET /api/context/:checkpoint_id
POST /api/context/restore
GET /api/context/search?q=authentication
Layer 3: ๐ฎ Augmented Layer
Goal
Intelligent search, research, and understanding (inspired by Nia but AITM-specific).
Components
3.1 Code Intelligence
CREATE TABLE embeddings (
id UUID PRIMARY KEY,
project_id UUID,
checkpoint_id TEXT,
file_path TEXT,
chunk_text TEXT,
embedding vector(1536), -- pgvector
metadata JSONB
);
CREATE INDEX ON embeddings USING ivfflat (embedding vector_cosine_ops);
3.2 Oracle Agent
The "Oracle" knows:
- Project history: What changed when and why
- Code context: Where functions are defined
- Chat history: What you discussed with AI
- External docs: Indexed documentation
MCP Tools (Nia-Inspired)
tm_oracle_ask(question)- Ask about projecttm_search_code(query)- Semantic code searchtm_index_docs(url)- Index documentationtm_universal_search(query)- Search everythingtm_research(topic)- Deep research agent
CLI Commands
aitm ask "Where is the auth logic?"
aitm search "database connection"
aitm index https://docs.example.com
aitm research "best practices for API design"
API Endpoints (Nia-Style)
POST /api/oracle/ask
POST /api/search/code
POST /api/search/universal
POST /api/index/docs
POST /api/research/start
GET /api/research/:job_id
๐ Data Flow: The Complete Picture
Capture Flow
AI makes change
โ
1. before_action checkpoint
โ
2. Capture tool call + args
โ
3. Execute change
โ
4. Capture tool output
โ
5. after_action checkpoint
โ
6. Link: message โ checkpoint โ context
โ
7. Sync to Neon (async)
โ
8. Generate embeddings (background)
Restore Flow
User: "Go back to before the error"
โ
1. Search checkpoints (by time/description)
โ
2. Load checkpoint metadata
โ
3. Fetch linked context from Neon
โ
4. Restore files from content store
โ
5. Return chat context to AI
โ
6. AI continues with restored state
๐ Implementation Priority
Phase 1: Time Layer (Core) โ
- Content-addressable storage
- Checkpoints
- Diff engine
- Packfiles
- MCP tools (basic)
Phase 2: Context Layer (Critical) ๐
- Chat message storage
- Tool call tracking
- Context snapshots
- Checkpoint โ Context linking
- Restore with context
Phase 3: Augmented Layer (Intelligence) ๐
- Code embeddings
- Oracle agent
- Documentation indexing
- Universal search
- Research agent
๐ฏ Key Differences from Nia
| Feature | Nia | AITimeMachine |
|---|---|---|
| Focus | External repos/docs | Your project history |
| Time Travel | โ No | โ Full restore |
| Chat Context | Limited | โ Full history |
| Undo AI Mistakes | โ No | โ Core feature |
| Local-First | โ Cloud-only | โ Hybrid |
| Git Integration | Basic | โ Deep (packfiles, trees) |
๐ Success Criteria
- โ
Instant Undo:
aitm undorestores in <1 second - โ Chat Restore: Going back includes conversation context
- โ Smart Search: Find "before the Docker changes"
- โ
Selective Restore: Restore just
src/api.ts - โ Oracle Intelligence: Ask "What did I change yesterday?"
- โ Heavy Backend: All data synced to Neon for reliability
๐ File Structure
src/
โโโ core/
โ โโโ engine.ts # Main TimeMachine engine
โ โโโ content-store.ts # Blob storage
โ โโโ diff-engine-v2.ts # Advanced diff
โ โโโ git/
โ โโโ tree.ts # Merkle trees
โ โโโ pack/ # Packfile logic
โโโ neon/
โ โโโ client.ts # Drizzle + Neon
โ โโโ schema.ts # DB schema
โ โโโ sync.ts # Sync service
โ โโโ indexer.ts # Embeddings
โโโ oracle/
โ โโโ agent.ts # Oracle intelligence
โโโ mcp/
โ โโโ mcp-daemon.ts # MCP server
โ โโโ ai-time-concept-tools.ts
โโโ api/
โ โโโ server.ts # REST API
โโโ cli/
โโโ cli-v2.ts # CLI commands
๐ Environment Variables
# Required
DATABASE_URL=postgres://...neon.tech/...
OPENAI_API_KEY=sk-...
# Optional
AITM_AUTO_SYNC=true
AITM_CAPTURE_INTERVAL=300 # 5 minutes
๐ Next Steps
-
Complete Context Layer:
- Implement chat storage in Neon
- Link checkpoints โ contexts
- Update
tm_go_backto restore context
-
Build Oracle:
- Implement embedding generation
- Create Oracle agent
- Add universal search
-
Polish UX:
- Add visual timeline (TUI)
- Improve error messages
- Add progress indicators
-
Documentation:
- User guide
- API reference
- Video tutorials