@amoree-code/ocean 2.9.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 (29) 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 +6 -1
  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/package.json +1 -1
  15. package/node_modules/@ocean/context/package.json +1 -1
  16. package/node_modules/@ocean/core/dist/domain/runs/loop-guard.js +61 -0
  17. package/node_modules/@ocean/core/package.json +1 -1
  18. package/node_modules/@ocean/loop/dist/loops/guard-runtime.js +67 -0
  19. package/node_modules/@ocean/loop/dist/loops/task-loop.js +24 -1
  20. package/node_modules/@ocean/loop/dist/runs/session-tokens.js +30 -0
  21. package/node_modules/@ocean/loop/package.json +1 -1
  22. package/node_modules/@ocean/market/package.json +1 -1
  23. package/node_modules/@ocean/services/dist/curator/curator.js +209 -0
  24. package/node_modules/@ocean/services/dist/hygiene/hygiene.js +236 -0
  25. package/node_modules/@ocean/services/dist/scorecard/scorecard.js +43 -34
  26. package/node_modules/@ocean/services/dist/upkeep/upkeep.js +149 -0
  27. package/node_modules/@ocean/services/package.json +1 -1
  28. package/ocean-marketplace.json +34 -34
  29. package/package.json +7 -7
@@ -0,0 +1,209 @@
1
+ import { mkdir, readdir, readFile, rename } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { appendAudit, sha256 } from "@ocean/brain/memory/memory-audit.js";
4
+ import { atomicWrite, parseFrontmatter } from "@ocean/core/shared/fs-utils.js";
5
+ import { KNOWLEDGE_DIR, oceanPath, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
6
+ import { setFrontmatterFields } from "@ocean/loop/tasks/task-verification.js";
7
+ // The curator (T-322, Hermes pattern): a lesson or skill not used for 30 days is marked `stale`,
8
+ // for 90 days `archived`; one not reviewed for 90 days is marked `stale` too (forge F8). Every
9
+ // change is reversible with `review`, which stamps `last_reviewed` and restores the status it had.
10
+ // Lessons archive into lessons/archive/ (the index never walks it); skills are only marked, never
11
+ // moved, because client skill folders are synced from bridge/skills/.
12
+ //
13
+ // No client records a use yet (T-323), so an item's clock starts the first night the curator
14
+ // sees it (bridge/state/curator.json): missing data is never read as "unused".
15
+ export const STALE_DAYS = 30;
16
+ export const ARCHIVE_DAYS = 90;
17
+ export const REVIEW_DAYS = 90;
18
+ const DAY_MS = 86_400_000;
19
+ const USE_FIELDS = [
20
+ "last_used",
21
+ "last_confirmed_at",
22
+ "last_verified",
23
+ "last_reviewed",
24
+ ];
25
+ const CURATOR_STATES = new Set(["stale", "archived"]);
26
+ const lessonsDir = () => oceanPath(KNOWLEDGE_DIR, "lessons");
27
+ const skillsDir = () => oceanPath(SYSTEM_DIR, "skills");
28
+ export const curatorStateFile = () => oceanPath(SYSTEM_DIR, "state", "curator.json");
29
+ const dayOf = (value) => value && /^\d{4}-\d{2}-\d{2}/.test(value) ? value.slice(0, 10) : null;
30
+ const daysBetween = (from, to) => Math.floor((Date.parse(to) - Date.parse(from)) / DAY_MS);
31
+ const latest = (days) => days
32
+ .filter((day) => day !== null)
33
+ .sort()
34
+ .at(-1) ?? null;
35
+ export async function listCurated() {
36
+ const items = [];
37
+ const lessons = lessonsDir();
38
+ for (const [dir, archived] of [
39
+ [lessons, false],
40
+ [path.join(lessons, "archive"), true],
41
+ ]) {
42
+ for (const name of (await readdir(dir).catch(() => [])).sort()) {
43
+ if (!name.endsWith(".md") || name === "CONFLICTS.md")
44
+ continue;
45
+ const file = path.join(dir, name);
46
+ // Only lessons the curator archived come back from archive/; T-314 retirements stay there.
47
+ if (archived) {
48
+ const status = parseFrontmatter(await readFile(file, "utf8")).status;
49
+ if (status !== "archived")
50
+ continue;
51
+ }
52
+ items.push({ kind: "lesson", key: `lesson:${name.slice(0, -3)}`, file });
53
+ }
54
+ }
55
+ for (const name of (await readdir(skillsDir()).catch(() => [])).sort()) {
56
+ const file = path.join(skillsDir(), name, "SKILL.md");
57
+ if (await readFile(file, "utf8").catch(() => null))
58
+ items.push({ kind: "skill", key: `skill:${name}`, file });
59
+ }
60
+ return items;
61
+ }
62
+ // What the curator would do to one item today, from its frontmatter and first-seen day.
63
+ export function judge(fields, firstSeen, today) {
64
+ const lastUse = latest([
65
+ firstSeen,
66
+ ...USE_FIELDS.map((key) => dayOf(fields[key])),
67
+ ]);
68
+ const lastReview = latest([firstSeen, dayOf(fields.last_reviewed)]);
69
+ const unused = lastUse ? daysBetween(lastUse, today) : 0;
70
+ const unreviewed = lastReview ? daysBetween(lastReview, today) : 0;
71
+ if (unused >= ARCHIVE_DAYS)
72
+ return { status: "archived", reason: `unused ${unused} days` };
73
+ if (unused >= STALE_DAYS)
74
+ return { status: "stale", reason: `unused ${unused} days` };
75
+ if (unreviewed >= REVIEW_DAYS)
76
+ return { status: "stale", reason: `not reviewed for ${unreviewed} days` };
77
+ return { status: "fresh", reason: "" };
78
+ }
79
+ function dropFields(source, keys) {
80
+ const end = source.indexOf("\n---", 4);
81
+ if (!source.startsWith("---\n") || end < 0)
82
+ return source;
83
+ const kept = source
84
+ .slice(4, end)
85
+ .split("\n")
86
+ .filter((line) => !keys.includes(line.match(/^([\w-]+):/)?.[1] ?? ""));
87
+ return `---\n${kept.join("\n")}${source.slice(end)}`;
88
+ }
89
+ const archivePath = (item) => path.join(lessonsDir(), "archive", path.basename(item.file));
90
+ const livePath = (item) => path.join(lessonsDir(), path.basename(item.file));
91
+ // Lesson edits go through the memory audit, so the nightly drift check does not flag them.
92
+ async function writeAudited(item, source, text, finalFile) {
93
+ if (item.kind !== "lesson")
94
+ return;
95
+ await appendAudit({
96
+ action: "update",
97
+ path: path.relative(oceanPath(), finalFile).split(path.sep).join("/"),
98
+ source: "curator",
99
+ beforeSha: sha256(source),
100
+ afterSha: sha256(text),
101
+ });
102
+ }
103
+ async function mark(item, source, status, today) {
104
+ const fields = parseFrontmatter(source);
105
+ const from = CURATOR_STATES.has(fields.status ?? "")
106
+ ? (fields.curator_from ?? "none")
107
+ : (fields.status ?? "none");
108
+ const text = setFrontmatterFields(source, {
109
+ status,
110
+ curator_from: from,
111
+ curated_at: today,
112
+ });
113
+ if (item.kind === "lesson" && status === "archived") {
114
+ await mkdir(path.dirname(archivePath(item)), { recursive: true });
115
+ await atomicWrite(item.file, text);
116
+ await rename(item.file, archivePath(item));
117
+ await writeAudited(item, source, text, archivePath(item));
118
+ }
119
+ else {
120
+ await atomicWrite(item.file, text);
121
+ await writeAudited(item, source, text, item.file);
122
+ }
123
+ }
124
+ async function restore(item, source, today) {
125
+ const fields = parseFrontmatter(source);
126
+ const previous = fields.curator_from;
127
+ let text = dropFields(source, ["curator_from", "curated_at"]);
128
+ text =
129
+ !previous || previous === "none"
130
+ ? dropFields(text, ["status"])
131
+ : setFrontmatterFields(text, { status: previous });
132
+ text = setFrontmatterFields(text, { last_reviewed: today });
133
+ await atomicWrite(item.file, text);
134
+ let file = item.file;
135
+ if (item.kind === "lesson" && item.file !== livePath(item)) {
136
+ await rename(item.file, livePath(item));
137
+ file = livePath(item);
138
+ }
139
+ await writeAudited(item, source, text, file);
140
+ return file;
141
+ }
142
+ async function readState() {
143
+ try {
144
+ const saved = JSON.parse(await readFile(curatorStateFile(), "utf8"));
145
+ return { firstSeen: saved.firstSeen ?? {} };
146
+ }
147
+ catch {
148
+ return { firstSeen: {} };
149
+ }
150
+ }
151
+ // One pass: record first sightings, then mark, archive or restore each item. Dry run unless apply.
152
+ export async function curate(options) {
153
+ const state = await readState();
154
+ const actions = [];
155
+ for (const item of await listCurated()) {
156
+ state.firstSeen[item.key] ??= options.today;
157
+ const source = await readFile(item.file, "utf8");
158
+ const fields = parseFrontmatter(source);
159
+ const current = CURATOR_STATES.has(fields.status ?? "")
160
+ ? fields.status
161
+ : "fresh";
162
+ const verdict = judge(fields, state.firstSeen[item.key], options.today);
163
+ if (verdict.status === current)
164
+ continue;
165
+ // A newer use or review lifts the mark; archived never steps back down to stale on its own.
166
+ if (verdict.status === "fresh") {
167
+ actions.push({
168
+ key: item.key,
169
+ action: "restored",
170
+ reason: "used or reviewed again",
171
+ });
172
+ if (options.apply)
173
+ await restore(item, source, options.today);
174
+ }
175
+ else if (!(current === "archived" && verdict.status === "stale")) {
176
+ actions.push({
177
+ key: item.key,
178
+ action: verdict.status,
179
+ reason: verdict.reason,
180
+ });
181
+ if (options.apply)
182
+ await mark(item, source, verdict.status, options.today);
183
+ }
184
+ }
185
+ if (options.apply) {
186
+ await mkdir(path.dirname(curatorStateFile()), { recursive: true });
187
+ await atomicWrite(curatorStateFile(), `${JSON.stringify(state, null, 2)}\n`);
188
+ }
189
+ return actions;
190
+ }
191
+ // `ocean curator review <key>`: the owner looked at it — stamp last_reviewed, undo any mark.
192
+ export async function reviewCurated(key, today) {
193
+ const item = (await listCurated()).find((candidate) => candidate.key === key || candidate.key.endsWith(`:${key}`));
194
+ if (!item)
195
+ throw new Error(`Not a lesson or skill the curator tracks: ${key}`);
196
+ const source = await readFile(item.file, "utf8");
197
+ const marked = CURATOR_STATES.has(parseFrontmatter(source).status ?? "");
198
+ if (marked)
199
+ return {
200
+ key: item.key,
201
+ file: await restore(item, source, today),
202
+ restored: true,
203
+ };
204
+ const text = setFrontmatterFields(source, { last_reviewed: today });
205
+ await atomicWrite(item.file, text);
206
+ await writeAudited(item, source, text, item.file);
207
+ return { key: item.key, file: item.file, restored: false };
208
+ }
209
+ //# sourceMappingURL=curator.js.map
@@ -0,0 +1,236 @@
1
+ import { mkdir, readdir, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { appendAudit, readAudit, sha256, } from "@ocean/brain/memory/memory-audit.js";
4
+ import { atomicWrite, parseFrontmatter } from "@ocean/core/shared/fs-utils.js";
5
+ import { DAILY_DIR, KNOWLEDGE_DIR, oceanPath, PERSONAL_DIR, PROJECTS_DIR, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
6
+ import { setFrontmatterFields } from "@ocean/loop/tasks/task-verification.js";
7
+ const SKIP_HOSTS = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|example\.(com|org|net)|[^/]*\.(local|test|example|invalid))$/i;
8
+ const PLACEHOLDER = /[<>*{}$|]|\.\.\./;
9
+ // An absolute path is a claim only under a real filesystem root; `/auth/refresh` is an API route.
10
+ const FS_ROOTS = /^\/(Users|home|opt|etc|usr|var|tmp|private|Library|Applications|Volumes|System|mnt|srv|root)\//;
11
+ // Workspace-relative markdown records that state facts: personal, professional, knowledge, and
12
+ // each project's memory/ and docs/. Archives are excluded.
13
+ export async function hygieneRecords() {
14
+ const root = oceanPath();
15
+ const found = [];
16
+ const walk = async (dir, keep) => {
17
+ const entries = await readdir(path.join(root, dir), {
18
+ withFileTypes: true,
19
+ }).catch(() => []);
20
+ for (const entry of entries) {
21
+ const rel = path.posix.join(dir, entry.name);
22
+ if (entry.isDirectory()) {
23
+ if (entry.name !== "archive" && !entry.name.startsWith("."))
24
+ await walk(rel, keep);
25
+ }
26
+ else if (entry.name.endsWith(".md") && keep(rel))
27
+ found.push(rel);
28
+ }
29
+ };
30
+ for (const dir of [PERSONAL_DIR, "03-professional", KNOWLEDGE_DIR])
31
+ await walk(dir, () => true);
32
+ await walk(PROJECTS_DIR, (rel) => /\/(memory|docs)\//.test(rel));
33
+ return found.sort();
34
+ }
35
+ export function extractClaims(text) {
36
+ const claims = new Map();
37
+ const add = (claim) => claims.set(`${claim.kind}:${claim.value}`, claim);
38
+ for (const [, raw] of text.matchAll(/`((?:~|\/)[^`\s]+)`/g)) {
39
+ if (PLACEHOLDER.test(raw) || !raw.replace(/^~?\//, "").includes("/"))
40
+ continue;
41
+ if (raw.startsWith("/") && !FS_ROOTS.test(raw))
42
+ continue;
43
+ add({ kind: "path", value: raw.replace(/[.,;:]+$/, "") });
44
+ }
45
+ for (const [raw] of text.matchAll(/https?:\/\/[^\s<>"'`)\]]+/g)) {
46
+ const url = raw.replace(/[.,;:!?]+$/, "");
47
+ let parsed;
48
+ try {
49
+ parsed = new URL(url);
50
+ }
51
+ catch {
52
+ continue;
53
+ }
54
+ if (SKIP_HOSTS.test(parsed.hostname) || PLACEHOLDER.test(url))
55
+ continue;
56
+ if (parsed.hostname === "github.com") {
57
+ const [owner, repo] = parsed.pathname.split("/").filter(Boolean);
58
+ if (owner && repo)
59
+ add({ kind: "repo", value: `${owner}/${repo.replace(/\.git$/, "")}` });
60
+ continue;
61
+ }
62
+ add({ kind: "url", value: url });
63
+ }
64
+ return [...claims.values()];
65
+ }
66
+ export function verdictOf(checks) {
67
+ if (checks.includes("missing"))
68
+ return "drifted";
69
+ return checks.every((check) => check === "ok") ? "verified" : "unverifiable";
70
+ }
71
+ const isNumber = (value) => value !== undefined && value !== "" && !Number.isNaN(Number(value));
72
+ // The stamp a record gets, or null when it gets none.
73
+ export function stampFor(source, verdict, today) {
74
+ if (verdict === "unverifiable")
75
+ return null;
76
+ const fields = parseFrontmatter(source);
77
+ if (!source.startsWith("---\n"))
78
+ return null;
79
+ const change = {};
80
+ if (verdict === "verified")
81
+ change.last_verified = today;
82
+ if (!isNumber(fields.confidence))
83
+ change.confidence = verdict === "verified" ? "high" : "low";
84
+ const next = setFrontmatterFields(source, change);
85
+ return next === source ? null : next;
86
+ }
87
+ export const hygieneFile = (month) => oceanPath(DAILY_DIR, "hygiene", `${month}.md`);
88
+ export async function runHygiene(options) {
89
+ const root = oceanPath();
90
+ const cache = new Map();
91
+ const check = (claim) => {
92
+ const key = `${claim.kind}:${claim.value}`;
93
+ if (!cache.has(key))
94
+ cache.set(key, options.check(claim).catch(() => "unknown"));
95
+ return cache.get(key);
96
+ };
97
+ const records = [];
98
+ for (const rel of await hygieneRecords()) {
99
+ const file = path.join(root, rel);
100
+ const source = await readFile(file, "utf8");
101
+ const claims = extractClaims(source);
102
+ if (!claims.length)
103
+ continue;
104
+ const checks = await Promise.all(claims.map(check));
105
+ const verdict = verdictOf(checks);
106
+ records.push({
107
+ path: rel,
108
+ verdict,
109
+ failing: claims.filter((_, index) => checks[index] === "missing"),
110
+ });
111
+ const stamped = options.apply
112
+ ? stampFor(source, verdict, options.today)
113
+ : null;
114
+ if (stamped) {
115
+ await atomicWrite(file, stamped);
116
+ await appendAudit({
117
+ action: "update",
118
+ path: rel,
119
+ source: "hygiene",
120
+ beforeSha: sha256(source),
121
+ afterSha: sha256(stamped),
122
+ });
123
+ }
124
+ }
125
+ const count = (verdict) => records.filter((record) => record.verdict === verdict).length;
126
+ return {
127
+ counts: {
128
+ month: options.today.slice(0, 7),
129
+ records: records.length,
130
+ verified: count("verified"),
131
+ drifted: count("drifted"),
132
+ unverifiable: count("unverifiable"),
133
+ },
134
+ records,
135
+ };
136
+ }
137
+ // Every saved monthly report's counts, oldest first.
138
+ export async function readHygieneHistory() {
139
+ const dir = path.dirname(hygieneFile("x"));
140
+ const history = [];
141
+ for (const name of (await readdir(dir).catch(() => [])).sort()) {
142
+ if (!/^\d{4}-\d{2}\.md$/.test(name))
143
+ continue;
144
+ const fields = parseFrontmatter(await readFile(path.join(dir, name), "utf8"));
145
+ history.push({
146
+ month: name.slice(0, 7),
147
+ records: Number(fields.records) || 0,
148
+ verified: Number(fields.verified) || 0,
149
+ drifted: Number(fields.drifted) || 0,
150
+ unverifiable: Number(fields.unverifiable) || 0,
151
+ });
152
+ }
153
+ return history;
154
+ }
155
+ export function renderHygieneReport(counts, records, earlier) {
156
+ const trend = [
157
+ ...earlier.filter((row) => row.month !== counts.month),
158
+ counts,
159
+ ];
160
+ const drifted = records.filter((record) => record.verdict === "drifted");
161
+ return [
162
+ "---",
163
+ "type: hygiene",
164
+ `month: ${counts.month}`,
165
+ `records: ${counts.records}`,
166
+ `verified: ${counts.verified}`,
167
+ `drifted: ${counts.drifted}`,
168
+ `unverifiable: ${counts.unverifiable}`,
169
+ "---",
170
+ "",
171
+ `# Memory hygiene — ${counts.month}`,
172
+ "",
173
+ `${counts.records} records make an environment claim: ${counts.verified} verified, ${counts.drifted} drifted, ${counts.unverifiable} unverifiable (a check could not answer).`,
174
+ "",
175
+ "## Drift trend",
176
+ "",
177
+ "| Month | Records | Verified | Drifted | Unverifiable |",
178
+ "|---|---|---|---|---|",
179
+ ...trend.map((row) => `| ${row.month} | ${row.records} | ${row.verified} | ${row.drifted} | ${row.unverifiable} |`),
180
+ "",
181
+ "## Proposed for archive (review; nothing was deleted)",
182
+ "",
183
+ ...(drifted.length
184
+ ? drifted.map((record) => `- \`${record.path}\` — ${record.failing.map((claim) => `${claim.kind} \`${claim.value}\` missing`).join("; ")}`)
185
+ : ["None."]),
186
+ "",
187
+ ].join("\n");
188
+ }
189
+ export async function writeHygieneReport(month, text) {
190
+ const file = hygieneFile(month);
191
+ await mkdir(path.dirname(file), { recursive: true });
192
+ await atomicWrite(file, text);
193
+ return file;
194
+ }
195
+ // --- Drift (F6) -----------------------------------------------------------------------------
196
+ const snapshotFile = () => oceanPath(SYSTEM_DIR, "state", "record-hashes.json");
197
+ export const driftFile = () => oceanPath(SYSTEM_DIR, "state", "drift.json");
198
+ export async function checkDrift(options) {
199
+ const now = (options.now ?? new Date()).toISOString();
200
+ const root = oceanPath();
201
+ const hashes = {};
202
+ for (const rel of await hygieneRecords())
203
+ hashes[rel] = sha256(await readFile(path.join(root, rel), "utf8"));
204
+ const previous = JSON.parse(await readFile(snapshotFile(), "utf8").catch(() => "{}"));
205
+ const since = previous.at ?? null;
206
+ let unrecorded = [];
207
+ if (since && previous.hashes) {
208
+ const old = previous.hashes;
209
+ const written = new Set((await readAudit())
210
+ .filter((entry) => entry.ts >= since)
211
+ .map((entry) => entry.path));
212
+ unrecorded = Object.keys(hashes).filter((rel) => old[rel] !== undefined && old[rel] !== hashes[rel] && !written.has(rel));
213
+ }
214
+ const result = {
215
+ at: now,
216
+ since,
217
+ records: Object.keys(hashes).length,
218
+ unrecorded,
219
+ };
220
+ if (options.apply) {
221
+ await mkdir(path.dirname(snapshotFile()), { recursive: true });
222
+ await atomicWrite(snapshotFile(), `${JSON.stringify({ at: now, hashes })}\n`);
223
+ await atomicWrite(driftFile(), `${JSON.stringify(result, null, 2)}\n`);
224
+ }
225
+ return result;
226
+ }
227
+ export async function readDrift() {
228
+ try {
229
+ const saved = JSON.parse(await readFile(driftFile(), "utf8"));
230
+ return Array.isArray(saved.unrecorded) ? saved : null;
231
+ }
232
+ catch {
233
+ return null;
234
+ }
235
+ }
236
+ //# sourceMappingURL=hygiene.js.map
@@ -1,7 +1,10 @@
1
1
  import { mkdir, readdir, readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { atomicWrite, parseFrontmatter } from "@ocean/core/shared/fs-utils.js";
4
- import { DAILY_DIR, KNOWLEDGE_DIR, listProjectDirs, oceanPath, } from "@ocean/core/shared/paths.js";
4
+ import { DAILY_DIR, KNOWLEDGE_DIR, listProjectDirs, oceanPath, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
5
+ import { sessionTokens } from "@ocean/loop/runs/session-tokens.js";
6
+ // Moved to the loop package (T-322) so run guards can count tokens; re-exported for callers.
7
+ export { sessionTokens };
5
8
  const percent = (n, of) => of ? `${Math.round((n / of) * 1000) / 10}%` : "n/a";
6
9
  function ratio(id, label, n, of, source) {
7
10
  return {
@@ -54,6 +57,8 @@ const OWNER_OR_OCEAN = new Set([
54
57
  "cli",
55
58
  "instructions",
56
59
  "session-telemetry",
60
+ "hygiene",
61
+ "curator",
57
62
  ]);
58
63
  export function writerOf(source, lookup) {
59
64
  const name = source?.trim() ?? "";
@@ -108,9 +113,9 @@ export function searchRows(search, searchEval) {
108
113
  id: "search-eval",
109
114
  label: "Search hit@5 (last eval)",
110
115
  value: `${percent(searchEval.hitAt5, 1)} on ${searchEval.at.slice(0, 10)}`,
111
- source: "ocean brain eval",
116
+ source: "ocean upkeep (memory eval)",
112
117
  }
113
- : notYet("search-eval", "Search hit@5 (last eval)", "ocean brain eval", "T-321", "no eval set"),
118
+ : notYet("search-eval", "Search hit@5 (last eval)", "ocean upkeep (memory eval)", "T-322", "no eval run yet"),
114
119
  ];
115
120
  }
116
121
  export function schedulesRow(schedules) {
@@ -160,7 +165,26 @@ export function tokensRow(tokens) {
160
165
  source: "session events (provider usage)",
161
166
  };
162
167
  }
163
- export const hygieneRow = () => notYet("hygiene", "Records verified / drifted / unverifiable", "ocean memory hygiene", "T-322");
168
+ export const hygieneRow = (hygiene) => hygiene
169
+ ? {
170
+ id: "hygiene",
171
+ label: "Records verified / drifted / unverifiable",
172
+ value: `${hygiene.verified} / ${hygiene.drifted} / ${hygiene.unverifiable} of ${hygiene.records} with claims (${hygiene.month})`,
173
+ n: hygiene.verified,
174
+ of: hygiene.records,
175
+ source: "ocean memory hygiene",
176
+ }
177
+ : notYet("hygiene", "Records verified / drifted / unverifiable", "ocean memory hygiene", "T-322", "no hygiene run yet");
178
+ export const driftRow = (drift) => drift?.since
179
+ ? {
180
+ id: "drift",
181
+ label: "Records changed with no recorded write",
182
+ value: `${drift.unrecorded} of ${drift.records} since ${drift.since.slice(0, 10)}`,
183
+ n: drift.unrecorded,
184
+ of: drift.records,
185
+ source: "ocean memory drift (hash vs audit log)",
186
+ }
187
+ : notYet("drift", "Records changed with no recorded write", "ocean memory drift (hash vs audit log)", "T-322", "no snapshot to compare yet");
164
188
  export function scorecardRows(input) {
165
189
  return [
166
190
  clientsRow(input.clients),
@@ -172,38 +196,10 @@ export function scorecardRows(input) {
172
196
  schedulesRow(input.schedules),
173
197
  ...lessonsRows(input.lessons),
174
198
  tokensRow(input.tokens),
175
- hygieneRow(),
199
+ hygieneRow(input.hygiene),
200
+ driftRow(input.drift),
176
201
  ];
177
202
  }
178
- // A provider's final `result` line (Claude's stream-json) carries the session's usage; the sum
179
- // of input, cache and output tokens, or null when no event reports any.
180
- export function sessionTokens(events) {
181
- let total = null;
182
- for (const event of events) {
183
- if (event.type !== "json" || !event.data.includes('"usage"'))
184
- continue;
185
- let parsed;
186
- try {
187
- parsed = JSON.parse(event.data);
188
- }
189
- catch {
190
- continue;
191
- }
192
- if (parsed.type !== "result" || !parsed.usage)
193
- continue;
194
- const usage = parsed.usage;
195
- const sum = [
196
- "input_tokens",
197
- "cache_creation_input_tokens",
198
- "cache_read_input_tokens",
199
- "output_tokens",
200
- ].reduce((acc, key) => acc + (Number(usage[key]) || 0), 0);
201
- // A zero-usage result (a synthetic or refused turn) is not a report.
202
- if (sum > 0)
203
- total = (total ?? 0) + sum;
204
- }
205
- return total;
206
- }
207
203
  export function renderTable(rows) {
208
204
  const width = Math.max(...rows.map((row) => row.label.length));
209
205
  return rows
@@ -226,6 +222,19 @@ export function renderMarkdown(rows, date) {
226
222
  "",
227
223
  ].join("\n");
228
224
  }
225
+ // The last nightly search eval (T-322): `ocean upkeep` saves it, the scorecard reads it.
226
+ export const searchEvalFile = () => oceanPath(SYSTEM_DIR, "state", "search-eval.json");
227
+ export async function readSearchEval() {
228
+ try {
229
+ const saved = JSON.parse(await readFile(searchEvalFile(), "utf8"));
230
+ return typeof saved.hitAt5 === "number" && typeof saved.at === "string"
231
+ ? { hitAt5: saved.hitAt5, at: saved.at }
232
+ : null;
233
+ }
234
+ catch {
235
+ return null;
236
+ }
237
+ }
229
238
  export function scorecardFile(date) {
230
239
  return oceanPath(DAILY_DIR, "scorecard", `${date}.md`);
231
240
  }