@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
@@ -0,0 +1,67 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { guardStop, } from "@ocean/core/domain/runs/loop-guard.js";
5
+ import { localDate } from "@ocean/core/shared/local-date.js";
6
+ import { INBOX_DIR, oceanPath } from "@ocean/core/shared/paths.js";
7
+ import { sessionTokens } from "../runs/session-tokens.js";
8
+ // Enforcing a LoopGuard after each run (T-322, C2), shared by scheduled jobs and task loops:
9
+ // count the run and its tokens, run the verifier, and — when a limit trips — say why and leave a
10
+ // note for the owner in 00-inbox/escalations/.
11
+ const VERIFY_TIMEOUT_MS = 5 * 60_000;
12
+ export function verifyPasses(command, cwd) {
13
+ return new Promise((resolve) => {
14
+ execFile("sh", ["-c", command], { cwd, timeout: VERIFY_TIMEOUT_MS }, (error) => resolve(!error));
15
+ });
16
+ }
17
+ export async function tokensOfSession(sessionId, openStore) {
18
+ try {
19
+ const store = await openStore();
20
+ try {
21
+ return sessionTokens(store.listEvents(sessionId)) ?? 0;
22
+ }
23
+ finally {
24
+ store.close();
25
+ }
26
+ }
27
+ catch {
28
+ return 0;
29
+ }
30
+ }
31
+ export const emptyUsage = () => ({
32
+ runs: 0,
33
+ tokens: 0,
34
+ noProgress: 0,
35
+ });
36
+ // The usage after one more completed run, and the reason to stop (null: keep going).
37
+ export async function afterGuardedRun(guard, usage, sessionId, cwd, openStore) {
38
+ const next = { ...(usage ?? emptyUsage()) };
39
+ next.runs += 1;
40
+ next.tokens += await tokensOfSession(sessionId, openStore);
41
+ next.noProgress = (await verifyPasses(guard.verify, cwd))
42
+ ? 0
43
+ : next.noProgress + 1;
44
+ return { usage: next, stop: guardStop(guard, next) };
45
+ }
46
+ export async function writeEscalation(input) {
47
+ const file = oceanPath(INBOX_DIR, "escalations", `${localDate()}-${input.kind}-${input.id}.md`);
48
+ await mkdir(path.dirname(file), { recursive: true });
49
+ await writeFile(file, [
50
+ "---",
51
+ "type: escalation",
52
+ `${input.kind}: ${input.id}`,
53
+ `date: ${localDate()}`,
54
+ "---",
55
+ "",
56
+ `# ${input.kind === "schedule" ? "Schedule" : "Loop"} \`${input.id}\` stopped`,
57
+ "",
58
+ `Reason: ${input.reason}.`,
59
+ "",
60
+ `Usage: ${input.usage.runs} runs, ${input.usage.tokens} tokens, ${input.usage.noProgress} runs in a row without verified progress.`,
61
+ "",
62
+ `Look at it, then ${input.resume} to resume, or leave it stopped.`,
63
+ "",
64
+ ].join("\n"), { mode: 0o600 });
65
+ return file;
66
+ }
67
+ //# sourceMappingURL=guard-runtime.js.map
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { assertGuard, guardProblems, } from "@ocean/core/domain/runs/loop-guard.js";
4
5
  import { TASK_ID } from "@ocean/core/domain/tasks/task-id.js";
