@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
@@ -1,8 +1,8 @@
1
- import { mkdir, readdir, writeFile } from "node:fs/promises";
1
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { redactRuntimeText } from "@ocean/core/domain/redaction/redaction.js";
4
4
  import { localDate, localMoment, localTime, } from "@ocean/core/shared/local-date.js";
5
- import { INBOX_DIR, oceanPath, oceanRoot } from "@ocean/core/shared/paths.js";
5
+ import { DAILY_DIR, INBOX_DIR, oceanPath, oceanRoot, } from "@ocean/core/shared/paths.js";
6
6
  import { findGitRoot } from "@ocean/core/shared/project-resolution.js";
7
7
  // Same fallback title stamped on a session with no explicit title (see
8
8
  // daily-narrative.ts) — never meaningful content on its own.
@@ -45,7 +45,7 @@ async function uniqueFilename(directory, base, ext) {
45
45
  return `${base}-${Date.now()}${ext}`;
46
46
  }
47
47
  /**
48
- * One human-readable Markdown file per session under brain/00-inbox/brain-dump/,
48
+ * One session record per session in 01-daily/sessions/YYYY-MM/ (T-314; was 00-inbox/brain-dump/),
49
49
  * separate from the machine-oriented kernel/bridge/sessions/summaries/ dump. Prefers
50
50
  * the cheap model narrative (see model-narrative.ts) and falls back to the
51
51
  * same deterministic heuristics as daily-narrative.ts when it is unavailable.
@@ -90,44 +90,62 @@ export async function writeBrainDump(input) {
90
90
  ? "completed"
91
91
  : "failed";
92
92
  const title = isGenericContent(workLog) ? project : workLog;
93
+ // A session record (T-314): flat frontmatter Obsidian can read, then fixed sections. The
94
+ // narrative comes from one model call when there was one; otherwise from the events.
95
+ const quote = (value) => JSON.stringify(value);
93
96
  const lines = [
94
- `# ${title}`,
97
+ "---",
98
+ "type: session",
99
+ `project: ${quote(project)}`,
100
+ `provider: ${quote(session.provider)}`,
101
+ `status: ${status}`,
102
+ `session_id: ${quote(session.sessionId)}`,
103
+ `date: ${date}`,
104
+ "tags: []",
105
+ "distilled: false",
106
+ "---",
95
107
  "",
96
- `- Date: ${date} ${time}`,
97
- `- Provider: ${session.provider}`,
98
- `- Project: ${project}`,
99
- `- Status: ${status}`,
108
+ `# ${title}`,
100
109
  "",
101
- "## What happened",
110
+ "## Goal",
102
111
  "",
103
112
  workLog || "No objective was captured.",
104
- ...(decision ? ["", "## Decision", "", decision] : []),
105
- ...(problem ? ["", "## Problem", "", problem] : []),
106
- ...(changedFiles.length
113
+ "",
114
+ "## Outcome",
115
+ "",
116
+ status === "completed" ? "Completed." : "Did not complete.",
117
+ ...(decision ? ["", "## Decisions", "", decision] : []),
118
+ ...(problem ? ["", "## Problems → fixes", "", problem] : []),
119
+ ...(observations?.length
107
120
  ? [
108
121
  "",
109
- "## Files changed",
122
+ "## Learned",
110
123
  "",
111
- ...changedFiles.map((f) => `- ${safeText(f, 240)}`),
124
+ ...observations.map((o) => `- [${o.signalType}] ${safeText(o.summary, 300)} (confidence ${o.confidence})`),
112
125
  ]
113
126
  : []),
114
- ...(hasNextAction
115
- ? ["", "## Next", "", safeText(nextAction, 300)]
116
- : []),
117
- ...(observations?.length
127
+ "",
128
+ "## Verification",
129
+ "",
130
+ status === "completed" && (input.exitCode ?? 0) === 0
131
+ ? "NOT PROVEN — the session ended cleanly; no check is recorded here."
132
+ : `NOT PROVEN — exit code ${input.exitCode ?? "unknown"}.`,
133
+ ...(changedFiles.length
118
134
  ? [
119
135
  "",
120
- "## Signals",
136
+ "## Files / commits",
121
137
  "",
122
- ...observations.map((o) => `- [${o.signalType}] ${safeText(o.summary, 300)} (confidence ${o.confidence})`),
138
+ ...changedFiles.map((f) => `- ${safeText(f, 240)}`),
123
139
  ]
124
140
  : []),
141
+ ...(hasNextAction
142
+ ? ["", "## Next", "", safeText(nextAction, 300)]
143
+ : []),
125
144
  "",
126
- "---",
127
- "",
128
- `Session id: ${session.sessionId} · Raw events: \`ocean session events ${session.sessionId}\``,
145
+ `Raw events: \`ocean session events ${session.sessionId}\``,
129
146
  ];
130
- const directory = oceanPath(INBOX_DIR, "brain-dump");
147
+ // 01-daily/sessions/YYYY-MM/, where the session-record template and Templater point.
148
+ const directory = oceanPath(DAILY_DIR, "sessions", date.slice(0, 7));
131
149
  await mkdir(directory, { recursive: true });
132
150
  const titleSlug = slugify(title);
133
151
  const slug = titleSlug.length >= MIN_USEFUL_SLUG_LENGTH
@@ -142,4 +160,35 @@ export async function writeBrainDump(input) {
142
160
  brainDumpPath: path.relative(oceanRoot(), file).split(path.sep).join("/"),
143
161
  };
144
162
  }
163
+ // The one-time move (T-314): brain-dump files written before session records become records,
164
+ // moved — never deleted — to 01-daily/sessions/YYYY-MM/ by the date in their name, with a
165
+ // `type: session` frontmatter added when they have none. Dry run unless `apply`; a target that
166
+ // already exists is left alone and reported.
167
+ export async function migrateBrainDumps(options) {
168
+ const source = oceanPath(INBOX_DIR, "brain-dump");
169
+ const names = await readdir(source).catch(() => []);
170
+ const moved = [];
171
+ const skipped = [];
172
+ for (const name of names.sort()) {
173
+ const date = /^(\d{4}-\d{2}-\d{2})-/.exec(name)?.[1];
174
+ if (!name.endsWith(".md") || !date)
175
+ continue;
176
+ const relative = `${DAILY_DIR}/sessions/${date.slice(0, 7)}/${name}`;
177
+ const target = oceanPath(relative);
178
+ if (await readFile(target).then(() => true, () => false)) {
179
+ skipped.push(relative);
180
+ continue;
181
+ }
182
+ moved.push(relative);
183
+ if (!options.apply)
184
+ continue;
185
+ const text = await readFile(path.join(source, name), "utf8");
186
+ await mkdir(path.dirname(target), { recursive: true });
187
+ await writeFile(target, text.startsWith("---")
188
+ ? text
189
+ : `---\ntype: session\ndate: ${date}\nstatus: legacy\ndistilled: false\n---\n\n${text}`, "utf8");
190
+ await rm(path.join(source, name));
191
+ }
192
+ return { moved, skipped };
193
+ }
145
194
  //# sourceMappingURL=brain-dump.js.map
@@ -0,0 +1,54 @@
1
+ import { projectDir } from "@ocean/core/shared/paths.js";
2
+ import { findProject, projectSlug, } from "@ocean/core/shared/project-resolution.js";
3
+ import { permanentRecord } from "./memory-paths.js";
4
+ import routing from "./routing.json" with { type: "json" };
5
+ // Where a fact lives, decided by one table (T-314): the model names a fact's type, code turns it
6
+ // into a record path, so a candidate arrives with its target and approving it needs no path.
7
+ // Each fact gets its own file, named after its title, in the type's folder; a project fact goes
8
+ // to that project's memory/, and only when the project is one Ocean already knows.
9
+ export const FACT_TYPES = Object.keys(routing.facts);
10
+ export function isFactType(value) {
11
+ return typeof value === "string" && Object.hasOwn(routing.facts, value);
12
+ }
13
+ // The record path for a fact, or "" when the table gives none: an unknown type, a project fact
14
+ // whose project is not registered, or a title that leaves no file name.
15
+ export async function factTarget(fact) {
16
+ if (!isFactType(fact.type))
17
+ return "";
18
+ const name = projectSlug(fact.title);
19
+ if (!name)
20
+ return "";
21
+ let folder = routing.facts[fact.type];
22
+ if (folder.includes("{project}")) {
23
+ const id = fact.project ? await findProject(fact.project) : undefined;
24
+ if (!id)
25
+ return "";
26
+ folder = folder.replace("04-projects/{project}", projectDir(id));
27
+ }
28
+ try {
29
+ return permanentRecord(`${folder}${name}.md`).relative;
30
+ }
31
+ catch {
32
+ return "";
33
+ }
34
+ }
35
+ // Records (T-314): every type with one home. A type outside this table (a client memory kind such
36
+ // as `feedback` or `long-term`) has no fixed folder and is never reported as misplaced.
37
+ export const RECORD_TYPES = Object.keys(routing.records);
38
+ export function recordFolder(type) {
39
+ const aliases = routing.aliases;
40
+ const canonical = Object.hasOwn(aliases, type) ? aliases[type] : type;
41
+ const records = routing.records;
42
+ return Object.hasOwn(records, canonical) ? records[canonical] : null;
43
+ }
44
+ // Whether a workspace-relative markdown file sits where its type lives. A project's own
45
+ // memory/ and docs/ may hold any type: a decision about one project belongs to that project.
46
+ export function inTypeLocation(relative, type) {
47
+ const folder = recordFolder(type);
48
+ if (!folder)
49
+ return true;
50
+ if (/^04-projects\/(?:[^/]+\/)?[^/]+\/(?:memory|docs)\//.test(relative))
51
+ return true;
52
+ return relative.startsWith(folder);
53
+ }
54
+ //# sourceMappingURL=fact-routing.js.map
@@ -0,0 +1,89 @@
1
+ import { copyFile, mkdir, readdir, readFile, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { atomicWrite } from "@ocean/core/shared/fs-utils.js";
4
+ import { BRAIN_RECORD_DIRS, NOTES_DIR, oceanPath, PROJECTS_DIR, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
5
+ // Flat frontmatter (T-314): Obsidian Properties and Bases read top-level keys only, so a record's
6
+ // `metadata:` block moves up one level. Readers already accept both shapes (parseFrontmatter
7
+ // reads keys indented up to two spaces); this is the one-time move for files written before.
8
+ // A key that is already top-level keeps its top-level value; the nested copy is dropped.
9
+ const KEY = /^([A-Za-z_][\w-]*):/;
10
+ export function flattenFrontmatter(source) {
11
+ const text = source.replace(/\r\n/g, "\n");
12
+ if (!text.startsWith("---\n"))
13
+ return null;
14
+ const end = text.indexOf("\n---", 3);
15
+ if (end < 0)
16
+ return null;
17
+ const lines = text.slice(4, end).split("\n");
18
+ const start = lines.findIndex((line) => /^metadata:\s*$/.test(line));
19
+ if (start < 0)
20
+ return null;
21
+ let stop = start + 1;
22
+ while (stop < lines.length && /^(\s+\S|\s*$)/.test(lines[stop]))
23
+ stop++;
24
+ const nested = lines
25
+ .slice(start + 1, stop)
26
+ .filter((line) => line.trim())
27
+ .map((line) => line.replace(/^ {2}/, ""));
28
+ const outside = [...lines.slice(0, start), ...lines.slice(stop)];
29
+ const taken = new Set(outside.map((line) => KEY.exec(line)?.[1]).filter(Boolean));
30
+ // A nested key and the lines under it (a list, a deeper map) move or drop together.
31
+ const moved = [];
32
+ let keep = true;
33
+ for (const line of nested) {
34
+ const key = KEY.exec(line)?.[1];
35
+ if (key)
36
+ keep = !taken.has(key);
37
+ if (keep)
38
+ moved.push(line);
39
+ }
40
+ const block = [...lines.slice(0, start), ...moved, ...lines.slice(stop)];
41
+ return `---\n${block.join("\n")}${text.slice(end)}`;
42
+ }
43
+ async function markdownFiles(directory) {
44
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
45
+ const files = [];
46
+ for (const entry of entries) {
47
+ if (entry.name.startsWith(".") || entry.name === "node_modules")
48
+ continue;
49
+ const file = path.join(directory, entry.name);
50
+ if (entry.isDirectory())
51
+ files.push(...(await markdownFiles(file)));
52
+ else if (entry.name.endsWith(".md"))
53
+ files.push(file);
54
+ }
55
+ return files;
56
+ }
57
+ // Every record area except the owner's own notes, which agents never write. Dry run unless
58
+ // `apply`; an applied run copies each original to bridge/archive first.
59
+ export async function flattenWorkspace(options) {
60
+ const roots = [...BRAIN_RECORD_DIRS, PROJECTS_DIR].filter((root) => root !== NOTES_DIR);
61
+ const changed = [];
62
+ for (const root of new Set(roots))
63
+ for (const file of await markdownFiles(oceanPath(root))) {
64
+ const text = flattenFrontmatter(await readFile(file, "utf8"));
65
+ if (text === null)
66
+ continue;
67
+ changed.push({
68
+ relative: path.relative(oceanPath(), file).split(path.sep).join("/"),
69
+ file,
70
+ text,
71
+ });
72
+ }
73
+ if (!options.apply || !changed.length)
74
+ return { changed: changed.map((item) => item.relative), backup: null };
75
+ const stamp = (options.now ?? new Date())
76
+ .toISOString()
77
+ .replace(/[-:]/g, "")
78
+ .slice(0, 15);
79
+ const backup = `${SYSTEM_DIR}/archive/frontmatter-flatten-${stamp}`;
80
+ for (const item of changed) {
81
+ const copy = oceanPath(backup, item.relative);
82
+ await mkdir(path.dirname(copy), { recursive: true });
83
+ await copyFile(item.file, copy);
84
+ // The rewrite keeps the file's own permissions (records are often 0600).
85
+ await atomicWrite(item.file, item.text, (await stat(item.file)).mode & 0o777);
86
+ }
87
+ return { changed: changed.map((item) => item.relative), backup };
88
+ }
89
+ //# sourceMappingURL=frontmatter-flatten.js.map
@@ -318,4 +318,24 @@ export async function migrateLegacyLessons(now = new Date()) {
318
318
  await rename(file, `${file}.migrated`);
319
319
  return result;
320
320
  }
321
+ // Lesson hygiene (T-314): retired lessons move to lessons/archive/, which the index never walks.
322
+ // Kept, never deleted. Dry run unless `apply`.
323
+ export async function archiveRetiredLessons(options) {
324
+ const dir = lessonsDir();
325
+ const names = await readdir(dir).catch(() => []);
326
+ const moved = [];
327
+ for (const name of names.sort()) {
328
+ if (!name.endsWith(".md") || name === "CONFLICTS.md")
329
+ continue;
330
+ const text = await readFile(path.join(dir, name), "utf8");
331
+ if (!/^status:\s*["']?retired["']?\s*$/m.test(text.split(/\r?\n---/, 1)[0]))
332
+ continue;
333
+ moved.push(name);
334
+ if (!options.apply)
335
+ continue;
336
+ await mkdir(path.join(dir, "archive"), { recursive: true });
337
+ await rename(path.join(dir, name), path.join(dir, "archive", name));
338
+ }
339
+ return moved;
340
+ }
321
341
  //# sourceMappingURL=lessons.js.map
@@ -1,7 +1,7 @@
1
1
  import { lstatSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { MemoryContractError } from "@ocean/core/domain/mcp/memory-contract.js";
4
- import { INBOX_DIR, oceanPath, PERSONAL_DIR, PROJECTS_DIR, projectDir, projectPathParts, resolveWithin, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
4
+ import { INBOX_DIR, NOTES_DIR, oceanPath, PERSONAL_DIR, PROJECTS_DIR, projectDir, projectPathParts, resolveWithin, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
5
5
  // Every place the memory tools may write, and nothing else (T-296). Permanent records are the
6
6
  // only paths a caller chooses; candidates, versions, trash, the audit log and the client
7
7
  // journal are named by the server. Native staging belongs to a client's own memory feature.
@@ -63,6 +63,8 @@ export function permanentRecord(relative) {
63
63
  if (PROTECTED.has(name.toLowerCase()))
64
64
  throw new MemoryContractError("PROTECTED", `${name} is maintained by Ocean, not written as a record`);
65
65
  const joined = parts.join("/");
66
+ if (joined.startsWith(`${NOTES_DIR}/`))
67
+ throw new MemoryContractError("PROTECTED", `${NOTES_DIR}/ is the owner's own notes; agents read it and propose, never write`);
66
68
  const under = (dir) => joined.startsWith(`${dir}/`)
67
69
  ? joined.slice(dir.length + 1).split("/")
68
70
  : null;
@@ -5,6 +5,7 @@ import { atomicWrite, withFileLock } from "@ocean/core/shared/fs-utils.js";
5
5
  import { localDate } from "@ocean/core/shared/local-date.js";
6
6
  import { oceanPath, PROJECTS_DIR, projectDir, } from "@ocean/core/shared/paths.js";
7
7
  import { findProject, readClaudeProjects, registerNamedProject, } from "@ocean/core/shared/project-resolution.js";
8
+ import { FACT_TYPES, factTarget, isFactType } from "./fact-routing.js";
8
9
  import { appendAudit, memorySettings, newId, sha256, writeDurable, } from "./memory-audit.js";
9
10
  import { assertNoLinks, candidatesRoot, storedCopy } from "./memory-paths.js";
10
11
  import { checkContent, proposeMemory, readMemoryRecord, writeMemoryRecord, } from "./memory-write.js";
@@ -96,6 +97,19 @@ async function retire(item, action, source = "owner-review") {
96
97
  });
97
98
  return id;
98
99
  }
100
+ // A candidate with no target gets one from the routing table (T-314): by the type passed, else
101
+ // by the type the extractor wrote. The title is the candidate's first heading.
102
+ async function routedTarget(item, type) {
103
+ if (type !== undefined && !isFactType(type))
104
+ throw new MemoryContractError("INVALID", `unknown fact type '${type}'; one of: ${FACT_TYPES.join(", ")}`);
105
+ const title = /^# (.+)$/m.exec(item.content)?.[1]?.trim() ?? "";
106
+ const project = typeof item.meta.project === "string" ? item.meta.project : undefined;
107
+ return factTarget({
108
+ type: type ?? (typeof item.meta.type === "string" ? item.meta.type : ""),
109
+ title,
110
+ project,
111
+ });
112
+ }
99
113
  // Writes the candidate's content to `to` (default: its proposed target). A new record is
100
114
  // created; an existing one gets the content appended, guarded by its current hash — unless
101
115
  // `createOnly` (an approval nobody looked at), which leaves that one to the owner's review.
@@ -112,9 +126,12 @@ export async function approveCandidate(options) {
112
126
  };
113
127
  if (item.meta.kind === "todo" && !options.to)
114
128
  return approveTodo(item, source);
115
- const target = options.to ?? item.target;
129
+ const target = options.to ??
130
+ (options.type !== undefined
131
+ ? await routedTarget(item, options.type)
132
+ : item.target || (await routedTarget(item)));
116
133
  if (!target)
117
- throw new MemoryContractError("INVALID", "the candidate names no target; pass --to <record path>");
134
+ throw new MemoryContractError("INVALID", `the candidate names no target; pass --type <${FACT_TYPES.join("|")}> or --to <record path>`);
118
135
  // A project doc is only ever created: an existing one stays the owner's (T-307).
119
136
  if (/^04-projects\/[^/]+\/docs\//.test(target)) {
120
137
  const written = await writeMemoryRecord({
@@ -4,7 +4,7 @@ import { MemoryContractError } from "@ocean/core/domain/mcp/memory-contract.js";
4
4
  import { containsKnownSecret } from "@ocean/core/domain/redaction/redaction.js";
5
5
  import { atomicWrite, withFileLock } from "@ocean/core/shared/fs-utils.js";
6
6
  import { localDate } from "@ocean/core/shared/local-date.js";
7
- import { listProjectDirs, oceanPath, PERSONAL_DIR, } from "@ocean/core/shared/paths.js";
7
+ import { listProjectDirs, NOTES_DIR, oceanPath, PERSONAL_DIR, } from "@ocean/core/shared/paths.js";
8
8
  import { syncMemoryIndexes } from "./index-sync.js";
9
9
  import { appendAudit, newId, sha256, writeDurable } from "./memory-audit.js";
10
10
  import { assertNoLinks, candidateFile, candidatesRoot, permanentRecord, projectDocument, storedCopy, } from "./memory-paths.js";
@@ -186,7 +186,10 @@ function metaLines(meta) {
186
186
  // the file; a proposed target is validated as a record path but never written here.
187
187
  export async function proposeMemory(options) {
188
188
  checkContent(options.content);
189
- const extra = metaLines(options.meta);
189
+ const note = options.contradicts
190
+ ? await humanNote(options.contradicts)
191
+ : null;
192
+ const extra = metaLines(note ? { ...options.meta, contradicts: note } : options.meta);
190
193
  if (options.origin !== "inferred" && options.origin !== "imported")
191
194
  throw new MemoryContractError("INVALID", "origin must be inferred or imported");
192
195
  const target = !options.target
@@ -211,6 +214,45 @@ export async function proposeMemory(options) {
211
214
  beforeSha: null,
212
215
  afterSha: sha256(body),
213
216
  });
214
- return { candidate, auditId: id };
217
+ if (!note)
218
+ return { candidate, auditId: id };
219
+ await recordNoteConflict({
220
+ note,
221
+ candidate,
222
+ content: options.content,
223
+ reason,
224
+ });
225
+ return { candidate, auditId: id, conflict: `${PERSONAL_DIR}/CONFLICTS.md` };
226
+ }
227
+ // 07-notes is the owner's: an agent never edits it, and a fact that disagrees with one of his
228
+ // notes is not reconciled by the agent. It waits in CONFLICTS.md, beside the candidate.
229
+ async function humanNote(relative) {
230
+ const clean = path.posix.normalize(relative.replace(/\\/g, "/"));
231
+ if (path.posix.isAbsolute(clean) ||
232
+ !clean.startsWith(`${NOTES_DIR}/`) ||
233
+ !clean.endsWith(".md"))
234
+ throw new MemoryContractError("INVALID", `contradicts must name a note under ${NOTES_DIR}/`);
235
+ if ((await readIfPresent(oceanPath(clean))) === null)
236
+ throw new MemoryContractError("MISSING", `${clean} not found`);
237
+ return clean;
238
+ }
239
+ async function recordNoteConflict(entry) {
240
+ const file = oceanPath(PERSONAL_DIR, "CONFLICTS.md");
241
+ const claim = entry.content.replace(/\s+/g, " ").trim().slice(0, 300);
242
+ const section = [
243
+ `## ${localDate()} — ${entry.note}`,
244
+ "",
245
+ `- Your note: \`${entry.note}\``,
246
+ `- An agent's fact that disagrees: ${claim}`,
247
+ ...(entry.reason ? [`- Why it thinks so: ${entry.reason}`] : []),
248
+ `- Waiting as \`${entry.candidate}\`: approve or reject it once you decide, then fix the note if it changed.`,
249
+ "",
250
+ ].join("\n");
251
+ await mkdir(path.dirname(file), { recursive: true });
252
+ await withFileLock(file, async () => {
253
+ const current = (await readIfPresent(file)) ??
254
+ "# Conflicts\n\nOpen contradictions for the owner to resolve. Nothing here is reconciled by an agent.\n";
255
+ await atomicWrite(file, `${current.endsWith("\n") ? current : `${current}\n`}\n${section}`);
256
+ });
215
257
  }
216
258
  //# sourceMappingURL=memory-write.js.map
@@ -0,0 +1,70 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { parseFrontmatter } from "@ocean/core/shared/fs-utils.js";
4
+ import { oceanPath, PERSONAL_DIR } from "@ocean/core/shared/paths.js";
5
+ // People (T-314): one file per person in 02-personal/people/ (`type: person`), named in any of
6
+ // their aliases, English or Arabic. A lookup matches a name exactly — file name, title or an
7
+ // alias, ignoring case, spacing and Unicode form — and never guesses beyond that, so a client
8
+ // asking "who is Ali" gets that person's file or nothing.
9
+ export const PEOPLE_DIR = `${PERSONAL_DIR}/people`;
10
+ const normalize = (value) => value
11
+ .normalize("NFKC")
12
+ .toLowerCase()
13
+ .replace(/[\s_-]+/g, " ")
14
+ .trim();
15
+ // `aliases: [a, b]` or a block list under `aliases:`.
16
+ function listField(source, key) {
17
+ const block = source.startsWith("---")
18
+ ? source.slice(3, Math.max(3, source.indexOf("\n---", 3)))
19
+ : "";
20
+ const lines = block.split("\n");
21
+ const index = lines.findIndex((line) => line.startsWith(`${key}:`));
22
+ if (index < 0)
23
+ return [];
24
+ const unquote = (item) => item.trim().replace(/^["']|["']$/g, "");
25
+ const inline = /\[(.*)\]/.exec(lines[index]);
26
+ if (inline)
27
+ return inline[1].split(",").map(unquote).filter(Boolean);
28
+ const items = [];
29
+ for (const line of lines.slice(index + 1)) {
30
+ const match = /^\s+-\s*(.+)$/.exec(line);
31
+ if (!match)
32
+ break;
33
+ items.push(unquote(match[1]));
34
+ }
35
+ return items.filter(Boolean);
36
+ }
37
+ export async function listPeople() {
38
+ const dir = oceanPath(PEOPLE_DIR);
39
+ const names = await readdir(dir).catch(() => []);
40
+ const people = [];
41
+ for (const entry of names.sort()) {
42
+ if (!entry.endsWith(".md") || entry.startsWith("."))
43
+ continue;
44
+ const source = (await readFile(path.join(dir, entry), "utf8")).replace(/\r\n/g, "\n");
45
+ const fields = parseFrontmatter(source);
46
+ // The same rule as people.base: a file is a person only when it says so.
47
+ if (fields.type !== "person")
48
+ continue;
49
+ const end = source.startsWith("---") ? source.indexOf("\n---", 3) : -1;
50
+ const body = end < 0 ? source : source.slice(end + 4);
51
+ const heading = /^#\s+(.+)$/m.exec(body)?.[1]?.trim();
52
+ people.push({
53
+ file: `${PEOPLE_DIR}/${entry}`,
54
+ name: heading ?? entry.replace(/\.md$/, ""),
55
+ aliases: listField(source, "aliases"),
56
+ role: fields.role ?? "",
57
+ org: fields.org ?? "",
58
+ relation: fields.relation ?? "",
59
+ lastSeen: fields.last_seen ?? "",
60
+ });
61
+ }
62
+ return people;
63
+ }
64
+ export async function lookupPerson(name) {
65
+ const wanted = normalize(name);
66
+ if (!wanted)
67
+ return [];
68
+ return (await listPeople()).filter((person) => [path.basename(person.file, ".md"), person.name, ...person.aliases].some((candidate) => normalize(candidate) === wanted));
69
+ }
70
+ //# sourceMappingURL=people.js.map
@@ -0,0 +1,39 @@
1
+ {
2
+ "facts": {
3
+ "identity": "02-personal/identity/",
4
+ "preference": "02-personal/work/",
5
+ "person": "02-personal/people/",
6
+ "interest": "02-personal/interests/",
7
+ "goal": "02-personal/goals/",
8
+ "education": "02-personal/education/",
9
+ "career": "02-personal/career/",
10
+ "schedule": "02-personal/schedule/",
11
+ "project": "04-projects/{project}/memory/"
12
+ },
13
+ "records": {
14
+ "capture": "00-inbox/captures/",
15
+ "daily": "01-daily/",
16
+ "session": "01-daily/sessions/",
17
+ "brief": "01-daily/briefs/",
18
+ "weekly": "01-daily/weekly/",
19
+ "monthly": "01-daily/monthly/",
20
+ "note": "07-notes/",
21
+ "decision": "05-knowledge/decisions/",
22
+ "lesson": "05-knowledge/lessons/",
23
+ "solution": "05-knowledge/solutions/",
24
+ "failure": "05-knowledge/failures/",
25
+ "discovery": "05-knowledge/discoveries/",
26
+ "architecture": "05-knowledge/architecture/",
27
+ "research": "05-knowledge/research/",
28
+ "result": "05-knowledge/results/",
29
+ "person": "02-personal/people/",
30
+ "interest": "02-personal/interests/",
31
+ "milestone": "02-personal/milestones/",
32
+ "study": "02-personal/education/study/"
33
+ },
34
+ "aliases": {
35
+ "experiential": "lesson",
36
+ "technical-solution": "solution",
37
+ "task-result": "result"
38
+ }
39
+ }
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  import { MemoryContractError } from "@ocean/core/domain/mcp/memory-contract.js";
4
4
  import { redactSecrets } from "@ocean/core/domain/redaction/redaction.js";
5
5
  import { atomicWrite, withFileLock } from "@ocean/core/shared/fs-utils.js";
6
+ import { FACT_TYPES, factTarget, isFactType, } from "./fact-routing.js";
6
7
  import { sha256 } from "./memory-audit.js";
7
8
  import { sessionFactsLedgerFile } from "./memory-paths.js";
8
9
  import { proposeMemory } from "./memory-write.js";
@@ -63,7 +64,8 @@ export function buildFactsPrompt(turns) {
63
64
  "Never extract temporary state (what is being debugged right now, today's to-do, a file being edited), secrets, credentials, or anything marked [REDACTED] or [PRIVATE_PATH].",
64
65
  `Return at most ${MAX_FACTS} facts. Returning none is correct and common.`,
65
66
  "Answer with JSON only, no prose and no code fence:",
66
- '{"facts":[{"title":"short label","content":"the fact as one or two plain sentences","evidence":"an exact quote, copied character for character from one USER line","reason":"why it is durable","project":"project name if the fact is about one, else omit"}]}',
67
+ '{"facts":[{"title":"short label","content":"the fact as one or two plain sentences","evidence":"an exact quote, copied character for character from one USER line","reason":"why it is durable","type":"one of the types below","project":"project name if the fact is about one, else omit"}]}',
68
+ `type is one of: ${FACT_TYPES.join(", ")}. Use project only for a fact about one project, and then also give its project name; a fact about the user stays a personal type even when it came up in a project.`,
67
69
  'Answer {"facts":[]} when nothing qualifies.',
68
70
  "",
69
71
  "Conversation:",
@@ -113,6 +115,8 @@ export function parseFacts(text) {
113
115
  const project = clean(value.project, 64);
114
116
  if (project)
115
117
  fact.project = project;
118
+ if (isFactType(value.type))
119
+ fact.type = value.type;
116
120
  if (fact.title && fact.content && fact.evidence)
117
121
  facts.push(fact);
118
122
  if (facts.length === MAX_FACTS)
@@ -211,9 +215,11 @@ async function proposeLocked(options) {
211
215
  origin: "inferred",
212
216
  source: `${SESSION_FACTS_SOURCE_PREFIX}${options.sessionId}`,
213
217
  reason: fact.reason || "stated by the user in a session",
218
+ target: await factTarget(fact),
214
219
  meta: {
215
220
  kind: "fact",
216
221
  client: options.client,
222
+ ...(fact.type ? { type: fact.type } : {}),
217
223
  ...(fact.project ? { project: fact.project } : {}),
218
224
  },
219
225
  });
@@ -45,7 +45,7 @@ export async function promoteSessionToKnowledge(sessionId, openStore, target = "
45
45
  const slug = `${session.provider}-${sessionId.slice(0, 8)}`.replace(/[^a-zA-Z0-9-]+/g, "-");
46
46
  const file = path.join(oceanPath(KNOWLEDGE_DIR, match[1], `${slug}.md`));
47
47
  await mkdir(path.dirname(file), { recursive: true });
48
- await writeFile(file, `---\nname: ${slug}\ndescription: Human-approved result from an Ocean session\nmetadata:\n type: session-result\n domain: ${match[1]}\n status: current\n verification: human-approved\n source-session: ${sessionId}\n provider: ${session.provider}\n---\n\n# ${session.provider} review\n\n## Request\n\n${redactRuntimeText(input)}\n\n## Result\n\n${outputs.join("\n\n")}\n`);
48
+ await writeFile(file, `---\nname: ${slug}\ndescription: Human-approved result from an Ocean session\ntype: session-result\ndomain: ${match[1]}\nstatus: current\nverification: human-approved\nsource-session: ${sessionId}\nprovider: ${session.provider}\n---\n\n# ${session.provider} review\n\n## Request\n\n${redactRuntimeText(input)}\n\n## Result\n\n${outputs.join("\n\n")}\n`);
49
49
  store.appendEvent(sessionId, "knowledge_promoted", JSON.stringify({
50
50
  file: path.relative(oceanPath(KNOWLEDGE_DIR), file),
51
51
  target,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/brain",
3
- "version": "1.6.2",
3
+ "version": "1.8.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/context",
3
- "version": "1.6.2",
3
+ "version": "1.8.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -77,6 +77,8 @@ export const KNOWLEDGE_DIR = brainArea("05-knowledge");
77
77
  export const DAILY_DIR = brainArea("01-daily");
78
78
  export const INBOX_DIR = brainArea("00-inbox");
79
79
  export const TEMPLATES_DIR = brainArea("06-templates");
80
+ // The owner's own notes (T-314): agents read and index them, and never write there.
81
+ export const NOTES_DIR = brainArea("07-notes");
80
82
  export const INDEX_DIR = brainArea(".index");
81
83
  export const PROJECTS_DIR = brainArea("04-projects");
82
84
  // Every top-level brain area that holds markdown records (used by the doctor and the
@@ -88,6 +90,7 @@ export const BRAIN_RECORD_DIRS = [
88
90
  brainArea("03-professional"),
89
91
  KNOWLEDGE_DIR,
90
92
  TEMPLATES_DIR,
93
+ NOTES_DIR,
91
94
  ];
92
95
  // The workspace's own project. Callers use these helpers instead of a literal.
93
96
  export const WORKSPACE_PROJECT_ID = "ocean";
@@ -227,6 +230,10 @@ export const POLICIES_DIR = `${CHARTER_DIR}/policies`;
227
230
  export const STORE_DIR = {
228
231
  memory: PERSONAL_DIR,
229
232
  knowledge: KNOWLEDGE_DIR,
233
+ notes: NOTES_DIR,
234
+ // Session records and briefs (T-314), searchable beside memory and knowledge.
235
+ sessions: `${DAILY_DIR}/sessions`,
236
+ briefs: `${DAILY_DIR}/briefs`,
230
237
  };
231
238
  // Brain-index records are "<store>/<path inside store>" ("memory/x.md", "knowledge/decisions/y.md").
232
239
  // Project memory (T-296) is "project/<id>/<path>" for 04-projects/<id>/memory/<path>, and