@amoree-code/ocean 1.5.1 → 1.6.1

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 (25) hide show
  1. package/dist/application/clients/hooks.js +8 -2
  2. package/dist/infrastructure/providers/session-facts-completer.js +70 -0
  3. package/dist/interfaces/cli/clients-command.js +35 -1
  4. package/dist/interfaces/cli/command-registry.js +25 -2
  5. package/dist/interfaces/cli/memory-command.js +19 -1
  6. package/dist/interfaces/cli/running-server-findings.js +19 -0
  7. package/dist/interfaces/cli/session-facts-command.js +65 -0
  8. package/node_modules/@ocean/brain/dist/memory/memory-audit.js +38 -3
  9. package/node_modules/@ocean/brain/dist/memory/memory-paths.js +4 -0
  10. package/node_modules/@ocean/brain/dist/memory/memory-review.js +5 -0
  11. package/node_modules/@ocean/brain/dist/memory/session-facts.js +236 -0
  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/package.json +1 -1
  15. package/node_modules/@ocean/loop/dist/hooks/session-end-hook.js +34 -22
  16. package/node_modules/@ocean/loop/dist/hooks/session-facts-hook.js +176 -0
  17. package/node_modules/@ocean/loop/package.json +1 -1
  18. package/node_modules/@ocean/market/package.json +1 -1
  19. package/node_modules/@ocean/services/dist/doctor/workspace-doctor.js +51 -3
  20. package/node_modules/@ocean/services/dist/infrastructure/mcp/call-ledger.js +26 -2
  21. package/node_modules/@ocean/services/dist/infrastructure/mcp/ocean-server.js +9 -3
  22. package/node_modules/@ocean/services/dist/infrastructure/mcp/server-version.js +11 -8
  23. package/node_modules/@ocean/services/package.json +1 -1
  24. package/ocean-marketplace.json +28 -28
  25. package/package.json +7 -7
@@ -15,6 +15,12 @@ const EVENTS = {
15
15
  flags: "",
16
16
  pattern: /ocean-session-close|\bhook session-end\b/,
17
17
  },
18
+ // Claude Code compacts a long conversation: its turns are read for facts first (T-313).
19
+ PreCompact: {
20
+ action: "pre-compact",
21
+ flags: "",
22
+ pattern: /\bhook pre-compact\b/,
23
+ },
18
24
  };
