@amoree-code/ocean 2.7.0 → 2.9.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/dist/infrastructure/providers/task-reviewer.js +35 -0
- package/dist/interfaces/cli/help-command.js +1 -1
- package/dist/interfaces/cli/memory-command.js +36 -10
- package/dist/interfaces/cli/operate-command.js +2 -0
- package/dist/interfaces/cli/tasks-command.js +18 -3
- package/node_modules/@ocean/brain/dist/brain/brain-eval.js +45 -9
- package/node_modules/@ocean/brain/dist/brain/brain-markdown.js +10 -1
- package/node_modules/@ocean/brain/dist/brain/brain-reindex.js +4 -1
- package/node_modules/@ocean/brain/dist/brain/brain-service.js +69 -8
- package/node_modules/@ocean/brain/dist/infrastructure/brain/brain-index.js +5 -3
- package/node_modules/@ocean/brain/dist/memory/lesson-learning.js +35 -3
- package/node_modules/@ocean/brain/dist/memory/session-promotion.js +2 -1
- 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/ports/brain-index-port.js +3 -2
- package/node_modules/@ocean/core/package.json +1 -1
- package/node_modules/@ocean/loop/dist/infrastructure/persistence/session-store.js +15 -0
- package/node_modules/@ocean/loop/dist/operations/task-operations.js +6 -1
- package/node_modules/@ocean/loop/dist/tasks/archive-tasks.js +11 -9
- package/node_modules/@ocean/loop/dist/tasks/claim-task.js +11 -3
- package/node_modules/@ocean/loop/dist/tasks/task-git.js +28 -0
- package/node_modules/@ocean/loop/dist/tasks/task-verification.js +302 -0
- package/node_modules/@ocean/loop/dist/tasks/verify-task.js +69 -21
- package/node_modules/@ocean/loop/package.json +1 -1
- package/node_modules/@ocean/market/package.json +1 -1
- package/node_modules/@ocean/services/dist/infrastructure/mcp/ocean-server.js +18 -0
- package/node_modules/@ocean/services/package.json +1 -1
- package/ocean-marketplace.json +34 -34
- package/package.json +7 -7
- package/templates/workspace/charter/policies/contracts/task.md +44 -1
- package/templates/workspace/charter/policies/task.md +5 -1
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { oceanEnv, oceanEnvPair, oceanRoot } from "@ocean/core/shared/paths.js";
|
|
2
|
+
import { resolveOriginalExecutable } from "./provider-registry.js";
|
|
3
|
+
import { runProvider } from "./providers.js";
|
|
4
|
+
import { FACTS_CALL_ENV, finalText } from "./session-facts-completer.js";
|
|
5
|
+
// The optional independent review of `ocean tasks verify` (T-320 F2): read-only, on the
|
|
6
|
+
// cheapest model, run only for a task that sets `review: agent`. It reads the workspace (to
|
|
7
|
+
// check that cited files exist) and never writes. OCEAN_TASK_REVIEW_MODEL overrides the model.
|
|
8
|
+
const PROVIDER = "claude";
|
|
9
|
+
const DEFAULT_MODEL = "haiku";
|
|
10
|
+
const TIMEOUT_MS = 180_000;
|
|
11
|
+
const REVIEW_SYSTEM_PROMPT = "You are a strict, read-only verifier. You never edit files or run commands that change state. You check that claims point to evidence and finish with one verdict line.";
|
|
12
|
+
export function taskReviewer(run = runProvider) {
|
|
13
|
+
try {
|
|
14
|
+
resolveOriginalExecutable(PROVIDER);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
const model = oceanEnv("TASK_REVIEW_MODEL") ?? DEFAULT_MODEL;
|
|
20
|
+
return async (prompt) => {
|
|
21
|
+
const result = await run({
|
|
22
|
+
provider: PROVIDER,
|
|
23
|
+
prompt,
|
|
24
|
+
cwd: oceanRoot(),
|
|
25
|
+
readOnly: true,
|
|
26
|
+
bare: { systemPrompt: REVIEW_SYSTEM_PROMPT },
|
|
27
|
+
model,
|
|
28
|
+
timeoutMs: TIMEOUT_MS,
|
|
29
|
+
// The same flag the fact-capture call carries: its hooks see it and record no session.
|
|
30
|
+
env: oceanEnvPair(FACTS_CALL_ENV, "1"),
|
|
31
|
+
});
|
|
32
|
+
return result.exitCode === 0 ? finalText(result.events) : null;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=task-reviewer.js.map
|
|
@@ -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> [--k N] [--min R]|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] [--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]|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.",
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
|
-
import { evaluateRecall, } from "@ocean/brain/brain/brain-eval.js";
|
|
2
|
+
import { evaluateRecall, parseEvalCases, } from "@ocean/brain/brain/brain-eval.js";
|
|
3
3
|
import { brainIndexPath, computeCorpusHash, reindexBrain, } from "@ocean/brain/brain/brain-reindex.js";
|
|
4
4
|
import { brainNeighbors, brainRead, brainSearch, } from "@ocean/brain/brain/brain-service.js";
|
|
5
5
|
import { migrateBrainDumps } from "@ocean/brain/memory/brain-dump.js";
|
|
@@ -35,7 +35,9 @@ async function runReindex(args) {
|
|
|
35
35
|
});
|
|
36
36
|
console.log(JSON.stringify(result, null, 2));
|
|
37
37
|
}
|
|
38
|
-
const searchUsage = "Usage: ocean memory search <query> [--project <id> | --all] [--json]";
|
|
38
|
+
const searchUsage = "Usage: ocean memory search <query> [--project <id> | --all] [--type <type>]... [--since YYYY-MM-DD] [--as-of YYYY-MM-DD] [--fts] [--json]";
|
|
39
|
+
const SEARCH_VALUE_FLAGS = new Set(["--type", "--since", "--as-of"]);
|
|
40
|
+
const isDay = (value) => value === undefined || /^\d{4}-\d{2}-\d{2}$/.test(value);
|
|
39
41
|
const neighborsUsage = "Usage: ocean memory neighbors <id|path> [--depth N] [--project <id> | --all]";
|
|
40
42
|
// --project <id> / --all, shared by search and neighbors. Default: the cwd's project plus
|
|
41
43
|
// global records; --all is the explicit unscoped view. null means the flags are malformed.
|
|
@@ -66,10 +68,23 @@ async function scopeFrom(flags) {
|
|
|
66
68
|
async function runSearch(args) {
|
|
67
69
|
const flags = parseScopeFlags(args);
|
|
68
70
|
const json = args.includes("--json");
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
71
|
+
const rest = flags?.rest ?? [];
|
|
72
|
+
const words = [];
|
|
73
|
+
const types = [];
|
|
74
|
+
for (let index = 0; index < rest.length; index += 1) {
|
|
75
|
+
const arg = rest[index];
|
|
76
|
+
if (SEARCH_VALUE_FLAGS.has(arg)) {
|
|
77
|
+
if (arg === "--type" && rest[index + 1])
|
|
78
|
+
types.push(rest[index + 1]);
|
|
79
|
+
index += 1;
|
|
80
|
+
}
|
|
81
|
+
else if (!arg.startsWith("--"))
|
|
82
|
+
words.push(arg);
|
|
83
|
+
}
|
|
84
|
+
const query = words.join(" ");
|
|
85
|
+
const since = flagValue(rest, "--since");
|
|
86
|
+
const asOf = flagValue(rest, "--as-of");
|
|
87
|
+
if (!flags || !query || !isDay(since) || !isDay(asOf)) {
|
|
73
88
|
console.error(searchUsage);
|
|
74
89
|
process.exitCode = 1;
|
|
75
90
|
return;
|
|
@@ -78,7 +93,14 @@ async function runSearch(args) {
|
|
|
78
93
|
const result = await brainSearch({
|
|
79
94
|
query,
|
|
80
95
|
scope: await scopeFrom(flags),
|
|
96
|
+
types: types.length ? types : undefined,
|
|
97
|
+
since,
|
|
98
|
+
asOf,
|
|
81
99
|
indexPort: defaultBrainIndexPort,
|
|
100
|
+
// Hybrid whenever the local embedder answers (T-321); keyword-only otherwise, or with --fts.
|
|
101
|
+
embedder: rest.includes("--fts")
|
|
102
|
+
? null
|
|
103
|
+
: await createOllamaEmbedder().catch(() => null),
|
|
82
104
|
});
|
|
83
105
|
console.log(json ? JSON.stringify(result) : JSON.stringify(result, null, 2));
|
|
84
106
|
}
|
|
@@ -267,14 +289,18 @@ async function runReview(args) {
|
|
|
267
289
|
async function runEval(args) {
|
|
268
290
|
const file = args.find((arg, index) => !arg.startsWith("--") && !args[index - 1]?.startsWith("--"));
|
|
269
291
|
if (!file) {
|
|
270
|
-
console.error("Usage: ocean memory eval <questions.json> [--k N] [--min 0.9] [--
|
|
292
|
+
console.error("Usage: ocean memory eval <questions.json|.jsonl> [--k N] [--min 0.9] [--fts]");
|
|
271
293
|
process.exitCode = 1;
|
|
272
294
|
return;
|
|
273
295
|
}
|
|
274
|
-
const cases =
|
|
296
|
+
const cases = parseEvalCases(await readFile(file, "utf8"));
|
|
297
|
+
// Same embedder rule as search: vectors when the local model answers, unless --fts pins keyword-only.
|
|
298
|
+
const embedder = args.includes("--fts")
|
|
299
|
+
? null
|
|
300
|
+
: await createOllamaEmbedder().catch(() => null);
|
|
275
301
|
const result = await evaluateRecall(cases, {
|
|
276
302
|
indexPort: defaultBrainIndexPort,
|
|
277
|
-
embedder
|
|
303
|
+
embedder,
|
|
278
304
|
k: Number(flagValue(args, "--k") ?? 5),
|
|
279
305
|
});
|
|
280
306
|
console.log(JSON.stringify(result, null, 2));
|
|
@@ -406,7 +432,7 @@ export async function runMemoryCommand(action, args) {
|
|
|
406
432
|
console.log(JSON.stringify({ dryRun: !args.includes("--apply"), stores: result }, null, 2));
|
|
407
433
|
return;
|
|
408
434
|
}
|
|
409
|
-
console.error("Usage: ocean memory doctor|sync [--apply]|review [list|approve <id> [--to <path>]|reject <id>]|eval <questions.json> [--k N] [--min R]|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] [--json]|read <id|path>|neighbors <id|path> [--depth N] [--project <id>|--all]");
|
|
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]");
|
|
410
436
|
process.exitCode = 1;
|
|
411
437
|
}
|
|
412
438
|
//# sourceMappingURL=memory-command.js.map
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { classifyIntent } from "@ocean/context/context/intent-router.js";
|
|
2
2
|
import { oceanRoot } from "@ocean/core/shared/paths.js";
|
|
3
3
|
import { knownTaskPrefixes } from "@ocean/core/shared/project-resolution.js";
|
|
4
|
+
import { openSessionStore } from "@ocean/loop/infrastructure/persistence/session-store.js";
|
|
4
5
|
import { operationForIntent, } from "@ocean/loop/operations/operation-contract.js";
|
|
5
6
|
import { runOperation } from "@ocean/loop/operations/record-operations.js";
|
|
6
7
|
import { guardedRunOperation, } from "@ocean/loop/operations/write-guard.js";
|
|
@@ -40,6 +41,7 @@ export async function runOperateCommand(text) {
|
|
|
40
41
|
query: text,
|
|
41
42
|
approval: approval ?? undefined,
|
|
42
43
|
indexPort: defaultBrainIndexPort,
|
|
44
|
+
openStore: openSessionStore,
|
|
43
45
|
}));
|
|
44
46
|
console.log(JSON.stringify({
|
|
45
47
|
classification,
|
|
@@ -5,14 +5,16 @@ import { promisify } from "node:util";
|
|
|
5
5
|
import { enginePath, oceanPath, projectDir, resolveWithin, WORKSPACE_PROJECT_ID, } from "@ocean/core/shared/paths.js";
|
|
6
6
|
import { folderProject, projectsWithTasks, } from "@ocean/core/shared/project-resolution.js";
|
|
7
7
|
import { resolveTaskReference } from "@ocean/core/shared/task-reference.js";
|
|
8
|
+
import { openSessionStore } from "@ocean/loop/infrastructure/persistence/session-store.js";
|
|
8
9
|
import { archiveDoneTasks, completeTask, } from "@ocean/loop/tasks/archive-tasks.js";
|
|
9
10
|
import { checkpointTask } from "@ocean/loop/tasks/checkpoint-task.js";
|
|
10
11
|
import { claimTask, releaseTask } from "@ocean/loop/tasks/claim-task.js";
|
|
11
12
|
import { listTasks, listTasksForFolder, } from "@ocean/loop/tasks/list-tasks.js";
|
|
12
13
|
import { newTask } from "@ocean/loop/tasks/new-task.js";
|
|
13
14
|
import { renumberTasks } from "@ocean/loop/tasks/renumber-tasks.js";
|
|
15
|
+
import { verifyAndRecord } from "@ocean/loop/tasks/task-verification.js";
|
|
14
16
|
import { verificationReadiness } from "@ocean/loop/tasks/verification-readiness.js";
|
|
15
|
-
import {
|
|
17
|
+
import { taskReviewer } from "../../infrastructure/providers/task-reviewer.js";
|
|
16
18
|
const execFile = promisify(execFileCallback);
|
|
17
19
|
// Re-exported for existing importers (daily/context commands, tests). The
|
|
18
20
|
// implementation and the MCP server both live in the application layer now.
|
|
@@ -32,6 +34,15 @@ async function liveTask(id, explicitProject, cwdProject) {
|
|
|
32
34
|
root: resolveWithin(oceanPath(projectDir(location.projectId)), "tasks"),
|
|
33
35
|
};
|
|
34
36
|
}
|
|
37
|
+
// `tasks verify` and `tasks complete` record their verdict on the task and its sessions (T-320).
|
|
38
|
+
// The model review is built only for a task that opted in, so a plain verify never resolves a
|
|
39
|
+
// provider.
|
|
40
|
+
function recordedVerification(id, root) {
|
|
41
|
+
return verifyAndRecord(id, root, {
|
|
42
|
+
openStore: openSessionStore,
|
|
43
|
+
reviewer: taskReviewer,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
35
46
|
// `ocean tasks list --pretty`: one aligned row per task, for a person rather than a tool.
|
|
36
47
|
function taskTable(tasks) {
|
|
37
48
|
if (!tasks.length)
|
|
@@ -165,8 +176,10 @@ export async function runTasksCommand(action, args) {
|
|
|
165
176
|
return;
|
|
166
177
|
}
|
|
167
178
|
const task = await liveTask(id, explicitProject, cwdProject);
|
|
168
|
-
const outcome = await
|
|
179
|
+
const outcome = await recordedVerification(task.id, task.root);
|
|
169
180
|
console.log(JSON.stringify(outcome, null, 2));
|
|
181
|
+
if (outcome.recordError)
|
|
182
|
+
console.error(`warning: evidence not recorded: ${outcome.recordError}`);
|
|
170
183
|
if (!outcome.passed)
|
|
171
184
|
process.exitCode = 1;
|
|
172
185
|
return;
|
|
@@ -185,7 +198,9 @@ export async function runTasksCommand(action, args) {
|
|
|
185
198
|
}
|
|
186
199
|
try {
|
|
187
200
|
const task = await liveTask(id, explicitProject, cwdProject);
|
|
188
|
-
console.log(JSON.stringify(await completeTask(task.id, task.root
|
|
201
|
+
console.log(JSON.stringify(await completeTask(task.id, task.root, {
|
|
202
|
+
verify: recordedVerification,
|
|
203
|
+
}), null, 2));
|
|
189
204
|
}
|
|
190
205
|
catch (error) {
|
|
191
206
|
console.error(error instanceof Error ? error.message : String(error));
|
|
@@ -1,28 +1,64 @@
|
|
|
1
1
|
import { brainSearch } from "./brain-service.js";
|
|
2
|
+
// MRR looks past k so a near miss at rank 6–10 still counts for something.
|
|
3
|
+
const MRR_DEPTH = 10;
|
|
4
|
+
// A JSON array, or JSON Lines (one case per line, blank lines ignored).
|
|
5
|
+
export function parseEvalCases(text) {
|
|
6
|
+
const trimmed = text.trim();
|
|
7
|
+
if (trimmed.startsWith("["))
|
|
8
|
+
return JSON.parse(trimmed);
|
|
9
|
+
return trimmed
|
|
10
|
+
.split("\n")
|
|
11
|
+
.map((line) => line.trim())
|
|
12
|
+
.filter(Boolean)
|
|
13
|
+
.map((line) => JSON.parse(line));
|
|
14
|
+
}
|
|
2
15
|
export async function evaluateRecall(cases, options) {
|
|
3
16
|
const k = options.k ?? 5;
|
|
17
|
+
const depth = Math.max(k, MRR_DEPTH);
|
|
4
18
|
const misses = [];
|
|
19
|
+
let hitsAt1 = 0;
|
|
20
|
+
let reciprocalSum = 0;
|
|
21
|
+
let hybrid = cases.length > 0;
|
|
5
22
|
for (const item of cases) {
|
|
6
23
|
const expect = [item.expect].flat();
|
|
7
|
-
const { results } = await brainSearch({
|
|
24
|
+
const { results, mode } = await brainSearch({
|
|
8
25
|
query: item.question,
|
|
9
|
-
limit:
|
|
26
|
+
limit: depth,
|
|
10
27
|
root: options.root,
|
|
11
28
|
embedder: options.embedder ?? null,
|
|
12
29
|
indexPort: options.indexPort,
|
|
13
30
|
scope: item.project === undefined ? undefined : { project: item.project },
|
|
14
31
|
});
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
32
|
+
if (mode !== "hybrid")
|
|
33
|
+
hybrid = false;
|
|
34
|
+
const rank = results.findIndex((hit) => expect.includes(hit.path) || expect.includes(hit.file)) + 1;
|
|
35
|
+
if (rank === 1)
|
|
36
|
+
hitsAt1 += 1;
|
|
37
|
+
if (rank > 0)
|
|
38
|
+
reciprocalSum += 1 / rank;
|
|
39
|
+
if (rank === 0 || rank > k)
|
|
40
|
+
misses.push({
|
|
41
|
+
question: item.question,
|
|
42
|
+
expect,
|
|
43
|
+
got: results.slice(0, k).map((hit) => hit.file),
|
|
44
|
+
});
|
|
19
45
|
}
|
|
20
|
-
const
|
|
46
|
+
const total = cases.length;
|
|
47
|
+
const hits = total - misses.length;
|
|
48
|
+
const ratio = (value) => total ? Math.round((value / total) * 1000) / 1000 : 0;
|
|
21
49
|
return {
|
|
50
|
+
settings: {
|
|
51
|
+
mode: hybrid ? "hybrid" : "fts",
|
|
52
|
+
embedder: hybrid ? (options.embedder?.model ?? null) : null,
|
|
53
|
+
k,
|
|
54
|
+
depth,
|
|
55
|
+
},
|
|
22
56
|
k,
|
|
23
|
-
total
|
|
57
|
+
total,
|
|
24
58
|
hits,
|
|
25
|
-
recall:
|
|
59
|
+
recall: ratio(hits),
|
|
60
|
+
hitAt1: ratio(hitsAt1),
|
|
61
|
+
mrr: ratio(reciprocalSum),
|
|
26
62
|
misses,
|
|
27
63
|
};
|
|
28
64
|
}
|
|
@@ -117,7 +117,16 @@ export function normalizeRecord(relPath, rawSource) {
|
|
|
117
117
|
? "defaulted"
|
|
118
118
|
: "declared",
|
|
119
119
|
};
|
|
120
|
-
return {
|
|
120
|
+
return {
|
|
121
|
+
record,
|
|
122
|
+
conformance,
|
|
123
|
+
body,
|
|
124
|
+
rawScope: scopeField.value,
|
|
125
|
+
validity: {
|
|
126
|
+
validFrom: fields.valid_from || null,
|
|
127
|
+
supersededBy: fields.superseded_by || null,
|
|
128
|
+
},
|
|
129
|
+
};
|
|
121
130
|
}
|
|
122
131
|
// Extracts `[[target]]`, `[[target|alias]]`, `[[target#heading]]`, ignoring fenced code
|
|
123
132
|
// blocks (``` ... ```) so a documentation example is never mistaken for a real link.
|
|
@@ -119,7 +119,7 @@ export async function reindexBrain(options) {
|
|
|
119
119
|
// A retired record (a superseded lesson or decision) stays on disk but out of search (T-314).
|
|
120
120
|
if (/^status:\s*["']?retired["']?\s*$/m.test(source.split(/\r?\n---/, 1)[0]))
|
|
121
121
|
continue;
|
|
122
|
-
const { record, conformance, body, rawScope } = normalizeRecord(relative, source);
|
|
122
|
+
const { record, conformance, body, rawScope, validity } = normalizeRecord(relative, source);
|
|
123
123
|
const links = extractWikilinks(body).map((link) => ({
|
|
124
124
|
targetRaw: link.target,
|
|
125
125
|
heading: link.heading,
|
|
@@ -131,6 +131,7 @@ export async function reindexBrain(options) {
|
|
|
131
131
|
record,
|
|
132
132
|
conformance,
|
|
133
133
|
rawScope,
|
|
134
|
+
validity,
|
|
134
135
|
body,
|
|
135
136
|
contentHash: createHash("sha256").update(source).digest("hex"),
|
|
136
137
|
bytes: Buffer.byteLength(source, "utf8"),
|
|
@@ -192,6 +193,8 @@ export async function reindexBrain(options) {
|
|
|
192
193
|
created: doc.record.created,
|
|
193
194
|
updated: doc.record.updated,
|
|
194
195
|
lastConfirmedAt: doc.record.lastConfirmedAt,
|
|
196
|
+
validFrom: doc.validity.validFrom,
|
|
197
|
+
supersededBy: doc.validity.supersededBy,
|
|
195
198
|
contentHash: doc.contentHash,
|
|
196
199
|
bytes: doc.bytes,
|
|
197
200
|
conformance: doc.conformance,
|
|
@@ -11,12 +11,60 @@ export class BrainIndexStaleError extends Error {
|
|
|
11
11
|
}
|
|
12
12
|
function assertScoped(reader) {
|
|
13
13
|
if (reader.meta.schemaVersion !== BRAIN_INDEX_SCHEMA_VERSION)
|
|
14
|
-
throw new BrainIndexStaleError(`brain index schema ${reader.meta.schemaVersion}
|
|
14
|
+
throw new BrainIndexStaleError(`brain index schema ${reader.meta.schemaVersion} is older than ${BRAIN_INDEX_SCHEMA_VERSION} — run \`ocean memory reindex\``);
|
|
15
15
|
}
|
|
16
16
|
const RRF_K = 60;
|
|
17
17
|
// The owner's own notes outrank what agents wrote on the same question (T-314).
|
|
18
18
|
const HUMAN_BOOST = 1.5;
|
|
19
19
|
const isHumanNote = (storePath) => storePath.startsWith("notes/");
|
|
20
|
+
// Rank adjustments (T-321), multiplied into the fused score. RRF scores sit close together, so
|
|
21
|
+
// these are nudges, not overrides. Tuned on the owner's 40-question eval (hybrid hit@5 0.825 →
|
|
22
|
+
// 0.90): a recency boost was tried and lowered both modes, so recency is the `since` filter only.
|
|
23
|
+
const RANK = {
|
|
24
|
+
decision: 1.05, // a decision answers "what did we decide" better than the talk around it
|
|
25
|
+
session: 0.6, // a raw session log loses to the curated record distilled from it
|
|
26
|
+
lowConfidence: 0.8, // confidence: low (COG memory hygiene, C1)
|
|
27
|
+
unverified: 0.9, // last confirmed more than STALE_DAYS ago
|
|
28
|
+
superseded: 0.5, // replaced by a newer record; still findable, never first
|
|
29
|
+
};
|
|
30
|
+
const STALE_DAYS = 180;
|
|
31
|
+
const DAY_MS = 86_400_000;
|
|
32
|
+
const text = (value) => typeof value === "string" && value ? value : null;
|
|
33
|
+
// Dates in frontmatter are YYYY-MM-DD, possibly with a time; the day is what is compared.
|
|
34
|
+
const dayOf = (value) => text(value)?.match(/^\d{4}-\d{2}-\d{2}/)?.[0] ?? null;
|
|
35
|
+
const daysBetween = (from, to) => (to.getTime() - Date.parse(`${from}T00:00:00Z`)) / DAY_MS;
|
|
36
|
+
const docDate = (doc) => dayOf(doc.updated) ?? dayOf(doc.last_confirmed_at) ?? dayOf(doc.created);
|
|
37
|
+
// When a record starts to hold: its declared valid_from, else when it was written.
|
|
38
|
+
const startOf = (doc) => dayOf(doc.valid_from) ?? dayOf(doc.created) ?? dayOf(doc.updated);
|
|
39
|
+
// Whether the fact a record states held on `asOf`: it had started, and whatever replaced it had
|
|
40
|
+
// not. A successor with no date, or one the index cannot resolve, counts as already in force.
|
|
41
|
+
function validOn(doc, asOf, successor) {
|
|
42
|
+
const start = startOf(doc);
|
|
43
|
+
if (start && start > asOf)
|
|
44
|
+
return false;
|
|
45
|
+
const replacedBy = text(doc.superseded_by);
|
|
46
|
+
if (!replacedBy)
|
|
47
|
+
return true;
|
|
48
|
+
const next = successor(replacedBy);
|
|
49
|
+
const nextStart = next ? startOf(next) : null;
|
|
50
|
+
return nextStart !== null && nextStart > asOf;
|
|
51
|
+
}
|
|
52
|
+
function rankFactor(doc, now, asOf) {
|
|
53
|
+
let factor = isHumanNote(String(doc.path ?? "")) ? HUMAN_BOOST : 1;
|
|
54
|
+
if (doc.type === "decision")
|
|
55
|
+
factor *= RANK.decision;
|
|
56
|
+
if (doc.type === "session")
|
|
57
|
+
factor *= RANK.session;
|
|
58
|
+
if (String(doc.confidence).toLowerCase() === "low")
|
|
59
|
+
factor *= RANK.lowConfidence;
|
|
60
|
+
const confirmed = dayOf(doc.last_confirmed_at);
|
|
61
|
+
if (confirmed && daysBetween(confirmed, now) > STALE_DAYS)
|
|
62
|
+
factor *= RANK.unverified;
|
|
63
|
+
// As of a past date the filter has already removed what was not yet replaced then.
|
|
64
|
+
if (!asOf && text(doc.superseded_by))
|
|
65
|
+
factor *= RANK.superseded;
|
|
66
|
+
return factor;
|
|
67
|
+
}
|
|
20
68
|
function snippetOf(text, maxLen = 240) {
|
|
21
69
|
const trimmed = text.trim().replace(/\s+/g, " ");
|
|
22
70
|
return trimmed.length > maxLen ? `${trimmed.slice(0, maxLen - 1)}…` : trimmed;
|
|
@@ -98,14 +146,18 @@ export async function brainSearch(options) {
|
|
|
98
146
|
});
|
|
99
147
|
}
|
|
100
148
|
}
|
|
149
|
+
const now = options.now ?? new Date();
|
|
150
|
+
const successor = (ref) => reader.getDocByIdOrPath(ref) ??
|
|
151
|
+
(ref.endsWith(".md") ? undefined : reader.getDocByIdOrPath(`${ref}.md`));
|
|
101
152
|
const ranked = [...byDoc.entries()]
|
|
102
|
-
.map(([docId, entry]) =>
|
|
103
|
-
docId
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
: entry.score,
|
|
108
|
-
|
|
153
|
+
.map(([docId, entry]) => {
|
|
154
|
+
const doc = reader.getDoc(docId);
|
|
155
|
+
return {
|
|
156
|
+
docId,
|
|
157
|
+
...entry,
|
|
158
|
+
score: doc ? entry.score * rankFactor(doc, now, options.asOf) : 0,
|
|
159
|
+
};
|
|
160
|
+
})
|
|
109
161
|
.sort((a, b) => b.score - a.score || a.docId - b.docId);
|
|
110
162
|
const results = [];
|
|
111
163
|
for (const item of ranked) {
|
|
@@ -117,6 +169,13 @@ export async function brainSearch(options) {
|
|
|
117
169
|
continue;
|
|
118
170
|
if (options.types?.length && !options.types.includes(String(doc.type)))
|
|
119
171
|
continue;
|
|
172
|
+
if (options.since) {
|
|
173
|
+
const dated = docDate(doc);
|
|
174
|
+
if (!dated || dated < options.since)
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (options.asOf && !validOn(doc, options.asOf, successor))
|
|
178
|
+
continue;
|
|
120
179
|
// Backstop for hits the SQL filter never saw (vector hits are not scope-filtered).
|
|
121
180
|
if (options.scope &&
|
|
122
181
|
!scopeVisible(String(doc.scope), options.scope.project))
|
|
@@ -133,6 +192,8 @@ export async function brainSearch(options) {
|
|
|
133
192
|
scope: String(doc.scope ?? "global"),
|
|
134
193
|
confidence: String(doc.confidence),
|
|
135
194
|
lastConfirmedAt: doc.last_confirmed_at ?? null,
|
|
195
|
+
validFrom: text(doc.valid_from),
|
|
196
|
+
supersededBy: text(doc.superseded_by),
|
|
136
197
|
heading: chunk ? (chunk.heading ?? null) : null,
|
|
137
198
|
snippet: chunk ? snippetOf(String(chunk.text)) : "",
|
|
138
199
|
score: Math.round(item.score * 1_000_000) / 1_000_000,
|
|
@@ -37,6 +37,8 @@ function createSchema(db, withVectors, dims) {
|
|
|
37
37
|
created TEXT,
|
|
38
38
|
updated TEXT,
|
|
39
39
|
last_confirmed_at TEXT,
|
|
40
|
+
valid_from TEXT,
|
|
41
|
+
superseded_by TEXT,
|
|
40
42
|
content_hash TEXT NOT NULL,
|
|
41
43
|
bytes INTEGER NOT NULL,
|
|
42
44
|
conformance_json TEXT NOT NULL
|
|
@@ -71,8 +73,8 @@ function createSchema(db, withVectors, dims) {
|
|
|
71
73
|
async function populate(db, docs, links, options) {
|
|
72
74
|
const insertDoc = db.prepare(`
|
|
73
75
|
INSERT INTO docs (id, path, title, summary, tags_json, type, scope, confidence, created, updated,
|
|
74
|
-
last_confirmed_at, content_hash, bytes, conformance_json)
|
|
75
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
76
|
+
last_confirmed_at, valid_from, superseded_by, content_hash, bytes, conformance_json)
|
|
77
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
76
78
|
`);
|
|
77
79
|
const insertChunk = db.prepare(`
|
|
78
80
|
INSERT INTO chunks (doc_id, ordinal, heading, text) VALUES (?, ?, ?, ?)
|
|
@@ -91,7 +93,7 @@ async function populate(db, docs, links, options) {
|
|
|
91
93
|
db.exec("BEGIN");
|
|
92
94
|
try {
|
|
93
95
|
for (const doc of docs) {
|
|
94
|
-
insertDoc.run(doc.id, doc.path, doc.title, doc.summary, JSON.stringify(doc.tags), doc.type, doc.scope, doc.confidence, doc.created, doc.updated, doc.lastConfirmedAt, doc.contentHash, doc.bytes, JSON.stringify(doc.conformance));
|
|
96
|
+
insertDoc.run(doc.id, doc.path, doc.title, doc.summary, JSON.stringify(doc.tags), doc.type, doc.scope, doc.confidence, doc.created, doc.updated, doc.lastConfirmedAt, doc.validFrom, doc.supersededBy, doc.contentHash, doc.bytes, JSON.stringify(doc.conformance));
|
|
95
97
|
const docIdRow = db.prepare("SELECT last_insert_rowid() AS id").get();
|
|
96
98
|
const docId = Number(docIdRow.id);
|
|
97
99
|
pathToDocId.set(doc.path, docId);
|
|
@@ -6,7 +6,22 @@ import { addLesson, confirmLesson, contradictLesson, LessonRejectedError, readLe
|
|
|
6
6
|
// session recorded itself — its exit, its evidence events — never the model's own claims.
|
|
7
7
|
export const PROMOTION_HITS = 3;
|
|
8
8
|
const MAX_NEW_LESSONS = 4;
|
|
9
|
-
//
|
|
9
|
+
// Evidence that checked an outcome (T-320): a task's verify commands, or a test run. A provider
|
|
10
|
+
// exiting 0 says the CLI finished, not that the work is right, so `provider_exit` never proves.
|
|
11
|
+
export const PROVING_EVIDENCE_TYPES = new Set([
|
|
12
|
+
"task_verify",
|
|
13
|
+
"test",
|
|
14
|
+
]);
|
|
15
|
+
// Whether one evidence event's data counts as outcome proof.
|
|
16
|
+
export function isProvingEvidence(data) {
|
|
17
|
+
const parsed = safeJsonParse(data);
|
|
18
|
+
return (parsed?.result === "proven" &&
|
|
19
|
+
PROVING_EVIDENCE_TYPES.has(String(parsed?.type ?? "")));
|
|
20
|
+
}
|
|
21
|
+
// verified = completed, exited 0, at least one proving evidence event (task_verify or test),
|
|
22
|
+
// and none unproven. `provider_exit` is ignored here: the exit code is read from process_exit.
|
|
23
|
+
// A task re-verified later supersedes its earlier verdict, so only the latest task_verify per
|
|
24
|
+
// task and acceptance criterion counts.
|
|
10
25
|
export function scoreSession(session, events) {
|
|
11
26
|
const exit = [...events].reverse().find((e) => e.type === "process_exit");
|
|
12
27
|
const exitCode = exit
|
|
@@ -16,14 +31,31 @@ export function scoreSession(session, events) {
|
|
|
16
31
|
: 1;
|
|
17
32
|
let provenCount = 0;
|
|
18
33
|
let unprovenCount = 0;
|
|
34
|
+
const latestTaskVerdict = new Map();
|
|
19
35
|
for (const event of events) {
|
|
20
36
|
if (event.type !== "evidence")
|
|
21
37
|
continue;
|
|
22
|
-
|
|
38
|
+
const data = safeJsonParse(event.data);
|
|
39
|
+
const type = String(data?.type ?? "");
|
|
40
|
+
if (type === "provider_exit")
|
|
41
|
+
continue;
|
|
42
|
+
const proven = data?.result === "proven";
|
|
43
|
+
if (type === "task_verify") {
|
|
44
|
+
const key = `${data?.taskId ?? ""}:${data?.criterion ?? ""}`;
|
|
45
|
+
latestTaskVerdict.delete(key);
|
|
46
|
+
latestTaskVerdict.set(key, proven);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (!proven)
|
|
50
|
+
unprovenCount += 1;
|
|
51
|
+
else if (PROVING_EVIDENCE_TYPES.has(type))
|
|
52
|
+
provenCount += 1;
|
|
53
|
+
}
|
|
54
|
+
for (const proven of latestTaskVerdict.values())
|
|
55
|
+
if (proven)
|
|
23
56
|
provenCount += 1;
|
|
24
57
|
else
|
|
25
58
|
unprovenCount += 1;
|
|
26
|
-
}
|
|
27
59
|
return {
|
|
28
60
|
verified: session.status === "completed" &&
|
|
29
61
|
exitCode === 0 &&
|
|
@@ -3,6 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import { redactRuntimeText } from "@ocean/core/domain/redaction/redaction.js";
|
|
4
4
|
import { KNOWLEDGE_DIR, oceanPath } from "@ocean/core/shared/paths.js";
|
|
5
5
|
import { syncMemoryIndexes } from "./index-sync.js";
|
|
6
|
+
import { isProvingEvidence } from "./lesson-learning.js";
|
|
6
7
|
const kinds = new Set([
|
|
7
8
|
"architecture",
|
|
8
9
|
"decisions",
|
|
@@ -30,7 +31,7 @@ export async function promoteSessionToKnowledge(sessionId, openStore, target = "
|
|
|
30
31
|
const evidence = events
|
|
31
32
|
.filter((event) => event.type === "evidence")
|
|
32
33
|
.map((event) => event.data)
|
|
33
|
-
.some(
|
|
34
|
+
.some(isProvingEvidence);
|
|
34
35
|
if (!evidence)
|
|
35
36
|
throw new Error("Session lacks independently recorded successful evidence");
|
|
36
37
|
const input = events.find((event) => event.type === "user_input")?.data ?? "";
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// concrete node:sqlite + sqlite-vec implementation lives in infrastructure/brain/brain-index.ts
|
|
3
3
|
// and is wired in through composition/runtime.js, never imported directly by application
|
|
4
4
|
// code (enforced by tests/architecture.test.mjs).
|
|
5
|
-
// 2: docs carry a scope.
|
|
6
|
-
|
|
5
|
+
// 2: docs carry a scope. 3: docs carry valid_from and superseded_by (T-321).
|
|
6
|
+
// The index is a disposable cache, so a bump means "reindex", not a migration.
|
|
7
|
+
export const BRAIN_INDEX_SCHEMA_VERSION = "3";
|
|
7
8
|
//# sourceMappingURL=brain-index-port.js.map
|
|
@@ -453,6 +453,21 @@ export class SessionStore {
|
|
|
453
453
|
const foreignKeys = this.database.prepare("PRAGMA foreign_key_check").all();
|
|
454
454
|
return { integrity, foreignKeys };
|
|
455
455
|
}
|
|
456
|
+
listTaskSessions(taskId, projectId) {
|
|
457
|
+
const rows = (projectId
|
|
458
|
+
? this.database
|
|
459
|
+
.prepare("SELECT * FROM sessions WHERE task_id = ? AND (project_id = ? OR project_id IS NULL) ORDER BY created_at")
|
|
460
|
+
.all(taskId, projectId)
|
|
461
|
+
: this.database
|
|
462
|
+
.prepare("SELECT * FROM sessions WHERE task_id = ? ORDER BY created_at")
|
|
463
|
+
.all(taskId));
|
|
464
|
+
return rows.map((row) => this.toSession(row));
|
|
465
|
+
}
|
|
466
|
+
setVerificationStatus(sessionId, status) {
|
|
467
|
+
this.database
|
|
468
|
+
.prepare("UPDATE sessions SET verification_status = ?, updated_at = ? WHERE session_id = ?")
|
|
469
|
+
.run(status, new Date().toISOString(), sessionId);
|
|
470
|
+
}
|
|
456
471
|
appendEvent(sessionId, type, data) {
|
|
457
472
|
const createdAt = new Date().toISOString();
|
|
458
473
|
const result = this.database
|
|
@@ -8,6 +8,7 @@ import { withNextTaskId } from "@ocean/core/shared/project-resolution.js";
|
|
|
8
8
|
import { resolveTaskReference, } from "@ocean/core/shared/task-reference.js";
|
|
9
9
|
import { completeTask } from "../tasks/archive-tasks.js";
|
|
10
10
|
import { taskRecord, validTaskTitle } from "../tasks/new-task.js";
|
|
11
|
+
import { verifyAndRecord } from "../tasks/task-verification.js";
|
|
11
12
|
import { approvalMatchesTarget, operationResult, selectFields, shapeRecords, validateTaskIdentifier, validateWriteTarget, } from "./operation-contract.js";
|
|
12
13
|
import { crossProjectGuard, taskRoot, } from "./operation-scope.js";
|
|
13
14
|
import { freshnessFor, readFrontmatterFile, relativeToOcean, requireAbsentTarget, } from "./record-io.js";
|
|
@@ -261,7 +262,11 @@ export async function taskCompleteOperation(classification, _budget, options, cw
|
|
|
261
262
|
return operationResult("task.complete", approvalCheck.reason);
|
|
262
263
|
try {
|
|
263
264
|
// Reuses the existing governed completion path: it refuses a task with unchecked work.
|
|
264
|
-
const result = await completeTask(resolved.location.id, taskRoot(project.projectId)
|
|
265
|
+
const result = await completeTask(resolved.location.id, taskRoot(project.projectId), options.openStore
|
|
266
|
+
? {
|
|
267
|
+
verify: (id, root) => verifyAndRecord(id, root, { openStore: options.openStore }),
|
|
268
|
+
}
|
|
269
|
+
: {});
|
|
265
270
|
return {
|
|
266
271
|
operation: "task.complete",
|
|
267
272
|
ok: true,
|