@joshuaswarren/openclaw-engram 9.0.61 → 9.0.63
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/chunk-RQ4ENU3T.js +1808 -0
- package/dist/chunk-RQ4ENU3T.js.map +1 -0
- package/dist/{chunk-QKD7TZY2.js → chunk-URYFI4X6.js} +1 -1
- package/dist/chunk-URYFI4X6.js.map +1 -0
- package/dist/engine-UD75NBCY.js +12 -0
- package/dist/index.js +927 -2140
- package/dist/index.js.map +1 -1
- package/dist/{storage-HA63XQAU.js → storage-BX3X2GUO.js} +2 -2
- package/dist/storage-BX3X2GUO.js.map +1 -0
- package/openclaw.plugin.json +12 -2
- package/package.json +1 -1
- package/dist/chunk-QKD7TZY2.js.map +0 -1
- /package/dist/{storage-HA63XQAU.js.map → engine-UD75NBCY.js.map} +0 -0
|
@@ -0,0 +1,1808 @@
|
|
|
1
|
+
// openclaw-engram: Local-first memory plugin
|
|
2
|
+
import {
|
|
3
|
+
StorageManager,
|
|
4
|
+
parseContinuityImprovementLoops,
|
|
5
|
+
parseContinuityIncident,
|
|
6
|
+
sanitizeMemoryContent
|
|
7
|
+
} from "./chunk-URYFI4X6.js";
|
|
8
|
+
import {
|
|
9
|
+
log
|
|
10
|
+
} from "./chunk-SSIIJJKA.js";
|
|
11
|
+
|
|
12
|
+
// src/compounding/engine.ts
|
|
13
|
+
import { createHash } from "crypto";
|
|
14
|
+
import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, unlink, writeFile as writeFile2 } from "fs/promises";
|
|
15
|
+
import path2 from "path";
|
|
16
|
+
import os2 from "os";
|
|
17
|
+
|
|
18
|
+
// src/shared-context/manager.ts
|
|
19
|
+
import { mkdir, readFile, readdir, appendFile, writeFile, stat } from "fs/promises";
|
|
20
|
+
import path from "path";
|
|
21
|
+
import os from "os";
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
var SharedFeedbackEntrySchema = z.object({
|
|
24
|
+
agent: z.string().min(1),
|
|
25
|
+
decision: z.enum(["approved", "approved_with_feedback", "rejected"]),
|
|
26
|
+
reason: z.string().min(1),
|
|
27
|
+
date: z.string().min(8),
|
|
28
|
+
// ISO-ish; keep loose
|
|
29
|
+
learning: z.string().optional(),
|
|
30
|
+
outcome: z.string().optional(),
|
|
31
|
+
severity: z.enum(["low", "medium", "high"]).optional(),
|
|
32
|
+
confidence: z.number().min(0).max(1).optional(),
|
|
33
|
+
workflow: z.string().min(1).optional(),
|
|
34
|
+
tags: z.array(z.string().min(1)).optional(),
|
|
35
|
+
evidenceWindowStart: z.string().min(8).optional(),
|
|
36
|
+
evidenceWindowEnd: z.string().min(8).optional(),
|
|
37
|
+
refs: z.array(z.string()).optional()
|
|
38
|
+
});
|
|
39
|
+
function safeSlug(s) {
|
|
40
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "output";
|
|
41
|
+
}
|
|
42
|
+
function ymd(d) {
|
|
43
|
+
return d.toISOString().slice(0, 10);
|
|
44
|
+
}
|
|
45
|
+
var CROSS_SIGNAL_STOPWORDS = /* @__PURE__ */ new Set([
|
|
46
|
+
"a",
|
|
47
|
+
"an",
|
|
48
|
+
"and",
|
|
49
|
+
"are",
|
|
50
|
+
"as",
|
|
51
|
+
"at",
|
|
52
|
+
"be",
|
|
53
|
+
"by",
|
|
54
|
+
"for",
|
|
55
|
+
"from",
|
|
56
|
+
"has",
|
|
57
|
+
"have",
|
|
58
|
+
"in",
|
|
59
|
+
"is",
|
|
60
|
+
"it",
|
|
61
|
+
"of",
|
|
62
|
+
"on",
|
|
63
|
+
"or",
|
|
64
|
+
"that",
|
|
65
|
+
"the",
|
|
66
|
+
"this",
|
|
67
|
+
"to",
|
|
68
|
+
"was",
|
|
69
|
+
"were",
|
|
70
|
+
"with",
|
|
71
|
+
"agent",
|
|
72
|
+
"output",
|
|
73
|
+
"today",
|
|
74
|
+
"daily",
|
|
75
|
+
"notes",
|
|
76
|
+
"note",
|
|
77
|
+
"summary"
|
|
78
|
+
]);
|
|
79
|
+
function extractTopicTokens(text, maxTokens = 12) {
|
|
80
|
+
const seen = /* @__PURE__ */ new Set();
|
|
81
|
+
const out = [];
|
|
82
|
+
const tokens = text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).map((token) => token.trim()).filter((token) => token.length >= 4).filter((token) => !CROSS_SIGNAL_STOPWORDS.has(token));
|
|
83
|
+
for (const token of tokens) {
|
|
84
|
+
if (seen.has(token)) continue;
|
|
85
|
+
seen.add(token);
|
|
86
|
+
out.push(token);
|
|
87
|
+
if (out.length >= maxTokens) break;
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
function stripYamlFrontmatter(text) {
|
|
92
|
+
if (!text.startsWith("---\n")) return text;
|
|
93
|
+
const closing = text.indexOf("\n---\n", 4);
|
|
94
|
+
if (closing === -1) return text;
|
|
95
|
+
return text.slice(closing + 5);
|
|
96
|
+
}
|
|
97
|
+
function semanticRoot(token) {
|
|
98
|
+
let root = token.toLowerCase();
|
|
99
|
+
if (root.endsWith("izations") && root.length > 9) {
|
|
100
|
+
root = `${root.slice(0, -8)}ize`;
|
|
101
|
+
} else if (root.endsWith("ization") && root.length > 8) {
|
|
102
|
+
root = `${root.slice(0, -7)}ize`;
|
|
103
|
+
} else if (root.endsWith("isations") && root.length > 9) {
|
|
104
|
+
root = `${root.slice(0, -8)}ise`;
|
|
105
|
+
} else if (root.endsWith("isation") && root.length > 8) {
|
|
106
|
+
root = `${root.slice(0, -7)}ise`;
|
|
107
|
+
} else {
|
|
108
|
+
const suffixes = [
|
|
109
|
+
"ations",
|
|
110
|
+
"ation",
|
|
111
|
+
"ments",
|
|
112
|
+
"ment",
|
|
113
|
+
"ingly",
|
|
114
|
+
"edly",
|
|
115
|
+
"ings",
|
|
116
|
+
"ing",
|
|
117
|
+
"ers",
|
|
118
|
+
"er",
|
|
119
|
+
"ies",
|
|
120
|
+
"ied",
|
|
121
|
+
"ions",
|
|
122
|
+
"ion",
|
|
123
|
+
"es",
|
|
124
|
+
"ed",
|
|
125
|
+
"s"
|
|
126
|
+
];
|
|
127
|
+
for (const suffix of suffixes) {
|
|
128
|
+
if (root.length > suffix.length + 3 && root.endsWith(suffix)) {
|
|
129
|
+
root = root.slice(0, -suffix.length);
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (root.length > 4 && root.endsWith("e")) {
|
|
135
|
+
root = root.slice(0, -1);
|
|
136
|
+
}
|
|
137
|
+
return root;
|
|
138
|
+
}
|
|
139
|
+
function mergeOverlaps(base, extra) {
|
|
140
|
+
const merged = /* @__PURE__ */ new Map();
|
|
141
|
+
for (const entry of [...base, ...extra]) {
|
|
142
|
+
const existing = merged.get(entry.token);
|
|
143
|
+
if (existing) {
|
|
144
|
+
for (const agent of entry.agents) existing.agents.add(agent);
|
|
145
|
+
for (const sourcePath of entry.sourcePaths) existing.sourcePaths.add(sourcePath);
|
|
146
|
+
} else {
|
|
147
|
+
merged.set(entry.token, {
|
|
148
|
+
agents: new Set(entry.agents),
|
|
149
|
+
sourcePaths: new Set(entry.sourcePaths)
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return [...merged.entries()].map(([token, value]) => ({
|
|
154
|
+
token,
|
|
155
|
+
agents: [...value.agents].sort(),
|
|
156
|
+
sourcePaths: [...value.sourcePaths].sort(),
|
|
157
|
+
agentCount: value.agents.size
|
|
158
|
+
})).filter((entry) => entry.agentCount >= 2).sort((a, b) => b.agentCount - a.agentCount || a.token.localeCompare(b.token));
|
|
159
|
+
}
|
|
160
|
+
async function computeSemanticOverlapCandidates(sources, maxCandidates, timeoutAtMs) {
|
|
161
|
+
const tokenRows = [];
|
|
162
|
+
for (const source of sources) {
|
|
163
|
+
for (const token of source.topics) {
|
|
164
|
+
if (Date.now() >= timeoutAtMs) return { overlaps: [], candidateCount: tokenRows.length, timedOut: true };
|
|
165
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
166
|
+
tokenRows.push({ token, agent: source.agent, path: source.path });
|
|
167
|
+
if (tokenRows.length >= maxCandidates) break;
|
|
168
|
+
}
|
|
169
|
+
if (tokenRows.length >= maxCandidates) break;
|
|
170
|
+
}
|
|
171
|
+
const byRoot = /* @__PURE__ */ new Map();
|
|
172
|
+
for (const row of tokenRows) {
|
|
173
|
+
if (Date.now() >= timeoutAtMs) return { overlaps: [], candidateCount: tokenRows.length, timedOut: true };
|
|
174
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
175
|
+
const root = semanticRoot(row.token);
|
|
176
|
+
if (root.length < 4) continue;
|
|
177
|
+
const rootGroup = byRoot.get(root) ?? /* @__PURE__ */ new Map();
|
|
178
|
+
const tokenGroup = rootGroup.get(row.token) ?? { agents: /* @__PURE__ */ new Set(), paths: /* @__PURE__ */ new Set() };
|
|
179
|
+
tokenGroup.agents.add(row.agent);
|
|
180
|
+
tokenGroup.paths.add(row.path);
|
|
181
|
+
rootGroup.set(row.token, tokenGroup);
|
|
182
|
+
byRoot.set(root, rootGroup);
|
|
183
|
+
}
|
|
184
|
+
const overlaps = [];
|
|
185
|
+
for (const [root, tokenMap] of byRoot.entries()) {
|
|
186
|
+
if (Date.now() >= timeoutAtMs) return { overlaps: [], candidateCount: tokenRows.length, timedOut: true };
|
|
187
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
188
|
+
if (tokenMap.size < 2) continue;
|
|
189
|
+
const agents = /* @__PURE__ */ new Set();
|
|
190
|
+
const sourcePaths = /* @__PURE__ */ new Set();
|
|
191
|
+
for (const value of tokenMap.values()) {
|
|
192
|
+
for (const agent of value.agents) agents.add(agent);
|
|
193
|
+
for (const sourcePath of value.paths) sourcePaths.add(sourcePath);
|
|
194
|
+
}
|
|
195
|
+
if (agents.size < 2) continue;
|
|
196
|
+
overlaps.push({
|
|
197
|
+
token: `semantic:${root}`,
|
|
198
|
+
agents: [...agents].sort(),
|
|
199
|
+
sourcePaths: [...sourcePaths].sort(),
|
|
200
|
+
agentCount: agents.size
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
overlaps.sort((a, b) => b.agentCount - a.agentCount || a.token.localeCompare(b.token));
|
|
204
|
+
return {
|
|
205
|
+
overlaps,
|
|
206
|
+
candidateCount: tokenRows.length,
|
|
207
|
+
timedOut: false
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
async function computeSemanticOverlapsWithTimeout(sources, timeoutMs, maxCandidates) {
|
|
211
|
+
const safeTimeoutMs = Math.max(1, Math.floor(timeoutMs));
|
|
212
|
+
const safeMaxCandidates = Math.max(0, Math.floor(maxCandidates));
|
|
213
|
+
if (safeMaxCandidates === 0 || sources.length === 0) {
|
|
214
|
+
return { overlaps: [], candidateCount: 0, timedOut: false };
|
|
215
|
+
}
|
|
216
|
+
const timeoutAtMs = Date.now() + safeTimeoutMs;
|
|
217
|
+
return computeSemanticOverlapCandidates(sources, safeMaxCandidates, timeoutAtMs);
|
|
218
|
+
}
|
|
219
|
+
function feedbackDecisionPriority(decision) {
|
|
220
|
+
switch (decision) {
|
|
221
|
+
case "rejected":
|
|
222
|
+
return 3;
|
|
223
|
+
case "approved_with_feedback":
|
|
224
|
+
return 2;
|
|
225
|
+
case "approved":
|
|
226
|
+
return 1;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function feedbackSeverityPriority(severity) {
|
|
230
|
+
switch (severity) {
|
|
231
|
+
case "high":
|
|
232
|
+
return 3;
|
|
233
|
+
case "medium":
|
|
234
|
+
return 2;
|
|
235
|
+
case "low":
|
|
236
|
+
return 1;
|
|
237
|
+
default:
|
|
238
|
+
return 0;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function compareFeedbackPriority(a, b) {
|
|
242
|
+
return feedbackDecisionPriority(b.decision) - feedbackDecisionPriority(a.decision) || feedbackSeverityPriority(b.severity) - feedbackSeverityPriority(a.severity) || a.date.localeCompare(b.date);
|
|
243
|
+
}
|
|
244
|
+
function formatFeedbackLine(entry) {
|
|
245
|
+
const extras = [`feedback: ${entry.date}`];
|
|
246
|
+
if (entry.severity) extras.push(`severity: ${entry.severity}`);
|
|
247
|
+
if (entry.refs?.length) extras.push(`refs: ${entry.refs.join(", ")}`);
|
|
248
|
+
return `- [${entry.agent}] ${entry.decision}: ${entry.reason} [${extras.join("; ")}]`;
|
|
249
|
+
}
|
|
250
|
+
function formatOverlapLine(entry) {
|
|
251
|
+
return `- \`${entry.token}\` (${entry.agentCount} agents: ${entry.agents.join(", ")}) [sources: ${entry.sourcePaths.join(", ")}]`;
|
|
252
|
+
}
|
|
253
|
+
var SharedContextManager = class {
|
|
254
|
+
constructor(config) {
|
|
255
|
+
this.config = config;
|
|
256
|
+
const base = typeof config.sharedContextDir === "string" && config.sharedContextDir.length > 0 ? config.sharedContextDir : path.join(os.homedir(), ".openclaw", "workspace", "shared-context");
|
|
257
|
+
this.dir = base;
|
|
258
|
+
this.prioritiesPath = path.join(base, "priorities.md");
|
|
259
|
+
this.prioritiesInboxPath = path.join(base, "priorities.inbox.md");
|
|
260
|
+
this.outputsDir = path.join(base, "agent-outputs");
|
|
261
|
+
this.roundtableDir = path.join(base, "roundtable");
|
|
262
|
+
this.feedbackDir = path.join(base, "feedback");
|
|
263
|
+
this.feedbackInboxPath = path.join(this.feedbackDir, "inbox.jsonl");
|
|
264
|
+
this.crossSignalsDir = path.join(base, "cross-signals");
|
|
265
|
+
}
|
|
266
|
+
dir;
|
|
267
|
+
prioritiesPath;
|
|
268
|
+
prioritiesInboxPath;
|
|
269
|
+
outputsDir;
|
|
270
|
+
roundtableDir;
|
|
271
|
+
feedbackDir;
|
|
272
|
+
feedbackInboxPath;
|
|
273
|
+
crossSignalsDir;
|
|
274
|
+
async ensureStructure() {
|
|
275
|
+
await mkdir(this.dir, { recursive: true });
|
|
276
|
+
await mkdir(this.outputsDir, { recursive: true });
|
|
277
|
+
await mkdir(this.roundtableDir, { recursive: true });
|
|
278
|
+
await mkdir(this.feedbackDir, { recursive: true });
|
|
279
|
+
await mkdir(this.crossSignalsDir, { recursive: true });
|
|
280
|
+
await mkdir(path.join(this.dir, "staging"), { recursive: true });
|
|
281
|
+
await mkdir(path.join(this.dir, "kpis"), { recursive: true });
|
|
282
|
+
await mkdir(path.join(this.dir, "calendar"), { recursive: true });
|
|
283
|
+
await mkdir(path.join(this.dir, "content-calendar"), { recursive: true });
|
|
284
|
+
await this.ensureFile(
|
|
285
|
+
this.prioritiesPath,
|
|
286
|
+
[
|
|
287
|
+
"# Priorities",
|
|
288
|
+
"",
|
|
289
|
+
"This is the shared priority stack. Agents should read this before acting.",
|
|
290
|
+
"",
|
|
291
|
+
"## Current",
|
|
292
|
+
"- (empty)",
|
|
293
|
+
"",
|
|
294
|
+
"## Notes",
|
|
295
|
+
"- (empty)",
|
|
296
|
+
""
|
|
297
|
+
].join("\n")
|
|
298
|
+
);
|
|
299
|
+
await this.ensureFile(
|
|
300
|
+
this.prioritiesInboxPath,
|
|
301
|
+
[
|
|
302
|
+
"# Priorities Inbox",
|
|
303
|
+
"",
|
|
304
|
+
"Append-only inbox. Curator merges into priorities.md.",
|
|
305
|
+
""
|
|
306
|
+
].join("\n")
|
|
307
|
+
);
|
|
308
|
+
await this.ensureFile(this.feedbackInboxPath, "");
|
|
309
|
+
}
|
|
310
|
+
async ensureFile(fp, content) {
|
|
311
|
+
try {
|
|
312
|
+
await stat(fp);
|
|
313
|
+
} catch {
|
|
314
|
+
await writeFile(fp, content, "utf-8");
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
async readPriorities() {
|
|
318
|
+
try {
|
|
319
|
+
return await readFile(this.prioritiesPath, "utf-8");
|
|
320
|
+
} catch {
|
|
321
|
+
return "";
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
async readLatestRoundtable() {
|
|
325
|
+
try {
|
|
326
|
+
const files = (await readdir(this.roundtableDir)).filter((f) => f.endsWith(".md")).sort().reverse();
|
|
327
|
+
const fp = files[0] ? path.join(this.roundtableDir, files[0]) : null;
|
|
328
|
+
if (!fp) return "";
|
|
329
|
+
return await readFile(fp, "utf-8");
|
|
330
|
+
} catch {
|
|
331
|
+
return "";
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
async readLatestCrossSignals() {
|
|
335
|
+
try {
|
|
336
|
+
const files = (await readdir(this.crossSignalsDir)).filter((f) => f.endsWith(".md")).sort().reverse();
|
|
337
|
+
const fp = files[0] ? path.join(this.crossSignalsDir, files[0]) : null;
|
|
338
|
+
if (!fp) return "";
|
|
339
|
+
return await readFile(fp, "utf-8");
|
|
340
|
+
} catch {
|
|
341
|
+
return "";
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
async writeAgentOutput(opts) {
|
|
345
|
+
const createdAt = opts.createdAt ?? /* @__PURE__ */ new Date();
|
|
346
|
+
const date = ymd(createdAt);
|
|
347
|
+
const time = createdAt.toISOString().slice(11, 19).replace(/:/g, "");
|
|
348
|
+
const slug = safeSlug(opts.title);
|
|
349
|
+
const dir = path.join(this.outputsDir, opts.agentId, date);
|
|
350
|
+
await mkdir(dir, { recursive: true });
|
|
351
|
+
const fp = path.join(dir, `${time}-${slug}.md`);
|
|
352
|
+
const body = `---
|
|
353
|
+
kind: agent_output
|
|
354
|
+
agent: ${opts.agentId}
|
|
355
|
+
createdAt: ${createdAt.toISOString()}
|
|
356
|
+
title: ${opts.title.replace(/\n/g, " ").slice(0, 200)}
|
|
357
|
+
---
|
|
358
|
+
|
|
359
|
+
` + opts.content.trimEnd() + "\n";
|
|
360
|
+
await writeFile(fp, body, "utf-8");
|
|
361
|
+
return fp;
|
|
362
|
+
}
|
|
363
|
+
async appendFeedback(entry) {
|
|
364
|
+
const parsed = SharedFeedbackEntrySchema.parse(entry);
|
|
365
|
+
await appendFile(this.feedbackInboxPath, JSON.stringify(parsed) + "\n", "utf-8");
|
|
366
|
+
}
|
|
367
|
+
async appendPrioritiesInbox(opts) {
|
|
368
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
369
|
+
const lines = [
|
|
370
|
+
"",
|
|
371
|
+
`## ${stamp} (${opts.agentId})`,
|
|
372
|
+
"",
|
|
373
|
+
opts.text.trimEnd(),
|
|
374
|
+
""
|
|
375
|
+
].join("\n");
|
|
376
|
+
await appendFile(this.prioritiesInboxPath, lines, "utf-8");
|
|
377
|
+
}
|
|
378
|
+
async synthesizeCrossSignals(opts) {
|
|
379
|
+
const date = opts.date ?? ymd(/* @__PURE__ */ new Date());
|
|
380
|
+
const maxSummaryItems = Math.max(1, opts.maxSummaryItems ?? 8);
|
|
381
|
+
const outputs = [];
|
|
382
|
+
try {
|
|
383
|
+
const agents = await readdir(this.outputsDir, { withFileTypes: true });
|
|
384
|
+
for (const a of agents) {
|
|
385
|
+
if (!a.isDirectory()) continue;
|
|
386
|
+
const dayDir = path.join(this.outputsDir, a.name, date);
|
|
387
|
+
try {
|
|
388
|
+
const files = (await readdir(dayDir)).filter((f) => f.endsWith(".md")).sort();
|
|
389
|
+
for (const f of files) {
|
|
390
|
+
const p = path.join(dayDir, f);
|
|
391
|
+
const raw = await readFile(p, "utf-8");
|
|
392
|
+
const title = (raw.match(/^title:\s*(.+)$/m)?.[1] ?? f).trim();
|
|
393
|
+
outputs.push({ agent: a.name, path: p, title, raw });
|
|
394
|
+
}
|
|
395
|
+
} catch {
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
} catch {
|
|
399
|
+
}
|
|
400
|
+
const feedback = [];
|
|
401
|
+
try {
|
|
402
|
+
const raw = await readFile(this.feedbackInboxPath, "utf-8");
|
|
403
|
+
for (const line of raw.split("\n")) {
|
|
404
|
+
if (!line.trim()) continue;
|
|
405
|
+
try {
|
|
406
|
+
const obj = JSON.parse(line);
|
|
407
|
+
const parsed = SharedFeedbackEntrySchema.safeParse(obj);
|
|
408
|
+
if (!parsed.success) continue;
|
|
409
|
+
if (String(parsed.data.date).startsWith(date)) feedback.push(parsed.data);
|
|
410
|
+
} catch {
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
} catch {
|
|
414
|
+
}
|
|
415
|
+
const sources = outputs.map((output) => {
|
|
416
|
+
const body = stripYamlFrontmatter(output.raw);
|
|
417
|
+
return {
|
|
418
|
+
agent: output.agent,
|
|
419
|
+
path: output.path,
|
|
420
|
+
title: output.title,
|
|
421
|
+
topics: extractTopicTokens(`${output.title}
|
|
422
|
+
${body}`)
|
|
423
|
+
};
|
|
424
|
+
});
|
|
425
|
+
const overlapMap = /* @__PURE__ */ new Map();
|
|
426
|
+
for (const source of sources) {
|
|
427
|
+
for (const token of source.topics) {
|
|
428
|
+
const existing = overlapMap.get(token);
|
|
429
|
+
if (existing) {
|
|
430
|
+
existing.agents.add(source.agent);
|
|
431
|
+
existing.sourcePaths.add(source.path);
|
|
432
|
+
} else {
|
|
433
|
+
overlapMap.set(token, {
|
|
434
|
+
agents: /* @__PURE__ */ new Set([source.agent]),
|
|
435
|
+
sourcePaths: /* @__PURE__ */ new Set([source.path])
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const overlaps = [...overlapMap.entries()].map(([token, v]) => ({
|
|
441
|
+
token,
|
|
442
|
+
agents: [...v.agents].sort(),
|
|
443
|
+
sourcePaths: [...v.sourcePaths].sort(),
|
|
444
|
+
agentCount: v.agents.size
|
|
445
|
+
})).filter((entry) => entry.agentCount >= 2).sort((a, b) => b.agentCount - a.agentCount || a.token.localeCompare(b.token));
|
|
446
|
+
const semanticEnabled = this.config.sharedCrossSignalSemanticEnabled === true || this.config.crossSignalsSemanticEnabled === true;
|
|
447
|
+
const semanticTimeoutMs = this.config.sharedCrossSignalSemanticTimeoutMs ?? this.config.crossSignalsSemanticTimeoutMs ?? 4e3;
|
|
448
|
+
const semanticMaxCandidates = this.config.sharedCrossSignalSemanticMaxCandidates ?? 120;
|
|
449
|
+
let semanticApplied = false;
|
|
450
|
+
let semanticTimedOut = false;
|
|
451
|
+
let semanticCandidateCount = 0;
|
|
452
|
+
let semanticAddedOverlapCount = 0;
|
|
453
|
+
let mergedOverlaps = overlaps;
|
|
454
|
+
if (semanticEnabled) {
|
|
455
|
+
try {
|
|
456
|
+
const semanticResult = await computeSemanticOverlapsWithTimeout(
|
|
457
|
+
sources,
|
|
458
|
+
semanticTimeoutMs,
|
|
459
|
+
semanticMaxCandidates
|
|
460
|
+
);
|
|
461
|
+
semanticTimedOut = semanticResult.timedOut;
|
|
462
|
+
semanticCandidateCount = semanticResult.candidateCount;
|
|
463
|
+
if (!semanticResult.timedOut && semanticResult.overlaps.length > 0) {
|
|
464
|
+
mergedOverlaps = mergeOverlaps(overlaps, semanticResult.overlaps);
|
|
465
|
+
semanticAddedOverlapCount = Math.max(0, mergedOverlaps.length - overlaps.length);
|
|
466
|
+
semanticApplied = semanticAddedOverlapCount > 0;
|
|
467
|
+
}
|
|
468
|
+
} catch (err) {
|
|
469
|
+
log.warn(`shared-context semantic cross-signals failed; fail-open to deterministic output: ${err}`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
const feedbackByDecision = {
|
|
473
|
+
approved: 0,
|
|
474
|
+
approved_with_feedback: 0,
|
|
475
|
+
rejected: 0
|
|
476
|
+
};
|
|
477
|
+
for (const entry of feedback) {
|
|
478
|
+
feedbackByDecision[entry.decision] += 1;
|
|
479
|
+
}
|
|
480
|
+
const report = {
|
|
481
|
+
date,
|
|
482
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
483
|
+
sourceCount: sources.length,
|
|
484
|
+
feedbackCount: feedback.length,
|
|
485
|
+
feedbackByDecision,
|
|
486
|
+
feedbackEntries: [...feedback].sort(compareFeedbackPriority),
|
|
487
|
+
sources,
|
|
488
|
+
overlaps: mergedOverlaps,
|
|
489
|
+
semantic: {
|
|
490
|
+
enabled: semanticEnabled,
|
|
491
|
+
applied: semanticApplied,
|
|
492
|
+
timedOut: semanticTimedOut,
|
|
493
|
+
candidateCount: semanticCandidateCount,
|
|
494
|
+
maxCandidates: Math.max(0, Math.floor(semanticMaxCandidates)),
|
|
495
|
+
addedOverlapCount: semanticAddedOverlapCount
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
const crossSignalsPath = path.join(this.crossSignalsDir, `${date}.json`);
|
|
499
|
+
await writeFile(crossSignalsPath, `${JSON.stringify(report, null, 2)}
|
|
500
|
+
`, "utf-8");
|
|
501
|
+
const recurringThemeLines = mergedOverlaps.length === 0 ? ["- No multi-agent topic overlap detected."] : mergedOverlaps.slice(0, maxSummaryItems).map((entry) => formatOverlapLine(entry));
|
|
502
|
+
const riskSignals = [...feedback].filter((entry) => entry.decision !== "approved" || entry.severity === "high" || entry.severity === "medium").sort(compareFeedbackPriority).slice(0, maxSummaryItems);
|
|
503
|
+
const riskLines = riskSignals.length === 0 ? ["- No explicit blockers or elevated review risks recorded."] : riskSignals.map((entry) => formatFeedbackLine(entry));
|
|
504
|
+
const promotionCandidates = mergedOverlaps.filter((entry) => entry.agentCount >= 3).slice(0, maxSummaryItems);
|
|
505
|
+
const promotionLines = promotionCandidates.length === 0 ? ["- No promotion candidates yet."] : promotionCandidates.map(
|
|
506
|
+
(entry) => `- Consider promoting \`${entry.token}\` into priorities or operating rules [sources: ${entry.sourcePaths.join(", ")}]`
|
|
507
|
+
);
|
|
508
|
+
const crossSignalsMarkdown = [
|
|
509
|
+
`# Cross-Signals \u2014 ${date}`,
|
|
510
|
+
"",
|
|
511
|
+
"## Overview",
|
|
512
|
+
`- Source outputs analyzed: ${sources.length}`,
|
|
513
|
+
`- Feedback entries analyzed: ${feedback.length}`,
|
|
514
|
+
`- Decision totals: approved=${feedbackByDecision.approved}, approved_with_feedback=${feedbackByDecision.approved_with_feedback}, rejected=${feedbackByDecision.rejected}`,
|
|
515
|
+
`- Semantic enhancer: ${semanticEnabled ? semanticTimedOut ? "enabled (timed out, fail-open)" : semanticApplied ? "enabled (applied)" : "enabled (no additional overlaps)" : "disabled"}`,
|
|
516
|
+
`- JSON report: ${crossSignalsPath}`,
|
|
517
|
+
"",
|
|
518
|
+
"## Recurring Themes",
|
|
519
|
+
...recurringThemeLines,
|
|
520
|
+
"",
|
|
521
|
+
"## Risks And Blockers",
|
|
522
|
+
...riskLines,
|
|
523
|
+
"",
|
|
524
|
+
"## Potential Promotions",
|
|
525
|
+
...promotionLines,
|
|
526
|
+
"",
|
|
527
|
+
"## Sources",
|
|
528
|
+
...sources.length === 0 ? ["- (none)"] : sources.map(
|
|
529
|
+
(source) => `- [${source.agent}] ${source.title} (${source.path})`
|
|
530
|
+
),
|
|
531
|
+
""
|
|
532
|
+
].join("\n");
|
|
533
|
+
const crossSignalsMarkdownPath = path.join(this.crossSignalsDir, `${date}.md`);
|
|
534
|
+
await writeFile(crossSignalsMarkdownPath, crossSignalsMarkdown, "utf-8");
|
|
535
|
+
return {
|
|
536
|
+
date,
|
|
537
|
+
crossSignalsPath,
|
|
538
|
+
crossSignalsMarkdownPath,
|
|
539
|
+
overlapCount: mergedOverlaps.length,
|
|
540
|
+
report
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
async curateDaily(opts) {
|
|
544
|
+
const date = opts.date ?? ymd(/* @__PURE__ */ new Date());
|
|
545
|
+
const maxChars = Math.max(2e3, opts.maxChars ?? 2e4);
|
|
546
|
+
const crossSignals = await this.synthesizeCrossSignals({ date });
|
|
547
|
+
const feedbackLines = crossSignals.report.feedbackEntries.length === 0 ? ["- (none)"] : crossSignals.report.feedbackEntries.map((entry) => formatFeedbackLine(entry));
|
|
548
|
+
const overlapBullets = crossSignals.report.overlaps.length === 0 ? ["- No multi-agent topic overlap detected."] : crossSignals.report.overlaps.slice(0, 8).map((entry) => formatOverlapLine(entry));
|
|
549
|
+
const md = [
|
|
550
|
+
`# Roundtable \u2014 ${date}`,
|
|
551
|
+
"",
|
|
552
|
+
"## Notable Agent Outputs",
|
|
553
|
+
...crossSignals.report.sources.length === 0 ? ["- (none)"] : crossSignals.report.sources.map((source) => `- ${source.title} (${source.path})`),
|
|
554
|
+
"",
|
|
555
|
+
"## Feedback (Approve/Reject)",
|
|
556
|
+
...feedbackLines,
|
|
557
|
+
"",
|
|
558
|
+
"## Cross-Signals",
|
|
559
|
+
`- Source outputs analyzed: ${crossSignals.report.sourceCount}`,
|
|
560
|
+
`- Feedback entries analyzed: ${crossSignals.report.feedbackCount}`,
|
|
561
|
+
`- Decision totals: approved=${crossSignals.report.feedbackByDecision.approved}, approved_with_feedback=${crossSignals.report.feedbackByDecision.approved_with_feedback}, rejected=${crossSignals.report.feedbackByDecision.rejected}`,
|
|
562
|
+
`- Semantic enhancer: ${crossSignals.report.semantic.enabled ? crossSignals.report.semantic.timedOut ? "enabled (timed out, fail-open)" : crossSignals.report.semantic.applied ? "enabled (applied)" : "enabled (no additional overlaps)" : "disabled"}`,
|
|
563
|
+
`- Cross-signals JSON: ${crossSignals.crossSignalsPath}`,
|
|
564
|
+
`- Cross-signals markdown: ${crossSignals.crossSignalsMarkdownPath}`,
|
|
565
|
+
...overlapBullets,
|
|
566
|
+
""
|
|
567
|
+
];
|
|
568
|
+
const out = md.join("\n");
|
|
569
|
+
const trimmed = out.length > maxChars ? out.slice(0, maxChars) + "\n\n...(trimmed)\n" : out;
|
|
570
|
+
const roundtablePath = path.join(this.roundtableDir, `${date}.md`);
|
|
571
|
+
await writeFile(roundtablePath, trimmed, "utf-8");
|
|
572
|
+
log.info(`shared-context curated daily roundtable: ${roundtablePath}`);
|
|
573
|
+
return {
|
|
574
|
+
date,
|
|
575
|
+
roundtablePath,
|
|
576
|
+
crossSignalsPath: crossSignals.crossSignalsPath,
|
|
577
|
+
crossSignalsMarkdownPath: crossSignals.crossSignalsMarkdownPath,
|
|
578
|
+
overlapCount: crossSignals.overlapCount
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
|
|
583
|
+
// src/compounding/engine.ts
|
|
584
|
+
var COMPOUNDING_VERSION = 2;
|
|
585
|
+
var RETIREMENT_WINDOW_WEEKS = 8;
|
|
586
|
+
function stableSlug(value) {
|
|
587
|
+
return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "item";
|
|
588
|
+
}
|
|
589
|
+
function tokenizeRecallQuery(text) {
|
|
590
|
+
const seen = /* @__PURE__ */ new Set();
|
|
591
|
+
const out = [];
|
|
592
|
+
for (const token of text.toLowerCase().replace(/[^a-z0-9\s]+/g, " ").split(/\s+/).map((part) => part.trim()).filter((part) => part.length >= 3)) {
|
|
593
|
+
if (seen.has(token)) continue;
|
|
594
|
+
seen.add(token);
|
|
595
|
+
out.push(token);
|
|
596
|
+
}
|
|
597
|
+
return out;
|
|
598
|
+
}
|
|
599
|
+
function weekIdToIndex(weekId) {
|
|
600
|
+
const match = weekId.match(/^(\d{4})-W(\d{2})$/);
|
|
601
|
+
if (!match) return Number.POSITIVE_INFINITY;
|
|
602
|
+
const year = Number(match[1]);
|
|
603
|
+
const week = Number(match[2]);
|
|
604
|
+
if (!Number.isInteger(year) || !Number.isInteger(week) || week < 1 || week > 53) {
|
|
605
|
+
return Number.POSITIVE_INFINITY;
|
|
606
|
+
}
|
|
607
|
+
const jan4 = new Date(Date.UTC(year, 0, 4));
|
|
608
|
+
const jan4Day = jan4.getUTCDay() || 7;
|
|
609
|
+
const isoWeekOneStart = new Date(jan4);
|
|
610
|
+
isoWeekOneStart.setUTCDate(jan4.getUTCDate() - (jan4Day - 1));
|
|
611
|
+
const targetWeekStart = new Date(isoWeekOneStart);
|
|
612
|
+
targetWeekStart.setUTCDate(isoWeekOneStart.getUTCDate() + (week - 1) * 7);
|
|
613
|
+
return Math.floor(targetWeekStart.getTime() / (7 * 24 * 60 * 60 * 1e3));
|
|
614
|
+
}
|
|
615
|
+
function normalizeConfidence(value) {
|
|
616
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return null;
|
|
617
|
+
const clamped = Math.max(0, Math.min(1, value));
|
|
618
|
+
return Number(clamped.toFixed(3));
|
|
619
|
+
}
|
|
620
|
+
function normalizeTags(tags) {
|
|
621
|
+
if (!Array.isArray(tags)) return [];
|
|
622
|
+
return [...new Set(tags.map((tag) => String(tag).trim()).filter((tag) => tag.length > 0))].sort();
|
|
623
|
+
}
|
|
624
|
+
function normalizeEvidenceWindow(start, end) {
|
|
625
|
+
const safeStart = typeof start === "string" && start.trim().length > 0 ? start : null;
|
|
626
|
+
const safeEnd = typeof end === "string" && end.trim().length > 0 ? end : null;
|
|
627
|
+
return { start: safeStart, end: safeEnd };
|
|
628
|
+
}
|
|
629
|
+
function mergeEvidenceWindows(current, next) {
|
|
630
|
+
return {
|
|
631
|
+
start: current.start === null ? next.start : next.start === null ? current.start : current.start <= next.start ? current.start : next.start,
|
|
632
|
+
end: current.end === null ? next.end : next.end === null ? current.end : current.end >= next.end ? current.end : next.end
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
function stableMistakeId(category, pattern, agent, workflow) {
|
|
636
|
+
return [
|
|
637
|
+
category,
|
|
638
|
+
agent ? stableSlug(agent) : "global",
|
|
639
|
+
workflow ? stableSlug(workflow) : "default",
|
|
640
|
+
stableSlug(pattern).slice(0, 48)
|
|
641
|
+
].join(":");
|
|
642
|
+
}
|
|
643
|
+
function stableRubricId(kind, subject) {
|
|
644
|
+
return `${kind}:${stableSlug(subject)}`;
|
|
645
|
+
}
|
|
646
|
+
function stablePromotionCandidateId(sourceType, subject, content) {
|
|
647
|
+
const digest = createHash("sha256").update(`${sourceType}\0${subject}\0${content}`).digest("hex").slice(0, 12);
|
|
648
|
+
return `${sourceType}:${digest}`;
|
|
649
|
+
}
|
|
650
|
+
function rubricArtifactFileName(entry, slugCollisions) {
|
|
651
|
+
const slug = stableSlug(entry.subject);
|
|
652
|
+
if ((slugCollisions.get(slug) ?? 0) <= 1) return `${slug}.md`;
|
|
653
|
+
const suffix = createHash("sha256").update(`${entry.kind}:${entry.subject}`).digest("hex").slice(0, 8);
|
|
654
|
+
return `${slug}-${suffix}.md`;
|
|
655
|
+
}
|
|
656
|
+
function inferLegacyMistakeScope(pattern) {
|
|
657
|
+
const separatorIndex = pattern.indexOf(":");
|
|
658
|
+
if (separatorIndex <= 0) return { agent: null, workflow: null };
|
|
659
|
+
const subject = pattern.slice(0, separatorIndex).trim();
|
|
660
|
+
return {
|
|
661
|
+
agent: subject.length > 0 ? subject : null,
|
|
662
|
+
workflow: null
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
function inferLegacyMistakeMetadata(pattern) {
|
|
666
|
+
if (pattern.startsWith("memory-action/")) {
|
|
667
|
+
return {
|
|
668
|
+
category: "action",
|
|
669
|
+
agent: null,
|
|
670
|
+
workflow: "memory-actions"
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
const scope = inferLegacyMistakeScope(pattern);
|
|
674
|
+
return {
|
|
675
|
+
category: "feedback",
|
|
676
|
+
agent: scope.agent,
|
|
677
|
+
workflow: scope.workflow
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
function normalizePromotionWhitespace(value) {
|
|
681
|
+
return value.replace(/\s+/g, " ").trim();
|
|
682
|
+
}
|
|
683
|
+
function stripTrailingPromotionPunctuation(value) {
|
|
684
|
+
return value.replace(/[,:;]+$/g, "").trim();
|
|
685
|
+
}
|
|
686
|
+
function extractExplicitIfThenRule(value) {
|
|
687
|
+
const normalized = normalizePromotionWhitespace(value);
|
|
688
|
+
const match = normalized.match(/^if\b([\s\S]+?)\bthen\b([\s\S]+?)(?:[.!?])?$/i);
|
|
689
|
+
if (!match) return null;
|
|
690
|
+
const condition = stripTrailingPromotionPunctuation(normalizePromotionWhitespace(match[1] ?? ""));
|
|
691
|
+
const outcome = stripTrailingPromotionPunctuation(normalizePromotionWhitespace(match[2] ?? ""));
|
|
692
|
+
if (condition.length === 0 || outcome.length === 0) return null;
|
|
693
|
+
return `IF ${condition} THEN ${outcome}.`;
|
|
694
|
+
}
|
|
695
|
+
function normalizePromotedGuidanceContent(value) {
|
|
696
|
+
const explicitRule = extractExplicitIfThenRule(value);
|
|
697
|
+
if (explicitRule) return explicitRule;
|
|
698
|
+
const normalized = normalizePromotionWhitespace(value);
|
|
699
|
+
if (normalized.length === 0) return normalized;
|
|
700
|
+
return /[.!?]$/.test(normalized) ? normalized : `${normalized}.`;
|
|
701
|
+
}
|
|
702
|
+
function canonicalPromotionContentKey(value) {
|
|
703
|
+
return normalizePromotedGuidanceContent(value).toLowerCase();
|
|
704
|
+
}
|
|
705
|
+
function lessonContentFromPattern(pattern, agent) {
|
|
706
|
+
if (!agent) return normalizePromotionWhitespace(pattern);
|
|
707
|
+
const prefix = `${agent}:`;
|
|
708
|
+
if (!pattern.startsWith(prefix)) return normalizePromotionWhitespace(pattern);
|
|
709
|
+
const withoutPrefix = pattern.slice(prefix.length).trim();
|
|
710
|
+
return withoutPrefix.length > 0 ? normalizePromotionWhitespace(withoutPrefix) : normalizePromotionWhitespace(pattern);
|
|
711
|
+
}
|
|
712
|
+
function promotionCategoryForContent(content) {
|
|
713
|
+
return extractExplicitIfThenRule(content) ? "rule" : "principle";
|
|
714
|
+
}
|
|
715
|
+
function clampPromotionScore(value) {
|
|
716
|
+
if (!Number.isFinite(value)) return 0.65;
|
|
717
|
+
return Number(Math.max(0.65, Math.min(0.98, value)).toFixed(3));
|
|
718
|
+
}
|
|
719
|
+
function defaultTierMigrationCycleBudget(config, trigger) {
|
|
720
|
+
if (trigger === "extraction") {
|
|
721
|
+
const limit2 = 12;
|
|
722
|
+
return {
|
|
723
|
+
limit: limit2,
|
|
724
|
+
scanLimit: limit2 * 4,
|
|
725
|
+
minIntervalMs: 6e4
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
const limit = config.qmdTierAutoBackfillEnabled ? 200 : 50;
|
|
729
|
+
return {
|
|
730
|
+
limit,
|
|
731
|
+
scanLimit: limit * 4,
|
|
732
|
+
minIntervalMs: config.qmdTierAutoBackfillEnabled ? 12e4 : 3e5
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
function isoWeekId(d) {
|
|
736
|
+
const dt = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
|
737
|
+
const day = dt.getUTCDay() || 7;
|
|
738
|
+
dt.setUTCDate(dt.getUTCDate() + 4 - day);
|
|
739
|
+
const yearStart = new Date(Date.UTC(dt.getUTCFullYear(), 0, 1));
|
|
740
|
+
const week = Math.ceil(((dt.getTime() - yearStart.getTime()) / 864e5 + 1) / 7);
|
|
741
|
+
const yyyy = dt.getUTCFullYear();
|
|
742
|
+
return `${yyyy}-W${String(week).padStart(2, "0")}`;
|
|
743
|
+
}
|
|
744
|
+
function isoMonthId(d) {
|
|
745
|
+
return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}`;
|
|
746
|
+
}
|
|
747
|
+
function monthIdFromIsoWeek(weekId) {
|
|
748
|
+
const match = weekId.match(/^(\d{4})-W(\d{2})$/);
|
|
749
|
+
if (!match) return isoMonthId(/* @__PURE__ */ new Date());
|
|
750
|
+
const year = Number(match[1]);
|
|
751
|
+
const week = Number(match[2]);
|
|
752
|
+
const jan4 = new Date(Date.UTC(year, 0, 4));
|
|
753
|
+
const jan4Day = jan4.getUTCDay() || 7;
|
|
754
|
+
const isoWeekOneMonday = new Date(jan4);
|
|
755
|
+
isoWeekOneMonday.setUTCDate(jan4.getUTCDate() - (jan4Day - 1));
|
|
756
|
+
const monday = new Date(isoWeekOneMonday);
|
|
757
|
+
monday.setUTCDate(isoWeekOneMonday.getUTCDate() + (week - 1) * 7);
|
|
758
|
+
return isoMonthId(monday);
|
|
759
|
+
}
|
|
760
|
+
function sharedContextDir(config) {
|
|
761
|
+
if (typeof config.sharedContextDir === "string" && config.sharedContextDir.length > 0) {
|
|
762
|
+
return config.sharedContextDir;
|
|
763
|
+
}
|
|
764
|
+
return path2.join(os2.homedir(), ".openclaw", "workspace", "shared-context");
|
|
765
|
+
}
|
|
766
|
+
function cadenceStaleWindowMs(cadence) {
|
|
767
|
+
switch (cadence) {
|
|
768
|
+
case "daily":
|
|
769
|
+
return 2 * 24 * 60 * 60 * 1e3;
|
|
770
|
+
case "weekly":
|
|
771
|
+
return 10 * 24 * 60 * 60 * 1e3;
|
|
772
|
+
case "monthly":
|
|
773
|
+
return 45 * 24 * 60 * 60 * 1e3;
|
|
774
|
+
case "quarterly":
|
|
775
|
+
return 120 * 24 * 60 * 60 * 1e3;
|
|
776
|
+
default:
|
|
777
|
+
return 45 * 24 * 60 * 60 * 1e3;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
var CompoundingEngine = class {
|
|
781
|
+
constructor(config) {
|
|
782
|
+
this.config = config;
|
|
783
|
+
this.weeklyDir = path2.join(config.memoryDir, "compounding", "weekly");
|
|
784
|
+
this.rubricsDir = path2.join(config.memoryDir, "compounding", "rubrics");
|
|
785
|
+
this.rubricsIndexPath = path2.join(this.rubricsDir, "index.json");
|
|
786
|
+
this.rubricsAgentsDir = path2.join(this.rubricsDir, "agents");
|
|
787
|
+
this.rubricsWorkflowsDir = path2.join(this.rubricsDir, "workflows");
|
|
788
|
+
this.rubricsPath = path2.join(config.memoryDir, "compounding", "rubrics.md");
|
|
789
|
+
this.mistakesPath = path2.join(config.memoryDir, "compounding", "mistakes.json");
|
|
790
|
+
this.feedbackInboxPath = path2.join(sharedContextDir(config), "feedback", "inbox.jsonl");
|
|
791
|
+
this.identityAnchorPath = path2.join(config.memoryDir, "identity", "identity-anchor.md");
|
|
792
|
+
this.identityIncidentsDir = path2.join(config.memoryDir, "identity", "incidents");
|
|
793
|
+
this.identityAuditWeeklyDir = path2.join(config.memoryDir, "identity", "audits", "weekly");
|
|
794
|
+
this.identityAuditMonthlyDir = path2.join(config.memoryDir, "identity", "audits", "monthly");
|
|
795
|
+
this.identityImprovementLoopsPath = path2.join(config.memoryDir, "identity", "improvement-loops.md");
|
|
796
|
+
this.memoryActionEventsPath = path2.join(config.memoryDir, "state", "memory-actions.jsonl");
|
|
797
|
+
}
|
|
798
|
+
weeklyDir;
|
|
799
|
+
rubricsDir;
|
|
800
|
+
rubricsIndexPath;
|
|
801
|
+
rubricsAgentsDir;
|
|
802
|
+
rubricsWorkflowsDir;
|
|
803
|
+
rubricsPath;
|
|
804
|
+
mistakesPath;
|
|
805
|
+
feedbackInboxPath;
|
|
806
|
+
identityAnchorPath;
|
|
807
|
+
identityIncidentsDir;
|
|
808
|
+
identityAuditWeeklyDir;
|
|
809
|
+
identityAuditMonthlyDir;
|
|
810
|
+
identityImprovementLoopsPath;
|
|
811
|
+
memoryActionEventsPath;
|
|
812
|
+
async ensureDirs() {
|
|
813
|
+
await mkdir2(this.weeklyDir, { recursive: true });
|
|
814
|
+
await mkdir2(path2.dirname(this.mistakesPath), { recursive: true });
|
|
815
|
+
await mkdir2(path2.dirname(this.rubricsPath), { recursive: true });
|
|
816
|
+
await mkdir2(this.rubricsDir, { recursive: true });
|
|
817
|
+
await mkdir2(this.rubricsAgentsDir, { recursive: true });
|
|
818
|
+
await mkdir2(this.rubricsWorkflowsDir, { recursive: true });
|
|
819
|
+
}
|
|
820
|
+
async synthesizeWeekly(opts) {
|
|
821
|
+
await this.ensureDirs();
|
|
822
|
+
const weekId = opts?.weekId ?? isoWeekId(/* @__PURE__ */ new Date());
|
|
823
|
+
const entries = await this.readFeedbackEntriesForWeek(weekId);
|
|
824
|
+
const actionEvents = await this.readActionEventsForWeek(weekId);
|
|
825
|
+
const actionPatterns = this.buildActionFailurePatterns(actionEvents);
|
|
826
|
+
const outcomeSummary = this.buildActionOutcomeSummary(actionEvents);
|
|
827
|
+
const previousMistakes = await this.readMistakes();
|
|
828
|
+
const mistakes = this.buildMistakes(entries, actionPatterns, weekId, previousMistakes?.registry ?? []);
|
|
829
|
+
const rubrics = this.buildRubricSnapshot(entries, outcomeSummary);
|
|
830
|
+
const promotionCandidates = this.config.compoundingSemanticEnabled ? this.derivePromotionCandidates(outcomeSummary, mistakes.registry, rubrics) : [];
|
|
831
|
+
const continuity = this.config.continuityAuditEnabled ? await this.readContinuityAuditReferences(weekId) : { monthId: monthIdFromIsoWeek(weekId), weeklyPath: null, monthlyPath: null };
|
|
832
|
+
const reportPath = path2.join(this.weeklyDir, `${weekId}.md`);
|
|
833
|
+
const md = this.formatWeeklyReport(weekId, entries, mistakes.patterns, mistakes.details, continuity, outcomeSummary, promotionCandidates);
|
|
834
|
+
await writeFile2(reportPath, md, "utf-8");
|
|
835
|
+
const reportJsonPath = path2.join(this.weeklyDir, `${weekId}.json`);
|
|
836
|
+
const weeklyArtifact = {
|
|
837
|
+
version: COMPOUNDING_VERSION,
|
|
838
|
+
generatedAt: mistakes.updatedAt,
|
|
839
|
+
weekId,
|
|
840
|
+
feedback: {
|
|
841
|
+
count: entries.length,
|
|
842
|
+
byDecision: {
|
|
843
|
+
approved: entries.filter((wrapped) => wrapped.entry.decision === "approved").length,
|
|
844
|
+
approved_with_feedback: entries.filter((wrapped) => wrapped.entry.decision === "approved_with_feedback").length,
|
|
845
|
+
rejected: entries.filter((wrapped) => wrapped.entry.decision === "rejected").length
|
|
846
|
+
},
|
|
847
|
+
entries: entries.map((wrapped) => ({
|
|
848
|
+
agent: wrapped.entry.agent,
|
|
849
|
+
workflow: wrapped.entry.workflow ?? null,
|
|
850
|
+
decision: wrapped.entry.decision,
|
|
851
|
+
reason: wrapped.entry.reason,
|
|
852
|
+
learning: wrapped.entry.learning?.trim() || null,
|
|
853
|
+
outcome: wrapped.entry.outcome?.trim() || null,
|
|
854
|
+
severity: wrapped.entry.severity ?? null,
|
|
855
|
+
confidence: normalizeConfidence(wrapped.entry.confidence),
|
|
856
|
+
tags: normalizeTags(wrapped.entry.tags),
|
|
857
|
+
provenance: `${path2.basename(wrapped.sourcePath)}:L${wrapped.sourceLine}#${wrapped.entryId}`,
|
|
858
|
+
evidenceWindow: normalizeEvidenceWindow(wrapped.entry.evidenceWindowStart, wrapped.entry.evidenceWindowEnd)
|
|
859
|
+
}))
|
|
860
|
+
},
|
|
861
|
+
mistakes: {
|
|
862
|
+
count: mistakes.patterns.length,
|
|
863
|
+
patterns: mistakes.patterns,
|
|
864
|
+
registry: mistakes.registry
|
|
865
|
+
},
|
|
866
|
+
rubrics,
|
|
867
|
+
outcomes: outcomeSummary,
|
|
868
|
+
promotionCandidates,
|
|
869
|
+
continuity
|
|
870
|
+
};
|
|
871
|
+
await writeFile2(reportJsonPath, JSON.stringify(weeklyArtifact, null, 2) + "\n", "utf-8");
|
|
872
|
+
const rubricsMarkdown = this.formatRubrics(outcomeSummary, rubrics);
|
|
873
|
+
await writeFile2(this.rubricsPath, rubricsMarkdown, "utf-8");
|
|
874
|
+
await writeFile2(this.rubricsIndexPath, JSON.stringify(rubrics, null, 2) + "\n", "utf-8");
|
|
875
|
+
await this.syncRubricArtifacts(rubrics);
|
|
876
|
+
await writeFile2(
|
|
877
|
+
this.mistakesPath,
|
|
878
|
+
JSON.stringify({
|
|
879
|
+
version: COMPOUNDING_VERSION,
|
|
880
|
+
updatedAt: mistakes.updatedAt,
|
|
881
|
+
patterns: mistakes.patterns,
|
|
882
|
+
registry: mistakes.registry
|
|
883
|
+
}, null, 2) + "\n",
|
|
884
|
+
"utf-8"
|
|
885
|
+
);
|
|
886
|
+
log.info(
|
|
887
|
+
`compounding: wrote weekly=${reportPath} weeklyJson=${reportJsonPath} rubrics=${this.rubricsPath} rubricsIndex=${this.rubricsIndexPath} mistakes=${this.mistakesPath}`
|
|
888
|
+
);
|
|
889
|
+
return {
|
|
890
|
+
weekId,
|
|
891
|
+
reportPath,
|
|
892
|
+
reportJsonPath,
|
|
893
|
+
rubricsPath: this.rubricsPath,
|
|
894
|
+
rubricsIndexPath: this.rubricsIndexPath,
|
|
895
|
+
mistakesCount: mistakes.patterns.length,
|
|
896
|
+
promotionCandidateCount: promotionCandidates.length
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
async promoteCandidate(opts) {
|
|
900
|
+
const report = {
|
|
901
|
+
enabled: this.config.compoundingEnabled === true && this.config.compoundingSemanticEnabled === true,
|
|
902
|
+
dryRun: opts.dryRun === true,
|
|
903
|
+
weekId: opts.weekId,
|
|
904
|
+
promoted: [],
|
|
905
|
+
skipped: []
|
|
906
|
+
};
|
|
907
|
+
if (!report.enabled) {
|
|
908
|
+
report.skipped.push({ weekId: opts.weekId, candidateId: opts.candidateId, reason: "disabled" });
|
|
909
|
+
return report;
|
|
910
|
+
}
|
|
911
|
+
const artifact = await this.readWeeklyArtifact(opts.weekId);
|
|
912
|
+
if (!artifact) {
|
|
913
|
+
report.skipped.push({ weekId: opts.weekId, candidateId: opts.candidateId, reason: "weekly-artifact-missing" });
|
|
914
|
+
return report;
|
|
915
|
+
}
|
|
916
|
+
const candidate = artifact.promotionCandidates.find((entry) => entry.id === opts.candidateId);
|
|
917
|
+
if (!candidate) {
|
|
918
|
+
report.skipped.push({ weekId: opts.weekId, candidateId: opts.candidateId, reason: "candidate-not-found" });
|
|
919
|
+
return report;
|
|
920
|
+
}
|
|
921
|
+
const content = normalizePromotedGuidanceContent(candidate.content);
|
|
922
|
+
const persistedContent = sanitizeMemoryContent(content).text;
|
|
923
|
+
const storage = new StorageManager(this.config.memoryDir);
|
|
924
|
+
const existing = (await storage.readAllMemories()).find(
|
|
925
|
+
(memory) => memory.frontmatter.category === candidate.category && memory.frontmatter.status !== "archived" && canonicalPromotionContentKey(memory.content) === canonicalPromotionContentKey(persistedContent)
|
|
926
|
+
);
|
|
927
|
+
if (existing) {
|
|
928
|
+
report.skipped.push({
|
|
929
|
+
weekId: opts.weekId,
|
|
930
|
+
candidateId: opts.candidateId,
|
|
931
|
+
reason: "duplicate-guidance",
|
|
932
|
+
existingMemoryId: existing.frontmatter.id
|
|
933
|
+
});
|
|
934
|
+
return report;
|
|
935
|
+
}
|
|
936
|
+
const tags = [
|
|
937
|
+
"compounding",
|
|
938
|
+
"compounding-promotion",
|
|
939
|
+
`compounding-source-${candidate.sourceType}`,
|
|
940
|
+
...candidate.agent ? [`agent:${stableSlug(candidate.agent)}`] : [],
|
|
941
|
+
...candidate.workflow ? [`workflow:${stableSlug(candidate.workflow)}`] : []
|
|
942
|
+
];
|
|
943
|
+
const uniqueTags = [...new Set(tags)];
|
|
944
|
+
const lineage = [`compounding:${opts.weekId}:${opts.candidateId}`];
|
|
945
|
+
const confidence = clampPromotionScore(candidate.score);
|
|
946
|
+
if (opts.dryRun === true) {
|
|
947
|
+
report.promoted.push({
|
|
948
|
+
id: `dry-run:${opts.weekId}:${opts.candidateId}`,
|
|
949
|
+
candidateId: opts.candidateId,
|
|
950
|
+
category: candidate.category,
|
|
951
|
+
content: persistedContent,
|
|
952
|
+
confidence,
|
|
953
|
+
tags: uniqueTags,
|
|
954
|
+
lineage
|
|
955
|
+
});
|
|
956
|
+
return report;
|
|
957
|
+
}
|
|
958
|
+
const id = await storage.writeMemory(candidate.category, persistedContent, {
|
|
959
|
+
source: "compounding-promotion",
|
|
960
|
+
tags: uniqueTags,
|
|
961
|
+
confidence,
|
|
962
|
+
lineage,
|
|
963
|
+
memoryKind: "note"
|
|
964
|
+
});
|
|
965
|
+
report.promoted.push({
|
|
966
|
+
id,
|
|
967
|
+
candidateId: opts.candidateId,
|
|
968
|
+
category: candidate.category,
|
|
969
|
+
content: persistedContent,
|
|
970
|
+
confidence,
|
|
971
|
+
tags: uniqueTags,
|
|
972
|
+
lineage
|
|
973
|
+
});
|
|
974
|
+
return report;
|
|
975
|
+
}
|
|
976
|
+
async synthesizeContinuityAudit(opts) {
|
|
977
|
+
const period = opts?.period === "monthly" ? "monthly" : "weekly";
|
|
978
|
+
const key = opts?.key?.trim() || (period === "weekly" ? isoWeekId(/* @__PURE__ */ new Date()) : isoMonthId(/* @__PURE__ */ new Date()));
|
|
979
|
+
const nowIso = (/* @__PURE__ */ new Date()).toISOString();
|
|
980
|
+
const [anchorPresent, improvementLoopsRaw, openIncidents, closedIncidents, mistakes] = await Promise.all([
|
|
981
|
+
this.readNonEmptyFile(this.identityAnchorPath),
|
|
982
|
+
this.readOptionalFile(this.identityImprovementLoopsPath),
|
|
983
|
+
this.readContinuityIncidents(200, "open"),
|
|
984
|
+
this.readContinuityIncidents(200, "closed"),
|
|
985
|
+
this.readMistakes()
|
|
986
|
+
]);
|
|
987
|
+
const improvementLoops = improvementLoopsRaw ? parseContinuityImprovementLoops(improvementLoopsRaw) : [];
|
|
988
|
+
const activeLoops = improvementLoops.filter((loop) => loop.status === "active");
|
|
989
|
+
const staleActiveLoops = activeLoops.filter((loop) => {
|
|
990
|
+
const reviewedAt = Date.parse(loop.lastReviewed);
|
|
991
|
+
if (!Number.isFinite(reviewedAt)) return true;
|
|
992
|
+
return Date.now() - reviewedAt > cadenceStaleWindowMs(loop.cadence);
|
|
993
|
+
});
|
|
994
|
+
const hardeningCandidates = [];
|
|
995
|
+
if (!anchorPresent) {
|
|
996
|
+
hardeningCandidates.push("Create/update identity anchor baseline and verify recovery injection path.");
|
|
997
|
+
}
|
|
998
|
+
if (openIncidents.length > 0) {
|
|
999
|
+
hardeningCandidates.push(
|
|
1000
|
+
`Close or downgrade ${openIncidents.length} open continuity incident${openIncidents.length === 1 ? "" : "s"}.`
|
|
1001
|
+
);
|
|
1002
|
+
}
|
|
1003
|
+
if (improvementLoops.length === 0) {
|
|
1004
|
+
hardeningCandidates.push("Initialize continuity improvement-loops register with cadence and kill conditions.");
|
|
1005
|
+
} else if (staleActiveLoops.length > 0) {
|
|
1006
|
+
hardeningCandidates.push(
|
|
1007
|
+
`Review stale active continuity loop${staleActiveLoops.length === 1 ? "" : "s"}: ${staleActiveLoops.slice(0, 3).map((loop) => loop.id).join(", ")}.`
|
|
1008
|
+
);
|
|
1009
|
+
}
|
|
1010
|
+
if ((mistakes?.patterns.length ?? 0) > 0) {
|
|
1011
|
+
hardeningCandidates.push("Review latest compounding mistakes and convert one pattern into preventive continuity rule.");
|
|
1012
|
+
}
|
|
1013
|
+
const nextAction = hardeningCandidates[0] ?? "No critical drift detected; keep weekly/monthly continuity audit cadence.";
|
|
1014
|
+
const lines = [
|
|
1015
|
+
`# Continuity Audit \u2014 ${period} ${key}`,
|
|
1016
|
+
"",
|
|
1017
|
+
`Generated: ${nowIso}`,
|
|
1018
|
+
`Scope: ${period}`,
|
|
1019
|
+
"",
|
|
1020
|
+
"## Signal Summary",
|
|
1021
|
+
`- Identity anchor present: ${anchorPresent ? "yes" : "no"}`,
|
|
1022
|
+
`- Improvement loops tracked: ${improvementLoops.length}`,
|
|
1023
|
+
`- Active improvement loops: ${activeLoops.length}`,
|
|
1024
|
+
`- Stale active loops: ${staleActiveLoops.length}`,
|
|
1025
|
+
`- Open incidents: ${openIncidents.length}`,
|
|
1026
|
+
`- Closed incidents: ${closedIncidents.length}`,
|
|
1027
|
+
`- Compounding mistake patterns: ${mistakes?.patterns.length ?? 0}`,
|
|
1028
|
+
"",
|
|
1029
|
+
"## Drift Checks",
|
|
1030
|
+
`- Identity anchor drift: ${anchorPresent ? "pass" : "needs attention"}`,
|
|
1031
|
+
`- Incident backlog: ${openIncidents.length === 0 ? "pass" : "needs attention"}`,
|
|
1032
|
+
`- Improvement-loop coverage: ${improvementLoops.length > 0 ? "pass" : "needs attention"}`,
|
|
1033
|
+
`- Improvement-loop freshness: ${staleActiveLoops.length === 0 ? "pass" : "needs attention"}`,
|
|
1034
|
+
"",
|
|
1035
|
+
"## Stale Rule Detection",
|
|
1036
|
+
`- Open incidents older than closure window: ${openIncidents.length > 0 ? "possible" : "none detected"}`,
|
|
1037
|
+
`- Stale active continuity loops: ${staleActiveLoops.length > 0 ? staleActiveLoops.map((l) => l.id).join(", ") : "none detected"}`,
|
|
1038
|
+
`- Preventive rule coverage on closed incidents: ${closedIncidents.some((i) => (i.preventiveRule ?? "").trim().length > 0) ? "present" : "not detected"}`,
|
|
1039
|
+
"",
|
|
1040
|
+
"## Next Hardening Action",
|
|
1041
|
+
`- ${nextAction}`,
|
|
1042
|
+
"",
|
|
1043
|
+
"## Open Incident IDs",
|
|
1044
|
+
...openIncidents.length > 0 ? openIncidents.slice(0, 20).map((i) => `- ${i.id}`) : ["- (none)"],
|
|
1045
|
+
""
|
|
1046
|
+
];
|
|
1047
|
+
const dir = period === "weekly" ? this.identityAuditWeeklyDir : this.identityAuditMonthlyDir;
|
|
1048
|
+
await mkdir2(dir, { recursive: true });
|
|
1049
|
+
const reportPath = path2.join(dir, `${key}.md`);
|
|
1050
|
+
await writeFile2(reportPath, lines.join("\n"), "utf-8");
|
|
1051
|
+
return { period, key, reportPath };
|
|
1052
|
+
}
|
|
1053
|
+
async readMistakes() {
|
|
1054
|
+
try {
|
|
1055
|
+
const raw = await readFile2(this.mistakesPath, "utf-8");
|
|
1056
|
+
const parsed = JSON.parse(raw);
|
|
1057
|
+
if (!parsed || !Array.isArray(parsed.patterns)) return null;
|
|
1058
|
+
if (!Array.isArray(parsed.registry)) {
|
|
1059
|
+
const updatedAt = typeof parsed.updatedAt === "string" && parsed.updatedAt.length > 0 ? parsed.updatedAt : (/* @__PURE__ */ new Date(0)).toISOString();
|
|
1060
|
+
parsed.registry = parsed.patterns.map((pattern) => {
|
|
1061
|
+
const metadata = inferLegacyMistakeMetadata(pattern);
|
|
1062
|
+
return {
|
|
1063
|
+
id: stableMistakeId(metadata.category, pattern, metadata.agent, metadata.workflow),
|
|
1064
|
+
pattern,
|
|
1065
|
+
category: metadata.category,
|
|
1066
|
+
status: "active",
|
|
1067
|
+
agent: metadata.agent,
|
|
1068
|
+
workflow: metadata.workflow,
|
|
1069
|
+
tags: [],
|
|
1070
|
+
severity: null,
|
|
1071
|
+
confidence: null,
|
|
1072
|
+
outcome: null,
|
|
1073
|
+
provenance: [],
|
|
1074
|
+
firstSeenAt: updatedAt,
|
|
1075
|
+
lastSeenAt: updatedAt,
|
|
1076
|
+
recurrenceCount: 1,
|
|
1077
|
+
lastWeekId: isoWeekId(new Date(updatedAt)),
|
|
1078
|
+
evidenceWindow: { start: null, end: null }
|
|
1079
|
+
};
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
return parsed;
|
|
1083
|
+
} catch {
|
|
1084
|
+
return null;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
async readRubrics() {
|
|
1088
|
+
try {
|
|
1089
|
+
const raw = await readFile2(this.rubricsIndexPath, "utf-8");
|
|
1090
|
+
const parsed = JSON.parse(raw);
|
|
1091
|
+
if (!parsed || !Array.isArray(parsed.agents) || !Array.isArray(parsed.workflows)) return null;
|
|
1092
|
+
parsed.agents = parsed.agents.map((entry) => this.normalizeRubricEntry(entry));
|
|
1093
|
+
parsed.workflows = parsed.workflows.map((entry) => this.normalizeRubricEntry(entry));
|
|
1094
|
+
return parsed;
|
|
1095
|
+
} catch {
|
|
1096
|
+
return null;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
async readWeeklyArtifact(weekId) {
|
|
1100
|
+
try {
|
|
1101
|
+
const raw = await readFile2(path2.join(this.weeklyDir, `${weekId}.json`), "utf-8");
|
|
1102
|
+
const parsed = JSON.parse(raw);
|
|
1103
|
+
if (!parsed || parsed.weekId !== weekId || !Array.isArray(parsed.promotionCandidates)) {
|
|
1104
|
+
return null;
|
|
1105
|
+
}
|
|
1106
|
+
return parsed;
|
|
1107
|
+
} catch {
|
|
1108
|
+
return null;
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
async buildRecallSection(query, opts) {
|
|
1112
|
+
const [mistakes, rubrics] = await Promise.all([
|
|
1113
|
+
this.readMistakes(),
|
|
1114
|
+
this.readRubrics()
|
|
1115
|
+
]);
|
|
1116
|
+
const maxPatterns = Math.max(0, Math.floor(opts?.maxPatterns ?? 40));
|
|
1117
|
+
const maxRubrics = Math.max(0, Math.floor(opts?.maxRubrics ?? 4));
|
|
1118
|
+
const queryTokens = tokenizeRecallQuery(query);
|
|
1119
|
+
const activePatterns = (mistakes?.registry ?? []).filter((entry) => entry.status === "active").sort(
|
|
1120
|
+
(a, b) => b.recurrenceCount - a.recurrenceCount || b.lastSeenAt.localeCompare(a.lastSeenAt) || a.pattern.localeCompare(b.pattern)
|
|
1121
|
+
);
|
|
1122
|
+
const topPatterns = activePatterns.slice(0, maxPatterns);
|
|
1123
|
+
const allRubrics = [
|
|
1124
|
+
...rubrics?.workflows ?? [],
|
|
1125
|
+
...rubrics?.agents ?? []
|
|
1126
|
+
];
|
|
1127
|
+
const scoredRubrics = allRubrics.map((entry) => ({
|
|
1128
|
+
entry,
|
|
1129
|
+
score: this.scoreRubricForQuery(entry, queryTokens)
|
|
1130
|
+
})).sort(
|
|
1131
|
+
(a, b) => b.score - a.score || b.entry.observations.length - a.entry.observations.length || a.entry.subject.localeCompare(b.entry.subject)
|
|
1132
|
+
);
|
|
1133
|
+
const topRubrics = scoredRubrics.filter((item) => item.score > 0 || queryTokens.length === 0).slice(0, maxRubrics).map((item) => item.entry);
|
|
1134
|
+
if (topPatterns.length === 0 && topRubrics.length === 0) return null;
|
|
1135
|
+
const lines = [
|
|
1136
|
+
"## Institutional Learning (Compounded)",
|
|
1137
|
+
""
|
|
1138
|
+
];
|
|
1139
|
+
if (topPatterns.length > 0) {
|
|
1140
|
+
lines.push("Avoid repeating these patterns:");
|
|
1141
|
+
for (const entry of topPatterns) {
|
|
1142
|
+
const scope = entry.workflow ?? entry.agent ?? null;
|
|
1143
|
+
const metadata = [`recurrence=${entry.recurrenceCount}`];
|
|
1144
|
+
if (scope) metadata.push(`scope=${scope}`);
|
|
1145
|
+
lines.push(`- ${entry.pattern} _(${metadata.join(", ")})_`);
|
|
1146
|
+
}
|
|
1147
|
+
lines.push("");
|
|
1148
|
+
}
|
|
1149
|
+
if (topRubrics.length > 0) {
|
|
1150
|
+
lines.push("Active rubrics:");
|
|
1151
|
+
for (const rubric of topRubrics) {
|
|
1152
|
+
const notes = rubric.observations.slice(0, 2).join("; ");
|
|
1153
|
+
lines.push(`- ${rubric.kind} ${rubric.subject}: ${notes}`);
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
return lines.join("\n");
|
|
1157
|
+
}
|
|
1158
|
+
tierMigrationCycleBudget(trigger) {
|
|
1159
|
+
return defaultTierMigrationCycleBudget(this.config, trigger);
|
|
1160
|
+
}
|
|
1161
|
+
async readFeedbackEntriesForWeek(weekId) {
|
|
1162
|
+
const out = [];
|
|
1163
|
+
try {
|
|
1164
|
+
const raw = await readFile2(this.feedbackInboxPath, "utf-8");
|
|
1165
|
+
const lines = raw.split("\n");
|
|
1166
|
+
for (let idx = 0; idx < lines.length; idx += 1) {
|
|
1167
|
+
const line = lines[idx];
|
|
1168
|
+
if (!line.trim()) continue;
|
|
1169
|
+
try {
|
|
1170
|
+
const obj = JSON.parse(line);
|
|
1171
|
+
const parsed = SharedFeedbackEntrySchema.safeParse(obj);
|
|
1172
|
+
if (!parsed.success) continue;
|
|
1173
|
+
const d = new Date(parsed.data.date);
|
|
1174
|
+
if (!Number.isFinite(d.getTime())) continue;
|
|
1175
|
+
if (isoWeekId(d) !== weekId) continue;
|
|
1176
|
+
const sourceLine = idx + 1;
|
|
1177
|
+
out.push({
|
|
1178
|
+
entry: parsed.data,
|
|
1179
|
+
sourceLine,
|
|
1180
|
+
sourcePath: this.feedbackInboxPath,
|
|
1181
|
+
entryId: `${parsed.data.agent}-${parsed.data.date}-${sourceLine}`.replace(/[^a-zA-Z0-9._:-]/g, "_")
|
|
1182
|
+
});
|
|
1183
|
+
} catch {
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
} catch {
|
|
1187
|
+
}
|
|
1188
|
+
return out;
|
|
1189
|
+
}
|
|
1190
|
+
buildActionFailurePatterns(events) {
|
|
1191
|
+
const out = [];
|
|
1192
|
+
for (const event of events) {
|
|
1193
|
+
const failed = event.outcome === "failed" || event.outcome === "skipped";
|
|
1194
|
+
if (!failed && event.policyDecision === null) continue;
|
|
1195
|
+
const suffix = event.reason && event.reason.trim().length > 0 ? ` - ${event.reason.trim().slice(0, 140)}` : "";
|
|
1196
|
+
out.push(
|
|
1197
|
+
`memory-action/${event.namespace}: ${event.action} ${event.outcome}${event.policyDecision ? `/${event.policyDecision}` : ""}${suffix}`
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1200
|
+
return out;
|
|
1201
|
+
}
|
|
1202
|
+
async readActionEventsForWeek(weekId) {
|
|
1203
|
+
const out = [];
|
|
1204
|
+
try {
|
|
1205
|
+
const raw = await readFile2(this.memoryActionEventsPath, "utf-8");
|
|
1206
|
+
const lines = raw.split("\n");
|
|
1207
|
+
for (let idx = 0; idx < lines.length; idx += 1) {
|
|
1208
|
+
const line = lines[idx];
|
|
1209
|
+
if (!line.trim()) continue;
|
|
1210
|
+
try {
|
|
1211
|
+
const parsed = JSON.parse(line);
|
|
1212
|
+
if (typeof parsed.timestamp !== "string" || typeof parsed.action !== "string") continue;
|
|
1213
|
+
const ts = new Date(parsed.timestamp);
|
|
1214
|
+
if (!Number.isFinite(ts.getTime()) || isoWeekId(ts) !== weekId) continue;
|
|
1215
|
+
out.push({
|
|
1216
|
+
line: idx + 1,
|
|
1217
|
+
action: parsed.action,
|
|
1218
|
+
outcome: parsed.outcome === "applied" || parsed.outcome === "skipped" || parsed.outcome === "failed" ? parsed.outcome : "unknown",
|
|
1219
|
+
policyDecision: parsed.policyDecision === "deny" || parsed.policyDecision === "defer" ? parsed.policyDecision : null,
|
|
1220
|
+
namespace: typeof parsed.namespace === "string" && parsed.namespace.length > 0 ? parsed.namespace : "default",
|
|
1221
|
+
reason: typeof parsed.reason === "string" ? parsed.reason : null
|
|
1222
|
+
});
|
|
1223
|
+
} catch {
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
} catch {
|
|
1227
|
+
}
|
|
1228
|
+
return out;
|
|
1229
|
+
}
|
|
1230
|
+
buildActionOutcomeSummary(events) {
|
|
1231
|
+
const byAction = /* @__PURE__ */ new Map();
|
|
1232
|
+
for (const event of events) {
|
|
1233
|
+
const key = event.action;
|
|
1234
|
+
const acc = byAction.get(key) ?? {
|
|
1235
|
+
counts: { applied: 0, skipped: 0, failed: 0, unknown: 0 },
|
|
1236
|
+
provenance: /* @__PURE__ */ new Set()
|
|
1237
|
+
};
|
|
1238
|
+
if (event.outcome === "applied") acc.counts.applied += 1;
|
|
1239
|
+
else if (event.outcome === "skipped") acc.counts.skipped += 1;
|
|
1240
|
+
else if (event.outcome === "failed") acc.counts.failed += 1;
|
|
1241
|
+
else acc.counts.unknown += 1;
|
|
1242
|
+
acc.provenance.add(`${path2.basename(this.memoryActionEventsPath)}:L${event.line}`);
|
|
1243
|
+
byAction.set(key, acc);
|
|
1244
|
+
}
|
|
1245
|
+
const out = [];
|
|
1246
|
+
for (const [action, data] of byAction.entries()) {
|
|
1247
|
+
const total = data.counts.applied + data.counts.skipped + data.counts.failed + data.counts.unknown;
|
|
1248
|
+
if (total <= 0) continue;
|
|
1249
|
+
const weightedScore = Number(((data.counts.applied * 1 - data.counts.skipped * 0.5 - data.counts.failed * 1.5) / total).toFixed(3));
|
|
1250
|
+
out.push({
|
|
1251
|
+
action,
|
|
1252
|
+
counts: data.counts,
|
|
1253
|
+
total,
|
|
1254
|
+
weightedScore,
|
|
1255
|
+
provenance: [...data.provenance].sort().slice(0, 8)
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
out.sort((a, b) => b.total - a.total || b.weightedScore - a.weightedScore || a.action.localeCompare(b.action));
|
|
1259
|
+
return out;
|
|
1260
|
+
}
|
|
1261
|
+
derivePromotionCandidates(summary, mistakes, rubrics) {
|
|
1262
|
+
const deduped = /* @__PURE__ */ new Map();
|
|
1263
|
+
const upsert = (candidate) => {
|
|
1264
|
+
const key = `${candidate.category}:${canonicalPromotionContentKey(candidate.content)}`;
|
|
1265
|
+
const existing = deduped.get(key);
|
|
1266
|
+
if (!existing) {
|
|
1267
|
+
deduped.set(key, candidate);
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
const mergedProvenance = [.../* @__PURE__ */ new Set([...existing.provenance, ...candidate.provenance])];
|
|
1271
|
+
if (candidate.score > existing.score) {
|
|
1272
|
+
deduped.set(key, {
|
|
1273
|
+
...candidate,
|
|
1274
|
+
provenance: mergedProvenance
|
|
1275
|
+
});
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
1278
|
+
existing.provenance = mergedProvenance;
|
|
1279
|
+
};
|
|
1280
|
+
for (const item of summary) {
|
|
1281
|
+
if (item.total < 3) continue;
|
|
1282
|
+
if (item.weightedScore < 0.3) continue;
|
|
1283
|
+
const content = normalizePromotedGuidanceContent(
|
|
1284
|
+
`Prefer ${item.action} when the same workflow recurs; this week's outcomes were applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}, unknown=${item.counts.unknown}.`
|
|
1285
|
+
);
|
|
1286
|
+
upsert({
|
|
1287
|
+
id: stablePromotionCandidateId("action-outcome", item.action, content),
|
|
1288
|
+
sourceType: "action-outcome",
|
|
1289
|
+
subject: item.action,
|
|
1290
|
+
category: promotionCategoryForContent(content),
|
|
1291
|
+
content,
|
|
1292
|
+
score: item.weightedScore,
|
|
1293
|
+
rationale: "High applied ratio with low failure/skips in weekly outcome telemetry.",
|
|
1294
|
+
outcome: item.counts,
|
|
1295
|
+
provenance: item.provenance,
|
|
1296
|
+
agent: null,
|
|
1297
|
+
workflow: "memory-actions"
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
for (const entry of mistakes) {
|
|
1301
|
+
if (entry.status !== "active") continue;
|
|
1302
|
+
if (entry.recurrenceCount < 2) continue;
|
|
1303
|
+
const content = normalizePromotedGuidanceContent(lessonContentFromPattern(entry.pattern, entry.agent));
|
|
1304
|
+
if (content.length === 0) continue;
|
|
1305
|
+
const confidence = entry.confidence ?? 0.75;
|
|
1306
|
+
const score = Number(Math.min(0.97, 0.45 + Math.min(entry.recurrenceCount, 6) * 0.08 + confidence * 0.15).toFixed(3));
|
|
1307
|
+
upsert({
|
|
1308
|
+
id: stablePromotionCandidateId("mistake-pattern", entry.id, content),
|
|
1309
|
+
sourceType: "mistake-pattern",
|
|
1310
|
+
subject: entry.pattern,
|
|
1311
|
+
category: promotionCategoryForContent(content),
|
|
1312
|
+
content,
|
|
1313
|
+
score,
|
|
1314
|
+
rationale: `Recurring lesson still active after ${entry.recurrenceCount} confirmations in the mistake registry.`,
|
|
1315
|
+
outcome: null,
|
|
1316
|
+
provenance: entry.provenance.length > 0 ? entry.provenance : [`mistakes.json#${entry.id}`],
|
|
1317
|
+
agent: entry.agent,
|
|
1318
|
+
workflow: entry.workflow
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
for (const rubric of [...rubrics.workflows, ...rubrics.agents]) {
|
|
1322
|
+
for (const observation of this.getRubricObservationEntries(rubric)) {
|
|
1323
|
+
if (this.isSyntheticOutcomeRubricObservation(observation.note)) continue;
|
|
1324
|
+
const evidenceCount = observation.provenance.length;
|
|
1325
|
+
if (evidenceCount < 2) continue;
|
|
1326
|
+
const content = normalizePromotedGuidanceContent(observation.note);
|
|
1327
|
+
if (content.length === 0) continue;
|
|
1328
|
+
const score = Number(Math.min(0.95, 0.5 + Math.min(evidenceCount, 5) * 0.08).toFixed(3));
|
|
1329
|
+
upsert({
|
|
1330
|
+
id: stablePromotionCandidateId("rubric", `${rubric.id}:${observation.note}`, content),
|
|
1331
|
+
sourceType: "rubric",
|
|
1332
|
+
subject: `${rubric.kind}:${rubric.subject}`,
|
|
1333
|
+
category: promotionCategoryForContent(content),
|
|
1334
|
+
content,
|
|
1335
|
+
score,
|
|
1336
|
+
rationale: `Rubric guidance repeated across ${evidenceCount} supporting observations.`,
|
|
1337
|
+
outcome: null,
|
|
1338
|
+
provenance: observation.provenance,
|
|
1339
|
+
agent: rubric.kind === "agent" ? rubric.subject : null,
|
|
1340
|
+
workflow: rubric.kind === "workflow" ? rubric.subject : null
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
return [...deduped.values()].sort((a, b) => b.score - a.score || a.subject.localeCompare(b.subject)).slice(0, 10);
|
|
1345
|
+
}
|
|
1346
|
+
buildMistakes(entries, actionPatterns = [], weekId, previousRegistry = []) {
|
|
1347
|
+
const patterns = [];
|
|
1348
|
+
const evidenceByPattern = /* @__PURE__ */ new Map();
|
|
1349
|
+
for (const wrapped of entries) {
|
|
1350
|
+
const e = wrapped.entry;
|
|
1351
|
+
const pattern = e.learning && e.learning.trim().length > 0 ? `${e.agent}: ${e.learning.trim()}` : e.decision === "rejected" ? `${e.agent}: ${e.reason.trim()}`.slice(0, 240) : null;
|
|
1352
|
+
if (!pattern) continue;
|
|
1353
|
+
const provenance = [`${path2.basename(wrapped.sourcePath)}:L${wrapped.sourceLine}#${wrapped.entryId}`];
|
|
1354
|
+
patterns.push({ pattern, provenance });
|
|
1355
|
+
const previous = evidenceByPattern.get(pattern) ?? {
|
|
1356
|
+
category: "feedback",
|
|
1357
|
+
agent: e.agent,
|
|
1358
|
+
workflow: e.workflow ?? null,
|
|
1359
|
+
tags: /* @__PURE__ */ new Set(),
|
|
1360
|
+
severity: e.severity ?? null,
|
|
1361
|
+
confidence: normalizeConfidence(e.confidence),
|
|
1362
|
+
outcome: e.outcome?.trim() || null,
|
|
1363
|
+
timestamps: [],
|
|
1364
|
+
evidenceWindow: normalizeEvidenceWindow(e.evidenceWindowStart, e.evidenceWindowEnd)
|
|
1365
|
+
};
|
|
1366
|
+
for (const tag of normalizeTags(e.tags)) previous.tags.add(tag);
|
|
1367
|
+
previous.timestamps.push(e.date);
|
|
1368
|
+
if (previous.workflow === null && e.workflow) previous.workflow = e.workflow;
|
|
1369
|
+
if (previous.severity === null && e.severity) previous.severity = e.severity;
|
|
1370
|
+
if (previous.confidence === null) previous.confidence = normalizeConfidence(e.confidence);
|
|
1371
|
+
if (previous.outcome === null && e.outcome) previous.outcome = e.outcome.trim();
|
|
1372
|
+
const nextEvidenceWindow = normalizeEvidenceWindow(e.evidenceWindowStart, e.evidenceWindowEnd);
|
|
1373
|
+
previous.evidenceWindow = mergeEvidenceWindows(previous.evidenceWindow, nextEvidenceWindow);
|
|
1374
|
+
evidenceByPattern.set(pattern, previous);
|
|
1375
|
+
}
|
|
1376
|
+
for (const pattern of actionPatterns) {
|
|
1377
|
+
patterns.push({ pattern, provenance: [`${path2.basename(this.memoryActionEventsPath)}:*`] });
|
|
1378
|
+
const previous = evidenceByPattern.get(pattern) ?? {
|
|
1379
|
+
category: "action",
|
|
1380
|
+
agent: null,
|
|
1381
|
+
workflow: "memory-actions",
|
|
1382
|
+
tags: /* @__PURE__ */ new Set(),
|
|
1383
|
+
severity: "medium",
|
|
1384
|
+
confidence: null,
|
|
1385
|
+
outcome: null,
|
|
1386
|
+
timestamps: [],
|
|
1387
|
+
evidenceWindow: { start: null, end: null }
|
|
1388
|
+
};
|
|
1389
|
+
evidenceByPattern.set(pattern, previous);
|
|
1390
|
+
}
|
|
1391
|
+
const byPattern = /* @__PURE__ */ new Map();
|
|
1392
|
+
for (const item of patterns) {
|
|
1393
|
+
const existing = byPattern.get(item.pattern) ?? /* @__PURE__ */ new Set();
|
|
1394
|
+
for (const provenance of item.provenance) existing.add(provenance);
|
|
1395
|
+
byPattern.set(item.pattern, existing);
|
|
1396
|
+
}
|
|
1397
|
+
const details = [...byPattern.entries()].map(([pattern, provenance]) => ({ pattern, provenance: [...provenance].sort() })).slice(0, 500);
|
|
1398
|
+
const previousById = new Map(previousRegistry.map((entry) => [entry.id, entry]));
|
|
1399
|
+
const previousByPattern = new Map(previousRegistry.map((entry) => [entry.pattern, entry]));
|
|
1400
|
+
const registry = details.map((detail) => {
|
|
1401
|
+
const evidence = evidenceByPattern.get(detail.pattern);
|
|
1402
|
+
const id = stableMistakeId(
|
|
1403
|
+
evidence?.category ?? "feedback",
|
|
1404
|
+
detail.pattern,
|
|
1405
|
+
evidence?.agent ?? null,
|
|
1406
|
+
evidence?.workflow ?? null
|
|
1407
|
+
);
|
|
1408
|
+
const previous = previousById.get(id) ?? previousByPattern.get(detail.pattern);
|
|
1409
|
+
const timestamps = (evidence?.timestamps ?? []).filter((value) => typeof value === "string" && value.length > 0).sort();
|
|
1410
|
+
const firstSeenAt = previous?.firstSeenAt ?? timestamps[0] ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1411
|
+
const lastSeenAt = timestamps[timestamps.length - 1] ?? previous?.lastSeenAt ?? firstSeenAt;
|
|
1412
|
+
return {
|
|
1413
|
+
id,
|
|
1414
|
+
pattern: detail.pattern,
|
|
1415
|
+
category: evidence?.category ?? "feedback",
|
|
1416
|
+
status: "active",
|
|
1417
|
+
agent: evidence?.agent ?? null,
|
|
1418
|
+
workflow: evidence?.workflow ?? null,
|
|
1419
|
+
tags: evidence ? [...evidence.tags].sort() : [],
|
|
1420
|
+
severity: evidence?.severity ?? null,
|
|
1421
|
+
confidence: evidence?.confidence ?? null,
|
|
1422
|
+
outcome: evidence?.outcome ?? null,
|
|
1423
|
+
provenance: detail.provenance,
|
|
1424
|
+
firstSeenAt,
|
|
1425
|
+
lastSeenAt,
|
|
1426
|
+
recurrenceCount: previous?.lastWeekId === weekId ? previous.recurrenceCount : (previous?.recurrenceCount ?? 0) + 1,
|
|
1427
|
+
lastWeekId: weekId,
|
|
1428
|
+
evidenceWindow: evidence?.evidenceWindow ?? { start: null, end: null },
|
|
1429
|
+
retiredAt: null
|
|
1430
|
+
};
|
|
1431
|
+
});
|
|
1432
|
+
const seenIds = new Set(registry.map((entry) => entry.id));
|
|
1433
|
+
const seenPatterns = new Set(registry.map((entry) => entry.pattern));
|
|
1434
|
+
for (const previous of previousRegistry) {
|
|
1435
|
+
if (seenIds.has(previous.id) || seenPatterns.has(previous.pattern)) continue;
|
|
1436
|
+
const staleWeeks = weekIdToIndex(weekId) - weekIdToIndex(previous.lastWeekId);
|
|
1437
|
+
registry.push({
|
|
1438
|
+
...previous,
|
|
1439
|
+
status: staleWeeks >= RETIREMENT_WINDOW_WEEKS ? "retired" : previous.status,
|
|
1440
|
+
retiredAt: staleWeeks >= RETIREMENT_WINDOW_WEEKS ? previous.retiredAt ?? (/* @__PURE__ */ new Date()).toISOString() : previous.retiredAt ?? null
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
registry.sort(
|
|
1444
|
+
(a, b) => Number(b.status === "active") - Number(a.status === "active") || b.recurrenceCount - a.recurrenceCount || b.lastSeenAt.localeCompare(a.lastSeenAt) || a.pattern.localeCompare(b.pattern)
|
|
1445
|
+
);
|
|
1446
|
+
return {
|
|
1447
|
+
version: COMPOUNDING_VERSION,
|
|
1448
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1449
|
+
patterns: details.map((d) => d.pattern),
|
|
1450
|
+
details,
|
|
1451
|
+
registry
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
formatWeeklyReport(weekId, entries, patterns, patternDetails, continuity, outcomeSummary, promotionCandidates) {
|
|
1455
|
+
const byAgent = /* @__PURE__ */ new Map();
|
|
1456
|
+
for (const wrapped of entries) {
|
|
1457
|
+
const list = byAgent.get(wrapped.entry.agent) ?? [];
|
|
1458
|
+
list.push(wrapped);
|
|
1459
|
+
byAgent.set(wrapped.entry.agent, list);
|
|
1460
|
+
}
|
|
1461
|
+
const lines = [
|
|
1462
|
+
`# Weekly Compounding \u2014 ${weekId}`,
|
|
1463
|
+
"",
|
|
1464
|
+
"This file is generated by Engram's compounding engine (v5.0).",
|
|
1465
|
+
"",
|
|
1466
|
+
"## Summary",
|
|
1467
|
+
`- Feedback entries: ${entries.length}`,
|
|
1468
|
+
`- Mistake patterns: ${patterns.length}`,
|
|
1469
|
+
"",
|
|
1470
|
+
"## By Agent"
|
|
1471
|
+
];
|
|
1472
|
+
if (byAgent.size === 0) {
|
|
1473
|
+
lines.push("- (none)");
|
|
1474
|
+
} else {
|
|
1475
|
+
for (const [agent, list] of Array.from(byAgent.entries()).sort((a, b) => a[0].localeCompare(b[0]))) {
|
|
1476
|
+
const approved = list.filter((e) => e.entry.decision === "approved").length;
|
|
1477
|
+
const awf = list.filter((e) => e.entry.decision === "approved_with_feedback").length;
|
|
1478
|
+
const rejected = list.filter((e) => e.entry.decision === "rejected").length;
|
|
1479
|
+
lines.push(`### ${agent}`);
|
|
1480
|
+
lines.push(`- approved: ${approved}`);
|
|
1481
|
+
lines.push(`- approved_with_feedback: ${awf}`);
|
|
1482
|
+
lines.push(`- rejected: ${rejected}`);
|
|
1483
|
+
const provenance = list.slice(0, 3).map((e) => `${path2.basename(e.sourcePath)}:L${e.sourceLine}#${e.entryId}`);
|
|
1484
|
+
if (provenance.length > 0) {
|
|
1485
|
+
lines.push(`- provenance: ${provenance.join(", ")}`);
|
|
1486
|
+
}
|
|
1487
|
+
lines.push("");
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
lines.push("## Patterns (Avoid / Prefer)");
|
|
1491
|
+
if (patterns.length === 0) {
|
|
1492
|
+
lines.push("- (none yet)");
|
|
1493
|
+
} else {
|
|
1494
|
+
const detailMap = new Map(patternDetails.map((d) => [d.pattern, d.provenance]));
|
|
1495
|
+
for (const p of patterns.slice(0, 100)) {
|
|
1496
|
+
const provenance = detailMap.get(p) ?? [];
|
|
1497
|
+
if (provenance.length > 0) {
|
|
1498
|
+
lines.push(`- ${p} _(source: ${provenance.join(", ")})_`);
|
|
1499
|
+
} else {
|
|
1500
|
+
lines.push(`- ${p}`);
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
lines.push("");
|
|
1505
|
+
lines.push("## Outcome Weighting");
|
|
1506
|
+
if (outcomeSummary.length === 0) {
|
|
1507
|
+
lines.push("- (no action outcomes recorded this week)");
|
|
1508
|
+
} else {
|
|
1509
|
+
for (const item of outcomeSummary.slice(0, 20)) {
|
|
1510
|
+
lines.push(
|
|
1511
|
+
`- ${item.action}: applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}, unknown=${item.counts.unknown}, weight=${item.weightedScore} _(source: ${item.provenance.join(", ")})_`
|
|
1512
|
+
);
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
lines.push("");
|
|
1516
|
+
if (this.config.compoundingSemanticEnabled) {
|
|
1517
|
+
lines.push("## Promotion Candidates (Advisory)");
|
|
1518
|
+
if (promotionCandidates.length === 0) {
|
|
1519
|
+
lines.push("- (no advisory promotion candidates this week)");
|
|
1520
|
+
} else {
|
|
1521
|
+
for (const candidate of promotionCandidates) {
|
|
1522
|
+
const outcomeSummaryText = candidate.outcome ? ` outcomes[a=${candidate.outcome.applied}, s=${candidate.outcome.skipped}, f=${candidate.outcome.failed}, u=${candidate.outcome.unknown}]` : "";
|
|
1523
|
+
lines.push(
|
|
1524
|
+
`- [${candidate.sourceType}] ${candidate.subject} -> ${candidate.content} (category=${candidate.category}, score=${candidate.score}, id=${candidate.id}): ${candidate.rationale}${outcomeSummaryText} _(source: ${candidate.provenance.join(", ")})_`
|
|
1525
|
+
);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
lines.push("");
|
|
1529
|
+
lines.push("_Advisory only: no automatic promotion write is performed by this report. Use `compounding_promote_candidate` or `openclaw engram compounding-promote` to persist one manually._");
|
|
1530
|
+
lines.push("");
|
|
1531
|
+
}
|
|
1532
|
+
if (this.config.continuityAuditEnabled) {
|
|
1533
|
+
lines.push("## Continuity Audits");
|
|
1534
|
+
if (continuity.weeklyPath) {
|
|
1535
|
+
lines.push(`- weekly: ${continuity.weeklyPath}`);
|
|
1536
|
+
} else {
|
|
1537
|
+
lines.push(`- weekly: (missing for ${weekId})`);
|
|
1538
|
+
}
|
|
1539
|
+
if (continuity.monthlyPath) {
|
|
1540
|
+
lines.push(`- monthly: ${continuity.monthlyPath}`);
|
|
1541
|
+
} else {
|
|
1542
|
+
lines.push(`- monthly: (missing for ${continuity.monthId})`);
|
|
1543
|
+
}
|
|
1544
|
+
lines.push("");
|
|
1545
|
+
}
|
|
1546
|
+
return lines.join("\n");
|
|
1547
|
+
}
|
|
1548
|
+
buildRubricSnapshot(entries, outcomeSummary) {
|
|
1549
|
+
const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1550
|
+
const byAgent = /* @__PURE__ */ new Map();
|
|
1551
|
+
const byWorkflow = /* @__PURE__ */ new Map();
|
|
1552
|
+
for (const wrapped of entries) {
|
|
1553
|
+
const note = (wrapped.entry.learning && wrapped.entry.learning.trim().length > 0 ? wrapped.entry.learning : wrapped.entry.decision === "rejected" ? wrapped.entry.reason : "").trim();
|
|
1554
|
+
if (!note) continue;
|
|
1555
|
+
const provenance = `${path2.basename(wrapped.sourcePath)}:L${wrapped.sourceLine}#${wrapped.entryId}`;
|
|
1556
|
+
const agentEntry = byAgent.get(wrapped.entry.agent) ?? {
|
|
1557
|
+
id: stableRubricId("agent", wrapped.entry.agent),
|
|
1558
|
+
kind: "agent",
|
|
1559
|
+
subject: wrapped.entry.agent,
|
|
1560
|
+
observations: [],
|
|
1561
|
+
tags: [],
|
|
1562
|
+
provenance: [],
|
|
1563
|
+
observationEntries: [],
|
|
1564
|
+
updatedAt
|
|
1565
|
+
};
|
|
1566
|
+
this.addRubricObservation(agentEntry, note, provenance);
|
|
1567
|
+
agentEntry.tags = normalizeTags([...agentEntry.tags, ...normalizeTags(wrapped.entry.tags)]);
|
|
1568
|
+
byAgent.set(wrapped.entry.agent, agentEntry);
|
|
1569
|
+
const workflow = wrapped.entry.workflow?.trim();
|
|
1570
|
+
if (!workflow) continue;
|
|
1571
|
+
const workflowEntry = byWorkflow.get(workflow) ?? {
|
|
1572
|
+
id: stableRubricId("workflow", workflow),
|
|
1573
|
+
kind: "workflow",
|
|
1574
|
+
subject: workflow,
|
|
1575
|
+
observations: [],
|
|
1576
|
+
tags: [],
|
|
1577
|
+
provenance: [],
|
|
1578
|
+
observationEntries: [],
|
|
1579
|
+
updatedAt
|
|
1580
|
+
};
|
|
1581
|
+
this.addRubricObservation(workflowEntry, note, provenance);
|
|
1582
|
+
workflowEntry.tags = normalizeTags([...workflowEntry.tags, ...normalizeTags(wrapped.entry.tags)]);
|
|
1583
|
+
byWorkflow.set(workflow, workflowEntry);
|
|
1584
|
+
}
|
|
1585
|
+
for (const item of outcomeSummary) {
|
|
1586
|
+
const workflowEntry = byWorkflow.get(item.action) ?? {
|
|
1587
|
+
id: stableRubricId("workflow", item.action),
|
|
1588
|
+
kind: "workflow",
|
|
1589
|
+
subject: item.action,
|
|
1590
|
+
observations: [],
|
|
1591
|
+
tags: [],
|
|
1592
|
+
provenance: [],
|
|
1593
|
+
observationEntries: [],
|
|
1594
|
+
updatedAt
|
|
1595
|
+
};
|
|
1596
|
+
this.addRubricObservation(
|
|
1597
|
+
workflowEntry,
|
|
1598
|
+
`Outcome weight=${item.weightedScore} (applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}, unknown=${item.counts.unknown})`,
|
|
1599
|
+
...item.provenance
|
|
1600
|
+
);
|
|
1601
|
+
byWorkflow.set(item.action, workflowEntry);
|
|
1602
|
+
}
|
|
1603
|
+
return {
|
|
1604
|
+
updatedAt,
|
|
1605
|
+
agents: [...byAgent.values()].sort((a, b) => a.subject.localeCompare(b.subject)),
|
|
1606
|
+
workflows: [...byWorkflow.values()].sort((a, b) => a.subject.localeCompare(b.subject))
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
formatRubrics(outcomeSummary, snapshot) {
|
|
1610
|
+
const lines = [
|
|
1611
|
+
"# Compounding Rubrics",
|
|
1612
|
+
"",
|
|
1613
|
+
`Generated: ${snapshot.updatedAt}`,
|
|
1614
|
+
"",
|
|
1615
|
+
"Stable, deterministic rubric snapshot generated from weekly feedback + action outcomes.",
|
|
1616
|
+
""
|
|
1617
|
+
];
|
|
1618
|
+
lines.push("## Agent Rubrics");
|
|
1619
|
+
if (snapshot.agents.length === 0) {
|
|
1620
|
+
lines.push("- (none yet)");
|
|
1621
|
+
} else {
|
|
1622
|
+
for (const rubric of snapshot.agents) {
|
|
1623
|
+
lines.push(`### ${rubric.subject}`);
|
|
1624
|
+
const observations = this.getRubricObservationEntries(rubric).slice(0, 8);
|
|
1625
|
+
if (observations.length === 0) {
|
|
1626
|
+
lines.push("- No rubric deltas this week.");
|
|
1627
|
+
} else {
|
|
1628
|
+
for (const observation of observations) {
|
|
1629
|
+
const provenance = observation.provenance.join(", ");
|
|
1630
|
+
lines.push(`- ${observation.note}${provenance ? ` _(source: ${provenance})_` : ""}`);
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
lines.push("");
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
lines.push("## Workflow Rubrics");
|
|
1637
|
+
if (snapshot.workflows.length === 0) {
|
|
1638
|
+
lines.push("- (none yet)");
|
|
1639
|
+
} else {
|
|
1640
|
+
for (const rubric of snapshot.workflows) {
|
|
1641
|
+
lines.push(`### ${rubric.subject}`);
|
|
1642
|
+
for (const observation of this.getRubricObservationEntries(rubric).slice(0, 8)) {
|
|
1643
|
+
const provenance = observation.provenance.join(", ");
|
|
1644
|
+
lines.push(`- ${observation.note}${provenance ? ` _(source: ${provenance})_` : ""}`);
|
|
1645
|
+
}
|
|
1646
|
+
lines.push("");
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
lines.push("## Action Outcome Signals");
|
|
1650
|
+
if (outcomeSummary.length === 0) {
|
|
1651
|
+
lines.push("- (none yet)");
|
|
1652
|
+
} else {
|
|
1653
|
+
for (const item of outcomeSummary.slice(0, 20)) {
|
|
1654
|
+
lines.push(
|
|
1655
|
+
`- ${item.action}: weight=${item.weightedScore} (applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}, unknown=${item.counts.unknown})`
|
|
1656
|
+
);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
lines.push("");
|
|
1660
|
+
return lines.join("\n");
|
|
1661
|
+
}
|
|
1662
|
+
async syncRubricArtifacts(snapshot) {
|
|
1663
|
+
await this.replaceRubricDirectory(this.rubricsAgentsDir, snapshot.agents);
|
|
1664
|
+
await this.replaceRubricDirectory(this.rubricsWorkflowsDir, snapshot.workflows);
|
|
1665
|
+
}
|
|
1666
|
+
async replaceRubricDirectory(dir, entries) {
|
|
1667
|
+
await mkdir2(dir, { recursive: true });
|
|
1668
|
+
try {
|
|
1669
|
+
const names = await readdir2(dir);
|
|
1670
|
+
await Promise.all(
|
|
1671
|
+
names.filter((name) => name.endsWith(".md")).map((name) => unlink(path2.join(dir, name)).catch(() => void 0))
|
|
1672
|
+
);
|
|
1673
|
+
} catch {
|
|
1674
|
+
}
|
|
1675
|
+
const slugCollisions = /* @__PURE__ */ new Map();
|
|
1676
|
+
for (const entry of entries) {
|
|
1677
|
+
const slug = stableSlug(entry.subject);
|
|
1678
|
+
slugCollisions.set(slug, (slugCollisions.get(slug) ?? 0) + 1);
|
|
1679
|
+
}
|
|
1680
|
+
await Promise.all(entries.map(async (entry) => {
|
|
1681
|
+
const observationEntries = this.getRubricObservationEntries(entry);
|
|
1682
|
+
const body = [
|
|
1683
|
+
`# ${entry.kind === "agent" ? "Agent" : "Workflow"} Rubric \u2014 ${entry.subject}`,
|
|
1684
|
+
"",
|
|
1685
|
+
`Updated: ${entry.updatedAt}`,
|
|
1686
|
+
"",
|
|
1687
|
+
"## Observations",
|
|
1688
|
+
...observationEntries.length > 0 ? observationEntries.map((item) => `- ${item.note}`) : ["- (none yet)"],
|
|
1689
|
+
"",
|
|
1690
|
+
"## Provenance",
|
|
1691
|
+
...entry.provenance.length > 0 ? entry.provenance.map((item) => `- ${item}`) : ["- (none yet)"],
|
|
1692
|
+
""
|
|
1693
|
+
].join("\n");
|
|
1694
|
+
const fileName = rubricArtifactFileName(entry, slugCollisions);
|
|
1695
|
+
await writeFile2(path2.join(dir, fileName), body, "utf-8");
|
|
1696
|
+
}));
|
|
1697
|
+
}
|
|
1698
|
+
scoreRubricForQuery(entry, queryTokens) {
|
|
1699
|
+
if (queryTokens.length === 0) return entry.observations.length;
|
|
1700
|
+
const haystack = [entry.subject, ...entry.observations, ...entry.tags].join(" ").toLowerCase();
|
|
1701
|
+
let score = 0;
|
|
1702
|
+
for (const token of queryTokens) {
|
|
1703
|
+
if (haystack.includes(token)) score += 2;
|
|
1704
|
+
if (entry.subject.toLowerCase().includes(token)) score += 2;
|
|
1705
|
+
}
|
|
1706
|
+
if (score === 0) return 0;
|
|
1707
|
+
return score + Math.min(entry.observations.length, 3);
|
|
1708
|
+
}
|
|
1709
|
+
normalizeRubricEntry(entry) {
|
|
1710
|
+
const normalizedEntries = this.getRubricObservationEntries(entry);
|
|
1711
|
+
return {
|
|
1712
|
+
...entry,
|
|
1713
|
+
observations: normalizedEntries.map((item) => item.note),
|
|
1714
|
+
provenance: [...new Set(normalizedEntries.flatMap((item) => item.provenance))],
|
|
1715
|
+
observationEntries: normalizedEntries
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
getRubricObservationEntries(entry) {
|
|
1719
|
+
if (Array.isArray(entry.observationEntries) && entry.observationEntries.length > 0) {
|
|
1720
|
+
return entry.observationEntries.map((item) => ({
|
|
1721
|
+
note: item.note,
|
|
1722
|
+
provenance: [...new Set(item.provenance)].sort()
|
|
1723
|
+
}));
|
|
1724
|
+
}
|
|
1725
|
+
return entry.observations.map((note, index) => ({
|
|
1726
|
+
note,
|
|
1727
|
+
provenance: entry.provenance[index] ? [entry.provenance[index]] : entry.provenance[0] ? [entry.provenance[0]] : []
|
|
1728
|
+
}));
|
|
1729
|
+
}
|
|
1730
|
+
isSyntheticOutcomeRubricObservation(note) {
|
|
1731
|
+
return note.trimStart().startsWith("Outcome weight=");
|
|
1732
|
+
}
|
|
1733
|
+
addRubricObservation(entry, note, ...provenance) {
|
|
1734
|
+
const normalized = this.normalizeRubricEntry(entry);
|
|
1735
|
+
const existing = normalized.observationEntries?.find((item) => item.note === note);
|
|
1736
|
+
if (existing) {
|
|
1737
|
+
existing.provenance = [.../* @__PURE__ */ new Set([...existing.provenance, ...provenance])].sort();
|
|
1738
|
+
} else {
|
|
1739
|
+
normalized.observationEntries?.push({
|
|
1740
|
+
note,
|
|
1741
|
+
provenance: [...new Set(provenance)].sort()
|
|
1742
|
+
});
|
|
1743
|
+
}
|
|
1744
|
+
entry.observationEntries = normalized.observationEntries;
|
|
1745
|
+
entry.observations = normalized.observationEntries?.map((item) => item.note) ?? [];
|
|
1746
|
+
entry.provenance = [...new Set((normalized.observationEntries ?? []).flatMap((item) => item.provenance))];
|
|
1747
|
+
}
|
|
1748
|
+
async readNonEmptyFile(filePath) {
|
|
1749
|
+
try {
|
|
1750
|
+
const raw = await readFile2(filePath, "utf-8");
|
|
1751
|
+
return raw.trim().length > 0;
|
|
1752
|
+
} catch {
|
|
1753
|
+
return false;
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
async readOptionalFile(filePath) {
|
|
1757
|
+
try {
|
|
1758
|
+
const raw = await readFile2(filePath, "utf-8");
|
|
1759
|
+
return raw.trim().length > 0 ? raw : null;
|
|
1760
|
+
} catch {
|
|
1761
|
+
return null;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
async readContinuityIncidents(limit = 200, state) {
|
|
1765
|
+
const normalizedLimit = Number.isFinite(limit) ? limit : 0;
|
|
1766
|
+
const cappedLimit = Math.max(0, Math.floor(normalizedLimit));
|
|
1767
|
+
if (cappedLimit === 0) return [];
|
|
1768
|
+
const incidents = [];
|
|
1769
|
+
try {
|
|
1770
|
+
const names = await readdir2(this.identityIncidentsDir);
|
|
1771
|
+
const files = names.filter((n) => n.endsWith(".md")).sort().reverse();
|
|
1772
|
+
for (const file of files) {
|
|
1773
|
+
if (incidents.length >= cappedLimit) break;
|
|
1774
|
+
const filePath = path2.join(this.identityIncidentsDir, file);
|
|
1775
|
+
try {
|
|
1776
|
+
const raw = await readFile2(filePath, "utf-8");
|
|
1777
|
+
const parsed = parseContinuityIncident(raw);
|
|
1778
|
+
if (!parsed) continue;
|
|
1779
|
+
if (state && parsed.state !== state) continue;
|
|
1780
|
+
incidents.push(parsed);
|
|
1781
|
+
} catch {
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
} catch {
|
|
1785
|
+
}
|
|
1786
|
+
return incidents;
|
|
1787
|
+
}
|
|
1788
|
+
async readContinuityAuditReferences(weekId) {
|
|
1789
|
+
const monthId = monthIdFromIsoWeek(weekId);
|
|
1790
|
+
const weeklyPath = path2.join(this.identityAuditWeeklyDir, `${weekId}.md`);
|
|
1791
|
+
const monthlyPath = path2.join(this.identityAuditMonthlyDir, `${monthId}.md`);
|
|
1792
|
+
const weeklyExists = await this.readNonEmptyFile(weeklyPath);
|
|
1793
|
+
const monthlyExists = await this.readNonEmptyFile(monthlyPath);
|
|
1794
|
+
return {
|
|
1795
|
+
weekId,
|
|
1796
|
+
monthId,
|
|
1797
|
+
weeklyPath: weeklyExists ? weeklyPath : null,
|
|
1798
|
+
monthlyPath: monthlyExists ? monthlyPath : null
|
|
1799
|
+
};
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
|
|
1803
|
+
export {
|
|
1804
|
+
SharedContextManager,
|
|
1805
|
+
defaultTierMigrationCycleBudget,
|
|
1806
|
+
CompoundingEngine
|
|
1807
|
+
};
|
|
1808
|
+
//# sourceMappingURL=chunk-RQ4ENU3T.js.map
|