@amoree-code/ocean 1.6.2 → 1.7.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 (79) hide show
  1. package/README.md +9 -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/interfaces/cli/brief-command.js +17 -0
  12. package/dist/interfaces/cli/capture-command.js +1 -1
  13. package/dist/interfaces/cli/clients-command.js +15 -2
  14. package/dist/interfaces/cli/command-registry.js +29 -2
  15. package/dist/interfaces/cli/desktop-command.js +124 -0
  16. package/dist/interfaces/cli/distill-command.js +36 -0
  17. package/dist/interfaces/cli/express-command.js +18 -0
  18. package/dist/interfaces/cli/help-command.js +30 -2
  19. package/dist/interfaces/cli/interests-command.js +33 -0
  20. package/dist/interfaces/cli/memory-command.js +37 -3
  21. package/dist/interfaces/cli/note-command.js +7 -0
  22. package/dist/interfaces/cli/setup-command.js +2 -1
  23. package/dist/interfaces/cli/telemetry-command.js +23 -0
  24. package/node_modules/@ocean/brain/dist/brain/brain-reindex.js +4 -1
  25. package/node_modules/@ocean/brain/dist/brain/brain-service.js +11 -1
  26. package/node_modules/@ocean/brain/dist/memory/brain-dump.js +73 -24
  27. package/node_modules/@ocean/brain/dist/memory/fact-routing.js +54 -0
  28. package/node_modules/@ocean/brain/dist/memory/frontmatter-flatten.js +89 -0
  29. package/node_modules/@ocean/brain/dist/memory/lessons.js +20 -0
  30. package/node_modules/@ocean/brain/dist/memory/memory-paths.js +3 -1
  31. package/node_modules/@ocean/brain/dist/memory/memory-review.js +19 -2
  32. package/node_modules/@ocean/brain/dist/memory/memory-write.js +45 -3
  33. package/node_modules/@ocean/brain/dist/memory/people.js +70 -0
  34. package/node_modules/@ocean/brain/dist/memory/routing.json +39 -0
  35. package/node_modules/@ocean/brain/dist/memory/session-facts.js +7 -1
  36. package/node_modules/@ocean/brain/dist/memory/session-promotion.js +1 -1
  37. package/node_modules/@ocean/brain/package.json +1 -1
  38. package/node_modules/@ocean/context/package.json +1 -1
  39. package/node_modules/@ocean/core/dist/shared/paths.js +7 -0
  40. package/node_modules/@ocean/core/package.json +1 -1
  41. package/node_modules/@ocean/loop/dist/handoff/handoff-service.js +5 -1
  42. package/node_modules/@ocean/loop/dist/hooks/desktop-facts.js +154 -0
  43. package/node_modules/@ocean/loop/dist/hooks/session-end-hook.js +1 -1
  44. package/node_modules/@ocean/loop/package.json +1 -1
  45. package/node_modules/@ocean/market/package.json +1 -1
  46. package/node_modules/@ocean/services/dist/brief/brief.js +218 -0
  47. package/node_modules/@ocean/services/dist/brief/interest-discovery.js +236 -0
  48. package/node_modules/@ocean/services/dist/brief/source-registry.json +35 -0
  49. package/node_modules/@ocean/services/dist/distill/distill.js +258 -0
  50. package/node_modules/@ocean/services/dist/doctor/workspace-doctor.js +129 -8
  51. package/node_modules/@ocean/services/dist/express/express.js +99 -0
  52. package/node_modules/@ocean/services/dist/infrastructure/mcp/ocean-server.js +17 -1
  53. package/node_modules/@ocean/services/dist/journey/telemetry.js +81 -0
  54. package/node_modules/@ocean/services/dist/obsidian/folder-templates.js +82 -0
  55. package/node_modules/@ocean/services/dist/onboarding/onboarding.js +62 -0
  56. package/node_modules/@ocean/services/package.json +1 -1
  57. package/ocean-marketplace.json +46 -28
  58. package/package.json +7 -7
  59. package/skills/core/weekly-review/SKILL.md +24 -0
  60. package/skills/index.json +6 -0
  61. package/templates/workspace/02-personal/education/study/study.base +15 -0
  62. package/templates/workspace/02-personal/milestones/milestones.base +14 -0
  63. package/templates/workspace/02-personal/people/people.base +18 -0
  64. package/templates/workspace/06-templates/TEMPLATES.md +12 -0
  65. package/templates/workspace/06-templates/capture.md +9 -0
  66. package/templates/workspace/06-templates/daily.md +13 -0
  67. package/templates/workspace/06-templates/decision.md +8 -0
  68. package/templates/workspace/06-templates/failure.md +13 -0
  69. package/templates/workspace/06-templates/intelligence.md +7 -0
  70. package/templates/workspace/06-templates/interest.md +13 -0
  71. package/templates/workspace/06-templates/lesson.md +16 -0
  72. package/templates/workspace/06-templates/milestone.md +10 -0
  73. package/templates/workspace/06-templates/note.md +8 -0
  74. package/templates/workspace/06-templates/person.md +15 -0
  75. package/templates/workspace/06-templates/session.md +10 -0
  76. package/templates/workspace/06-templates/solution.md +14 -0
  77. package/templates/workspace/06-templates/study.md +14 -0
  78. package/templates/workspace/07-notes/.gitkeep +0 -0
  79. package/templates/workspace/MANIFEST.json +14 -0
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/core",
3
- "version": "1.6.2",
3
+ "version": "1.7.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -32,7 +32,11 @@ export async function createHandoffWithStore(store, input) {
32
32
  const handoff = validateHandoff({
33
33
  handoffId: `handoff-${randomUUID()}`,
34
34
  taskId: task?.id ?? session?.taskId ?? null,
35
- title: input.title ?? task?.title ?? session?.title ?? "Ocean session handoff",
35
+ // A session's title defaults to "", which `??` would keep and the schema rejects.
36
+ title: input.title?.trim() ||
37
+ task?.title?.trim() ||
38
+ session?.title?.trim() ||
39
+ "Ocean session handoff",
36
40
  objective: task?.objective ??
37
41
  "Continue the selected Ocean session with bounded context.",
38
42
  state: task?.state ?? session?.status ?? "paused",
@@ -0,0 +1,154 @@
1
+ import { mkdir, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { sessionFactsEnabled } from "@ocean/brain/memory/memory-audit.js";
4
+ import { extractSessionFacts, proposeSessionFacts, } from "@ocean/brain/memory/session-facts.js";
5
+ import { atomicWrite, withFileLock } from "@ocean/core/shared/fs-utils.js";
6
+ import { oceanPath, SYSTEM_DIR } from "@ocean/core/shared/paths.js";
7
+ // Fact capture from Claude Desktop's plain chat (T-315). Desktop has no hooks, so a run reads
8
+ // the conversations the app keeps locally (the reader is injected: it lives in harness) and
9
+ // sends the new turns of each conversation that has gone quiet to the same extraction T-313
10
+ // uses. A per-conversation cursor — the creation time of the newest message already claimed,
11
+ // which the app's store and the official export both carry — makes every turn read once,
12
+ // whichever source it came from: a run claims (cursor, newest] under a short lock, calls the
13
+ // model unlocked,
14
+ // and hands the turns back if the model gave no answer. Candidates carry
15
+ // `source: session:desktop:<uuid>`, so they are never auto-approved. No message text is ever
16
+ // written outside the candidates themselves: the state file and the run report hold ids,
17
+ // times and counts only.
18
+ export const DESKTOP_CLIENT = "claude-desktop";
19
+ export const DEFAULT_QUIET_MS = 10 * 60 * 1000;
20
+ export function desktopFactsStateFile() {
21
+ return oceanPath(SYSTEM_DIR, "state", "memory", "desktop", "cursors.json");
22
+ }
23
+ // The last run's outcome, for `ocean doctor`: status, counts and an error code, never text.
24
+ export function desktopFactsLastRunFile() {
25
+ return oceanPath(SYSTEM_DIR, "state", "memory", "desktop", "last-run.json");
26
+ }
27
+ export async function recordDesktopRun(run) {
28
+ await mkdir(path.dirname(desktopFactsLastRunFile()), {
29
+ recursive: true,
30
+ mode: 0o700,
31
+ });
32
+ await atomicWrite(desktopFactsLastRunFile(), `${JSON.stringify(run, null, 2)}\n`, 0o600);
33
+ }
34
+ async function readState() {
35
+ try {
36
+ const parsed = JSON.parse(await readFile(desktopFactsStateFile(), "utf8"));
37
+ if (parsed && typeof parsed.conversations === "object") {
38
+ // Only claims in the current shape count; any other is read from the start.
39
+ for (const [uuid, claim] of Object.entries(parsed.conversations))
40
+ if (typeof claim?.to !== "string")
41
+ delete parsed.conversations[uuid];
42
+ return parsed;
43
+ }
44
+ }
45
+ catch {
46
+ // no state yet, or unreadable: start from the beginning of each conversation
47
+ }
48
+ return { conversations: {} };
49
+ }
50
+ async function writeState(state) {
51
+ await atomicWrite(desktopFactsStateFile(), `${JSON.stringify(state, null, 2)}\n`, 0o600);
52
+ }
53
+ async function locked(run) {
54
+ await mkdir(path.dirname(desktopFactsStateFile()), {
55
+ recursive: true,
56
+ mode: 0o700,
57
+ });
58
+ return withFileLock(desktopFactsStateFile(), async () => run(await readState()));
59
+ }
60
+ const toTurn = (message) => ({
61
+ role: message.sender === "human" ? "user" : "assistant",
62
+ text: message.text,
63
+ });
64
+ export async function runDesktopFacts(options) {
65
+ if (!(await (options.enabled ?? sessionFactsEnabled)()))
66
+ return { status: "off" };
67
+ const read = await options.read();
68
+ if (read.status === "absent")
69
+ return { status: "absent" };
70
+ const now = (options.now ?? new Date()).getTime();
71
+ const quietMs = options.quietMs ?? DEFAULT_QUIET_MS;
72
+ const result = {
73
+ status: "done",
74
+ conversations: read.conversations.length,
75
+ waiting: 0,
76
+ upToDate: 0,
77
+ runs: [],
78
+ };
79
+ for (const conversation of read.conversations) {
80
+ const updated = Date.parse(conversation.updatedAt);
81
+ if (options.since && !(updated >= options.since.getTime()))
82
+ continue;
83
+ // A conversation still being written is left for a later run.
84
+ if (!(updated <= now - quietMs)) {
85
+ result.waiting++;
86
+ continue;
87
+ }
88
+ const run = await captureOne(conversation, options.complete);
89
+ if (run)
90
+ result.runs.push(run);
91
+ else
92
+ result.upToDate++;
93
+ }
94
+ return result;
95
+ }
96
+ async function captureOne(conversation, complete) {
97
+ const dated = conversation.messages.filter((m) => m.createdAt);
98
+ const newest = dated.reduce((max, m) => (m.createdAt > max ? m.createdAt : max), "");
99
+ const claim = await locked(async (state) => {
100
+ const from = state.conversations[conversation.uuid]?.to ?? "";
101
+ // Nothing is claimed without a model, so a later run that has one still reads the turns.
102
+ if (newest <= from || !complete)
103
+ return { from, claimed: false };
104
+ state.conversations[conversation.uuid] = {
105
+ from,
106
+ to: newest,
107
+ at: new Date().toISOString(),
108
+ };
109
+ await writeState(state);
110
+ return { from, claimed: true };
111
+ });
112
+ const base = { uuid: conversation.uuid, from: claim.from, to: newest };
113
+ if (newest <= claim.from)
114
+ return null;
115
+ if (!claim.claimed || !complete)
116
+ return { ...base, status: "no-provider" };
117
+ const turns = dated
118
+ .filter((message) => message.createdAt > claim.from && message.text.trim())
119
+ .map(toTurn);
120
+ if (!turns.some((turn) => turn.role === "user"))
121
+ return { ...base, status: "no-user-text" };
122
+ const extraction = await extractSessionFacts({ turns, complete });
123
+ if (extraction.failed) {
124
+ // Nothing was learned: hand the turns back, unless a later run already claimed past them.
125
+ await locked(async (state) => {
126
+ const latest = state.conversations[conversation.uuid];
127
+ if (latest?.from === claim.from && latest.to === newest) {
128
+ if (!claim.from)
129
+ delete state.conversations[conversation.uuid];
130
+ else
131
+ state.conversations[conversation.uuid] = {
132
+ from: claim.from,
133
+ to: claim.from,
134
+ at: new Date().toISOString(),
135
+ };
136
+ await writeState(state);
137
+ }
138
+ });
139
+ return { ...base, status: "failed" };
140
+ }
141
+ const proposed = await proposeSessionFacts({
142
+ sessionId: `desktop:${conversation.uuid}`,
143
+ client: DESKTOP_CLIENT,
144
+ facts: extraction.facts,
145
+ });
146
+ return {
147
+ ...base,
148
+ status: "done",
149
+ candidates: proposed.proposed,
150
+ rejected: extraction.rejected.length,
151
+ skipped: proposed.skipped.length,
152
+ };
153
+ }
154
+ //# sourceMappingURL=desktop-facts.js.map
@@ -132,7 +132,7 @@ export async function readTranscriptEvents(transcriptPath, client = "claude") {
132
132
  * its transcript as bounded user_input/provider_output events, and runs it
133
133
  * through the same finalizeSession pipeline as `ocean run` and `ocean
134
134
  * intercept` sessions — producing the summary, daily narrative, and
135
- * brain/00-inbox/brain-dump/ entry. Reuses the sessionId Claude Code itself
135
+ * session record in 01-daily/sessions/YYYY-MM/ (T-314). Reuses the sessionId Claude Code itself
136
136
  * assigned, so a hook re-run for the same session (e.g. `/clear` followed by
137
137
  * another SessionEnd) is idempotent via finalizeSession's own closeout guard.
138
138
  * Best-effort throughout: any failure is swallowed so a broken hook can never
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/loop",
3
- "version": "1.6.2",
3
+ "version": "1.7.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/market",
3
- "version": "1.6.2",
3
+ "version": "1.7.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,218 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readdir, readFile, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { atomicWrite, parseFrontmatter } from "@ocean/core/shared/fs-utils.js";
5
+ import { DAILY_DIR, KNOWLEDGE_DIR, NOTES_DIR, oceanPath, PERSONAL_DIR, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
6
+ // The daily brief (T-314): what moved in the things the owner follows. Interests are files in
7
+ // 02-personal/interests/ (`type: interest`, priority, keywords, sources); a source is a feed URL
8
+ // (RSS or Atom) or `github:<owner>/<repo>` for that repo's releases. A seen-ledger keeps an item
9
+ // from coming back. Daily: high-priority interests only, five items at most. Weekly: every
10
+ // interest, fifteen at most. No model and no web search here: the brief is the feed, filtered.
11
+ export const INTERESTS_DIR = `${PERSONAL_DIR}/interests`;
12
+ const BRIEFS_DIR = `${DAILY_DIR}/briefs`;
13
+ const DAILY_LIMIT = 5;
14
+ const WEEKLY_LIMIT = 15;
15
+ const FETCH_TIMEOUT_MS = 10_000;
16
+ function listField(block, key) {
17
+ const lines = block.split("\n");
18
+ const index = lines.findIndex((line) => line.startsWith(`${key}:`));
19
+ if (index < 0)
20
+ return [];
21
+ const unquote = (item) => item.trim().replace(/^["']|["']$/g, "");
22
+ const inline = /\[(.*)\]/.exec(lines[index]);
23
+ if (inline)
24
+ return inline[1].split(",").map(unquote).filter(Boolean);
25
+ const items = [];
26
+ for (const line of lines.slice(index + 1)) {
27
+ const match = /^\s+-\s*(.+)$/.exec(line);
28
+ if (!match)
29
+ break;
30
+ items.push(unquote(match[1]));
31
+ }
32
+ return items.filter(Boolean);
33
+ }
34
+ export async function listInterests() {
35
+ const dir = oceanPath(INTERESTS_DIR);
36
+ const names = await readdir(dir).catch(() => []);
37
+ const interests = [];
38
+ for (const name of names.sort()) {
39
+ if (!name.endsWith(".md") || name.startsWith("."))
40
+ continue;
41
+ const source = (await readFile(path.join(dir, name), "utf8")).replace(/\r\n/g, "\n");
42
+ const fields = parseFrontmatter(source);
43
+ if (fields.type !== "interest")
44
+ continue;
45
+ const end = source.startsWith("---") ? source.indexOf("\n---", 3) : -1;
46
+ const block = end < 0 ? "" : source.slice(3, end);
47
+ const heading = /^#\s+(.+)$/m.exec(end < 0 ? source : source.slice(end + 4));
48
+ const priority = ["high", "medium", "low"].includes(fields.priority ?? "")
49
+ ? fields.priority
50
+ : "medium";
51
+ interests.push({
52
+ file: `${INTERESTS_DIR}/${name}`,
53
+ name: heading?.[1]?.trim() ?? name.replace(/\.md$/, ""),
54
+ priority,
55
+ keywords: listField(block, "keywords"),
56
+ sources: listField(block, "sources"),
57
+ });
58
+ }
59
+ return interests;
60
+ }
61
+ export function sourceUrl(source) {
62
+ const github = /^github:([\w.-]+\/[\w.-]+)$/.exec(source);
63
+ if (github)
64
+ return `https://github.com/${github[1]}/releases.atom`;
65
+ return /^https:\/\//.test(source) ? source : null;
66
+ }
67
+ const decode = (text) => text
68
+ .replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1")
69
+ .replace(/<[^>]+>/g, "")
70
+ .replace(/&lt;/g, "<")
71
+ .replace(/&gt;/g, ">")
72
+ .replace(/&quot;/g, '"')
73
+ .replace(/&#39;/g, "'")
74
+ .replace(/&amp;/g, "&")
75
+ .replace(/\s+/g, " ")
76
+ .trim();
77
+ // Atom <entry> and RSS <item>, read by pattern: a feed is untrusted text, never executed.
78
+ export function parseFeed(xml) {
79
+ const items = [];
80
+ for (const match of xml.matchAll(/<(entry|item)\b[\s\S]*?<\/\1>/g)) {
81
+ const block = match[0];
82
+ const tag = (name) => new RegExp(`<${name}\\b[^>]*>([\\s\\S]*?)</${name}>`).exec(block)?.[1];
83
+ const title = decode(tag("title") ?? "");
84
+ const link = /<link\b[^>]*href="([^"]+)"/.exec(block)?.[1] ??
85
+ decode(tag("link") ?? "");
86
+ const date = decode(tag("updated") ?? tag("published") ?? tag("pubDate") ?? "");
87
+ // A link that could break out of the markdown line it is written into is dropped.
88
+ if (title && /^https:\/\/[^\s()<>[\]]+$/.test(link))
89
+ items.push({
90
+ title: title.replace(/[<>[\]]/g, "").slice(0, 200),
91
+ link,
92
+ date: Number.isNaN(Date.parse(date))
93
+ ? ""
94
+ : new Date(date).toISOString(),
95
+ });
96
+ }
97
+ return items;
98
+ }
99
+ const defaultFetch = async (url) => {
100
+ try {
101
+ const response = await fetch(url, {
102
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
103
+ headers: { "user-agent": "ocean-brief" },
104
+ });
105
+ return response.ok ? await response.text() : null;
106
+ }
107
+ catch {
108
+ return null;
109
+ }
110
+ };
111
+ const seenFile = () => oceanPath(SYSTEM_DIR, "state", "brief", "seen.json");
112
+ const itemKey = (item) => createHash("sha256").update(item.link).digest("hex").slice(0, 24);
113
+ async function readSeen() {
114
+ try {
115
+ return JSON.parse(await readFile(seenFile(), "utf8"));
116
+ }
117
+ catch {
118
+ return {};
119
+ }
120
+ }
121
+ const REEVALUATE_DAYS = 90;
122
+ // One thing from the past per daily brief (T-314): the decision verified longest ago, once that is
123
+ // more than 90 days back (it needs re-evaluation), else the owner's least recently touched note.
124
+ export async function pickResurface(date) {
125
+ const cutoff = Date.parse(date) - REEVALUATE_DAYS * 24 * 60 * 60 * 1000;
126
+ const decisions = oceanPath(KNOWLEDGE_DIR, "decisions");
127
+ let oldest = null;
128
+ for (const name of await readdir(decisions).catch(() => [])) {
129
+ if (!name.endsWith(".md"))
130
+ continue;
131
+ const fields = parseFrontmatter(await readFile(path.join(decisions, name), "utf8"));
132
+ if (fields.status === "retired" || fields.status === "superseded")
133
+ continue;
134
+ const at = Date.parse(fields.last_verified ?? fields.updated ?? "");
135
+ if (Number.isNaN(at) || at >= cutoff)
136
+ continue;
137
+ if (!oldest || at < oldest.at)
138
+ oldest = { file: name, at };
139
+ }
140
+ if (oldest)
141
+ return `${KNOWLEDGE_DIR}/decisions/${oldest.file} — needs re-evaluation (last verified ${new Date(oldest.at).toISOString().slice(0, 10)})`;
142
+ const notes = oceanPath(NOTES_DIR);
143
+ let quiet = null;
144
+ for (const name of await readdir(notes).catch(() => [])) {
145
+ if (!name.endsWith(".md"))
146
+ continue;
147
+ const at = (await stat(path.join(notes, name))).mtimeMs;
148
+ if (!quiet || at < quiet.at)
149
+ quiet = { file: name, at };
150
+ }
151
+ return quiet
152
+ ? `${NOTES_DIR}/${quiet.file} — one of your notes, worth a second look`
153
+ : null;
154
+ }
155
+ export async function buildBrief(options) {
156
+ const fetchText = options.fetchText ?? defaultFetch;
157
+ const seen = await readSeen();
158
+ const failedSources = [];
159
+ const found = [];
160
+ const order = { high: 0, medium: 1, low: 2 };
161
+ const interests = (await listInterests())
162
+ .filter((interest) => options.weekly || interest.priority === "high")
163
+ .sort((a, b) => order[a.priority] - order[b.priority]);
164
+ for (const interest of interests) {
165
+ const keywords = interest.keywords.map((word) => word.toLowerCase());
166
+ for (const source of interest.sources) {
167
+ const url = sourceUrl(source);
168
+ const xml = url ? await fetchText(url) : null;
169
+ if (xml === null) {
170
+ failedSources.push(source);
171
+ continue;
172
+ }
173
+ for (const item of parseFeed(xml)) {
174
+ if (seen[itemKey(item)])
175
+ continue;
176
+ if (found.some((other) => other.link === item.link))
177
+ continue;
178
+ // A releases feed is wanted whole; a general feed is narrowed by the keywords.
179
+ const general = !source.startsWith("github:");
180
+ if (general &&
181
+ keywords.length &&
182
+ !keywords.some((word) => item.title.toLowerCase().includes(word)))
183
+ continue;
184
+ found.push({
185
+ ...item,
186
+ interest: interest.name,
187
+ rank: order[interest.priority],
188
+ });
189
+ }
190
+ }
191
+ }
192
+ const limit = options.weekly ? WEEKLY_LIMIT : DAILY_LIMIT;
193
+ // Higher priority first, then newest; feed order breaks ties (Array.sort is stable).
194
+ const items = [...found]
195
+ .sort((a, b) => a.rank - b.rank || b.date.localeCompare(a.date))
196
+ .slice(0, limit)
197
+ .map(({ rank: _rank, ...item }) => item);
198
+ const resurface = options.weekly ? null : await pickResurface(options.date);
199
+ // A day with nothing new still gets its Resurface line.
200
+ if (options.dryRun || (!items.length && !resurface))
201
+ return { file: null, items, failedSources, resurface };
202
+ const relative = `${BRIEFS_DIR}/${options.date}${options.weekly ? "-weekly" : ""}.md`;
203
+ const lines = items.map((item) => `- **${item.interest}** — [${item.title.replace(/[[\]]/g, "")}](${item.link})${item.date ? ` (${item.date.slice(0, 10)})` : ""}`);
204
+ const file = oceanPath(relative);
205
+ // A second run the same day adds to that day's brief; the items already there stay.
206
+ const earlier = (await readFile(file, "utf8").catch(() => ""))
207
+ .split("\n")
208
+ .filter((line) => line.startsWith("- **"));
209
+ const all = [...earlier, ...lines];
210
+ await mkdir(path.dirname(file), { recursive: true });
211
+ await atomicWrite(file, `---\ntype: brief\ndate: ${options.date}\ncadence: ${options.weekly ? "weekly" : "daily"}\nitems: ${all.length}\n---\n\n# Brief — ${options.date}\n\n${all.join("\n")}\n${resurface ? `\n## Resurface\n\n- ${resurface}\n` : ""}`);
212
+ for (const item of items)
213
+ seen[itemKey(item)] = options.date;
214
+ await mkdir(path.dirname(seenFile()), { recursive: true });
215
+ await atomicWrite(seenFile(), `${JSON.stringify(seen, null, 2)}\n`, 0o600);
216
+ return { file: relative, items, failedSources, resurface };
217
+ }
218
+ //# sourceMappingURL=brief.js.map
@@ -0,0 +1,236 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { listCandidates } from "@ocean/brain/memory/memory-review.js";
4
+ import { proposeMemory } from "@ocean/brain/memory/memory-write.js";
5
+ import { MemoryContractError } from "@ocean/core/domain/mcp/memory-contract.js";
6
+ import { atomicWrite, parseFrontmatter } from "@ocean/core/shared/fs-utils.js";
7
+ import { localDate } from "@ocean/core/shared/local-date.js";
8
+ import { DAILY_DIR, oceanPath } from "@ocean/core/shared/paths.js";
9
+ import { expandHome, listProjectManifests, projectSlug, } from "@ocean/core/shared/project-resolution.js";
10
+ import { INTERESTS_DIR, listInterests } from "./brief.js";
11
+ import registry from "./source-registry.json" with { type: "json" };
12
+ const SOURCES = registry;
13
+ // Packages the registered projects depend on, mapped through the source registry.
14
+ export async function discoverStack() {
15
+ const byTopic = new Map();
16
+ for (const manifest of await listProjectManifests()) {
17
+ for (const folder of manifest.paths ?? []) {
18
+ let pkg;
19
+ try {
20
+ // Paths are stored portable (`~/…`).
21
+ pkg = JSON.parse(await readFile(path.join(expandHome(folder), "package.json"), "utf8"));
22
+ }
23
+ catch {
24
+ continue;
25
+ }
26
+ const deps = {
27
+ ...pkg.dependencies,
28
+ ...pkg.devDependencies,
29
+ };
30
+ for (const name of Object.keys(deps)) {
31
+ const entry = Object.hasOwn(SOURCES, name) ? SOURCES[name] : null;
32
+ if (!entry)
33
+ continue;
34
+ const found = byTopic.get(entry.topic) ?? {
35
+ topic: entry.topic,
36
+ source: entry.source,
37
+ projects: [],
38
+ };
39
+ if (!found.projects.includes(manifest.id))
40
+ found.projects.push(manifest.id);
41
+ byTopic.set(entry.topic, found);
42
+ }
43
+ }
44
+ }
45
+ return [...byTopic.values()].sort((a, b) => b.projects.length - a.projects.length || a.topic.localeCompare(b.topic));
46
+ }
47
+ // Each topic without an interest file yet becomes one candidate (dry run unless apply). Shared by
48
+ // every way Ocean learns what the owner follows: his projects, his own answers, his sessions.
49
+ export async function proposeInterests(items, options) {
50
+ const existing = await listInterests();
51
+ const have = new Set(existing.flatMap((interest) => [
52
+ projectSlug(interest.name),
53
+ ...interest.sources,
54
+ ]));
55
+ const waiting = new Set((await listCandidates()).map((item) => item.target));
56
+ const result = { proposed: [], known: [], pending: [] };
57
+ const batch = new Set();
58
+ for (const item of items) {
59
+ const slug = projectSlug(item.topic);
60
+ // The same topic twice in one batch (stack and topics both name it) is one proposal.
61
+ if (!slug || batch.has(slug))
62
+ continue;
63
+ batch.add(slug);
64
+ if (have.has(slug) || item.sources.some((source) => have.has(source))) {
65
+ result.known.push(item.topic);
66
+ continue;
67
+ }
68
+ if (waiting.has(`${INTERESTS_DIR}/${slug}.md`)) {
69
+ result.pending.push({
70
+ topic: item.topic,
71
+ reason: "a candidate waits for review",
72
+ });
73
+ continue;
74
+ }
75
+ if (!options.apply) {
76
+ result.proposed.push(item.topic);
77
+ continue;
78
+ }
79
+ const list = (values) => `[${values.map((value) => JSON.stringify(value)).join(", ")}]`;
80
+ try {
81
+ const { candidate } = await proposeMemory({
82
+ content: `---\ntype: interest\npriority: medium\nkeywords: ${list(item.keywords)}\nsources: ${list(item.sources)}\ncadence: weekly\norigin: ${options.origin}\nweight: 1\nlast_signal: ${localDate()}\n---\n\n# ${item.topic.replace(/\s+/g, " ").trim()}\n\n${item.note}\n`,
83
+ origin: "inferred",
84
+ source: options.source,
85
+ target: `${INTERESTS_DIR}/${slug}.md`,
86
+ reason: item.reason,
87
+ meta: { kind: "interest" },
88
+ });
89
+ result.proposed.push(candidate);
90
+ }
91
+ catch (error) {
92
+ if (!(error instanceof MemoryContractError))
93
+ throw error;
94
+ result.pending.push({
95
+ topic: item.topic,
96
+ reason: `${error.code}: ${error.message}`,
97
+ });
98
+ }
99
+ }
100
+ return result;
101
+ }
102
+ export async function proposeDiscoveredInterests(options) {
103
+ const found = await discoverStack();
104
+ const result = await proposeInterests(found.map((item) => ({
105
+ topic: item.topic,
106
+ sources: [item.source],
107
+ keywords: [],
108
+ reason: `a dependency of ${item.projects.length} registered project(s)`,
109
+ note: `Used in: ${item.projects.join(", ")}.`,
110
+ })), {
111
+ apply: options.apply,
112
+ origin: "discovered",
113
+ source: "interest-discovery",
114
+ });
115
+ return { ...result, found };
116
+ }
117
+ // A topic the owner names (setup's onboarding question) is matched to the registry by topic or
118
+ // package name for its feed; one the registry does not know is followed by its keywords alone.
119
+ export function topicProposal(topic, reason) {
120
+ const wanted = topic.trim().toLowerCase();
121
+ const entry = Object.entries(SOURCES).find(([name, item]) => name === wanted || item.topic.toLowerCase() === wanted)?.[1];
122
+ return {
123
+ topic: entry?.topic ?? topic.trim(),
124
+ sources: entry ? [entry.source] : [],
125
+ keywords: entry ? [] : [wanted],
126
+ reason,
127
+ note: entry ? "" : "Add a feed under sources to follow it in the brief.",
128
+ };
129
+ }
130
+ const SIGNAL_SESSIONS = 3;
131
+ // Implicit signal: a registry topic named in at least three session records of the last `weeks`
132
+ // weeks (or a tag they carry) is proposed as an interest. Proposed, never added.
133
+ export async function sessionSignals(options) {
134
+ const cutoff = new Date(Date.parse(options.today ?? localDate()) -
135
+ (options.weeks ?? 4) * 7 * 24 * 60 * 60 * 1000)
136
+ .toISOString()
137
+ .slice(0, 10);
138
+ const topics = [...new Set(Object.values(SOURCES).map((item) => item.topic))];
139
+ const counts = new Map();
140
+ const root = oceanPath(DAILY_DIR, "sessions");
141
+ for (const month of await readdir(root).catch(() => [])) {
142
+ if (!/^\d{4}-\d{2}$/.test(month) || `${month}-31` < cutoff)
143
+ continue;
144
+ for (const name of await readdir(path.join(root, month)).catch(() => [])) {
145
+ if (!name.endsWith(".md"))
146
+ continue;
147
+ const text = await readFile(path.join(root, month, name), "utf8").catch(() => "");
148
+ const fields = parseFrontmatter(text);
149
+ if (fields.type !== "session" || (fields.date ?? "") < cutoff)
150
+ continue;
151
+ const seen = new Set();
152
+ for (const topic of topics)
153
+ if (new RegExp(`(^|[^\\w.])${escapeRegex(topic)}(?![\\w])`, "i").test(text))
154
+ seen.add(topic);
155
+ const tags = /^tags:\s*\[(.*)\]/m.exec(text)?.[1] ?? "";
156
+ for (const tag of tags.split(","))
157
+ if (tag.trim())
158
+ seen.add(tag.trim().replace(/^["']|["']$/g, ""));
159
+ for (const topic of seen)
160
+ counts.set(topic, (counts.get(topic) ?? 0) + 1);
161
+ }
162
+ }
163
+ return [...counts]
164
+ .filter(([, sessions]) => sessions >= SIGNAL_SESSIONS)
165
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
166
+ .map(([topic, sessions]) => ({ topic, sessions }));
167
+ }
168
+ const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
169
+ export async function proposeSignalInterests(options) {
170
+ const signals = await sessionSignals(options);
171
+ const result = await proposeInterests(signals.map((signal) => ({
172
+ ...topicProposal(signal.topic, `named in ${signal.sessions} recent session records`),
173
+ note: `Came up in ${signal.sessions} sessions in the last ${options.weeks ?? 4} weeks.`,
174
+ })), { apply: options.apply, origin: "signal", source: "session-signals" });
175
+ return { ...result, signals };
176
+ }
177
+ function setField(source, key, value) {
178
+ const end = source.indexOf("\n---", 3);
179
+ if (!source.startsWith("---") || end < 0)
180
+ return source;
181
+ const head = source.slice(0, end);
182
+ const line = new RegExp(`^${key}:.*$`, "m");
183
+ const next = line.test(head)
184
+ ? head.replace(line, `${key}: ${value}`)
185
+ : `${head}\n${key}: ${value}`;
186
+ return next + source.slice(end);
187
+ }
188
+ const WEIGHT_STEP = 0.25;
189
+ const clampWeight = (value) => Math.round(Math.min(3, Math.max(0, value)) * 100) / 100;
190
+ async function readWeight(file) {
191
+ const text = await readFile(oceanPath(file), "utf8");
192
+ const weight = Number(/^weight:\s*([\d.]+)/m.exec(text)?.[1] ?? 1);
193
+ return { text, weight: Number.isFinite(weight) ? weight : 1 };
194
+ }
195
+ // keep → weight up and a fresh signal; skip → weight down. Found by exact name or file slug.
196
+ export async function interestFeedback(name, verdict, today = localDate()) {
197
+ const wanted = projectSlug(name);
198
+ const interest = (await listInterests()).find((item) => projectSlug(item.name) === wanted ||
199
+ path.basename(item.file, ".md") === wanted);
200
+ if (!interest)
201
+ throw new Error(`no interest named '${name}'`);
202
+ const { text, weight } = await readWeight(interest.file);
203
+ const next = clampWeight(weight + (verdict === "keep" ? WEIGHT_STEP : -WEIGHT_STEP));
204
+ let updated = setField(text, "weight", String(next));
205
+ if (verdict === "keep")
206
+ updated = setField(updated, "last_signal", today);
207
+ await atomicWrite(oceanPath(interest.file), updated);
208
+ return { file: interest.file, weight: next };
209
+ }
210
+ // An interest with no signal for `weeks` loses one step of weight (dry run unless apply). An
211
+ // interest the owner wrote himself (`origin: owner`, or none) is never decayed.
212
+ export async function decayInterests(options) {
213
+ const today = Date.parse(options.today ?? localDate());
214
+ const cutoff = today - (options.weeks ?? 8) * 7 * 24 * 60 * 60 * 1000;
215
+ const changed = [];
216
+ for (const interest of await listInterests()) {
217
+ const { text, weight } = await readWeight(interest.file);
218
+ const origin = /^origin:\s*(\S+)/m.exec(text)?.[1] ?? "owner";
219
+ if (origin === "owner")
220
+ continue;
221
+ // The later of the last signal and the last decay: one step per window, not per run.
222
+ const dates = [/^last_signal:\s*(\S+)/m, /^decayed:\s*(\S+)/m]
223
+ .map((pattern) => Date.parse(pattern.exec(text)?.[1] ?? ""))
224
+ .filter((time) => !Number.isNaN(time));
225
+ if (dates.length && Math.max(...dates) >= cutoff)
226
+ continue;
227
+ const to = clampWeight(weight - WEIGHT_STEP);
228
+ if (to === weight)
229
+ continue;
230
+ changed.push({ file: interest.file, from: weight, to });
231
+ if (options.apply)
232
+ await atomicWrite(oceanPath(interest.file), setField(setField(text, "weight", String(to)), "decayed", options.today ?? localDate()));
233
+ }
234
+ return changed;
235
+ }
236
+ //# sourceMappingURL=interest-discovery.js.map