@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.
- package/README.md +6 -4
- package/dist/application/scheduler/local-scheduler.js +57 -4
- package/dist/application/upkeep/claim-checkers.js +51 -0
- package/dist/application/upkeep/nightly-upkeep.js +229 -0
- package/dist/infrastructure/process/service.js +19 -0
- package/dist/interfaces/cli/command-registry.js +48 -26
- package/dist/interfaces/cli/curator-command.js +21 -0
- package/dist/interfaces/cli/help-command.js +13 -5
- package/dist/interfaces/cli/hygiene-command.js +31 -0
- package/dist/interfaces/cli/memory-command.js +6 -1
- package/dist/interfaces/cli/rhythm-command.js +10 -1
- package/dist/interfaces/cli/scorecard-command.js +11 -2
- package/dist/interfaces/cli/upkeep-command.js +25 -0
- package/node_modules/@ocean/brain/package.json +1 -1
- package/node_modules/@ocean/context/package.json +1 -1
- package/node_modules/@ocean/core/dist/domain/runs/loop-guard.js +61 -0
- package/node_modules/@ocean/core/package.json +1 -1
- package/node_modules/@ocean/loop/dist/loops/guard-runtime.js +67 -0
- package/node_modules/@ocean/loop/dist/loops/task-loop.js +24 -1
- package/node_modules/@ocean/loop/dist/runs/session-tokens.js +30 -0
- package/node_modules/@ocean/loop/package.json +1 -1
- package/node_modules/@ocean/market/package.json +1 -1
- package/node_modules/@ocean/services/dist/curator/curator.js +209 -0
- package/node_modules/@ocean/services/dist/hygiene/hygiene.js +236 -0
- package/node_modules/@ocean/services/dist/scorecard/scorecard.js +43 -34
- package/node_modules/@ocean/services/dist/upkeep/upkeep.js +149 -0
- package/node_modules/@ocean/services/package.json +1 -1
- package/ocean-marketplace.json +34 -34
- package/package.json +7 -7
|
@@ -13,7 +13,7 @@ const commandGroups = [
|
|
|
13
13
|
],
|
|
14
14
|
[
|
|
15
15
|
"Knowledge",
|
|
16
|
-
"memory, pull, desktop, observe, capture, note, brief, interests, distill, harvest, rhythm, telemetry, scorecard, express, handoff, idea, daily, skill, catalog",
|
|
16
|
+
"memory, pull, desktop, observe, capture, note, brief, interests, distill, harvest, rhythm, upkeep, curator, telemetry, scorecard, express, handoff, idea, daily, skill, catalog",
|
|
17
17
|
],
|
|
18
18
|
["Integrations", "obsidian, hook, migrate, layout, env"],
|
|
19
19
|
];
|
|
@@ -52,7 +52,7 @@ export const commandHelp = {
|
|
|
52
52
|
],
|
|
53
53
|
loop: [
|
|
54
54
|
"Start, inspect and stop task loops (repeated agent runs on one task).",
|
|
55
|
-
"ocean loop start <task-id> <profile> --
|
|
55
|
+
"ocean loop start <task-id> <profile> --approve --verify <cmd> --max-runs N --budget-tokens N --no-progress N --escalate inbox [--interval-ms N] [--max-attempts N] --prompt <text>|status|stop <loop-id>|worker-once|worker",
|
|
56
56
|
],
|
|
57
57
|
policy: [
|
|
58
58
|
"List the charter's policies, check them, or print one.",
|
|
@@ -104,7 +104,7 @@ export const commandHelp = {
|
|
|
104
104
|
],
|
|
105
105
|
schedule: [
|
|
106
106
|
"Add, list and run scheduled agent runs.",
|
|
107
|
-
"ocean schedule list|add <id> <profile> <interval-ms> <prompt>|enable|disable|run-due|run-now|worker-once|worker",
|
|
107
|
+
"ocean schedule list|add <id> <profile> <interval-ms> --verify <cmd> --max-runs N --budget-tokens N --no-progress N --escalate inbox <prompt>|enable|disable|run-due|run-now|worker-once|worker",
|
|
108
108
|
],
|
|
109
109
|
client: [
|
|
110
110
|
"Inspect, open, register and sync AI clients.",
|
|
@@ -138,7 +138,7 @@ export const commandHelp = {
|
|
|
138
138
|
],
|
|
139
139
|
memory: [
|
|
140
140
|
"Search, read, review and maintain memory records and the brain index.",
|
|
141
|
-
"ocean memory doctor|sync [--apply]|review [list|approve <id> [--to <path>]|reject <id>]|eval <questions.json|.jsonl> [--k N] [--min R] [--fts]|digest|harvest [--source <id>] [--yes]|import-claude <export-dir> [--yes]|history [path] [--limit N]|audit [--client <name>] [--days N] [--limit N] [--json]|restore <id> [--hash <sha256>]|delete <path> --hash <sha256>|purge [--days N] [--yes]|facts <profile> [key] [value]|facts <profile> delete <key>|reindex [--no-vectors]|search <q> [--project <id>|--all] [--type T] [--since D] [--as-of D] [--fts] [--json]|read <id|path>|neighbors <id|path> [--depth N] [--project <id>|--all]",
|
|
141
|
+
"ocean memory doctor|sync [--apply]|review [list|approve <id> [--to <path>]|reject <id>]|eval <questions.json|.jsonl> [--k N] [--min R] [--fts]|hygiene [--yes]|drift [--yes]|digest|harvest [--source <id>] [--yes]|import-claude <export-dir> [--yes]|history [path] [--limit N]|audit [--client <name>] [--days N] [--limit N] [--json]|restore <id> [--hash <sha256>]|delete <path> --hash <sha256>|purge [--days N] [--yes]|facts <profile> [key] [value]|facts <profile> delete <key>|reindex [--no-vectors]|search <q> [--project <id>|--all] [--type T] [--since D] [--as-of D] [--fts] [--json]|read <id|path>|neighbors <id|path> [--depth N] [--project <id>|--all]",
|
|
142
142
|
],
|
|
143
143
|
pull: [
|
|
144
144
|
"Pull what AI clients hold into Ocean as review candidates; a dry run until --yes.",
|
|
@@ -173,9 +173,17 @@ export const commandHelp = {
|
|
|
173
173
|
"ocean harvest [--date YYYY-MM-DD | --pending] [--yes] | archive [--days N] [--yes] | undo <YYYY-MM-DD>",
|
|
174
174
|
],
|
|
175
175
|
rhythm: [
|
|
176
|
-
"Run the day's rhythm once per period, no model: morning note, harvest, archive, last week's digest, last month's review.",
|
|
176
|
+
"Run the day's rhythm once per period, no model: morning note, harvest, archive, last week's digest, last month's review, then the nightly upkeep.",
|
|
177
177
|
"ocean rhythm [--yes]",
|
|
178
178
|
],
|
|
179
|
+
upkeep: [
|
|
180
|
+
"Run the nightly jobs (doctor, telemetry, reindex, search eval, curator, scorecard), no model, and write the morning digest to 01-daily/digest/.",
|
|
181
|
+
"ocean upkeep [--yes] [--if-due]",
|
|
182
|
+
],
|
|
183
|
+
curator: [
|
|
184
|
+
"Mark lessons and skills stale after 30 days unused (or 90 unreviewed), archive after 90; review undoes a mark.",
|
|
185
|
+
"ocean curator [--yes] | review <lesson:id|skill:name>",
|
|
186
|
+
],
|
|
179
187
|
telemetry: [
|
|
180
188
|
"Find recurring errors and failing providers in recent sessions; propose them as backlog lines.",
|
|
181
189
|
"ocean telemetry [--days N] [--yes]",
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { localDate } from "@ocean/core/shared/local-date.js";
|
|
2
|
+
import { checkDrift, readHygieneHistory, renderHygieneReport, runHygiene, writeHygieneReport, } from "@ocean/services/hygiene/hygiene.js";
|
|
3
|
+
import { claimChecker } from "../../application/upkeep/claim-checkers.js";
|
|
4
|
+
// `ocean memory hygiene [--yes]` and `ocean memory drift [--yes]` (T-322): argument parsing and
|
|
5
|
+
// output around services/hygiene and the checkers in application/upkeep.
|
|
6
|
+
export async function runHygieneCommand(args) {
|
|
7
|
+
if (args.some((arg) => arg !== "--yes"))
|
|
8
|
+
throw new Error("Usage: ocean memory hygiene [--yes]");
|
|
9
|
+
const apply = args.includes("--yes");
|
|
10
|
+
const { counts, records } = await runHygiene({
|
|
11
|
+
today: localDate(),
|
|
12
|
+
apply,
|
|
13
|
+
check: claimChecker,
|
|
14
|
+
});
|
|
15
|
+
const drifted = records.filter((record) => record.verdict === "drifted");
|
|
16
|
+
let report = null;
|
|
17
|
+
if (apply)
|
|
18
|
+
report = await writeHygieneReport(counts.month, renderHygieneReport(counts, records, await readHygieneHistory()));
|
|
19
|
+
console.log(JSON.stringify({ counts, drifted, report }, null, 2));
|
|
20
|
+
if (!apply)
|
|
21
|
+
console.error("Dry run: pass --yes to stamp records and write the report.");
|
|
22
|
+
}
|
|
23
|
+
export async function runDriftCommand(args) {
|
|
24
|
+
if (args.some((arg) => arg !== "--yes"))
|
|
25
|
+
throw new Error("Usage: ocean memory drift [--yes]");
|
|
26
|
+
const result = await checkDrift({ apply: args.includes("--yes") });
|
|
27
|
+
console.log(JSON.stringify(result, null, 2));
|
|
28
|
+
if (!args.includes("--yes"))
|
|
29
|
+
console.error("Dry run: pass --yes to save the snapshot and the result.");
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=hygiene-command.js.map
|
|
@@ -16,6 +16,7 @@ import { isValidProjectId } from "@ocean/core/domain/context/project-id.js";
|
|
|
16
16
|
import { folderProject } from "@ocean/core/shared/project-resolution.js";
|
|
17
17
|
import { defaultBrainIndexPort } from "../../composition/runtime.js";
|
|
18
18
|
import { createOllamaEmbedder } from "../../infrastructure/providers/ollama-embedder.js";
|
|
19
|
+
import { runDriftCommand, runHygieneCommand } from "./hygiene-command.js";
|
|
19
20
|
async function runReindex(args) {
|
|
20
21
|
const noVectors = args.includes("--no-vectors");
|
|
21
22
|
let embedder = null;
|
|
@@ -357,6 +358,10 @@ export async function runMemoryCommand(action, args) {
|
|
|
357
358
|
}
|
|
358
359
|
if (action === "eval")
|
|
359
360
|
return runEval(args);
|
|
361
|
+
if (action === "hygiene")
|
|
362
|
+
return runHygieneCommand(args);
|
|
363
|
+
if (action === "drift")
|
|
364
|
+
return runDriftCommand(args);
|
|
360
365
|
if (action === "archive-retired") {
|
|
361
366
|
// T-314: retired lessons out of the index, into lessons/archive/ (kept).
|
|
362
367
|
const moved = await archiveRetiredLessons({
|
|
@@ -432,7 +437,7 @@ export async function runMemoryCommand(action, args) {
|
|
|
432
437
|
console.log(JSON.stringify({ dryRun: !args.includes("--apply"), stores: result }, null, 2));
|
|
433
438
|
return;
|
|
434
439
|
}
|
|
435
|
-
console.error("Usage: ocean memory doctor|sync [--apply]|review [list|approve <id> [--to <path>]|reject <id>]|eval <questions.json|.jsonl> [--k N] [--min R] [--fts]|digest|harvest [--source <id>] [--yes]|import-claude <export-dir> [--yes]|history [path] [--limit N]|audit [--client <name>] [--days N] [--limit N] [--json]|restore <id> [--hash <sha256>]|delete <path> --hash <sha256>|purge [--days N] [--yes]|facts <profile> [key] [value]|facts <profile> delete <key>|session-facts [on|off]|reindex [--no-vectors]|search <q> [--project <id>|--all] [--type T] [--since D] [--as-of D] [--fts] [--json]|read <id|path>|neighbors <id|path> [--depth N] [--project <id>|--all]");
|
|
440
|
+
console.error("Usage: ocean memory doctor|sync [--apply]|review [list|approve <id> [--to <path>]|reject <id>]|eval <questions.json|.jsonl> [--k N] [--min R] [--fts]|hygiene [--yes]|drift [--yes]|digest|harvest [--source <id>] [--yes]|import-claude <export-dir> [--yes]|history [path] [--limit N]|audit [--client <name>] [--days N] [--limit N] [--json]|restore <id> [--hash <sha256>]|delete <path> --hash <sha256>|purge [--days N] [--yes]|facts <profile> [key] [value]|facts <profile> delete <key>|session-facts [on|off]|reindex [--no-vectors]|search <q> [--project <id>|--all] [--type T] [--since D] [--as-of D] [--fts] [--json]|read <id|path>|neighbors <id|path> [--depth N] [--project <id>|--all]");
|
|
436
441
|
process.exitCode = 1;
|
|
437
442
|
}
|
|
438
443
|
//# sourceMappingURL=memory-command.js.map
|
|
@@ -8,9 +8,11 @@ import { prepareDay } from "@ocean/services/day/day.js";
|
|
|
8
8
|
import { hasBlock, noteFile } from "@ocean/services/day/note.js";
|
|
9
9
|
import { distillWeek, isoWeek, reviewMonth, } from "@ocean/services/distill/distill.js";
|
|
10
10
|
import { archiveHarvested, harvestDay, pendingDays, } from "@ocean/services/harvest/harvest.js";
|
|
11
|
+
import { runUpkeepCommand } from "./upkeep-command.js";
|
|
11
12
|
// `ocean rhythm [--yes]` (T-314): everything the day, week and month need, with no model, each
|
|
12
13
|
// at most once: today's morning note, every day not yet harvested (and today so far), the
|
|
13
|
-
// archive, last week's digest once the week is over, last month's review once the month is over
|
|
14
|
+
// archive, last week's digest once the week is over, last month's review once the month is over,
|
|
15
|
+
// then the nightly upkeep and its morning digest once a day (T-322).
|
|
14
16
|
// The background service runs it at each session start; a run with nothing due is quick.
|
|
15
17
|
const stampFile = () => oceanPath(SYSTEM_DIR, "state", "rhythm.json");
|
|
16
18
|
const previousMonth = (date) => {
|
|
@@ -23,6 +25,13 @@ export async function runRhythmCommand(args) {
|
|
|
23
25
|
await mkdir(path.dirname(stampFile()), { recursive: true });
|
|
24
26
|
// One run at a time: a session start and the hourly service tick can land together.
|
|
25
27
|
await withFileLock(stampFile(), () => rhythm(args));
|
|
28
|
+
// Nightly upkeep (T-322) once a day, outside the rhythm lock: its jobs take minutes. A run that
|
|
29
|
+
// finds another one holding the upkeep lock leaves it to that one.
|
|
30
|
+
if (args.includes("--yes"))
|
|
31
|
+
await runUpkeepCommand(["--yes", "--if-due"]).catch((error) => {
|
|
32
|
+
if (!/still held/.test(String(error)))
|
|
33
|
+
throw error;
|
|
34
|
+
});
|
|
26
35
|
}
|
|
27
36
|
async function rhythm(args) {
|
|
28
37
|
const apply = args.includes("--yes");
|
|
@@ -3,7 +3,8 @@ import { brainIndexPort } from "@ocean/brain/infrastructure/brain/brain-index.js
|
|
|
3
3
|
import { readAudit } from "@ocean/brain/memory/memory-audit.js";
|
|
4
4
|
import { localDate } from "@ocean/core/shared/local-date.js";
|
|
5
5
|
import { openSessionStoreReadOnly } from "@ocean/loop/infrastructure/persistence/session-store.js";
|
|
6
|
-
import {
|
|
6
|
+
import { readDrift, readHygieneHistory, } from "@ocean/services/hygiene/hygiene.js";
|
|
7
|
+
import { readLessonFrontmatter, readSearchEval, readTaskFrontmatter, renderTable, scorecardRows, sessionTokens, writeScorecard, } from "@ocean/services/scorecard/scorecard.js";
|
|
7
8
|
import { clientFindings } from "../../application/clients/clients.js";
|
|
8
9
|
import { CLIENT_ADAPTERS } from "../../application/clients/registry.js";
|
|
9
10
|
import { listSchedules } from "../../application/scheduler/local-scheduler.js";
|
|
@@ -67,10 +68,18 @@ async function collect() {
|
|
|
67
68
|
},
|
|
68
69
|
tasks: await readTaskFrontmatter(),
|
|
69
70
|
search,
|
|
70
|
-
searchEval:
|
|
71
|
+
searchEval: await readSearchEval(),
|
|
71
72
|
schedules: await listSchedules(),
|
|
72
73
|
lessons: await readLessonFrontmatter(),
|
|
73
74
|
tokens,
|
|
75
|
+
hygiene: (await readHygieneHistory()).at(-1) ?? null,
|
|
76
|
+
drift: await readDrift().then((drift) => drift
|
|
77
|
+
? {
|
|
78
|
+
records: drift.records,
|
|
79
|
+
unrecorded: drift.unrecorded.length,
|
|
80
|
+
since: drift.since,
|
|
81
|
+
}
|
|
82
|
+
: null),
|
|
74
83
|
};
|
|
75
84
|
}
|
|
76
85
|
// `ocean scorecard [--json] [--write]` (T-318): Ocean's health numbers from real data; --write
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { localDate } from "@ocean/core/shared/local-date.js";
|
|
2
|
+
import { runNightlyUpkeep, upkeepDoneToday, upkeepJobs, } from "../../application/upkeep/nightly-upkeep.js";
|
|
3
|
+
// `ocean upkeep [--yes] [--if-due]` (T-322): the nightly jobs and the morning digest. `ocean
|
|
4
|
+
// rhythm` runs it with --if-due, so it happens at most once a day; by hand it always runs. A dry
|
|
5
|
+
// run lists tonight's jobs.
|
|
6
|
+
export async function runUpkeepCommand(args) {
|
|
7
|
+
const unknown = args.filter((arg) => !["--yes", "--if-due"].includes(arg));
|
|
8
|
+
if (unknown.length)
|
|
9
|
+
throw new Error("Usage: ocean upkeep [--yes] [--if-due]");
|
|
10
|
+
const today = localDate();
|
|
11
|
+
const ifDue = args.includes("--if-due");
|
|
12
|
+
if (ifDue && (await upkeepDoneToday(today))) {
|
|
13
|
+
console.log(JSON.stringify({ upkeep: "done today" }));
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
if (!args.includes("--yes")) {
|
|
17
|
+
const jobs = await upkeepJobs(today);
|
|
18
|
+
console.log(JSON.stringify({ jobs: jobs.map((job) => `ocean ${job.args.join(" ")}`) }, null, 2));
|
|
19
|
+
console.error("Dry run: pass --yes to run them and write the digest.");
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const ran = await runNightlyUpkeep({ today, ifDue });
|
|
23
|
+
console.log(JSON.stringify(ran ?? { upkeep: "done today" }, null, 2));
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=upkeep-command.js.map
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// The guard every recurring agent run declares (T-322, COG C2 loop engineering): how a run is
|
|
2
|
+
// verified, a hard cap on runs, a token budget, when to stop for lack of progress, and who is
|
|
3
|
+
// told when it stops. A scheduled job or loop without a complete guard is refused at creation.
|
|
4
|
+
export const GUARD_FLAGS = "--verify <cmd> --max-runs N --budget-tokens N --no-progress N --escalate inbox";
|
|
5
|
+
const positiveInt = (value) => typeof value === "number" && Number.isInteger(value) && value > 0;
|
|
6
|
+
// What is missing or invalid; empty when the guard is complete.
|
|
7
|
+
export function guardProblems(guard) {
|
|
8
|
+
const problems = [];
|
|
9
|
+
if (!guard?.verify?.trim())
|
|
10
|
+
problems.push("verify: a verifier command");
|
|
11
|
+
if (!positiveInt(guard?.maxRuns))
|
|
12
|
+
problems.push("max-runs: a hard cap");
|
|
13
|
+
if (!positiveInt(guard?.budgetTokens))
|
|
14
|
+
problems.push("budget-tokens: a token budget");
|
|
15
|
+
if (!positiveInt(guard?.noProgressRuns))
|
|
16
|
+
problems.push("no-progress: a no-progress exit");
|
|
17
|
+
if (guard?.escalate !== "inbox")
|
|
18
|
+
problems.push("escalate: human escalation (inbox)");
|
|
19
|
+
return problems;
|
|
20
|
+
}
|
|
21
|
+
export function assertGuard(guard) {
|
|
22
|
+
const problems = guardProblems(guard);
|
|
23
|
+
if (problems.length)
|
|
24
|
+
throw new Error(`Refused: a recurring agent run must declare ${problems.join("; ")}. Pass ${GUARD_FLAGS}.`);
|
|
25
|
+
}
|
|
26
|
+
// Why the guard stops the job now, or null to keep going.
|
|
27
|
+
export function guardStop(guard, usage) {
|
|
28
|
+
if (usage.runs >= guard.maxRuns)
|
|
29
|
+
return `hard cap reached: ${usage.runs} of ${guard.maxRuns} runs`;
|
|
30
|
+
if (usage.tokens >= guard.budgetTokens)
|
|
31
|
+
return `token budget used: ${usage.tokens} of ${guard.budgetTokens}`;
|
|
32
|
+
if (usage.noProgress >= guard.noProgressRuns)
|
|
33
|
+
return `no verified progress in ${usage.noProgress} runs in a row`;
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
// Parses the guard flags out of an argument list; returns the guard and the remaining arguments.
|
|
37
|
+
export function parseGuardFlags(args) {
|
|
38
|
+
const guard = {};
|
|
39
|
+
const rest = [];
|
|
40
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
41
|
+
const flag = args[index];
|
|
42
|
+
const value = args[index + 1];
|
|
43
|
+
if (flag === "--verify")
|
|
44
|
+
guard.verify = value;
|
|
45
|
+
else if (flag === "--max-runs")
|
|
46
|
+
guard.maxRuns = Number(value);
|
|
47
|
+
else if (flag === "--budget-tokens")
|
|
48
|
+
guard.budgetTokens = Number(value);
|
|
49
|
+
else if (flag === "--no-progress")
|
|
50
|
+
guard.noProgressRuns = Number(value);
|
|
51
|
+
else if (flag === "--escalate")
|
|
52
|
+
guard.escalate = value;
|
|
53
|
+
else {
|
|
54
|
+
rest.push(flag);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
index += 1;
|
|
58
|
+
}
|
|
59
|
+
return { guard, rest };
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=loop-guard.js.map
|
|
@@ -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(
|
|
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
|