@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
package/README.md CHANGED
@@ -134,7 +134,7 @@ prints its usage and never runs it. To hand `--help` to a wrapped client, put it
134
134
  | `ocean context` | the workspace context for this folder; `cost` measures each client's always-on context | Reads |
135
135
  | `ocean project` | resolve, bind, register, rename, move and index projects; `status`: each one's git state, open tasks, last session and next action | Reads; `bind`, `register`, `rename`, `unbind`, `--write` write |
136
136
  | `ocean tasks` | list, create, claim, checkpoint, verify and complete tasks | Reads; `new`, `claim`, `checkpoint`, `complete`, `archive --apply` write |
137
- | `ocean loop` | repeated agent runs on one task | Runs; `start` needs `--approve` |
137
+ | `ocean loop` | repeated agent runs on one task, each loop with a guard (verifier, run cap, token budget, no-progress exit, escalation) | Runs; `start` needs `--approve` and the guard |
138
138
  | `ocean policy` | list the charter's policies or print one | Reads |
139
139
  | `ocean lifecycle` | decide whether work should checkpoint now | Reads |
140
140
  | `ocean doctor` | health check of workspace, clients and integrations | Reads |
@@ -147,7 +147,7 @@ prints its usage and never runs it. To hand `--help` to a wrapped client, put it
147
147
  | `ocean operate` | classify a plain-language request and run the matching operation | Runs |
148
148
  | `ocean intent` | classify a plain-language request | Reads |
149
149
  | `ocean gateway` | local webhook gateway on 127.0.0.1 (needs `OCEAN_GATEWAY_TOKEN`) | Runs |
150
- | `ocean schedule` | scheduled agent runs | Writes; `run-now`, `worker` run |
150
+ | `ocean schedule` | scheduled agent runs, each with a guard (verifier, run cap, token budget, no-progress exit, escalation); `add` refuses one without it; the service runs due ones hourly | Writes; `run-now`, `worker` run |
151
151
  | `ocean client` | inspect, open, register and sync AI clients | Reads; `open` runs; `sync`, `register`, `enable`, `disable` write |
152
152
  | `ocean clients` | connect installed AI clients to Ocean | Reads; `apply` needs `--yes` and writes client config outside the workspace |
153
153
  | `ocean install` / `update` / `remove` | install, update or remove an AI client CLI | Runs an installer; needs `--yes` |
@@ -155,7 +155,7 @@ prints its usage and never runs it. To hand `--help` to a wrapped client, put it
155
155
  | `ocean mcp` | print MCP client configs, or serve Ocean's MCP server and gateway | Reads; `serve`, `gateway` run; `browser-service uninstall` removes the retired browser bridge's service |
156
156
  | `ocean market` | marketplace skills and MCP servers | Reads; `install`, `update`, `uninstall` write; `exec` runs; permissions need `--yes` |
157
157
  | `ocean browser` | drive a browser session | Runs; `upload`, `submit` need `--approve` |
158
- | `ocean memory` | search, read, review and maintain memory | Reads; `approve`, `delete`, `restore`, `reindex`, `sync --apply`, `purge --yes` write |
158
+ | `ocean memory` | search, read, review and maintain memory; `hygiene` re-checks records' paths, URLs and repos, `drift` finds records changed without an audited write | Reads; `approve`, `delete`, `restore`, `reindex`, `sync --apply`, `purge --yes`, `hygiene --yes`, `drift --yes` write |
159
159
  | `ocean pull` | pull what AI clients hold into Ocean as review candidates | Reads (dry run); `--yes` writes |
160
160
  | `ocean desktop` | capture facts from Claude Desktop's chat, read from the app's local store, as review candidates | Reads (`--dry-run`); a run writes candidates |
161
161
  | `ocean observe` | run a command and record its output | Runs |
@@ -165,7 +165,9 @@ prints its usage and never runs it. To hand `--help` to a wrapped client, put it
165
165
  | `ocean interests` | propose interests from your projects or recurring session topics (as candidates), decay, keep/skip | Writes |
166
166
  | `ocean distill` | `--week`: a weekly digest, decisions and lessons as candidates; `--month`: last month against your goals | Writes |
167
167
  | `ocean harvest` | a day's sessions from every client into its summary; decisions, fixes and lessons filed into knowledge (undo per day); archive after 30 days | Writes |
