@amoree-code/ocean 2.8.0 → 2.10.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 (36) hide show
  1. package/README.md +6 -4
  2. package/dist/application/scheduler/local-scheduler.js +57 -4
  3. package/dist/application/upkeep/claim-checkers.js +51 -0
  4. package/dist/application/upkeep/nightly-upkeep.js +229 -0
  5. package/dist/infrastructure/process/service.js +19 -0
  6. package/dist/interfaces/cli/command-registry.js +48 -26
  7. package/dist/interfaces/cli/curator-command.js +21 -0
  8. package/dist/interfaces/cli/help-command.js +13 -5
  9. package/dist/interfaces/cli/hygiene-command.js +31 -0
  10. package/dist/interfaces/cli/memory-command.js +41 -10
  11. package/dist/interfaces/cli/rhythm-command.js +10 -1
  12. package/dist/interfaces/cli/scorecard-command.js +11 -2
  13. package/dist/interfaces/cli/upkeep-command.js +25 -0
  14. package/node_modules/@ocean/brain/dist/brain/brain-eval.js +45 -9
  15. package/node_modules/@ocean/brain/dist/brain/brain-markdown.js +10 -1
  16. package/node_modules/@ocean/brain/dist/brain/brain-reindex.js +4 -1
  17. package/node_modules/@ocean/brain/dist/brain/brain-service.js +69 -8
  18. package/node_modules/@ocean/brain/dist/infrastructure/brain/brain-index.js +5 -3
  19. package/node_modules/@ocean/brain/package.json +1 -1
  20. package/node_modules/@ocean/context/package.json +1 -1
  21. package/node_modules/@ocean/core/dist/domain/ports/brain-index-port.js +3 -2
  22. package/node_modules/@ocean/core/dist/domain/runs/loop-guard.js +61 -0
  23. package/node_modules/@ocean/core/package.json +1 -1
  24. package/node_modules/@ocean/loop/dist/loops/guard-runtime.js +67 -0
  25. package/node_modules/@ocean/loop/dist/loops/task-loop.js +24 -1
  26. package/node_modules/@ocean/loop/dist/runs/session-tokens.js +30 -0
  27. package/node_modules/@ocean/loop/package.json +1 -1
  28. package/node_modules/@ocean/market/package.json +1 -1
  29. package/node_modules/@ocean/services/dist/curator/curator.js +209 -0
  30. package/node_modules/@ocean/services/dist/hygiene/hygiene.js +236 -0
  31. package/node_modules/@ocean/services/dist/infrastructure/mcp/ocean-server.js +18 -0
  32. package/node_modules/@ocean/services/dist/scorecard/scorecard.js +43 -34
  33. package/node_modules/@ocean/services/dist/upkeep/upkeep.js +149 -0
  34. package/node_modules/@ocean/services/package.json +1 -1
  35. package/ocean-marketplace.json +34 -34
  36. package/package.json +7 -7
@@ -13,7 +13,7 @@ const commandGroups = [
13
13
  ],
14
14
  [
15
15
  "Knowledge",
16
- "memory, pull, desktop, observe, capture, note, brief, interests, distill, harvest, rhythm, telemetry, scorecard, express, handoff, idea, daily, skill, catalog",
16
+ "memory, pull, desktop, observe, capture, note, brief, interests, distill, harvest, rhythm, upkeep, curator, telemetry, scorecard, express, handoff, idea, daily, skill, catalog",
17
17
  ],
18
18
  ["Integrations", "obsidian, hook, migrate, layout, env"],
19
19
  ];
@@ -52,7 +52,7 @@ export const commandHelp = {
52
52
  ],
53
53
  loop: [
54
54
  "Start, inspect and stop task loops (repeated agent runs on one task).",
55
- "ocean loop start <task-id> <profile> --prompt <text> --approve [--max-iterations N] [--interval-ms N] [--max-attempts N]|status|stop <loop-id>|worker-once|worker",
55
+ "ocean loop start <task-id> <profile> --approve --verify <cmd> --max-runs N --budget-tokens N --no-progress N --escalate inbox [--interval-ms N] [--max-attempts N] --prompt <text>|status|stop <loop-id>|worker-once|worker",
56
56
  ],
