@amoree-code/ocean 1.5.1 → 1.6.1
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/application/clients/hooks.js +8 -2
- package/dist/infrastructure/providers/session-facts-completer.js +70 -0
- package/dist/interfaces/cli/clients-command.js +35 -1
- package/dist/interfaces/cli/command-registry.js +25 -2
- package/dist/interfaces/cli/memory-command.js +19 -1
- package/dist/interfaces/cli/running-server-findings.js +19 -0
- package/dist/interfaces/cli/session-facts-command.js +65 -0
- package/node_modules/@ocean/brain/dist/memory/memory-audit.js +38 -3
- package/node_modules/@ocean/brain/dist/memory/memory-paths.js +4 -0
- package/node_modules/@ocean/brain/dist/memory/memory-review.js +5 -0
- package/node_modules/@ocean/brain/dist/memory/session-facts.js +236 -0
- package/node_modules/@ocean/brain/package.json +1 -1
- package/node_modules/@ocean/context/package.json +1 -1
- package/node_modules/@ocean/core/package.json +1 -1
- package/node_modules/@ocean/loop/dist/hooks/session-end-hook.js +34 -22
- package/node_modules/@ocean/loop/dist/hooks/session-facts-hook.js +176 -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/doctor/workspace-doctor.js +51 -3
- package/node_modules/@ocean/services/dist/infrastructure/mcp/call-ledger.js +26 -2
- package/node_modules/@ocean/services/dist/infrastructure/mcp/ocean-server.js +9 -3
- package/node_modules/@ocean/services/dist/infrastructure/mcp/server-version.js +11 -8
- package/node_modules/@ocean/services/package.json +1 -1
- package/ocean-marketplace.json +28 -28
- package/package.json +7 -7
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { mkdir, readFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { MemoryContractError } from "@ocean/core/domain/mcp/memory-contract.js";
|
|
4
|
+
import { redactSecrets } from "@ocean/core/domain/redaction/redaction.js";
|
|
5
|
+
import { atomicWrite, withFileLock } from "@ocean/core/shared/fs-utils.js";
|
|
6
|
+
import { sha256 } from "./memory-audit.js";
|
|
7
|
+
import { sessionFactsLedgerFile } from "./memory-paths.js";
|
|
8
|
+
import { proposeMemory } from "./memory-write.js";
|
|
9
|
+
export const SESSION_FACTS_SOURCE_PREFIX = "session:";
|
|
10
|
+
export function isSessionFactSource(source) {
|
|
11
|
+
return (typeof source === "string" && source.startsWith(SESSION_FACTS_SOURCE_PREFIX));
|
|
12
|
+
}
|
|
13
|
+
// About 6k tokens of transcript per call; the user's own words get most of it.
|
|
14
|
+
export const DEFAULT_FACTS_BUDGET_CHARS = 24_000;
|
|
15
|
+
const USER_SHARE = 0.7;
|
|
16
|
+
const MAX_TURN_CHARS = 4_000;
|
|
17
|
+
export const MAX_FACTS = 5;
|
|
18
|
+
const MAX_TITLE = 100;
|
|
19
|
+
const MAX_CONTENT = 1_200;
|
|
20
|
+
const MAX_EVIDENCE = 300;
|
|
21
|
+
const MIN_EVIDENCE = 8;
|
|
22
|
+
// Secrets and private paths are replaced before any text reaches a model (the candidate check
|
|
23
|
+
// runs again on the output). Turns are then chosen within the budget: the newest user turns
|
|
24
|
+
// first, up to USER_SHARE of it, then the newest assistant turns in what is left, and the chosen
|
|
25
|
+
// ones are put back in conversation order.
|
|
26
|
+
export function selectTurns(turns, budgetChars = DEFAULT_FACTS_BUDGET_CHARS) {
|
|
27
|
+
const redacted = turns
|
|
28
|
+
.map((turn, index) => ({
|
|
29
|
+
index,
|
|
30
|
+
role: turn.role,
|
|
31
|
+
text: redactSecrets(turn.text.replace(/\s+/g, " ").trim()).slice(0, MAX_TURN_CHARS),
|
|
32
|
+
}))
|
|
33
|
+
.filter((turn) => turn.text);
|
|
34
|
+
const chosen = new Set();
|
|
35
|
+
let used = 0;
|
|
36
|
+
const take = (role, limit) => {
|
|
37
|
+
for (let i = redacted.length - 1; i >= 0; i--) {
|
|
38
|
+
const turn = redacted[i];
|
|
39
|
+
if (turn.role !== role || chosen.has(turn.index))
|
|
40
|
+
continue;
|
|
41
|
+
if (used + turn.text.length > limit)
|
|
42
|
+
continue;
|
|
43
|
+
chosen.add(turn.index);
|
|
44
|
+
used += turn.text.length;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
take("user", Math.floor(budgetChars * USER_SHARE));
|
|
48
|
+
take("assistant", budgetChars);
|
|
49
|
+
// Left-over room from the assistant pass goes back to older user turns.
|
|
50
|
+
take("user", budgetChars);
|
|
51
|
+
return redacted
|
|
52
|
+
.filter((turn) => chosen.has(turn.index))
|
|
53
|
+
.map(({ role, text }) => ({ role, text }));
|
|
54
|
+
}
|
|
55
|
+
export function buildFactsPrompt(turns) {
|
|
56
|
+
const transcript = turns
|
|
57
|
+
.map((turn) => `[${turn.role === "user" ? "USER" : "ASSISTANT"}] ${turn.text}`)
|
|
58
|
+
.join("\n");
|
|
59
|
+
return [
|
|
60
|
+
"You extract durable memory from one conversation between a user and an AI assistant.",
|
|
61
|
+
"Durable means still true and useful in a later, unrelated conversation: the user's identity, role, preferences, standing decisions, project facts, constraints, and corrections to the assistant.",
|
|
62
|
+
"Only extract what the USER stated or explicitly confirmed. Never extract the assistant's suggestions, guesses or plans the user did not confirm.",
|
|
63
|
+
"Never extract temporary state (what is being debugged right now, today's to-do, a file being edited), secrets, credentials, or anything marked [REDACTED] or [PRIVATE_PATH].",
|
|
64
|
+
`Return at most ${MAX_FACTS} facts. Returning none is correct and common.`,
|
|
65
|
+
"Answer with JSON only, no prose and no code fence:",
|
|
66
|
+
'{"facts":[{"title":"short label","content":"the fact as one or two plain sentences","evidence":"an exact quote, copied character for character from one USER line","reason":"why it is durable","project":"project name if the fact is about one, else omit"}]}',
|
|
67
|
+
'Answer {"facts":[]} when nothing qualifies.',
|
|
68
|
+
"",
|
|
69
|
+
"Conversation:",
|
|
70
|
+
transcript,
|
|
71
|
+
].join("\n");
|
|
72
|
+
}
|
|
73
|
+
const clean = (value, max) => typeof value === "string"
|
|
74
|
+
? value.replace(/\s+/g, " ").trim().slice(0, max)
|
|
75
|
+
: "";
|
|
76
|
+
// The model's answer → well-formed facts. Anything else (prose, a fence around the JSON, missing
|
|
77
|
+
// fields) yields what can be read and drops the rest; never throws.
|
|
78
|
+
// The `facts` list the answer holds, or null when the answer is no such JSON at all (a failed
|
|
79
|
+
// call, prose, a refusal): then the turns are read again by a later run.
|
|
80
|
+
function factsList(text) {
|
|
81
|
+
if (!text)
|
|
82
|
+
return null;
|
|
83
|
+
const start = text.indexOf("{");
|
|
84
|
+
const end = text.lastIndexOf("}");
|
|
85
|
+
if (start < 0 || end <= start)
|
|
86
|
+
return null;
|
|
87
|
+
let parsed;
|
|
88
|
+
try {
|
|
89
|
+
parsed = JSON.parse(text.slice(start, end + 1));
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
return parsed &&
|
|
95
|
+
typeof parsed === "object" &&
|
|
96
|
+
Array.isArray(parsed.facts)
|
|
97
|
+
? parsed.facts
|
|
98
|
+
: null;
|
|
99
|
+
}
|
|
100
|
+
export function parseFacts(text) {
|
|
101
|
+
const list = factsList(text) ?? [];
|
|
102
|
+
const facts = [];
|
|
103
|
+
for (const item of list) {
|
|
104
|
+
if (!item || typeof item !== "object")
|
|
105
|
+
continue;
|
|
106
|
+
const value = item;
|
|
107
|
+
const fact = {
|
|
108
|
+
title: clean(value.title, MAX_TITLE),
|
|
109
|
+
content: clean(value.content, MAX_CONTENT),
|
|
110
|
+
evidence: clean(value.evidence, MAX_EVIDENCE),
|
|
111
|
+
reason: clean(value.reason, 300),
|
|
112
|
+
};
|
|
113
|
+
const project = clean(value.project, 64);
|
|
114
|
+
if (project)
|
|
115
|
+
fact.project = project;
|
|
116
|
+
if (fact.title && fact.content && fact.evidence)
|
|
117
|
+
facts.push(fact);
|
|
118
|
+
if (facts.length === MAX_FACTS)
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
return facts;
|
|
122
|
+
}
|
|
123
|
+
const normalize = (value) => value
|
|
124
|
+
.toLowerCase()
|
|
125
|
+
.normalize("NFKC")
|
|
126
|
+
.replace(/[‘’“”"'`]/g, "")
|
|
127
|
+
.replace(/\s+/g, " ")
|
|
128
|
+
.trim();
|
|
129
|
+
// The false-positive guard: a fact counts only when its evidence is really in what the user
|
|
130
|
+
// said (after the same redaction the model saw). An assistant line, a paraphrase passed off as a
|
|
131
|
+
// quote, or an invented fact has no such quote.
|
|
132
|
+
export function isGrounded(fact, turns) {
|
|
133
|
+
const evidence = normalize(fact.evidence);
|
|
134
|
+
if (evidence.length < MIN_EVIDENCE)
|
|
135
|
+
return false;
|
|
136
|
+
if (/\[(redacted|private_path)\]/.test(evidence))
|
|
137
|
+
return false;
|
|
138
|
+
return turns.some((turn) => turn.role === "user" && normalize(turn.text).includes(evidence));
|
|
139
|
+
}
|
|
140
|
+
export async function extractSessionFacts(options) {
|
|
141
|
+
const turns = selectTurns(options.turns, options.budgetChars);
|
|
142
|
+
if (!turns.some((turn) => turn.role === "user"))
|
|
143
|
+
return { facts: [], rejected: [], prompt: "", turns: 0, failed: false };
|
|
144
|
+
const prompt = buildFactsPrompt(turns);
|
|
145
|
+
let answer = null;
|
|
146
|
+
try {
|
|
147
|
+
answer = await options.complete(prompt);
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
answer = null;
|
|
151
|
+
}
|
|
152
|
+
const facts = [];
|
|
153
|
+
const rejected = [];
|
|
154
|
+
for (const fact of parseFacts(answer)) {
|
|
155
|
+
if (isGrounded(fact, turns))
|
|
156
|
+
facts.push(fact);
|
|
157
|
+
else
|
|
158
|
+
rejected.push({
|
|
159
|
+
title: fact.title,
|
|
160
|
+
reason: "evidence not found in a user turn",
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
facts,
|
|
165
|
+
rejected,
|
|
166
|
+
prompt,
|
|
167
|
+
turns: turns.length,
|
|
168
|
+
failed: factsList(answer) === null,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
const factKey = (fact) => `f:${sha256(normalize(fact.content))}`;
|
|
172
|
+
async function readLedger() {
|
|
173
|
+
try {
|
|
174
|
+
return JSON.parse(await readFile(sessionFactsLedgerFile(), "utf8"));
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return {};
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
async function writeLedger(ledger) {
|
|
181
|
+
const file = sessionFactsLedgerFile();
|
|
182
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
183
|
+
await atomicWrite(file, `${JSON.stringify(ledger, null, 2)}\n`, 0o600);
|
|
184
|
+
}
|
|
185
|
+
// Each fact → one candidate, through proposeMemory's own checks (size, secrets). A ledger of
|
|
186
|
+
// content hashes keeps the same fact from being proposed twice across sessions; within one
|
|
187
|
+
// session the transcript cursor already keeps the same turns from being read twice.
|
|
188
|
+
export async function proposeSessionFacts(options) {
|
|
189
|
+
// Two sessions ending together read and write the same ledger.
|
|
190
|
+
await mkdir(path.dirname(sessionFactsLedgerFile()), {
|
|
191
|
+
recursive: true,
|
|
192
|
+
mode: 0o700,
|
|
193
|
+
});
|
|
194
|
+
return withFileLock(sessionFactsLedgerFile(), () => proposeLocked(options));
|
|
195
|
+
}
|
|
196
|
+
async function proposeLocked(options) {
|
|
197
|
+
const ledger = await readLedger();
|
|
198
|
+
const result = { proposed: [], skipped: [] };
|
|
199
|
+
for (const fact of options.facts) {
|
|
200
|
+
const key = factKey(fact);
|
|
201
|
+
if (ledger[key]) {
|
|
202
|
+
result.skipped.push({
|
|
203
|
+
title: fact.title,
|
|
204
|
+
reason: `already proposed as ${ledger[key]}`,
|
|
205
|
+
});
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
const { candidate } = await proposeMemory({
|
|
210
|
+
content: `# ${fact.title}\n\n${fact.content}\n\n> ${fact.evidence}\n`,
|
|
211
|
+
origin: "inferred",
|
|
212
|
+
source: `${SESSION_FACTS_SOURCE_PREFIX}${options.sessionId}`,
|
|
213
|
+
reason: fact.reason || "stated by the user in a session",
|
|
214
|
+
meta: {
|
|
215
|
+
kind: "fact",
|
|
216
|
+
client: options.client,
|
|
217
|
+
...(fact.project ? { project: fact.project } : {}),
|
|
218
|
+
},
|
|
219
|
+
});
|
|
220
|
+
ledger[key] = candidate;
|
|
221
|
+
result.proposed.push(candidate);
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
if (!(error instanceof MemoryContractError))
|
|
225
|
+
throw error;
|
|
226
|
+
result.skipped.push({
|
|
227
|
+
title: fact.title,
|
|
228
|
+
reason: `${error.code}: ${error.message}`,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (result.proposed.length)
|
|
233
|
+
await writeLedger(ledger);
|
|
234
|
+
return result;
|
|
235
|
+
}
|
|
236
|
+
//# sourceMappingURL=session-facts.js.map
|
|
@@ -12,7 +12,10 @@ export const SESSION_END_CLIENTS = [
|
|
|
12
12
|
"qwen",
|
|
13
13
|
"cursor",
|
|
14
14
|
];
|
|
15
|
-
const TRANSCRIPT_CLIENTS = [
|
|
15
|
+
export const TRANSCRIPT_CLIENTS = [
|
|
16
|
+
"claude",
|
|
17
|
+
"codex",
|
|
18
|
+
];
|
|
16
19
|
export function isSessionEndClient(value) {
|
|
17
20
|
return SESSION_END_CLIENTS.includes(value);
|
|
18
21
|
}
|
|
@@ -43,7 +46,7 @@ function isInjectedCodexText(text) {
|
|
|
43
46
|
// One transcript line → the turn it holds, or null. Claude Code writes
|
|
44
47
|
// {type, message:{role, content}}; Codex writes {type:"response_item",
|
|
45
48
|
// payload:{type:"message", role, content:[{type:"input_text"|"output_text", text}]}}.
|
|
46
|
-
function transcriptTurn(record, client) {
|
|
49
|
+
export function transcriptTurn(record, client) {
|
|
47
50
|
if (client === "codex") {
|
|
48
51
|
const payload = record.payload;
|
|
49
52
|
if (record.type !== "response_item" || payload?.type !== "message")
|
|
@@ -135,32 +138,41 @@ export async function readTranscriptEvents(transcriptPath, client = "claude") {
|
|
|
135
138
|
* Best-effort throughout: any failure is swallowed so a broken hook can never
|
|
136
139
|
* block the user's actual session from ending.
|
|
137
140
|
*/
|
|
141
|
+
// The working folder a hook payload names: `cwd`, else Cursor's first workspace root.
|
|
142
|
+
export function payloadCwd(payload) {
|
|
143
|
+
const roots = payload.workspace_roots;
|
|
144
|
+
return (payload.cwd ||
|
|
145
|
+
(Array.isArray(roots) && typeof roots[0] === "string" ? roots[0] : "") ||
|
|
146
|
+
process.cwd());
|
|
147
|
+
}
|
|
148
|
+
// A desktop client's session in the store, registered the first time any of its hooks sees it
|
|
149
|
+
// (SessionEnd, or PreCompact before it), under the id the client itself assigned.
|
|
150
|
+
export async function ensureHookSession(store, sessionId, client, cwd) {
|
|
151
|
+
const existing = store.get(sessionId);
|
|
152
|
+
if (existing)
|
|
153
|
+
return existing;
|
|
154
|
+
store.create({
|
|
155
|
+
sessionId,
|
|
156
|
+
provider: client,
|
|
157
|
+
providerSessionId: sessionId,
|
|
158
|
+
parentSessionId: null,
|
|
159
|
+
profile: `desktop:${client}`,
|
|
160
|
+
profileIdentity: "",
|
|
161
|
+
workingDirectory: cwd,
|
|
162
|
+
resumeData: null,
|
|
163
|
+
projectId: await sessionProjectId(cwd),
|
|
164
|
+
});
|
|
165
|
+
store.updateStatus(sessionId, "running");
|
|
166
|
+
return store.get(sessionId);
|
|
167
|
+
}
|
|
138
168
|
export async function claudeSessionEndHook(payload, openStore, client = "claude") {
|
|
139
169
|
const sessionId = payload.session_id;
|
|
140
170
|
if (!sessionId)
|
|
141
171
|
return;
|
|
142
|
-
const
|
|
143
|
-
const cwd = payload.cwd ||
|
|
144
|
-
(Array.isArray(roots) && typeof roots[0] === "string" ? roots[0] : "") ||
|
|
145
|
-
process.cwd();
|
|
172
|
+
const cwd = payloadCwd(payload);
|
|
146
173
|
const store = await openStore();
|
|
147
174
|
try {
|
|
148
|
-
|
|
149
|
-
if (!session) {
|
|
150
|
-
store.create({
|
|
151
|
-
sessionId,
|
|
152
|
-
provider: client,
|
|
153
|
-
providerSessionId: sessionId,
|
|
154
|
-
parentSessionId: null,
|
|
155
|
-
profile: `desktop:${client}`,
|
|
156
|
-
profileIdentity: "",
|
|
157
|
-
workingDirectory: cwd,
|
|
158
|
-
resumeData: null,
|
|
159
|
-
projectId: await sessionProjectId(cwd),
|
|
160
|
-
});
|
|
161
|
-
store.updateStatus(sessionId, "running");
|
|
162
|
-
session = store.get(sessionId);
|
|
163
|
-
}
|
|
175
|
+
const session = await ensureHookSession(store, sessionId, client, cwd);
|
|
164
176
|
if (!session || session.closedAt)
|
|
165
177
|
return;
|
|
166
178
|
const events = payload.transcript_path && TRANSCRIPT_CLIENTS.includes(client)
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { mkdir, open, stat } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { sessionFactsEnabled } from "@ocean/brain/memory/memory-audit.js";
|
|
4
|
+
import { extractSessionFacts, proposeSessionFacts, } from "@ocean/brain/memory/session-facts.js";
|
|
5
|
+
import { safeJsonParse, withFileLock } from "@ocean/core/shared/fs-utils.js";
|
|
6
|
+
import { oceanPath, SYSTEM_DIR } from "@ocean/core/shared/paths.js";
|
|
7
|
+
import { ensureHookSession, payloadCwd, TRANSCRIPT_CLIENTS, transcriptTurn, } from "./session-end-hook.js";
|
|
8
|
+
// Fact capture from a client's transcript (T-313), run by `ocean hook session-facts` in the
|
|
9
|
+
// background after SessionEnd and PreCompact (a hook itself has seconds; a model call takes
|
|
10
|
+
// longer). A per-session cursor — the transcript byte offset already claimed — makes PreCompact
|
|
11
|
+
// then SessionEnd read each turn once: a run claims [cursor, end of the last complete line)
|
|
12
|
+
// under a short lock, records the claim as a session event, then calls the model unlocked.
|
|
13
|
+
// The most of a transcript one run reads; a longer unread part keeps its newest end.
|
|
14
|
+
const MAX_SLICE_BYTES = 4 * 1024 * 1024;
|
|
15
|
+
export const FACTS_CLAIM_EVENT = "memory_extract_claim";
|
|
16
|
+
export const FACTS_DONE_EVENT = "memory_extracted";
|
|
17
|
+
// Claude Code adds its own text to user turns: reminders, slash-command echoes, local command
|
|
18
|
+
// output. None of it is something the user said.
|
|
19
|
+
function userText(text) {
|
|
20
|
+
const stripped = text
|
|
21
|
+
.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, " ")
|
|
22
|
+
.trim();
|
|
23
|
+
if (/^<(command-|local-command-|bash-|user-prompt-submit-hook)/.test(stripped) ||
|
|
24
|
+
stripped.startsWith("Caveat: The messages below"))
|
|
25
|
+
return "";
|
|
26
|
+
return stripped;
|
|
27
|
+
}
|
|
28
|
+
// The complete lines after `from`, as turns, and the offset just past the last of them. A line
|
|
29
|
+
// still being written (no newline yet) is left for the next run.
|
|
30
|
+
export async function readTranscriptSlice(transcriptPath, client, from = 0) {
|
|
31
|
+
let size;
|
|
32
|
+
try {
|
|
33
|
+
size = (await stat(transcriptPath)).size;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return { turns: [], offset: from };
|
|
37
|
+
}
|
|
38
|
+
// A transcript shorter than the cursor was replaced: read it from the start.
|
|
39
|
+
let start = size < from ? 0 : from;
|
|
40
|
+
let partialFirst = false;
|
|
41
|
+
if (size - start > MAX_SLICE_BYTES) {
|
|
42
|
+
start = size - MAX_SLICE_BYTES;
|
|
43
|
+
partialFirst = true;
|
|
44
|
+
}
|
|
45
|
+
if (size <= start)
|
|
46
|
+
return { turns: [], offset: start };
|
|
47
|
+
const buffer = Buffer.alloc(size - start);
|
|
48
|
+
const handle = await open(transcriptPath, "r");
|
|
49
|
+
try {
|
|
50
|
+
await handle.read(buffer, 0, buffer.length, start);
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
await handle.close();
|
|
54
|
+
}
|
|
55
|
+
const lastNewline = buffer.lastIndexOf(0x0a);
|
|
56
|
+
if (lastNewline < 0)
|
|
57
|
+
return { turns: [], offset: start };
|
|
58
|
+
const lines = buffer.subarray(0, lastNewline).toString("utf8").split("\n");
|
|
59
|
+
if (partialFirst)
|
|
60
|
+
lines.shift();
|
|
61
|
+
const turns = [];
|
|
62
|
+
for (const line of lines) {
|
|
63
|
+
const record = line.trim() ? safeJsonParse(line) : null;
|
|
64
|
+
if (!record || record.isMeta === true)
|
|
65
|
+
continue;
|
|
66
|
+
const turn = transcriptTurn(record, client);
|
|
67
|
+
if (!turn)
|
|
68
|
+
continue;
|
|
69
|
+
const text = turn.role === "user" ? userText(turn.text) : turn.text.trim();
|
|
70
|
+
if (text)
|
|
71
|
+
turns.push({ role: turn.role, text });
|
|
72
|
+
}
|
|
73
|
+
return { turns, offset: start + lastNewline + 1 };
|
|
74
|
+
}
|
|
75
|
+
// The cursor: where the latest claim for this transcript ended. Each claim starts at the
|
|
76
|
+
// cursor, so claims only move it forward, except a rewind, which a failed run appends to hand
|
|
77
|
+
// its turns back (only while its claim is still the latest one).
|
|
78
|
+
function latestClaim(store, sessionId, transcriptPath) {
|
|
79
|
+
let latest = null;
|
|
80
|
+
for (const event of store.listEvents(sessionId)) {
|
|
81
|
+
if (event.type !== FACTS_CLAIM_EVENT)
|
|
82
|
+
continue;
|
|
83
|
+
const claim = safeJsonParse(event.data);
|
|
84
|
+
if (claim?.transcript !== transcriptPath)
|
|
85
|
+
continue;
|
|
86
|
+
if (typeof claim.from === "number" && typeof claim.to === "number")
|
|
87
|
+
latest = { from: claim.from, to: claim.to };
|
|
88
|
+
}
|
|
89
|
+
return latest;
|
|
90
|
+
}
|
|
91
|
+
function lockFile(sessionId) {
|
|
92
|
+
return oceanPath(SYSTEM_DIR, "state", "memory", "extract", sessionId.replace(/[^A-Za-z0-9_-]/g, "_"));
|
|
93
|
+
}
|
|
94
|
+
export async function runSessionFacts(payload, openStore, client, completer, options = {}) {
|
|
95
|
+
if (!(await (options.enabled ?? sessionFactsEnabled)()))
|
|
96
|
+
return { status: "off" };
|
|
97
|
+
const sessionId = payload.session_id;
|
|
98
|
+
const transcript = payload.transcript_path;
|
|
99
|
+
if (!sessionId || !transcript || !TRANSCRIPT_CLIENTS.includes(client))
|
|
100
|
+
return { status: "no-transcript" };
|
|
101
|
+
const transcriptPath = path.resolve(transcript);
|
|
102
|
+
const complete = completer(client);
|
|
103
|
+
await mkdir(path.dirname(lockFile(sessionId)), {
|
|
104
|
+
recursive: true,
|
|
105
|
+
mode: 0o700,
|
|
106
|
+
});
|
|
107
|
+
// Claim the unread turns. Without a model nothing is claimed, so a later run that has one
|
|
108
|
+
// still reads them.
|
|
109
|
+
const claim = await withFileLock(lockFile(sessionId), async () => {
|
|
110
|
+
const store = await openStore();
|
|
111
|
+
try {
|
|
112
|
+
await ensureHookSession(store, sessionId, client, payloadCwd(payload));
|
|
113
|
+
const from = latestClaim(store, sessionId, transcriptPath)?.to ?? 0;
|
|
114
|
+
const slice = await readTranscriptSlice(transcriptPath, client, from);
|
|
115
|
+
if (slice.offset === from)
|
|
116
|
+
return { from, slice, claimed: false };
|
|
117
|
+
if (!complete)
|
|
118
|
+
return { from, slice, claimed: false };
|
|
119
|
+
store.appendEvent(sessionId, FACTS_CLAIM_EVENT, JSON.stringify({ transcript: transcriptPath, from, to: slice.offset }));
|
|
120
|
+
return { from, slice, claimed: true };
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
store.close();
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
if (claim.slice.offset === claim.from)
|
|
127
|
+
return { status: "nothing-new" };
|
|
128
|
+
if (!complete || !claim.claimed)
|
|
129
|
+
return { status: "no-provider", from: claim.from, to: claim.slice.offset };
|
|
130
|
+
const extraction = await extractSessionFacts({
|
|
131
|
+
turns: claim.slice.turns,
|
|
132
|
+
complete,
|
|
133
|
+
});
|
|
134
|
+
if (extraction.failed) {
|
|
135
|
+
// Nothing was learned: hand the turns back, unless a later run already claimed past them.
|
|
136
|
+
await withFileLock(lockFile(sessionId), async () => {
|
|
137
|
+
const store = await openStore();
|
|
138
|
+
try {
|
|
139
|
+
const latest = latestClaim(store, sessionId, transcriptPath);
|
|
140
|
+
if (latest?.from === claim.from && latest.to === claim.slice.offset)
|
|
141
|
+
store.appendEvent(sessionId, FACTS_CLAIM_EVENT, JSON.stringify({
|
|
142
|
+
transcript: transcriptPath,
|
|
143
|
+
from: claim.slice.offset,
|
|
144
|
+
to: claim.from,
|
|
145
|
+
rewind: true,
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
store.close();
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
return { status: "failed", from: claim.from, to: claim.slice.offset };
|
|
153
|
+
}
|
|
154
|
+
const proposed = await proposeSessionFacts({
|
|
155
|
+
sessionId,
|
|
156
|
+
client,
|
|
157
|
+
facts: extraction.facts,
|
|
158
|
+
});
|
|
159
|
+
const run = {
|
|
160
|
+
status: "done",
|
|
161
|
+
from: claim.from,
|
|
162
|
+
to: claim.slice.offset,
|
|
163
|
+
candidates: proposed.proposed,
|
|
164
|
+
rejected: extraction.rejected.length,
|
|
165
|
+
skipped: proposed.skipped.length,
|
|
166
|
+
};
|
|
167
|
+
const store = await openStore();
|
|
168
|
+
try {
|
|
169
|
+
store.appendEvent(sessionId, FACTS_DONE_EVENT, JSON.stringify(run));
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
store.close();
|
|
173
|
+
}
|
|
174
|
+
return run;
|
|
175
|
+
}
|
|
176
|
+
//# sourceMappingURL=session-facts-hook.js.map
|
|
@@ -4,7 +4,8 @@ import { access, chmod, mkdir, readdir, readFile, stat, writeFile, } from "node:
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
6
|
import { doctorMemoryIndexes, syncMemoryIndexes, } from "@ocean/brain/memory/index-sync.js";
|
|
7
|
-
import {
|
|
7
|
+
import { memorySettings } from "@ocean/brain/memory/memory-audit.js";
|
|
8
|
+
import { BRAIN_RECORD_DIRS, CHARTER_DIR, enginePath, INBOX_DIR, oceanEnv, oceanPath, POLICIES_DIR, PROJECTS_DIR, projectDir, repoPath, SYSTEM_DIR, workspaceTasksRoot, } from "@ocean/core/shared/paths.js";
|
|
8
9
|
import { ensureProjectLayout, listProjectManifests, PROJECT_ROOT_ENTRIES, scanProjectManifests, UNCATEGORIZED, } from "@ocean/core/shared/project-resolution.js";
|
|
9
10
|
const execFile = promisify(execFileCallback);
|
|
10
11
|
const roots = [...BRAIN_RECORD_DIRS, PROJECTS_DIR, SYSTEM_DIR];
|
|
@@ -76,10 +77,19 @@ async function checkStructure() {
|
|
|
76
77
|
// Session summaries are machine-written records that quote links from past chats, and
|
|
77
78
|
// bridge/skills holds installed third-party skill docs whose links are relative to their upstream
|
|
78
79
|
// repo. Neither is authored here, so their links are not ours to fix.
|
|
79
|
-
|
|
80
|
+
// Soft-deleted memory in state/memory/trash keeps the links it had when it was deleted.
|
|
81
|
+
const UNCHECKED_LINK_DIRS = [
|
|
82
|
+
"sessions",
|
|
83
|
+
"skills",
|
|
84
|
+
path.join("state", "memory", "trash"),
|
|
85
|
+
];
|
|
80
86
|
async function checkLinks() {
|
|
81
87
|
const findings = [];
|
|
82
|
-
const unchecked =
|
|
88
|
+
const unchecked = [
|
|
89
|
+
...UNCHECKED_LINK_DIRS.map((name) => path.join(oceanPath(SYSTEM_DIR), name) + path.sep),
|
|
90
|
+
// Candidates hold text copied from other tools' memory, links relative to where it was.
|
|
91
|
+
path.join(oceanPath(INBOX_DIR), "candidates") + path.sep,
|
|
92
|
+
];
|
|
83
93
|
for (const root of roots) {
|
|
84
94
|
for (const file of await markdownFiles(oceanPath(root))) {
|
|
85
95
|
if (unchecked.some((prefix) => file.startsWith(prefix)))
|
|
@@ -429,6 +439,43 @@ async function checkProfileAuthority() {
|
|
|
429
439
|
},
|
|
430
440
|
];
|
|
431
441
|
}
|
|
442
|
+
// Session fact capture (T-313) is asked once at `ocean client apply`; a machine that never
|
|
443
|
+
// answered (a non-interactive install) captures nothing until the owner chooses.
|
|
444
|
+
async function checkSessionFacts() {
|
|
445
|
+
let saved;
|
|
446
|
+
try {
|
|
447
|
+
saved = (await memorySettings()).sessionFacts;
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
return [
|
|
451
|
+
{
|
|
452
|
+
code: "MEMORY_SETTINGS_INVALID",
|
|
453
|
+
severity: "WARN",
|
|
454
|
+
message: error instanceof Error ? error.message : String(error),
|
|
455
|
+
fixable: false,
|
|
456
|
+
},
|
|
457
|
+
];
|
|
458
|
+
}
|
|
459
|
+
if (saved === null)
|
|
460
|
+
return [
|
|
461
|
+
{
|
|
462
|
+
code: "SESSION_FACTS_UNSET",
|
|
463
|
+
severity: "WARN",
|
|
464
|
+
message: "automatic fact capture from sessions is off until you choose: ocean memory session-facts on|off",
|
|
465
|
+
fixable: false,
|
|
466
|
+
},
|
|
467
|
+
];
|
|
468
|
+
return [
|
|
469
|
+
{
|
|
470
|
+
code: saved ? "SESSION_FACTS_ON" : "SESSION_FACTS_OFF",
|
|
471
|
+
severity: "OK",
|
|
472
|
+
message: saved
|
|
473
|
+
? "facts from finished and compacted sessions go to the review queue"
|
|
474
|
+
: "automatic fact capture from sessions is off (owner's choice)",
|
|
475
|
+
fixable: false,
|
|
476
|
+
},
|
|
477
|
+
];
|
|
478
|
+
}
|
|
432
479
|
async function checkVersion() {
|
|
433
480
|
const packageFile = enginePath("package.json");
|
|
434
481
|
if (!(await exists(packageFile)))
|
|
@@ -495,6 +542,7 @@ async function scanWorkspace(wrapperManager) {
|
|
|
495
542
|
...(await checkStructure()),
|
|
496
543
|
...(await checkLinks()),
|
|
497
544
|
...(await checkMemory()),
|
|
545
|
+
...(await checkSessionFacts()),
|
|
498
546
|
...(await checkVersion()),
|
|
499
547
|
...(await checkGovernance()),
|
|
500
548
|
...(await checkWrappers(wrapperManager)),
|