19
25
  export const HOOK_ADAPTERS = [
20
26
  {
@@ -22,7 +28,7 @@ export const HOOK_ADAPTERS = [
22
28
  hookClient: "claude",
23
29
  file: ".claude/settings.json",
24
30
  windowsShell: "powershell",
25
- events: ["SessionStart", "SessionEnd"],
31
+ events: ["SessionStart", "SessionEnd", "PreCompact"],
26
32
  group: (command, windows) => ({
27
33
  hooks: [
28
34
  {
@@ -290,7 +296,7 @@ export async function restoreHooks(options) {
290
296
  const conflicts = [];
291
297
  const undo = newBatch();
292
298
  for (const entry of entries) {
293
- const label = `${entry.client}:${entry.key === "SessionEnd" ? "end-hook" : "hook"}`;
299
+ const label = `${entry.client}:${entry.key === "SessionEnd" ? "end-hook" : entry.key === "PreCompact" ? "compact-hook" : "hook"}`;
294
300
  // Set per attempt: edit() may run the change again when the file moved under it.
295
301
  const outcome = { restored: false };
296
302
  await edit(path.join(env.home, entry.file), (text) => {
@@ -0,0 +1,70 @@
1
+ import { mkdir } from "node:fs/promises";
2
+ import { oceanEnv, oceanEnvPair, oceanPath, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
3
+ import { resolveOriginalExecutable } from "./provider-registry.js";
4
+ import { runProvider } from "./providers.js";
5
+ // The model call behind session fact capture (T-313), through the provider layer: the client
6
+ // whose session it was runs it, so whoever uses only Codex gets capture too and no other CLI is
7
+ // required. Read-only, in a folder of its own (no project context to load), with a cheap model
8
+ // where the client has a known one. OCEAN_SESSION_FACTS_MODEL overrides it.
9
+ // The env flag the spawned call carries: its own hooks see it and do nothing, so the capture
10
+ // call is never recorded as a session, and never captures from itself.
11
+ export const FACTS_CALL_ENV = "FACTS_CALL";
12
+ const DEFAULT_MODEL = {
13
+ claude: "haiku",
14
+ };
15
+ const PROVIDER = {
16
+ claude: "claude",
17
+ codex: "codex",
18
+ };
19
+ const TIMEOUT_MS = 90_000;
20
+ // The model's final answer: the Claude SDK's `result` message, or Codex's last agent message
21
+ // (`codex exec --json`); otherwise the plain text the client printed.
22
+ export function finalText(events) {
23
+ let answer = null;
24
+ const texts = [];
25
+ for (const event of events) {
26
+ if (event.type === "text") {
27
+ if (typeof event.data === "string")
28
+ texts.push(event.data);
29
+ continue;
30
+ }
31
+ const data = event.data;
32
+ if (!data || typeof data !== "object")
33
+ continue;
34
+ if (data.type === "result" && typeof data.result === "string")
35
+ answer = data.result;
36
+ const item = data.item;
37
+ if (data.type === "item.completed" &&
38
+ item?.type === "agent_message" &&
39
+ typeof item.text === "string")
40
+ answer = item.text;
41
+ }
42
+ return answer ?? (texts.length ? texts.join("\n") : null);
43
+ }
44
+ export function sessionFactsCompleter(client, run = runProvider) {
45
+ const provider = PROVIDER[client];
46
+ if (!provider)
47
+ return null;
48
+ try {
49
+ resolveOriginalExecutable(provider);
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ const model = oceanEnv("SESSION_FACTS_MODEL") ?? DEFAULT_MODEL[provider];
55
+ return async (prompt) => {
56
+ const cwd = oceanPath(SYSTEM_DIR, "state", "memory", "extract");
57
+ await mkdir(cwd, { recursive: true, mode: 0o700 });
58
+ const result = await run({
59
+ provider,
60
+ prompt,
61
+ cwd,
62
+ readOnly: true,
63
+ model,
64
+ timeoutMs: TIMEOUT_MS,
65
+ env: oceanEnvPair(FACTS_CALL_ENV, "1"),
66
+ });
67
+ return result.exitCode === 0 ? finalText(result.events) : null;
68
+ };
69
+ }
70
+ //# sourceMappingURL=session-facts-completer.js.map
@@ -1,3 +1,5 @@
1
+ import readline from "node:readline/promises";
2
+ import { memorySettings, setSessionFacts, } from "@ocean/brain/memory/memory-audit.js";
1
3
  import { marketplacePaths } from "@ocean/market/install/default-marketplace.js";
2
4
  import { updateGatewayAccess } from "@ocean/market/mcp/mcp-gateway.js";
3
5
  import { readCallLedger, summarizeCallLedger, } from "@ocean/services/infrastructure/mcp/call-ledger.js";
@@ -5,7 +7,38 @@ import { applyClients, attributeLedger, confirmClient, defaultClientEnv, gateway
5
7
  import { applyHooks, planHooks, restoreHooks, } from "../../application/clients/hooks.js";
6
8
  import { applyNative, planNative, restoreNative, } from "../../application/clients/native.js";
7
9
  import { applyOpencodePlugin, planOpencodePlugin, restoreOpencodePlugin, } from "../../application/clients/opencode-plugin.js";
8
- const usage = "Usage: ocean clients detect|plan [--json] | apply [--client <id>…] [--yes] | verify [<id>…] | confirm <id>… --label in-app|headless|connected|blocked [--via <evidence>] [--reason <why>] | gateway [<id> on|off] [--default gateway|per-server] | allow|deny|unset <id> <server> | ledger | repair | restore [--batch <id>]";
10
+ const usage = "Usage: ocean clients detect|plan [--json] | apply [--client <id>…] [--yes] [--session-facts on|off] | verify [<id>…] | confirm <id>… --label in-app|headless|connected|blocked [--via <evidence>] [--reason <why>] | gateway [<id> on|off] [--default gateway|per-server] | allow|deny|unset <id> <server> | ledger | repair | restore [--batch <id>]";
11
+ export const SESSION_FACTS_QUESTION = "Capture durable facts from your sessions automatically? It costs one small model call per session, run by the client the session was in. Every fact goes to your review queue; nothing is saved without your approval, even with auto-approve on. [y/N] ";
12
+ // The session-facts answer, asked once (T-313): `--session-facts on|off` decides; otherwise a
13
+ // terminal is asked; with no terminal and no saved answer it stays unset (off), and
14
+ // `ocean doctor` points to `ocean memory session-facts on|off`.
15
+ async function sessionFactsAnswer(flag) {
16
+ if (flag === "on" || flag === "off") {
17
+ await setSessionFacts(flag === "on");
18
+ return flag;
19
+ }
20
+ if (flag !== undefined)
21
+ throw new Error("--session-facts takes on or off");
22
+ if ((await memorySettings()).sessionFacts !== null)
23
+ return "kept";
24
+ if (!process.stdin.isTTY || !process.stderr.isTTY)
25
+ return "unset";
26
+ const terminal = readline.createInterface({
27
+ input: process.stdin,
28
+ output: process.stderr,
29
+ });
30
+ try {
31
+ const answer = (await terminal.question(SESSION_FACTS_QUESTION))
32
+ .trim()
33
+ .toLowerCase();
34
+ const on = answer === "y" || answer === "yes";
35
+ await setSessionFacts(on);
36
+ return on ? "on" : "off";
37
+ }
38
+ finally {
39
+ terminal.close();
40
+ }
41
+ }
9
42
  // `ocean clients` (T-296 P2/P3b): every installed AI client's `ocean` MCP entry and, where the
10
43
  // client has a verified session-start event, Ocean's session hook. `apply` shows the plan until
11
44
  // --yes; `repair` only re-applies clients already approved; `restore` undoes an apply batch
@@ -75,6 +108,7 @@ export async function runClientsCommand(args) {
75
108
  plugins: (await applyOpencodePlugin({ clients: selected, batch: applied.batch })).results,
76
109
  native: (await applyNative({ clients: selected, batch: applied.batch }))
77
110
  .results,
111
+ sessionFacts: await sessionFactsAnswer(values("--session-facts")[0]),
78
112
  };
79
113
  }
80
114
  else if (action === "verify") {
@@ -67,6 +67,8 @@ import { manageClients, runOnboardCommand } from "./onboard-command.js";
67
67
  import { runOperateCommand } from "./operate-command.js";
68
68
  import { runProfilesCommand } from "./profiles-command.js";
69
69
  import { runPullCommand } from "./pull-command.js";
70
+ import { runningServerFindings } from "./running-server-findings.js";
71
+ import { insideFactsCall, runSessionFactsCommand, startSessionFacts, } from "./session-facts-command.js";
70
72
  import { parseSetupArgs, SETUP_USAGE, setup } from "./setup-command.js";
71
73
  import { runTasksCommand } from "./tasks-command.js";
72
74
  // brain_search over MCP uses vectors when the local embedder answers (T-307), and full text when
@@ -596,6 +598,26 @@ function startBackgroundSync() {
596
598
  }
597
599
  async function commandHook() {
598
600
  const action = process.argv[3] ?? "";
601
+ // The model call fact capture makes is a client session too: its hooks do nothing (T-313).
602
+ if (insideFactsCall())
603
+ return;
604
+ if (action === "session-facts") {
605
+ await runSessionFactsCommand(process.argv.slice(4));
606
+ return;
607
+ }
608
+ if (action === "pre-compact") {
609
+ // Claude Code's PreCompact: capture the turns about to be compacted, in the background.
610
+ try {
611
+ const raw = await readBoundedStdin();
612
+ const payload = raw.trim() ? JSON.parse(raw) : {};
613
+ await startSessionFacts(payload, "claude");
614
+ }
615
+ catch (error) {
616
+ console.error(error instanceof Error ? error.message : String(error));
617
+ process.exitCode = 1;
618
+ }
619
+ return;
620
+ }
599
621
  if (action === "session-start") {
600
622
  const flags = process.argv.slice(4);
601
623
  if (flags.includes("--repair"))
@@ -644,6 +666,7 @@ async function commandHook() {
644
666
  const raw = await readBoundedStdin();
645
667
  const payload = raw.trim() ? JSON.parse(raw) : {};
646
668
  await claudeSessionEndHook(payload, defaultSessionStoreFactory, client);
669
+ await startSessionFacts(payload, client);
647
670
  }
648
671
  catch (error) {
649
672
  console.error(error instanceof Error ? error.message : String(error));
@@ -656,7 +679,7 @@ async function commandHook() {
656
679
  }
657
680
  }
658
681
  const sessionEndUsage = `Usage: ocean hook session-end [--client ${SESSION_END_CLIENTS.join("|")}] (reads a hook payload from stdin)`;
659
- const sessionStartUsage = `Usage: ocean hook session-start [--client ${SESSION_START_CLIENTS.join("|")}] [--repair]`;
682
+ const sessionStartUsage = `Usage: ocean hook session-start [--client ${SESSION_START_CLIENTS.join("|")}] [--repair]|pre-compact (reads a hook payload from stdin)|session-facts --client claude|codex --session <id> --transcript <path>`;
660
683
  async function commandIntent() {
661
684
  const action = process.argv[3] ?? "classify";
662
685
  if (action !== "classify") {
@@ -927,7 +950,7 @@ async function commandUpdateOrRemove(command) {
927
950
  async function commandDoctor() {
928
951
  const report = await workspaceReport(defaultWrapperManager);
929
952
  // T-296: every installed AI client's `ocean` entry (supported fail, unknown warn).
930
- report.findings.push(...(await clientFindings()), ...(await nativeFindings()), ...(await browserFindings()), ...(await gatewayFindings()));
953
+ report.findings.push(...(await clientFindings()), ...(await nativeFindings()), ...(await browserFindings()), ...(await gatewayFindings()), ...(await runningServerFindings()));
931
954
  if (process.argv.includes("--json"))
932
955
  console.log(JSON.stringify(report, null, 2));
933
956
  else
@@ -3,6 +3,7 @@ import { evaluateRecall, } from "@ocean/brain/brain/brain-eval.js";
3
3
  import { brainIndexPath, computeCorpusHash, reindexBrain, } from "@ocean/brain/brain/brain-reindex.js";
4
4
  import { brainNeighbors, brainRead, brainSearch, } from "@ocean/brain/brain/brain-service.js";
5
5
  import { doctorMemoryIndexes, syncMemoryIndexes, } from "@ocean/brain/memory/index-sync.js";
6
+ import { memorySettings, sessionFactsEnabled, setSessionFacts, } from "@ocean/brain/memory/memory-audit.js";
6
7
  import { memoryDigest } from "@ocean/brain/memory/memory-digest.js";
7
8
  import { HARVEST_SOURCES, harvestMemory, importClaudeExport, } from "@ocean/brain/memory/memory-harvest.js";
8
9
  import { approveCandidate, listCandidates, rejectCandidate, } from "@ocean/brain/memory/memory-review.js";
@@ -293,6 +294,23 @@ export async function runMemoryCommand(action, args) {
293
294
  return runNeighbors(args);
294
295
  if (action === "facts")
295
296
  return runFacts(args);
297
+ if (action === "session-facts") {
298
+ // Automatic fact capture from session transcripts (T-313): show or set the owner's answer.
299
+ const choice = args[1];
300
+ if (choice === "on" || choice === "off")
301
+ await setSessionFacts(choice === "on");
302
+ else if (choice !== undefined) {
303
+ console.error("Usage: ocean memory session-facts [on|off]");
304
+ process.exitCode = 1;
305
+ return;
306
+ }
307
+ const saved = (await memorySettings()).sessionFacts;
308
+ console.log(JSON.stringify({
309
+ sessionFacts: saved === null ? "unset" : saved ? "on" : "off",
310
+ effective: (await sessionFactsEnabled()) ? "on" : "off",
311
+ }));
312
+ return;
313
+ }
296
314
  if (action === "doctor") {
297
315
  const result = await doctorMemoryIndexes();
298
316
  if (!result.ok) {
@@ -311,7 +329,7 @@ export async function runMemoryCommand(action, args) {
311
329
  console.log(JSON.stringify({ dryRun: !args.includes("--apply"), stores: result }, null, 2));
312
330
  return;
313
331
  }
314
- console.error("Usage: ocean memory doctor|sync [--apply]|review [list|approve <id> [--to <path>]|reject <id>]|eval <questions.json> [--k N] [--min R]|digest|harvest [--source <id>] [--yes]|import-claude <export-dir> [--yes]|history [path] [--limit N]|restore <id> [--hash <sha256>]|delete <path> --hash <sha256>|purge [--days N] [--yes]|facts <profile> [key] [value]|facts <profile> delete <key>|reindex [--no-vectors]|search <q> [--project <id>|--all] [--json]|read <id|path>|neighbors <id|path> [--depth N] [--project <id>|--all]");
332
+ console.error("Usage: ocean memory doctor|sync [--apply]|review [list|approve <id> [--to <path>]|reject <id>]|eval <questions.json> [--k N] [--min R]|digest|harvest [--source <id>] [--yes]|import-claude <export-dir> [--yes]|history [path] [--limit N]|restore <id> [--hash <sha256>]|delete <path> --hash <sha256>|purge [--days N] [--yes]|facts <profile> [key] [value]|facts <profile> delete <key>|session-facts [on|off]|reindex [--no-vectors]|search <q> [--project <id>|--all] [--json]|read <id|path>|neighbors <id|path> [--depth N] [--project <id>|--all]");
315
333
  process.exitCode = 1;
316
334
  }
317
335
  //# sourceMappingURL=memory-command.js.map
@@ -0,0 +1,19 @@
1
+ import { readCallLedger, runningVersions, } from "@ocean/services/infrastructure/mcp/call-ledger.js";
2
+ import { oceanVersion } from "../../version.js";
3
+ // `ocean doctor` (T-313): a client keeps its Ocean server process until it restarts, so after an
4
+ // upgrade it still answers with the old release. The call ledger names the release that answered
5
+ // each call; a client whose newest call came from another release than the installed one is told
6
+ // to restart.
7
+ export async function runningServerFindings(options = {}) {
8
+ const installed = options.installed ?? (await oceanVersion());
9
+ const calls = options.calls ?? (await readCallLedger());
10
+ return runningVersions(calls, options.now)
11
+ .filter((row) => row.version !== installed)
12
+ .map((row) => ({
13
+ code: "RUNNING_STALE",
14
+ severity: "WARN",
15
+ message: `${row.client} last reached Ocean ${row.version} (${row.last}); ${installed} is installed: restart ${row.client}`,
16
+ fixable: false,
17
+ }));
18
+ }
19
+ //# sourceMappingURL=running-server-findings.js.map
@@ -0,0 +1,65 @@
1
+ import { spawn } from "node:child_process";
2
+ import { sessionFactsEnabled } from "@ocean/brain/memory/memory-audit.js";
3
+ import { oceanEnv } from "@ocean/core/shared/paths.js";
4
+ import { isSessionEndClient, payloadCwd, TRANSCRIPT_CLIENTS, } from "@ocean/loop/hooks/session-end-hook.js";
5
+ import { runSessionFacts } from "@ocean/loop/hooks/session-facts-hook.js";
6
+ import { defaultSessionStoreFactory } from "../../composition/runtime.js";
7
+ import { FACTS_CALL_ENV, sessionFactsCompleter, } from "../../infrastructure/providers/session-facts-completer.js";
8
+ // True inside the model call fact capture makes (T-313): that call's own hooks do nothing.
9
+ export function insideFactsCall() {
10
+ return oceanEnv(FACTS_CALL_ENV) === "1";
11
+ }
12
+ // From SessionEnd and PreCompact: capture runs as its own detached process, since a hook has
13
+ // seconds and a model call takes longer, and the client may exit as soon as the hook returns.
14
+ export async function startSessionFacts(payload, client) {
15
+ if (!payload.session_id || !payload.transcript_path)
16
+ return;
17
+ if (!TRANSCRIPT_CLIENTS.includes(client))
18
+ return;
19
+ if (!(await sessionFactsEnabled()))
20
+ return;
21
+ try {
22
+ spawn(process.execPath, [
23
+ process.argv[1],
24
+ "hook",
25
+ "session-facts",
26
+ "--client",
27
+ client,
28
+ "--session",
29
+ payload.session_id,
30
+ "--transcript",
31
+ payload.transcript_path,
32
+ "--cwd",
33
+ payloadCwd(payload),
34
+ ], { detached: true, stdio: "ignore" })
35
+ .on("error", () => { })
36
+ .unref();
37
+ }
38
+ catch {
39
+ // no capture this time; the next PreCompact or SessionEnd reads from the same cursor
40
+ }
41
+ }
42
+ const usage = "Usage: ocean hook session-facts --client claude|codex --session <id> --transcript <path> [--cwd <dir>]";
43
+ // `ocean hook session-facts`: one capture run, in the foreground (the detached process above, or
44
+ // by hand to see what a session yields). Prints the run as JSON.
45
+ export async function runSessionFactsCommand(args) {
46
+ const value = (flag) => {
47
+ const index = args.indexOf(flag);
48
+ return index >= 0 ? args[index + 1] : undefined;
49
+ };
50
+ const client = value("--client") ?? "claude";
51
+ const sessionId = value("--session");
52
+ const transcript = value("--transcript");
53
+ if (!isSessionEndClient(client) || !sessionId || !transcript) {
54
+ console.error(usage);
55
+ process.exitCode = 1;
56
+ return;
57
+ }
58
+ const run = await runSessionFacts({
59
+ session_id: sessionId,
60
+ transcript_path: transcript,
61
+ cwd: value("--cwd"),
62
+ }, defaultSessionStoreFactory, client, (each) => sessionFactsCompleter(each));
63
+ console.log(JSON.stringify(run, null, 2));
64
+ }
65
+ //# sourceMappingURL=session-facts-command.js.map
@@ -1,8 +1,8 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
  import { appendFile, mkdir, open, readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { withFileLock } from "@ocean/core/shared/fs-utils.js";
5
- import { oceanPath, SYSTEM_DIR } from "@ocean/core/shared/paths.js";
4
+ import { atomicWrite, withFileLock } from "@ocean/core/shared/fs-utils.js";
5
+ import { oceanEnv, oceanPath, SYSTEM_DIR } from "@ocean/core/shared/paths.js";
6
6
  import { auditFile } from "./memory-paths.js";
7
7
  export const DEFAULT_RETENTION_DAYS = 90;
8
8
  export function sha256(content) {
@@ -64,7 +64,7 @@ export async function readAudit() {
64
64
  // bridge/config/memory.json — optional; without it MCP writes are on, copies are kept 90 days and
65
65
  // pulled memory waits for review.
66
66
  export async function memorySettings() {
67
- const file = oceanPath(SYSTEM_DIR, "config", "memory.json");
67
+ const file = memorySettingsFile();
68
68
  let input;
69
69
  try {
70
70
  input = JSON.parse(await readFile(file, "utf8"));
@@ -76,6 +76,7 @@ export async function memorySettings() {
76
76
  retentionDays: DEFAULT_RETENTION_DAYS,
77
77
  pullAutoApprove: false,
78
78
  proposeAutoApprove: false,
79
+ sessionFacts: null,
79
80
  };
80
81
  throw new Error(`Invalid memory settings in ${file}`);
81
82
  }
@@ -83,6 +84,11 @@ export async function memorySettings() {
83
84
  const days = input.retentionDays ?? DEFAULT_RETENTION_DAYS;
84
85
  const pullApprove = input.pullAutoApprove ?? "off";
85
86
  const proposeApprove = input.proposeAutoApprove ?? "off";
87
+ const sessionFacts = input.sessionFacts;
88
+ if (sessionFacts !== undefined &&
89
+ sessionFacts !== "on" &&
90
+ sessionFacts !== "off")
91
+ throw new Error(`Invalid memory settings in ${file}`);
86
92
  if ((writes !== "on" && writes !== "off") ||
87
93
  (pullApprove !== "on" && pullApprove !== "off") ||
88
94
  (proposeApprove !== "project" && proposeApprove !== "off") ||
@@ -95,6 +101,35 @@ export async function memorySettings() {
95
101
  retentionDays: days,
96
102
  pullAutoApprove: pullApprove === "on",
97
103
  proposeAutoApprove: proposeApprove === "project",
104
+ sessionFacts: sessionFacts === undefined ? null : sessionFacts === "on",
98
105
  };
99
106
  }
107
+ function memorySettingsFile() {
108
+ return oceanPath(SYSTEM_DIR, "config", "memory.json");
109
+ }
110
+ // The owner's answer to the session-facts question; every other setting is kept as it is.
111
+ export async function setSessionFacts(on) {
112
+ const file = memorySettingsFile();
113
+ let input = {};
114
+ try {
115
+ input = JSON.parse(await readFile(file, "utf8"));
116
+ }
117
+ catch (error) {
118
+ if (error.code !== "ENOENT")
119
+ throw new Error(`Invalid memory settings in ${file}`);
120
+ }
121
+ input.sessionFacts = on ? "on" : "off";
122
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
123
+ await atomicWrite(file, `${JSON.stringify(input, null, 2)}\n`, 0o600);
124
+ }
125
+ // Whether a finished session's facts are captured: OCEAN_SESSION_FACTS=on|off overrides the
126
+ // owner's saved answer; no answer is off.
127
+ export async function sessionFactsEnabled(env = process.env) {
128
+ const override = oceanEnv("SESSION_FACTS", env);
129
+ if (override === "on")
130
+ return true;
131
+ if (override === "off")
132
+ return false;
133
+ return (await memorySettings()).sessionFacts === true;
134
+ }
100
135
  //# sourceMappingURL=memory-audit.js.map
@@ -164,6 +164,10 @@ export function storedCopy(kind, id, relative) {
164
164
  export function harvestLedgerFile() {
165
165
  return stateDir("memory", "harvest.json");
166
166
  }
167
+ // Content hashes of facts captured from sessions (T-313), so one fact is proposed once.
168
+ export function sessionFactsLedgerFile() {
169
+ return stateDir("memory", "session-facts.json");
170
+ }
167
171
  export function auditFile() {
168
172
  return stateDir("memory", "audit.jsonl");
169
173
  }
@@ -8,6 +8,7 @@ import { findProject, readClaudeProjects, registerNamedProject, } from "@ocean/c
8
8
  import { appendAudit, memorySettings, newId, sha256, writeDurable, } from "./memory-audit.js";
9
9
  import { assertNoLinks, candidatesRoot, storedCopy } from "./memory-paths.js";
10
10
  import { checkContent, proposeMemory, readMemoryRecord, writeMemoryRecord, } from "./memory-write.js";
11
+ import { isSessionFactSource } from "./session-facts.js";
11
12
  function parse(text) {
12
13
  const match = /^---\n([\s\S]*?)\n---\n\n?/.exec(text);
13
14
  if (!match)
@@ -101,6 +102,10 @@ async function retire(item, action, source = "owner-review") {
101
102
  export async function approveCandidate(options) {
102
103
  const source = options.source ?? "owner-review";
103
104
  const item = await candidate(options.id);
105
+ // A fact captured from a session transcript (T-313) is the model's reading of a conversation:
106
+ // only the owner approves it, whatever proposeAutoApprove or pullAutoApprove say.
107
+ if (isSessionFactSource(item.source) && source !== "owner-review")
108
+ throw new MemoryContractError("PROTECTED", "a fact captured from a session waits for the owner's review");
104
109
  const provenance = {
105
110
  origin: item.origin === "imported" ? "imported" : "inferred",
106
111
  candidate: options.id,