@aaryanbindage/omnicontext 0.1.3 → 0.3.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/src/store.js CHANGED
@@ -4,14 +4,18 @@
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';
16
+ import { buildGraph } from './graph.js';
13
17
 
14
- export const VERSION = '0.1.3';
18
+ export const VERSION = '0.3.0';
15
19
 
16
20
  export function defaultHome() {
17
21
  return process.env.OMNICONTEXT_HOME || path.join(os.homedir(), '.omnicontext');
@@ -76,6 +80,7 @@ export class Store {
76
80
  ensure() {
77
81
  fs.mkdirSync(path.join(this.home, 'projects'), { recursive: true });
78
82
  fs.mkdirSync(path.join(this.home, 'handoffs'), { recursive: true });
83
+ fs.mkdirSync(path.join(this.home, 'inbox'), { recursive: true });
79
84
  if (!fs.existsSync(this.profilePath)) fs.writeFileSync(this.profilePath, PROFILE_TEMPLATE);
80
85
  const gitignore = path.join(this.home, '.gitignore');
81
86
  if (!fs.existsSync(gitignore)) fs.writeFileSync(gitignore, 'local.json\n*.tmp\n');
@@ -130,6 +135,19 @@ export class Store {
130
135
  this.setProfile(lines.join('\n'));
131
136
  return line;
132
137
  }
138
+ /** Remove profile bullet lines containing `text` (case-insensitive). Returns the removed lines. */
139
+ forget(text) {
140
+ const q = String(text).trim().toLowerCase();
141
+ if (q.length < 3) throw new Error('Give at least 3 characters of the fact to forget');
142
+ const removed = [];
143
+ const kept = this.getProfile().split('\n').filter((l) => {
144
+ const hit = /^\s*[-*]\s/.test(l) && l.toLowerCase().includes(q);
145
+ if (hit) removed.push(l.trim());
146
+ return !hit;
147
+ });
148
+ if (removed.length) this.setProfile(kept.join('\n'));
149
+ return removed;
150
+ }
133
151
 
134
152
  // ---- projects --------------------------------------------------------
135
153
 
@@ -229,9 +247,9 @@ export class Store {
229
247
  }
230
248
  saveHandoff({ project, title, summary, nextSteps = [], files = [], cwd = '' }) {
231
249
  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;
250
+ const id = newId();
251
+ let proj = project ? this.getProject(project) : null;
252
+ if (!proj && cwd) proj = this.projectForCwd(cwd);
235
253
  const h = {
236
254
  id,
237
255
  title: title || summary.split('\n')[0].slice(0, 80),
@@ -244,6 +262,8 @@ export class Store {
244
262
  status: 'open',
245
263
  createdAt: now(),
246
264
  };
265
+ const g = cwd ? gitStateOf(cwd) : null;
266
+ if (g) h.git = g;
247
267
  writeJson(this.handoffPath(id), h);
248
268
  if (proj) this.touchProject(proj.slug);
249
269
  return h;
@@ -273,6 +293,146 @@ export class Store {
273
293
  deleteHandoff(id) {
274
294
  fs.rmSync(this.handoffPath(id), { force: true });
275
295
  }
296
+
297
+ // ---- inbox -----------------------------------------------------------
298
+
299
+ inboxPath(id) {
300
+ return path.join(this.home, 'inbox', `${String(id).replace(/[^\w-]/g, '')}.json`);
301
+ }
302
+ /** Quick capture to file later: a thought dictated on the watch, a note from the CLI. */
303
+ capture(text, { project = '', source } = {}) {
304
+ const t = String(text ?? '').trim();
305
+ if (!t) throw new Error('Nothing to capture');
306
+ const item = { id: newId(), text: t, project, source: source || this.device, createdAt: now() };
307
+ writeJson(this.inboxPath(item.id), item);
308
+ return item;
309
+ }
310
+ listInbox() {
311
+ return listJson(path.join(this.home, 'inbox')).sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
312
+ }
313
+ /**
314
+ * File an inbox item: as a profile fact, as a note on a project, or drop it.
315
+ * `text` overrides the stored wording (e.g. a cleaned-up version of a dictation).
316
+ */
317
+ fileInbox(id, { as, project, text } = {}) {
318
+ const item = readJson(this.inboxPath(id), null);
319
+ if (!item) throw new Error(`No inbox item "${id}"`);
320
+ const body = text || item.text;
321
+ let result;
322
+ if (as === 'fact') result = this.remember(body);
323
+ else if (as === 'note') {
324
+ const p = this.getProject(project || item.project);
325
+ if (!p) throw new Error(`No project "${project || item.project}" to file the note under`);
326
+ this.addProjectNote(p.slug, body);
327
+ result = p.slug;
328
+ } else if (as !== 'dismiss') throw new Error('`as` must be fact, note or dismiss');
329
+ fs.rmSync(this.inboxPath(id), { force: true });
330
+ return { item, filedAs: as, result };
331
+ }
332
+
333
+ // ---- snapshot --------------------------------------------------------
334
+
335
+ get snapshotPath() {
336
+ return path.join(this.home, 'snapshot.json');
337
+ }
338
+ /** One-file summary for read-only clients (the watch app). Deterministic, so unchanged data means no new commit. */
339
+ buildSnapshot() {
340
+ const projects = this.listProjects().map((p) => ({
341
+ name: p.name,
342
+ slug: p.slug,
343
+ aliases: p.aliases || [],
344
+ tags: p.tags || [],
345
+ status: p.status || 'active',
346
+ description: p.description || '',
347
+ repo: p.repo || '',
348
+ devices: Object.keys(p.paths || {}),
349
+ notes: (p.notes || []).slice(-10),
350
+ lastActiveAt: p.lastActiveAt || p.updatedAt || p.createdAt || '',
351
+ }));
352
+ const all = this.listHandoffs({ status: 'all' });
353
+ const handoffs = [...all.filter((h) => h.status === 'open'), ...all.filter((h) => h.status !== 'open').slice(0, 10)];
354
+ const inbox = this.listInbox();
355
+ const stamps = [
356
+ ...projects.map((p) => p.lastActiveAt),
357
+ ...all.map((h) => h.doneAt || h.resumedAt || h.createdAt),
358
+ ...inbox.map((i) => i.createdAt),
359
+ ].filter(Boolean).sort();
360
+ return {
361
+ format: 1,
362
+ updatedAt: stamps[stamps.length - 1] || '',
363
+ profile: this.getProfile().replace(/<!--[\s\S]*?-->/g, '').replace(/\n{3,}/g, '\n\n').trim(),
364
+ projects,
365
+ handoffs,
366
+ inbox,
367
+ graph: compactGraph(buildGraph(this)),
368
+ };
369
+ }
370
+ writeSnapshot() {
371
+ const next = JSON.stringify(this.buildSnapshot(), null, 1) + '\n';
372
+ let prev = '';
373
+ try {
374
+ prev = fs.readFileSync(this.snapshotPath, 'utf8');
375
+ } catch {}
376
+ if (prev !== next) fs.writeFileSync(this.snapshotPath, next);
377
+ return prev !== next;
378
+ }
379
+
380
+ // ---- export / import -------------------------------------------------
381
+
382
+ exportAll() {
383
+ return {
384
+ omnicontext: VERSION,
385
+ exportedAt: now(),
386
+ profile: this.getProfile(),
387
+ projects: this.listProjects(),
388
+ handoffs: this.listHandoffs({ status: 'all' }),
389
+ inbox: this.listInbox(),
390
+ };
391
+ }
392
+ /** Merge an export into this store. Existing records with the same id/slug are overwritten. */
393
+ importAll(data, { replaceProfile = false } = {}) {
394
+ if (!data || typeof data !== 'object' || !('projects' in data)) throw new Error('Not an OmniContext export');
395
+ if (data.profile && (replaceProfile || this.getProfile().trim() === PROFILE_TEMPLATE.trim())) this.setProfile(data.profile);
396
+ for (const p of data.projects || []) if (p?.slug) writeJson(this.projectPath(p.slug), p);
397
+ for (const h of data.handoffs || []) if (h?.id) writeJson(this.handoffPath(h.id), h);
398
+ for (const i of data.inbox || []) if (i?.id) writeJson(this.inboxPath(i.id), i);
399
+ return { projects: (data.projects || []).length, handoffs: (data.handoffs || []).length, inbox: (data.inbox || []).length };
400
+ }
401
+ }
402
+
403
+ /** Graph in a compact form for the watch: nodes [id, type, label], edges [source, target, kind]. */
404
+ function compactGraph(g) {
405
+ return {
406
+ nodes: g.nodes.map((n) => [n.id, n.type, n.label]),
407
+ edges: g.edges.map((e) => [e.source, e.target, e.kind]),
408
+ };
409
+ }
410
+
411
+ function newId() {
412
+ const stamp = now().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
413
+ return `${stamp}-${crypto.randomBytes(2).toString('hex')}`;
414
+ }
415
+
416
+ /** Branch, commit and uncommitted files of the repo at `cwd`, so another device can pick up the same state. */
417
+ export function gitStateOf(cwd) {
418
+ const git = (args) => {
419
+ try {
420
+ return execFileSync('git', args, { cwd, encoding: 'utf8', timeout: 4000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
421
+ } catch {
422
+ return null;
423
+ }
424
+ };
425
+ const commit = git(['rev-parse', '--short', 'HEAD']);
426
+ if (!commit) return null;
427
+ const status = git(['status', '--porcelain']) || '';
428
+ const upstream = git(['rev-list', '--count', '@{u}..HEAD']);
429
+ return {
430
+ branch: git(['rev-parse', '--abbrev-ref', 'HEAD']) || '',
431
+ commit,
432
+ remote: git(['remote', 'get-url', 'origin']) || '',
433
+ uncommitted: status.split('\n').filter(Boolean).slice(0, 30).map((l) => l.slice(3)),
434
+ unpushed: upstream === null ? null : Number(upstream),
435
+ };
276
436
  }
277
437
 
278
438
  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