@amoree-code/ocean 2.13.0 → 2.15.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 (32) hide show
  1. package/dist/application/upkeep/nightly-upkeep.js +1 -1
  2. package/dist/infrastructure/process/service.js +17 -0
  3. package/dist/interfaces/cli/brief-command.js +1 -1
  4. package/dist/interfaces/cli/command-registry.js +2 -1
  5. package/dist/interfaces/cli/harvest-command.js +4 -3
  6. package/dist/interfaces/cli/help-command.js +5 -5
  7. package/dist/interfaces/cli/scorecard-command.js +1 -1
  8. package/dist/interfaces/cli/setup-command.js +20 -2
  9. package/dist/interfaces/cli/tasks-command.js +31 -1
  10. package/node_modules/@ocean/brain/dist/memory/brain-dump.js +196 -26
  11. package/node_modules/@ocean/brain/dist/memory/routing.json +3 -3
  12. package/node_modules/@ocean/brain/package.json +1 -1
  13. package/node_modules/@ocean/context/package.json +1 -1
  14. package/node_modules/@ocean/core/dist/shared/paths.js +12 -1
  15. package/node_modules/@ocean/core/package.json +1 -1
  16. package/node_modules/@ocean/loop/dist/tasks/archive-tasks.js +1 -1
  17. package/node_modules/@ocean/loop/dist/tasks/sync-task-prs.js +122 -0
  18. package/node_modules/@ocean/loop/package.json +1 -1
  19. package/node_modules/@ocean/market/package.json +1 -1
  20. package/node_modules/@ocean/services/dist/brief/brief.js +2 -2
  21. package/node_modules/@ocean/services/dist/day/day.js +6 -5
  22. package/node_modules/@ocean/services/dist/distill/distill.js +8 -8
  23. package/node_modules/@ocean/services/dist/harvest/harvest.js +56 -31
  24. package/node_modules/@ocean/services/dist/hygiene/hygiene.js +2 -2
  25. package/node_modules/@ocean/services/dist/scorecard/scorecard.js +2 -2
  26. package/node_modules/@ocean/services/dist/upkeep/upkeep.js +2 -2
  27. package/node_modules/@ocean/services/package.json +1 -1
  28. package/ocean-marketplace.json +38 -38
  29. package/package.json +7 -7
  30. package/skills/core/daily-harvest/SKILL.md +3 -3
  31. package/skills/core/weekly-review/SKILL.md +1 -1
  32. package/templates/workspace/charter/policies/task.md +4 -1
@@ -9,7 +9,7 @@ import { scorecardFile, searchEvalFile, } from "@ocean/services/scorecard/scorec
9
9
  import { previousScorecard, renderDigest, runUpkeepJobs, scorecardMoves, writeDigest, } from "@ocean/services/upkeep/upkeep.js";
10
10
  import { listSchedules } from "../scheduler/local-scheduler.js";
11
11
  // Nightly upkeep (T-322): each job is a child `ocean` process with a timeout; the results become
12
- // the morning digest in 01-daily/digest/. Once a day through `ocean rhythm` (ifDue), and the
12
+ // the morning digest in 01-daily/reports/digest/. Once a day through `ocean rhythm` (ifDue), and the
13
13
  // monthly memory hygiene joins the first run of a month that has no report yet.
14
14
  const MINUTE = 60_000;
15
15
  const OUTPUT_LIMIT = 4 * 1024 * 1024;
@@ -112,6 +112,23 @@ export function startBackgroundSchedules() {
112
112
  // the next tick runs it
113
113
  }
114
114
  }
115
+ // Task state follows linked GitHub PRs (open → in-qa, merged → done via the completion gate).
116
+ // Session starts run it in the background; it needs `gh` and never blocks the session.
117
+ export function startBackgroundTaskSync() {
118
+ if (process.env.OCEAN_NO_PULL_ON_START === "1")
119
+ return;
120
+ try {
121
+ spawn(process.execPath, [process.argv[1], "tasks", "sync", "--all"], {
122
+ detached: true,
123
+ stdio: "ignore",
124
+ })
125
+ .on("error", () => { })
126
+ .unref();
127
+ }
128
+ catch {
129
+ // the next session start runs it
130
+ }
131
+ }
115
132
  const runCommand = (command, args) => promisify(execFile)(command, args);
