@amoree-code/ocean 2.9.0 → 2.11.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 +9 -6
  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 +55 -27
  7. package/dist/interfaces/cli/curator-command.js +21 -0
  8. package/dist/interfaces/cli/failures-command.js +71 -0
  9. package/dist/interfaces/cli/help-command.js +18 -6
  10. package/dist/interfaces/cli/hygiene-command.js +31 -0
  11. package/dist/interfaces/cli/memory-command.js +6 -1
  12. package/dist/interfaces/cli/rhythm-command.js +10 -1
  13. package/dist/interfaces/cli/scorecard-command.js +26 -3
  14. package/dist/interfaces/cli/telemetry-command.js +23 -3
  15. package/dist/interfaces/cli/upkeep-command.js +25 -0
  16. package/node_modules/@ocean/brain/dist/memory/lesson-learning.js +3 -1
  17. package/node_modules/@ocean/brain/package.json +1 -1
  18. package/node_modules/@ocean/context/package.json +1 -1
  19. package/node_modules/@ocean/core/dist/domain/runs/loop-guard.js +61 -0
  20. package/node_modules/@ocean/core/package.json +1 -1
  21. package/node_modules/@ocean/loop/dist/loops/guard-runtime.js +67 -0
  22. package/node_modules/@ocean/loop/dist/loops/task-loop.js +24 -1
  23. package/node_modules/@ocean/loop/dist/runs/run-agent.js +3 -1
  24. package/node_modules/@ocean/loop/dist/runs/session-tokens.js +30 -0
  25. package/node_modules/@ocean/loop/package.json +1 -1
  26. package/node_modules/@ocean/market/package.json +1 -1
  27. package/node_modules/@ocean/services/dist/curator/curator.js +209 -0
  28. package/node_modules/@ocean/services/dist/hygiene/hygiene.js +236 -0
  29. package/node_modules/@ocean/services/dist/journey/failures.js +252 -0
  30. package/node_modules/@ocean/services/dist/journey/lesson-effect.js +79 -0
  31. package/node_modules/@ocean/services/dist/journey/telemetry.js +63 -19
  32. package/node_modules/@ocean/services/dist/scorecard/scorecard.js +73 -41
  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
