-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.py
More file actions
369 lines (299 loc) · 9.91 KB
/
setup.py
File metadata and controls
369 lines (299 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#!/usr/bin/env python3
"""
memnode setup script.
Handles:
1. Fresh install: Creates notes directory structure
2. Existing notes repo: Rebuilds index, validates structure
3. New machine: Clone notes repo, point MEMNODE_DIR, rebuild index
Usage:
uv run python setup.py [--notes-dir PATH]
Or after install:
memnode-setup [--notes-dir PATH]
"""
import argparse
import os
import subprocess
import sys
from pathlib import Path
# ANSI colors
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
BLUE = "\033[94m"
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
def print_step(msg: str):
print(f"{BLUE}==>{RESET} {msg}")
def print_success(msg: str):
print(f"{GREEN}✓{RESET} {msg}")
def print_warning(msg: str):
print(f"{YELLOW}!{RESET} {msg}")
def print_error(msg: str):
print(f"{RED}✗{RESET} {msg}")
def get_default_notes_dir() -> Path:
"""Get default notes directory."""
# Check env first (MEMNODE_DIR takes precedence)
if env_dir := os.environ.get("MEMNODE_DIR"):
return Path(env_dir).expanduser().resolve()
if env_dir := os.environ.get("NOTES_DIR"):
return Path(env_dir).expanduser().resolve()
# Default to ~/memnode
return Path.home() / "memnode"
def init_notes_directory(notes_dir: Path) -> bool:
"""Initialize notes directory structure."""
print_step(f"Initializing directory: {notes_dir}")
# Create directories
dirs = ["todos", "people", "projects", "decisions", "journal", "meetings"]
for d in dirs:
(notes_dir / d).mkdir(parents=True, exist_ok=True)
print_success(f"Created {d}/")
# Create .gitignore
gitignore = notes_dir / ".gitignore"
if not gitignore.exists():
gitignore.write_text("""# SQLite index (regenerated on each machine)
.memnode_index.db
.memnode_index.db-journal
.notes_index.db
.notes_index.db-journal
# OS files
.DS_Store
Thumbs.db
""")
print_success("Created .gitignore")
# Create relationships file
relationships = notes_dir / ".relationships.yaml"
if not relationships.exists():
relationships.write_text("relationships: []\n")
print_success("Created .relationships.yaml")
# Create inbox
inbox = notes_dir / "todos" / "inbox.md"
if not inbox.exists():
inbox.write_text("""---
type: todo
---
# Inbox
Capture quick thoughts here, organize later.
""")
print_success("Created todos/inbox.md")
# Initialize git if not already a repo
if not (notes_dir / ".git").exists():
print_step("Initializing git repository...")
subprocess.run(["git", "init"], cwd=notes_dir, capture_output=True)
subprocess.run(["git", "add", "."], cwd=notes_dir, capture_output=True)
subprocess.run(
["git", "commit", "-m", "Initial memnode structure"],
cwd=notes_dir,
capture_output=True,
)
print_success("Git repository initialized")
else:
print_success("Git repository already exists")
return True
def rebuild_index(notes_dir: Path) -> bool:
"""Rebuild the SQLite index."""
print_step("Rebuilding search index...")
# Remove old index
for db_name in [".memnode_index.db", ".notes_index.db"]:
db_path = notes_dir / db_name
if db_path.exists():
db_path.unlink()
# Import and rebuild
try:
sys.path.insert(0, str(Path(__file__).parent))
from src.indexer import NotesIndex
index = NotesIndex(notes_dir)
index.reindex_all()
index.close()
print_success("Search index rebuilt")
return True
except Exception as e:
print_error(f"Failed to rebuild index: {e}")
return False
def validate_structure(notes_dir: Path) -> list[str]:
"""Validate notes directory structure."""
issues = []
required_dirs = ["todos", "people", "projects"]
for d in required_dirs:
if not (notes_dir / d).exists():
issues.append(f"Missing directory: {d}/")
if not (notes_dir / ".relationships.yaml").exists():
issues.append("Missing .relationships.yaml")
return issues
def print_shell_config(notes_dir: Path):
"""Print shell configuration instructions."""
print()
print(f"{BOLD}Add to your shell config (~/.zshrc or ~/.bashrc):{RESET}")
print()
print(f' export MEMNODE_DIR="{notes_dir}"')
print()
def print_mcp_config(notes_dir: Path):
"""Print MCP configuration."""
project_dir = Path(__file__).parent.resolve()
print(f"{BOLD}MCP Configuration (Claude Desktop / OpenCode / Cursor):{RESET}")
print()
print("""{
"mcpServers": {
"memnode": {
"command": "uv",
"args": ["run", "--directory", "%s", "python", "-m", "src.server"],
"env": {
"MEMNODE_DIR": "%s"
}
}
}
}""" % (project_dir, notes_dir))
print()
def print_completion_instructions():
"""Print shell completion setup instructions."""
print(f"{BOLD}Shell Completions:{RESET}")
print()
print(f" {DIM}# Bash{RESET}")
print(" memnode --install-completion bash")
print()
print(f" {DIM}# Zsh{RESET}")
print(" memnode --install-completion zsh")
print()
print(f" {DIM}# Fish{RESET}")
print(" memnode --install-completion fish")
print()
def count_notes(notes_dir: Path) -> dict:
"""Count notes by type."""
counts = {}
for subdir in ["todos", "people", "projects", "decisions", "journal"]:
path = notes_dir / subdir
if path.exists():
counts[subdir] = len(list(path.glob("*.md")))
else:
counts[subdir] = 0
return counts
def main():
parser = argparse.ArgumentParser(
description="Setup memnode for a fresh install or new machine",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Interactive setup (prompts for directory)
uv run python setup.py
# Specify directory directly
uv run python setup.py --notes-dir ~/my-notes
# Use existing notes repo (e.g., after git clone)
uv run python setup.py --notes-dir ~/work-notes
# Rebuild index after syncing
uv run python setup.py --rebuild-index
# Show config for copy/paste
uv run python setup.py --show-config --notes-dir ~/my-notes
"""
)
parser.add_argument(
"--notes-dir", "-d",
type=Path,
default=None,
help="Path to notes directory (will prompt if not specified)",
)
parser.add_argument(
"--rebuild-index",
action="store_true",
help="Only rebuild the search index",
)
parser.add_argument(
"--show-config",
action="store_true",
help="Show MCP and shell configuration",
)
args = parser.parse_args()
print()
print(f"{BOLD}memnode setup{RESET}")
print(f"{'=' * 50}")
print()
# Determine notes directory
if args.notes_dir:
notes_dir = args.notes_dir.expanduser().resolve()
else:
# Check environment variables
env_dir = os.environ.get("MEMNODE_DIR") or os.environ.get("NOTES_DIR")
if env_dir:
default_dir = Path(env_dir).expanduser().resolve()
print(f"{DIM}Found MEMNODE_DIR={env_dir}{RESET}")
else:
default_dir = Path.home() / "memnode"
# Interactive prompt for directory
print("Where would you like to store your notes?")
print(f"{DIM}(This should be a git repository you can sync across machines){RESET}")
print()
user_input = input(f"Notes directory [{default_dir}]: ").strip()
if user_input:
notes_dir = Path(user_input).expanduser().resolve()
else:
notes_dir = default_dir
print()
# Show config only
if args.show_config:
print_shell_config(notes_dir)
print_mcp_config(notes_dir)
print_completion_instructions()
return 0
# Rebuild index only
if args.rebuild_index:
if not notes_dir.exists():
print_error(f"Directory not found: {notes_dir}")
return 1
rebuild_index(notes_dir)
return 0
# Full setup
if notes_dir.exists():
print_step(f"Found existing directory: {notes_dir}")
# Validate structure
issues = validate_structure(notes_dir)
if issues:
print_warning("Structure issues found:")
for issue in issues:
print(f" - {issue}")
print()
response = input("Fix issues and continue? [Y/n] ").strip().lower()
if response and response != "y":
return 1
init_notes_directory(notes_dir)
else:
print_success("Structure validated")
# Show stats
counts = count_notes(notes_dir)
print()
print_step("Current data:")
for category, count in counts.items():
if count > 0:
print(f" {category}: {count} files")
else:
print_step(f"Creating new directory: {notes_dir}")
response = input("Continue? [Y/n] ").strip().lower()
if response and response != "y":
return 1
init_notes_directory(notes_dir)
# Rebuild index
print()
rebuild_index(notes_dir)
# Print next steps
print()
print(f"{BOLD}{'=' * 50}{RESET}")
print(f"{GREEN}Setup complete!{RESET}")
print()
print_shell_config(notes_dir)
print_mcp_config(notes_dir)
print_completion_instructions()
print(f"{BOLD}Quick start:{RESET}")
print()
print(" # Add a person to your network")
print(" memnode add person")
print()
print(" # Quick capture a thought")
print(" memnode capture 'Look into that thing'")
print()
print(" # Record a 1:1")
print(" memnode add 1on1 <person-slug>")
print()
print(" # See all commands")
print(" memnode --help")
print()
return 0
if __name__ == "__main__":
sys.exit(main())