116
133
  function serviceContext(options) {
117
134
  const home = options.home ?? os.homedir();
@@ -1,7 +1,7 @@
1
1
  import { localDate } from "@ocean/core/shared/local-date.js";
2
2
  import { buildBrief } from "@ocean/services/brief/brief.js";
3
3
  // `ocean brief [--weekly] [--dry-run] [--date YYYY-MM-DD]` (T-314): what moved in what the owner
4
- // follows, written to 01-daily/briefs/.
4
+ // follows, written to 01-daily/reports/briefs/.
5
5
  export async function runBriefCommand(args) {
6
6
  const at = args.indexOf("--date");
7
7
  const date = at >= 0 ? args[at + 1] : localDate();
@@ -45,7 +45,7 @@ import { selectProfileForTask } from "../../application/profiles/profile-suggest
45
45
  import { listSchedules, runDueSchedules, runSchedule, runSchedulerWorker, runSchedulerWorkerOnce, saveSchedule, setScheduleEnabled, } from "../../application/scheduler/local-scheduler.js";
46
46
  import { defaultAgentRuntime, defaultBrainIndexPort, defaultProviderRegistry, defaultSessionStoreFactory, defaultSessionStoreOpener, defaultWrapperManager, } from "../../composition/runtime.js";
47
47
  import { loadRuntimeConfig } from "../../infrastructure/filesystem/runtime-config-loader.js";
48
- import { ensureService, restartService, runService, startBackgroundPull, startBackgroundRhythm, } from "../../infrastructure/process/service.js";
48
+ import { ensureService, restartService, runService, startBackgroundPull, startBackgroundRhythm, startBackgroundTaskSync, } from "../../infrastructure/process/service.js";
49
49
  import { createOllamaEmbedder } from "../../infrastructure/providers/ollama-embedder.js";
50
50
  import { loadProviderRegistry } from "../../infrastructure/providers/provider-registry.js";
51
51
  import { installShellPath, registerProvider, setProviderEnabled, syncProviderWrappers, wrapperDoctor, wrapperStatus, } from "../../infrastructure/wrappers/wrapper-manager.js";
@@ -695,6 +695,7 @@ async function commandHook() {
695
695
  startBackgroundSync();
696
696
  startBackgroundPull();
697
697
  startBackgroundRhythm();
698
+ startBackgroundTaskSync();
698
699
  const inline = flags.find((arg) => arg.startsWith("--client="));
699
700
  const clientIndex = flags.indexOf("--client");
700
701
  const client = inline
@@ -4,8 +4,9 @@ import { archiveHarvested, harvestDay, pendingDays, undoDay, } from "@ocean/serv
4
4
  const USAGE = "Usage: ocean harvest [--date YYYY-MM-DD | --pending] [--yes] | archive [--days N] [--yes] | undo <YYYY-MM-DD>";
5
5
  const DATE = /^\d{4}-\d{2}-\d{2}$/;
6
6
  // `ocean harvest` (T-314): a day's sessions from every AI client into that day's summary, their
7
- // decisions, fixes and lessons into 05-knowledge on their own (undo per day), then archiving after
8
- // 30 days. A dry run until --yes. The service runs `--pending --yes` once a day.
7
+ // decisions, fixes and lessons into 05-knowledge on their own (undo per day), then archiving the
8
+ // day's note after 7 days and its session records after 30. A dry run until --yes. The service
9
+ // runs `--pending --yes` once a day.
9
10
  export async function runHarvestCommand(args) {
10
11
  const apply = args.includes("--yes");
11
12
  const [action] = args;
@@ -18,7 +19,7 @@ export async function runHarvestCommand(args) {
18
19
  }
19
20
  if (action === "archive") {
20
21
  const at = args.indexOf("--days");
21
- const days = at >= 0 ? Number(args[at + 1]) : 30;
22
+ const days = at >= 0 ? Number(args[at + 1]) : 7;
22
23
  if (!(days > 0))
23
24
  throw new Error(USAGE);
24
25
  const result = await archiveHarvested({ today: localDate(), days, apply });
@@ -48,7 +48,7 @@ export const commandHelp = {
48
48
  ],
49
49
  tasks: [
50
50
  "List, create, claim, checkpoint, verify and complete tasks.",
51
- "ocean tasks list [state] [--project <id>] [--pretty]|new <title> [--project <id>]|doctor [--all]|index [--write]|checkpoint <id> --note <text> [--next <text>]|verify <id>|complete <id>|claim <id> --by <name> [--paths a,b] [--force]|release <id> [--by <name>] [--force]|archive [--apply|--auto]|renumber --project <id> --prefix <PREFIX> [--write]",
51
+ "ocean tasks list [state] [--project <id>] [--pretty]|new <title> [--project <id>]|doctor [--all]|index [--write]|checkpoint <id> --note <text> [--next <text>]|verify <id>|complete <id>|sync [--all] [--dry-run]|claim <id> --by <name> [--paths a,b] [--force]|release <id> [--by <name>] [--force]|archive [--apply|--auto]|renumber --project <id> --prefix <PREFIX> [--write]",
52
52
  ],
53
53
  loop: [
54
54
  "Start, inspect and stop task loops (repeated agent runs on one task).",
@@ -157,7 +157,7 @@ export const commandHelp = {
157
157
  "ocean capture add <idea>|scan [session-id]|list [status]|promote <id> <target>|discard <id>",
158
158
  ],
159
159
  brief: [
160
- "Write today's brief from your interests' feeds to 01-daily/briefs/ (high priority daily, all weekly).",
160
+ "Write today's brief from your interests' feeds to 01-daily/reports/briefs/ (high priority daily, all weekly).",
161
161
  "ocean brief [--weekly] [--dry-run] [--date YYYY-MM-DD]",
162
162
  ],
163
163
  interests: [
@@ -165,7 +165,7 @@ export const commandHelp = {
165
165
  "ocean interests discover [--yes] | signals [--weeks N] [--yes] | decay [--weeks N] [--yes] | keep <name> | skip <name>",
166
166
  ],
167
167
  distill: [
168
- "Distill a week (digest in 01-daily/weekly/, decisions and lessons as candidates), or review last month against goals.md (01-daily/monthly/).",
168
+ "Distill a week (digest in 01-daily/reports/weekly/, decisions and lessons as candidates), or review last month against goals.md (01-daily/reports/monthly/).",
169
169
  "ocean distill --week [--date YYYY-MM-DD] [--yes] | --month [--month-of YYYY-MM] [--yes]",
170
170
  ],
171
171
  harvest: [
@@ -177,7 +177,7 @@ export const commandHelp = {
177
177
  "ocean rhythm [--yes]",
178
178
  ],
179
179
  upkeep: [
180
- "Run the nightly jobs (doctor, telemetry, reindex, search eval, curator, scorecard), no model, and write the morning digest to 01-daily/digest/.",
180
+ "Run the nightly jobs (doctor, telemetry, reindex, search eval, curator, scorecard), no model, and write the morning digest to 01-daily/reports/digest/.",
181
181
  "ocean upkeep [--yes] [--if-due]",
182
182
  ],
183
183
  curator: [
@@ -193,7 +193,7 @@ export const commandHelp = {
193
193
  "ocean failures [list] [--json] | open <id> <signature> --title <t> --mechanism <why> [--lesson <id>] [--rung <r>] | status <id> <status> [--by <mechanism>] | climb <id>",
194
194
  ],
195
195
  scorecard: [
196
- "Print Ocean's health numbers from real data; --write saves 01-daily/scorecard/YYYY-MM-DD.md.",
196
+ "Print Ocean's health numbers from real data; --write saves 01-daily/reports/scorecard/YYYY-MM-DD.md.",
197
197
  "ocean scorecard [--json] [--write]",
198
198
  ],
199
199
  express: [
@@ -97,7 +97,7 @@ async function collect() {
97
97
  };
98
98
  }
99
99
  // `ocean scorecard [--json] [--write]` (T-318): Ocean's health numbers from real data; --write
100
- // also saves 01-daily/scorecard/YYYY-MM-DD.md.
100
+ // also saves 01-daily/reports/scorecard/YYYY-MM-DD.md.
101
101
  export async function runScorecardCommand(args) {
102
102
  const unknown = args.filter((arg) => !["--json", "--write"].includes(arg));
103
103
  if (unknown.length)
@@ -2,7 +2,7 @@ import { access, chmod, mkdir, readdir, readFile, rename, writeFile, } from "nod
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { registryFile } from "@ocean/core/shared/fs-utils.js";
5
- import { DAILY_DIR, INBOX_DIR, KNOWLEDGE_DIR, LEGACY_NOTES_DIR, liveEngineEntry, NOTES_DIR, oceanPath, oceanRoot, PERSONAL_DIR, projectDir, REGISTRY_DIR, SYSTEM_DIR, TEMPLATES_DIR, WORKSPACE_PROJECT_ID, } from "@ocean/core/shared/paths.js";
5
+ import { DAILY_DIR, INBOX_DIR, KNOWLEDGE_DIR, LEGACY_NOTES_DIR, liveEngineEntry, NOTES_DIR, oceanPath, oceanRoot, PERSONAL_DIR, projectDir, REGISTRY_DIR, REPORT_KINDS, REPORTS_DIR, SYSTEM_DIR, TEMPLATES_DIR, WORKSPACE_PROJECT_ID, } from "@ocean/core/shared/paths.js";
6
6
  import { connectObsidianVault } from "@ocean/services/obsidian/vault-discovery.js";
7
7
  import { seedWorkspaceTemplate } from "../../application/layout/workspace-template.js";
8
8
  import { installShellIntegration, syncProviderWrappers, } from "../../infrastructure/wrappers/wrapper-manager.js";
@@ -114,8 +114,8 @@ export function parseSetupArgs(args) {
114
114
  }
115
115
  // The notes moved from 07-notes into 02-personal/notes. An older workspace's folder moves once,
116
116
  // whole; when both exist nothing is touched (the doctor names the leftover for the owner).
117
+ const present = (file) => access(file).then(() => true, () => false);
117
118
  export async function moveLegacyNotes() {
118
- const present = (file) => access(file).then(() => true, () => false);
119
119
  const from = oceanPath(LEGACY_NOTES_DIR);
120
120
  const to = oceanPath(NOTES_DIR);
121
121
  if (!(await present(from)))
@@ -126,9 +126,27 @@ export async function moveLegacyNotes() {
126
126
  await rename(from, to);
127
127
  return "moved";
128
128
  }
129
+ // The generated reports moved from 01-daily/<kind>/ into 01-daily/reports/<kind>/. Each folder
130
+ // moves once, whole; one that already exists at the new place is left for the owner.
131
+ export async function moveReportFolders() {
132
+ const moved = [];
133
+ for (const kind of REPORT_KINDS) {
134
+ const from = oceanPath(DAILY_DIR, kind);
135
+ const to = oceanPath(REPORTS_DIR, kind);
136
+ if (!(await present(from)) || (await present(to)))
137
+ continue;
138
+ await mkdir(path.dirname(to), { recursive: true });
139
+ await rename(from, to);
140
+ moved.push(kind);
141
+ }
142
+ return moved;
143
+ }
129
144
  export async function setup(options = {}) {
130
145
  if ((await moveLegacyNotes()) === "moved")
131
146
  console.log(`Moved your notes: ${LEGACY_NOTES_DIR}/ → ${NOTES_DIR}/`);
147
+ const reports = await moveReportFolders();
148
+ if (reports.length)
149
+ console.log(`Moved reports into ${REPORTS_DIR}/: ${reports.join(", ")}`);
132
150
  await Promise.all([...personalDirectories, `${projectDir(WORKSPACE_PROJECT_ID)}/tasks`].map((directory) => mkdir(oceanPath(directory), { recursive: true })));
133
151
  // T-296: charter, policies, templates and indexes for a new workspace; existing files are kept.
134
152
  await seedWorkspaceTemplate();
@@ -12,6 +12,7 @@ import { claimTask, releaseTask } from "@ocean/loop/tasks/claim-task.js";
12
12
  import { listTasks, listTasksForFolder, } from "@ocean/loop/tasks/list-tasks.js";
13
13
  import { newTask } from "@ocean/loop/tasks/new-task.js";
14
14
  import { renumberTasks } from "@ocean/loop/tasks/renumber-tasks.js";
15
+ import { syncTaskPrs, } from "@ocean/loop/tasks/sync-task-prs.js";
15
16
  import { verifyAndRecord } from "@ocean/loop/tasks/task-verification.js";
16
17
  import { verificationReadiness } from "@ocean/loop/tasks/verification-readiness.js";
17
18
  import { taskReviewer } from "../../infrastructure/providers/task-reviewer.js";
@@ -43,6 +44,14 @@ function recordedVerification(id, root) {
43
44
  reviewer: taskReviewer,
44
45
  });
45
46
  }
47
+ // A linked PR's state, read with the owner's own `gh` login.
48
+ async function githubPrState(link) {
49
+ const { stdout } = await execFile("gh", ["pr", "view", link.url, "--json", "state", "--jq", ".state"], { timeout: 20_000 });
50
+ const state = stdout.trim();
51
+ if (state === "OPEN" || state === "MERGED" || state === "CLOSED")
52
+ return state;
53
+ throw new Error(`${link.url}: unexpected PR state "${state}"`);
54
+ }
46
55
  // `ocean tasks list --pretty`: one aligned row per task, for a person rather than a tool.
47
56
  function taskTable(tasks) {
48
57
  if (!tasks.length)
@@ -184,6 +193,27 @@ export async function runTasksCommand(action, args) {
184
193
  process.exitCode = 1;
185
194
  return;
186
195
  }
196
+ if (action === "sync") {
197
+ // Task state follows linked GitHub PRs: open → in-qa, all merged → done via the completion
198
+ // gate. Session start runs `--all` in the background.
199
+ const projects = args.includes("--all")
200
+ ? await projectsWithTasks()
201
+ : [projectId];
202
+ const apply = !args.includes("--dry-run");
203
+ const report = {};
204
+ for (const project of projects) {
205
+ const root = resolveWithin(oceanPath(projectDir(project)), "tasks");
206
+ const outcome = await syncTaskPrs(root, {
207
+ apply,
208
+ fetchPr: githubPrState,
209
+ complete: (id, taskRoot) => completeTask(id, taskRoot, { verify: recordedVerification }),
210
+ });
211
+ if (outcome.changed.length || outcome.skipped.length)
212
+ report[project] = outcome;
213
+ }
214
+ console.log(JSON.stringify({ apply, projects: report }, null, 2));
215
+ return;
216
+ }
187
217
  if (action === "complete") {
188
218
  const id = args[0];
189
219
  if (!id) {
@@ -251,7 +281,7 @@ export async function runTasksCommand(action, args) {
251
281
  return;
252
282
  }
253
283
  if (action !== "archive") {
254
- console.error("Usage: ocean tasks list [state] [--project <id>] [--pretty]|new <title> [--project <id>]|doctor [--all]|index [--write]|checkpoint <id> --note <text> [--next <text>]|verify <id>|complete <id>|claim <id> --by <name> [--paths a,b] [--force]|release <id> [--by <name>] [--force]|archive [--apply|--auto]|renumber --project <id> --prefix <PREFIX> [--write]");
284
+ console.error("Usage: ocean tasks list [state] [--project <id>] [--pretty]|new <title> [--project <id>]|doctor [--all]|index [--write]|checkpoint <id> --note <text> [--next <text>]|verify <id>|complete <id>|sync [--all] [--dry-run]|claim <id> --by <name> [--paths a,b] [--force]|release <id> [--by <name>] [--force]|archive [--apply|--auto]|renumber --project <id> --prefix <PREFIX> [--write]");
255
285
  process.exitCode = 1;
256
286
  return;
257
287
  }
@@ -1,10 +1,11 @@
1
- import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { mkdir, open, 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 { cleanTitle } from "@ocean/core/shared/clean-title.js";
5
5
  import { localDate, localMoment, localTime, } from "@ocean/core/shared/local-date.js";
6
6
  import { DAILY_DIR, INBOX_DIR, oceanPath, oceanRoot, } from "@ocean/core/shared/paths.js";
7
7
  import { findGitRoot } from "@ocean/core/shared/project-resolution.js";
8
+ import { isTrivialSession } from "./model-narrative.js";
8
9
  // Same fallback title stamped on a session with no explicit title (see
9
10
  // daily-narrative.ts) — never meaningful content on its own.
10
11
  const GENERIC_TITLE = /^(claude|codex|hermes|kimi|gemini|copilot|kilo|antigravity|openhands) session$/i;
@@ -45,6 +46,107 @@ async function uniqueFilename(directory, base, ext) {
45
46
  }
46
47
  return `${base}-${Date.now()}${ext}`;
47
48
  }
49
+ // Blocks a client wraps around or slips in front of the user's words — system notes, IDE state,
50
+ // slash-command echoes, background-task notices. Never the goal of a session (T-326).
51
+ const WRAPPER_TAGS = "system-reminder|task-notification|ide_[a-z_]+|command-[a-z-]+|local-command-[a-z-]+|browser_instruction|user-prompt-submit-hook";
52
+ const WRAPPER_BLOCK = new RegExp(`<(${WRAPPER_TAGS})\\b[^>]*>[\\s\\S]*?</\\1>`, "gi");
53
+ const WRAPPER_START = new RegExp(`^<(${WRAPPER_TAGS})\\b`, "i");
54
+ /** The user's own words in a message, or "" when it was only client wrapping. */
55
+ export function withoutWrappers(text) {
56
+ const stripped = text.replace(WRAPPER_BLOCK, " ").trim();
57
+ return WRAPPER_START.test(stripped) ? "" : stripped;
58
+ }
59
+ const RECORD_HEAD_BYTES = 1024;
60
+ async function recordHead(file) {
61
+ const handle = await open(file, "r").catch(() => null);
62
+ if (!handle)
63
+ return "";
64
+ try {
65
+ const buffer = Buffer.alloc(RECORD_HEAD_BYTES);
66
+ const { bytesRead } = await handle.read(buffer, 0, RECORD_HEAD_BYTES, 0);
67
+ return buffer.subarray(0, bytesRead).toString("utf8");
68
+ }
69
+ finally {
70
+ await handle.close();
71
+ }
72
+ }
73
+ /**
74
+ * The live record of one session in 01-daily/sessions/YYYY-MM/ (archive/ is history and is never
75
+ * rewritten). When an older duplicate exists, the digest record wins over a closeout one.
76
+ */
77
+ export async function findSessionRecord(sessionId) {
78
+ const root = oceanPath(DAILY_DIR, "sessions");
79
+ const needle = `session_id: ${JSON.stringify(sessionId)}`;
80
+ const months = (await readdir(root).catch(() => []))
81
+ .filter((name) => /^\d{4}-\d{2}$/.test(name))
82
+ .sort()
83
+ .reverse();
84
+ const found = [];
85
+ for (const month of months) {
86
+ const directory = path.join(root, month);
87
+ for (const name of (await readdir(directory).catch(() => [])).sort()) {
88
+ if (!name.endsWith(".md"))
89
+ continue;
90
+ const file = path.join(directory, name);
91
+ if (!(await recordHead(file)).split("\n").includes(needle))
92
+ continue;
93
+ found.push({ file, text: await readFile(file, "utf8") });
94
+ }
95
+ }
96
+ return (found.find((record) => isDigestRecord(record.text)) ?? found[0] ?? null);
97
+ }
98
+ // Records written before `source:` existed carry the chat summary's verification line instead.
99
+ export function isDigestRecord(text) {
100
+ return (/^source: "digest"$/m.test(text) ||
101
+ text.includes("NOT PROVEN — summarized from a chat"));
102
+ }
103
+ const PLACEHOLDER = /^(not stated\.?|no objective was captured\.?)$/i;
104
+ /** A digest record read back into the digest it was written from. */
105
+ export function recordDigest(text) {
106
+ const section = (heading) => {
107
+ const start = text.indexOf(`\n## ${heading}\n`);
108
+ if (start < 0)
109
+ return "";
110
+ const body = text.slice(start + heading.length + 5);
111
+ const end = body.search(/\n## |\n---\n|\nRaw events:/);
112
+ return (end < 0 ? body : body.slice(0, end)).trim();
113
+ };
114
+ const prose = (heading) => {
115
+ const value = section(heading);
116
+ return PLACEHOLDER.test(value) ? "" : value;
117
+ };
118
+ const items = (heading) => section(heading)
119
+ .split("\n")
120
+ .filter((line) => line.startsWith("- "))
121
+ .map((line) => line.slice(2).trim())
122
+ .filter(Boolean);
123
+ return {
124
+ title: /^# (.+)$/m.exec(text)?.[1]?.trim() ?? "",
125
+ goal: prose("Goal"),
126
+ outcome: prose("Outcome"),
127
+ decisions: items("Decisions"),
128
+ fixes: items("Problems → fixes"),
129
+ learned: items("Learned"),
130
+ next: items("Next"),
131
+ };
132
+ }
133
+ const MERGED_ITEMS = 5;
134
+ /**
135
+ * Two stretches of one conversation as one account: what it set out to do comes from the first,
136
+ * where it ended from the latest, and what remains to do only from the latest that said anything.
137
+ */
138
+ export function mergeDigests(earlier, later) {
139
+ const union = (a, b) => [...new Set([...a, ...b])].slice(-MERGED_ITEMS);
140
+ return {
141
+ title: earlier.title || later.title,
142
+ goal: earlier.goal || later.goal,
143
+ outcome: later.outcome || earlier.outcome,
144
+ decisions: union(earlier.decisions, later.decisions),
145
+ fixes: union(earlier.fixes, later.fixes),
146
+ learned: union(earlier.learned, later.learned),
147
+ next: (later.next.length ? later.next : earlier.next).slice(0, MERGED_ITEMS),
148
+ };
149
+ }
48
150
  /**
49
151
  * One session record per session in 01-daily/sessions/YYYY-MM/ (T-314; was 00-inbox/brain-dump/),
50
152
  * separate from the machine-oriented kernel/bridge/sessions/summaries/ dump. Prefers
@@ -61,14 +163,39 @@ async function uniqueFilename(directory, base, ext) {
61
163
  */
62
164
  export async function writeBrainDump(input) {
63
165
  const { session, events, narrative, changedFiles, observations } = input;
166
+ // One record per session (T-326): the chat digest's record is the richer account, so it wins;
167
+ // a session that changed nothing and said nothing gets no record at all.
168
+ const existing = await findSessionRecord(session.sessionId);
169
+ if (existing && isDigestRecord(existing.text))
170
+ return {
171
+ brainDumpPath: path
172
+ .relative(oceanRoot(), existing.file)
173
+ .split(path.sep)
174
+ .join("/"),
175
+ };
176
+ if (!narrative && isTrivialSession(events, changedFiles))
177
+ return null;
178
+ // The first thing the user actually said, past any client wrapping.
64
179
  const workLog = narrative?.workLog ??
65
180
  (() => {
66
- const objectiveEvent = events.find((event) => event.type === "user_input" || event.type === "resume_requested");
67
- return safeText(objectiveEvent?.data ?? session.title, 200);
181
+ for (const event of events) {
182
+ if (event.type !== "user_input" && event.type !== "resume_requested")
183
+ continue;
184
+ const words = withoutWrappers(event.data);
185
+ if (words)
186
+ return safeText(words, 200);
187
+ }
188
+ return safeText(session.title, 200);
68
189
  })();
69
190
  const hasRealProject = findGitRoot(session.workingDirectory) !== null;
70
191
  if (isGenericContent(workLog) && !hasRealProject)
71
192
  return null;
193
+ // Where the session ended: the assistant's last reply, else what it touched.
194
+ const lastReply = [...events]
195
+ .reverse()
196
+ .filter((event) => event.type === "provider_output" || event.type === "text")
197
+ .map((event) => safeText(withoutWrappers(event.data), 300))
198
+ .find(Boolean);
72
199
  const decision = narrative?.decision ??
73
200
  events
74
201
  .filter((event) => event.type === "provider_output" ||
@@ -90,9 +217,17 @@ export async function writeBrainDump(input) {
90
217
  const status = session.status === "completed" && (input.exitCode ?? 0) === 0
91
218
  ? "completed"
92
219
  : "failed";
93
- const title = isGenericContent(workLog)
94
- ? project
95
- : cleanTitle(workLog, project);
220
+ const title = !isGenericContent(workLog)
221
+ ? cleanTitle(workLog, project)
222
+ : lastReply
223
+ ? cleanTitle(lastReply, project)
224
+ : project;
225
+ const outcome = status === "completed"
226
+ ? (lastReply ??
227
+ (changedFiles.length
228
+ ? `Changed ${changedFiles.length} file(s).`
229
+ : "Completed."))
230
+ : `Did not complete.${lastReply ? ` ${lastReply}` : ""}`;
96
231
  // A session record (T-314): flat frontmatter Obsidian can read, then fixed sections. The
97
232
  // narrative comes from one model call when there was one; otherwise from the events.
98
233
  const quote = (value) => JSON.stringify(value);
@@ -101,6 +236,7 @@ export async function writeBrainDump(input) {
101
236
  "type: session",
102
237
  `project: ${quote(project)}`,
103
238
  `provider: ${quote(session.provider)}`,
239
+ 'source: "closeout"',
104
240
  `status: ${status}`,
105
241
  `session_id: ${quote(session.sessionId)}`,
106
242
  `date: ${date}`,
@@ -116,7 +252,7 @@ export async function writeBrainDump(input) {
116
252
  "",
117
253
  "## Outcome",
118
254
  "",
119
- status === "completed" ? "Completed." : "Did not complete.",
255
+ outcome,
120
256
  ...(decision ? ["", "## Decisions", "", decision] : []),
121
257
  ...(problem ? ["", "## Problems → fixes", "", problem] : []),
122
258
  ...(observations?.length
@@ -127,12 +263,15 @@ export async function writeBrainDump(input) {
127
263
  ...observations.map((o) => `- [${o.signalType}] ${safeText(o.summary, 300)} (confidence ${o.confidence})`),
128
264
  ]
129
265
  : []),
130
- "",
131
- "## Verification",
132
- "",
133
- status === "completed" && (input.exitCode ?? 0) === 0
134
- ? "NOT PROVEN — the session ended cleanly; no check is recorded here."
135
- : `NOT PROVEN — exit code ${input.exitCode ?? "unknown"}.`,
266
+ // A clean exit proves nothing either way, so it says nothing; a failed one says how it ended.
267
+ ...(status === "failed"
268
+ ? [
269
+ "",
270
+ "## Verification",
271
+ "",
272
+ `NOT PROVEN — exit code ${input.exitCode ?? "unknown"}.`,
273
+ ]
274
+ : []),
136
275
  ...(changedFiles.length
137
276
  ? [
138
277
  "",
@@ -147,6 +286,16 @@ export async function writeBrainDump(input) {
147
286
  "",
148
287
  `Raw events: \`ocean session events ${session.sessionId}\``,
149
288
  ];
289
+ // A session closed out again (resumed, then ended) rewrites its own record.
290
+ if (existing) {
291
+ await writeFile(existing.file, `${lines.join("\n")}\n`, "utf8");
292
+ return {
293
+ brainDumpPath: path
294
+ .relative(oceanRoot(), existing.file)
295
+ .split(path.sep)
296
+ .join("/"),
297
+ };
298
+ }
150
299
  // 01-daily/sessions/YYYY-MM/, where the session-record template and Templater point.
151
300
  const directory = oceanPath(DAILY_DIR, "sessions", date.slice(0, 7));
152
301
  await mkdir(directory, { recursive: true });
@@ -194,12 +343,20 @@ export async function migrateBrainDumps(options) {
194
343
  }
195
344
  return { moved, skipped };
196
345
  }
197
- // A chat with no session in the store (Claude Desktop, an export: T-314) gets the same record, from
198
- // the digest its fact extraction returned — no model call of its own. One record per captured
199
- // stretch of the conversation, dated by its newest message.
346
+ // A chat's record (Claude Desktop, an export, a Claude Code transcript: T-314) from the digest its
347
+ // fact extraction returned — no model call of its own. One record per session (T-326): a later
348
+ // stretch of the same conversation is merged into the record the first one wrote, and a thin
349
+ // closeout record for the session is replaced by this richer one.
200
350
  export async function writeDigestRecord(input) {
201
- const { digest } = input;
202
- const date = localDate(localMoment(input.endedAt));
351
+ const existing = await findSessionRecord(input.sessionId);
352
+ const earlier = existing && isDigestRecord(existing.text)
353
+ ? recordDigest(existing.text)
354
+ : null;
355
+ const digest = earlier ? mergeDigests(earlier, input.digest) : input.digest;
356
+ const existingDate = existing
357
+ ? /^date: (\d{4}-\d{2}-\d{2})$/m.exec(existing.text)?.[1]
358
+ : undefined;
359
+ const date = existingDate ?? localDate(localMoment(input.endedAt));
203
360
  const time = localTime(localMoment(input.startedAt));
204
361
  const title = cleanTitle(safeText(digest.title || digest.goal, 400), input.project || "Conversation");
205
362
  const quote = (value) => JSON.stringify(value);
@@ -216,6 +373,7 @@ export async function writeDigestRecord(input) {
216
373
  "type: session",
217
374
  `project: ${quote(input.project ?? "")}`,
218
375
  `provider: ${quote(input.provider)}`,
376
+ 'source: "digest"',
219
377
  "status: completed",
220
378
  `session_id: ${quote(input.sessionId)}`,
221
379
  `date: ${date}`,
@@ -235,17 +393,29 @@ export async function writeDigestRecord(input) {
235
393
  ...list("Decisions", digest.decisions),
236
394
  ...list("Problems → fixes", digest.fixes),
237
395
  ...list("Learned", digest.learned),
238
- "",
239
- "## Verification",
240
- "",
241
- "NOT PROVEN — summarized from a chat; nothing was run.",
242
396
  ...list("Next", digest.next),
243
397
  "",
244
398
  ];
245
- const directory = oceanPath(DAILY_DIR, "sessions", date.slice(0, 7));
246
- await mkdir(directory, { recursive: true });
247
- const filename = await uniqueFilename(directory, `${date}-${time.replace(":", "")}-${slugify(title).length >= MIN_USEFUL_SLUG_LENGTH ? slugify(title) : input.provider}`, ".md");
248
- const file = path.join(directory, filename);
399
+ const slug = slugify(title).length >= MIN_USEFUL_SLUG_LENGTH
400
+ ? slugify(title)
401
+ : input.provider;
402
+ let file;
403
+ if (earlier && existing) {
404
+ // A later stretch of the same chat: the record keeps its name, its day and its place.
405
+ file = existing.file;
406
+ }
407
+ else if (existing) {
408
+ // The thin closeout record for this session: replaced in place, renamed after the real title.
409
+ const directory = path.dirname(existing.file);
410
+ const stamp = /^\d{4}-\d{2}-\d{2}-\d{4}/.exec(path.basename(existing.file))?.[0];
411
+ await rm(existing.file, { force: true });
412
+ file = path.join(directory, await uniqueFilename(directory, `${stamp ?? `${date}-${time.replace(":", "")}`}-${slug}`, ".md"));
413
+ }
414
+ else {
415
+ const directory = oceanPath(DAILY_DIR, "sessions", date.slice(0, 7));
416
+ await mkdir(directory, { recursive: true });
417
+ file = path.join(directory, await uniqueFilename(directory, `${date}-${time.replace(":", "")}-${slug}`, ".md"));
418
+ }
249
419
  await writeFile(file, `${lines.join("\n")}\n`, "utf8");
250
420
  return { path: path.relative(oceanRoot(), file).split(path.sep).join("/") };
251
421
  }
@@ -14,9 +14,9 @@
14
14
  "capture": "00-inbox/captures/",
15
15
  "daily": "01-daily/",
16
16
  "session": "01-daily/sessions/",
17
- "brief": "01-daily/briefs/",
18
- "weekly": "01-daily/weekly/",
19
- "monthly": "01-daily/monthly/",
17
+ "brief": "01-daily/reports/briefs/",
18
+ "weekly": "01-daily/reports/weekly/",
19
+ "monthly": "01-daily/reports/monthly/",
20
20
  "note": "02-personal/notes/",
21
21
  "decision": "05-knowledge/decisions/",
22
22
  "lesson": "05-knowledge/lessons/",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/brain",
3
- "version": "2.13.0",
3
+ "version": "2.15.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": "2.13.0",
3
+ "version": "2.15.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -75,6 +75,17 @@ const brainArea = (area) => path.posix.join(BRAIN_PREFIX, area);
75
75
  export const PERSONAL_DIR = brainArea("02-personal");
76
76
  export const KNOWLEDGE_DIR = brainArea("05-knowledge");
77
77
  export const DAILY_DIR = brainArea("01-daily");
78
+ // Generated reports (briefs, digest, scorecard, hygiene, weekly, monthly), one folder each, so
79
+ // 01-daily/ itself holds only day notes, session records and their archive.
80
+ export const REPORTS_DIR = path.posix.join(DAILY_DIR, "reports");
81
+ export const REPORT_KINDS = [
82
+ "briefs",
83
+ "digest",
84
+ "scorecard",
85
+ "hygiene",
86
+ "weekly",
87
+ "monthly",
88
+ ];
78
89
  export const INBOX_DIR = brainArea("00-inbox");
79
90
  export const TEMPLATES_DIR = brainArea("06-templates");
80
91
  // The owner's own notes (T-314): agents read and index them, and never write there. They sit
@@ -236,7 +247,7 @@ export const STORE_DIR = {
236
247
  notes: NOTES_DIR,
237
248
  // Session records and briefs (T-314), searchable beside memory and knowledge.
238
249
  sessions: `${DAILY_DIR}/sessions`,
239
- briefs: `${DAILY_DIR}/briefs`,
250
+ briefs: `${REPORTS_DIR}/briefs`,
240
251
  };
241
252
  // Brain-index records are "<store>/<path inside store>" ("memory/x.md", "knowledge/decisions/y.md").
242
253
  // Project memory (T-296) is "project/<id>/<path>" for 04-projects/<id>/memory/<path>, and
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/core",
3
- "version": "2.13.0",
3
+ "version": "2.15.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,7 +18,7 @@ function section(source, heading) {
18
18
  const nextHeading = /^## /m.exec(source.slice(start));
19
19
  return source.slice(start, nextHeading ? start + nextHeading.index : source.length);
20
20
  }
21
- function completionIssues(source) {
21
+ export function completionIssues(source) {
22
22
  const issues = [];
23
23
  if (/^\s*-\s+"?\[ \] /m.test(source))
24
24
  issues.push("unchecked work");