@amoree-code/ocean 1.6.2 → 1.8.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.
Files changed (84) hide show
  1. package/README.md +10 -1
  2. package/dist/application/clients/desktop-watcher.js +234 -0
  3. package/dist/application/clients/opencode-plugin.js +4 -3
  4. package/dist/application/layout/layout-plan.js +1 -0
  5. package/dist/application/onboarding/steps.js +20 -1
  6. package/dist/infrastructure/desktop/claude-export.js +84 -0
  7. package/dist/infrastructure/desktop/desktop-chat.js +165 -0
  8. package/dist/infrastructure/desktop/indexeddb.js +158 -0
  9. package/dist/infrastructure/desktop/leveldb.js +247 -0
  10. package/dist/infrastructure/desktop/snappy.js +74 -0
  11. package/dist/infrastructure/process/service.js +8 -0
  12. package/dist/interfaces/cli/brief-command.js +17 -0
  13. package/dist/interfaces/cli/capture-command.js +1 -1
  14. package/dist/interfaces/cli/clients-command.js +15 -2
  15. package/dist/interfaces/cli/command-registry.js +31 -2
  16. package/dist/interfaces/cli/desktop-command.js +124 -0
  17. package/dist/interfaces/cli/distill-command.js +36 -0
  18. package/dist/interfaces/cli/express-command.js +18 -0
  19. package/dist/interfaces/cli/harvest-command.js +58 -0
  20. package/dist/interfaces/cli/help-command.js +34 -2
  21. package/dist/interfaces/cli/interests-command.js +33 -0
  22. package/dist/interfaces/cli/memory-command.js +37 -3
  23. package/dist/interfaces/cli/note-command.js +7 -0
  24. package/dist/interfaces/cli/setup-command.js +2 -1
  25. package/dist/interfaces/cli/telemetry-command.js +23 -0
  26. package/node_modules/@ocean/brain/dist/brain/brain-reindex.js +4 -1
  27. package/node_modules/@ocean/brain/dist/brain/brain-service.js +11 -1
  28. package/node_modules/@ocean/brain/dist/memory/brain-dump.js +73 -24
  29. package/node_modules/@ocean/brain/dist/memory/fact-routing.js +54 -0
  30. package/node_modules/@ocean/brain/dist/memory/frontmatter-flatten.js +89 -0
  31. package/node_modules/@ocean/brain/dist/memory/lessons.js +20 -0
  32. package/node_modules/@ocean/brain/dist/memory/memory-paths.js +3 -1
  33. package/node_modules/@ocean/brain/dist/memory/memory-review.js +19 -2
  34. package/node_modules/@ocean/brain/dist/memory/memory-write.js +45 -3
  35. package/node_modules/@ocean/brain/dist/memory/people.js +70 -0
  36. package/node_modules/@ocean/brain/dist/memory/routing.json +39 -0
  37. package/node_modules/@ocean/brain/dist/memory/session-facts.js +7 -1
  38. package/node_modules/@ocean/brain/dist/memory/session-promotion.js +1 -1
  39. package/node_modules/@ocean/brain/package.json +1 -1
  40. package/node_modules/@ocean/context/package.json +1 -1
  41. package/node_modules/@ocean/core/dist/shared/paths.js +7 -0
  42. package/node_modules/@ocean/core/package.json +1 -1
  43. package/node_modules/@ocean/loop/dist/handoff/handoff-service.js +5 -1
  44. package/node_modules/@ocean/loop/dist/hooks/desktop-facts.js +154 -0
  45. package/node_modules/@ocean/loop/dist/hooks/session-end-hook.js +1 -1
  46. package/node_modules/@ocean/loop/package.json +1 -1
  47. package/node_modules/@ocean/market/package.json +1 -1
  48. package/node_modules/@ocean/services/dist/brief/brief.js +218 -0
  49. package/node_modules/@ocean/services/dist/brief/interest-discovery.js +236 -0
  50. package/node_modules/@ocean/services/dist/brief/source-registry.json +35 -0
  51. package/node_modules/@ocean/services/dist/distill/distill.js +258 -0
  52. package/node_modules/@ocean/services/dist/doctor/workspace-doctor.js +129 -8
  53. package/node_modules/@ocean/services/dist/express/express.js +99 -0
  54. package/node_modules/@ocean/services/dist/harvest/harvest.js +453 -0
  55. package/node_modules/@ocean/services/dist/infrastructure/mcp/ocean-server.js +17 -1
  56. package/node_modules/@ocean/services/dist/journey/telemetry.js +81 -0
  57. package/node_modules/@ocean/services/dist/obsidian/folder-templates.js +82 -0
  58. package/node_modules/@ocean/services/dist/onboarding/onboarding.js +62 -0
  59. package/node_modules/@ocean/services/package.json +1 -1
  60. package/ocean-marketplace.json +82 -28
  61. package/package.json +7 -7
  62. package/skills/core/daily-harvest/SKILL.md +72 -0
  63. package/skills/core/memory-review/SKILL.md +53 -0
  64. package/skills/core/weekly-review/SKILL.md +24 -0
  65. package/skills/index.json +18 -0
  66. package/templates/workspace/02-personal/education/study/study.base +15 -0
  67. package/templates/workspace/02-personal/milestones/milestones.base +14 -0
  68. package/templates/workspace/02-personal/people/people.base +18 -0
  69. package/templates/workspace/06-templates/TEMPLATES.md +12 -0
  70. package/templates/workspace/06-templates/capture.md +9 -0
  71. package/templates/workspace/06-templates/daily.md +13 -0
  72. package/templates/workspace/06-templates/decision.md +8 -0
  73. package/templates/workspace/06-templates/failure.md +13 -0
  74. package/templates/workspace/06-templates/intelligence.md +7 -0
  75. package/templates/workspace/06-templates/interest.md +13 -0
  76. package/templates/workspace/06-templates/lesson.md +16 -0
  77. package/templates/workspace/06-templates/milestone.md +10 -0
  78. package/templates/workspace/06-templates/note.md +8 -0
  79. package/templates/workspace/06-templates/person.md +15 -0
  80. package/templates/workspace/06-templates/session.md +10 -0
  81. package/templates/workspace/06-templates/solution.md +14 -0
  82. package/templates/workspace/06-templates/study.md +14 -0
  83. package/templates/workspace/07-notes/.gitkeep +0 -0
  84. package/templates/workspace/MANIFEST.json +14 -0