57
57
  policy: [
58
58
  "List the charter's policies, check them, or print one.",
@@ -104,7 +104,7 @@ export const commandHelp = {
104
104
  ],
105
105
  schedule: [
106
106
  "Add, list and run scheduled agent runs.",
107
- "ocean schedule list|add <id> <profile> <interval-ms> <prompt>|enable|disable|run-due|run-now|worker-once|worker",
107
+ "ocean schedule list|add <id> <profile> <interval-ms> --verify <cmd> --max-runs N --budget-tokens N --no-progress N --escalate inbox <prompt>|enable|disable|run-due|run-now|worker-once|worker",
108
108
  ],
109
109
  client: [
110
110
  "Inspect, open, register and sync AI clients.",
@@ -138,7 +138,7 @@ export const commandHelp = {
138
138
  ],
139
139
  memory: [
140
140
  "Search, read, review and maintain memory records and the brain index.",
141
- "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]|audit [--client <name>] [--days N] [--limit N] [--json]|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]",
141
+ "ocean memory doctor|sync [--apply]|review [list|approve <id> [--to <path>]|reject <id>]|eval <questions.json|.jsonl> [--k N] [--min R] [--fts]|hygiene [--yes]|drift [--yes]|digest|harvest [--source <id>] [--yes]|import-claude <export-dir> [--yes]|history [path] [--limit N]|audit [--client <name>] [--days N] [--limit N] [--json]|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] [--type T] [--since D] [--as-of D] [--fts] [--json]|read <id|path>|neighbors <id|path> [--depth N] [--project <id>|--all]",
142
142
  ],
143
143
  pull: [
144
144
  "Pull what AI clients hold into Ocean as review candidates; a dry run until --yes.",
@@ -173,9 +173,17 @@ export const commandHelp = {
173
173
  "ocean harvest [--date YYYY-MM-DD | --pending] [--yes] | archive [--days N] [--yes] | undo <YYYY-MM-DD>",
174
174
  ],
175
175
  rhythm: [
176
- "Run the day's rhythm once per period, no model: morning note, harvest, archive, last week's digest, last month's review.",
176
+ "Run the day's rhythm once per period, no model: morning note, harvest, archive, last week's digest, last month's review, then the nightly upkeep.",
177
177
  "ocean rhythm [--yes]",
178
178
  ],
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/.",
181
+ "ocean upkeep [--yes] [--if-due]",
182
+ ],
183
+ curator: [
184
+ "Mark lessons and skills stale after 30 days unused (or 90 unreviewed), archive after 90; review undoes a mark.",
185
+ "ocean curator [--yes] | review <lesson:id|skill:name>",
186
+ ],
179
187
  telemetry: [
180
188
  "Find recurring errors and failing providers in recent sessions; propose them as backlog lines.",
181
189
  "ocean telemetry [--days N] [--yes]",
@@ -0,0 +1,31 @@
1
+ import { localDate } from "@ocean/core/shared/local-date.js";
2
+ import { checkDrift, readHygieneHistory, renderHygieneReport, runHygiene, writeHygieneReport, } from "@ocean/services/hygiene/hygiene.js";
3
+ import { claimChecker } from "../../application/upkeep/claim-checkers.js";
4
+ // `ocean memory hygiene [--yes]` and `ocean memory drift [--yes]` (T-322): argument parsing and
5
+ // output around services/hygiene and the checkers in application/upkeep.
6
+ export async function runHygieneCommand(args) {
7
+ if (args.some((arg) => arg !== "--yes"))
8
+ throw new Error("Usage: ocean memory hygiene [--yes]");
9
+ const apply = args.includes("--yes");
10
+ const { counts, records } = await runHygiene({
11
+ today: localDate(),
12
+ apply,
13
+ check: claimChecker,
14
+ });
15
+ const drifted = records.filter((record) => record.verdict === "drifted");
16
+ let report = null;
17
+ if (apply)
18
+ report = await writeHygieneReport(counts.month, renderHygieneReport(counts, records, await readHygieneHistory()));
19
+ console.log(JSON.stringify({ counts, drifted, report }, null, 2));
20
+ if (!apply)
21
+ console.error("Dry run: pass --yes to stamp records and write the report.");
22
+ }
23
+ export async function runDriftCommand(args) {
24
+ if (args.some((arg) => arg !== "--yes"))
25
+ throw new Error("Usage: ocean memory drift [--yes]");
26
+ const result = await checkDrift({ apply: args.includes("--yes") });
27
+ console.log(JSON.stringify(result, null, 2));
28
+ if (!args.includes("--yes"))
29
+ console.error("Dry run: pass --yes to save the snapshot and the result.");
30
+ }
31
+ //# sourceMappingURL=hygiene-command.js.map
@@ -1,5 +1,5 @@
1
1
  import { readFile } from "node:fs/promises";
2
- import { evaluateRecall, } from "@ocean/brain/brain/brain-eval.js";
2
+ import { evaluateRecall, parseEvalCases, } 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 { migrateBrainDumps } from "@ocean/brain/memory/brain-dump.js";
@@ -16,6 +16,7 @@ import { isValidProjectId } from "@ocean/core/domain/context/project-id.js";
16
16
  import { folderProject } from "@ocean/core/shared/project-resolution.js";
17
17
  import { defaultBrainIndexPort } from "../../composition/runtime.js";
18
18
  import { createOllamaEmbedder } from "../../infrastructure/providers/ollama-embedder.js";
19
+ import { runDriftCommand, runHygieneCommand } from "./hygiene-command.js";
19
20
  async function runReindex(args) {
20
21
  const noVectors = args.includes("--no-vectors");
21
22
  let embedder = null;
@@ -35,7 +36,9 @@ async function runReindex(args) {
35
36
  });
36
37
  console.log(JSON.stringify(result, null, 2));
37
38
  }
38
- const searchUsage = "Usage: ocean memory search <query> [--project <id> | --all] [--json]";
39
+ const searchUsage = "Usage: ocean memory search <query> [--project <id> | --all] [--type <type>]... [--since YYYY-MM-DD] [--as-of YYYY-MM-DD] [--fts] [--json]";
40
+ const SEARCH_VALUE_FLAGS = new Set(["--type", "--since", "--as-of"]);
41
+ const isDay = (value) => value === undefined || /^\d{4}-\d{2}-\d{2}$/.test(value);
39
42
  const neighborsUsage = "Usage: ocean memory neighbors <id|path> [--depth N] [--project <id> | --all]";
40
43
  // --project <id> / --all, shared by search and neighbors. Default: the cwd's project plus
41
44
  // global records; --all is the explicit unscoped view. null means the flags are malformed.
@@ -66,10 +69,23 @@ async function scopeFrom(flags) {
66
69
  async function runSearch(args) {
67
70
  const flags = parseScopeFlags(args);
68
71
  const json = args.includes("--json");
69
- const query = (flags?.rest ?? [])
70
- .filter((arg) => !arg.startsWith("--"))
71
- .join(" ");
72
- if (!flags || !query) {
72
+ const rest = flags?.rest ?? [];
73
+ const words = [];
74
+ const types = [];
75
+ for (let index = 0; index < rest.length; index += 1) {
76
+ const arg = rest[index];
77
+ if (SEARCH_VALUE_FLAGS.has(arg)) {
78
+ if (arg === "--type" && rest[index + 1])
79
+ types.push(rest[index + 1]);
80
+ index += 1;
81
+ }
82
+ else if (!arg.startsWith("--"))
83
+ words.push(arg);
84
+ }
85
+ const query = words.join(" ");
86
+ const since = flagValue(rest, "--since");
87
+ const asOf = flagValue(rest, "--as-of");
88
+ if (!flags || !query || !isDay(since) || !isDay(asOf)) {
73
89
  console.error(searchUsage);
74
90
  process.exitCode = 1;
75
91
  return;
@@ -78,7 +94,14 @@ async function runSearch(args) {
78
94
  const result = await brainSearch({
79
95
  query,
80
96
  scope: await scopeFrom(flags),
97
+ types: types.length ? types : undefined,
98
+ since,
99
+ asOf,
81
100
  indexPort: defaultBrainIndexPort,
101
+ // Hybrid whenever the local embedder answers (T-321); keyword-only otherwise, or with --fts.
102
+ embedder: rest.includes("--fts")
103
+ ? null
104
+ : await createOllamaEmbedder().catch(() => null),
82
105
  });
83
106
  console.log(json ? JSON.stringify(result) : JSON.stringify(result, null, 2));
84
107
  }
@@ -267,14 +290,18 @@ async function runReview(args) {
267
290
  async function runEval(args) {
268
291
  const file = args.find((arg, index) => !arg.startsWith("--") && !args[index - 1]?.startsWith("--"));
269
292
  if (!file) {
270
- console.error("Usage: ocean memory eval <questions.json> [--k N] [--min 0.9] [--vectors]");
293
+ console.error("Usage: ocean memory eval <questions.json|.jsonl> [--k N] [--min 0.9] [--fts]");
271
294
  process.exitCode = 1;
272
295
  return;
273
296
  }
274
- const cases = JSON.parse(await readFile(file, "utf8"));
297
+ const cases = parseEvalCases(await readFile(file, "utf8"));
298
+ // Same embedder rule as search: vectors when the local model answers, unless --fts pins keyword-only.
299
+ const embedder = args.includes("--fts")
300
+ ? null
301
+ : await createOllamaEmbedder().catch(() => null);
275
302
  const result = await evaluateRecall(cases, {
276
303
  indexPort: defaultBrainIndexPort,
277
- embedder: args.includes("--vectors") ? await createOllamaEmbedder() : null,
304
+ embedder,
278
305
  k: Number(flagValue(args, "--k") ?? 5),
279
306
  });
280
307
  console.log(JSON.stringify(result, null, 2));
@@ -331,6 +358,10 @@ export async function runMemoryCommand(action, args) {
331
358
  }
332
359
  if (action === "eval")
333
360
  return runEval(args);
361
+ if (action === "hygiene")
362
+ return runHygieneCommand(args);
363
+ if (action === "drift")
364
+ return runDriftCommand(args);
334
365
  if (action === "archive-retired") {
335
366
  // T-314: retired lessons out of the index, into lessons/archive/ (kept).
336
367
  const moved = await archiveRetiredLessons({
@@ -406,7 +437,7 @@ export async function runMemoryCommand(action, args) {
406
437
  console.log(JSON.stringify({ dryRun: !args.includes("--apply"), stores: result }, null, 2));
407
438
  return;
408
439
  }
409
- 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]|audit [--client <name>] [--days N] [--limit N] [--json]|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]");
440
+ console.error("Usage: ocean memory doctor|sync [--apply]|review [list|approve <id> [--to <path>]|reject <id>]|eval <questions.json|.jsonl> [--k N] [--min R] [--fts]|hygiene [--yes]|drift [--yes]|digest|harvest [--source <id>] [--yes]|import-claude <export-dir> [--yes]|history [path] [--limit N]|audit [--client <name>] [--days N] [--limit N] [--json]|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] [--type T] [--since D] [--as-of D] [--fts] [--json]|read <id|path>|neighbors <id|path> [--depth N] [--project <id>|--all]");
410
441
  process.exitCode = 1;
411
442
  }
412
443
  //# sourceMappingURL=memory-command.js.map
@@ -8,9 +8,11 @@ import { prepareDay } from "@ocean/services/day/day.js";
8
8
  import { hasBlock, noteFile } from "@ocean/services/day/note.js";
9
9
  import { distillWeek, isoWeek, reviewMonth, } from "@ocean/services/distill/distill.js";
10
10
  import { archiveHarvested, harvestDay, pendingDays, } from "@ocean/services/harvest/harvest.js";
11
+ import { runUpkeepCommand } from "./upkeep-command.js";
11
12
  // `ocean rhythm [--yes]` (T-314): everything the day, week and month need, with no model, each
12
13
  // at most once: today's morning note, every day not yet harvested (and today so far), the
13
- // archive, last week's digest once the week is over, last month's review once the month is over.
14
+ // archive, last week's digest once the week is over, last month's review once the month is over,
15
+ // then the nightly upkeep and its morning digest once a day (T-322).
14
16
  // The background service runs it at each session start; a run with nothing due is quick.
15
17
  const stampFile = () => oceanPath(SYSTEM_DIR, "state", "rhythm.json");
16
18
  const previousMonth = (date) => {
@@ -23,6 +25,13 @@ export async function runRhythmCommand(args) {
23
25
  await mkdir(path.dirname(stampFile()), { recursive: true });
24
26
  // One run at a time: a session start and the hourly service tick can land together.
25
27
  await withFileLock(stampFile(), () => rhythm(args));
28
+ // Nightly upkeep (T-322) once a day, outside the rhythm lock: its jobs take minutes. A run that
29
+ // finds another one holding the upkeep lock leaves it to that one.
30
+ if (args.includes("--yes"))
31
+ await runUpkeepCommand(["--yes", "--if-due"]).catch((error) => {
32
+ if (!/still held/.test(String(error)))
33
+ throw error;
34
+ });
26
35
  }
27
36
  async function rhythm(args) {
28
37
  const apply = args.includes("--yes");
@@ -3,7 +3,8 @@ import { brainIndexPort } from "@ocean/brain/infrastructure/brain/brain-index.js
3
3
  import { readAudit } from "@ocean/brain/memory/memory-audit.js";
4
4
  import { localDate } from "@ocean/core/shared/local-date.js";
5
5
  import { openSessionStoreReadOnly } from "@ocean/loop/infrastructure/persistence/session-store.js";
6
- import { readLessonFrontmatter, readTaskFrontmatter, renderTable, scorecardRows, sessionTokens, writeScorecard, } from "@ocean/services/scorecard/scorecard.js";
6
+ import { readDrift, readHygieneHistory, } from "@ocean/services/hygiene/hygiene.js";
7
+ import { readLessonFrontmatter, readSearchEval, readTaskFrontmatter, renderTable, scorecardRows, sessionTokens, writeScorecard, } from "@ocean/services/scorecard/scorecard.js";
7
8
  import { clientFindings } from "../../application/clients/clients.js";
8
9
  import { CLIENT_ADAPTERS } from "../../application/clients/registry.js";
9
10
  import { listSchedules } from "../../application/scheduler/local-scheduler.js";
@@ -67,10 +68,18 @@ async function collect() {
67
68
  },
68
69
  tasks: await readTaskFrontmatter(),
69
70
  search,
70
- searchEval: null,
71
+ searchEval: await readSearchEval(),
71
72
  schedules: await listSchedules(),
72
73
  lessons: await readLessonFrontmatter(),
73
74
  tokens,
75
+ hygiene: (await readHygieneHistory()).at(-1) ?? null,
76
+ drift: await readDrift().then((drift) => drift
77
+ ? {
78
+ records: drift.records,
79
+ unrecorded: drift.unrecorded.length,
80
+ since: drift.since,
81
+ }
82
+ : null),
74
83
  };
75
84
  }
76
85
  // `ocean scorecard [--json] [--write]` (T-318): Ocean's health numbers from real data; --write
@@ -0,0 +1,25 @@
1
+ import { localDate } from "@ocean/core/shared/local-date.js";
2
+ import { runNightlyUpkeep, upkeepDoneToday, upkeepJobs, } from "../../application/upkeep/nightly-upkeep.js";
3
+ // `ocean upkeep [--yes] [--if-due]` (T-322): the nightly jobs and the morning digest. `ocean
4
+ // rhythm` runs it with --if-due, so it happens at most once a day; by hand it always runs. A dry
5
+ // run lists tonight's jobs.
6
+ export async function runUpkeepCommand(args) {
7
+ const unknown = args.filter((arg) => !["--yes", "--if-due"].includes(arg));
8
+ if (unknown.length)
9
+ throw new Error("Usage: ocean upkeep [--yes] [--if-due]");
10
+ const today = localDate();
11
+ const ifDue = args.includes("--if-due");
12
+ if (ifDue && (await upkeepDoneToday(today))) {
13
+ console.log(JSON.stringify({ upkeep: "done today" }));
14
+ return;
15
+ }
16
+ if (!args.includes("--yes")) {
17
+ const jobs = await upkeepJobs(today);
18
+ console.log(JSON.stringify({ jobs: jobs.map((job) => `ocean ${job.args.join(" ")}`) }, null, 2));
19
+ console.error("Dry run: pass --yes to run them and write the digest.");
20
+ return;
21
+ }
22
+ const ran = await runNightlyUpkeep({ today, ifDue });
23
+ console.log(JSON.stringify(ran ?? { upkeep: "done today" }, null, 2));
24
+ }
25
+ //# sourceMappingURL=upkeep-command.js.map
@@ -1,28 +1,64 @@
1
1
  import { brainSearch } from "./brain-service.js";
2
+ // MRR looks past k so a near miss at rank 6–10 still counts for something.
3
+ const MRR_DEPTH = 10;
4
+ // A JSON array, or JSON Lines (one case per line, blank lines ignored).
5
+ export function parseEvalCases(text) {
6
+ const trimmed = text.trim();
7
+ if (trimmed.startsWith("["))
8
+ return JSON.parse(trimmed);
9
+ return trimmed
10
+ .split("\n")
11
+ .map((line) => line.trim())
12
+ .filter(Boolean)
13
+ .map((line) => JSON.parse(line));
14
+ }
2
15
  export async function evaluateRecall(cases, options) {
3
16
  const k = options.k ?? 5;
17
+ const depth = Math.max(k, MRR_DEPTH);
4
18
  const misses = [];
19
+ let hitsAt1 = 0;
20
+ let reciprocalSum = 0;
21
+ let hybrid = cases.length > 0;
5
22
  for (const item of cases) {
6
23
  const expect = [item.expect].flat();
7
- const { results } = await brainSearch({
24
+ const { results, mode } = await brainSearch({
8
25
  query: item.question,
9
- limit: k,
26
+ limit: depth,
10
27
  root: options.root,
11
28
  embedder: options.embedder ?? null,
12
29
  indexPort: options.indexPort,
13
30
  scope: item.project === undefined ? undefined : { project: item.project },
14
31
  });
15
- const got = results.map((hit) => hit.file);
16
- const found = results.some((hit) => expect.includes(hit.path) || expect.includes(hit.file));
17
- if (!found)
18
- misses.push({ question: item.question, expect, got });
32
+ if (mode !== "hybrid")
33
+ hybrid = false;
34
+ const rank = results.findIndex((hit) => expect.includes(hit.path) || expect.includes(hit.file)) + 1;
35
+ if (rank === 1)
36
+ hitsAt1 += 1;
37
+ if (rank > 0)
38
+ reciprocalSum += 1 / rank;
39
+ if (rank === 0 || rank > k)
40
+ misses.push({
41
+ question: item.question,
42
+ expect,
43
+ got: results.slice(0, k).map((hit) => hit.file),
44
+ });
19
45
  }
20
- const hits = cases.length - misses.length;
46
+ const total = cases.length;
47
+ const hits = total - misses.length;
48
+ const ratio = (value) => total ? Math.round((value / total) * 1000) / 1000 : 0;
21
49
  return {
50
+ settings: {
51
+ mode: hybrid ? "hybrid" : "fts",
52
+ embedder: hybrid ? (options.embedder?.model ?? null) : null,
53
+ k,
54
+ depth,
55
+ },
22
56
  k,
23
- total: cases.length,
57
+ total,
24
58
  hits,
25
- recall: cases.length ? hits / cases.length : 0,
59
+ recall: ratio(hits),
60
+ hitAt1: ratio(hitsAt1),
61
+ mrr: ratio(reciprocalSum),
26
62
  misses,
27
63
  };
28
64
  }
@@ -117,7 +117,16 @@ export function normalizeRecord(relPath, rawSource) {
117
117
  ? "defaulted"
118
118
  : "declared",
119
119
  };
120
- return { record, conformance, body, rawScope: scopeField.value };
120
+ return {
121
+ record,
122
+ conformance,
123
+ body,
124
+ rawScope: scopeField.value,
125
+ validity: {
126
+ validFrom: fields.valid_from || null,
127
+ supersededBy: fields.superseded_by || null,
128
+ },
129
+ };
121
130
  }
122
131
  // Extracts `[[target]]`, `[[target|alias]]`, `[[target#heading]]`, ignoring fenced code
123
132
  // blocks (``` ... ```) so a documentation example is never mistaken for a real link.
@@ -119,7 +119,7 @@ export async function reindexBrain(options) {
119
119
  // A retired record (a superseded lesson or decision) stays on disk but out of search (T-314).
120
120
  if (/^status:\s*["']?retired["']?\s*$/m.test(source.split(/\r?\n---/, 1)[0]))
121
121
  continue;
122
- const { record, conformance, body, rawScope } = normalizeRecord(relative, source);
122
+ const { record, conformance, body, rawScope, validity } = normalizeRecord(relative, source);
123
123
  const links = extractWikilinks(body).map((link) => ({
124
124
  targetRaw: link.target,
125
125
  heading: link.heading,
@@ -131,6 +131,7 @@ export async function reindexBrain(options) {
131
131
  record,
132
132
  conformance,
133
133
  rawScope,
134
+ validity,
134
135
  body,
135
136
  contentHash: createHash("sha256").update(source).digest("hex"),
136
137
  bytes: Buffer.byteLength(source, "utf8"),
@@ -192,6 +193,8 @@ export async function reindexBrain(options) {
192
193
  created: doc.record.created,
193
194
  updated: doc.record.updated,
194
195
  lastConfirmedAt: doc.record.lastConfirmedAt,
196
+ validFrom: doc.validity.validFrom,
197
+ supersededBy: doc.validity.supersededBy,
195
198
  contentHash: doc.contentHash,
196
199
  bytes: doc.bytes,
197
200
  conformance: doc.conformance,
@@ -11,12 +11,60 @@ export class BrainIndexStaleError extends Error {
11
11
  }
12
12
  function assertScoped(reader) {
13
13
  if (reader.meta.schemaVersion !== BRAIN_INDEX_SCHEMA_VERSION)
14
- throw new BrainIndexStaleError(`brain index schema ${reader.meta.schemaVersion} predates record scopes — run \`ocean memory reindex\``);
14
+ throw new BrainIndexStaleError(`brain index schema ${reader.meta.schemaVersion} is older than ${BRAIN_INDEX_SCHEMA_VERSION} — run \`ocean memory reindex\``);
15
15
  }
16
16
  const RRF_K = 60;
17
17
  // The owner's own notes outrank what agents wrote on the same question (T-314).
18
18
  const HUMAN_BOOST = 1.5;
19
19
  const isHumanNote = (storePath) => storePath.startsWith("notes/");
20
+ // Rank adjustments (T-321), multiplied into the fused score. RRF scores sit close together, so
21
+ // these are nudges, not overrides. Tuned on the owner's 40-question eval (hybrid hit@5 0.825 →
22
+ // 0.90): a recency boost was tried and lowered both modes, so recency is the `since` filter only.
23
+ const RANK = {
24
+ decision: 1.05, // a decision answers "what did we decide" better than the talk around it
25
+ session: 0.6, // a raw session log loses to the curated record distilled from it
26
+ lowConfidence: 0.8, // confidence: low (COG memory hygiene, C1)
27
+ unverified: 0.9, // last confirmed more than STALE_DAYS ago
28
+ superseded: 0.5, // replaced by a newer record; still findable, never first
29
+ };
30
+ const STALE_DAYS = 180;
31
+ const DAY_MS = 86_400_000;
32
+ const text = (value) => typeof value === "string" && value ? value : null;
33
+ // Dates in frontmatter are YYYY-MM-DD, possibly with a time; the day is what is compared.
34
+ const dayOf = (value) => text(value)?.match(/^\d{4}-\d{2}-\d{2}/)?.[0] ?? null;
35
+ const daysBetween = (from, to) => (to.getTime() - Date.parse(`${from}T00:00:00Z`)) / DAY_MS;
36
+ const docDate = (doc) => dayOf(doc.updated) ?? dayOf(doc.last_confirmed_at) ?? dayOf(doc.created);
37
+ // When a record starts to hold: its declared valid_from, else when it was written.
38
+ const startOf = (doc) => dayOf(doc.valid_from) ?? dayOf(doc.created) ?? dayOf(doc.updated);
39
+ // Whether the fact a record states held on `asOf`: it had started, and whatever replaced it had
40
+ // not. A successor with no date, or one the index cannot resolve, counts as already in force.
41
+ function validOn(doc, asOf, successor) {
42
+ const start = startOf(doc);
43
+ if (start && start > asOf)
44
+ return false;
45
+ const replacedBy = text(doc.superseded_by);
46
+ if (!replacedBy)
47
+ return true;
48
+ const next = successor(replacedBy);
49
+ const nextStart = next ? startOf(next) : null;
50
+ return nextStart !== null && nextStart > asOf;
51
+ }
52
+ function rankFactor(doc, now, asOf) {
53
+ let factor = isHumanNote(String(doc.path ?? "")) ? HUMAN_BOOST : 1;
54
+ if (doc.type === "decision")
55
+ factor *= RANK.decision;
56
+ if (doc.type === "session")
57
+ factor *= RANK.session;
58
+ if (String(doc.confidence).toLowerCase() === "low")
59
+ factor *= RANK.lowConfidence;
60
+ const confirmed = dayOf(doc.last_confirmed_at);
61
+ if (confirmed && daysBetween(confirmed, now) > STALE_DAYS)
62
+ factor *= RANK.unverified;
63
+ // As of a past date the filter has already removed what was not yet replaced then.
64
+ if (!asOf && text(doc.superseded_by))
65
+ factor *= RANK.superseded;
66
+ return factor;
67
+ }
20
68
  function snippetOf(text, maxLen = 240) {
21
69
  const trimmed = text.trim().replace(/\s+/g, " ");
22
70
  return trimmed.length > maxLen ? `${trimmed.slice(0, maxLen - 1)}…` : trimmed;
@@ -98,14 +146,18 @@ export async function brainSearch(options) {
98
146
  });
99
147
  }
100
148
  }
149
+ const now = options.now ?? new Date();
150
+ const successor = (ref) => reader.getDocByIdOrPath(ref) ??
151
+ (ref.endsWith(".md") ? undefined : reader.getDocByIdOrPath(`${ref}.md`));
101
152
  const ranked = [...byDoc.entries()]
102
- .map(([docId, entry]) => ({
103
- docId,
104
- ...entry,
105
- score: isHumanNote(String(reader.getDoc(docId)?.path ?? ""))
106
- ? entry.score * HUMAN_BOOST
107
- : entry.score,
108
- }))
153
+ .map(([docId, entry]) => {
154
+ const doc = reader.getDoc(docId);
155
+ return {
156
+ docId,
157
+ ...entry,
158
+ score: doc ? entry.score * rankFactor(doc, now, options.asOf) : 0,
159
+ };
160
+ })
109
161
  .sort((a, b) => b.score - a.score || a.docId - b.docId);
110
162
  const results = [];
111
163
  for (const item of ranked) {
@@ -117,6 +169,13 @@ export async function brainSearch(options) {
117
169
  continue;
118
170
  if (options.types?.length && !options.types.includes(String(doc.type)))
119
171
  continue;
172
+ if (options.since) {
173
+ const dated = docDate(doc);
174
+ if (!dated || dated < options.since)
175
+ continue;
176
+ }
177
+ if (options.asOf && !validOn(doc, options.asOf, successor))
178
+ continue;
120
179
  // Backstop for hits the SQL filter never saw (vector hits are not scope-filtered).
121
180
  if (options.scope &&
122
181
  !scopeVisible(String(doc.scope), options.scope.project))
@@ -133,6 +192,8 @@ export async function brainSearch(options) {
133
192
  scope: String(doc.scope ?? "global"),
134
193
  confidence: String(doc.confidence),
135
194
  lastConfirmedAt: doc.last_confirmed_at ?? null,
195
+ validFrom: text(doc.valid_from),
196
+ supersededBy: text(doc.superseded_by),
136
197
  heading: chunk ? (chunk.heading ?? null) : null,
137
198
  snippet: chunk ? snippetOf(String(chunk.text)) : "",
138
199
  score: Math.round(item.score * 1_000_000) / 1_000_000,
@@ -37,6 +37,8 @@ function createSchema(db, withVectors, dims) {
37
37
  created TEXT,
38
38
  updated TEXT,
39
39
  last_confirmed_at TEXT,
40
+ valid_from TEXT,
41
+ superseded_by TEXT,
40
42
  content_hash TEXT NOT NULL,
41
43
  bytes INTEGER NOT NULL,
42
44
  conformance_json TEXT NOT NULL
@@ -71,8 +73,8 @@ function createSchema(db, withVectors, dims) {
71
73
  async function populate(db, docs, links, options) {
72
74
  const insertDoc = db.prepare(`
73
75
  INSERT INTO docs (id, path, title, summary, tags_json, type, scope, confidence, created, updated,
74
- last_confirmed_at, content_hash, bytes, conformance_json)
75
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
76
+ last_confirmed_at, valid_from, superseded_by, content_hash, bytes, conformance_json)
77
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
76
78
  `);
77
79
  const insertChunk = db.prepare(`
78
80
  INSERT INTO chunks (doc_id, ordinal, heading, text) VALUES (?, ?, ?, ?)
@@ -91,7 +93,7 @@ async function populate(db, docs, links, options) {
91
93
  db.exec("BEGIN");
92
94
  try {
93
95
  for (const doc of docs) {
94
- insertDoc.run(doc.id, doc.path, doc.title, doc.summary, JSON.stringify(doc.tags), doc.type, doc.scope, doc.confidence, doc.created, doc.updated, doc.lastConfirmedAt, doc.contentHash, doc.bytes, JSON.stringify(doc.conformance));
96
+ insertDoc.run(doc.id, doc.path, doc.title, doc.summary, JSON.stringify(doc.tags), doc.type, doc.scope, doc.confidence, doc.created, doc.updated, doc.lastConfirmedAt, doc.validFrom, doc.supersededBy, doc.contentHash, doc.bytes, JSON.stringify(doc.conformance));
95
97
  const docIdRow = db.prepare("SELECT last_insert_rowid() AS id").get();
96
98
  const docId = Number(docIdRow.id);
97
99
  pathToDocId.set(doc.path, docId);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/brain",
3
- "version": "2.8.0",
3
+ "version": "2.10.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.8.0",
3
+ "version": "2.10.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -2,6 +2,7 @@
2
2
  // concrete node:sqlite + sqlite-vec implementation lives in infrastructure/brain/brain-index.ts
3
3
  // and is wired in through composition/runtime.js, never imported directly by application
4
4
  // code (enforced by tests/architecture.test.mjs).
5
- // 2: docs carry a scope. The index is a disposable cache, so a bump means "reindex", not a migration.
6
- export const BRAIN_INDEX_SCHEMA_VERSION = "2";
5
+ // 2: docs carry a scope. 3: docs carry valid_from and superseded_by (T-321).
6
+ // The index is a disposable cache, so a bump means "reindex", not a migration.
7
+ export const BRAIN_INDEX_SCHEMA_VERSION = "3";
7
8
  //# sourceMappingURL=brain-index-port.js.map
@@ -0,0 +1,61 @@
1
+ // The guard every recurring agent run declares (T-322, COG C2 loop engineering): how a run is
2
+ // verified, a hard cap on runs, a token budget, when to stop for lack of progress, and who is
3
+ // told when it stops. A scheduled job or loop without a complete guard is refused at creation.
4
+ export const GUARD_FLAGS = "--verify <cmd> --max-runs N --budget-tokens N --no-progress N --escalate inbox";
5
+ const positiveInt = (value) => typeof value === "number" && Number.isInteger(value) && value > 0;
6
+ // What is missing or invalid; empty when the guard is complete.
7
+ export function guardProblems(guard) {
8
+ const problems = [];
9
+ if (!guard?.verify?.trim())
10
+ problems.push("verify: a verifier command");
11
+ if (!positiveInt(guard?.maxRuns))
12
+ problems.push("max-runs: a hard cap");
13
+ if (!positiveInt(guard?.budgetTokens))
14
+ problems.push("budget-tokens: a token budget");
15
+ if (!positiveInt(guard?.noProgressRuns))
16
+ problems.push("no-progress: a no-progress exit");
17
+ if (guard?.escalate !== "inbox")
18
+ problems.push("escalate: human escalation (inbox)");
19
+ return problems;
20
+ }
21
+ export function assertGuard(guard) {
22
+ const problems = guardProblems(guard);
23
+ if (problems.length)
24
+ throw new Error(`Refused: a recurring agent run must declare ${problems.join("; ")}. Pass ${GUARD_FLAGS}.`);
25
+ }
26
+ // Why the guard stops the job now, or null to keep going.
27
+ export function guardStop(guard, usage) {
28
+ if (usage.runs >= guard.maxRuns)
29
+ return `hard cap reached: ${usage.runs} of ${guard.maxRuns} runs`;
30
+ if (usage.tokens >= guard.budgetTokens)
31
+ return `token budget used: ${usage.tokens} of ${guard.budgetTokens}`;
32
+ if (usage.noProgress >= guard.noProgressRuns)
33
+ return `no verified progress in ${usage.noProgress} runs in a row`;
34
+ return null;
35
+ }
36
+ // Parses the guard flags out of an argument list; returns the guard and the remaining arguments.
37
+ export function parseGuardFlags(args) {
38
+ const guard = {};
39
+ const rest = [];
40
+ for (let index = 0; index < args.length; index += 1) {
41
+ const flag = args[index];
42
+ const value = args[index + 1];
43
+ if (flag === "--verify")
44
+ guard.verify = value;
45
+ else if (flag === "--max-runs")
46
+ guard.maxRuns = Number(value);
47
+ else if (flag === "--budget-tokens")
48
+ guard.budgetTokens = Number(value);
49
+ else if (flag === "--no-progress")
50
+ guard.noProgressRuns = Number(value);
51
+ else if (flag === "--escalate")
52
+ guard.escalate = value;
53
+ else {
54
+ rest.push(flag);
55
+ continue;
56
+ }
57
+ index += 1;
58
+ }
59
+ return { guard, rest };
60
+ }
61
+ //# sourceMappingURL=loop-guard.js.map
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/core",
3
- "version": "2.8.0",
3
+ "version": "2.10.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {