@aaryanbindage/omnicontext 0.1.3 → 0.2.0
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/README.md +14 -5
- package/dist/omnicontext.mjs +66 -45
- package/package.json +1 -1
- package/src/cli.js +36 -1
- package/src/context.js +17 -2
- package/src/mcp.js +116 -4
- package/src/store.js +154 -4
- package/src/sync.js +7 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aaryanbindage/omnicontext",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Persistent, cross-device memory for Claude: your profile, your projects, and resumable handoffs — shared by every Claude session (Claude Code plugin + MCP server + desktop app).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/cli.js
CHANGED
|
@@ -16,6 +16,9 @@ Usage:
|
|
|
16
16
|
omnicontext status Data folder, device, sync state
|
|
17
17
|
|
|
18
18
|
omnicontext remember "<fact>" Add a fact to your profile
|
|
19
|
+
omnicontext forget "<words>" Remove profile facts containing these words
|
|
20
|
+
omnicontext capture "<text>" [--project P] Drop a quick note in the inbox
|
|
21
|
+
omnicontext inbox List inbox items (captures from the watch and elsewhere)
|
|
19
22
|
omnicontext profile [--edit FILE] Print profile, or replace it from FILE
|
|
20
23
|
omnicontext projects List projects
|
|
21
24
|
omnicontext project add <name> [--alias A]... [--tag T]... [--desc D] [--path DIR] [--repo URL]
|
|
@@ -27,6 +30,8 @@ Usage:
|
|
|
27
30
|
omnicontext sync --github [NAME] Create a private GitHub repo (via gh) and sync to it
|
|
28
31
|
omnicontext sync --remote <git-url> Sync to any git remote you own
|
|
29
32
|
omnicontext device <name> Name this device
|
|
33
|
+
omnicontext export [FILE] Write everything to one JSON file (stdout if no FILE)
|
|
34
|
+
omnicontext import FILE [--replace-profile] Merge an export into this device's memory
|
|
30
35
|
|
|
31
36
|
omnicontext install claude-desktop Add the MCP server to Claude Desktop
|
|
32
37
|
omnicontext install claude-code Install the Claude Code plugin
|
|
@@ -115,7 +120,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
115
120
|
case 'status': {
|
|
116
121
|
const st = syncStatus(store.home);
|
|
117
122
|
console.log(`Data: ${store.home}\nDevice: ${store.device}`);
|
|
118
|
-
console.log(`Projects: ${store.listProjects().length} Open handoffs: ${store.listHandoffs({ status: 'open' }).length}`);
|
|
123
|
+
console.log(`Projects: ${store.listProjects().length} Open handoffs: ${store.listHandoffs({ status: 'open' }).length} Inbox: ${store.listInbox().length}`);
|
|
119
124
|
console.log(`Sync: ${st.configured ? `${st.remote}${st.dirty ? ' (unsynced changes)' : ''}` : 'not configured (omnicontext sync --github)'}`);
|
|
120
125
|
return;
|
|
121
126
|
}
|
|
@@ -125,6 +130,36 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
125
130
|
console.log('Saved:', store.remember(pos.join(' ')));
|
|
126
131
|
return;
|
|
127
132
|
|
|
133
|
+
case 'forget': {
|
|
134
|
+
const removed = store.forget(pos.join(' '));
|
|
135
|
+
console.log(removed.length ? `Removed:\n${removed.join('\n')}` : 'No matching fact.');
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
case 'capture': {
|
|
140
|
+
const item = store.capture(pos.join(' '), { project: typeof flags.project === 'string' ? flags.project : '' });
|
|
141
|
+
return console.log(`Captured ${item.id}`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
case 'inbox':
|
|
145
|
+
for (const i of store.listInbox()) console.log(`${i.id} ${i.text}${i.project ? ` (${i.project})` : ''} — ${i.source}`);
|
|
146
|
+
return;
|
|
147
|
+
|
|
148
|
+
case 'export': {
|
|
149
|
+
const json = JSON.stringify(store.exportAll(), null, 2) + '\n';
|
|
150
|
+
if (pos[0]) {
|
|
151
|
+
fs.writeFileSync(pos[0], json);
|
|
152
|
+
return console.log(`Exported to ${pos[0]}`);
|
|
153
|
+
}
|
|
154
|
+
return process.stdout.write(json);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
case 'import': {
|
|
158
|
+
if (!pos[0]) throw new Error('Usage: omnicontext import FILE');
|
|
159
|
+
const r = store.importAll(JSON.parse(fs.readFileSync(pos[0], 'utf8')), { replaceProfile: !!flags['replace-profile'] });
|
|
160
|
+
return console.log(`Imported ${r.projects} projects, ${r.handoffs} handoffs, ${r.inbox} inbox items.`);
|
|
161
|
+
}
|
|
162
|
+
|
|
128
163
|
case 'profile':
|
|
129
164
|
if (typeof flags.edit === 'string') store.setProfile(fs.readFileSync(flags.edit, 'utf8'));
|
|
130
165
|
return console.log(store.getProfile());
|
package/src/context.js
CHANGED
|
@@ -26,14 +26,20 @@ export function projectLine(p, device, current) {
|
|
|
26
26
|
|
|
27
27
|
export function handoffLine(h) {
|
|
28
28
|
const next = h.nextSteps?.length ? ` Next: ${h.nextSteps.slice(0, 2).join('; ')}` : '';
|
|
29
|
-
|
|
29
|
+
const branch = h.git?.branch ? ` Branch \`${h.git.branch}\`.` : '';
|
|
30
|
+
return `- \`${h.id}\` **${h.title}**${h.project ? ` (${h.project})` : ''} — from ${h.device}, ${ago(h.createdAt)}.${branch}${next}`;
|
|
30
31
|
}
|
|
31
32
|
|
|
33
|
+
const STALE_DAYS = 30;
|
|
34
|
+
|
|
32
35
|
export function buildContext(store, { cwd } = {}) {
|
|
33
36
|
const device = store.device;
|
|
34
37
|
const projects = store.listProjects();
|
|
35
38
|
const current = store.projectForCwd(cwd);
|
|
36
|
-
const
|
|
39
|
+
const allOpen = store.listHandoffs({ status: 'open' });
|
|
40
|
+
const fresh = allOpen.filter((h) => Date.now() - new Date(h.createdAt).getTime() < STALE_DAYS * 86400000);
|
|
41
|
+
const open = fresh.slice(0, 5);
|
|
42
|
+
const inbox = store.listInbox();
|
|
37
43
|
const profile = store.getProfile().replace(/<!--[\s\S]*?-->/g, '').replace(/\n{3,}/g, '\n\n').trim();
|
|
38
44
|
|
|
39
45
|
const out = [];
|
|
@@ -73,6 +79,15 @@ export function buildContext(store, { cwd } = {}) {
|
|
|
73
79
|
for (const h of open) out.push(handoffLine(h));
|
|
74
80
|
out.push('If the user says "resume", "continue", or "pick up where I left off", call `resume_handoff`.');
|
|
75
81
|
}
|
|
82
|
+
const hidden = allOpen.length - open.length;
|
|
83
|
+
if (hidden > 0) out.push(`${open.length ? '' : '\n'}(${hidden} more open handoff${hidden > 1 ? 's' : ''}, older or beyond the first five: \`list_handoffs\`.)`);
|
|
84
|
+
|
|
85
|
+
if (inbox.length) {
|
|
86
|
+
out.push(`\n## Inbox (${inbox.length} quick capture${inbox.length > 1 ? 's' : ''} to file)`);
|
|
87
|
+
for (const i of inbox.slice(0, 10))
|
|
88
|
+
out.push(`- \`${i.id}\` "${i.text.slice(0, 200)}"${i.project ? ` (for ${i.project})` : ''} — from ${i.source}, ${ago(i.createdAt)}`);
|
|
89
|
+
out.push('At a natural moment, mention these and offer to file each one with `file_inbox` (as a profile fact, a project note, or dismiss).');
|
|
90
|
+
}
|
|
76
91
|
|
|
77
92
|
out.push(
|
|
78
93
|
`\n## Keeping this memory useful\n` +
|
package/src/mcp.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// MCP server (stdio). Works in Claude Code, Claude Desktop, and any MCP client.
|
|
2
2
|
|
|
3
|
-
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
3
|
+
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
4
4
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
-
import { Store, VERSION } from './store.js';
|
|
6
|
+
import { Store, VERSION, gitStateOf } from './store.js';
|
|
7
7
|
import { resolveProjects } from './resolve.js';
|
|
8
8
|
import { buildContext } from './context.js';
|
|
9
9
|
import { sync, syncStatus } from './sync.js';
|
|
@@ -11,6 +11,18 @@ import { sync, syncStatus } from './sync.js';
|
|
|
11
11
|
const text = (t) => ({ content: [{ type: 'text', text: typeof t === 'string' ? t : JSON.stringify(t, null, 2) }] });
|
|
12
12
|
const fail = (t) => ({ content: [{ type: 'text', text: t }], isError: true });
|
|
13
13
|
|
|
14
|
+
/** How to get this device's checkout to where the handoff left off. */
|
|
15
|
+
function gitSection(h, device) {
|
|
16
|
+
const g = h.git;
|
|
17
|
+
if (!g) return '';
|
|
18
|
+
const lines = [`\n## Git state on ${h.device}`, `Branch \`${g.branch}\` at \`${g.commit}\`${g.remote ? ` (${g.remote})` : ''}.`];
|
|
19
|
+
if (g.unpushed) lines.push(`⚠ ${g.unpushed} commit(s) were not pushed from ${h.device}; they won't be on the remote.`);
|
|
20
|
+
if (g.uncommitted?.length)
|
|
21
|
+
lines.push(`⚠ Uncommitted changes on ${h.device} (not available here unless pushed): ${g.uncommitted.slice(0, 10).join(', ')}${g.uncommitted.length > 10 ? ', …' : ''}`);
|
|
22
|
+
if (h.device !== device) lines.push(`To match it here: \`git fetch && git checkout ${g.branch} && git pull\`.`);
|
|
23
|
+
return lines.join('\n') + '\n';
|
|
24
|
+
}
|
|
25
|
+
|
|
14
26
|
export async function startMcpServer(store = new Store()) {
|
|
15
27
|
const server = new McpServer({ name: 'omnicontext', version: VERSION });
|
|
16
28
|
|
|
@@ -72,6 +84,22 @@ export async function startMcpServer(store = new Store()) {
|
|
|
72
84
|
}),
|
|
73
85
|
);
|
|
74
86
|
|
|
87
|
+
server.registerTool(
|
|
88
|
+
'forget',
|
|
89
|
+
{
|
|
90
|
+
title: 'Forget a fact',
|
|
91
|
+
description: 'Remove profile facts (bullet lines) that contain the given text, e.g. when the user says something is no longer true.',
|
|
92
|
+
inputSchema: { text: z.string().min(3).describe('Words from the fact to remove') },
|
|
93
|
+
annotations: { destructiveHint: true },
|
|
94
|
+
},
|
|
95
|
+
guard(async ({ text: q }) => {
|
|
96
|
+
const removed = store.forget(q);
|
|
97
|
+
if (!removed.length) return fail(`No profile fact contains "${q}". Use get_profile to see the exact wording.`);
|
|
98
|
+
changed();
|
|
99
|
+
return text(`Removed ${removed.length} line(s):\n${removed.join('\n')}`);
|
|
100
|
+
}),
|
|
101
|
+
);
|
|
102
|
+
|
|
75
103
|
server.registerTool(
|
|
76
104
|
'update_profile',
|
|
77
105
|
{
|
|
@@ -187,7 +215,9 @@ export async function startMcpServer(store = new Store()) {
|
|
|
187
215
|
},
|
|
188
216
|
guard(async ({ title, summary, next_steps, project, files, cwd }) => {
|
|
189
217
|
const proj = project ? store.getProject(project) || resolveProjects(store.listProjects(), project, 1)[0]?.project : null;
|
|
190
|
-
|
|
218
|
+
// Claude Code starts MCP servers in the project folder, so fall back to it to capture the git state.
|
|
219
|
+
const dir = cwd || (gitStateOf(process.cwd()) ? process.cwd() : '');
|
|
220
|
+
const h = store.saveHandoff({ title, summary, nextSteps: next_steps, files, cwd: dir, project: proj?.slug || project });
|
|
191
221
|
changed();
|
|
192
222
|
return text(`Handoff saved: ${h.id}. Resume on any device with "resume ${h.title}" or /omnicontext:resume.`);
|
|
193
223
|
}),
|
|
@@ -238,6 +268,7 @@ export async function startMcpServer(store = new Store()) {
|
|
|
238
268
|
return text(
|
|
239
269
|
`# Resuming: ${h.title}\nFrom ${h.device} at ${h.createdAt}${proj ? ` · project ${proj.name}` : ''}\n` +
|
|
240
270
|
(localPath ? `Project folder on this device: ${localPath}\n` : proj ? `Project folder isn't linked on this device yet.\n` : '') +
|
|
271
|
+
gitSection(h, store.device) +
|
|
241
272
|
`\n## Summary\n${h.summary}\n` +
|
|
242
273
|
(h.nextSteps?.length ? `\n## Next steps\n${h.nextSteps.map((s) => `- ${s}`).join('\n')}\n` : '') +
|
|
243
274
|
(h.files?.length ? `\n## Files\n${h.files.map((s) => `- ${s}`).join('\n')}\n` : ''),
|
|
@@ -277,11 +308,92 @@ export async function startMcpServer(store = new Store()) {
|
|
|
277
308
|
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
309
|
}
|
|
279
310
|
for (const h of store.listHandoffs({ status: 'all' }))
|
|
280
|
-
if (`${h.title} ${h.summary}`.toLowerCase().includes(q))
|
|
311
|
+
if (`${h.title} ${h.summary} ${(h.nextSteps || []).join(' ')}`.toLowerCase().includes(q))
|
|
312
|
+
hits.push({ in: `handoff:${h.id}`, text: h.title, status: h.status });
|
|
313
|
+
for (const i of store.listInbox()) if (i.text.toLowerCase().includes(q)) hits.push({ in: `inbox:${i.id}`, text: i.text });
|
|
281
314
|
return text(hits.length ? hits.slice(0, 30) : `Nothing found for "${query}".`);
|
|
282
315
|
}),
|
|
283
316
|
);
|
|
284
317
|
|
|
318
|
+
server.registerTool(
|
|
319
|
+
'capture',
|
|
320
|
+
{
|
|
321
|
+
title: 'Capture to inbox',
|
|
322
|
+
description:
|
|
323
|
+
"Drop a quick thought into the user's inbox to sort out later (all devices see it). Prefer remember / add_project_note when you already know where it belongs.",
|
|
324
|
+
inputSchema: {
|
|
325
|
+
text: z.string().min(1),
|
|
326
|
+
project: z.string().optional().describe('Project it probably relates to'),
|
|
327
|
+
},
|
|
328
|
+
},
|
|
329
|
+
guard(async ({ text: t, project }) => {
|
|
330
|
+
const item = store.capture(t, { project });
|
|
331
|
+
changed();
|
|
332
|
+
return text(`Captured ${item.id}.`);
|
|
333
|
+
}),
|
|
334
|
+
);
|
|
335
|
+
|
|
336
|
+
server.registerTool(
|
|
337
|
+
'list_inbox',
|
|
338
|
+
{
|
|
339
|
+
title: 'List inbox',
|
|
340
|
+
description: 'Quick captures (for example dictated on the Apple Watch app) waiting to be filed.',
|
|
341
|
+
inputSchema: {},
|
|
342
|
+
annotations: { readOnlyHint: true },
|
|
343
|
+
},
|
|
344
|
+
guard(async () => {
|
|
345
|
+
const items = store.listInbox();
|
|
346
|
+
return text(items.length ? items : 'Inbox is empty.');
|
|
347
|
+
}),
|
|
348
|
+
);
|
|
349
|
+
|
|
350
|
+
server.registerTool(
|
|
351
|
+
'file_inbox',
|
|
352
|
+
{
|
|
353
|
+
title: 'File inbox item',
|
|
354
|
+
description:
|
|
355
|
+
'Move an inbox item into memory: as a profile fact, as a note on a project, or dismiss it. You may pass cleaned-up `text` (dictations are often rough).',
|
|
356
|
+
inputSchema: {
|
|
357
|
+
id: z.string(),
|
|
358
|
+
as: z.enum(['fact', 'note', 'dismiss']),
|
|
359
|
+
project: z.string().optional().describe('Required when as=note, unless the item already names a project'),
|
|
360
|
+
text: z.string().optional().describe('Rewritten wording to store instead of the raw capture'),
|
|
361
|
+
},
|
|
362
|
+
},
|
|
363
|
+
guard(async ({ id, as, project, text: t }) => {
|
|
364
|
+
const target = project ? store.getProject(project) || resolveProjects(store.listProjects(), project, 1)[0]?.project : null;
|
|
365
|
+
const r = store.fileInbox(id, { as, project: target?.slug || project, text: t });
|
|
366
|
+
changed();
|
|
367
|
+
return text(as === 'dismiss' ? `Dismissed ${id}.` : `Filed ${id} as ${as}${as === 'note' ? ` on ${r.result}` : ''}.`);
|
|
368
|
+
}),
|
|
369
|
+
);
|
|
370
|
+
|
|
371
|
+
// Read-only resources, for clients that browse MCP resources.
|
|
372
|
+
server.registerResource(
|
|
373
|
+
'profile',
|
|
374
|
+
'omnicontext://profile',
|
|
375
|
+
{ title: 'Profile', description: "The user's profile", mimeType: 'text/markdown' },
|
|
376
|
+
async (uri) => ({ contents: [{ uri: uri.href, mimeType: 'text/markdown', text: store.getProfile() }] }),
|
|
377
|
+
);
|
|
378
|
+
server.registerResource(
|
|
379
|
+
'briefing',
|
|
380
|
+
'omnicontext://context',
|
|
381
|
+
{ title: 'Briefing', description: 'The full session briefing', mimeType: 'text/markdown' },
|
|
382
|
+
async (uri) => ({ contents: [{ uri: uri.href, mimeType: 'text/markdown', text: buildContext(store) }] }),
|
|
383
|
+
);
|
|
384
|
+
server.registerResource(
|
|
385
|
+
'project',
|
|
386
|
+
new ResourceTemplate('omnicontext://projects/{slug}', {
|
|
387
|
+
list: async () => ({
|
|
388
|
+
resources: store.listProjects().map((p) => ({ uri: `omnicontext://projects/${p.slug}`, name: p.name, mimeType: 'application/json' })),
|
|
389
|
+
}),
|
|
390
|
+
}),
|
|
391
|
+
{ title: 'Project', description: 'One project with notes', mimeType: 'application/json' },
|
|
392
|
+
async (uri, { slug }) => ({
|
|
393
|
+
contents: [{ uri: uri.href, mimeType: 'application/json', text: JSON.stringify(store.getProject(String(slug)), null, 2) }],
|
|
394
|
+
}),
|
|
395
|
+
);
|
|
396
|
+
|
|
285
397
|
server.registerTool(
|
|
286
398
|
'sync_now',
|
|
287
399
|
{
|
package/src/store.js
CHANGED
|
@@ -4,14 +4,17 @@
|
|
|
4
4
|
// profile.md who you are (markdown, free-form)
|
|
5
5
|
// projects/<slug>.json one per project
|
|
6
6
|
// handoffs/<id>.json resumable work, one per handoff
|
|
7
|
+
// inbox/<id>.json quick captures (e.g. dictated on a watch) waiting to be filed
|
|
8
|
+
// snapshot.json everything above in one file, for read-only clients like the watch app
|
|
7
9
|
// local.json device-only settings (never synced)
|
|
8
10
|
|
|
9
11
|
import fs from 'node:fs';
|
|
10
12
|
import path from 'node:path';
|
|
11
13
|
import os from 'node:os';
|
|
12
14
|
import crypto from 'node:crypto';
|
|
15
|
+
import { execFileSync } from 'node:child_process';
|
|
13
16
|
|
|
14
|
-
export const VERSION = '0.
|
|
17
|
+
export const VERSION = '0.2.0';
|
|
15
18
|
|
|
16
19
|
export function defaultHome() {
|
|
17
20
|
return process.env.OMNICONTEXT_HOME || path.join(os.homedir(), '.omnicontext');
|
|
@@ -76,6 +79,7 @@ export class Store {
|
|
|
76
79
|
ensure() {
|
|
77
80
|
fs.mkdirSync(path.join(this.home, 'projects'), { recursive: true });
|
|
78
81
|
fs.mkdirSync(path.join(this.home, 'handoffs'), { recursive: true });
|
|
82
|
+
fs.mkdirSync(path.join(this.home, 'inbox'), { recursive: true });
|
|
79
83
|
if (!fs.existsSync(this.profilePath)) fs.writeFileSync(this.profilePath, PROFILE_TEMPLATE);
|
|
80
84
|
const gitignore = path.join(this.home, '.gitignore');
|
|
81
85
|
if (!fs.existsSync(gitignore)) fs.writeFileSync(gitignore, 'local.json\n*.tmp\n');
|
|
@@ -130,6 +134,19 @@ export class Store {
|
|
|
130
134
|
this.setProfile(lines.join('\n'));
|
|
131
135
|
return line;
|
|
132
136
|
}
|
|
137
|
+
/** Remove profile bullet lines containing `text` (case-insensitive). Returns the removed lines. */
|
|
138
|
+
forget(text) {
|
|
139
|
+
const q = String(text).trim().toLowerCase();
|
|
140
|
+
if (q.length < 3) throw new Error('Give at least 3 characters of the fact to forget');
|
|
141
|
+
const removed = [];
|
|
142
|
+
const kept = this.getProfile().split('\n').filter((l) => {
|
|
143
|
+
const hit = /^\s*[-*]\s/.test(l) && l.toLowerCase().includes(q);
|
|
144
|
+
if (hit) removed.push(l.trim());
|
|
145
|
+
return !hit;
|
|
146
|
+
});
|
|
147
|
+
if (removed.length) this.setProfile(kept.join('\n'));
|
|
148
|
+
return removed;
|
|
149
|
+
}
|
|
133
150
|
|
|
134
151
|
// ---- projects --------------------------------------------------------
|
|
135
152
|
|
|
@@ -229,9 +246,9 @@ export class Store {
|
|
|
229
246
|
}
|
|
230
247
|
saveHandoff({ project, title, summary, nextSteps = [], files = [], cwd = '' }) {
|
|
231
248
|
if (!summary) throw new Error('A handoff needs a summary');
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
249
|
+
const id = newId();
|
|
250
|
+
let proj = project ? this.getProject(project) : null;
|
|
251
|
+
if (!proj && cwd) proj = this.projectForCwd(cwd);
|
|
235
252
|
const h = {
|
|
236
253
|
id,
|
|
237
254
|
title: title || summary.split('\n')[0].slice(0, 80),
|
|
@@ -244,6 +261,8 @@ export class Store {
|
|
|
244
261
|
status: 'open',
|
|
245
262
|
createdAt: now(),
|
|
246
263
|
};
|
|
264
|
+
const g = cwd ? gitStateOf(cwd) : null;
|
|
265
|
+
if (g) h.git = g;
|
|
247
266
|
writeJson(this.handoffPath(id), h);
|
|
248
267
|
if (proj) this.touchProject(proj.slug);
|
|
249
268
|
return h;
|
|
@@ -273,6 +292,137 @@ export class Store {
|
|
|
273
292
|
deleteHandoff(id) {
|
|
274
293
|
fs.rmSync(this.handoffPath(id), { force: true });
|
|
275
294
|
}
|
|
295
|
+
|
|
296
|
+
// ---- inbox -----------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
inboxPath(id) {
|
|
299
|
+
return path.join(this.home, 'inbox', `${String(id).replace(/[^\w-]/g, '')}.json`);
|
|
300
|
+
}
|
|
301
|
+
/** Quick capture to file later: a thought dictated on the watch, a note from the CLI. */
|
|
302
|
+
capture(text, { project = '', source } = {}) {
|
|
303
|
+
const t = String(text ?? '').trim();
|
|
304
|
+
if (!t) throw new Error('Nothing to capture');
|
|
305
|
+
const item = { id: newId(), text: t, project, source: source || this.device, createdAt: now() };
|
|
306
|
+
writeJson(this.inboxPath(item.id), item);
|
|
307
|
+
return item;
|
|
308
|
+
}
|
|
309
|
+
listInbox() {
|
|
310
|
+
return listJson(path.join(this.home, 'inbox')).sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* File an inbox item: as a profile fact, as a note on a project, or drop it.
|
|
314
|
+
* `text` overrides the stored wording (e.g. a cleaned-up version of a dictation).
|
|
315
|
+
*/
|
|
316
|
+
fileInbox(id, { as, project, text } = {}) {
|
|
317
|
+
const item = readJson(this.inboxPath(id), null);
|
|
318
|
+
if (!item) throw new Error(`No inbox item "${id}"`);
|
|
319
|
+
const body = text || item.text;
|
|
320
|
+
let result;
|
|
321
|
+
if (as === 'fact') result = this.remember(body);
|
|
322
|
+
else if (as === 'note') {
|
|
323
|
+
const p = this.getProject(project || item.project);
|
|
324
|
+
if (!p) throw new Error(`No project "${project || item.project}" to file the note under`);
|
|
325
|
+
this.addProjectNote(p.slug, body);
|
|
326
|
+
result = p.slug;
|
|
327
|
+
} else if (as !== 'dismiss') throw new Error('`as` must be fact, note or dismiss');
|
|
328
|
+
fs.rmSync(this.inboxPath(id), { force: true });
|
|
329
|
+
return { item, filedAs: as, result };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ---- snapshot --------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
get snapshotPath() {
|
|
335
|
+
return path.join(this.home, 'snapshot.json');
|
|
336
|
+
}
|
|
337
|
+
/** One-file summary for read-only clients (the watch app). Deterministic, so unchanged data means no new commit. */
|
|
338
|
+
buildSnapshot() {
|
|
339
|
+
const projects = this.listProjects().map((p) => ({
|
|
340
|
+
name: p.name,
|
|
341
|
+
slug: p.slug,
|
|
342
|
+
aliases: p.aliases || [],
|
|
343
|
+
tags: p.tags || [],
|
|
344
|
+
status: p.status || 'active',
|
|
345
|
+
description: p.description || '',
|
|
346
|
+
repo: p.repo || '',
|
|
347
|
+
devices: Object.keys(p.paths || {}),
|
|
348
|
+
notes: (p.notes || []).slice(-10),
|
|
349
|
+
lastActiveAt: p.lastActiveAt || p.updatedAt || p.createdAt || '',
|
|
350
|
+
}));
|
|
351
|
+
const all = this.listHandoffs({ status: 'all' });
|
|
352
|
+
const handoffs = [...all.filter((h) => h.status === 'open'), ...all.filter((h) => h.status !== 'open').slice(0, 10)];
|
|
353
|
+
const inbox = this.listInbox();
|
|
354
|
+
const stamps = [
|
|
355
|
+
...projects.map((p) => p.lastActiveAt),
|
|
356
|
+
...all.map((h) => h.doneAt || h.resumedAt || h.createdAt),
|
|
357
|
+
...inbox.map((i) => i.createdAt),
|
|
358
|
+
].filter(Boolean).sort();
|
|
359
|
+
return {
|
|
360
|
+
format: 1,
|
|
361
|
+
updatedAt: stamps[stamps.length - 1] || '',
|
|
362
|
+
profile: this.getProfile().replace(/<!--[\s\S]*?-->/g, '').replace(/\n{3,}/g, '\n\n').trim(),
|
|
363
|
+
projects,
|
|
364
|
+
handoffs,
|
|
365
|
+
inbox,
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
writeSnapshot() {
|
|
369
|
+
const next = JSON.stringify(this.buildSnapshot(), null, 1) + '\n';
|
|
370
|
+
let prev = '';
|
|
371
|
+
try {
|
|
372
|
+
prev = fs.readFileSync(this.snapshotPath, 'utf8');
|
|
373
|
+
} catch {}
|
|
374
|
+
if (prev !== next) fs.writeFileSync(this.snapshotPath, next);
|
|
375
|
+
return prev !== next;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// ---- export / import -------------------------------------------------
|
|
379
|
+
|
|
380
|
+
exportAll() {
|
|
381
|
+
return {
|
|
382
|
+
omnicontext: VERSION,
|
|
383
|
+
exportedAt: now(),
|
|
384
|
+
profile: this.getProfile(),
|
|
385
|
+
projects: this.listProjects(),
|
|
386
|
+
handoffs: this.listHandoffs({ status: 'all' }),
|
|
387
|
+
inbox: this.listInbox(),
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
/** Merge an export into this store. Existing records with the same id/slug are overwritten. */
|
|
391
|
+
importAll(data, { replaceProfile = false } = {}) {
|
|
392
|
+
if (!data || typeof data !== 'object' || !('projects' in data)) throw new Error('Not an OmniContext export');
|
|
393
|
+
if (data.profile && (replaceProfile || this.getProfile().trim() === PROFILE_TEMPLATE.trim())) this.setProfile(data.profile);
|
|
394
|
+
for (const p of data.projects || []) if (p?.slug) writeJson(this.projectPath(p.slug), p);
|
|
395
|
+
for (const h of data.handoffs || []) if (h?.id) writeJson(this.handoffPath(h.id), h);
|
|
396
|
+
for (const i of data.inbox || []) if (i?.id) writeJson(this.inboxPath(i.id), i);
|
|
397
|
+
return { projects: (data.projects || []).length, handoffs: (data.handoffs || []).length, inbox: (data.inbox || []).length };
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function newId() {
|
|
402
|
+
const stamp = now().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
|
|
403
|
+
return `${stamp}-${crypto.randomBytes(2).toString('hex')}`;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Branch, commit and uncommitted files of the repo at `cwd`, so another device can pick up the same state. */
|
|
407
|
+
export function gitStateOf(cwd) {
|
|
408
|
+
const git = (args) => {
|
|
409
|
+
try {
|
|
410
|
+
return execFileSync('git', args, { cwd, encoding: 'utf8', timeout: 4000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
411
|
+
} catch {
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
const commit = git(['rev-parse', '--short', 'HEAD']);
|
|
416
|
+
if (!commit) return null;
|
|
417
|
+
const status = git(['status', '--porcelain']) || '';
|
|
418
|
+
const upstream = git(['rev-list', '--count', '@{u}..HEAD']);
|
|
419
|
+
return {
|
|
420
|
+
branch: git(['rev-parse', '--abbrev-ref', 'HEAD']) || '',
|
|
421
|
+
commit,
|
|
422
|
+
remote: git(['remote', 'get-url', 'origin']) || '',
|
|
423
|
+
uncommitted: status.split('\n').filter(Boolean).slice(0, 30).map((l) => l.slice(3)),
|
|
424
|
+
unpushed: upstream === null ? null : Number(upstream),
|
|
425
|
+
};
|
|
276
426
|
}
|
|
277
427
|
|
|
278
428
|
export function normalizeRepo(url) {
|
package/src/sync.js
CHANGED
|
@@ -4,6 +4,7 @@ import { execFileSync } from 'node:child_process';
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import os from 'node:os';
|
|
7
|
+
import { Store } from './store.js';
|
|
7
8
|
|
|
8
9
|
function git(home, args, { timeout = 30000, allowFail = false } = {}) {
|
|
9
10
|
try {
|
|
@@ -53,6 +54,9 @@ function ensureRepo(home) {
|
|
|
53
54
|
}
|
|
54
55
|
|
|
55
56
|
function commitAll(home, device) {
|
|
57
|
+
try {
|
|
58
|
+
new Store(home).writeSnapshot();
|
|
59
|
+
} catch {}
|
|
56
60
|
git(home, ['add', '-A']);
|
|
57
61
|
if (git(home, ['status', '--porcelain'])) {
|
|
58
62
|
git(home, ['commit', '-q', '-m', `sync from ${device} ${new Date().toISOString()}`]);
|
|
@@ -87,6 +91,8 @@ export function sync(home, device = os.hostname(), { allowUnrelated = false, tim
|
|
|
87
91
|
return { ok: false, reason: 'merge failed; resolve manually in ' + home };
|
|
88
92
|
}
|
|
89
93
|
pulled = before !== git(home, ['rev-parse', 'HEAD'], { allowFail: true });
|
|
94
|
+
// The merge may have brought in other devices' records; refresh the snapshot so it covers them.
|
|
95
|
+
if (pulled) commitAll(home, device);
|
|
90
96
|
}
|
|
91
97
|
} else {
|
|
92
98
|
return { ok: false, committed, reason: 'could not reach remote (offline?)' };
|
|
@@ -104,6 +110,7 @@ export function pull(home, { timeout = 8000 } = {}) {
|
|
|
104
110
|
if (!git(home, ['rev-parse', '-q', '--verify', 'origin/main'], { allowFail: true })) return { ok: true };
|
|
105
111
|
const ok = git(home, ['merge', '-q', '--no-edit', '-X', 'ours', 'origin/main'], { allowFail: true }) !== null;
|
|
106
112
|
if (!ok) git(home, ['merge', '--abort'], { allowFail: true });
|
|
113
|
+
else commitAll(home, os.hostname());
|
|
107
114
|
return { ok };
|
|
108
115
|
}
|
|
109
116
|
|