168
- | `ocean rhythm` | the day's rhythm, once per period and with no model: morning note, harvest, archive, last week's digest, last month's review (the service runs it) | Writes |
168
+ | `ocean rhythm` | the day's rhythm, once per period and with no model: morning note, harvest, archive, last week's digest, last month's review, then the nightly upkeep (the service runs it) | Writes |
169
+ | `ocean upkeep` | the nightly jobs with no model — doctor, telemetry, reindex, search eval, drift, curator, scorecard, and memory hygiene once a month — then the morning digest in `01-daily/digest/` | Writes with `--yes` |
170
+ | `ocean curator` | marks lessons and skills stale after 30 days unused (or 90 unreviewed) and archives them after 90; `review` undoes a mark | Writes with `--yes` |
169
171
  | `ocean telemetry` | recurring session errors and failing providers, as proposed backlog lines | Writes |
170
172
  | `ocean scorecard` | Ocean's health numbers from real data: clients working, sessions verified and linked to tasks, attributed memory writes, search mode, schedules, lessons | Reads; `--write` saves `01-daily/scorecard/` |
171
173
  | `ocean express` | draft a CV section, LinkedIn post or scholarship paragraph from milestones | Writes |
@@ -1,6 +1,8 @@
1
1
  import { mkdir, open, readFile, rename, unlink, writeFile, } from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import { assertGuard, guardProblems, } from "@ocean/core/domain/runs/loop-guard.js";
3
4
  import { oceanPath, SYSTEM_DIR } from "@ocean/core/shared/paths.js";
5
+ import { afterGuardedRun, emptyUsage, writeEscalation, } from "@ocean/loop/loops/guard-runtime.js";
4
6
  import { runAgent } from "@ocean/loop/runs/run-agent.js";
5
7
  const file = () => oceanPath(SYSTEM_DIR, "schedules.json");
6
8
  const running = new Set();