5
6
  import { oceanPath, projectDir, resolveWithin, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
6
7
  import { folderProject } from "@ocean/core/shared/project-resolution.js";
@@ -8,6 +9,7 @@ import { resolveTaskReference, } from "@ocean/core/shared/task-reference.js";
8
9
  import { runAgent } from "../runs/run-agent.js";
9
10
  import { checkpointTask } from "../tasks/checkpoint-task.js";
10
11
  import { verifyTask } from "../tasks/verify-task.js";
12
+ import { afterGuardedRun, writeEscalation } from "./guard-runtime.js";
11
13
  const loopsFile = () => oceanPath(SYSTEM_DIR, "loops.json");
12
14
  const checkpointsDir = () => oceanPath(SYSTEM_DIR, "loop-checkpoints");
13
15
  export async function listTaskLoops() {
@@ -25,6 +27,8 @@ export async function startTaskLoop(input) {
25
27
  throw new Error("Loop start requires explicit approval.");
26
28
  if (!input.taskId || !TASK_ID.test(input.taskId))
27
29
  throw new Error("Loop requires a valid task id.");
30
+ const guard = input.guard;
31
+ assertGuard(guard);
28
32
  const loop = {
29
33
  id: `loop-${randomUUID()}`,
30
34
  taskId: input.taskId,
@@ -34,7 +38,7 @@ export async function startTaskLoop(input) {
34
38
  cwd: input.cwd,
35
39
  status: "active",
36
40
  approved: true,
37
- maxIterations: bounded(input.maxIterations ?? 10, 1, 100),
41
+ maxIterations: bounded(guard.maxRuns, 1, 100),
38
42
  intervalMs: bounded(input.intervalMs ?? 60_000, 1_000, 86_400_000),
39
43
  maxAttempts: bounded(input.maxAttempts ?? 2, 1, 5),
40
44
  iterations: 0,
@@ -44,6 +48,7 @@ export async function startTaskLoop(input) {
44
48
  lastError: null,
45
49
  checkpoint: "Loop created; inspect the task and choose the first bounded action.",
46
50
  resultPath: null,
51
+ guard,
47
52
  };
48
53
  await saveLoops([...(await listTaskLoops()), loop]);
49
54
  return loop;
@@ -86,6 +91,9 @@ export async function runTaskLoopsOnce(cwd, runtime, options = {}) {
86
91
  const interrupted = saved.next.length > 0;
87
92
  if (loop.status !== "active")
88
93
  continue;
94
+ // A loop started before guards existed never runs (T-322, C2).
95
+ if (guardProblems(loop.guard).length)
96
+ continue;
89
97
  if (!interrupted && Date.parse(loop.nextRunAt) > Date.now())
90
98
  continue;
91
99
  try {
@@ -176,6 +184,21 @@ function iterationSteps(cwd, runtime, options) {
176
184
  loop.checkpoint = `Iteration ${loop.iterations} completed; inspect task ${loop.taskId} before continuing.`;
177
185
  loop.lastError = null;
178
186
  loop.nextRunAt = new Date(Date.now() + loop.intervalMs).toISOString();
187
+ // The guard after each run: token budget, verifier progress, hard cap. A tripped guard
188
+ // fails the loop and tells the owner; the verify step may still mark the task complete.
189
+ const guarded = await afterGuardedRun(loop.guard, loop.usage, sessionId, loop.cwd || cwd, runtime.openStore);
190
+ loop.usage = guarded.usage;
191
+ if (guarded.stop) {
192
+ loop.status = "failed";
193
+ loop.lastError = `guard: ${guarded.stop}`;
194
+ await writeEscalation({
195
+ kind: "loop",
196
+ id: loop.id,
197
+ reason: guarded.stop,
198
+ usage: guarded.usage,
199
+ resume: `start a new loop for ${loop.taskId}`,
200
+ });
201
+ }
179
202
  return { loop, next: "verify" };
180
203
  },
181
204
  // A task is only complete when it claims done AND an independent verifier agrees. A
@@ -0,0 +1,30 @@
1
+ // A provider's final `result` line (Claude's stream-json) carries the session's usage; the sum
2
+ // of input, cache and output tokens, or null when no event reports any.
3
+ export function sessionTokens(events) {
4
+ let total = null;
5
+ for (const event of events) {
6
+ if (event.type !== "json" || !event.data.includes('"usage"'))
7
+ continue;
8
+ let parsed;
9
+ try {
10
+ parsed = JSON.parse(event.data);
11
+ }
12
+ catch {
13
+ continue;
14
+ }
15
+ if (parsed.type !== "result" || !parsed.usage)
16
+ continue;
17
+ const usage = parsed.usage;
18
+ const sum = [
19
+ "input_tokens",
20
+ "cache_creation_input_tokens",
21
+ "cache_read_input_tokens",
22
+ "output_tokens",
23
+ ].reduce((acc, key) => acc + (Number(usage[key]) || 0), 0);
24
+ // A zero-usage result (a synthetic or refused turn) is not a report.
25
+ if (sum > 0)
26
+ total = (total ?? 0) + sum;
27
+ }
28
+ return total;
29
+ }
30
+ //# sourceMappingURL=session-tokens.js.map
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/loop",
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/market",
3
- "version": "2.8.0",
3
+ "version": "2.10.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -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
@@ -193,6 +193,14 @@ const tools = new McpToolRegistry(withContextAck([
193
193
  query: { type: "string" },
194
194
  limit: { type: "number" },
195
195
  types: { type: "array", items: { type: "string" } },
196
+ since: {
197
+ type: "string",
198
+ description: "YYYY-MM-DD: only records dated on or after it",
199
+ },
200
+ asOf: {
201
+ type: "string",
202
+ description: "YYYY-MM-DD: only facts valid on that day (valid_from / superseded_by)",
203
+ },
196
204
  project: { type: "string" },
197
205
  cwd: { type: "string" },
198
206
  },
@@ -580,6 +588,8 @@ async function callTool(name, args, ports) {
580
588
  types: Array.isArray(args.types)
581
589
  ? args.types.filter((item) => typeof item === "string")
582
590
  : undefined,
591
+ since: isoDay(args.since, "since"),
592
+ asOf: isoDay(args.asOf, "asOf"),
583
593
  indexPort: ports.brainIndex,
584
594
  embedder: ports.embedder ? await ports.embedder() : null,
585
595
  });
@@ -767,6 +777,14 @@ async function readResource(uri, ports) {
767
777
  text: JSON.stringify(value, null, 2),
768
778
  };
769
779
  }
780
+ // An optional YYYY-MM-DD argument; anything else is refused rather than silently ignored.
781
+ function isoDay(value, key) {
782
+ if (value === undefined || value === null || value === "")
783
+ return undefined;
784
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value))
785
+ throw new Error(`${key} must be a YYYY-MM-DD date`);
786
+ return value;
787
+ }
770
788
  function requiredArgument(args, key) {
771
789
  const value = args[key];
772
790
  if (typeof value !== "string" || !value)