@@ -0,0 +1,252 @@
1
+ import { mkdir, readdir, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { setLessonStatus } from "@ocean/brain/memory/lessons.js";
4
+ import { atomicWrite, parseFrontmatter, withFileLock, } from "@ocean/core/shared/fs-utils.js";
5
+ import { localDate } from "@ocean/core/shared/local-date.js";
6
+ import { KNOWLEDGE_DIR, oceanPath } from "@ocean/core/shared/paths.js";
7
+ // Failure records (T-323): one markdown file per failure signature in 05-knowledge/failures/.
8
+ // A record states the mechanism, not the symptom, and carries a closed status
9
+ // open → fix-landing → absorbed → superseded-by <id>
10
+ // changed only by code, one field per update, with a line appended to its status log; the
11
+ // body above that log is never rewritten. A guardrail ladder (lesson → doctor → test) says
12
+ // how the failure is guarded: when an absorbed signature comes back, telemetry proposes
13
+ // climbing one rung and the owner approves with `ocean failures climb`.
14
+ export const RUNGS = ["lesson", "doctor", "test"];
15
+ // F4: absorb with the cheapest mechanism first, in this order.
16
+ export const ABSORB_MECHANISMS = [
17
+ "doctor",
18
+ "template",
19
+ "code",
20
+ "skill-edit",
21
+ "new-skill",
22
+ ];
23
+ export class FailureRecordError extends Error {
24
+ }
25
+ const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,80}$/;
26
+ const SIGNATURE_PATTERN = /^[a-z]+\/[A-Za-z_]+\/[0-9a-f]{8}$/;
27
+ const NEXT = {
28
+ open: ["fix-landing", "absorbed"],
29
+ "fix-landing": ["absorbed", "open"],
30
+ // Back to open only by climbing the ladder.
31
+ absorbed: [],
32
+ };
33
+ export const failuresDir = () => oceanPath(KNOWLEDGE_DIR, "failures");
34
+ const failureFile = (id) => path.join(failuresDir(), `${id}.md`);
35
+ function parse(source) {
36
+ const fields = parseFrontmatter(source);
37
+ // Records written before T-323 carry no signature; the tooling leaves them alone.
38
+ if (!fields.id || !SIGNATURE_PATTERN.test(fields.signature ?? ""))
39
+ return null;
40
+ const superseded = /^superseded-by\s+(\S+)$/.exec(fields.status ?? "");
41
+ const status = superseded ? "superseded" : fields.status;
42
+ if (!superseded && !(status in NEXT))
43
+ return null;
44
+ const rung = fields.rung;
45
+ if (!RUNGS.includes(rung))
46
+ return null;
47
+ const absorbedBy = (fields.absorbed_by || null);
48
+ if (absorbedBy && !ABSORB_MECHANISMS.includes(absorbedBy))
49
+ return null;
50
+ return {
51
+ id: fields.id,
52
+ title: fields.title ?? fields.id,
53
+ signature: fields.signature,
54
+ status,
55
+ supersededBy: superseded?.[1] ?? null,
56
+ rung,
57
+ mechanism: fields.mechanism ?? "",
58
+ absorbedBy,
59
+ absorbedAt: fields.absorbed_at || null,
60
+ lesson: fields.lesson || null,
61
+ created: fields.created ?? "",
62
+ updated: fields.updated ?? "",
63
+ };
64
+ }
65
+ export async function readFailure(id) {
66
+ if (!ID_PATTERN.test(id))
67
+ throw new FailureRecordError(`Invalid id: ${id}`);
68
+ const source = await readFile(failureFile(id), "utf8").catch(() => null);
69
+ return source === null ? null : parse(source);
70
+ }
71
+ export async function listFailures() {
72
+ const names = await readdir(failuresDir()).catch(() => []);
73
+ const records = [];
74
+ for (const name of names.filter((entry) => entry.endsWith(".md")).sort()) {
75
+ const source = await readFile(path.join(failuresDir(), name), "utf8");
76
+ const record = parse(source);
77
+ if (record)
78
+ records.push(record);
79
+ }
80
+ return records;
81
+ }
82
+ export async function openFailure(input, now = new Date()) {
83
+ const rung = input.rung ?? RUNGS[0];
84
+ if (!RUNGS.includes(rung))
85
+ throw new FailureRecordError(`Rung is one of ${RUNGS.join(" → ")}`);
86
+ if (!ID_PATTERN.test(input.id))
87
+ throw new FailureRecordError(`Invalid id: ${input.id}`);
88
+ if (!SIGNATURE_PATTERN.test(input.signature))
89
+ throw new FailureRecordError(`Invalid signature: ${input.signature} (expected <command>/<class>/<hash>, from ocean telemetry)`);
90
+ if (!input.mechanism.trim())
91
+ throw new FailureRecordError("A failure record states its mechanism: why it happens, not what was seen");
92
+ const owner = (await listFailures()).find((record) => record.signature === input.signature);
93
+ if (owner)
94
+ throw new FailureRecordError(`Signature ${input.signature} already has a record: ${owner.id}`);
95
+ const file = failureFile(input.id);
96
+ await mkdir(failuresDir(), { recursive: true });
97
+ return withFileLock(file, async () => {
98
+ if (await readFile(file, "utf8").catch(() => null))
99
+ throw new FailureRecordError(`Failure ${input.id} already exists`);
100
+ const head = [
101
+ `id: ${input.id}`,
102
+ "type: failure",
103
+ `title: ${JSON.stringify(input.title)}`,
104
+ `signature: ${input.signature}`,
105
+ "status: open",
106
+ `rung: ${rung}`,
107
+ `mechanism: ${JSON.stringify(input.mechanism.replace(/\s+/g, " ").trim())}`,
108
+ input.lesson ? `lesson: ${input.lesson}` : "",
109
+ `created: ${localDate(now)}`,
110
+ `updated: ${localDate(now)}`,
111
+ ].filter(Boolean);
112
+ await atomicWrite(file, [
113
+ `---\n${head.join("\n")}\n---`,
114
+ `# ${input.title}`,
115
+ `## Mechanism\n\n${input.mechanism.trim()}`,
116
+ `## Fix\n\n${input.fix?.trim() || "Pending."}`,
117
+ `## Guardrail\n\n${input.guardrail?.trim() || "Pending."}`,
118
+ // Recurrence is not stored: `ocean failures` counts it from the sessions.
119
+ `## Status log\n\n- ${now.toISOString()} — open (rung ${rung})\n`,
120
+ ].join("\n\n"));
121
+ const record = parse(await readFile(file, "utf8"));
122
+ if (!record)
123
+ throw new FailureRecordError(`Could not read back ${file}`);
124
+ return record;
125
+ });
126
+ }
127
+ // One change per update: the given frontmatter fields are replaced in place, `updated` is
128
+ // stamped and one line is appended to the status log. Nothing else in the file moves.
129
+ async function amend(id, change, now) {
130
+ const file = failureFile(id);
131
+ return withFileLock(file, async () => {
132
+ const source = await readFile(file, "utf8").catch(() => null);
133
+ const record = source === null ? null : parse(source);
134
+ if (!source || !record)
135
+ throw new FailureRecordError(`No failure record: ${id}`);
136
+ const { fields, log } = change(record);
137
+ const end = source.indexOf("\n---", 3);
138
+ let head = source.slice(0, end);
139
+ for (const [key, value] of Object.entries({
140
+ ...fields,
141
+ updated: localDate(now),
142
+ })) {
143
+ const line = new RegExp(`^${key}:.*$`, "m");
144
+ head = line.test(head)
145
+ ? head.replace(line, `${key}: ${value}`)
146
+ : `${head}\n${key}: ${value}`;
147
+ }
148
+ const body = source.slice(end).replace(/\n*$/, "\n");
149
+ await atomicWrite(file, `${head}${body}- ${now.toISOString()} — ${log}\n`);
150
+ const updated = parse(await readFile(file, "utf8"));
151
+ if (!updated)
152
+ throw new FailureRecordError(`Could not read back ${file}`);
153
+ return updated;
154
+ });
155
+ }
156
+ export async function setFailureStatus(id, next, options = {}) {
157
+ const now = options.now ?? new Date();
158
+ const record = await amend(id, (current) => {
159
+ if (current.status === "superseded")
160
+ throw new FailureRecordError(`${id} is superseded by ${current.supersededBy}; it no longer changes`);
161
+ const superseded = /^superseded-by\s+([a-z0-9][a-z0-9-]*)$/.exec(next);
162
+ if (superseded) {
163
+ if (superseded[1] === id)
164
+ throw new FailureRecordError("A record cannot supersede itself");
165
+ return { fields: { status: next }, log: next };
166
+ }
167
+ if (!NEXT[current.status].includes(next))
168
+ throw new FailureRecordError(`${id}: ${current.status} → ${next} is not allowed (${current.status} → ${NEXT[current.status].join(" | ") || "climb"})`);
169
+ if (next !== "absorbed")
170
+ return { fields: { status: next }, log: next };
171
+ const by = options.by;
172
+ if (!by || !ABSORB_MECHANISMS.includes(by))
173
+ throw new FailureRecordError(`Absorbing needs --by <mechanism>, cheapest first: ${ABSORB_MECHANISMS.join(" → ")}`);
174
+ return {
175
+ fields: {
176
+ status: "absorbed",
177
+ absorbed_by: by,
178
+ absorbed_at: now.toISOString(),
179
+ },
180
+ log: `absorbed by ${by}`,
181
+ };
182
+ }, now);
183
+ // An absorbed failure's lesson has done its job and leaves context.
184
+ if (record.status === "absorbed" && record.lesson)
185
+ await setLessonStatus(record.lesson, "retired").catch(() => undefined);
186
+ return record;
187
+ }
188
+ // The owner's approval of a proposed climb: one rung up, and the failure is open again.
189
+ export async function climbFailure(id, now = new Date()) {
190
+ return amend(id, (current) => {
191
+ if (current.status === "superseded")
192
+ throw new FailureRecordError(`${id} is superseded`);
193
+ const at = RUNGS.indexOf(current.rung);
194
+ const next = RUNGS[at + 1];
195
+ if (!next)
196
+ throw new FailureRecordError(`${id} is already on the top rung (${current.rung}); supersede it with a new record instead`);
197
+ return {
198
+ fields: { rung: next, status: "open", absorbed_at: "" },
199
+ log: `climbed ${current.rung} → ${next}; open`,
200
+ };
201
+ }, now);
202
+ }
203
+ // The Definition of done's bar: an absorbed failure clean this many days is driven to zero.
204
+ export const RECURRENCE_WINDOW_DAYS = 14;
205
+ export function failureRecurrence(records,
206
+ // Read over all history, so a recurrence long after absorption still counts.
207
+ stats, now = new Date(), windowDays = RECURRENCE_WINDOW_DAYS) {
208
+ const windowMs = windowDays * 86_400_000;
209
+ return records.map((record) => {
210
+ const seen = stats.get(record.signature);
211
+ const absorbedAt = record.absorbedAt;
212
+ const sinceAbsorbed = absorbedAt
213
+ ? new Set((seen?.hits ?? [])
214
+ .filter((hit) => hit.at > absorbedAt)
215
+ .map((hit) => hit.sessionId)).size
216
+ : 0;
217
+ const lastSeen = seen?.lastSeen ?? null;
218
+ const anchor = record.status === "absorbed" && record.absorbedAt
219
+ ? [record.absorbedAt, lastSeen ?? ""].sort().at(-1)
220
+ : null;
221
+ return {
222
+ id: record.id,
223
+ signature: record.signature,
224
+ status: record.status,
225
+ rung: record.rung,
226
+ recent: new Set((seen?.hits ?? [])
227
+ .filter((hit) => Date.parse(hit.at) >= now.getTime() - windowMs)
228
+ .map((hit) => hit.sessionId)).size,
229
+ sinceAbsorbed,
230
+ lastSeen,
231
+ cleanDays: anchor
232
+ ? Math.floor((now.getTime() - Date.parse(anchor)) / 86_400_000)
233
+ : null,
234
+ };
235
+ });
236
+ }
237
+ // Telemetry's ladder proposals: an absorbed failure whose signature came back.
238
+ export function ladderFindings(recurrence) {
239
+ return recurrence
240
+ .filter((entry) => entry.status === "absorbed" && entry.sinceAbsorbed > 0)
241
+ .map((entry) => {
242
+ const next = RUNGS[RUNGS.indexOf(entry.rung) + 1];
243
+ return {
244
+ line: next
245
+ ? `Failure ${entry.id} came back in ${entry.sinceAbsorbed} sessions after it was absorbed: climb its guardrail ${entry.rung} → ${next} with \`ocean failures climb ${entry.id}\``
246
+ : `Failure ${entry.id} came back in ${entry.sinceAbsorbed} sessions after it was absorbed, on the top rung (${entry.rung}): supersede it with a new record`,
247
+ sessions: entry.sinceAbsorbed,
248
+ signature: entry.signature,
249
+ };
250
+ });
251
+ }
252
+ //# sourceMappingURL=failures.js.map
@@ -0,0 +1,79 @@
1
+ import { scoreSession } from "@ocean/brain/memory/lesson-learning.js";
2
+ import { safeJsonParse } from "@ocean/core/shared/fs-utils.js";
3
+ import { failureSignature } from "./telemetry.js";
4
+ // Does a lesson help? (T-323, ACE): every injected lesson leaves a `lesson_applied` event, so the
5
+ // sessions that had it can be compared with comparable sessions that did not — on verified rate,
6
+ // and, for a lesson tied to a failure record, on how often that failure's signature appeared.
7
+ // A lesson that does no better on either, with enough sessions on both sides, is proposed for
8
+ // retirement; nothing is retired without the owner.
9
+ // `skill_auto_activated` is the same event under its name before T-323.
10
+ export const LESSON_APPLIED_TYPES = new Set([
11
+ "lesson_applied",
12
+ "skill_auto_activated",
13
+ ]);
14
+ // Lessons are only ever injected into runs that assembled context; others are not comparable.
15
+ const COMPARABLE_EVENT = "context_manifest";
16
+ export const MIN_SAMPLE = 5;
17
+ export function appliedLessonIds(events) {
18
+ const ids = events
19
+ .filter((event) => LESSON_APPLIED_TYPES.has(event.type))
20
+ .map((event) => safeJsonParse(event.data)?.id)
21
+ .filter((id) => typeof id === "string");
22
+ return [...new Set(ids)];
23
+ }
24
+ const rate = (n, of) => (of ? n / of : 0);
25
+ export function lessonEffects(sessions, eventsOf, sinceIso, failures = []) {
26
+ const runs = sessions
27
+ .filter((session) => session.createdAt >= sinceIso)
28
+ .map((session) => {
29
+ const events = eventsOf(session.sessionId);
30
+ return { session, events };
31
+ })
32
+ .filter(({ events }) => events.some((e) => e.type === COMPARABLE_EVENT))
33
+ .map(({ session, events }) => ({
34
+ verified: scoreSession(session, events).verified,
35
+ applied: new Set(appliedLessonIds(events)),
36
+ signatures: new Set(events
37
+ .map((event) => failureSignature(event.type, event.data))
38
+ .filter((signature) => signature !== null)),
39
+ }));
40
+ const lessons = new Set(runs.flatMap((run) => [...run.applied]));
41
+ return [...lessons].sort().map((lesson) => {
42
+ const failure = failures.find((record) => record.lesson === lesson) ?? null;
43
+ const sides = { with: blank(), without: blank() };
44
+ for (const run of runs) {
45
+ const side = run.applied.has(lesson) ? sides.with : sides.without;
46
+ side.sessions++;
47
+ if (run.verified)
48
+ side.verified++;
49
+ if (failure && run.signatures.has(failure.signature))
50
+ side.recurred++;
51
+ }
52
+ const enough = sides.with.sessions >= MIN_SAMPLE && sides.without.sessions >= MIN_SAMPLE;
53
+ const betterVerified = rate(sides.with.verified, sides.with.sessions) >
54
+ rate(sides.without.verified, sides.without.sessions);
55
+ const fewerRecurrences = failure !== null &&
56
+ rate(sides.with.recurred, sides.with.sessions) <
57
+ rate(sides.without.recurred, sides.without.sessions);
58
+ return {
59
+ lesson,
60
+ ...sides,
61
+ failure: failure?.id ?? null,
62
+ verdict: !enough
63
+ ? "too-few"
64
+ : betterVerified || fewerRecurrences
65
+ ? "helps"
66
+ : "no-better",
67
+ };
68
+ });
69
+ }
70
+ const blank = () => ({ sessions: 0, verified: 0, recurred: 0 });
71
+ export function retirementFindings(effects) {
72
+ return effects
73
+ .filter((effect) => effect.verdict === "no-better")
74
+ .map((effect) => ({
75
+ line: `Lesson ${effect.lesson} does no better than without it (verified ${effect.with.verified}/${effect.with.sessions} vs ${effect.without.verified}/${effect.without.sessions}${effect.failure ? `; ${effect.failure} recurred ${effect.with.recurred}/${effect.with.sessions} vs ${effect.without.recurred}/${effect.without.sessions}` : ""}): retire it with \`ocean skill review ${effect.lesson} rejected\``,
76
+ sessions: effect.with.sessions,
77
+ }));
78
+ }
79
+ //# sourceMappingURL=lesson-effect.js.map
@@ -1,12 +1,19 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { proposeMemory } from "@ocean/brain/memory/memory-write.js";
2
3
  import { MemoryContractError } from "@ocean/core/domain/mcp/memory-contract.js";