@@ -17,6 +19,7 @@ export async function listSchedules() {
17
19
  export async function saveSchedule(schedule) {
18
20
  if (!Number.isFinite(schedule.intervalMs) || schedule.intervalMs < 1_000)
19
21
  throw new Error("Schedule interval must be at least 1000ms");
22
+ assertGuard(schedule.guard);
20
23
  await mutateSchedules((schedules) => [
21
24
  ...schedules.filter((item) => item.id !== schedule.id),
22
25
  schedule,
@@ -27,18 +30,56 @@ export async function setScheduleEnabled(id, enabled) {
27
30
  await mutateSchedules((schedules) => schedules.map((schedule) => {
28
31
  if (schedule.id !== id)
29
32
  return schedule;
30
- updated = { ...schedule, enabled };
33
+ // Enabling a schedule a guard stopped is the owner's answer to the escalation: its
34
+ // counters start over.
35
+ updated =
36
+ enabled && schedule.stoppedReason
37
+ ? {
38
+ ...schedule,
39
+ enabled,
40
+ stoppedReason: undefined,
41
+ usage: emptyUsage(),
42
+ }
43
+ : { ...schedule, enabled };
31
44
  return updated;
32
45
  }));
33
46
  if (!updated)
34
47
  throw new Error(`Schedule not found: ${id}`);
35
48
  return updated;
36
49
  }
50
+ const guarded = (schedule) => guardProblems(schedule.guard).length === 0;
51
+ // After a completed run: count it and its tokens, run the verifier, and stop the schedule (and
52
+ // tell the owner) when a guard trips. Mutates `schedule`.
53
+ async function applyGuard(schedule, sessionId, cwd, runtime) {
54
+ const { usage, stop } = await afterGuardedRun(schedule.guard, schedule.usage, sessionId, cwd, runtime.openStore);
55
+ schedule.usage = usage;
56
+ if (!stop)
57
+ return;
58
+ schedule.enabled = false;
59
+ schedule.stoppedReason = stop;
60
+ await writeEscalation({
61
+ kind: "schedule",
62
+ id: schedule.id,
63
+ reason: stop,
64
+ usage,
65
+ resume: `\`ocean schedule enable ${schedule.id}\``,
66
+ });
67
+ }
68
+ const guardFields = (schedule) => ({
69
+ usage: schedule.usage,
70
+ enabled: schedule.enabled,
71
+ stoppedReason: schedule.stoppedReason,
72
+ });
37
73
  export async function runSchedule(id, cwd, runtime) {
38
74
  const schedule = (await listSchedules()).find((item) => item.id === id);
39
75
  if (!schedule)
40
76
  throw new Error(`Schedule not found: ${id}`);
41
- await runAgent({ profileName: schedule.profile, prompt: schedule.prompt, cwd }, runtime);
77
+ assertGuard(schedule.guard);
78
+ const session = await runAgent({ profileName: schedule.profile, prompt: schedule.prompt, cwd }, runtime);
79
+ if (session.status !== "completed")
80
+ return;
81
+ await applyGuard(schedule, session.sessionId, cwd, runtime);
82
+ await mutateSchedules((current) => current.map((item) => item.id === id ? { ...item, ...guardFields(schedule) } : item));
42
83
  }
43
84
  export async function runDueSchedules(cwd, runtime) {
44
85
  const now = Date.now();
@@ -46,6 +87,7 @@ export async function runDueSchedules(cwd, runtime) {
46
87
  const ran = [];
47
88
  for (const schedule of schedules) {
48
89
  if (!schedule.enabled ||
90
+ !guarded(schedule) ||
49
91
  Date.parse(schedule.nextRunAt) > now ||
50
92
  (schedule.retryAt && Date.parse(schedule.retryAt) > now) ||
51
93
  running.has(schedule.id))
@@ -59,6 +101,7 @@ export async function runDueSchedules(cwd, runtime) {
59
101
  if (session.status !== "completed")
60
102
  throw new Error(`Scheduled run failed: ${session.sessionId}`);
61
103
  schedule.nextRunAt = new Date(now + schedule.intervalMs).toISOString();
104
+ await applyGuard(schedule, session.sessionId, cwd, runtime);
62
105
  ran.push(schedule.id);
63
106
  }
64
107
  finally {
@@ -70,7 +113,13 @@ export async function runDueSchedules(cwd, runtime) {
70
113
  for (const id of ran) {
71
114
  const completed = schedules.find((schedule) => schedule.id === id);
72
115
  if (completed)
73
- await mutateSchedules((current) => current.map((item) => item.id === id ? { ...item, nextRunAt: completed.nextRunAt } : item));
116
+ await mutateSchedules((current) => current.map((item) => item.id === id
117
+ ? {
118
+ ...item,
119
+ nextRunAt: completed.nextRunAt,
120
+ ...guardFields(completed),
121
+ }
122
+ : item));
74
123
  }
75
124
  return ran;
76
125
  }
@@ -78,7 +127,9 @@ export async function runSchedulerWorkerOnce(cwd, runtime) {
78
127
  const schedules = await listSchedules();
79
128
  const ran = [];
80
129
  for (const schedule of schedules) {
81
- if (!schedule.enabled || Date.parse(schedule.nextRunAt) > Date.now())
130
+ if (!schedule.enabled ||
131
+ !guarded(schedule) ||
132
+ Date.parse(schedule.nextRunAt) > Date.now())
82
133
  continue;
83
134
  const lease = leaseFile(schedule.id);
84
135
  const handle = await acquireLease(schedule.id);
@@ -92,6 +143,7 @@ export async function runSchedulerWorkerOnce(cwd, runtime) {
92
143
  schedule.nextRunAt = new Date(Date.now() + schedule.intervalMs).toISOString();
93
144
  schedule.attempts = 0;
94
145
  delete schedule.retryAt;
146
+ await applyGuard(schedule, session.sessionId, cwd, runtime);
95
147
  ran.push(schedule.id);
96
148
  }
97
149
  catch {
@@ -118,6 +170,7 @@ export async function runSchedulerWorkerOnce(cwd, runtime) {
118
170
  ...item,
119
171
  nextRunAt: changed.nextRunAt,
120
172
  attempts: changed.attempts,
173
+ ...(ran.includes(changed.id) ? guardFields(changed) : {}),
121
174
  };
122
175
  if (changed.retryAt)
123
176
  updated.retryAt = changed.retryAt;
@@ -0,0 +1,51 @@
1
+ import { execFile } from "node:child_process";
2
+ import { access } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ // The memory-hygiene checkers (T-322, C1): a path on disk, a URL's HEAD, a repo through the
6
+ // owner's `gh`. Only a definite "not there" (no file, 404/410, no such repo) is drift; anything
7
+ // a check cannot settle (offline, 403, timeout) is unverifiable.
8
+ const TIMEOUT_MS = 10_000;
9
+ const checkPath = async ({ value }) => {
10
+ const resolved = value.startsWith("~/")
11
+ ? path.join(os.homedir(), value.slice(2))
12
+ : value;
13
+ return access(resolved).then(() => "ok", () => "missing");
14
+ };
15
+ const checkUrl = async ({ value }) => {
16
+ const request = (method) => fetch(value, {
17
+ method,
18
+ redirect: "follow",
19
+ signal: AbortSignal.timeout(TIMEOUT_MS),
20
+ headers: { "user-agent": "ocean-hygiene" },
21
+ });
22
+ try {
23
+ let response = await request("HEAD");
24
+ if (response.status === 405)
25
+ response = await request("GET");
26
+ if (response.ok)
27
+ return "ok";
28
+ return response.status === 404 || response.status === 410
29
+ ? "missing"
30
+ : "unknown";
31
+ }
32
+ catch {
33
+ return "unknown";
34
+ }
35
+ };
36
+ const checkRepo = ({ value }) => new Promise((resolve) => {
37
+ execFile("gh", ["repo", "view", value, "--json", "name"], { timeout: TIMEOUT_MS }, (error, _stdout, stderr) => {
38
+ if (!error)
39
+ resolve("ok");
40
+ else
41
+ resolve(/could not resolve to a repository/i.test(String(stderr))
42
+ ? "missing"
43
+ : "unknown");
44
+ });
45
+ });
46
+ export const claimChecker = (claim) => claim.kind === "path"
47
+ ? checkPath(claim)
48
+ : claim.kind === "url"
49
+ ? checkUrl(claim)
50
+ : checkRepo(claim);
51
+ //# sourceMappingURL=claim-checkers.js.map
@@ -0,0 +1,229 @@
1
+ import { spawn } from "node:child_process";
2
+ import { access, mkdir, readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { atomicWrite, withFileLock } from "@ocean/core/shared/fs-utils.js";
5
+ import { KNOWLEDGE_DIR, oceanPath, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
6
+ import { listTaskLoops } from "@ocean/loop/loops/task-loop.js";
7
+ import { hygieneFile } from "@ocean/services/hygiene/hygiene.js";
8
+ import { scorecardFile, searchEvalFile, } from "@ocean/services/scorecard/scorecard.js";
9
+ import { previousScorecard, renderDigest, runUpkeepJobs, scorecardMoves, writeDigest, } from "@ocean/services/upkeep/upkeep.js";
10
+ import { listSchedules } from "../scheduler/local-scheduler.js";
11
+ // Nightly upkeep (T-322): each job is a child `ocean` process with a timeout; the results become
12
+ // the morning digest in 01-daily/digest/. Once a day through `ocean rhythm` (ifDue), and the
13
+ // monthly memory hygiene joins the first run of a month that has no report yet.
14
+ const MINUTE = 60_000;
15
+ const OUTPUT_LIMIT = 4 * 1024 * 1024;
16
+ const stampFile = () => oceanPath(SYSTEM_DIR, "state", "upkeep.json");
17
+ const evalSet = () => oceanPath(KNOWLEDGE_DIR, "evals", "search.jsonl");
18
+ const json = (stdout) => {
19
+ try {
20
+ return JSON.parse(stdout);
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ };
26
+ function nightlyJobs() {
27
+ return [
28
+ {
29
+ id: "doctor",
30
+ args: ["doctor", "--json"],
31
+ timeoutMs: 5 * MINUTE,
32
+ model: null,
33
+ summarize: (stdout) => {
34
+ const findings = json(stdout)?.findings ?? [];
35
+ const count = (severity) => findings.filter((finding) => finding.severity === severity).length;
36
+ return {
37
+ note: `${count("OK")} ok, ${count("WARN")} warn, ${count("ERROR")} error`,
38
+ ok: count("ERROR") === 0,
39
+ };
40
+ },
41
+ },
42
+ {
43
+ id: "telemetry",
44
+ args: ["telemetry", "--yes"],
45
+ timeoutMs: 5 * MINUTE,
46
+ model: null,
47
+ summarize: (stdout) => {
48
+ const findings = json(stdout)?.findings;
49
+ return {
50
+ note: Array.isArray(findings)
51
+ ? `${findings.length} recurring findings`
52
+ : "ok",
53
+ };
54
+ },
55
+ },
56
+ {
57
+ id: "reindex",
58
+ args: ["memory", "reindex"],
59
+ timeoutMs: 20 * MINUTE,
60
+ model: null,
61
+ },
62
+ {
63
+ id: "search-eval",
64
+ args: ["memory", "eval", evalSet(), "--min", "0"],
65
+ timeoutMs: 10 * MINUTE,
66
+ model: null,
67
+ summarize: (stdout) => {
68
+ const result = json(stdout);
69
+ if (typeof result?.recall !== "number")
70
+ return { note: "no eval result", ok: false };
71
+ return {
72
+ note: `hit@${result.k} ${(result.recall * 100).toFixed(0)}%, hit@1 ${(result.hitAt1 * 100).toFixed(0)}%, MRR ${result.mrr.toFixed(2)} over ${result.total} (${result.settings?.mode ?? "?"})`,
73
+ };
74
+ },
75
+ },
76
+ {
77
+ id: "drift",
78
+ args: ["memory", "drift", "--yes"],
79
+ timeoutMs: 5 * MINUTE,
80
+ model: null,
81
+ summarize: (stdout) => {
82
+ const result = json(stdout);
83
+ if (!result)
84
+ return { note: "no result", ok: false };
85
+ return {
86
+ note: result.since
87
+ ? `${result.unrecorded.length} of ${result.records} records changed with no recorded write`
88
+ : `first snapshot of ${result.records} records`,
89
+ };
90
+ },
91
+ },
92
+ {
93
+ id: "curator",
94
+ args: ["curator", "--yes"],
95
+ timeoutMs: 5 * MINUTE,
96
+ model: null,
97
+ summarize: (stdout) => {
98
+ const actions = json(stdout)?.actions ?? [];
99
+ return {
100
+ note: actions.length
101
+ ? actions.map((item) => `${item.action} ${item.key}`).join(", ")
102
+ : "no changes",
103
+ };
104
+ },
105
+ },
106
+ {
107
+ id: "scorecard",
108
+ args: ["scorecard", "--write"],
109
+ timeoutMs: 5 * MINUTE,
110
+ model: null,
111
+ summarize: () => ({ note: "saved" }),
112
+ },
113
+ ];
114
+ }
115
+ function runChild(job) {
116
+ return new Promise((resolve, reject) => {
117
+ const child = spawn(process.execPath, [process.argv[1], ...job.args], {
118
+ cwd: oceanPath(),
119
+ stdio: ["ignore", "pipe", "pipe"],
120
+ env: { ...process.env, OCEAN_NO_PULL_ON_START: "1" },
121
+ });
122
+ let stdout = "";
123
+ let stderr = "";
124
+ const take = (current, chunk) => current.length < OUTPUT_LIMIT
125
+ ? current + chunk.toString("utf8")
126
+ : current;
127
+ child.stdout.on("data", (chunk) => {
128
+ stdout = take(stdout, chunk);
129
+ });
130
+ child.stderr.on("data", (chunk) => {
131
+ stderr = take(stderr, chunk);
132
+ });
133
+ let timedOut = false;
134
+ const timer = setTimeout(() => {
135
+ timedOut = true;
136
+ child.kill("SIGTERM");
137
+ }, job.timeoutMs);
138
+ child.on("error", (error) => {
139
+ clearTimeout(timer);
140
+ reject(error);
141
+ });
142
+ child.on("close", (exitCode) => {
143
+ clearTimeout(timer);
144
+ resolve({ exitCode, stdout, stderr, timedOut });
145
+ });
146
+ });
147
+ }
148
+ const hygieneJob = {
149
+ id: "memory-hygiene",
150
+ args: ["memory", "hygiene", "--yes"],
151
+ timeoutMs: 20 * MINUTE,
152
+ model: null,
153
+ summarize: (stdout) => {
154
+ const counts = json(stdout)?.counts;
155
+ return counts
156
+ ? {
157
+ note: `${counts.verified} verified, ${counts.drifted} drifted, ${counts.unverifiable} unverifiable of ${counts.records}`,
158
+ }
159
+ : { note: "no result", ok: false };
160
+ },
161
+ };
162
+ const exists = (file) => access(file).then(() => true, () => false);
163
+ // Tonight's jobs: the nightly set, plus hygiene when this month has no report yet. Scorecard
164
+ // stays last so it reads what the others wrote.
165
+ export async function upkeepJobs(today) {
166
+ const jobs = nightlyJobs();
167
+ if (await exists(hygieneFile(today.slice(0, 7))))
168
+ return jobs;
169
+ return [...jobs.slice(0, -1), hygieneJob, ...jobs.slice(-1)];
170
+ }
171
+ // Every guarded schedule and loop with its token budget, for the digest's model-calls section.
172
+ async function modelBudgets() {
173
+ const budgets = [];
174
+ for (const schedule of await listSchedules())
175
+ if (schedule.guard)
176
+ budgets.push({
177
+ id: schedule.id,
178
+ kind: "schedule",
179
+ active: schedule.enabled,
180
+ used: schedule.usage?.tokens ?? 0,
181
+ budget: schedule.guard.budgetTokens,
182
+ stopped: schedule.stoppedReason,
183
+ });
184
+ for (const loop of await listTaskLoops())
185
+ if (loop.guard && loop.status === "active")
186
+ budgets.push({
187
+ id: loop.id,
188
+ kind: "loop",
189
+ active: true,
190
+ used: loop.usage?.tokens ?? 0,
191
+ budget: loop.guard.budgetTokens,
192
+ });
193
+ return budgets;
194
+ }
195
+ const readStamp = async () => JSON.parse(await readFile(stampFile(), "utf8").catch(() => "{}"));
196
+ export async function upkeepDoneToday(today) {
197
+ return (await readStamp()).day === today;
198
+ }
199
+ // Runs tonight's jobs and writes the digest; null when ifDue and another run already did today.
200
+ export async function runNightlyUpkeep(options) {
201
+ const { today } = options;
202
+ await mkdir(path.dirname(stampFile()), { recursive: true });
203
+ return withFileLock(stampFile(), async () => {
204
+ // A second caller waited for the lock while the first ran today's upkeep.
205
+ if (options.ifDue && (await upkeepDoneToday(today)))
206
+ return null;
207
+ const results = await runUpkeepJobs(await upkeepJobs(today), async (job) => {
208
+ const outcome = await runChild(job);
209
+ if (job.id === "search-eval" && outcome.exitCode === 0) {
210
+ const result = json(outcome.stdout);
211
+ if (typeof result?.recall === "number")
212
+ await atomicWrite(searchEvalFile(), `${JSON.stringify({ hitAt5: result.recall, k: result.k, at: new Date().toISOString(), settings: result.settings }, null, 2)}\n`);
213
+ }
214
+ return outcome;
215
+ });
216
+ const before = await previousScorecard(today);
217
+ const after = await readFile(scorecardFile(today), "utf8").catch(() => null);
218
+ const digest = await writeDigest(today, renderDigest({
219
+ date: today,
220
+ results,
221
+ moves: scorecardMoves(before, after),
222
+ hasPrevious: before !== null,
223
+ budgets: await modelBudgets().catch(() => []),
224
+ }));
225
+ await atomicWrite(stampFile(), `${JSON.stringify({ day: today }, null, 2)}\n`);
226
+ return { digest, results };
227
+ });
228
+ }
229
+ //# sourceMappingURL=nightly-upkeep.js.map
@@ -95,6 +95,23 @@ export function startBackgroundRhythm() {
95
95
  // the next start runs it
96
96
  }
97
97
  }
98
+ // Scheduled agent runs (T-322): each guarded schedule that is due, at most hourly. Schedules
99
+ // without a guard never run (local-scheduler.ts).
100
+ export function startBackgroundSchedules() {
101
+ if (process.env.OCEAN_NO_PULL_ON_START === "1")
102
+ return;
103
+ try {
104
+ spawn(process.execPath, [process.argv[1], "schedule", "run-due"], {
105
+ detached: true,
106
+ stdio: "ignore",
107
+ })
108
+ .on("error", () => { })
109
+ .unref();
110
+ }
111
+ catch {
112
+ // the next tick runs it
113
+ }
114
+ }
98
115
  const runCommand = (command, args) => promisify(execFile)(command, args);
99
116
  function serviceContext(options) {
100
117
  const home = options.home ?? os.homedir();
@@ -230,9 +247,11 @@ export async function runService(shutdownAfterMs) {
230
247
  const heartbeat = setInterval(() => undefined, 60_000);
231
248
  startBackgroundPull();
232
249
  startBackgroundRhythm();
250
+ startBackgroundSchedules();
233
251
  const dailyPull = setInterval(() => {
234
252
  startBackgroundPull();
235
253
  startBackgroundRhythm();
254
+ startBackgroundSchedules();
236
255
  }, HOUR_MS);
237
256
  startAutoReindex();
238
257
  const autoReindex = setInterval(startAutoReindex, REINDEX_CHECK_MS);
@@ -6,6 +6,7 @@ import { addLesson, effectiveConfidence, listLessons, migrateLegacyLessons, read
6
6
  import { promoteSessionToKnowledge } from "@ocean/brain/memory/session-promotion.js";
7
7
  import { classifyIntent } from "@ocean/context/context/intent-router.js";
8
8
  import { resolveProfileName } from "@ocean/core/domain/profiles/runtime-config.js";
9
+ import { GUARD_FLAGS, parseGuardFlags, } from "@ocean/core/domain/runs/loop-guard.js";
9
10
  import { oceanEnv, oceanPath, oceanRoot, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
10
11
  import { autoRegisterProject, bindProject, createProject, findGitRoot, knownTaskPrefixes, listProjectBindings, migrateProjectBindings, moveProject, PROJECT_CATEGORIES, projectCategory, renameProject, renderProjectIndex, resolveProject, scanProjectManifests, unbindProjectPath, writeProjectIndex, } from "@ocean/core/shared/project-resolution.js";
11
12
  import { claudeSessionEndHook, isSessionEndClient, SESSION_END_CLIENTS, } from "@ocean/loop/hooks/session-end-hook.js";
@@ -57,6 +58,7 @@ import { runCaptureCommand } from "./capture-command.js";
57
58
  import { runClientTestCommand } from "./client-test-command.js";
58
59
  import { runClientsCommand } from "./clients-command.js";
59
60
  import { runContextCommand, runContextCostCommand } from "./context-command.js";
61
+ import { runCuratorCommand } from "./curator-command.js";
60
62
  import { runDailyCommand } from "./daily-command.js";
61
63
  import { runDesktopCommand } from "./desktop-command.js";
62
64
  import { runDistillCommand } from "./distill-command.js";
@@ -88,6 +90,7 @@ import { parseSetupArgs, SETUP_USAGE, setup } from "./setup-command.js";
88
90
  import { runTasksCommand } from "./tasks-command.js";
89
91
  import { runTelemetryCommand } from "./telemetry-command.js";
90
92
  import { runUninstallCommand } from "./uninstall-command.js";
93
+ import { runUpkeepCommand } from "./upkeep-command.js";
91
94
  // brain_search over MCP uses vectors when the local embedder answers (T-307), and full text when
92
95
  // it does not; a working embedder is kept, a failure is retried on the next search.
93
96
  function mcpEmbedder() {
@@ -789,20 +792,28 @@ async function commandSchedule() {
789
792
  if (action === "list")
790
793
  console.log(JSON.stringify(await listSchedules(), null, 2));
791
794
  else if (action === "add") {
792
- const [id, profile, intervalMs, ...prompt] = process.argv.slice(4);
795
+ const { guard, rest } = parseGuardFlags(process.argv.slice(4));
796
+ const [id, profile, intervalMs, ...prompt] = rest;
793
797
  if (!id || !profile || !intervalMs || !prompt.length) {
794
- console.error("Usage: ocean schedule add <id> <profile> <interval-ms> <prompt>");
798
+ console.error(`Usage: ocean schedule add <id> <profile> <interval-ms> ${GUARD_FLAGS} <prompt>`);
795
799
  process.exitCode = 1;
796
800
  }
797
801
  else
798
- await saveSchedule({
799
- id,
800
- profile,
801
- prompt: prompt.join(" "),
802
- intervalMs: Number(intervalMs),
803
- nextRunAt: new Date().toISOString(),
804
- enabled: true,
805
- });
802
+ try {
803
+ await saveSchedule({
804
+ id,
805
+ profile,
806
+ prompt: prompt.join(" "),
807
+ intervalMs: Number(intervalMs),
808
+ nextRunAt: new Date().toISOString(),
809
+ enabled: true,
810
+ guard: guard,
811
+ });
812
+ }
813
+ catch (error) {
814
+ console.error(error instanceof Error ? error.message : String(error));
815
+ process.exitCode = 1;
816
+ }
806
817
  }
807
818
  else if (action === "run-due")
808
819
  console.log(JSON.stringify({ ran: await runDueSchedules(oceanRoot(), defaultAgentRuntime) }, null, 2));
@@ -834,29 +845,38 @@ async function commandLoop() {
834
845
  if (action === "status")
835
846
  console.log(JSON.stringify(await listTaskLoops(), null, 2));
836
847
  else if (action === "start") {
837
- const taskId = process.argv[4];
838
- const profile = process.argv[5] ?? "developer";
848
+ // The prompt is everything after --prompt, so the guard flags come before it.
839
849
  const promptIndex = process.argv.indexOf("--prompt");
850
+ const head = promptIndex >= 0 ? process.argv.slice(0, promptIndex) : process.argv;
851
+ const { guard, rest } = parseGuardFlags(head.slice(4));
852
+ const [taskId, profile = "developer"] = rest.filter((arg, index, all) => !arg.startsWith("--") &&
853
+ !["--interval-ms", "--max-attempts"].includes(all[index - 1] ?? ""));
840
854
  const prompt = promptIndex >= 0 ? process.argv.slice(promptIndex + 1).join(" ") : "";
841
- if (!taskId || !prompt || !process.argv.includes("--approve")) {
842
- console.error("Usage: ocean loop start <task-id> <profile> --prompt <text> --approve [--max-iterations N] [--interval-ms N] [--max-attempts N]");
855
+ if (!taskId || !prompt || !head.includes("--approve")) {
856
+ console.error(`Usage: ocean loop start <task-id> <profile> --approve ${GUARD_FLAGS} [--interval-ms N] [--max-attempts N] --prompt <text>`);
843
857
  process.exitCode = 1;
844
858
  }
845
859
  else {
846
860
  const value = (flag, fallback) => {
847
- const index = process.argv.indexOf(flag);
848
- return index >= 0 ? Number(process.argv[index + 1]) : fallback;
861
+ const index = head.indexOf(flag);
862
+ return index >= 0 ? Number(head[index + 1]) : fallback;
849
863
  };
850
- console.log(JSON.stringify(await startTaskLoop({
851
- taskId,
852
- profile,
853
- prompt,
854
- cwd: oceanRoot(),
855
- approved: true,
856
- maxIterations: value("--max-iterations", 10),
857
- intervalMs: value("--interval-ms", 60_000),
858
- maxAttempts: value("--max-attempts", 2),
859
- }), null, 2));
864
+ try {
865
+ console.log(JSON.stringify(await startTaskLoop({
866
+ taskId,
867
+ profile,
868
+ prompt,
869
+ cwd: oceanRoot(),
870
+ approved: true,
871
+ guard,
872
+ intervalMs: value("--interval-ms", 60_000),
873
+ maxAttempts: value("--max-attempts", 2),
874
+ }), null, 2));
875
+ }
876
+ catch (error) {
877
+ console.error(error instanceof Error ? error.message : String(error));
878
+ process.exitCode = 1;
879
+ }
860
880
  }
861
881
  }
862
882
  else if (action === "worker-once") {
@@ -1305,6 +1325,8 @@ export const commandRegistry = {
1305
1325
  rhythm: () => runRhythmCommand(process.argv.slice(3)),
1306
1326
  telemetry: () => runTelemetryCommand(process.argv.slice(3)),
1307
1327
  scorecard: () => runScorecardCommand(process.argv.slice(3)),
1328
+ upkeep: () => runUpkeepCommand(process.argv.slice(3)),
1329
+ curator: () => runCuratorCommand(process.argv.slice(3)),
1308
1330
  express: () => runExpressCommand(process.argv.slice(3)),
1309
1331
  daily: commandDaily,
1310
1332
  schedule: commandSchedule,
@@ -0,0 +1,21 @@
1
+ import { localDate } from "@ocean/core/shared/local-date.js";
2
+ import { curate, reviewCurated } from "@ocean/services/curator/curator.js";
3
+ const USAGE = "Usage: ocean curator [--yes] | review <lesson:id|skill:name>";
4
+ // `ocean curator [--yes] | review <key>` (T-322): mark lessons and skills stale after 30 days
5
+ // unused (or 90 unreviewed), archive after 90; `review` undoes a mark and stamps last_reviewed.
6
+ export async function runCuratorCommand(args) {
7
+ if (args[0] === "review") {
8
+ if (!args[1])
9
+ throw new Error(USAGE);
10
+ console.log(JSON.stringify(await reviewCurated(args[1], localDate()), null, 2));
11
+ return;
12
+ }
13
+ if (args.some((arg) => arg !== "--yes"))
14
+ throw new Error(USAGE);
15
+ const apply = args.includes("--yes");
16
+ const actions = await curate({ today: localDate(), apply });
17
+ console.log(JSON.stringify({ actions }, null, 2));
18
+ if (!apply)
19
+ console.error("Dry run: pass --yes to apply.");
20
+ }
21
+ //# sourceMappingURL=curator-command.js.map