@@ -0,0 +1,453 @@
1
+ import { copyFile, mkdir, readdir, readFile, rename, rm, } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { syncMemoryIndexes } from "@ocean/brain/memory/index-sync.js";
4
+ import { containsKnownSecret } from "@ocean/core/domain/redaction/redaction.js";
5
+ import { atomicWrite, parseFrontmatter } from "@ocean/core/shared/fs-utils.js";
6
+ import { DAILY_DIR, KNOWLEDGE_DIR, oceanPath, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
7
+ import { section } from "../distill/distill.js";
8
+ // The daily harvest (T-316): every session of a day, from every AI client, becomes one summary in
9
+ // that day's note, and what the sessions decided, fixed and learned is filed into 05-knowledge on
10
+ // its own, with no review step (owner's decision, 2026-11-16). Safety instead of review: a record
11
+ // that already says the same thing is strengthened, not duplicated; every write is in a ledger
12
+ // with the record's previous version, and `ocean harvest undo <date>` takes a day back. Nothing
13
+ // here calls a model: the judgement work (legacy records, imports, corrections that become rules)
14
+ // is the daily-harvest skill's.
15
+ const MARK_START = "<!-- ocean:harvest:start -->";
16
+ const MARK_END = "<!-- ocean:harvest:end -->";
17
+ const DAY_MS = 24 * 60 * 60 * 1000;
18
+ const MAX_SESSION_MS = 8 * 60 * 60 * 1000;
19
+ const MIN_ITEM = 25;
20
+ const SAME_TITLE = 0.6;
21
+ // Where each kind of harvested item is filed, and the record type it carries.
22
+ const KINDS = {
23
+ decision: { heading: "Decisions", folder: "decisions" },
24
+ solution: { heading: "Problems → fixes", folder: "solutions" },
25
+ discovery: { heading: "Learned", folder: "discoveries" },
26
+ };
27
+ const relativeOf = (file) => path.relative(oceanPath(), file).split(path.sep).join("/");
28
+ const sessionsRoot = () => oceanPath(DAILY_DIR, "sessions");
29
+ const stateDir = (...parts) => oceanPath(SYSTEM_DIR, "state", "harvest", ...parts);
30
+ async function markdownIn(dir, skipArchive = true) {
31
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
32
+ const files = [];
33
+ for (const entry of entries) {
34
+ if (entry.name.startsWith("."))
35
+ continue;
36
+ if (skipArchive && entry.name === "archive")
37
+ continue;
38
+ const file = path.join(dir, entry.name);
39
+ if (entry.isDirectory())
40
+ files.push(...(await markdownIn(file, skipArchive)));
41
+ else if (entry.name.endsWith(".md"))
42
+ files.push(file);
43
+ }
44
+ return files.sort();
45
+ }
46
+ export async function daySessions(date) {
47
+ const sessions = [];
48
+ for (const file of await markdownIn(path.join(sessionsRoot(), date.slice(0, 7)))) {
49
+ const text = (await readFile(file, "utf8")).replace(/\r\n/g, "\n");
50
+ const fields = parseFrontmatter(text);
51
+ if (fields.type !== "session" || fields.date !== date)
52
+ continue;
53
+ sessions.push({
54
+ file,
55
+ relative: relativeOf(file),
56
+ title: /^# (.+)$/m.exec(text)?.[1]?.trim() ?? path.basename(file, ".md"),
57
+ date,
58
+ project: fields.project || "",
59
+ provider: fields.provider || "",
60
+ status: fields.status || "",
61
+ text,
62
+ });
63
+ }
64
+ return sessions;
65
+ }
66
+ const clean = (text) => text
67
+ .replace(/^[-*]\s+/, "")
68
+ .replace(/\s+/g, " ")
69
+ .trim();
70
+ // A section's items: its bullets, or the whole paragraph when it has none. Placeholders and
71
+ // fragments too short to stand alone are dropped.
72
+ export function sectionItems(text, heading) {
73
+ const body = section(text, heading);
74
+ if (!body)
75
+ return [];
76
+ const lines = body.split("\n").filter((line) => line.trim());
77
+ const bullets = lines.filter((line) => /^\s*[-*]\s+/.test(line));
78
+ const items = bullets.length ? bullets.map(clean) : [clean(body)];
79
+ return items.filter((item) => item.length >= MIN_ITEM &&
80
+ !/^(none|n\/a|nothing|no )/i.test(item) &&
81
+ !containsKnownSecret(item));
82
+ }
83
+ // A record written with sections (Goal, Outcome, Decisions, …) can be mined here; an older dump
84
+ // (one "What happened" paragraph) needs the skill's reading.
85
+ export const structured = (session) => /^## (Goal|Outcome|Decisions|Learned)$/m.test(session.text);
86
+ export function harvestItems(sessions) {
87
+ const items = [];
88
+ for (const session of sessions)
89
+ for (const kind of Object.keys(KINDS))
90
+ for (const text of sectionItems(session.text, KINDS[kind].heading))
91
+ items.push({ kind, text, session });
92
+ return items;
93
+ }
94
+ // What the owner said to correct an AI ("no, not like that", "غلط", "don't …"): candidates for a
95
+ // standing rule. Read from his own turns only, never the model's.
96
+ const CORRECTION = /(^|[\s,.!])(no,|nope|wrong|don't|do not|stop |not like that|i said|instead of)|(^|\s)(لا |غلط|مو هيچ|مو هيج|مو هيك|ما اريد|لا تسوي|ليش سويت|گلتلك|قلتلك)/i;
97
+ export function detectCorrections(events) {
98
+ const found = [];
99
+ for (const event of events) {
100
+ if (event.type !== "user_input")
101
+ continue;
102
+ const text = event.data.replace(/\s+/g, " ").trim();
103
+ if (!text || text.length > 600 || containsKnownSecret(text))
104
+ continue;
105
+ // Text a client injects as the user's turn (a skill body, a command, a notice) is not his.
106
+ if (/^(base directory for this skill|<|caveat:|\[request interrupted|this session is being continued)/i.test(text))
107
+ continue;
108
+ if (CORRECTION.test(text))
109
+ found.push(text.slice(0, 160));
110
+ }
111
+ return found;
112
+ }
113
+ const localDay = (iso) => {
114
+ const day = new Date(iso);
115
+ return `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, "0")}-${String(day.getDate()).padStart(2, "0")}`;
116
+ };
117
+ // Minutes per project for sessions started that day: from the start to the latest of its close,
118
+ // its last update and its last event, each session capped at eight hours. A session the store saw
119
+ // only for seconds counts nothing, and a project with nothing recorded is left out.
120
+ export function minutesByProject(sessions, date, eventsOf = () => []) {
121
+ const minutes = {};
122
+ for (const session of sessions) {
123
+ if (localDay(session.createdAt) !== date)
124
+ continue;
125
+ const ends = [
126
+ session.closedAt,
127
+ session.updatedAt,
128
+ ...eventsOf(session.sessionId).map((event) => event.createdAt),
129
+ ]
130
+ .map((time) => Date.parse(time ?? ""))
131
+ .filter((time) => !Number.isNaN(time));
132
+ const span = Math.min(Math.max(0, Math.max(...ends, 0) - Date.parse(session.createdAt)), MAX_SESSION_MS);
133
+ const counted = Math.round(span / 60_000);
134
+ if (!counted)
135
+ continue;
136
+ const project = session.projectId || path.basename(session.workingDirectory) || "other";
137
+ minutes[project] = (minutes[project] ?? 0) + counted;
138
+ }
139
+ return minutes;
140
+ }
141
+ const slug = (text) => text
142
+ .toLowerCase()
143
+ .replace(/`[^`]*`/g, (code) => code.slice(1, -1))
144
+ .replace(/[^a-z0-9؀-ۿ]+/g, " ")
145
+ .trim()
146
+ .split(" ")
147
+ .filter(Boolean)
148
+ .slice(0, 8)
149
+ .join("-")
150
+ .slice(0, 80);
151
+ const words = (text) => new Set(text
152
+ .toLowerCase()
153
+ .split(/[^a-z0-9؀-ۿ]+/)
154
+ .filter((word) => word.length > 2));
155
+ function similarity(a, b) {
156
+ const left = words(a);
157
+ const right = words(b);
158
+ // Too few words to tell two statements apart: never the same record.
159
+ if (Math.min(left.size, right.size) < 3)
160
+ return 0;
161
+ let shared = 0;
162
+ for (const word of left)
163
+ if (right.has(word))
164
+ shared++;
165
+ return shared / Math.min(left.size, right.size);
166
+ }
167
+ const titleOf = (text) => {
168
+ const sentence = text.split(/(?<=[.!?])\s/)[0] ?? text;
169
+ return sentence.length > 90 ? `${sentence.slice(0, 87).trim()}…` : sentence;
170
+ };
171
+ function setField(text, key, value) {
172
+ const end = text.startsWith("---\n") ? text.indexOf("\n---", 3) : -1;
173
+ if (end < 0)
174
+ return text;
175
+ const head = text.slice(0, end);
176
+ const line = new RegExp(`^${key}:.*$`, "m");
177
+ const next = line.test(head)
178
+ ? head.replace(line, `${key}: ${value}`)
179
+ : `${head}\n${key}: ${value}`;
180
+ return next + text.slice(end);
181
+ }
182
+ // One harvested item into 05-knowledge: the record that already says it gains this day as
183
+ // evidence and a fresh last_verified; otherwise a new record. Returns the file and what happened.
184
+ async function fileItem(item, ledger) {
185
+ const folder = oceanPath(KNOWLEDGE_DIR, KINDS[item.kind].folder);
186
+ const title = titleOf(item.text);
187
+ let match = null;
188
+ for (const name of await readdir(folder).catch(() => [])) {
189
+ if (!name.endsWith(".md"))
190
+ continue;
191
+ const existing = await readFile(path.join(folder, name), "utf8");
192
+ const heading = /^# (.+)$/m.exec(existing)?.[1] ?? name;
193
+ if (name === `${slug(item.text)}.md` ||
194
+ similarity(heading, title) >= SAME_TITLE) {
195
+ match = path.join(folder, name);
196
+ break;
197
+ }
198
+ }
199
+ const link = `- ${item.session.date}: [${item.session.title.replace(/[[\]]/g, "")}](${path
200
+ .relative(folder, item.session.file)
201
+ .split(path.sep)
202
+ .join("/")})`;
203
+ if (match) {
204
+ const current = await readFile(match, "utf8");
205
+ if (current.includes(link))
206
+ return { file: relativeOf(match), action: "same" };
207
+ const copy = stateDir("versions", ledger.date, relativeOf(match));
208
+ await mkdir(path.dirname(copy), { recursive: true });
209
+ await copyFile(match, copy);
210
+ ledger.updated.push({ file: relativeOf(match), copy: relativeOf(copy) });
211
+ let next = setField(current, "last_verified", item.session.date);
212
+ next = /^## Evidence$/m.test(next)
213
+ ? next.replace(/^## Evidence\n+/m, (head) => `${head}${link}\n`)
214
+ : `${next.replace(/\n*$/, "")}\n\n## Evidence\n\n${link}\n`;
215
+ await atomicWrite(match, next);
216
+ return { file: relativeOf(match), action: "strengthened" };
217
+ }
218
+ const file = path.join(folder, `${slug(item.text) || "untitled"}.md`);
219
+ const body = [
220
+ "---",
221
+ `type: ${item.kind}`,
222
+ `title: ${JSON.stringify(title)}`,
223
+ "status: active",
224
+ "origin: harvested",
225
+ `source: ${JSON.stringify(`session:${item.session.provider || "unknown"}`)}`,
226
+ ...(item.session.project
227
+ ? [`project: ${JSON.stringify(item.session.project)}`]
228
+ : []),
229
+ `created: ${item.session.date}`,
230
+ `last_verified: ${item.session.date}`,
231
+ "---",
232
+ "",
233
+ `# ${title}`,
234
+ "",
235
+ item.text,
236
+ "",
237
+ "## Evidence",
238
+ "",
239
+ link,
240
+ "",
241
+ ].join("\n");
242
+ await mkdir(folder, { recursive: true });
243
+ await atomicWrite(file, body);
244
+ ledger.created.push(relativeOf(file));
245
+ return { file: relativeOf(file), action: "created" };
246
+ }
247
+ function dayBlock(input) {
248
+ const link = (session) => `[${session.title.replace(/[[\]]/g, "")}](${path
249
+ .relative(oceanPath(DAILY_DIR), session.file)
250
+ .split(path.sep)
251
+ .join("/")})`;
252
+ const byProvider = new Map();
253
+ for (const session of input.sessions)
254
+ byProvider.set(session.provider || "unknown", (byProvider.get(session.provider || "unknown") ?? 0) + 1);
255
+ const kind = (k, label) => {
256
+ const items = input.items.filter((item) => item.kind === k);
257
+ return items.length
258
+ ? [
259
+ "",
260
+ `### ${label}`,
261
+ "",
262
+ ...items.map((item) => {
263
+ const filed = input.filed.get(item);
264
+ return `- ${item.text}${filed ? ` → \`${filed}\`` : ""} (${link(item.session)})`;
265
+ }),
266
+ ]
267
+ : [];
268
+ };
269
+ const next = input.sessions.flatMap((session) => sectionItems(session.text, "Next").map((item) => `- ${item} (${link(session)})`));
270
+ const minutes = Object.entries(input.minutes).sort((a, b) => b[1] - a[1]);
271
+ return [
272
+ MARK_START,
273
+ "## Day summary",
274
+ "",
275
+ `${input.sessions.length} session(s): ${[...byProvider].map(([provider, n]) => `${provider} ${n}`).join(", ") || "none"}.`,
276
+ "",
277
+ "### Sessions",
278
+ "",
279
+ ...(input.sessions.length
280
+ ? input.sessions.map((session) => `- ${link(session)} — ${[session.project, session.provider, session.status].filter(Boolean).join(" · ")}`)
281
+ : ["- none"]),
282
+ ...kind("decision", "Decisions"),
283
+ ...kind("solution", "Problems → fixes"),
284
+ ...kind("discovery", "Learned"),
285
+ ...(next.length ? ["", "### Open next", "", ...next] : []),
286
+ ...(input.corrections.length
287
+ ? [
288
+ "",
289
+ "### Corrections you made",
290
+ "",
291
+ ...input.corrections.map((text) => `- ${text}`),
292
+ ]
293
+ : []),
294
+ ...(minutes.length
295
+ ? [
296
+ "",
297
+ "### Time",
298
+ "",
299
+ ...minutes.map(([project, n]) => `- ${project}: ${Math.floor(n / 60)}h ${String(n % 60).padStart(2, "0")}m`),
300
+ ]
301
+ : []),
302
+ ...(input.filed.size
303
+ ? [
304
+ "",
305
+ `Filed into knowledge on its own; undo with \`ocean harvest undo ${input.date}\`.`,
306
+ ]
307
+ : []),
308
+ MARK_END,
309
+ ].join("\n");
310
+ }
311
+ // The day's note keeps what the owner wrote: only the block between the markers is Ocean's.
312
+ export function withBlock(note, date, block) {
313
+ if (note === null)
314
+ return `---\ntype: daily\ndate: ${date}\n---\n\n# ${date}\n\n${block}\n`;
315
+ const start = note.indexOf(MARK_START);
316
+ const end = note.indexOf(MARK_END);
317
+ if (start >= 0 && end > start)
318
+ return note.slice(0, start) + block + note.slice(end + MARK_END.length);
319
+ return `${note.replace(/\n*$/, "")}\n\n${block}\n`;
320
+ }
321
+ const ledgerFile = (date) => stateDir("ledger", `${date}.json`);
322
+ export async function harvestDay(options) {
323
+ const { date } = options;
324
+ const sessions = await daySessions(date);
325
+ const items = harvestItems(sessions);
326
+ const ofDay = (options.store?.sessions ?? []).filter((session) => localDay(session.createdAt) === date);
327
+ const corrections = [
328
+ ...new Set(ofDay.flatMap((session) => detectCorrections(options.store?.eventsOf(session.sessionId) ?? []))),
329
+ ];
330
+ const minutes = minutesByProject(ofDay, date, (id) => options.store ? options.store.eventsOf(id) : []);
331
+ const result = {
332
+ date,
333
+ sessions: sessions.length,
334
+ note: null,
335
+ created: [],
336
+ strengthened: [],
337
+ corrections,
338
+ minutes,
339
+ };
340
+ if (!sessions.length && !ofDay.length)
341
+ return result;
342
+ result.note = `${DAILY_DIR}/${date}.md`;
343
+ if (!options.apply) {
344
+ result.created = items.map((item) => `${KINDS[item.kind].folder}: ${titleOf(item.text)}`);
345
+ return result;
346
+ }
347
+ const previous = JSON.parse(await readFile(ledgerFile(date), "utf8").catch(() => "null")) ?? { date, created: [], updated: [] };
348
+ const filed = new Map();
349
+ for (const item of items) {
350
+ const { file, action } = await fileItem(item, previous);
351
+ filed.set(item, file);
352
+ if (action === "created")
353
+ result.created.push(file);
354
+ if (action === "strengthened")
355
+ result.strengthened.push(file);
356
+ }
357
+ await mkdir(path.dirname(ledgerFile(date)), { recursive: true });
358
+ await atomicWrite(ledgerFile(date), `${JSON.stringify(previous, null, 2)}\n`);
359
+ const noteFile = oceanPath(result.note);
360
+ const note = await readFile(noteFile, "utf8").catch(() => null);
361
+ await atomicWrite(noteFile, withBlock(note, date, dayBlock({ sessions, items, filed, corrections, minutes, date })));
362
+ // A legacy record (no sections) is summarized here but read by the daily-harvest skill, which
363
+ // marks it once it has mined it.
364
+ for (const session of sessions.filter(structured))
365
+ await atomicWrite(session.file, setField(session.text, "harvested", date));
366
+ if (result.created.length || result.strengthened.length)
367
+ await syncMemoryIndexes(true);
368
+ return result;
369
+ }
370
+ // Days before today whose session records have not been harvested yet (the service runs this).
371
+ export async function pendingDays(today, lookbackDays = 45) {
372
+ const cutoff = new Date(Date.parse(today) - lookbackDays * DAY_MS)
373
+ .toISOString()
374
+ .slice(0, 10);
375
+ const days = new Set();
376
+ for (const file of await markdownIn(sessionsRoot())) {
377
+ const head = (await readFile(file, "utf8")).slice(0, 4096);
378
+ const fields = parseFrontmatter(head);
379
+ if (fields.type !== "session" || fields.harvested)
380
+ continue;
381
+ if (fields.date && fields.date < today && fields.date >= cutoff)
382
+ days.add(fields.date);
383
+ }
384
+ return [...days].sort();
385
+ }
386
+ // Undo one day's knowledge writes: records it created are removed, records it strengthened get
387
+ // their earlier version back. The day's summary and session flags stay.
388
+ export async function undoDay(date) {
389
+ const ledger = JSON.parse(await readFile(ledgerFile(date), "utf8").catch(() => "null"));
390
+ if (!ledger)
391
+ throw new Error(`no harvest ledger for ${date}`);
392
+ const removed = [];
393
+ const restored = [];
394
+ for (const file of ledger.created) {
395
+ await rm(oceanPath(file), { force: true });
396
+ removed.push(file);
397
+ }
398
+ // Oldest version first wins: a file strengthened twice returns to how it was before the day.
399
+ const seen = new Set();
400
+ for (const { file, copy } of ledger.updated) {
401
+ if (seen.has(file))
402
+ continue;
403
+ seen.add(file);
404
+ await copyFile(oceanPath(copy), oceanPath(file));
405
+ restored.push(file);
406
+ }
407
+ await rename(ledgerFile(date), stateDir("ledger", `${date}.undone.json`));
408
+ return { removed, restored };
409
+ }
410
+ // After `days`, a harvested day leaves the working folders: the day's note to
411
+ // 01-daily/archive/<YYYY-MM>/, its session records to 01-daily/sessions/archive/<YYYY-MM>/ (still
412
+ // searched). Nothing is deleted, and nothing unharvested moves.
413
+ export async function archiveHarvested(options) {
414
+ const cutoff = new Date(Date.parse(options.today) - (options.days ?? 30) * DAY_MS)
415
+ .toISOString()
416
+ .slice(0, 10);
417
+ const moves = [];
418
+ for (const file of await markdownIn(sessionsRoot())) {
419
+ const fields = parseFrontmatter((await readFile(file, "utf8")).slice(0, 4096));
420
+ if (fields.type !== "session" || !fields.date || fields.date >= cutoff)
421
+ continue;
422
+ if (!fields.harvested)
423
+ continue;
424
+ moves.push({
425
+ from: file,
426
+ to: path.join(sessionsRoot(), "archive", fields.date.slice(0, 7), path.basename(file)),
427
+ kind: "sessions",
428
+ });
429
+ }
430
+ for (const name of await readdir(oceanPath(DAILY_DIR)).catch(() => [])) {
431
+ const day = /^(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
432
+ if (!day || day >= cutoff)
433
+ continue;
434
+ // A day leaves once none of its sessions waits to be harvested.
435
+ if ((await daySessions(day)).some((session) => !/^harvested:/m.test(session.text)))
436
+ continue;
437
+ moves.push({
438
+ from: oceanPath(DAILY_DIR, name),
439
+ to: oceanPath(DAILY_DIR, "archive", day.slice(0, 7), name),
440
+ kind: "notes",
441
+ });
442
+ }
443
+ const result = { notes: [], sessions: [] };
444
+ for (const move of moves) {
445
+ result[move.kind].push(relativeOf(move.to));
446
+ if (!options.apply)
447
+ continue;
448
+ await mkdir(path.dirname(move.to), { recursive: true });
449
+ await rename(move.from, move.to);
450
+ }
451
+ return result;
452
+ }
453
+ //# sourceMappingURL=harvest.js.map
@@ -5,6 +5,7 @@ import { memorySettings } from "@ocean/brain/memory/memory-audit.js";
5
5
  import { fileProposal, } from "@ocean/brain/memory/memory-review.js";
6
6
  import { deleteMemoryRecord, memoryHistory, restoreMemory, } from "@ocean/brain/memory/memory-trash.js";
7
7
  import { proposeMemory, readMemoryRecord, writeMemoryRecord, } from "@ocean/brain/memory/memory-write.js";
8
+ import { lookupPerson } from "@ocean/brain/memory/people.js";
8
9
  import { promoteSessionToKnowledge } from "@ocean/brain/memory/session-promotion.js";
9
10
  import { isValidProjectId } from "@ocean/core/domain/context/project-id.js";
10
11
  import { actionFingerprint, mcpApprovalSchema, } from "@ocean/core/domain/mcp/mcp-contract.js";
@@ -270,7 +271,7 @@ const tools = new McpToolRegistry([
270
271
  },
271
272
  {
272
273
  name: "memory_propose",
273
- description: "Call this when the user states something worth keeping across sessions (a decision, preference or project fact) without asking you to remember it, for a fact you inferred, or for one imported from another tool's memory: it queues it for the user's review. It is not memory until approved. In a conversation about one project, pass its name (as the user's Claude project is called) or Ocean id as project, and kind instead of target: `fact` (a decision, preference or detail) or `doc` (a spec, brief or longer notes), each with a kebab-case name, is filed in that project's memory/ or docs/ — written at once when the user allows it; `todo` (work to do) waits for review as a backlog line. Optionally say why (reason).",
274
+ description: "Call this when the user states something worth keeping across sessions (a decision, preference or project fact) without asking you to remember it, for a fact you inferred, or for one imported from another tool's memory: it queues it for the user's review. It is not memory until approved. In a conversation about one project, pass its name (as the user's Claude project is called) or Ocean id as project, and kind instead of target: `fact` (a decision, preference or detail) or `doc` (a spec, brief or longer notes), each with a kebab-case name, is filed in that project's memory/ or docs/ — written at once when the user allows it; `todo` (work to do) waits for review as a backlog line. Optionally say why (reason). If the fact disagrees with one of the user's own notes in 07-notes, pass that note's path as contradicts: the note is never edited, and the disagreement waits in 02-personal/CONFLICTS.md for the user.",
274
275
  annotations: { readOnlyHint: false, destructiveHint: false },
275
276
  inputSchema: {
276
277
  type: "object",
@@ -282,6 +283,7 @@ const tools = new McpToolRegistry([
282
283
  kind: { type: "string", enum: ["fact", "doc", "todo"] },
283
284
  name: { type: "string" },
284
285
  reason: { type: "string" },
286
+ contradicts: { type: "string" },
285
287
  },
286
288
  required: ["content", "origin"],
287
289
  additionalProperties: false,
@@ -349,6 +351,17 @@ const tools = new McpToolRegistry([
349
351
  additionalProperties: false,
350
352
  },
351
353
  },
354
+ {
355
+ name: "people_lookup",
356
+ description: "Find a person the user knows by name, in English or Arabic: matches a file name, title or alias in 02-personal/people/ exactly (case and spacing ignored), never a part of a name. Returns each match's file, name, aliases, role, org, relation and last_seen; read the file with memory_read for the history.",
357
+ annotations: { readOnlyHint: true },
358
+ inputSchema: {
359
+ type: "object",
360
+ properties: { name: { type: "string" } },
361
+ required: ["name"],
362
+ additionalProperties: false,
363
+ },
364
+ },
352
365
  ]);
353
366
  // What one MCP handoff may hold, summed over its texts (T-307).
354
367
  export const HANDOFF_MAX_BYTES = 4096;
@@ -589,6 +602,8 @@ async function callTool(name, args, ports) {
589
602
  };
590
603
  if (name === "ocean_handoff_create")
591
604
  return createClientHandoff(args, ports);
605
+ if (name === "people_lookup")
606
+ return lookupPerson(requiredArgument(args, "name"));
592
607
  if (name === "memory_read")
593
608
  return readMemoryRecord(requiredArgument(args, "path"));
594
609
  if (name === "memory_history")
@@ -628,6 +643,7 @@ async function callTool(name, args, ports) {
628
643
  origin: args.origin,
629
644
  target: text("target"),
630
645
  reason: text("reason"),
646
+ contradicts: text("contradicts"),
631
647
  source,
632
648
  });
633
649
  if (name === "memory_delete")
@@ -0,0 +1,81 @@
1
+ import { proposeMemory } from "@ocean/brain/memory/memory-write.js";
2
+ import { MemoryContractError } from "@ocean/core/domain/mcp/memory-contract.js";
3
+ // Session telemetry (T-314): what keeps going wrong in Ocean's own sessions becomes a proposed
4
+ // backlog line for the owner — never a task, never applied without review. Read from the session
5
+ // store: an error seen in at least MIN_REPEATS sessions, and providers whose sessions fail or are
6
+ // left unfinished.
7
+ const MIN_REPEATS = 3;
8
+ const STUCK_AFTER_MS = 6 * 60 * 60 * 1000;
9
+ const ERROR_TYPES = new Set(["error", "provider_blocked", "closeout_warning"]);
10
+ // The same failure with different ids, paths or numbers counts as one.
11
+ export function errorShape(text) {
12
+ return text
13
+ .replace(/\/[^\s:'"]+/g, "<path>")
14
+ .replace(/[0-9a-f]{8}-[0-9a-f-]{27,}/gi, "<id>")
15
+ .replace(/\d+/g, "<n>")
16
+ .replace(/\s+/g, " ")
17
+ .trim()
18
+ .slice(0, 120);
19
+ }
20
+ export function analyzeSessions(sessions, eventsOf, sinceIso, now = Date.now()) {
21
+ const recent = sessions.filter((session) => session.createdAt >= sinceIso);
22
+ const errors = new Map();
23
+ for (const session of recent)
24
+ for (const event of eventsOf(session.sessionId)) {
25
+ if (!ERROR_TYPES.has(event.type))
26
+ continue;
27
+ const shape = errorShape(event.data);
28
+ if (!shape)
29
+ continue;
30
+ const seen = errors.get(shape) ?? new Set();
31
+ seen.add(session.sessionId);
32
+ errors.set(shape, seen);
33
+ }
34
+ const findings = [...errors]
35
+ .filter(([, ids]) => ids.size >= MIN_REPEATS)
36
+ .sort((a, b) => b[1].size - a[1].size)
37
+ .map(([shape, ids]) => ({
38
+ line: `Recurring error in ${ids.size} sessions: ${shape}`,
39
+ sessions: ids.size,
40
+ }));
41
+ const byProvider = new Map();
42
+ for (const session of recent) {
43
+ const entry = byProvider.get(session.provider) ?? { failed: 0, total: 0 };
44
+ entry.total++;
45
+ // A running session counts only once it has run longer than any real session would.
46
+ const stuck = session.status === "running" &&
47
+ now - Date.parse(session.createdAt) > STUCK_AFTER_MS;
48
+ if (session.status === "failed" || stuck)
49
+ entry.failed++;
50
+ byProvider.set(session.provider, entry);
51
+ }
52
+ for (const [provider, { failed, total }] of byProvider)
53
+ if (failed >= MIN_REPEATS && failed / total >= 0.25)
54
+ findings.push({
55
+ line: `${provider}: ${failed} of ${total} sessions failed or never finished`,
56
+ sessions: failed,
57
+ });
58
+ return findings;
59
+ }
60
+ export async function proposeTelemetry(findings, apply) {
61
+ if (!apply)
62
+ return findings.map((finding) => finding.line);
63
+ const proposed = [];
64
+ for (const finding of findings)
65
+ try {
66
+ const { candidate } = await proposeMemory({
67
+ content: finding.line,
68
+ origin: "inferred",
69
+ source: "session-telemetry",
70
+ reason: "seen repeatedly in Ocean's own sessions",
71
+ meta: { kind: "todo", project: "ocean" },
72
+ });
73
+ proposed.push(candidate);
74
+ }
75
+ catch (error) {
76
+ if (!(error instanceof MemoryContractError))
77
+ throw error;
78
+ }
79
+ return proposed;
80
+ }
81
+ //# sourceMappingURL=telemetry.js.map
@@ -0,0 +1,82 @@
1
+ import { mkdir, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { RECORD_TYPES, recordFolder, } from "@ocean/brain/memory/fact-routing.js";
4
+ import { redactSecrets } from "@ocean/core/domain/redaction/redaction.js";
5
+ import { atomicWrite } from "@ocean/core/shared/fs-utils.js";
6
+ import { INBOX_DIR, oceanPath, TEMPLATES_DIR, } from "@ocean/core/shared/paths.js";
7
+ import { projectSlug } from "@ocean/core/shared/project-resolution.js";
8
+ const TEMPLATER_CONFIG = [
9
+ ".obsidian",
10
+ "plugins",
11
+ "templater-obsidian",
12
+ "data.json",
13
+ ];
14
+ async function exists(file) {
15
+ return readFile(file).then(() => true, () => false);
16
+ }
17
+ // One entry per routed type whose template exists in 06-templates; entries the owner made for
18
+ // other folders are kept, and a routed folder's entry is replaced.
19
+ export async function planFolderTemplates(current) {
20
+ const routed = [];
21
+ const missing = [];
22
+ for (const type of RECORD_TYPES) {
23
+ const folder = recordFolder(type)?.replace(/\/$/, "");
24
+ if (!folder)
25
+ continue;
26
+ const template = `${TEMPLATES_DIR}/${type}.md`;
27
+ if (await exists(oceanPath(template)))
28
+ routed.push({ folder, template });
29
+ else
30
+ missing.push(type);
31
+ }
32
+ const ours = new Set(routed.map((entry) => entry.folder));
33
+ return {
34
+ entries: [...current.filter((entry) => !ours.has(entry.folder)), ...routed],
35
+ missing,
36
+ };
37
+ }
38
+ export async function syncFolderTemplates(options) {
39
+ const file = oceanPath(...TEMPLATER_CONFIG);
40
+ let config = {};
41
+ try {
42
+ config = JSON.parse(await readFile(file, "utf8"));
43
+ }
44
+ catch (error) {
45
+ if (error.code !== "ENOENT")
46
+ throw new Error(`${TEMPLATER_CONFIG.join("/")} is not valid JSON`);
47
+ }
48
+ const current = Array.isArray(config.folder_templates)
49
+ ? config.folder_templates.filter((entry) => typeof entry?.folder === "string" &&
50
+ typeof entry?.template === "string")
51
+ : [];
52
+ const plan = await planFolderTemplates(current);
53
+ const relative = TEMPLATER_CONFIG.join("/");
54
+ if (!options.apply)
55
+ return { file: relative, ...plan, written: false };
56
+ await mkdir(path.dirname(file), { recursive: true });
57
+ await atomicWrite(file, `${JSON.stringify({
58
+ ...config,
59
+ templates_folder: config.templates_folder ?? TEMPLATES_DIR,
60
+ enable_folder_templates: true,
61
+ folder_templates: plan.entries,
62
+ }, null, 2)}\n`);
63
+ return { file: relative, ...plan, written: true };
64
+ }
65
+ // A quick note from anywhere (`ocean note "<text>"`): one file in 00-inbox/captures with the
66
+ // capture frontmatter, named by time and its first words. Secrets are redacted before writing.
67
+ export async function writeCapture(text, now = new Date()) {
68
+ const body = redactSecrets(text.trim());
69
+ if (!body)
70
+ throw new Error('Usage: ocean note "<text>"');
71
+ const stamp = now.toISOString().replace(/[-:]/g, "").slice(0, 15);
72
+ const slug = projectSlug(body.split(/\s+/).slice(0, 6).join(" ")).slice(0, 40) || "note";
73
+ const relative = `${INBOX_DIR}/captures/${stamp}-${slug}.md`;
74
+ const file = oceanPath(relative);
75
+ await mkdir(path.dirname(file), { recursive: true });
76
+ if (await exists(file))
77
+ throw new Error(`${relative} already exists`);
78
+ const title = body.split("\n")[0].slice(0, 80);
79
+ await atomicWrite(file, `---\ntype: capture\ncreated: ${now.toISOString()}\nsource: cli\ntags: []\n---\n\n# ${title}\n\n${body}\n`);
80
+ return relative;
81
+ }
82
+ //# sourceMappingURL=folder-templates.js.map