3
4
  // Session telemetry (T-314): what keeps going wrong in Ocean's own sessions becomes a proposed
4
5
  // backlog line for the owner — never a task, never applied without review. Read from the session
5
6
  // store: an error seen in at least MIN_REPEATS sessions, and providers whose sessions fail or are
6
- // left unfinished.
7
+ // left unfinished. T-323 names each error by a signature so a failure record can track it.
7
8
  const MIN_REPEATS = 3;
8
9
  const STUCK_AFTER_MS = 6 * 60 * 60 * 1000;
9
- const ERROR_TYPES = new Set(["error", "provider_blocked", "closeout_warning"]);
10
+ // The event type says which step failed; the signature names that step.
11
+ const COMMAND_OF = {
12
+ error: "run",
13
+ provider_blocked: "provider",
14
+ closeout_warning: "closeout",
15
+ };
16
+ export const isFailureEvent = (type) => type in COMMAND_OF;
10
17
  // The same failure with different ids, paths or numbers counts as one.
11
18
  export function errorShape(text) {
12
19
  return text
@@ -17,26 +24,63 @@ export function errorShape(text) {
17
24
  .trim()
18
25
  .slice(0, 120);
19
26
  }
20
- export function analyzeSessions(sessions, eventsOf, sinceIso, now = Date.now()) {
21
- const recent = sessions.filter((session) => session.createdAt >= sinceIso);
22
- const errors = new Map();
23
- for (const session of recent)
27
+ // What kind of error, without the message: a zod issue code, a Node errno, or an Error's name.
28
+ export function errorClass(text) {
29
+ return (/"code"\s*:\s*"([a-z_]+)"/.exec(text)?.[1] ??
30
+ /\b(E[A-Z]{3,})\b/.exec(text)?.[1] ??
31
+ /\b([A-Z][A-Za-z]*Error)\b/.exec(text)?.[1] ??
32
+ "error");
33
+ }
34
+ // `<command>/<error class>/<hash of the shape>`: stable across ids, paths and numbers, short
35
+ // enough to name a failure record by.
36
+ export function failureSignature(eventType, text) {
37
+ const command = COMMAND_OF[eventType];
38
+ const shape = errorShape(text);
39
+ if (!command || !shape)
40
+ return null;
41
+ const hash = createHash("sha256").update(shape).digest("hex").slice(0, 8);
42
+ return `${command}/${errorClass(text)}/${hash}`;
43
+ }
44
+ // Every signature seen since `sinceIso`, with the sessions it appeared in, however rare.
45
+ export function signatureStats(sessions, eventsOf, sinceIso) {
46
+ const stats = new Map();
47
+ for (const session of sessions) {
48
+ if (session.createdAt < sinceIso)
49
+ continue;
24
50
  for (const event of eventsOf(session.sessionId)) {
25
- if (!ERROR_TYPES.has(event.type))
26
- continue;
27
- const shape = errorShape(event.data);
28
- if (!shape)
51
+ const signature = failureSignature(event.type, event.data);
52
+ if (!signature)
29
53
  continue;
30
- const seen = errors.get(shape) ?? new Set();
31
- seen.add(session.sessionId);
32
- errors.set(shape, seen);
54
+ const at = event.createdAt ?? session.createdAt;
55
+ const entry = stats.get(signature) ?? {
56
+ shape: errorShape(event.data),
57
+ sessions: new Set(),
58
+ hits: [],
59
+ firstSeen: at,
60
+ lastSeen: at,
61
+ };
62
+ entry.sessions.add(session.sessionId);
63
+ entry.hits.push({ sessionId: session.sessionId, at });
64
+ if (at < entry.firstSeen)
65
+ entry.firstSeen = at;
66
+ if (at > entry.lastSeen)
67
+ entry.lastSeen = at;
68
+ stats.set(signature, entry);
33
69
  }
34
- const findings = [...errors]
35
- .filter(([, ids]) => ids.size >= MIN_REPEATS)
36
- .sort((a, b) => b[1].size - a[1].size)
37
- .map(([shape, ids]) => ({
38
- line: `Recurring error in ${ids.size} sessions: ${shape}`,
39
- sessions: ids.size,
70
+ }
71
+ return stats;
72
+ }
73
+ export function analyzeSessions(sessions, eventsOf, sinceIso, now = Date.now()) {
74
+ const recent = sessions.filter((session) => session.createdAt >= sinceIso);
75
+ const findings = [
76
+ ...signatureStats(recent, eventsOf, sinceIso),
77
+ ]
78
+ .filter(([, stats]) => stats.sessions.size >= MIN_REPEATS)
79
+ .sort((a, b) => b[1].sessions.size - a[1].sessions.size)
80
+ .map(([signature, stats]) => ({
81
+ line: `Recurring error in ${stats.sessions.size} sessions [${signature}]: ${stats.shape}`,
82
+ sessions: stats.sessions.size,
83
+ signature,
40
84
  }));
41
85
  const byProvider = new Map();
42
86
  for (const session of recent) {
@@ -1,7 +1,11 @@
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
+ import { RECURRENCE_WINDOW_DAYS, } from "../journey/failures.js";
7
+ // Moved to the loop package (T-322) so run guards can count tokens; re-exported for callers.
8
+ export { sessionTokens };
5
9
  const percent = (n, of) => of ? `${Math.round((n / of) * 1000) / 10}%` : "n/a";
6
10
  function ratio(id, label, n, of, source) {
7
11
  return {
@@ -54,6 +58,8 @@ const OWNER_OR_OCEAN = new Set([
54
58
  "cli",
55
59
  "instructions",
56
60
  "session-telemetry",
61
+ "hygiene",
62
+ "curator",
57
63
  ]);
58
64
  export function writerOf(source, lookup) {
59
65
  const name = source?.trim() ?? "";
@@ -108,9 +114,9 @@ export function searchRows(search, searchEval) {
108
114
  id: "search-eval",
109
115
  label: "Search hit@5 (last eval)",
110
116
  value: `${percent(searchEval.hitAt5, 1)} on ${searchEval.at.slice(0, 10)}`,
111
- source: "ocean brain eval",
117
+ source: "ocean upkeep (memory eval)",
112
118
  }
113
- : notYet("search-eval", "Search hit@5 (last eval)", "ocean brain eval", "T-321", "no eval set"),
119
+ : notYet("search-eval", "Search hit@5 (last eval)", "ocean upkeep (memory eval)", "T-322", "no eval run yet"),
114
120
  ];
115
121
  }
116
122
  export function schedulesRow(schedules) {
@@ -124,10 +130,10 @@ export function schedulesRow(schedules) {
124
130
  source: "ocean schedule list",
125
131
  };
126
132
  }
127
- // "Used" needs a hit count; lessons written before T-323 carry none, so it is not a zero.
128
- export function lessonsRows(lessons) {
133
+ // "Used" counts lessons injected into at least one run (`lesson_applied`, T-323).
134
+ export function lessonsRows(lessons, applied = []) {
129
135
  const active = lessons.filter((fields) => fields.status === "active").length;
130
- const tracked = lessons.filter((fields) => fields.hits !== undefined);
136
+ const used = new Set(applied);
131
137
  return [
132
138
  {
133
139
  id: "lessons-active",
@@ -137,9 +143,30 @@ export function lessonsRows(lessons) {
137
143
  of: lessons.length,
138
144
  source: "05-knowledge/lessons status",
139
145
  },
140
- tracked.length
141
- ? ratio("lessons-used", "Lessons used", tracked.filter((fields) => Number(fields.hits) > 0).length, lessons.length, "lesson hits")
142
- : notYet("lessons-used", "Lessons used", "lesson_applied events", "T-323", "no lesson records its use"),
146
+ ratio("lessons-used", "Lessons used", lessons.filter((fields) => used.has(fields.id)).length, lessons.length, "lesson_applied events"),
147
+ ];
148
+ }
149
+ // Recurrence per failure signature (T-323): one summary row, then one row per failure record.
150
+ export function failuresRows(failures) {
151
+ const zero = failures.filter((entry) => entry.status === "absorbed" &&
152
+ entry.recent === 0 &&
153
+ (entry.cleanDays ?? 0) >= RECURRENCE_WINDOW_DAYS).length;
154
+ return [
155
+ {
156
+ id: "failures-zero",
157
+ label: `Failures at zero ${RECURRENCE_WINDOW_DAYS}+ days`,
158
+ value: `${zero} of ${failures.length}`,
159
+ n: zero,
160
+ of: failures.length,
161
+ source: "05-knowledge/failures + session signatures",
162
+ },
163
+ ...failures.map((entry) => ({
164
+ id: `failure:${entry.id}`,
165
+ label: ` ${entry.id}`,
166
+ value: `${entry.status}, rung ${entry.rung}: ${entry.recent} sessions in ${RECURRENCE_WINDOW_DAYS} d${entry.cleanDays === null ? "" : `, clean ${entry.cleanDays} d`}`,
167
+ n: entry.recent,
168
+ source: `signature ${entry.signature}`,
169
+ })),
143
170
  ];
144
171
  }
145
172
  export function tokensRow(tokens) {
@@ -160,7 +187,26 @@ export function tokensRow(tokens) {
160
187
  source: "session events (provider usage)",
161
188
  };
162
189
  }
163
- export const hygieneRow = () => notYet("hygiene", "Records verified / drifted / unverifiable", "ocean memory hygiene", "T-322");
190
+ export const hygieneRow = (hygiene) => hygiene
191
+ ? {
192
+ id: "hygiene",
193
+ label: "Records verified / drifted / unverifiable",
194
+ value: `${hygiene.verified} / ${hygiene.drifted} / ${hygiene.unverifiable} of ${hygiene.records} with claims (${hygiene.month})`,
195
+ n: hygiene.verified,
196
+ of: hygiene.records,
197
+ source: "ocean memory hygiene",
198
+ }
199
+ : notYet("hygiene", "Records verified / drifted / unverifiable", "ocean memory hygiene", "T-322", "no hygiene run yet");
200
+ export const driftRow = (drift) => drift?.since
201
+ ? {
202
+ id: "drift",
203
+ label: "Records changed with no recorded write",
204
+ value: `${drift.unrecorded} of ${drift.records} since ${drift.since.slice(0, 10)}`,
205
+ n: drift.unrecorded,
206
+ of: drift.records,
207
+ source: "ocean memory drift (hash vs audit log)",
208
+ }
209
+ : notYet("drift", "Records changed with no recorded write", "ocean memory drift (hash vs audit log)", "T-322", "no snapshot to compare yet");
164
210
  export function scorecardRows(input) {
165
211
  return [
166
212
  clientsRow(input.clients),
@@ -170,40 +216,13 @@ export function scorecardRows(input) {
170
216
  tasksVerifiedRow(input.tasks),
171
217
  ...searchRows(input.search, input.searchEval),
172
218
  schedulesRow(input.schedules),
173
- ...lessonsRows(input.lessons),
219
+ ...lessonsRows(input.lessons, input.lessonsApplied),
220
+ ...failuresRows(input.failures),
174
221
  tokensRow(input.tokens),
175
- hygieneRow(),
222
+ hygieneRow(input.hygiene),
223
+ driftRow(input.drift),
176
224
  ];
177
225
  }
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
226
  export function renderTable(rows) {
208
227
  const width = Math.max(...rows.map((row) => row.label.length));
209
228
  return rows
@@ -226,6 +245,19 @@ export function renderMarkdown(rows, date) {
226
245
  "",
227
246
  ].join("\n");
228
247
  }
248
+ // The last nightly search eval (T-322): `ocean upkeep` saves it, the scorecard reads it.
249
+ export const searchEvalFile = () => oceanPath(SYSTEM_DIR, "state", "search-eval.json");
250
+ export async function readSearchEval() {
251
+ try {
252
+ const saved = JSON.parse(await readFile(searchEvalFile(), "utf8"));
253
+ return typeof saved.hitAt5 === "number" && typeof saved.at === "string"
254
+ ? { hitAt5: saved.hitAt5, at: saved.at }
255
+ : null;
256
+ }
257
+ catch {
258
+ return null;
259
+ }
260
+ }
229
261
  export function scorecardFile(date) {
230
262
  return oceanPath(DAILY_DIR, "scorecard", `${date}.md`);
231
263
  }