@aaryanbindage/omnicontext 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp.js ADDED
@@ -0,0 +1,323 @@
1
+ // MCP server (stdio). Works in Claude Code, Claude Desktop, and any MCP client.
2
+
3
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
+ import { z } from 'zod';
6
+ import { Store, VERSION } from './store.js';
7
+ import { resolveProjects } from './resolve.js';
8
+ import { buildContext } from './context.js';
9
+ import { sync, syncStatus } from './sync.js';
10
+
11
+ const text = (t) => ({ content: [{ type: 'text', text: typeof t === 'string' ? t : JSON.stringify(t, null, 2) }] });
12
+ const fail = (t) => ({ content: [{ type: 'text', text: t }], isError: true });
13
+
14
+ export async function startMcpServer(store = new Store()) {
15
+ const server = new McpServer({ name: 'omnicontext', version: VERSION });
16
+
17
+ // Push writes to the sync remote shortly after they happen (debounced).
18
+ let timer;
19
+ const changed = () => {
20
+ if (store.getLocal().autoSync === false) return;
21
+ clearTimeout(timer);
22
+ timer = setTimeout(() => {
23
+ try {
24
+ if (syncStatus(store.home).configured) sync(store.home, store.device);
25
+ } catch {}
26
+ }, 4000);
27
+ };
28
+
29
+ const guard = (fn) => async (args) => {
30
+ try {
31
+ return await fn(args);
32
+ } catch (e) {
33
+ return fail(String(e.message || e));
34
+ }
35
+ };
36
+
37
+ server.registerTool(
38
+ 'get_context',
39
+ {
40
+ title: 'Get user context',
41
+ description:
42
+ "Briefing about the user: profile, all projects, open handoffs. Call at the start of a conversation (when it wasn't injected automatically) or when the user refers to something you don't recognise.",
43
+ inputSchema: { cwd: z.string().optional().describe('Current working directory, to detect the active project') },
44
+ annotations: { readOnlyHint: true },
45
+ },
46
+ guard(async ({ cwd }) => text(buildContext(store, { cwd }))),
47
+ );
48
+
49
+ server.registerTool(
50
+ 'get_profile',
51
+ {
52
+ title: 'Get profile',
53
+ description: "The user's full profile markdown (who they are, preferences, facts).",
54
+ inputSchema: {},
55
+ annotations: { readOnlyHint: true },
56
+ },
57
+ guard(async () => text(store.getProfile())),
58
+ );
59
+
60
+ server.registerTool(
61
+ 'remember',
62
+ {
63
+ title: 'Remember a fact about the user',
64
+ description:
65
+ 'Save a durable fact about the user (role, preference, tool, goal, constraint) to their profile so every future session knows it. For project-specific info use add_project_note. Never store secrets.',
66
+ inputSchema: { fact: z.string().min(3).describe('One concise fact, e.g. "Prefers TypeScript over JavaScript"') },
67
+ },
68
+ guard(async ({ fact }) => {
69
+ const line = store.remember(fact);
70
+ changed();
71
+ return text(`Saved to profile: ${line}`);
72
+ }),
73
+ );
74
+
75
+ server.registerTool(
76
+ 'update_profile',
77
+ {
78
+ title: 'Rewrite profile',
79
+ description: 'Replace the whole profile markdown. Read it with get_profile first and keep existing facts unless the user asks to remove them.',
80
+ inputSchema: { content: z.string().describe('Full new profile markdown') },
81
+ },
82
+ guard(async ({ content }) => {
83
+ store.setProfile(content);
84
+ changed();
85
+ return text('Profile updated.');
86
+ }),
87
+ );
88
+
89
+ server.registerTool(
90
+ 'list_projects',
91
+ {
92
+ title: 'List projects',
93
+ description: "All of the user's projects with aliases, tags, status and paths.",
94
+ inputSchema: { status: z.string().optional().describe('Filter by status, e.g. active, paused, archived') },
95
+ annotations: { readOnlyHint: true },
96
+ },
97
+ guard(async ({ status }) => {
98
+ const list = store.listProjects().filter((p) => !status || p.status === status);
99
+ return text(list.map(({ notes, ...p }) => ({ ...p, noteCount: notes?.length || 0 })));
100
+ }),
101
+ );
102
+
103
+ server.registerTool(
104
+ 'resolve_project',
105
+ {
106
+ title: 'Resolve a project reference',
107
+ description:
108
+ 'Turn a loose reference like "my game project", "the bot", or "that website" into the matching project(s), best first, with full details and notes.',
109
+ inputSchema: { query: z.string().describe('What the user called it') },
110
+ annotations: { readOnlyHint: true },
111
+ },
112
+ guard(async ({ query }) => {
113
+ const hits = resolveProjects(store.listProjects(), query, 3);
114
+ if (!hits.length) return text(`No project matches "${query}". Ask the user which project they mean, then register it with upsert_project.`);
115
+ return text(hits.map((h) => ({ score: h.score, ...h.project })));
116
+ }),
117
+ );
118
+
119
+ server.registerTool(
120
+ 'get_project',
121
+ {
122
+ title: 'Get project',
123
+ description: 'Full details, notes, and recent handoffs for one project (by slug, name, or alias).',
124
+ inputSchema: { project: z.string() },
125
+ annotations: { readOnlyHint: true },
126
+ },
127
+ guard(async ({ project }) => {
128
+ const p = store.getProject(project) || resolveProjects(store.listProjects(), project, 1)[0]?.project;
129
+ if (!p) return fail(`No project "${project}"`);
130
+ return text({ ...p, handoffs: store.listHandoffs({ project: p.slug, limit: 5 }) });
131
+ }),
132
+ );
133
+
134
+ server.registerTool(
135
+ 'upsert_project',
136
+ {
137
+ title: 'Create or update project',
138
+ description:
139
+ 'Register a project or update it. Aliases are what the user calls it ("my game", "the rpg") — add them generously so future references resolve. Pass `path` to link a folder on this device.',
140
+ inputSchema: {
141
+ name: z.string().describe('Display name'),
142
+ description: z.string().optional().describe('What it is, stack, goal — one or two sentences'),
143
+ aliases: z.array(z.string()).optional().describe('Nicknames the user uses for it'),
144
+ tags: z.array(z.string()).optional(),
145
+ status: z.enum(['active', 'paused', 'done', 'archived']).optional(),
146
+ repo: z.string().optional().describe('Git remote URL'),
147
+ path: z.string().optional().describe('Absolute folder path on this device'),
148
+ },
149
+ },
150
+ guard(async (args) => {
151
+ const p = store.upsertProject(args);
152
+ changed();
153
+ return text({ saved: p.slug, project: p });
154
+ }),
155
+ );
156
+
157
+ server.registerTool(
158
+ 'add_project_note',
159
+ {
160
+ title: 'Add project note',
161
+ description: 'Record a decision, status update, or important detail on a project. Visible to all future sessions.',
162
+ inputSchema: { project: z.string().describe('Slug, name, or alias'), note: z.string() },
163
+ },
164
+ guard(async ({ project, note }) => {
165
+ const target = store.getProject(project) || resolveProjects(store.listProjects(), project, 1)[0]?.project;
166
+ if (!target) return fail(`No project "${project}". Create it with upsert_project first.`);
167
+ store.addProjectNote(target.slug, note);
168
+ changed();
169
+ return text(`Note added to ${target.name}.`);
170
+ }),
171
+ );
172
+
173
+ server.registerTool(
174
+ 'save_handoff',
175
+ {
176
+ title: 'Save handoff',
177
+ description:
178
+ 'Save the state of the current work so it can be resumed later in any Claude session on any device. Write it for a future assistant with no memory of this conversation: goal, what was done, key decisions, where things are, and concrete next steps.',
179
+ inputSchema: {
180
+ title: z.string().describe('Short title'),
181
+ summary: z.string().describe('Self-contained summary of the work so far'),
182
+ next_steps: z.array(z.string()).optional(),
183
+ project: z.string().optional().describe('Project slug/name/alias this belongs to'),
184
+ files: z.array(z.string()).optional().describe('Key files involved (paths relative to the project)'),
185
+ cwd: z.string().optional(),
186
+ },
187
+ },
188
+ guard(async ({ title, summary, next_steps, project, files, cwd }) => {
189
+ const proj = project ? store.getProject(project) || resolveProjects(store.listProjects(), project, 1)[0]?.project : null;
190
+ const h = store.saveHandoff({ title, summary, nextSteps: next_steps, files, cwd, project: proj?.slug || project });
191
+ changed();
192
+ return text(`Handoff saved: ${h.id}. Resume on any device with "resume ${h.title}" or /omnicontext:resume.`);
193
+ }),
194
+ );
195
+
196
+ server.registerTool(
197
+ 'list_handoffs',
198
+ {
199
+ title: 'List handoffs',
200
+ description: 'Saved handoffs, newest first.',
201
+ inputSchema: {
202
+ project: z.string().optional(),
203
+ status: z.enum(['open', 'resumed', 'done', 'all']).optional().describe('Default: open'),
204
+ limit: z.number().int().positive().optional(),
205
+ },
206
+ annotations: { readOnlyHint: true },
207
+ },
208
+ guard(async ({ project, status = 'open', limit = 10 }) => text(store.listHandoffs({ project, status, limit }))),
209
+ );
210
+
211
+ server.registerTool(
212
+ 'resume_handoff',
213
+ {
214
+ title: 'Resume handoff',
215
+ description:
216
+ 'Load a handoff to continue that work here. Give an id, or a project / words from the title; with nothing it picks the most recent open handoff. Marks it resumed.',
217
+ inputSchema: {
218
+ id: z.string().optional(),
219
+ query: z.string().optional().describe('Project name or words from the title'),
220
+ },
221
+ },
222
+ guard(async ({ id, query }) => {
223
+ let h = id ? store.getHandoff(id) : null;
224
+ if (!h) {
225
+ const open = store.listHandoffs({ status: 'open' });
226
+ if (query) {
227
+ const proj = resolveProjects(store.listProjects(), query, 1)[0]?.project;
228
+ const q = query.toLowerCase();
229
+ h = open.find((x) => proj && x.project === proj.slug) ||
230
+ open.find((x) => `${x.title} ${x.summary}`.toLowerCase().includes(q));
231
+ } else h = open[0];
232
+ }
233
+ if (!h) return fail('No matching open handoff. Use list_handoffs with status "all" to see older ones.');
234
+ store.setHandoffStatus(h.id, 'resumed');
235
+ changed();
236
+ const proj = h.project ? store.getProject(h.project) : null;
237
+ const localPath = proj?.paths?.[store.device];
238
+ return text(
239
+ `# Resuming: ${h.title}\nFrom ${h.device} at ${h.createdAt}${proj ? ` · project ${proj.name}` : ''}\n` +
240
+ (localPath ? `Project folder on this device: ${localPath}\n` : proj ? `Project folder isn't linked on this device yet.\n` : '') +
241
+ `\n## Summary\n${h.summary}\n` +
242
+ (h.nextSteps?.length ? `\n## Next steps\n${h.nextSteps.map((s) => `- ${s}`).join('\n')}\n` : '') +
243
+ (h.files?.length ? `\n## Files\n${h.files.map((s) => `- ${s}`).join('\n')}\n` : ''),
244
+ );
245
+ }),
246
+ );
247
+
248
+ server.registerTool(
249
+ 'complete_handoff',
250
+ {
251
+ title: 'Complete handoff',
252
+ description: 'Mark a handoff done once its work is finished.',
253
+ inputSchema: { id: z.string() },
254
+ },
255
+ guard(async ({ id }) => {
256
+ store.setHandoffStatus(id, 'done');
257
+ changed();
258
+ return text(`Handoff ${id} marked done.`);
259
+ }),
260
+ );
261
+
262
+ server.registerTool(
263
+ 'search_memory',
264
+ {
265
+ title: 'Search memory',
266
+ description: 'Full-text search across profile, project notes, and handoffs.',
267
+ inputSchema: { query: z.string() },
268
+ annotations: { readOnlyHint: true },
269
+ },
270
+ guard(async ({ query }) => {
271
+ const q = query.toLowerCase();
272
+ const hits = [];
273
+ for (const line of store.getProfile().split('\n')) if (line.toLowerCase().includes(q)) hits.push({ in: 'profile', text: line.trim() });
274
+ for (const p of store.listProjects()) {
275
+ if (`${p.name} ${p.description} ${(p.aliases || []).join(' ')}`.toLowerCase().includes(q))
276
+ hits.push({ in: `project:${p.slug}`, text: p.description || p.name });
277
+ for (const n of p.notes || []) if (n.text.toLowerCase().includes(q)) hits.push({ in: `project:${p.slug}`, text: n.text, at: n.at });
278
+ }
279
+ for (const h of store.listHandoffs({ status: 'all' }))
280
+ if (`${h.title} ${h.summary}`.toLowerCase().includes(q)) hits.push({ in: `handoff:${h.id}`, text: h.title, status: h.status });
281
+ return text(hits.length ? hits.slice(0, 30) : `Nothing found for "${query}".`);
282
+ }),
283
+ );
284
+
285
+ server.registerTool(
286
+ 'sync_now',
287
+ {
288
+ title: 'Sync now',
289
+ description: 'Push/pull memory to the user\'s sync remote so other devices see it.',
290
+ inputSchema: {},
291
+ },
292
+ guard(async () => text(sync(store.home, store.device))),
293
+ );
294
+
295
+ server.registerPrompt(
296
+ 'resume',
297
+ { title: 'Resume my last work', description: 'Continue the most recent open handoff from any device.' },
298
+ () => ({
299
+ messages: [{ role: 'user', content: { type: 'text', text: 'Call resume_handoff and continue that work. Start by briefly restating where things stand.' } }],
300
+ }),
301
+ );
302
+ server.registerPrompt(
303
+ 'handoff',
304
+ { title: 'Save a handoff', description: 'Save the current work so it can be resumed on another device.' },
305
+ () => ({
306
+ messages: [{ role: 'user', content: { type: 'text', text: 'Summarise what we are working on and call save_handoff with a self-contained summary, the project, key files, and concrete next steps.' } }],
307
+ }),
308
+ );
309
+
310
+ await server.connect(new StdioServerTransport());
311
+ // Flush any pending sync before exit.
312
+ const flush = () => {
313
+ if (timer) {
314
+ clearTimeout(timer);
315
+ try {
316
+ if (syncStatus(store.home).configured) sync(store.home, store.device);
317
+ } catch {}
318
+ }
319
+ process.exit(0);
320
+ };
321
+ process.stdin.on('close', flush);
322
+ process.on('SIGTERM', flush);
323
+ }
package/src/resolve.js ADDED
@@ -0,0 +1,55 @@
1
+ // Resolve vague references ("my game project", "the discord bot") to a stored project.
2
+
3
+ import path from 'node:path';
4
+
5
+ const STOP = new Set(
6
+ ('my the a an our this that those these project projects app apps thing stuff repo repository codebase code one ' +
7
+ 'with for of on in to at i im i\'m working work about called named new old side').split(' '),
8
+ );
9
+
10
+ const stem = (t) => (t.length > 4 && t.endsWith('ies') ? t.slice(0, -3) + 'y' : t.length > 3 && t.endsWith('s') ? t.slice(0, -1) : t);
11
+
12
+ export function tokens(s) {
13
+ return String(s ?? '')
14
+ .toLowerCase()
15
+ .split(/[^a-z0-9]+/)
16
+ .filter((t) => t && !STOP.has(t))
17
+ .map(stem);
18
+ }
19
+
20
+ export function scoreProject(p, query) {
21
+ const q = String(query).toLowerCase().trim();
22
+ const names = [p.name, p.slug, ...(p.aliases || [])].filter(Boolean).map((x) => String(x).toLowerCase());
23
+ let score = 0;
24
+ if (names.includes(q)) score += 100;
25
+ for (const n of names) if (n.length > 2 && q.includes(n)) score += 40;
26
+
27
+ const nameTok = tokens(names.join(' '));
28
+ const tagTok = tokens((p.tags || []).join(' '));
29
+ const descTok = tokens(p.description);
30
+ const pathTok = tokens(Object.values(p.paths || {}).map((x) => path.basename(String(x))).join(' '));
31
+ const noteTok = tokens((p.notes || []).slice(-10).map((n) => n.text).join(' '));
32
+
33
+ for (const t of tokens(query)) {
34
+ if (nameTok.includes(t)) score += 20;
35
+ else if (t.length > 2 && nameTok.some((n) => n.length > 2 && (n.startsWith(t) || t.startsWith(n)))) score += 10;
36
+ if (tagTok.includes(t)) score += 12;
37
+ if (pathTok.includes(t)) score += 8;
38
+ if (descTok.includes(t)) score += 5;
39
+ if (noteTok.includes(t)) score += 2;
40
+ }
41
+ if (score > 0 && p.status === 'archived') score -= 5;
42
+ return score;
43
+ }
44
+
45
+ export function resolveProjects(projects, query, limit = 5) {
46
+ return projects
47
+ .map((project) => ({ project, score: scoreProject(project, query) }))
48
+ .filter((x) => x.score > 0)
49
+ .sort(
50
+ (a, b) =>
51
+ b.score - a.score ||
52
+ String(b.project.lastActiveAt || '').localeCompare(String(a.project.lastActiveAt || '')),
53
+ )
54
+ .slice(0, limit);
55
+ }
package/src/store.js ADDED
@@ -0,0 +1,303 @@
1
+ // File-backed store. One file per record so git sync rarely conflicts.
2
+ //
3
+ // <home>/
4
+ // profile.md who you are (markdown, free-form)
5
+ // projects/<slug>.json one per project
6
+ // handoffs/<id>.json resumable work, one per handoff
7
+ // local.json device-only settings (never synced)
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import os from 'node:os';
12
+ import crypto from 'node:crypto';
13
+
14
+ export const VERSION = '0.1.2';
15
+
16
+ export function defaultHome() {
17
+ return process.env.OMNICONTEXT_HOME || path.join(os.homedir(), '.omnicontext');
18
+ }
19
+
20
+ const PROFILE_TEMPLATE = `# About me
21
+
22
+ <!-- Who you are, what you do, how you like to work. Every Claude session reads this. -->
23
+
24
+ ## Facts
25
+ `;
26
+
27
+ export function slugify(s) {
28
+ const slug = String(s ?? '')
29
+ .toLowerCase()
30
+ .normalize('NFKD')
31
+ .replace(/[^\w\s-]/g, '')
32
+ .trim()
33
+ .replace(/[\s_]+/g, '-')
34
+ .replace(/-+/g, '-')
35
+ .replace(/^-|-$/g, '')
36
+ .slice(0, 60);
37
+ return slug || 'project';
38
+ }
39
+
40
+ const now = () => new Date().toISOString();
41
+ const uniq = (arr) => [...new Set(arr.map((x) => String(x).trim()).filter(Boolean))];
42
+
43
+ function readJson(file, fallback) {
44
+ try {
45
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
46
+ } catch {
47
+ return fallback;
48
+ }
49
+ }
50
+
51
+ function writeJson(file, data) {
52
+ fs.mkdirSync(path.dirname(file), { recursive: true });
53
+ const tmp = `${file}.${process.pid}.tmp`;
54
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n');
55
+ fs.renameSync(tmp, file);
56
+ }
57
+
58
+ function listJson(dir) {
59
+ try {
60
+ return fs
61
+ .readdirSync(dir)
62
+ .filter((f) => f.endsWith('.json'))
63
+ .map((f) => readJson(path.join(dir, f), null))
64
+ .filter(Boolean);
65
+ } catch {
66
+ return [];
67
+ }
68
+ }
69
+
70
+ export class Store {
71
+ constructor(home = defaultHome()) {
72
+ this.home = path.resolve(home);
73
+ this.ensure();
74
+ }
75
+
76
+ ensure() {
77
+ fs.mkdirSync(path.join(this.home, 'projects'), { recursive: true });
78
+ fs.mkdirSync(path.join(this.home, 'handoffs'), { recursive: true });
79
+ if (!fs.existsSync(this.profilePath)) fs.writeFileSync(this.profilePath, PROFILE_TEMPLATE);
80
+ const gitignore = path.join(this.home, '.gitignore');
81
+ if (!fs.existsSync(gitignore)) fs.writeFileSync(gitignore, 'local.json\n*.tmp\n');
82
+ return this;
83
+ }
84
+
85
+ // ---- device-local settings -------------------------------------------
86
+
87
+ get localPath() {
88
+ return path.join(this.home, 'local.json');
89
+ }
90
+ getLocal() {
91
+ return readJson(this.localPath, {});
92
+ }
93
+ setLocal(patch) {
94
+ const next = { ...this.getLocal(), ...patch };
95
+ writeJson(this.localPath, next);
96
+ return next;
97
+ }
98
+ get device() {
99
+ return this.getLocal().deviceName || os.hostname();
100
+ }
101
+
102
+ // ---- profile ---------------------------------------------------------
103
+
104
+ get profilePath() {
105
+ return path.join(this.home, 'profile.md');
106
+ }
107
+ getProfile() {
108
+ try {
109
+ return fs.readFileSync(this.profilePath, 'utf8');
110
+ } catch {
111
+ return PROFILE_TEMPLATE;
112
+ }
113
+ }
114
+ setProfile(content) {
115
+ fs.writeFileSync(this.profilePath, String(content).replace(/\s*$/, '\n'));
116
+ return this.getProfile();
117
+ }
118
+ /** Append a durable fact about the user under "## Facts". */
119
+ remember(fact) {
120
+ const line = `- ${String(fact).trim().replace(/\s+/g, ' ')} _(${now().slice(0, 10)})_`;
121
+ let profile = this.getProfile().replace(/\s*$/, '\n');
122
+ if (!/^## Facts\s*$/m.test(profile)) profile += '\n## Facts\n';
123
+ // Insert at the end of the Facts section (before the next "## " heading, if any).
124
+ const lines = profile.split('\n');
125
+ const start = lines.findIndex((l) => /^## Facts\s*$/.test(l));
126
+ let end = lines.findIndex((l, i) => i > start && /^## /.test(l));
127
+ if (end === -1) end = lines.length;
128
+ while (end > start + 1 && lines[end - 1].trim() === '') end--;
129
+ lines.splice(end, 0, line);
130
+ this.setProfile(lines.join('\n'));
131
+ return line;
132
+ }
133
+
134
+ // ---- projects --------------------------------------------------------
135
+
136
+ projectPath(slug) {
137
+ return path.join(this.home, 'projects', `${slugify(slug)}.json`);
138
+ }
139
+ listProjects() {
140
+ return listJson(path.join(this.home, 'projects')).sort((a, b) =>
141
+ String(b.lastActiveAt || b.updatedAt || '').localeCompare(String(a.lastActiveAt || a.updatedAt || '')),
142
+ );
143
+ }
144
+ getProject(slugOrName) {
145
+ if (!slugOrName) return null;
146
+ const direct = readJson(this.projectPath(slugOrName), null);
147
+ if (direct) return direct;
148
+ const key = String(slugOrName).toLowerCase();
149
+ return (
150
+ this.listProjects().find(
151
+ (p) => p.name.toLowerCase() === key || (p.aliases || []).some((a) => a.toLowerCase() === key),
152
+ ) || null
153
+ );
154
+ }
155
+ /** Create or merge a project. Lists (aliases, tags) are unioned; `path` is stored for this device. */
156
+ upsertProject(input) {
157
+ if (!input?.name && !input?.slug) throw new Error('Project needs a name');
158
+ const existing = this.getProject(input.slug || input.name);
159
+ const p = existing || {
160
+ name: input.name,
161
+ slug: slugify(input.slug || input.name),
162
+ aliases: [],
163
+ tags: [],
164
+ description: '',
165
+ status: 'active',
166
+ repo: '',
167
+ paths: {},
168
+ notes: [],
169
+ createdAt: now(),
170
+ };
171
+ if (input.name) p.name = input.name;
172
+ for (const key of ['description', 'status', 'repo']) {
173
+ if (input[key] !== undefined && input[key] !== null) p[key] = String(input[key]);
174
+ }
175
+ if (input.aliases) p.aliases = uniq(input.replaceLists ? input.aliases : [...p.aliases, ...input.aliases]);
176
+ if (input.tags) p.tags = uniq(input.replaceLists ? input.tags : [...p.tags, ...input.tags]);
177
+ if (input.path) p.paths = { ...p.paths, [input.device || this.device]: path.resolve(input.path) };
178
+ if (input.paths) p.paths = { ...p.paths, ...input.paths };
179
+ p.updatedAt = now();
180
+ writeJson(this.projectPath(p.slug), p);
181
+ return p;
182
+ }
183
+ addProjectNote(slugOrName, text) {
184
+ const p = this.getProject(slugOrName);
185
+ if (!p) throw new Error(`No project "${slugOrName}"`);
186
+ p.notes = [...(p.notes || []), { text: String(text).trim(), at: now(), device: this.device }];
187
+ p.updatedAt = p.lastActiveAt = now();
188
+ writeJson(this.projectPath(p.slug), p);
189
+ return p;
190
+ }
191
+ touchProject(slugOrName) {
192
+ const p = this.getProject(slugOrName);
193
+ if (!p) return null;
194
+ p.lastActiveAt = now();
195
+ writeJson(this.projectPath(p.slug), p);
196
+ return p;
197
+ }
198
+ deleteProject(slug) {
199
+ fs.rmSync(this.projectPath(slug), { force: true });
200
+ }
201
+ /** The project whose path on this device contains `cwd`, or whose repo matches cwd's git remote. */
202
+ projectForCwd(cwd) {
203
+ if (!cwd) return null;
204
+ const norm = (p) => path.resolve(p).toLowerCase().replace(/[\\/]+$/, '');
205
+ const here = norm(cwd);
206
+ let best = null;
207
+ for (const p of this.listProjects()) {
208
+ for (const dir of Object.values(p.paths || {})) {
209
+ const d = norm(dir);
210
+ if ((here === d || here.startsWith(d + path.sep.toLowerCase()) || here.startsWith(d + '/')) &&
211
+ (!best || d.length > best.len)) {
212
+ best = { project: p, len: d.length };
213
+ }
214
+ }
215
+ }
216
+ if (best) return best.project;
217
+ const remote = gitRemoteOf(cwd);
218
+ if (remote) {
219
+ const r = normalizeRepo(remote);
220
+ return this.listProjects().find((p) => p.repo && normalizeRepo(p.repo) === r) || null;
221
+ }
222
+ return null;
223
+ }
224
+
225
+ // ---- handoffs --------------------------------------------------------
226
+
227
+ handoffPath(id) {
228
+ return path.join(this.home, 'handoffs', `${String(id).replace(/[^\w-]/g, '')}.json`);
229
+ }
230
+ saveHandoff({ project, title, summary, nextSteps = [], files = [], cwd = '' }) {
231
+ if (!summary) throw new Error('A handoff needs a summary');
232
+ const stamp = now().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
233
+ const id = `${stamp}-${crypto.randomBytes(2).toString('hex')}`;
234
+ const proj = project ? this.getProject(project) : null;
235
+ const h = {
236
+ id,
237
+ title: title || summary.split('\n')[0].slice(0, 80),
238
+ project: proj ? proj.slug : project || '',
239
+ summary,
240
+ nextSteps,
241
+ files,
242
+ cwd,
243
+ device: this.device,
244
+ status: 'open',
245
+ createdAt: now(),
246
+ };
247
+ writeJson(this.handoffPath(id), h);
248
+ if (proj) this.touchProject(proj.slug);
249
+ return h;
250
+ }
251
+ listHandoffs({ project, status, limit } = {}) {
252
+ let list = listJson(path.join(this.home, 'handoffs')).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
253
+ if (project) {
254
+ const p = this.getProject(project);
255
+ const slug = p ? p.slug : project;
256
+ list = list.filter((h) => h.project === slug);
257
+ }
258
+ if (status && status !== 'all') list = list.filter((h) => h.status === status);
259
+ return limit ? list.slice(0, limit) : list;
260
+ }
261
+ getHandoff(id) {
262
+ return readJson(this.handoffPath(id), null);
263
+ }
264
+ setHandoffStatus(id, status) {
265
+ const h = this.getHandoff(id);
266
+ if (!h) throw new Error(`No handoff "${id}"`);
267
+ h.status = status;
268
+ h[`${status}At`] = now();
269
+ if (status === 'resumed') h.resumedOn = this.device;
270
+ writeJson(this.handoffPath(id), h);
271
+ return h;
272
+ }
273
+ deleteHandoff(id) {
274
+ fs.rmSync(this.handoffPath(id), { force: true });
275
+ }
276
+ }
277
+
278
+ export function normalizeRepo(url) {
279
+ return String(url)
280
+ .trim()
281
+ .toLowerCase()
282
+ .replace(/^git@([^:]+):/, '$1/')
283
+ .replace(/^[a-z+]+:\/\//, '')
284
+ .replace(/^[^@/]+@/, '')
285
+ .replace(/\.git$/, '')
286
+ .replace(/\/+$/, '');
287
+ }
288
+
289
+ function gitRemoteOf(cwd) {
290
+ // Walk up to find .git/config without spawning git (keeps hooks fast).
291
+ let dir = path.resolve(cwd);
292
+ for (let i = 0; i < 20; i++) {
293
+ const cfg = path.join(dir, '.git', 'config');
294
+ if (fs.existsSync(cfg)) {
295
+ const m = fs.readFileSync(cfg, 'utf8').match(/\[remote "origin"\][^[]*?url\s*=\s*(\S+)/);
296
+ return m ? m[1] : null;
297
+ }
298
+ const parent = path.dirname(dir);
299
+ if (parent === dir) break;
300
+ dir = parent;
301
+ }
302
+ return null;
303
+ }