nexus-agents 2.29.0 → 2.29.2
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/adaptive-memory-5VP5WWTE.js +15 -0
- package/dist/chunk-5COIDGQJ.js +1585 -0
- package/dist/chunk-5COIDGQJ.js.map +1 -0
- package/dist/{chunk-HWDBNDUX.js → chunk-63AJLNKU.js} +2 -2
- package/dist/chunk-66NNHMVB.js +195 -0
- package/dist/chunk-66NNHMVB.js.map +1 -0
- package/dist/chunk-AP2FD37C.js +127 -0
- package/dist/chunk-AP2FD37C.js.map +1 -0
- package/dist/chunk-BC3M4VLP.js +359 -0
- package/dist/chunk-BC3M4VLP.js.map +1 -0
- package/dist/chunk-BQ4YXGGQ.js +127 -0
- package/dist/chunk-BQ4YXGGQ.js.map +1 -0
- package/dist/{chunk-ZBZJHXRT.js → chunk-CW2Z773T.js} +19 -347
- package/dist/chunk-CW2Z773T.js.map +1 -0
- package/dist/chunk-DDQGAVQA.js +944 -0
- package/dist/chunk-DDQGAVQA.js.map +1 -0
- package/dist/chunk-ED6VQWNG.js +63 -0
- package/dist/chunk-ED6VQWNG.js.map +1 -0
- package/dist/{chunk-7F6HYUIY.js → chunk-EPMBGZQX.js} +16 -97
- package/dist/chunk-EPMBGZQX.js.map +1 -0
- package/dist/chunk-GX436VRU.js +931 -0
- package/dist/chunk-GX436VRU.js.map +1 -0
- package/dist/{chunk-IMWYKX4H.js → chunk-HSOPD265.js} +444 -399
- package/dist/chunk-HSOPD265.js.map +1 -0
- package/dist/{chunk-S3BKWNST.js → chunk-J245RJGW.js} +680 -1436
- package/dist/chunk-J245RJGW.js.map +1 -0
- package/dist/{chunk-I6YDS23R.js → chunk-KQIDTE52.js} +2 -2
- package/dist/{chunk-POBO4G2P.js → chunk-LDIN2PLV.js} +250 -110
- package/dist/chunk-LDIN2PLV.js.map +1 -0
- package/dist/{chunk-KGDG6PWZ.js → chunk-LKDHAJJB.js} +2 -2
- package/dist/{chunk-T7PU3NPQ.js → chunk-NKGTEJYU.js} +7 -5
- package/dist/{chunk-T7PU3NPQ.js.map → chunk-NKGTEJYU.js.map} +1 -1
- package/dist/chunk-QGODFK36.js +122 -0
- package/dist/chunk-QGODFK36.js.map +1 -0
- package/dist/{chunk-DAMRMAM2.js → chunk-QSNAFOE6.js} +12369 -14499
- package/dist/chunk-QSNAFOE6.js.map +1 -0
- package/dist/chunk-TL2GJMJ5.js +700 -0
- package/dist/chunk-TL2GJMJ5.js.map +1 -0
- package/dist/{chunk-WSK4VSXP.js → chunk-V6MSPUQF.js} +2 -2
- package/dist/chunk-VZ2YOQWU.js +90 -0
- package/dist/chunk-VZ2YOQWU.js.map +1 -0
- package/dist/{chunk-5VZLXMO7.js → chunk-WSYJN7BI.js} +7 -6
- package/dist/chunk-WSYJN7BI.js.map +1 -0
- package/dist/chunk-Y477EGI4.js +356 -0
- package/dist/chunk-Y477EGI4.js.map +1 -0
- package/dist/{chunk-HH5LVGEE.js → chunk-Z4OZ25VS.js} +4 -4
- package/dist/cli-circuit-breaker-6EJO3PPU.js +13 -0
- package/dist/cli.js +123 -68
- package/dist/cli.js.map +1 -1
- package/dist/codebase-search-CZUA37RU.js +9 -0
- package/dist/{composite-router-YPRWVTRB.js → composite-router-JD7URTC2.js} +2 -2
- package/dist/{consensus-vote-DBE6RNZG.js → consensus-vote-COW34Q2Y.js} +7 -5
- package/dist/{dist-7PQR2BQB.js → dist-CV74KUT7.js} +1302 -805
- package/dist/dist-CV74KUT7.js.map +1 -0
- package/dist/{doctor-deep-AWE7SRU6.js → doctor-deep-4A4X5X6U.js} +3 -3
- package/dist/expert-bridge-J36C7VES.js +10 -0
- package/dist/{expert-config-FHNBQRX2.js → expert-config-MQ5OJE3U.js} +2 -2
- package/dist/{factory-O5C7ZBZO.js → factory-4Z4RSUYE.js} +5 -4
- package/dist/{factory-PCHGQ3ZG.js → factory-NHORX63J.js} +4 -3
- package/dist/index.d.ts +507 -42
- package/dist/index.js +331 -78
- package/dist/index.js.map +1 -1
- package/dist/issue-triage-TIG3RKXF.js +15 -0
- package/dist/{mcp-config-AUZQPUBY.js → mcp-config-ETY7GFGW.js} +3 -3
- package/dist/mobimem-5PAAMVFR.js +13 -0
- package/dist/mobimem-5PAAMVFR.js.map +1 -0
- package/dist/repo-analyze-HWMXSK5C.js +24 -0
- package/dist/repo-analyze-HWMXSK5C.js.map +1 -0
- package/dist/repo-security-plan-KQB3ZJTE.js +17 -0
- package/dist/repo-security-plan-KQB3ZJTE.js.map +1 -0
- package/dist/research-helpers-synthesize-ZMERZZ5B.js +10 -0
- package/dist/research-helpers-synthesize-ZMERZZ5B.js.map +1 -0
- package/dist/{routing-memory-QY3XMU2R.js → routing-memory-3ES3OHLM.js} +2 -2
- package/dist/routing-memory-3ES3OHLM.js.map +1 -0
- package/dist/{session-memory-3MBCE5KS.js → session-memory-E2OE2CYR.js} +3 -3
- package/dist/session-memory-E2OE2CYR.js.map +1 -0
- package/dist/{setup-command-IQ4MD3FT.js → setup-command-CMCQRBJF.js} +7 -6
- package/dist/setup-command-CMCQRBJF.js.map +1 -0
- package/dist/{setup-config-5YUPLDXF.js → setup-config-KITOPV7V.js} +3 -3
- package/dist/setup-config-KITOPV7V.js.map +1 -0
- package/dist/shared-memory-AEO2HJLC.js +8 -0
- package/dist/shared-memory-AEO2HJLC.js.map +1 -0
- package/dist/symbol-extractor-UEBANFSN.js +10 -0
- package/dist/symbol-extractor-UEBANFSN.js.map +1 -0
- package/dist/{weather-report-CC2C4KAX.js → weather-report-KUSVNXDZ.js} +2 -2
- package/dist/weather-report-KUSVNXDZ.js.map +1 -0
- package/package.json +14 -13
- package/dist/chunk-5VZLXMO7.js.map +0 -1
- package/dist/chunk-7F6HYUIY.js.map +0 -1
- package/dist/chunk-DAMRMAM2.js.map +0 -1
- package/dist/chunk-IMWYKX4H.js.map +0 -1
- package/dist/chunk-POBO4G2P.js.map +0 -1
- package/dist/chunk-S3BKWNST.js.map +0 -1
- package/dist/chunk-ZBZJHXRT.js.map +0 -1
- package/dist/dist-7PQR2BQB.js.map +0 -1
- /package/dist/{composite-router-YPRWVTRB.js.map → adaptive-memory-5VP5WWTE.js.map} +0 -0
- /package/dist/{chunk-HWDBNDUX.js.map → chunk-63AJLNKU.js.map} +0 -0
- /package/dist/{chunk-I6YDS23R.js.map → chunk-KQIDTE52.js.map} +0 -0
- /package/dist/{chunk-KGDG6PWZ.js.map → chunk-LKDHAJJB.js.map} +0 -0
- /package/dist/{chunk-WSK4VSXP.js.map → chunk-V6MSPUQF.js.map} +0 -0
- /package/dist/{chunk-HH5LVGEE.js.map → chunk-Z4OZ25VS.js.map} +0 -0
- /package/dist/{consensus-vote-DBE6RNZG.js.map → cli-circuit-breaker-6EJO3PPU.js.map} +0 -0
- /package/dist/{doctor-deep-AWE7SRU6.js.map → codebase-search-CZUA37RU.js.map} +0 -0
- /package/dist/{expert-config-FHNBQRX2.js.map → composite-router-JD7URTC2.js.map} +0 -0
- /package/dist/{factory-O5C7ZBZO.js.map → consensus-vote-COW34Q2Y.js.map} +0 -0
- /package/dist/{factory-PCHGQ3ZG.js.map → doctor-deep-4A4X5X6U.js.map} +0 -0
- /package/dist/{mcp-config-AUZQPUBY.js.map → expert-bridge-J36C7VES.js.map} +0 -0
- /package/dist/{routing-memory-QY3XMU2R.js.map → expert-config-MQ5OJE3U.js.map} +0 -0
- /package/dist/{session-memory-3MBCE5KS.js.map → factory-4Z4RSUYE.js.map} +0 -0
- /package/dist/{setup-command-IQ4MD3FT.js.map → factory-NHORX63J.js.map} +0 -0
- /package/dist/{setup-config-5YUPLDXF.js.map → issue-triage-TIG3RKXF.js.map} +0 -0
- /package/dist/{weather-report-CC2C4KAX.js.map → mcp-config-ETY7GFGW.js.map} +0 -0
|
@@ -1,11 +1,19 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SessionMemory
|
|
3
|
+
} from "./chunk-KQIDTE52.js";
|
|
4
|
+
import {
|
|
5
|
+
AdaptiveMemoryBackend,
|
|
6
|
+
HybridMemoryBackend,
|
|
7
|
+
MemoryError,
|
|
8
|
+
MemoryImportance,
|
|
9
|
+
getMemoryEntry,
|
|
10
|
+
memoryExists,
|
|
11
|
+
memoryRowToEntry
|
|
12
|
+
} from "./chunk-DDQGAVQA.js";
|
|
1
13
|
import {
|
|
2
14
|
stringifyValue,
|
|
3
|
-
tokenize,
|
|
4
15
|
tokenizeFiltered
|
|
5
16
|
} from "./chunk-633WH2ML.js";
|
|
6
|
-
import {
|
|
7
|
-
SessionMemory
|
|
8
|
-
} from "./chunk-I6YDS23R.js";
|
|
9
17
|
import {
|
|
10
18
|
createCliAdapter,
|
|
11
19
|
createCliDetectionCache,
|
|
@@ -13,7 +21,7 @@ import {
|
|
|
13
21
|
getAvailableClis,
|
|
14
22
|
isCliAvailable,
|
|
15
23
|
withTimeout
|
|
16
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-CW2Z773T.js";
|
|
17
25
|
import {
|
|
18
26
|
AgentError,
|
|
19
27
|
CACHE_TIMEOUTS,
|
|
@@ -58,45 +66,45 @@ import {
|
|
|
58
66
|
resolveVoteTimeout,
|
|
59
67
|
toRateLimitError,
|
|
60
68
|
validateTimeout
|
|
61
|
-
} from "./chunk-
|
|
69
|
+
} from "./chunk-HSOPD265.js";
|
|
62
70
|
import {
|
|
63
71
|
OUTCOMES_FILE,
|
|
64
72
|
ensureLearningDir
|
|
65
73
|
} from "./chunk-CLYZ7FWP.js";
|
|
66
74
|
|
|
67
75
|
// src/mcp/tools/consensus-vote.ts
|
|
68
|
-
import { z as
|
|
76
|
+
import { z as z19 } from "zod";
|
|
69
77
|
|
|
70
78
|
// src/mcp/mcp-notifier.ts
|
|
71
79
|
import { AsyncLocalStorage } from "async_hooks";
|
|
72
80
|
var internalLogger = createLogger({ component: "mcp-notifier" });
|
|
73
81
|
function createMcpNotifier(server) {
|
|
74
|
-
function send(level,
|
|
82
|
+
function send(level, logger11, data) {
|
|
75
83
|
try {
|
|
76
|
-
server.sendLoggingMessage({ level, logger:
|
|
84
|
+
server.sendLoggingMessage({ level, logger: logger11, data }).catch((error) => {
|
|
77
85
|
internalLogger.debug("Failed to send MCP notification", {
|
|
78
86
|
level,
|
|
79
|
-
logger:
|
|
87
|
+
logger: logger11,
|
|
80
88
|
error: getErrorMessage(error)
|
|
81
89
|
});
|
|
82
90
|
});
|
|
83
91
|
} catch (error) {
|
|
84
92
|
internalLogger.debug("Failed to send MCP notification", {
|
|
85
93
|
level,
|
|
86
|
-
logger:
|
|
94
|
+
logger: logger11,
|
|
87
95
|
error: getErrorMessage(error)
|
|
88
96
|
});
|
|
89
97
|
}
|
|
90
98
|
}
|
|
91
99
|
return {
|
|
92
|
-
info: (
|
|
93
|
-
send("info",
|
|
100
|
+
info: (logger11, data) => {
|
|
101
|
+
send("info", logger11, data);
|
|
94
102
|
},
|
|
95
|
-
debug: (
|
|
96
|
-
send("debug",
|
|
103
|
+
debug: (logger11, data) => {
|
|
104
|
+
send("debug", logger11, data);
|
|
97
105
|
},
|
|
98
|
-
warn: (
|
|
99
|
-
send("warning",
|
|
106
|
+
warn: (logger11, data) => {
|
|
107
|
+
send("warning", logger11, data);
|
|
100
108
|
}
|
|
101
109
|
};
|
|
102
110
|
}
|
|
@@ -221,7 +229,7 @@ var RateLimiter = class {
|
|
|
221
229
|
this.logger.debug("Rate limiter reset", { tokens: this.tokens });
|
|
222
230
|
}
|
|
223
231
|
};
|
|
224
|
-
function createDefaultRateLimiter(name,
|
|
232
|
+
function createDefaultRateLimiter(name, logger11) {
|
|
225
233
|
const config = {
|
|
226
234
|
capacity: 100,
|
|
227
235
|
refillRate: 10,
|
|
@@ -230,8 +238,8 @@ function createDefaultRateLimiter(name, logger13) {
|
|
|
230
238
|
if (name !== void 0) {
|
|
231
239
|
config.name = name;
|
|
232
240
|
}
|
|
233
|
-
if (
|
|
234
|
-
config.logger =
|
|
241
|
+
if (logger11 !== void 0) {
|
|
242
|
+
config.logger = logger11;
|
|
235
243
|
}
|
|
236
244
|
return new RateLimiter(config);
|
|
237
245
|
}
|
|
@@ -669,7 +677,7 @@ var TimeoutGuard = class {
|
|
|
669
677
|
reject(new Error(`Operation timed out after ${String(timeoutMs)}ms`));
|
|
670
678
|
}, timeoutMs);
|
|
671
679
|
});
|
|
672
|
-
const
|
|
680
|
+
const promises = [operation(), timeoutPromise];
|
|
673
681
|
if (signal !== void 0 && !signal.aborted) {
|
|
674
682
|
const abortPromise = new Promise((_resolve, reject) => {
|
|
675
683
|
signal.addEventListener(
|
|
@@ -680,9 +688,9 @@ var TimeoutGuard = class {
|
|
|
680
688
|
{ once: true }
|
|
681
689
|
);
|
|
682
690
|
});
|
|
683
|
-
|
|
691
|
+
promises.push(abortPromise);
|
|
684
692
|
}
|
|
685
|
-
return Promise.race(
|
|
693
|
+
return Promise.race(promises);
|
|
686
694
|
}
|
|
687
695
|
handleSuccess(result, startTime, timeoutMs, operationName) {
|
|
688
696
|
const durationMs = getTimeProvider().now() - startTime;
|
|
@@ -943,13 +951,13 @@ function buildMiddlewareStack(config) {
|
|
|
943
951
|
return middlewares;
|
|
944
952
|
}
|
|
945
953
|
function createMiddlewareChain(config) {
|
|
946
|
-
const
|
|
954
|
+
const logger11 = config.logger ?? createLogger({ tool: config.toolName });
|
|
947
955
|
const middlewares = buildMiddlewareStack(config);
|
|
948
956
|
const composed = composeMiddleware(middlewares);
|
|
949
957
|
return (handler) => {
|
|
950
958
|
return async (args) => {
|
|
951
959
|
const requestContext = createRequestContext({ toolName: config.toolName });
|
|
952
|
-
const requestLogger =
|
|
960
|
+
const requestLogger = logger11.child(contextForLogging(requestContext));
|
|
953
961
|
const ctx = { requestContext, logger: requestLogger };
|
|
954
962
|
return composed(args, ctx, (finalArgs, finalCtx) => handler(finalArgs, finalCtx));
|
|
955
963
|
};
|
|
@@ -1158,15 +1166,15 @@ function sanitizeToolInput(args) {
|
|
|
1158
1166
|
detectedPatterns: uniquePatterns
|
|
1159
1167
|
};
|
|
1160
1168
|
}
|
|
1161
|
-
function logSanitizationResult(result,
|
|
1169
|
+
function logSanitizationResult(result, logger11, toolName) {
|
|
1162
1170
|
if (result.wasModified) {
|
|
1163
|
-
|
|
1171
|
+
logger11.warn("Tool input sanitized \u2014 XML injection tags stripped", {
|
|
1164
1172
|
tool: toolName,
|
|
1165
1173
|
modifiedFields: result.modifiedCount
|
|
1166
1174
|
});
|
|
1167
1175
|
}
|
|
1168
1176
|
if (result.detectedPatterns.length > 0) {
|
|
1169
|
-
|
|
1177
|
+
logger11.warn("Injection patterns detected in tool input", {
|
|
1170
1178
|
tool: toolName,
|
|
1171
1179
|
patterns: result.detectedPatterns
|
|
1172
1180
|
});
|
|
@@ -1211,11 +1219,11 @@ var SECRET_PATTERNS = [
|
|
|
1211
1219
|
// password= or token= in output
|
|
1212
1220
|
/(?:password|token|secret|apikey|api_key)\s*[=:]\s*\S{8,}/i
|
|
1213
1221
|
];
|
|
1214
|
-
function sanitizeOutput(text,
|
|
1222
|
+
function sanitizeOutput(text, logger11) {
|
|
1215
1223
|
let sanitized = text;
|
|
1216
1224
|
for (const pattern of SECRET_PATTERNS) {
|
|
1217
1225
|
if (pattern.test(sanitized)) {
|
|
1218
|
-
|
|
1226
|
+
logger11.warn("Potential secret detected in tool output, redacting", {
|
|
1219
1227
|
pattern: pattern.source.slice(0, 30)
|
|
1220
1228
|
});
|
|
1221
1229
|
sanitized = sanitized.replace(pattern, "[REDACTED]");
|
|
@@ -1223,25 +1231,25 @@ function sanitizeOutput(text, logger13) {
|
|
|
1223
1231
|
}
|
|
1224
1232
|
return sanitized;
|
|
1225
1233
|
}
|
|
1226
|
-
function sanitizeToolResult(result,
|
|
1234
|
+
function sanitizeToolResult(result, logger11) {
|
|
1227
1235
|
for (const item of result.content) {
|
|
1228
|
-
item.text = sanitizeOutput(item.text,
|
|
1236
|
+
item.text = sanitizeOutput(item.text, logger11);
|
|
1229
1237
|
}
|
|
1230
1238
|
}
|
|
1231
|
-
function checkInputSize(args,
|
|
1239
|
+
function checkInputSize(args, logger11, requestId) {
|
|
1232
1240
|
if (args === void 0) return null;
|
|
1233
1241
|
const inputSize = JSON.stringify(args).length;
|
|
1234
1242
|
if (inputSize > MAX_INPUT_SIZE_BYTES) {
|
|
1235
|
-
|
|
1243
|
+
logger11.warn("Input size exceeds limit", { inputSize, limit: MAX_INPUT_SIZE_BYTES });
|
|
1236
1244
|
return internalError("Input too large", requestId);
|
|
1237
1245
|
}
|
|
1238
1246
|
return null;
|
|
1239
1247
|
}
|
|
1240
|
-
function checkRateLimit(rateLimiter,
|
|
1248
|
+
function checkRateLimit(rateLimiter, logger11) {
|
|
1241
1249
|
const acquired = rateLimiter.tryAcquire();
|
|
1242
1250
|
if (!acquired) {
|
|
1243
1251
|
const state = rateLimiter.getState();
|
|
1244
|
-
|
|
1252
|
+
logger11.warn("Rate limit exceeded");
|
|
1245
1253
|
return rateLimitError(state.nextTokenMs);
|
|
1246
1254
|
}
|
|
1247
1255
|
return null;
|
|
@@ -1262,14 +1270,14 @@ function checkPolicy(opts) {
|
|
|
1262
1270
|
opts.logger.debug("Policy check passed", { reason: decision.reason });
|
|
1263
1271
|
return null;
|
|
1264
1272
|
}
|
|
1265
|
-
async function executeHandler(handler, args, ctx,
|
|
1273
|
+
async function executeHandler(handler, args, ctx, logger11) {
|
|
1266
1274
|
const startTime = getTimeProvider().now();
|
|
1267
1275
|
const result = handler.length >= 2 ? await handler(args, ctx) : await handler(args);
|
|
1268
1276
|
const durationMs = getTimeProvider().now() - startTime;
|
|
1269
1277
|
if (result.isError === true) {
|
|
1270
|
-
|
|
1278
|
+
logger11.warn("Tool execution completed with error", { durationMs });
|
|
1271
1279
|
} else {
|
|
1272
|
-
|
|
1280
|
+
logger11.info("Tool execution completed", { durationMs });
|
|
1273
1281
|
}
|
|
1274
1282
|
return result;
|
|
1275
1283
|
}
|
|
@@ -1305,12 +1313,12 @@ function emitRateLimitAudit(auditLogger, toolName, ctx) {
|
|
|
1305
1313
|
requestId: ctx.requestId
|
|
1306
1314
|
});
|
|
1307
1315
|
}
|
|
1308
|
-
function checkSecurityTier(config, sanitizeResult,
|
|
1316
|
+
function checkSecurityTier(config, sanitizeResult, logger11) {
|
|
1309
1317
|
const tier = config.securityTier ?? "standard";
|
|
1310
1318
|
if (tier === "standard" || sanitizeResult.detectedPatterns.length === 0) {
|
|
1311
1319
|
return null;
|
|
1312
1320
|
}
|
|
1313
|
-
|
|
1321
|
+
logger11.warn("Input rejected by security tier validation", {
|
|
1314
1322
|
tier,
|
|
1315
1323
|
patterns: sanitizeResult.detectedPatterns
|
|
1316
1324
|
});
|
|
@@ -1324,16 +1332,16 @@ function checkSecurityTier(config, sanitizeResult, logger13) {
|
|
|
1324
1332
|
]
|
|
1325
1333
|
};
|
|
1326
1334
|
}
|
|
1327
|
-
function runPreChecks(config, args, mode, requestContext,
|
|
1328
|
-
const sizeResult = checkInputSize(args,
|
|
1335
|
+
function runPreChecks(config, args, mode, requestContext, logger11) {
|
|
1336
|
+
const sizeResult = checkInputSize(args, logger11, requestContext.requestId);
|
|
1329
1337
|
if (sizeResult) return { error: sizeResult, sanitizedArgs: args };
|
|
1330
1338
|
const sanitizeResult = sanitizeToolInput(args);
|
|
1331
|
-
logSanitizationResult(sanitizeResult,
|
|
1339
|
+
logSanitizationResult(sanitizeResult, logger11, config.toolName);
|
|
1332
1340
|
const sanitizedArgs = sanitizeResult.wasModified ? sanitizeResult.sanitized : args;
|
|
1333
|
-
const tierError = checkSecurityTier(config, sanitizeResult,
|
|
1341
|
+
const tierError = checkSecurityTier(config, sanitizeResult, logger11);
|
|
1334
1342
|
if (tierError !== null) return { error: tierError, sanitizedArgs };
|
|
1335
1343
|
if (config.rateLimiter) {
|
|
1336
|
-
const rlResult = checkRateLimit(config.rateLimiter,
|
|
1344
|
+
const rlResult = checkRateLimit(config.rateLimiter, logger11);
|
|
1337
1345
|
if (rlResult) {
|
|
1338
1346
|
if (config.auditLogger)
|
|
1339
1347
|
emitRateLimitAudit(config.auditLogger, config.toolName, requestContext);
|
|
@@ -1347,7 +1355,7 @@ function runPreChecks(config, args, mode, requestContext, logger13) {
|
|
|
1347
1355
|
args: sanitizedArgs,
|
|
1348
1356
|
mode,
|
|
1349
1357
|
allowedPaths: config.allowedPaths,
|
|
1350
|
-
logger:
|
|
1358
|
+
logger: logger11,
|
|
1351
1359
|
requestId: requestContext.requestId
|
|
1352
1360
|
});
|
|
1353
1361
|
if (pResult) {
|
|
@@ -1359,7 +1367,7 @@ function runPreChecks(config, args, mode, requestContext, logger13) {
|
|
|
1359
1367
|
return { error: null, sanitizedArgs };
|
|
1360
1368
|
}
|
|
1361
1369
|
function createSecureHandler(handler, config) {
|
|
1362
|
-
const
|
|
1370
|
+
const logger11 = config.logger ?? createLogger({ tool: config.toolName });
|
|
1363
1371
|
const mode = config.executionMode ?? "read-only";
|
|
1364
1372
|
return async (args) => {
|
|
1365
1373
|
const ctxOpts = {
|
|
@@ -1367,7 +1375,7 @@ function createSecureHandler(handler, config) {
|
|
|
1367
1375
|
...config.callerInfo && { caller: config.callerInfo }
|
|
1368
1376
|
};
|
|
1369
1377
|
const requestContext = createRequestContext(ctxOpts);
|
|
1370
|
-
const requestLogger =
|
|
1378
|
+
const requestLogger = logger11.child(contextForLogging(requestContext));
|
|
1371
1379
|
requestLogger.info("Tool invocation started");
|
|
1372
1380
|
const { error: preCheckError, sanitizedArgs } = runPreChecks(
|
|
1373
1381
|
config,
|
|
@@ -2685,13 +2693,13 @@ var SdkAdapter = class extends BaseAdapter {
|
|
|
2685
2693
|
sdkConfig;
|
|
2686
2694
|
/** Inflight init promise for coalescing concurrent calls (Issue #1438). */
|
|
2687
2695
|
initPromise;
|
|
2688
|
-
constructor(config,
|
|
2696
|
+
constructor(config, logger11) {
|
|
2689
2697
|
const apiKey = resolveApiKey(config.providerId, config.apiKey);
|
|
2690
2698
|
super({
|
|
2691
2699
|
providerId: `sdk-${config.providerId}`,
|
|
2692
2700
|
modelId: config.modelId,
|
|
2693
2701
|
capabilities: [ModelCapability.COMPLETION, ModelCapability.STREAMING],
|
|
2694
|
-
logger:
|
|
2702
|
+
logger: logger11 ?? createLogger({ adapter: `sdk-${config.providerId}` }),
|
|
2695
2703
|
...apiKey !== void 0 ? { apiKey } : {},
|
|
2696
2704
|
...config.timeout !== void 0 ? { timeout: config.timeout } : {},
|
|
2697
2705
|
...config.maxRetries !== void 0 ? { maxRetries: config.maxRetries } : {}
|
|
@@ -2864,19 +2872,19 @@ var SdkAdapter = class extends BaseAdapter {
|
|
|
2864
2872
|
|
|
2865
2873
|
// src/adapters/auto-adapter.ts
|
|
2866
2874
|
var defaultLogger = createLogger({ component: "auto-adapter" });
|
|
2867
|
-
function resolveCache(config,
|
|
2875
|
+
function resolveCache(config, logger11) {
|
|
2868
2876
|
if (config.cache !== void 0) {
|
|
2869
2877
|
return config.cache;
|
|
2870
2878
|
}
|
|
2871
2879
|
const enableCache = config.enableCache ?? true;
|
|
2872
|
-
return enableCache ? createCliDetectionCache({ logger:
|
|
2880
|
+
return enableCache ? createCliDetectionCache({ logger: logger11 }) : void 0;
|
|
2873
2881
|
}
|
|
2874
|
-
async function tryCliAdapter(config,
|
|
2882
|
+
async function tryCliAdapter(config, logger11, cache) {
|
|
2875
2883
|
const preferredCli = config.preferredCli;
|
|
2876
2884
|
const bridgeConfig = config.defaultCliTimeoutMs !== void 0 ? { defaultTimeoutMs: config.defaultCliTimeoutMs } : void 0;
|
|
2877
2885
|
if (preferredCli !== void 0 && await isCliAvailable(preferredCli, cache)) {
|
|
2878
|
-
|
|
2879
|
-
const cliAdapter2 = createCliAdapter({ cli: preferredCli, logger:
|
|
2886
|
+
logger11.info("Using preferred CLI", { cli: preferredCli });
|
|
2887
|
+
const cliAdapter2 = createCliAdapter({ cli: preferredCli, logger: logger11 });
|
|
2880
2888
|
await cliAdapter2.initialize();
|
|
2881
2889
|
return {
|
|
2882
2890
|
adapter: createCliToModelAdapter(cliAdapter2, bridgeConfig),
|
|
@@ -2888,15 +2896,15 @@ async function tryCliAdapter(config, logger13, cache) {
|
|
|
2888
2896
|
}
|
|
2889
2897
|
const availableClis = await getAvailableClis(cache);
|
|
2890
2898
|
if (availableClis.length === 0) {
|
|
2891
|
-
|
|
2899
|
+
logger11.info("No CLI adapters available");
|
|
2892
2900
|
return null;
|
|
2893
2901
|
}
|
|
2894
2902
|
const selectedCli = availableClis[0];
|
|
2895
2903
|
if (selectedCli === void 0) {
|
|
2896
2904
|
return null;
|
|
2897
2905
|
}
|
|
2898
|
-
|
|
2899
|
-
const cliAdapter = createCliAdapter({ cli: selectedCli, logger:
|
|
2906
|
+
logger11.info("Auto-selected CLI", { cli: selectedCli, available: availableClis });
|
|
2907
|
+
const cliAdapter = createCliAdapter({ cli: selectedCli, logger: logger11 });
|
|
2900
2908
|
await cliAdapter.initialize();
|
|
2901
2909
|
return {
|
|
2902
2910
|
adapter: createCliToModelAdapter(cliAdapter, bridgeConfig),
|
|
@@ -2910,13 +2918,13 @@ function resolveApiKeyFromEnv(configKey, envVar) {
|
|
|
2910
2918
|
const key = configKey ?? process.env[envVar];
|
|
2911
2919
|
return key !== void 0 && key.length > 0 ? key : void 0;
|
|
2912
2920
|
}
|
|
2913
|
-
function tryApiAdapter(config,
|
|
2921
|
+
function tryApiAdapter(config, logger11) {
|
|
2914
2922
|
const claudeModelId = getCliModelName(DEFAULT_MODEL_PER_CLI["claude"]);
|
|
2915
2923
|
const codexModelId = getCliModelName(DEFAULT_MODEL_PER_CLI["codex"]);
|
|
2916
2924
|
const geminiModelId = getCliModelName(DEFAULT_MODEL_PER_CLI["gemini"]);
|
|
2917
2925
|
const anthropicKey = resolveApiKeyFromEnv(config.anthropicApiKey, "ANTHROPIC_API_KEY");
|
|
2918
2926
|
if (anthropicKey !== void 0) {
|
|
2919
|
-
|
|
2927
|
+
logger11.info("Using Anthropic API adapter", { model: claudeModelId });
|
|
2920
2928
|
return {
|
|
2921
2929
|
adapter: createClaudeAdapter({ modelId: claudeModelId, apiKey: anthropicKey }),
|
|
2922
2930
|
source: "api",
|
|
@@ -2926,7 +2934,7 @@ function tryApiAdapter(config, logger13) {
|
|
|
2926
2934
|
}
|
|
2927
2935
|
const openaiKey = resolveApiKeyFromEnv(config.openaiApiKey, "OPENAI_API_KEY");
|
|
2928
2936
|
if (openaiKey !== void 0) {
|
|
2929
|
-
|
|
2937
|
+
logger11.info("Using OpenAI API adapter (AI SDK)", { model: codexModelId });
|
|
2930
2938
|
return {
|
|
2931
2939
|
adapter: new SdkAdapter({ providerId: "openai", modelId: codexModelId, apiKey: openaiKey }),
|
|
2932
2940
|
source: "api",
|
|
@@ -2936,7 +2944,7 @@ function tryApiAdapter(config, logger13) {
|
|
|
2936
2944
|
}
|
|
2937
2945
|
const googleKey = resolveApiKeyFromEnv(config.googleApiKey, "GOOGLE_AI_API_KEY");
|
|
2938
2946
|
if (googleKey !== void 0) {
|
|
2939
|
-
|
|
2947
|
+
logger11.info("Using Google AI API adapter (AI SDK)", { model: geminiModelId });
|
|
2940
2948
|
return {
|
|
2941
2949
|
adapter: new SdkAdapter({
|
|
2942
2950
|
providerId: "google",
|
|
@@ -2948,55 +2956,55 @@ function tryApiAdapter(config, logger13) {
|
|
|
2948
2956
|
reason: `Using Google AI API via AI SDK (model: ${geminiModelId})`
|
|
2949
2957
|
};
|
|
2950
2958
|
}
|
|
2951
|
-
|
|
2959
|
+
logger11.info("No API keys available for any provider");
|
|
2952
2960
|
return null;
|
|
2953
2961
|
}
|
|
2954
|
-
async function selectCliFirst(config,
|
|
2955
|
-
const cliResult = await tryCliAdapter(config,
|
|
2962
|
+
async function selectCliFirst(config, logger11, cache) {
|
|
2963
|
+
const cliResult = await tryCliAdapter(config, logger11, cache);
|
|
2956
2964
|
if (cliResult !== null) return cliResult;
|
|
2957
|
-
const apiResult = tryApiAdapter(config,
|
|
2965
|
+
const apiResult = tryApiAdapter(config, logger11);
|
|
2958
2966
|
if (apiResult !== null) return apiResult;
|
|
2959
2967
|
throw new Error(
|
|
2960
2968
|
"No adapters available. Install a CLI (claude/gemini/codex) or set ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_AI_API_KEY."
|
|
2961
2969
|
);
|
|
2962
2970
|
}
|
|
2963
|
-
async function selectApiFirst(config,
|
|
2964
|
-
const apiResult = tryApiAdapter(config,
|
|
2971
|
+
async function selectApiFirst(config, logger11, cache) {
|
|
2972
|
+
const apiResult = tryApiAdapter(config, logger11);
|
|
2965
2973
|
if (apiResult !== null) return apiResult;
|
|
2966
|
-
const cliResult = await tryCliAdapter(config,
|
|
2974
|
+
const cliResult = await tryCliAdapter(config, logger11, cache);
|
|
2967
2975
|
if (cliResult !== null) return cliResult;
|
|
2968
2976
|
throw new Error(
|
|
2969
2977
|
"No adapters available. Set ANTHROPIC_API_KEY/OPENAI_API_KEY/GOOGLE_AI_API_KEY or install a CLI (claude/gemini/codex)."
|
|
2970
2978
|
);
|
|
2971
2979
|
}
|
|
2972
|
-
async function selectCliOnly(config,
|
|
2973
|
-
const cliResult = await tryCliAdapter(config,
|
|
2980
|
+
async function selectCliOnly(config, logger11, cache) {
|
|
2981
|
+
const cliResult = await tryCliAdapter(config, logger11, cache);
|
|
2974
2982
|
if (cliResult !== null) return cliResult;
|
|
2975
2983
|
throw new Error(
|
|
2976
2984
|
"No CLI adapters available. Install and authenticate claude, gemini, or codex CLI."
|
|
2977
2985
|
);
|
|
2978
2986
|
}
|
|
2979
|
-
function selectApiOnly(config,
|
|
2980
|
-
const apiResult = tryApiAdapter(config,
|
|
2987
|
+
function selectApiOnly(config, logger11) {
|
|
2988
|
+
const apiResult = tryApiAdapter(config, logger11);
|
|
2981
2989
|
if (apiResult !== null) return apiResult;
|
|
2982
2990
|
throw new Error(
|
|
2983
2991
|
"No API key available. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_AI_API_KEY."
|
|
2984
2992
|
);
|
|
2985
2993
|
}
|
|
2986
2994
|
async function createAutoAdapter(config = {}) {
|
|
2987
|
-
const
|
|
2995
|
+
const logger11 = config.logger ?? defaultLogger;
|
|
2988
2996
|
const priority = config.priority ?? "cli-first";
|
|
2989
|
-
const cache = resolveCache(config,
|
|
2990
|
-
|
|
2997
|
+
const cache = resolveCache(config, logger11);
|
|
2998
|
+
logger11.info("Auto-selecting adapter", { priority, cacheEnabled: cache !== void 0 });
|
|
2991
2999
|
switch (priority) {
|
|
2992
3000
|
case "cli-first":
|
|
2993
|
-
return selectCliFirst(config,
|
|
3001
|
+
return selectCliFirst(config, logger11, cache);
|
|
2994
3002
|
case "api-first":
|
|
2995
|
-
return selectApiFirst(config,
|
|
3003
|
+
return selectApiFirst(config, logger11, cache);
|
|
2996
3004
|
case "cli-only":
|
|
2997
|
-
return selectCliOnly(config,
|
|
3005
|
+
return selectCliOnly(config, logger11, cache);
|
|
2998
3006
|
case "api-only":
|
|
2999
|
-
return selectApiOnly(config,
|
|
3007
|
+
return selectApiOnly(config, logger11);
|
|
3000
3008
|
default: {
|
|
3001
3009
|
const exhaustive = priority;
|
|
3002
3010
|
throw new Error(`Unknown priority: ${String(exhaustive)}`);
|
|
@@ -3247,13 +3255,13 @@ var EventBus = class {
|
|
|
3247
3255
|
topic: enrichedEvent.topic,
|
|
3248
3256
|
eventId: enrichedEvent.eventId
|
|
3249
3257
|
});
|
|
3250
|
-
const
|
|
3258
|
+
const promises = [];
|
|
3251
3259
|
for (const record of this.subscriptions.values()) {
|
|
3252
3260
|
if (topicMatchesPattern(enrichedEvent.topic, record.regex)) {
|
|
3253
|
-
|
|
3261
|
+
promises.push(this.invokeListenerAsync(record, enrichedEvent));
|
|
3254
3262
|
}
|
|
3255
3263
|
}
|
|
3256
|
-
await Promise.all(
|
|
3264
|
+
await Promise.all(promises);
|
|
3257
3265
|
}
|
|
3258
3266
|
/**
|
|
3259
3267
|
* Subscribe to events matching a topic pattern.
|
|
@@ -4191,14 +4199,14 @@ async function executeSingleVoteAttempt(role, proposal, adapter, timeoutMs) {
|
|
|
4191
4199
|
}
|
|
4192
4200
|
}
|
|
4193
4201
|
async function executeWithRetries(opts) {
|
|
4194
|
-
const { role, proposal, adapter, logger:
|
|
4202
|
+
const { role, proposal, adapter, logger: logger11, timeoutMs, maxRetries } = opts;
|
|
4195
4203
|
let lastError = "";
|
|
4196
4204
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
4197
4205
|
if (attempt > 0) {
|
|
4198
4206
|
const isRateLimit = isRateLimitError(lastError);
|
|
4199
4207
|
const baseDelay = isRateLimit ? RATE_LIMIT_RETRY_DELAY_MS : INITIAL_RETRY_DELAY_MS;
|
|
4200
4208
|
const delayMs = baseDelay * Math.pow(2, attempt - 1);
|
|
4201
|
-
|
|
4209
|
+
logger11.debug("Retrying vote execution", { role, attempt, delayMs, isRateLimit });
|
|
4202
4210
|
await delay(delayMs);
|
|
4203
4211
|
}
|
|
4204
4212
|
const result = await executeSingleVoteAttempt(role, proposal, adapter, timeoutMs);
|
|
@@ -4207,7 +4215,7 @@ async function executeWithRetries(opts) {
|
|
|
4207
4215
|
}
|
|
4208
4216
|
lastError = result.error;
|
|
4209
4217
|
const rateLimited = isRateLimitError(lastError);
|
|
4210
|
-
|
|
4218
|
+
logger11.warn("Vote attempt failed", {
|
|
4211
4219
|
role,
|
|
4212
4220
|
attempt: attempt + 1,
|
|
4213
4221
|
maxRetries: maxRetries + 1,
|
|
@@ -4218,35 +4226,85 @@ async function executeWithRetries(opts) {
|
|
|
4218
4226
|
return { error: lastError !== "" ? lastError : "Unknown error after all retries", ok: false };
|
|
4219
4227
|
}
|
|
4220
4228
|
|
|
4229
|
+
// src/cli/voter-agents-deadline.ts
|
|
4230
|
+
var DEADLINE_MESSAGE = "overall consensus deadline exceeded";
|
|
4231
|
+
function raceWithDeadline(p, role, deadlineMs) {
|
|
4232
|
+
let timer;
|
|
4233
|
+
const timeoutP = new Promise((resolve) => {
|
|
4234
|
+
timer = setTimeout(() => {
|
|
4235
|
+
resolve(createErrorVoteResult(role, DEADLINE_MESSAGE, deadlineMs));
|
|
4236
|
+
}, deadlineMs);
|
|
4237
|
+
});
|
|
4238
|
+
return Promise.race([p, timeoutP]).finally(() => {
|
|
4239
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
4240
|
+
});
|
|
4241
|
+
}
|
|
4242
|
+
async function launchVotesWithOverallDeadline(input) {
|
|
4243
|
+
const {
|
|
4244
|
+
roles,
|
|
4245
|
+
proposal,
|
|
4246
|
+
roleAdapters,
|
|
4247
|
+
fallbackAdapter,
|
|
4248
|
+
logger: logger11,
|
|
4249
|
+
voteOptions,
|
|
4250
|
+
interDelay,
|
|
4251
|
+
overallDeadlineMs,
|
|
4252
|
+
voteFn
|
|
4253
|
+
} = input;
|
|
4254
|
+
const startedAt = Date.now();
|
|
4255
|
+
const wrapped = roles.map(async (role, i) => {
|
|
4256
|
+
if (i > 0 && interDelay > 0) await delay(interDelay);
|
|
4257
|
+
const adapter = roleAdapters.get(role) ?? fallbackAdapter;
|
|
4258
|
+
const elapsed = Date.now() - startedAt;
|
|
4259
|
+
const remaining = Math.max(1, overallDeadlineMs - elapsed);
|
|
4260
|
+
return raceWithDeadline(voteFn(role, proposal, adapter, logger11, voteOptions), role, remaining);
|
|
4261
|
+
});
|
|
4262
|
+
const results = await Promise.all(wrapped);
|
|
4263
|
+
const expired = results.filter((r) => r.source === "error" && r.error === DEADLINE_MESSAGE);
|
|
4264
|
+
if (expired.length > 0) {
|
|
4265
|
+
logger11.warn("Consensus overall deadline reached; returning partial results", {
|
|
4266
|
+
totalRoles: roles.length,
|
|
4267
|
+
expiredRoles: expired.map((r) => r.role),
|
|
4268
|
+
overallDeadlineMs
|
|
4269
|
+
});
|
|
4270
|
+
}
|
|
4271
|
+
return results;
|
|
4272
|
+
}
|
|
4273
|
+
|
|
4221
4274
|
// src/cli/voter-agents.ts
|
|
4222
|
-
|
|
4275
|
+
function computeOverallConsensusDeadlineMs(timeoutMs, maxRetries, roleCount, interDelayMs) {
|
|
4276
|
+
const perVoteBudget = timeoutMs * (maxRetries + 1);
|
|
4277
|
+
const staggerBudget = Math.max(0, roleCount - 1) * interDelayMs;
|
|
4278
|
+
return perVoteBudget + staggerBudget + 6e4;
|
|
4279
|
+
}
|
|
4280
|
+
var DEFAULT_INTER_AGENT_DELAY_MS = 2e3;
|
|
4223
4281
|
var defaultLogger2 = createLogger({ component: "voter-agents" });
|
|
4224
|
-
async function executeAgentVote(role, proposal, adapter,
|
|
4282
|
+
async function executeAgentVote(role, proposal, adapter, logger11, options) {
|
|
4225
4283
|
const start = getTimeProvider().now();
|
|
4226
4284
|
const timeoutMs = options?.timeoutMs ?? resolveVoteTimeout();
|
|
4227
4285
|
const maxRetries = options?.maxRetries ?? VOTE_TIMEOUTS.maxRetries;
|
|
4228
4286
|
const allowSimulation = options?.allowSimulation ?? false;
|
|
4229
|
-
|
|
4287
|
+
logger11.info("Executing vote", { role, model: adapter.modelId, provider: adapter.providerId });
|
|
4230
4288
|
const result = await executeWithRetries({
|
|
4231
4289
|
role,
|
|
4232
4290
|
proposal,
|
|
4233
4291
|
adapter,
|
|
4234
|
-
logger:
|
|
4292
|
+
logger: logger11,
|
|
4235
4293
|
timeoutMs,
|
|
4236
4294
|
maxRetries
|
|
4237
4295
|
});
|
|
4238
4296
|
const processingTimeMs = getTimeProvider().now() - start;
|
|
4239
4297
|
if (result.ok) {
|
|
4240
|
-
|
|
4298
|
+
logger11.info("Vote completed", { role, model: adapter.modelId, decision: result.vote.decision });
|
|
4241
4299
|
return { role, vote: result.vote, processingTimeMs, source: "llm", cli: adapter.providerId };
|
|
4242
4300
|
}
|
|
4243
|
-
|
|
4301
|
+
logger11.error("Vote execution failed after all retries", void 0, {
|
|
4244
4302
|
role,
|
|
4245
4303
|
model: adapter.modelId,
|
|
4246
4304
|
errorMessage: result.error
|
|
4247
4305
|
});
|
|
4248
4306
|
if (allowSimulation) {
|
|
4249
|
-
|
|
4307
|
+
logger11.warn("Falling back to simulation (allowSimulation=true)", { role });
|
|
4250
4308
|
return createSimulationVoteResult(role, proposal, processingTimeMs, result.error);
|
|
4251
4309
|
}
|
|
4252
4310
|
return createErrorVoteResult(role, result.error, processingTimeMs);
|
|
@@ -4257,10 +4315,10 @@ var NoAdapterError = class extends Error {
|
|
|
4257
4315
|
this.name = "NoAdapterError";
|
|
4258
4316
|
}
|
|
4259
4317
|
};
|
|
4260
|
-
function resolveAdapter(options,
|
|
4318
|
+
function resolveAdapter(options, logger11) {
|
|
4261
4319
|
try {
|
|
4262
4320
|
if (options.adapter !== void 0) return { adapter: options.adapter };
|
|
4263
|
-
const registry = getGlobalRegistry({ logger:
|
|
4321
|
+
const registry = getGlobalRegistry({ logger: logger11 });
|
|
4264
4322
|
return { adapter: registry.getDefault() };
|
|
4265
4323
|
} catch (error) {
|
|
4266
4324
|
return { error: getErrorMessage(error) };
|
|
@@ -4271,29 +4329,29 @@ function assignUniformAdapter(roles, adapter) {
|
|
|
4271
4329
|
for (const role of roles) adapters.set(role, adapter);
|
|
4272
4330
|
return adapters;
|
|
4273
4331
|
}
|
|
4274
|
-
function createCliAdapterMap(clis,
|
|
4275
|
-
const registry = getGlobalRegistry({ logger:
|
|
4332
|
+
function createCliAdapterMap(clis, logger11) {
|
|
4333
|
+
const registry = getGlobalRegistry({ logger: logger11 });
|
|
4276
4334
|
const result = /* @__PURE__ */ new Map();
|
|
4277
4335
|
for (const cli of clis) {
|
|
4278
4336
|
result.set(cli, registry.getAdapterForCli(cli));
|
|
4279
4337
|
}
|
|
4280
4338
|
return result;
|
|
4281
4339
|
}
|
|
4282
|
-
async function resolveDiverseAdapters(roles,
|
|
4340
|
+
async function resolveDiverseAdapters(roles, logger11, fallbackAdapter) {
|
|
4283
4341
|
let availableClis;
|
|
4284
4342
|
try {
|
|
4285
4343
|
availableClis = await getAvailableClis();
|
|
4286
4344
|
} catch (e) {
|
|
4287
|
-
|
|
4345
|
+
logger11.warn("Failed to resolve available CLIs; falling back to single adapter", {
|
|
4288
4346
|
error: String(e)
|
|
4289
4347
|
});
|
|
4290
4348
|
availableClis = [];
|
|
4291
4349
|
}
|
|
4292
4350
|
if (availableClis.length <= 1) {
|
|
4293
|
-
|
|
4351
|
+
logger11.info("Using single adapter for all roles", { cliCount: availableClis.length });
|
|
4294
4352
|
return assignUniformAdapter(roles, fallbackAdapter);
|
|
4295
4353
|
}
|
|
4296
|
-
const cliAdapters = createCliAdapterMap(availableClis,
|
|
4354
|
+
const cliAdapters = createCliAdapterMap(availableClis, logger11);
|
|
4297
4355
|
if (cliAdapters.size <= 1) return assignUniformAdapter(roles, fallbackAdapter);
|
|
4298
4356
|
const cliList = [...cliAdapters.entries()];
|
|
4299
4357
|
const adapters = /* @__PURE__ */ new Map();
|
|
@@ -4305,7 +4363,7 @@ async function resolveDiverseAdapters(roles, logger13, fallbackAdapter) {
|
|
|
4305
4363
|
adapters.set(role, entry[1]);
|
|
4306
4364
|
assignments[role] = entry[0];
|
|
4307
4365
|
}
|
|
4308
|
-
|
|
4366
|
+
logger11.info("Diverse adapters assigned", {
|
|
4309
4367
|
cliCount: cliAdapters.size,
|
|
4310
4368
|
clis: [...cliAdapters.keys()],
|
|
4311
4369
|
roleAssignments: assignments
|
|
@@ -4313,38 +4371,46 @@ async function resolveDiverseAdapters(roles, logger13, fallbackAdapter) {
|
|
|
4313
4371
|
return adapters;
|
|
4314
4372
|
}
|
|
4315
4373
|
async function launchStaggeredVotes(input) {
|
|
4316
|
-
const { roles, proposal, roleAdapters, fallbackAdapter, logger:
|
|
4317
|
-
const
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
|
|
4325
|
-
|
|
4374
|
+
const { roles, proposal, roleAdapters, fallbackAdapter, logger: logger11, voteOptions, interDelay } = input;
|
|
4375
|
+
const overallDeadlineMs = computeOverallConsensusDeadlineMs(
|
|
4376
|
+
voteOptions.timeoutMs,
|
|
4377
|
+
voteOptions.maxRetries,
|
|
4378
|
+
roles.length,
|
|
4379
|
+
interDelay
|
|
4380
|
+
);
|
|
4381
|
+
return launchVotesWithOverallDeadline({
|
|
4382
|
+
roles,
|
|
4383
|
+
proposal,
|
|
4384
|
+
roleAdapters,
|
|
4385
|
+
fallbackAdapter,
|
|
4386
|
+
logger: logger11,
|
|
4387
|
+
voteOptions,
|
|
4388
|
+
interDelay,
|
|
4389
|
+
overallDeadlineMs,
|
|
4390
|
+
voteFn: executeAgentVote
|
|
4391
|
+
});
|
|
4326
4392
|
}
|
|
4327
4393
|
async function collectRealVotes(options) {
|
|
4328
|
-
const
|
|
4394
|
+
const logger11 = options.logger ?? defaultLogger2;
|
|
4329
4395
|
const { roles, proposal, simulate, allowSimulation } = options;
|
|
4330
4396
|
const timeoutMs = options.timeoutMs ?? resolveVoteTimeout();
|
|
4331
4397
|
const maxRetries = options.maxRetries ?? VOTE_TIMEOUTS.maxRetries;
|
|
4332
4398
|
if (simulate === true) {
|
|
4333
|
-
|
|
4399
|
+
logger11.info("Using simulation mode (explicitly requested)");
|
|
4334
4400
|
return createSimulatedVotes(roles, proposal);
|
|
4335
4401
|
}
|
|
4336
|
-
const adapterResult = resolveAdapter(options,
|
|
4402
|
+
const adapterResult = resolveAdapter(options, logger11);
|
|
4337
4403
|
if ("error" in adapterResult) {
|
|
4338
|
-
|
|
4404
|
+
logger11.error("No adapter available for voting", void 0, { error: adapterResult.error });
|
|
4339
4405
|
if (allowSimulation === true) {
|
|
4340
|
-
|
|
4406
|
+
logger11.warn("Falling back to simulation (allowSimulation=true)");
|
|
4341
4407
|
return createSimulatedVotes(roles, proposal, "No adapter available");
|
|
4342
4408
|
}
|
|
4343
4409
|
throw new NoAdapterError(
|
|
4344
4410
|
`No adapter available for voting: ${adapterResult.error}. Install a CLI (claude/gemini/codex) or set ANTHROPIC_API_KEY.`
|
|
4345
4411
|
);
|
|
4346
4412
|
}
|
|
4347
|
-
const roleAdapters = options.adapter !== void 0 ? assignUniformAdapter(roles, adapterResult.adapter) : await resolveDiverseAdapters(roles,
|
|
4413
|
+
const roleAdapters = options.adapter !== void 0 ? assignUniformAdapter(roles, adapterResult.adapter) : await resolveDiverseAdapters(roles, logger11, adapterResult.adapter);
|
|
4348
4414
|
const voteOptions = { timeoutMs, maxRetries, allowSimulation: allowSimulation ?? false };
|
|
4349
4415
|
const interDelay = options.interAgentDelayMs ?? DEFAULT_INTER_AGENT_DELAY_MS;
|
|
4350
4416
|
return launchStaggeredVotes({
|
|
@@ -4352,7 +4418,7 @@ async function collectRealVotes(options) {
|
|
|
4352
4418
|
proposal,
|
|
4353
4419
|
roleAdapters,
|
|
4354
4420
|
fallbackAdapter: adapterResult.adapter,
|
|
4355
|
-
logger:
|
|
4421
|
+
logger: logger11,
|
|
4356
4422
|
voteOptions,
|
|
4357
4423
|
interDelay
|
|
4358
4424
|
});
|
|
@@ -5297,11 +5363,11 @@ var ConsensusEngine = class {
|
|
|
5297
5363
|
logger;
|
|
5298
5364
|
metrics;
|
|
5299
5365
|
voterExpansionCallback;
|
|
5300
|
-
constructor(config,
|
|
5366
|
+
constructor(config, logger11) {
|
|
5301
5367
|
this.config = { ...DEFAULT_CONSENSUS_CONFIG, ...config };
|
|
5302
5368
|
this.cacheConfig = { ...DEFAULT_PROPOSAL_CACHE_CONFIG, ...config?.proposalCache };
|
|
5303
5369
|
this.quorumConfig = { ...DEFAULT_INCREMENTAL_QUORUM_CONFIG, ...config?.incrementalQuorum };
|
|
5304
|
-
this.logger =
|
|
5370
|
+
this.logger = logger11 ?? createLogger({ component: "ConsensusEngine" });
|
|
5305
5371
|
this.strategyFactory = new VotingStrategyFactory();
|
|
5306
5372
|
this.metrics = this.createInitialMetrics();
|
|
5307
5373
|
}
|
|
@@ -5724,8 +5790,8 @@ var ConsensusEngine = class {
|
|
|
5724
5790
|
this.logger.debug("Proposal cache cleared");
|
|
5725
5791
|
}
|
|
5726
5792
|
};
|
|
5727
|
-
function createConsensusEngine(config,
|
|
5728
|
-
return new ConsensusEngine(config,
|
|
5793
|
+
function createConsensusEngine(config, logger11) {
|
|
5794
|
+
return new ConsensusEngine(config, logger11);
|
|
5729
5795
|
}
|
|
5730
5796
|
|
|
5731
5797
|
// src/consensus/quorum-validator.ts
|
|
@@ -5733,8 +5799,8 @@ var DEFAULT_MIN_TRUST = 0.3;
|
|
|
5733
5799
|
var DEFAULT_MIN_WEIGHT = 0.1;
|
|
5734
5800
|
var QuorumValidator = class {
|
|
5735
5801
|
logger;
|
|
5736
|
-
constructor(
|
|
5737
|
-
this.logger =
|
|
5802
|
+
constructor(logger11) {
|
|
5803
|
+
this.logger = logger11 ?? createLogger({ component: "QuorumValidator" });
|
|
5738
5804
|
}
|
|
5739
5805
|
validateQuorum(input) {
|
|
5740
5806
|
const { votes, config } = input;
|
|
@@ -5961,8 +6027,8 @@ var QuorumValidator = class {
|
|
|
5961
6027
|
};
|
|
5962
6028
|
}
|
|
5963
6029
|
};
|
|
5964
|
-
function createQuorumValidator(
|
|
5965
|
-
return new QuorumValidator(
|
|
6030
|
+
function createQuorumValidator(logger11) {
|
|
6031
|
+
return new QuorumValidator(logger11);
|
|
5966
6032
|
}
|
|
5967
6033
|
|
|
5968
6034
|
// src/consensus/voting-protocol-helpers.ts
|
|
@@ -7571,44 +7637,12 @@ function buildResponse(input, result) {
|
|
|
7571
7637
|
}
|
|
7572
7638
|
|
|
7573
7639
|
// src/mcp/tools/tool-memory.ts
|
|
7574
|
-
import * as
|
|
7640
|
+
import * as fs3 from "fs";
|
|
7575
7641
|
import * as os3 from "os";
|
|
7576
|
-
import * as
|
|
7577
|
-
|
|
7578
|
-
// src/context/memory-backend-types.ts
|
|
7579
|
-
import { z as z9 } from "zod";
|
|
7580
|
-
var MemoryImportance = {
|
|
7581
|
-
LOW: "low",
|
|
7582
|
-
MEDIUM: "medium",
|
|
7583
|
-
HIGH: "high"
|
|
7584
|
-
};
|
|
7585
|
-
var MemoryImportanceSchema = z9.enum(["low", "medium", "high"]);
|
|
7586
|
-
var MemoryMetadataSchema = z9.object({
|
|
7587
|
-
importance: MemoryImportanceSchema,
|
|
7588
|
-
tags: z9.array(z9.string()).optional(),
|
|
7589
|
-
ttl: z9.number().positive().optional()
|
|
7590
|
-
});
|
|
7591
|
-
var MemoryEntrySchema = z9.object({
|
|
7592
|
-
key: z9.string().min(1),
|
|
7593
|
-
value: z9.unknown(),
|
|
7594
|
-
metadata: MemoryMetadataSchema,
|
|
7595
|
-
createdAt: z9.date(),
|
|
7596
|
-
accessedAt: z9.date()
|
|
7597
|
-
});
|
|
7598
|
-
var MemoryError = class extends NexusError {
|
|
7599
|
-
constructor(message, options) {
|
|
7600
|
-
super(message, { code: ErrorCode.INTERNAL_ERROR, ...options });
|
|
7601
|
-
this.name = "MemoryError";
|
|
7602
|
-
}
|
|
7603
|
-
};
|
|
7604
|
-
var HybridMemoryConfigSchema = z9.object({
|
|
7605
|
-
dbPath: z9.string().min(1),
|
|
7606
|
-
markdownDir: z9.string().min(1),
|
|
7607
|
-
autoExpire: z9.boolean().optional()
|
|
7608
|
-
});
|
|
7642
|
+
import * as path3 from "path";
|
|
7609
7643
|
|
|
7610
7644
|
// src/context/belief-core-types.ts
|
|
7611
|
-
import { z as
|
|
7645
|
+
import { z as z9 } from "zod";
|
|
7612
7646
|
var BeliefConfidence = {
|
|
7613
7647
|
/** Strong evidence, short reasoning chain */
|
|
7614
7648
|
HIGH: "high",
|
|
@@ -7619,7 +7653,7 @@ var BeliefConfidence = {
|
|
|
7619
7653
|
/** Speculative or hypothetical */
|
|
7620
7654
|
SPECULATIVE: "speculative"
|
|
7621
7655
|
};
|
|
7622
|
-
var BeliefConfidenceSchema =
|
|
7656
|
+
var BeliefConfidenceSchema = z9.enum(["high", "medium", "low", "speculative"]);
|
|
7623
7657
|
var BeliefSourceType = {
|
|
7624
7658
|
/** Direct observation from environment */
|
|
7625
7659
|
OBSERVATION: "observation",
|
|
@@ -7634,7 +7668,7 @@ var BeliefSourceType = {
|
|
|
7634
7668
|
/** Default or prior belief */
|
|
7635
7669
|
PRIOR: "prior"
|
|
7636
7670
|
};
|
|
7637
|
-
var BeliefSourceTypeSchema =
|
|
7671
|
+
var BeliefSourceTypeSchema = z9.enum([
|
|
7638
7672
|
"observation",
|
|
7639
7673
|
"inference",
|
|
7640
7674
|
"external",
|
|
@@ -7642,26 +7676,26 @@ var BeliefSourceTypeSchema = z10.enum([
|
|
|
7642
7676
|
"hindsight",
|
|
7643
7677
|
"prior"
|
|
7644
7678
|
]);
|
|
7645
|
-
var BeliefSchema =
|
|
7646
|
-
beliefId:
|
|
7647
|
-
subject:
|
|
7648
|
-
predicate:
|
|
7649
|
-
object:
|
|
7679
|
+
var BeliefSchema = z9.object({
|
|
7680
|
+
beliefId: z9.string().min(1),
|
|
7681
|
+
subject: z9.string().min(1),
|
|
7682
|
+
predicate: z9.string().min(1),
|
|
7683
|
+
object: z9.string(),
|
|
7650
7684
|
confidence: BeliefConfidenceSchema,
|
|
7651
7685
|
sourceType: BeliefSourceTypeSchema,
|
|
7652
|
-
sourceRef:
|
|
7653
|
-
derivedFrom:
|
|
7654
|
-
version:
|
|
7655
|
-
createdAt:
|
|
7656
|
-
updatedAt:
|
|
7657
|
-
superseded:
|
|
7658
|
-
supersededBy:
|
|
7659
|
-
domain:
|
|
7660
|
-
metadata:
|
|
7686
|
+
sourceRef: z9.string().optional(),
|
|
7687
|
+
derivedFrom: z9.array(z9.string()).optional(),
|
|
7688
|
+
version: z9.number().int().min(1),
|
|
7689
|
+
createdAt: z9.date(),
|
|
7690
|
+
updatedAt: z9.date(),
|
|
7691
|
+
superseded: z9.boolean(),
|
|
7692
|
+
supersededBy: z9.string().optional(),
|
|
7693
|
+
domain: z9.string().optional(),
|
|
7694
|
+
metadata: z9.record(z9.string(), z9.unknown()).optional()
|
|
7661
7695
|
});
|
|
7662
7696
|
|
|
7663
7697
|
// src/context/belief-update-types.ts
|
|
7664
|
-
import { z as
|
|
7698
|
+
import { z as z10 } from "zod";
|
|
7665
7699
|
var BeliefUpdateType = {
|
|
7666
7700
|
/** Add a new belief (retain) */
|
|
7667
7701
|
RETAIN: "retain",
|
|
@@ -7676,7 +7710,7 @@ var BeliefUpdateType = {
|
|
|
7676
7710
|
/** Weaken belief based on contradicting evidence */
|
|
7677
7711
|
WEAKEN: "weaken"
|
|
7678
7712
|
};
|
|
7679
|
-
var BeliefUpdateTypeSchema =
|
|
7713
|
+
var BeliefUpdateTypeSchema = z10.enum([
|
|
7680
7714
|
"retain",
|
|
7681
7715
|
"revise",
|
|
7682
7716
|
"supersede",
|
|
@@ -7684,75 +7718,75 @@ var BeliefUpdateTypeSchema = z11.enum([
|
|
|
7684
7718
|
"reinforce",
|
|
7685
7719
|
"weaken"
|
|
7686
7720
|
]);
|
|
7687
|
-
var BeliefUpdateSchema =
|
|
7688
|
-
updateId:
|
|
7689
|
-
beliefId:
|
|
7721
|
+
var BeliefUpdateSchema = z10.object({
|
|
7722
|
+
updateId: z10.string().min(1),
|
|
7723
|
+
beliefId: z10.string().min(1),
|
|
7690
7724
|
updateType: BeliefUpdateTypeSchema,
|
|
7691
|
-
previousState:
|
|
7692
|
-
newState:
|
|
7693
|
-
reason:
|
|
7694
|
-
evidence:
|
|
7695
|
-
timestamp:
|
|
7696
|
-
updatedBy:
|
|
7725
|
+
previousState: z10.record(z10.string(), z10.unknown()).optional(),
|
|
7726
|
+
newState: z10.record(z10.string(), z10.unknown()),
|
|
7727
|
+
reason: z10.string().min(1),
|
|
7728
|
+
evidence: z10.string().optional(),
|
|
7729
|
+
timestamp: z10.date(),
|
|
7730
|
+
updatedBy: z10.string().optional()
|
|
7697
7731
|
});
|
|
7698
|
-
var BeliefQuerySchema =
|
|
7699
|
-
subject:
|
|
7700
|
-
predicate:
|
|
7701
|
-
domain:
|
|
7732
|
+
var BeliefQuerySchema = z10.object({
|
|
7733
|
+
subject: z10.string().optional(),
|
|
7734
|
+
predicate: z10.string().optional(),
|
|
7735
|
+
domain: z10.string().optional(),
|
|
7702
7736
|
minConfidence: BeliefConfidenceSchema.optional(),
|
|
7703
|
-
includeSuperseded:
|
|
7737
|
+
includeSuperseded: z10.boolean().optional(),
|
|
7704
7738
|
sourceType: BeliefSourceTypeSchema.optional(),
|
|
7705
|
-
limit:
|
|
7706
|
-
orderBy:
|
|
7707
|
-
orderDirection:
|
|
7739
|
+
limit: z10.number().int().positive().max(1e3).optional(),
|
|
7740
|
+
orderBy: z10.enum(["createdAt", "updatedAt", "confidence"]).optional(),
|
|
7741
|
+
orderDirection: z10.enum(["asc", "desc"]).optional()
|
|
7708
7742
|
});
|
|
7709
7743
|
|
|
7710
7744
|
// src/context/belief-hindsight-types.ts
|
|
7711
|
-
import { z as
|
|
7712
|
-
var CounterfactualSchema =
|
|
7713
|
-
counterfactualId:
|
|
7714
|
-
hypothesis:
|
|
7715
|
-
affectedBeliefs:
|
|
7716
|
-
predictedOutcomes:
|
|
7717
|
-
actualOutcomes:
|
|
7718
|
-
validated:
|
|
7719
|
-
createdAt:
|
|
7720
|
-
taskContext:
|
|
7745
|
+
import { z as z11 } from "zod";
|
|
7746
|
+
var CounterfactualSchema = z11.object({
|
|
7747
|
+
counterfactualId: z11.string().min(1),
|
|
7748
|
+
hypothesis: z11.string().min(1),
|
|
7749
|
+
affectedBeliefs: z11.array(z11.string()),
|
|
7750
|
+
predictedOutcomes: z11.array(z11.string()),
|
|
7751
|
+
actualOutcomes: z11.array(z11.string()).optional(),
|
|
7752
|
+
validated: z11.boolean(),
|
|
7753
|
+
createdAt: z11.date(),
|
|
7754
|
+
taskContext: z11.string().optional()
|
|
7721
7755
|
});
|
|
7722
|
-
var HindsightRecordSchema =
|
|
7723
|
-
hindsightId:
|
|
7724
|
-
taskId:
|
|
7725
|
-
priorBeliefs:
|
|
7726
|
-
expectedOutcome:
|
|
7727
|
-
actualOutcome:
|
|
7728
|
-
outcomeMatched:
|
|
7729
|
-
correctedBeliefs:
|
|
7730
|
-
newBeliefs:
|
|
7731
|
-
lessons:
|
|
7732
|
-
createdAt:
|
|
7756
|
+
var HindsightRecordSchema = z11.object({
|
|
7757
|
+
hindsightId: z11.string().min(1),
|
|
7758
|
+
taskId: z11.string().min(1),
|
|
7759
|
+
priorBeliefs: z11.array(z11.string()),
|
|
7760
|
+
expectedOutcome: z11.string(),
|
|
7761
|
+
actualOutcome: z11.string(),
|
|
7762
|
+
outcomeMatched: z11.boolean(),
|
|
7763
|
+
correctedBeliefs: z11.array(z11.string()),
|
|
7764
|
+
newBeliefs: z11.array(z11.string()),
|
|
7765
|
+
lessons: z11.array(z11.string()),
|
|
7766
|
+
createdAt: z11.date()
|
|
7733
7767
|
});
|
|
7734
7768
|
|
|
7735
7769
|
// src/context/belief-memory-interface.ts
|
|
7736
|
-
import { z as
|
|
7737
|
-
var BeliefMemoryStatsSchema =
|
|
7738
|
-
totalBeliefs:
|
|
7739
|
-
activeBeliefs:
|
|
7740
|
-
supersededBeliefs:
|
|
7741
|
-
beliefsByConfidence:
|
|
7742
|
-
beliefsBySource:
|
|
7743
|
-
totalUpdates:
|
|
7744
|
-
totalCounterfactuals:
|
|
7745
|
-
totalHindsightRecords:
|
|
7746
|
-
oldestBelief:
|
|
7747
|
-
newestBelief:
|
|
7770
|
+
import { z as z12 } from "zod";
|
|
7771
|
+
var BeliefMemoryStatsSchema = z12.object({
|
|
7772
|
+
totalBeliefs: z12.number().int().min(0),
|
|
7773
|
+
activeBeliefs: z12.number().int().min(0),
|
|
7774
|
+
supersededBeliefs: z12.number().int().min(0),
|
|
7775
|
+
beliefsByConfidence: z12.record(BeliefConfidenceSchema, z12.number().int().min(0)),
|
|
7776
|
+
beliefsBySource: z12.record(BeliefSourceTypeSchema, z12.number().int().min(0)),
|
|
7777
|
+
totalUpdates: z12.number().int().min(0),
|
|
7778
|
+
totalCounterfactuals: z12.number().int().min(0),
|
|
7779
|
+
totalHindsightRecords: z12.number().int().min(0),
|
|
7780
|
+
oldestBelief: z12.date().optional(),
|
|
7781
|
+
newestBelief: z12.date().optional()
|
|
7748
7782
|
});
|
|
7749
|
-
var BeliefMemoryConfigSchema =
|
|
7750
|
-
maxBeliefsPerSubject:
|
|
7751
|
-
maxTotalBeliefs:
|
|
7752
|
-
autoPruneAge:
|
|
7753
|
-
enableInference:
|
|
7783
|
+
var BeliefMemoryConfigSchema = z12.object({
|
|
7784
|
+
maxBeliefsPerSubject: z12.number().int().positive().optional(),
|
|
7785
|
+
maxTotalBeliefs: z12.number().int().positive().optional(),
|
|
7786
|
+
autoPruneAge: z12.number().positive().optional(),
|
|
7787
|
+
enableInference: z12.boolean().optional(),
|
|
7754
7788
|
defaultConfidence: BeliefConfidenceSchema.optional(),
|
|
7755
|
-
maxInferenceDepth:
|
|
7789
|
+
maxInferenceDepth: z12.number().int().positive().max(10).optional()
|
|
7756
7790
|
});
|
|
7757
7791
|
var DEFAULT_BELIEF_CONFIG = {
|
|
7758
7792
|
maxBeliefsPerSubject: 100,
|
|
@@ -8272,13 +8306,13 @@ var HindsightBeliefMemory = class {
|
|
|
8272
8306
|
domainIndex = /* @__PURE__ */ new Map();
|
|
8273
8307
|
config;
|
|
8274
8308
|
logger;
|
|
8275
|
-
constructor(config,
|
|
8309
|
+
constructor(config, logger11) {
|
|
8276
8310
|
const validation = BeliefMemoryConfigSchema.safeParse(config ?? {});
|
|
8277
8311
|
if (!validation.success) {
|
|
8278
8312
|
throw new MemoryError(`Invalid BeliefMemoryConfig: ${formatZodError(validation.error)}`);
|
|
8279
8313
|
}
|
|
8280
8314
|
this.config = { ...DEFAULT_BELIEF_CONFIG, ...config };
|
|
8281
|
-
this.logger =
|
|
8315
|
+
this.logger = logger11 ?? createLogger({ component: "HindsightBeliefMemory" });
|
|
8282
8316
|
this.logger.info("HindsightBeliefMemory initialized", { config: this.config });
|
|
8283
8317
|
}
|
|
8284
8318
|
get auditStores() {
|
|
@@ -8648,448 +8682,8 @@ var HindsightBeliefMemory = class {
|
|
|
8648
8682
|
}
|
|
8649
8683
|
};
|
|
8650
8684
|
|
|
8651
|
-
// src/context/memory-backend.ts
|
|
8652
|
-
import { z as z14 } from "zod";
|
|
8653
|
-
|
|
8654
|
-
// src/context/memory-markdown.ts
|
|
8655
|
-
import * as fs2 from "fs";
|
|
8656
|
-
import * as path2 from "path";
|
|
8657
|
-
var MemoryMarkdownHelper = class {
|
|
8658
|
-
constructor(markdownDir, logger13) {
|
|
8659
|
-
this.markdownDir = markdownDir;
|
|
8660
|
-
this.logger = logger13;
|
|
8661
|
-
}
|
|
8662
|
-
/**
|
|
8663
|
-
* Ensure the Markdown export directory exists.
|
|
8664
|
-
*/
|
|
8665
|
-
ensureDir() {
|
|
8666
|
-
if (!fs2.existsSync(this.markdownDir)) {
|
|
8667
|
-
fs2.mkdirSync(this.markdownDir, { recursive: true });
|
|
8668
|
-
this.logger.debug("Created Markdown directory", { path: this.markdownDir });
|
|
8669
|
-
}
|
|
8670
|
-
}
|
|
8671
|
-
/**
|
|
8672
|
-
* Write a memory entry to Markdown file.
|
|
8673
|
-
*/
|
|
8674
|
-
async write(key, value, metadata, createdAt) {
|
|
8675
|
-
const filename = this.keyToFilename(key);
|
|
8676
|
-
const filepath = path2.join(this.markdownDir, filename);
|
|
8677
|
-
const content = this.format(key, value, metadata, createdAt);
|
|
8678
|
-
try {
|
|
8679
|
-
await fs2.promises.writeFile(filepath, content, "utf-8");
|
|
8680
|
-
this.logger.debug("Wrote Markdown file", { key, filepath });
|
|
8681
|
-
} catch (error) {
|
|
8682
|
-
this.logger.warn("Failed to write Markdown file", { key, filepath, error });
|
|
8683
|
-
}
|
|
8684
|
-
}
|
|
8685
|
-
/**
|
|
8686
|
-
* Delete a Markdown file for a memory.
|
|
8687
|
-
*/
|
|
8688
|
-
delete(key) {
|
|
8689
|
-
const filename = this.keyToFilename(key);
|
|
8690
|
-
const filepath = path2.join(this.markdownDir, filename);
|
|
8691
|
-
try {
|
|
8692
|
-
if (fs2.existsSync(filepath)) {
|
|
8693
|
-
fs2.unlinkSync(filepath);
|
|
8694
|
-
this.logger.debug("Deleted Markdown file", { key, filepath });
|
|
8695
|
-
}
|
|
8696
|
-
} catch (error) {
|
|
8697
|
-
this.logger.warn("Failed to delete Markdown file", { key, filepath, error });
|
|
8698
|
-
}
|
|
8699
|
-
}
|
|
8700
|
-
/**
|
|
8701
|
-
* Convert a memory key to a safe filename.
|
|
8702
|
-
*/
|
|
8703
|
-
keyToFilename(key) {
|
|
8704
|
-
const safeKey = key.replace(/[^a-zA-Z0-9-_]/g, "_").replace(/_+/g, "_").substring(0, 200);
|
|
8705
|
-
return `${safeKey}.md`;
|
|
8706
|
-
}
|
|
8707
|
-
/**
|
|
8708
|
-
* Format a memory entry as Markdown.
|
|
8709
|
-
*/
|
|
8710
|
-
format(key, value, metadata, createdAt) {
|
|
8711
|
-
const lines = [
|
|
8712
|
-
`# Memory: ${key}`,
|
|
8713
|
-
"",
|
|
8714
|
-
"## Metadata",
|
|
8715
|
-
"",
|
|
8716
|
-
`- **Importance:** ${metadata.importance}`,
|
|
8717
|
-
`- **Created:** ${createdAt.toISOString()}`
|
|
8718
|
-
];
|
|
8719
|
-
if (metadata.tags !== void 0 && metadata.tags.length > 0) {
|
|
8720
|
-
lines.push(`- **Tags:** ${metadata.tags.join(", ")}`);
|
|
8721
|
-
}
|
|
8722
|
-
if (metadata.ttl !== void 0) {
|
|
8723
|
-
const expiresAt = new Date(createdAt.getTime() + metadata.ttl);
|
|
8724
|
-
lines.push(`- **Expires:** ${expiresAt.toISOString()}`);
|
|
8725
|
-
}
|
|
8726
|
-
lines.push("", "## Value", "");
|
|
8727
|
-
if (typeof value === "string") {
|
|
8728
|
-
lines.push(value);
|
|
8729
|
-
} else if (value === null) {
|
|
8730
|
-
lines.push("`null`");
|
|
8731
|
-
} else if (typeof value === "object") {
|
|
8732
|
-
lines.push("```json", JSON.stringify(value, null, 2), "```");
|
|
8733
|
-
} else {
|
|
8734
|
-
const stringValue = typeof value === "number" || typeof value === "boolean" ? String(value) : JSON.stringify(value);
|
|
8735
|
-
lines.push(`\`${stringValue}\``);
|
|
8736
|
-
}
|
|
8737
|
-
lines.push("");
|
|
8738
|
-
return lines.join("\n");
|
|
8739
|
-
}
|
|
8740
|
-
};
|
|
8741
|
-
|
|
8742
|
-
// src/context/memory-operations.ts
|
|
8743
|
-
function safeParseJson(raw) {
|
|
8744
|
-
try {
|
|
8745
|
-
return JSON.parse(raw);
|
|
8746
|
-
} catch {
|
|
8747
|
-
return null;
|
|
8748
|
-
}
|
|
8749
|
-
}
|
|
8750
|
-
function parseMetadataOrDefault(raw) {
|
|
8751
|
-
const parsed = safeParseJson(raw);
|
|
8752
|
-
if (parsed !== null && typeof parsed === "object") return parsed;
|
|
8753
|
-
return { importance: "medium" };
|
|
8754
|
-
}
|
|
8755
|
-
function rowToEntry(row) {
|
|
8756
|
-
return {
|
|
8757
|
-
key: row.key,
|
|
8758
|
-
value: safeParseJson(row.value),
|
|
8759
|
-
metadata: parseMetadataOrDefault(row.metadata),
|
|
8760
|
-
createdAt: new Date(row.created_at),
|
|
8761
|
-
accessedAt: new Date(row.accessed_at)
|
|
8762
|
-
};
|
|
8763
|
-
}
|
|
8764
|
-
function sanitizeFtsQuery(query) {
|
|
8765
|
-
return query.replace(/[*:^"(){}[\]]/g, " ").replace(/\bAND\b/gi, " ").replace(/\bOR\b/gi, " ").replace(/\bNOT\b/gi, " ").replace(/\bNEAR\b/gi, " ").replace(/\s+/g, " ").trim();
|
|
8766
|
-
}
|
|
8767
|
-
function cleanupExpiredEntries(rows, database, autoExpire, logger13) {
|
|
8768
|
-
const now = getTimeProvider().now();
|
|
8769
|
-
const entries = [];
|
|
8770
|
-
const expiredKeys = [];
|
|
8771
|
-
for (const row of rows) {
|
|
8772
|
-
if (autoExpire && row.expires_at !== null && row.expires_at < now) {
|
|
8773
|
-
expiredKeys.push(row.key);
|
|
8774
|
-
continue;
|
|
8775
|
-
}
|
|
8776
|
-
entries.push(rowToEntry(row));
|
|
8777
|
-
}
|
|
8778
|
-
if (expiredKeys.length > 0) {
|
|
8779
|
-
const deleteStmt = database.prepare(
|
|
8780
|
-
`DELETE FROM memories WHERE key IN (${expiredKeys.map(() => "?").join(",")})`
|
|
8781
|
-
);
|
|
8782
|
-
deleteStmt.run(...expiredKeys);
|
|
8783
|
-
logger13.debug("Auto-expired memories", { count: expiredKeys.length });
|
|
8784
|
-
}
|
|
8785
|
-
return { entries, expiredCount: expiredKeys.length };
|
|
8786
|
-
}
|
|
8787
|
-
function countMemories(database) {
|
|
8788
|
-
try {
|
|
8789
|
-
const stmt = database.prepare("SELECT COUNT(*) as count FROM memories");
|
|
8790
|
-
const row = stmt.get();
|
|
8791
|
-
return ok(row?.count ?? 0);
|
|
8792
|
-
} catch (error) {
|
|
8793
|
-
const causeError = error instanceof Error ? error : new Error(String(error));
|
|
8794
|
-
return err(new MemoryError("Failed to count memories", { cause: causeError }));
|
|
8795
|
-
}
|
|
8796
|
-
}
|
|
8797
|
-
function expireAllEntries(database, logger13) {
|
|
8798
|
-
try {
|
|
8799
|
-
const stmt = database.prepare(
|
|
8800
|
-
"DELETE FROM memories WHERE expires_at IS NOT NULL AND expires_at < ?"
|
|
8801
|
-
);
|
|
8802
|
-
const result = stmt.run(getTimeProvider().now());
|
|
8803
|
-
logger13.info("Expired memories", { count: result.changes });
|
|
8804
|
-
return ok(result.changes);
|
|
8805
|
-
} catch (error) {
|
|
8806
|
-
const causeError = error instanceof Error ? error : new Error(String(error));
|
|
8807
|
-
return err(new MemoryError("Failed to expire memories", { cause: causeError }));
|
|
8808
|
-
}
|
|
8809
|
-
}
|
|
8810
|
-
function pruneOldEntries(database, olderThan, logger13) {
|
|
8811
|
-
try {
|
|
8812
|
-
const stmt = database.prepare("DELETE FROM memories WHERE created_at < ?");
|
|
8813
|
-
const result = stmt.run(olderThan.getTime());
|
|
8814
|
-
logger13.info("Pruned old memories", {
|
|
8815
|
-
olderThan: olderThan.toISOString(),
|
|
8816
|
-
count: result.changes
|
|
8817
|
-
});
|
|
8818
|
-
return ok(result.changes);
|
|
8819
|
-
} catch (error) {
|
|
8820
|
-
const causeError = error instanceof Error ? error : new Error(String(error));
|
|
8821
|
-
return err(
|
|
8822
|
-
new MemoryError("Failed to prune memories", {
|
|
8823
|
-
cause: causeError,
|
|
8824
|
-
context: { olderThan: olderThan.toISOString() }
|
|
8825
|
-
})
|
|
8826
|
-
);
|
|
8827
|
-
}
|
|
8828
|
-
}
|
|
8829
|
-
|
|
8830
|
-
// src/context/memory-backend.ts
|
|
8831
|
-
var HybridMemoryBackend = class {
|
|
8832
|
-
dbPath;
|
|
8833
|
-
logger;
|
|
8834
|
-
autoExpire;
|
|
8835
|
-
markdown;
|
|
8836
|
-
db = null;
|
|
8837
|
-
initialized = false;
|
|
8838
|
-
initPromise;
|
|
8839
|
-
constructor(config) {
|
|
8840
|
-
const validation = HybridMemoryConfigSchema.safeParse(config);
|
|
8841
|
-
if (!validation.success) {
|
|
8842
|
-
throw new ValidationError(
|
|
8843
|
-
`Invalid HybridMemoryBackend config: ${formatZodError(validation.error)}`,
|
|
8844
|
-
{
|
|
8845
|
-
context: { config, validationErrors: validation.error.issues }
|
|
8846
|
-
}
|
|
8847
|
-
);
|
|
8848
|
-
}
|
|
8849
|
-
this.dbPath = config.dbPath;
|
|
8850
|
-
this.logger = config.logger ?? createLogger({ component: "HybridMemoryBackend" });
|
|
8851
|
-
this.autoExpire = config.autoExpire ?? true;
|
|
8852
|
-
this.markdown = new MemoryMarkdownHelper(config.markdownDir, this.logger);
|
|
8853
|
-
}
|
|
8854
|
-
initializeWithDatabase(database) {
|
|
8855
|
-
this.db = database;
|
|
8856
|
-
this.createTables();
|
|
8857
|
-
this.markdown.ensureDir();
|
|
8858
|
-
this.initialized = true;
|
|
8859
|
-
this.logger.info("HybridMemoryBackend initialized", { dbPath: this.dbPath });
|
|
8860
|
-
}
|
|
8861
|
-
async initialize() {
|
|
8862
|
-
if (this.initialized) return ok(void 0);
|
|
8863
|
-
this.initPromise ??= this.doInitialize().finally(() => {
|
|
8864
|
-
this.initPromise = void 0;
|
|
8865
|
-
});
|
|
8866
|
-
return this.initPromise;
|
|
8867
|
-
}
|
|
8868
|
-
async doInitialize() {
|
|
8869
|
-
try {
|
|
8870
|
-
const betterSqlite3Module = await import("better-sqlite3").catch((cause) => {
|
|
8871
|
-
this.logger.debug("better-sqlite3 import failed", { error: String(cause) });
|
|
8872
|
-
return null;
|
|
8873
|
-
});
|
|
8874
|
-
if (betterSqlite3Module === null) {
|
|
8875
|
-
return err(
|
|
8876
|
-
new MemoryError("better-sqlite3 not installed. Install: npm install better-sqlite3", {
|
|
8877
|
-
context: { dbPath: this.dbPath }
|
|
8878
|
-
})
|
|
8879
|
-
);
|
|
8880
|
-
}
|
|
8881
|
-
const Database = betterSqlite3Module.default;
|
|
8882
|
-
this.db = new Database(this.dbPath);
|
|
8883
|
-
this.createTables();
|
|
8884
|
-
this.markdown.ensureDir();
|
|
8885
|
-
this.initialized = true;
|
|
8886
|
-
this.logger.info("HybridMemoryBackend initialized", { dbPath: this.dbPath });
|
|
8887
|
-
return ok(void 0);
|
|
8888
|
-
} catch (error) {
|
|
8889
|
-
const causeError = error instanceof Error ? error : new Error(String(error));
|
|
8890
|
-
this.logger.error("Failed to initialize HybridMemoryBackend", causeError);
|
|
8891
|
-
return err(
|
|
8892
|
-
new MemoryError("Failed to initialize memory backend", {
|
|
8893
|
-
cause: causeError,
|
|
8894
|
-
context: { dbPath: this.dbPath }
|
|
8895
|
-
})
|
|
8896
|
-
);
|
|
8897
|
-
}
|
|
8898
|
-
}
|
|
8899
|
-
createTables() {
|
|
8900
|
-
const database = this.getDatabase();
|
|
8901
|
-
database.exec(`
|
|
8902
|
-
CREATE TABLE IF NOT EXISTS memories (
|
|
8903
|
-
key TEXT PRIMARY KEY, value TEXT NOT NULL, metadata TEXT NOT NULL,
|
|
8904
|
-
created_at INTEGER NOT NULL, accessed_at INTEGER NOT NULL, expires_at INTEGER
|
|
8905
|
-
)
|
|
8906
|
-
`);
|
|
8907
|
-
database.exec(`
|
|
8908
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
8909
|
-
key, value, tags, content='memories', content_rowid='rowid'
|
|
8910
|
-
)
|
|
8911
|
-
`);
|
|
8912
|
-
database.exec(`
|
|
8913
|
-
CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
|
|
8914
|
-
INSERT INTO memories_fts(rowid, key, value, tags)
|
|
8915
|
-
SELECT rowid, NEW.key, NEW.value, json_extract(NEW.metadata, '$.tags') FROM memories WHERE key = NEW.key;
|
|
8916
|
-
END
|
|
8917
|
-
`);
|
|
8918
|
-
database.exec(`
|
|
8919
|
-
CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
|
|
8920
|
-
INSERT INTO memories_fts(memories_fts, rowid, key, value, tags)
|
|
8921
|
-
VALUES('delete', OLD.rowid, OLD.key, OLD.value, json_extract(OLD.metadata, '$.tags'));
|
|
8922
|
-
END
|
|
8923
|
-
`);
|
|
8924
|
-
database.exec(`
|
|
8925
|
-
CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
|
|
8926
|
-
INSERT INTO memories_fts(memories_fts, rowid, key, value, tags)
|
|
8927
|
-
VALUES('delete', OLD.rowid, OLD.key, OLD.value, json_extract(OLD.metadata, '$.tags'));
|
|
8928
|
-
INSERT INTO memories_fts(rowid, key, value, tags)
|
|
8929
|
-
SELECT rowid, NEW.key, NEW.value, json_extract(NEW.metadata, '$.tags') FROM memories WHERE key = NEW.key;
|
|
8930
|
-
END
|
|
8931
|
-
`);
|
|
8932
|
-
database.exec(
|
|
8933
|
-
`CREATE INDEX IF NOT EXISTS idx_memories_expires_at ON memories(expires_at) WHERE expires_at IS NOT NULL`
|
|
8934
|
-
);
|
|
8935
|
-
database.exec(`CREATE INDEX IF NOT EXISTS idx_memories_created_at ON memories(created_at)`);
|
|
8936
|
-
this.logger.debug("Database tables created");
|
|
8937
|
-
}
|
|
8938
|
-
getDatabase() {
|
|
8939
|
-
if (this.db === null) throw new MemoryError("Database not initialized");
|
|
8940
|
-
return this.db;
|
|
8941
|
-
}
|
|
8942
|
-
ensureInitialized() {
|
|
8943
|
-
if (!this.initialized || this.db === null) {
|
|
8944
|
-
throw new MemoryError("HybridMemoryBackend not initialized. Call initialize() first.");
|
|
8945
|
-
}
|
|
8946
|
-
}
|
|
8947
|
-
async store(key, value, metadata) {
|
|
8948
|
-
try {
|
|
8949
|
-
this.ensureInitialized();
|
|
8950
|
-
const keyValidation = z14.string().min(1).safeParse(key);
|
|
8951
|
-
if (!keyValidation.success)
|
|
8952
|
-
return err(new MemoryError("Invalid key: must be non-empty string", { context: { key } }));
|
|
8953
|
-
const metadataValidation = MemoryMetadataSchema.safeParse(metadata);
|
|
8954
|
-
if (!metadataValidation.success)
|
|
8955
|
-
return err(
|
|
8956
|
-
new MemoryError("Invalid metadata", {
|
|
8957
|
-
context: { metadata, errors: metadataValidation.error.issues }
|
|
8958
|
-
})
|
|
8959
|
-
);
|
|
8960
|
-
const now = getTimeProvider().now();
|
|
8961
|
-
const expiresAt = metadata.ttl !== void 0 ? now + metadata.ttl : null;
|
|
8962
|
-
const database = this.getDatabase();
|
|
8963
|
-
const stmt = database.prepare(
|
|
8964
|
-
`INSERT OR REPLACE INTO memories (key, value, metadata, created_at, accessed_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)`
|
|
8965
|
-
);
|
|
8966
|
-
stmt.run(key, JSON.stringify(value), JSON.stringify(metadata), now, now, expiresAt);
|
|
8967
|
-
this.logger.debug("Stored memory", { key, importance: metadata.importance });
|
|
8968
|
-
if (metadata.importance === MemoryImportance.HIGH)
|
|
8969
|
-
await this.markdown.write(key, value, metadata, new Date(now));
|
|
8970
|
-
return ok(void 0);
|
|
8971
|
-
} catch (error) {
|
|
8972
|
-
const causeError = error instanceof Error ? error : new Error(String(error));
|
|
8973
|
-
this.logger.error("Failed to store memory", causeError, { key });
|
|
8974
|
-
return err(
|
|
8975
|
-
new MemoryError("Failed to store memory", { cause: causeError, context: { key } })
|
|
8976
|
-
);
|
|
8977
|
-
}
|
|
8978
|
-
}
|
|
8979
|
-
retrieve(key) {
|
|
8980
|
-
try {
|
|
8981
|
-
this.ensureInitialized();
|
|
8982
|
-
const database = this.getDatabase();
|
|
8983
|
-
const stmt = database.prepare(
|
|
8984
|
-
`SELECT key, value, metadata, created_at, accessed_at, expires_at FROM memories WHERE key = ?`
|
|
8985
|
-
);
|
|
8986
|
-
const row = stmt.get(key);
|
|
8987
|
-
if (row === void 0) return Promise.resolve(ok(null));
|
|
8988
|
-
if (this.autoExpire && row.expires_at !== null && row.expires_at < getTimeProvider().now()) {
|
|
8989
|
-
database.prepare("DELETE FROM memories WHERE key = ?").run(key);
|
|
8990
|
-
this.logger.debug("Auto-expired memory", { key });
|
|
8991
|
-
return Promise.resolve(ok(null));
|
|
8992
|
-
}
|
|
8993
|
-
database.prepare("UPDATE memories SET accessed_at = ? WHERE key = ?").run(getTimeProvider().now(), key);
|
|
8994
|
-
return Promise.resolve(ok(JSON.parse(row.value)));
|
|
8995
|
-
} catch (error) {
|
|
8996
|
-
const causeError = error instanceof Error ? error : new Error(String(error));
|
|
8997
|
-
this.logger.error("Failed to retrieve memory", causeError, { key });
|
|
8998
|
-
return Promise.resolve(
|
|
8999
|
-
err(new MemoryError("Failed to retrieve memory", { cause: causeError, context: { key } }))
|
|
9000
|
-
);
|
|
9001
|
-
}
|
|
9002
|
-
}
|
|
9003
|
-
search(query, limit) {
|
|
9004
|
-
try {
|
|
9005
|
-
this.ensureInitialized();
|
|
9006
|
-
if (limit <= 0 || limit > 1e3)
|
|
9007
|
-
return Promise.resolve(
|
|
9008
|
-
err(new MemoryError("Invalid limit: must be between 1 and 1000", { context: { limit } }))
|
|
9009
|
-
);
|
|
9010
|
-
const sanitizedQuery = sanitizeFtsQuery(query);
|
|
9011
|
-
if (sanitizedQuery.length === 0) return Promise.resolve(ok([]));
|
|
9012
|
-
const database = this.getDatabase();
|
|
9013
|
-
const stmt = database.prepare(`
|
|
9014
|
-
SELECT m.key, m.value, m.metadata, m.created_at, m.accessed_at, m.expires_at
|
|
9015
|
-
FROM memories m INNER JOIN memories_fts fts ON m.rowid = fts.rowid
|
|
9016
|
-
WHERE memories_fts MATCH ? ORDER BY rank LIMIT ?
|
|
9017
|
-
`);
|
|
9018
|
-
const rows = stmt.all(sanitizedQuery, limit);
|
|
9019
|
-
const { entries } = cleanupExpiredEntries(rows, database, this.autoExpire, this.logger);
|
|
9020
|
-
return Promise.resolve(ok(entries));
|
|
9021
|
-
} catch (error) {
|
|
9022
|
-
const causeError = error instanceof Error ? error : new Error(String(error));
|
|
9023
|
-
this.logger.error("Failed to search memories", causeError, { query });
|
|
9024
|
-
return Promise.resolve(
|
|
9025
|
-
err(
|
|
9026
|
-
new MemoryError("Failed to search memories", {
|
|
9027
|
-
cause: causeError,
|
|
9028
|
-
context: { query, limit }
|
|
9029
|
-
})
|
|
9030
|
-
)
|
|
9031
|
-
);
|
|
9032
|
-
}
|
|
9033
|
-
}
|
|
9034
|
-
prune(olderThan) {
|
|
9035
|
-
this.ensureInitialized();
|
|
9036
|
-
return Promise.resolve(pruneOldEntries(this.getDatabase(), olderThan, this.logger));
|
|
9037
|
-
}
|
|
9038
|
-
expireAll() {
|
|
9039
|
-
this.ensureInitialized();
|
|
9040
|
-
return Promise.resolve(expireAllEntries(this.getDatabase(), this.logger));
|
|
9041
|
-
}
|
|
9042
|
-
delete(key) {
|
|
9043
|
-
try {
|
|
9044
|
-
this.ensureInitialized();
|
|
9045
|
-
const result = this.getDatabase().prepare("DELETE FROM memories WHERE key = ?").run(key);
|
|
9046
|
-
if (result.changes > 0) {
|
|
9047
|
-
this.markdown.delete(key);
|
|
9048
|
-
this.logger.debug("Deleted memory", { key });
|
|
9049
|
-
return Promise.resolve(ok(true));
|
|
9050
|
-
}
|
|
9051
|
-
return Promise.resolve(ok(false));
|
|
9052
|
-
} catch (error) {
|
|
9053
|
-
const causeError = error instanceof Error ? error : new Error(String(error));
|
|
9054
|
-
this.logger.error("Failed to delete memory", causeError, { key });
|
|
9055
|
-
return Promise.resolve(
|
|
9056
|
-
err(new MemoryError("Failed to delete memory", { cause: causeError, context: { key } }))
|
|
9057
|
-
);
|
|
9058
|
-
}
|
|
9059
|
-
}
|
|
9060
|
-
getAll(limit = 100) {
|
|
9061
|
-
try {
|
|
9062
|
-
this.ensureInitialized();
|
|
9063
|
-
const database = this.getDatabase();
|
|
9064
|
-
const rows = database.prepare(
|
|
9065
|
-
`SELECT key, value, metadata, created_at, accessed_at, expires_at FROM memories ORDER BY accessed_at DESC LIMIT ?`
|
|
9066
|
-
).all(limit);
|
|
9067
|
-
const { entries } = cleanupExpiredEntries(rows, database, this.autoExpire, this.logger);
|
|
9068
|
-
return Promise.resolve(ok(entries));
|
|
9069
|
-
} catch (error) {
|
|
9070
|
-
const causeError = error instanceof Error ? error : new Error(String(error));
|
|
9071
|
-
this.logger.error("Failed to get all memories", causeError);
|
|
9072
|
-
return Promise.resolve(
|
|
9073
|
-
err(new MemoryError("Failed to get all memories", { cause: causeError }))
|
|
9074
|
-
);
|
|
9075
|
-
}
|
|
9076
|
-
}
|
|
9077
|
-
count() {
|
|
9078
|
-
this.ensureInitialized();
|
|
9079
|
-
return Promise.resolve(countMemories(this.getDatabase()));
|
|
9080
|
-
}
|
|
9081
|
-
close() {
|
|
9082
|
-
if (this.db !== null) {
|
|
9083
|
-
this.db.close();
|
|
9084
|
-
this.db = null;
|
|
9085
|
-
this.initialized = false;
|
|
9086
|
-
this.logger.info("HybridMemoryBackend closed");
|
|
9087
|
-
}
|
|
9088
|
-
}
|
|
9089
|
-
};
|
|
9090
|
-
|
|
9091
8685
|
// src/context/graph-memory-types.ts
|
|
9092
|
-
import { z as
|
|
8686
|
+
import { z as z13 } from "zod";
|
|
9093
8687
|
var RelationType = {
|
|
9094
8688
|
/** General association between memories */
|
|
9095
8689
|
RELATED_TO: "related_to",
|
|
@@ -9108,7 +8702,7 @@ var RelationType = {
|
|
|
9108
8702
|
/** Causal relationship */
|
|
9109
8703
|
CAUSES: "causes"
|
|
9110
8704
|
};
|
|
9111
|
-
var RelationTypeSchema =
|
|
8705
|
+
var RelationTypeSchema = z13.enum([
|
|
9112
8706
|
"related_to",
|
|
9113
8707
|
"derived_from",
|
|
9114
8708
|
"contradicts",
|
|
@@ -9118,28 +8712,28 @@ var RelationTypeSchema = z15.enum([
|
|
|
9118
8712
|
"precedes",
|
|
9119
8713
|
"causes"
|
|
9120
8714
|
]);
|
|
9121
|
-
var GraphEdgeSchema =
|
|
9122
|
-
from:
|
|
9123
|
-
to:
|
|
8715
|
+
var GraphEdgeSchema = z13.object({
|
|
8716
|
+
from: z13.string().min(1),
|
|
8717
|
+
to: z13.string().min(1),
|
|
9124
8718
|
type: RelationTypeSchema,
|
|
9125
|
-
weight:
|
|
9126
|
-
createdAt:
|
|
9127
|
-
metadata:
|
|
8719
|
+
weight: z13.number().min(0).max(1),
|
|
8720
|
+
createdAt: z13.date(),
|
|
8721
|
+
metadata: z13.record(z13.string(), z13.unknown()).optional()
|
|
9128
8722
|
});
|
|
9129
|
-
var TraversalOptionsSchema =
|
|
9130
|
-
maxDepth:
|
|
9131
|
-
relationTypes:
|
|
9132
|
-
minWeight:
|
|
9133
|
-
limit:
|
|
9134
|
-
includeStart:
|
|
9135
|
-
direction:
|
|
8723
|
+
var TraversalOptionsSchema = z13.object({
|
|
8724
|
+
maxDepth: z13.number().int().positive().optional(),
|
|
8725
|
+
relationTypes: z13.array(RelationTypeSchema).optional(),
|
|
8726
|
+
minWeight: z13.number().min(0).max(1).optional(),
|
|
8727
|
+
limit: z13.number().int().positive().optional(),
|
|
8728
|
+
includeStart: z13.boolean().optional(),
|
|
8729
|
+
direction: z13.enum(["outgoing", "incoming", "both"]).optional()
|
|
9136
8730
|
});
|
|
9137
|
-
var GraphMemoryConfigSchema =
|
|
9138
|
-
dbPath:
|
|
9139
|
-
markdownDir:
|
|
9140
|
-
defaultTraversalDepth:
|
|
9141
|
-
maxTraversalDepth:
|
|
9142
|
-
autoExpire:
|
|
8731
|
+
var GraphMemoryConfigSchema = z13.object({
|
|
8732
|
+
dbPath: z13.string().min(1),
|
|
8733
|
+
markdownDir: z13.string().min(1),
|
|
8734
|
+
defaultTraversalDepth: z13.number().int().positive().optional(),
|
|
8735
|
+
maxTraversalDepth: z13.number().int().positive().optional(),
|
|
8736
|
+
autoExpire: z13.boolean().optional()
|
|
9143
8737
|
});
|
|
9144
8738
|
var DEFAULT_GRAPH_MEMORY_CONFIG = {
|
|
9145
8739
|
defaultTraversalDepth: 2,
|
|
@@ -9147,50 +8741,6 @@ var DEFAULT_GRAPH_MEMORY_CONFIG = {
|
|
|
9147
8741
|
autoExpire: true
|
|
9148
8742
|
};
|
|
9149
8743
|
|
|
9150
|
-
// src/utils/memory-db-utils.ts
|
|
9151
|
-
var logger6 = createLogger({ component: "MemoryDbUtils" });
|
|
9152
|
-
function safeJsonParse(json, fallback, context) {
|
|
9153
|
-
try {
|
|
9154
|
-
return JSON.parse(json);
|
|
9155
|
-
} catch {
|
|
9156
|
-
logger6.warn("Corrupt JSON in memory database row", { context });
|
|
9157
|
-
return fallback;
|
|
9158
|
-
}
|
|
9159
|
-
}
|
|
9160
|
-
function memoryRowToEntry(row) {
|
|
9161
|
-
return {
|
|
9162
|
-
key: row.key,
|
|
9163
|
-
value: safeJsonParse(row.value, row.value, `value for key="${row.key}"`),
|
|
9164
|
-
metadata: safeJsonParse(
|
|
9165
|
-
row.metadata,
|
|
9166
|
-
{ importance: MemoryImportance.MEDIUM },
|
|
9167
|
-
`metadata for key="${row.key}"`
|
|
9168
|
-
),
|
|
9169
|
-
createdAt: new Date(row.created_at),
|
|
9170
|
-
accessedAt: new Date(row.accessed_at)
|
|
9171
|
-
};
|
|
9172
|
-
}
|
|
9173
|
-
function memoryExists(db, key) {
|
|
9174
|
-
const stmt = db.prepare(
|
|
9175
|
-
"SELECT COUNT(*) as count FROM memories WHERE key = ?"
|
|
9176
|
-
);
|
|
9177
|
-
const result = stmt.get(key);
|
|
9178
|
-
return result !== void 0 && result.count > 0;
|
|
9179
|
-
}
|
|
9180
|
-
function getMemoryEntry(db, key) {
|
|
9181
|
-
const stmt = db.prepare("SELECT * FROM memories WHERE key = ?");
|
|
9182
|
-
const row = stmt.get(key);
|
|
9183
|
-
return row !== void 0 ? memoryRowToEntry(row) : void 0;
|
|
9184
|
-
}
|
|
9185
|
-
function getMemoryRow(db, key) {
|
|
9186
|
-
const stmt = db.prepare("SELECT * FROM memories WHERE key = ?");
|
|
9187
|
-
return stmt.get(key);
|
|
9188
|
-
}
|
|
9189
|
-
function getAllMemoryRows(db, limit) {
|
|
9190
|
-
const stmt = db.prepare("SELECT * FROM memories ORDER BY accessed_at DESC LIMIT ?");
|
|
9191
|
-
return stmt.all(limit);
|
|
9192
|
-
}
|
|
9193
|
-
|
|
9194
8744
|
// src/context/graph-memory-helpers.ts
|
|
9195
8745
|
var CREATE_EDGES_TABLE_SQL = `
|
|
9196
8746
|
CREATE TABLE IF NOT EXISTS graph_edges (
|
|
@@ -9279,11 +8829,11 @@ function getNextKeys(currentKey, edges, opts) {
|
|
|
9279
8829
|
}
|
|
9280
8830
|
return next;
|
|
9281
8831
|
}
|
|
9282
|
-
function buildTraversalResult(entry, depth,
|
|
8832
|
+
function buildTraversalResult(entry, depth, path4, edge) {
|
|
9283
8833
|
if (edge !== void 0) {
|
|
9284
|
-
return { entry, depth, path:
|
|
8834
|
+
return { entry, depth, path: path4, edge };
|
|
9285
8835
|
}
|
|
9286
|
-
return { entry, depth, path:
|
|
8836
|
+
return { entry, depth, path: path4 };
|
|
9287
8837
|
}
|
|
9288
8838
|
function bfsTraverse(config) {
|
|
9289
8839
|
const { db, startKey, opts } = config;
|
|
@@ -9339,7 +8889,7 @@ function findShortestPath(db, from, to, opts) {
|
|
|
9339
8889
|
}
|
|
9340
8890
|
|
|
9341
8891
|
// src/context/graph-memory.ts
|
|
9342
|
-
var
|
|
8892
|
+
var logger6 = createLogger({ component: "GraphMemoryBackend" });
|
|
9343
8893
|
var GraphMemoryBackend = class {
|
|
9344
8894
|
config;
|
|
9345
8895
|
log;
|
|
@@ -9354,7 +8904,7 @@ var GraphMemoryBackend = class {
|
|
|
9354
8904
|
throw new MemoryError(`Invalid GraphMemoryBackend config: ${msg}`);
|
|
9355
8905
|
}
|
|
9356
8906
|
this.config = { ...DEFAULT_GRAPH_MEMORY_CONFIG, ...config };
|
|
9357
|
-
this.log =
|
|
8907
|
+
this.log = logger6;
|
|
9358
8908
|
this.base = new HybridMemoryBackend({ dbPath: config.dbPath, markdownDir: config.markdownDir });
|
|
9359
8909
|
}
|
|
9360
8910
|
async initialize() {
|
|
@@ -9369,7 +8919,7 @@ var GraphMemoryBackend = class {
|
|
|
9369
8919
|
if (!baseInit.ok) return baseInit;
|
|
9370
8920
|
try {
|
|
9371
8921
|
const mod = await import("better-sqlite3").catch((cause) => {
|
|
9372
|
-
|
|
8922
|
+
logger6.debug("better-sqlite3 import failed", { error: String(cause) });
|
|
9373
8923
|
return null;
|
|
9374
8924
|
});
|
|
9375
8925
|
if (mod === null)
|
|
@@ -9500,8 +9050,8 @@ var GraphMemoryBackend = class {
|
|
|
9500
9050
|
if (!memoryExists(db, to))
|
|
9501
9051
|
return Promise.resolve(err(new MemoryError(`To key not found: ${to}`)));
|
|
9502
9052
|
const resolved = resolveTraversalOptions(opts);
|
|
9503
|
-
const
|
|
9504
|
-
return Promise.resolve(ok(
|
|
9053
|
+
const path4 = findShortestPath(db, from, to, resolved);
|
|
9054
|
+
return Promise.resolve(ok(path4));
|
|
9505
9055
|
} catch (error) {
|
|
9506
9056
|
const cause = error instanceof Error ? error : new Error(String(error));
|
|
9507
9057
|
return Promise.resolve(err(new MemoryError("Path finding failed", { cause })));
|
|
@@ -9541,11 +9091,11 @@ var GraphMemoryBackend = class {
|
|
|
9541
9091
|
};
|
|
9542
9092
|
|
|
9543
9093
|
// src/context/agentic-memory-types.ts
|
|
9544
|
-
import { z as
|
|
9094
|
+
import { z as z15 } from "zod";
|
|
9545
9095
|
|
|
9546
9096
|
// src/context/agentic-memory-primitives.ts
|
|
9547
|
-
import { z as
|
|
9548
|
-
var EntityTypeSchema =
|
|
9097
|
+
import { z as z14 } from "zod";
|
|
9098
|
+
var EntityTypeSchema = z14.enum([
|
|
9549
9099
|
"person",
|
|
9550
9100
|
"organization",
|
|
9551
9101
|
"concept",
|
|
@@ -9553,60 +9103,60 @@ var EntityTypeSchema = z16.enum([
|
|
|
9553
9103
|
"file",
|
|
9554
9104
|
"unknown"
|
|
9555
9105
|
]);
|
|
9556
|
-
var EntityReferenceSchema =
|
|
9557
|
-
name:
|
|
9106
|
+
var EntityReferenceSchema = z14.object({
|
|
9107
|
+
name: z14.string().min(1).max(200),
|
|
9558
9108
|
type: EntityTypeSchema
|
|
9559
9109
|
});
|
|
9560
|
-
var EvolutionTypeSchema =
|
|
9110
|
+
var EvolutionTypeSchema = z14.enum([
|
|
9561
9111
|
"refinement",
|
|
9562
9112
|
"contradiction",
|
|
9563
9113
|
"extension",
|
|
9564
9114
|
"supersession"
|
|
9565
9115
|
]);
|
|
9566
|
-
var EvolutionResultSchema =
|
|
9116
|
+
var EvolutionResultSchema = z14.object({
|
|
9567
9117
|
type: EvolutionTypeSchema,
|
|
9568
|
-
affectedKey:
|
|
9569
|
-
confidence:
|
|
9570
|
-
description:
|
|
9118
|
+
affectedKey: z14.string().min(1),
|
|
9119
|
+
confidence: z14.number().min(0).max(1),
|
|
9120
|
+
description: z14.string().max(500)
|
|
9571
9121
|
});
|
|
9572
|
-
var LinkSuggestionSchema =
|
|
9573
|
-
from:
|
|
9574
|
-
to:
|
|
9122
|
+
var LinkSuggestionSchema = z14.object({
|
|
9123
|
+
from: z14.string().min(1),
|
|
9124
|
+
to: z14.string().min(1),
|
|
9575
9125
|
relationType: RelationTypeSchema,
|
|
9576
|
-
reason:
|
|
9577
|
-
confidence:
|
|
9126
|
+
reason: z14.string().max(200),
|
|
9127
|
+
confidence: z14.number().min(0).max(1)
|
|
9578
9128
|
});
|
|
9579
9129
|
|
|
9580
9130
|
// src/context/agentic-memory-types.ts
|
|
9581
|
-
var MemoryAttributesSchema =
|
|
9582
|
-
keywords:
|
|
9583
|
-
semanticTags:
|
|
9584
|
-
contextDescription:
|
|
9585
|
-
entities:
|
|
9586
|
-
attributesUpdatedAt:
|
|
9131
|
+
var MemoryAttributesSchema = z15.object({
|
|
9132
|
+
keywords: z15.array(z15.string().max(100)).max(50),
|
|
9133
|
+
semanticTags: z15.array(z15.string().max(50)).max(20),
|
|
9134
|
+
contextDescription: z15.string().max(500),
|
|
9135
|
+
entities: z15.array(EntityReferenceSchema).max(30),
|
|
9136
|
+
attributesUpdatedAt: z15.date()
|
|
9587
9137
|
});
|
|
9588
|
-
var ExtractionConfigSchema =
|
|
9589
|
-
maxKeywords:
|
|
9590
|
-
maxSemanticTags:
|
|
9591
|
-
maxContextLength:
|
|
9592
|
-
maxEntities:
|
|
9138
|
+
var ExtractionConfigSchema = z15.object({
|
|
9139
|
+
maxKeywords: z15.number().int().positive().max(50),
|
|
9140
|
+
maxSemanticTags: z15.number().int().positive().max(20),
|
|
9141
|
+
maxContextLength: z15.number().int().positive().max(500),
|
|
9142
|
+
maxEntities: z15.number().int().positive().max(30)
|
|
9593
9143
|
});
|
|
9594
|
-
var LinkingConfigSchema =
|
|
9595
|
-
suggestionThreshold:
|
|
9596
|
-
maxSuggestions:
|
|
9597
|
-
allowedTypes:
|
|
9144
|
+
var LinkingConfigSchema = z15.object({
|
|
9145
|
+
suggestionThreshold: z15.number().min(0).max(1),
|
|
9146
|
+
maxSuggestions: z15.number().int().positive().max(20),
|
|
9147
|
+
allowedTypes: z15.array(RelationTypeSchema)
|
|
9598
9148
|
});
|
|
9599
|
-
var LinkingOptionsSchema =
|
|
9600
|
-
threshold:
|
|
9601
|
-
maxLinks:
|
|
9602
|
-
bidirectional:
|
|
9149
|
+
var LinkingOptionsSchema = z15.object({
|
|
9150
|
+
threshold: z15.number().min(0).max(1).optional(),
|
|
9151
|
+
maxLinks: z15.number().int().positive().optional(),
|
|
9152
|
+
bidirectional: z15.boolean().optional()
|
|
9603
9153
|
});
|
|
9604
|
-
var AgenticMemoryConfigSchema =
|
|
9605
|
-
dbPath:
|
|
9606
|
-
markdownDir:
|
|
9154
|
+
var AgenticMemoryConfigSchema = z15.object({
|
|
9155
|
+
dbPath: z15.string().min(1),
|
|
9156
|
+
markdownDir: z15.string().min(1),
|
|
9607
9157
|
extraction: ExtractionConfigSchema.partial().optional(),
|
|
9608
9158
|
linking: LinkingConfigSchema.partial().optional(),
|
|
9609
|
-
autoExpire:
|
|
9159
|
+
autoExpire: z15.boolean().optional()
|
|
9610
9160
|
});
|
|
9611
9161
|
var DEFAULT_EXTRACTION_CONFIG = {
|
|
9612
9162
|
maxKeywords: 10,
|
|
@@ -9859,7 +9409,7 @@ function mergeLinkingConfig(partial) {
|
|
|
9859
9409
|
}
|
|
9860
9410
|
|
|
9861
9411
|
// src/context/agentic-memory-db-helpers.ts
|
|
9862
|
-
var
|
|
9412
|
+
var logger7 = createLogger({ component: "AgenticMemoryDbHelpers" });
|
|
9863
9413
|
function safeExtractAttributes(amem) {
|
|
9864
9414
|
if (!Array.isArray(amem.keywords) || amem.attributesUpdatedAt === void 0) return null;
|
|
9865
9415
|
const updatedAt = amem.attributesUpdatedAt;
|
|
@@ -9884,7 +9434,7 @@ function memoryRowToAgenticEntry(row, extractionConfig) {
|
|
|
9884
9434
|
try {
|
|
9885
9435
|
parsedMeta = JSON.parse(row.metadata);
|
|
9886
9436
|
} catch {
|
|
9887
|
-
|
|
9437
|
+
logger7.warn("Corrupt metadata JSON in memory row, using fallback extraction", {
|
|
9888
9438
|
key: row.key
|
|
9889
9439
|
});
|
|
9890
9440
|
}
|
|
@@ -9917,7 +9467,7 @@ function getAttributesFromRow(row, extractionConfig) {
|
|
|
9917
9467
|
try {
|
|
9918
9468
|
meta = JSON.parse(row.metadata);
|
|
9919
9469
|
} catch {
|
|
9920
|
-
|
|
9470
|
+
logger7.warn("Corrupt metadata JSON in getAttributesFromRow, using value extraction", {
|
|
9921
9471
|
key: row.key
|
|
9922
9472
|
});
|
|
9923
9473
|
}
|
|
@@ -9929,7 +9479,7 @@ function getAttributesFromRow(row, extractionConfig) {
|
|
|
9929
9479
|
try {
|
|
9930
9480
|
parsedValue = JSON.parse(row.value);
|
|
9931
9481
|
} catch {
|
|
9932
|
-
|
|
9482
|
+
logger7.warn("Corrupt value JSON in getAttributesFromRow, using raw string", {
|
|
9933
9483
|
key: row.key
|
|
9934
9484
|
});
|
|
9935
9485
|
}
|
|
@@ -10019,7 +9569,7 @@ function buildAgenticEntry(key, value, metadata, attributes, createdAt) {
|
|
|
10019
9569
|
}
|
|
10020
9570
|
|
|
10021
9571
|
// src/context/agentic-memory.ts
|
|
10022
|
-
var
|
|
9572
|
+
var logger8 = createLogger({ component: "AgenticMemoryBackend" });
|
|
10023
9573
|
var AgenticMemoryBackend = class {
|
|
10024
9574
|
config;
|
|
10025
9575
|
log;
|
|
@@ -10037,7 +9587,7 @@ var AgenticMemoryBackend = class {
|
|
|
10037
9587
|
throw new MemoryError(`Invalid AgenticMemoryBackend config: ${msg}`);
|
|
10038
9588
|
}
|
|
10039
9589
|
this.config = config;
|
|
10040
|
-
this.log =
|
|
9590
|
+
this.log = logger8;
|
|
10041
9591
|
this.extractionConfig = mergeExtractionConfig(config.extraction);
|
|
10042
9592
|
this.linkingConfig = mergeLinkingConfig(config.linking);
|
|
10043
9593
|
this.base = new HybridMemoryBackend({
|
|
@@ -10284,477 +9834,80 @@ var AgenticMemoryBackend = class {
|
|
|
10284
9834
|
}
|
|
10285
9835
|
};
|
|
10286
9836
|
|
|
10287
|
-
// src/context/adaptive-memory-types.ts
|
|
10288
|
-
import { z as z18 } from "zod";
|
|
10289
|
-
var ScoringWeightsBaseSchema = z18.object({
|
|
10290
|
-
recency: z18.number().min(0).max(1),
|
|
10291
|
-
importance: z18.number().min(0).max(1),
|
|
10292
|
-
relevance: z18.number().min(0).max(1)
|
|
10293
|
-
});
|
|
10294
|
-
var ScoringWeightsSchema = ScoringWeightsBaseSchema.refine(
|
|
10295
|
-
(w) => Math.abs(w.recency + w.importance + w.relevance - 1) < 1e-3,
|
|
10296
|
-
{ message: "Weights must sum to 1.0" }
|
|
10297
|
-
);
|
|
10298
|
-
var PartialScoringWeightsSchema = ScoringWeightsBaseSchema.partial();
|
|
10299
|
-
var ImportanceWeightsSchema = z18.object({
|
|
10300
|
-
low: z18.number().min(0).max(1),
|
|
10301
|
-
medium: z18.number().min(0).max(1),
|
|
10302
|
-
high: z18.number().min(0).max(1)
|
|
10303
|
-
});
|
|
10304
|
-
var DecayConfigSchema = z18.object({
|
|
10305
|
-
halfLifeMs: z18.number().positive(),
|
|
10306
|
-
minScore: z18.number().min(0).max(1)
|
|
10307
|
-
});
|
|
10308
|
-
var PriorityScoreSchema = z18.object({
|
|
10309
|
-
score: z18.number().min(0),
|
|
10310
|
-
components: z18.object({
|
|
10311
|
-
recency: z18.number().min(0).max(1),
|
|
10312
|
-
importance: z18.number().min(0).max(1),
|
|
10313
|
-
relevance: z18.number().min(0).max(1)
|
|
10314
|
-
})
|
|
10315
|
-
});
|
|
10316
|
-
var ScoredMemoryEntrySchema = z18.object({
|
|
10317
|
-
entry: z18.object({
|
|
10318
|
-
key: z18.string(),
|
|
10319
|
-
value: z18.unknown(),
|
|
10320
|
-
metadata: z18.object({
|
|
10321
|
-
importance: z18.enum(["low", "medium", "high"]),
|
|
10322
|
-
tags: z18.array(z18.string()).optional(),
|
|
10323
|
-
ttl: z18.number().optional()
|
|
10324
|
-
}),
|
|
10325
|
-
createdAt: z18.date(),
|
|
10326
|
-
accessedAt: z18.date()
|
|
10327
|
-
}),
|
|
10328
|
-
priority: PriorityScoreSchema
|
|
10329
|
-
});
|
|
10330
|
-
var PriorityRetrievalOptionsSchema = z18.object({
|
|
10331
|
-
query: z18.string().optional(),
|
|
10332
|
-
limit: z18.number().int().positive().optional(),
|
|
10333
|
-
minScore: z18.number().min(0).optional(),
|
|
10334
|
-
weights: PartialScoringWeightsSchema.optional(),
|
|
10335
|
-
importanceFilter: z18.array(z18.enum(["low", "medium", "high"])).optional(),
|
|
10336
|
-
tagFilter: z18.array(z18.string()).optional()
|
|
10337
|
-
});
|
|
10338
|
-
var ScoringConfigSchema = z18.object({
|
|
10339
|
-
weights: ScoringWeightsSchema,
|
|
10340
|
-
importanceWeights: ImportanceWeightsSchema,
|
|
10341
|
-
decay: DecayConfigSchema
|
|
10342
|
-
});
|
|
10343
|
-
var AdaptiveMemoryConfigSchema = z18.object({
|
|
10344
|
-
dbPath: z18.string().min(1),
|
|
10345
|
-
markdownDir: z18.string().min(1),
|
|
10346
|
-
scoring: ScoringConfigSchema.partial().optional(),
|
|
10347
|
-
autoExpire: z18.boolean().optional()
|
|
10348
|
-
});
|
|
10349
|
-
var DEFAULT_SCORING_WEIGHTS = {
|
|
10350
|
-
recency: 0.4,
|
|
10351
|
-
importance: 0.3,
|
|
10352
|
-
relevance: 0.3
|
|
10353
|
-
};
|
|
10354
|
-
var DEFAULT_IMPORTANCE_WEIGHTS = {
|
|
10355
|
-
low: 0.25,
|
|
10356
|
-
medium: 0.5,
|
|
10357
|
-
high: 1
|
|
10358
|
-
};
|
|
10359
|
-
var DEFAULT_DECAY_CONFIG = {
|
|
10360
|
-
halfLifeMs: 24 * 60 * 60 * 1e3,
|
|
10361
|
-
// 24 hours
|
|
10362
|
-
minScore: 0.1
|
|
10363
|
-
};
|
|
10364
|
-
var DEFAULT_SCORING_CONFIG = {
|
|
10365
|
-
weights: DEFAULT_SCORING_WEIGHTS,
|
|
10366
|
-
importanceWeights: DEFAULT_IMPORTANCE_WEIGHTS,
|
|
10367
|
-
decay: DEFAULT_DECAY_CONFIG
|
|
10368
|
-
};
|
|
10369
|
-
|
|
10370
|
-
// src/utils/similarity-utils.ts
|
|
10371
|
-
function calculateTokenOverlap(queryTokens, targetTokens) {
|
|
10372
|
-
if (queryTokens.length === 0) return 0;
|
|
10373
|
-
if (targetTokens.length === 0) return 0;
|
|
10374
|
-
const targetSet = new Set(targetTokens);
|
|
10375
|
-
let matches = 0;
|
|
10376
|
-
for (const token of queryTokens) {
|
|
10377
|
-
if (targetSet.has(token)) matches++;
|
|
10378
|
-
}
|
|
10379
|
-
return matches / queryTokens.length;
|
|
10380
|
-
}
|
|
10381
|
-
function calculateSetOverlapCount(sourceSet, targetSet) {
|
|
10382
|
-
let count = 0;
|
|
10383
|
-
for (const item of sourceSet) {
|
|
10384
|
-
if (targetSet.has(item)) count++;
|
|
10385
|
-
}
|
|
10386
|
-
return count;
|
|
10387
|
-
}
|
|
10388
|
-
function calculateJaccardSimilarity(set1, set2) {
|
|
10389
|
-
if (set1.size === 0 && set2.size === 0) return 1;
|
|
10390
|
-
if (set1.size === 0 || set2.size === 0) return 0;
|
|
10391
|
-
const intersection = calculateSetOverlapCount(set1, set2);
|
|
10392
|
-
const union = set1.size + set2.size - intersection;
|
|
10393
|
-
return union > 0 ? intersection / union : 0;
|
|
10394
|
-
}
|
|
10395
|
-
function calculateTextJaccardSimilarity(text1, text2) {
|
|
10396
|
-
const words1 = new Set(
|
|
10397
|
-
text1.toLowerCase().split(/\s+/).filter((w) => w.length > 0)
|
|
10398
|
-
);
|
|
10399
|
-
const words2 = new Set(
|
|
10400
|
-
text2.toLowerCase().split(/\s+/).filter((w) => w.length > 0)
|
|
10401
|
-
);
|
|
10402
|
-
return calculateJaccardSimilarity(words1, words2);
|
|
10403
|
-
}
|
|
10404
|
-
|
|
10405
|
-
// src/context/adaptive-memory-helpers.ts
|
|
10406
|
-
function calculateRecencyScore(accessedAt, now, halfLifeMs, minScore) {
|
|
10407
|
-
const elapsedMs = now.getTime() - accessedAt.getTime();
|
|
10408
|
-
if (elapsedMs <= 0) return 1;
|
|
10409
|
-
const lambda = Math.LN2 / halfLifeMs;
|
|
10410
|
-
const decayedScore = Math.exp(-lambda * elapsedMs);
|
|
10411
|
-
return Math.max(minScore, decayedScore);
|
|
10412
|
-
}
|
|
10413
|
-
function calculateImportanceScore(importance, config) {
|
|
10414
|
-
switch (importance) {
|
|
10415
|
-
case MemoryImportance.HIGH:
|
|
10416
|
-
return config.importanceWeights.high;
|
|
10417
|
-
case MemoryImportance.MEDIUM:
|
|
10418
|
-
return config.importanceWeights.medium;
|
|
10419
|
-
case MemoryImportance.LOW:
|
|
10420
|
-
return config.importanceWeights.low;
|
|
10421
|
-
default:
|
|
10422
|
-
return config.importanceWeights.medium;
|
|
10423
|
-
}
|
|
10424
|
-
}
|
|
10425
|
-
function calculateRelevanceScore(query, value) {
|
|
10426
|
-
if (query === void 0 || query.trim() === "") return 1;
|
|
10427
|
-
const queryTokens = tokenize2(query);
|
|
10428
|
-
const valueTokens = tokenize2(value);
|
|
10429
|
-
if (queryTokens.length === 0 || valueTokens.length === 0) return 0.5;
|
|
10430
|
-
return calculateTokenOverlap(queryTokens, valueTokens);
|
|
10431
|
-
}
|
|
10432
|
-
function tokenize2(text) {
|
|
10433
|
-
return tokenize(text, 1);
|
|
10434
|
-
}
|
|
10435
|
-
function calculatePriorityScore(input) {
|
|
10436
|
-
const { entry, query, now, config, weightOverrides } = input;
|
|
10437
|
-
const recency = calculateRecencyScore(
|
|
10438
|
-
entry.accessedAt,
|
|
10439
|
-
now,
|
|
10440
|
-
config.decay.halfLifeMs,
|
|
10441
|
-
config.decay.minScore
|
|
10442
|
-
);
|
|
10443
|
-
const importance = calculateImportanceScore(entry.metadata.importance, config);
|
|
10444
|
-
const relevance = calculateRelevanceScore(query, stringifyValue2(entry.value));
|
|
10445
|
-
const components = { recency, importance, relevance };
|
|
10446
|
-
const weights = resolveWeights(config.weights, weightOverrides);
|
|
10447
|
-
const score = recency * weights.recency + importance * weights.importance + relevance * weights.relevance;
|
|
10448
|
-
return { score, components };
|
|
10449
|
-
}
|
|
10450
|
-
function stringifyValue2(value) {
|
|
10451
|
-
return stringifyValue(value);
|
|
10452
|
-
}
|
|
10453
|
-
function resolveWeights(base, overrides) {
|
|
10454
|
-
if (overrides === void 0) return base;
|
|
10455
|
-
const merged = {
|
|
10456
|
-
recency: overrides.recency ?? base.recency,
|
|
10457
|
-
importance: overrides.importance ?? base.importance,
|
|
10458
|
-
relevance: overrides.relevance ?? base.relevance
|
|
10459
|
-
};
|
|
10460
|
-
const sum = merged.recency + merged.importance + merged.relevance;
|
|
10461
|
-
if (sum === 0) return base;
|
|
10462
|
-
if (Math.abs(sum - 1) > 1e-3) {
|
|
10463
|
-
return {
|
|
10464
|
-
recency: merged.recency / sum,
|
|
10465
|
-
importance: merged.importance / sum,
|
|
10466
|
-
relevance: merged.relevance / sum
|
|
10467
|
-
};
|
|
10468
|
-
}
|
|
10469
|
-
return merged;
|
|
10470
|
-
}
|
|
10471
|
-
function filterScoredEntries(entries, config) {
|
|
10472
|
-
return entries.filter((e) => {
|
|
10473
|
-
if (config.minScore !== void 0 && e.priority.score < config.minScore) {
|
|
10474
|
-
return false;
|
|
10475
|
-
}
|
|
10476
|
-
if (config.importanceFilter !== void 0 && config.importanceFilter.length > 0) {
|
|
10477
|
-
if (!config.importanceFilter.includes(e.entry.metadata.importance)) {
|
|
10478
|
-
return false;
|
|
10479
|
-
}
|
|
10480
|
-
}
|
|
10481
|
-
if (config.tagFilter !== void 0 && config.tagFilter.length > 0) {
|
|
10482
|
-
const entryTags = e.entry.metadata.tags ?? [];
|
|
10483
|
-
const hasMatch = config.tagFilter.some((t) => entryTags.includes(t));
|
|
10484
|
-
if (!hasMatch) return false;
|
|
10485
|
-
}
|
|
10486
|
-
return true;
|
|
10487
|
-
});
|
|
10488
|
-
}
|
|
10489
|
-
function touchMemory(db, key) {
|
|
10490
|
-
const stmt = db.prepare("UPDATE memories SET accessed_at = ? WHERE key = ?");
|
|
10491
|
-
const result = stmt.run(getTimeProvider().now(), key);
|
|
10492
|
-
return result.changes > 0;
|
|
10493
|
-
}
|
|
10494
|
-
function scoreAndSortEntries(rows, opts, config) {
|
|
10495
|
-
const now = new Date(getTimeProvider().now());
|
|
10496
|
-
const scored = rows.map((row) => {
|
|
10497
|
-
const entry = memoryRowToEntry(row);
|
|
10498
|
-
const priority = calculatePriorityScore({
|
|
10499
|
-
entry,
|
|
10500
|
-
now,
|
|
10501
|
-
config,
|
|
10502
|
-
...opts?.query !== void 0 && { query: opts.query },
|
|
10503
|
-
...opts?.weights !== void 0 && { weightOverrides: opts.weights }
|
|
10504
|
-
});
|
|
10505
|
-
return { entry, priority };
|
|
10506
|
-
});
|
|
10507
|
-
const filterConfig = {
|
|
10508
|
-
...opts?.minScore !== void 0 && { minScore: opts.minScore },
|
|
10509
|
-
...opts?.importanceFilter !== void 0 && { importanceFilter: opts.importanceFilter },
|
|
10510
|
-
...opts?.tagFilter !== void 0 && { tagFilter: opts.tagFilter }
|
|
10511
|
-
};
|
|
10512
|
-
const filtered = filterScoredEntries(scored, filterConfig);
|
|
10513
|
-
filtered.sort((a, b) => b.priority.score - a.priority.score);
|
|
10514
|
-
const limit = opts?.limit ?? 100;
|
|
10515
|
-
return filtered.slice(0, limit);
|
|
10516
|
-
}
|
|
10517
|
-
function mergeScoringConfig(partial) {
|
|
10518
|
-
if (partial === void 0) return DEFAULT_SCORING_CONFIG;
|
|
10519
|
-
return {
|
|
10520
|
-
weights: partial.weights ?? DEFAULT_SCORING_CONFIG.weights,
|
|
10521
|
-
importanceWeights: partial.importanceWeights ?? DEFAULT_SCORING_CONFIG.importanceWeights,
|
|
10522
|
-
decay: partial.decay ?? DEFAULT_SCORING_CONFIG.decay
|
|
10523
|
-
};
|
|
10524
|
-
}
|
|
10525
|
-
|
|
10526
|
-
// src/context/adaptive-memory.ts
|
|
10527
|
-
var logger10 = createLogger({ component: "AdaptiveMemoryBackend" });
|
|
10528
|
-
var AdaptiveMemoryBackend = class {
|
|
10529
|
-
config;
|
|
10530
|
-
log;
|
|
10531
|
-
base;
|
|
10532
|
-
scoringConfig;
|
|
10533
|
-
db = null;
|
|
10534
|
-
initialized = false;
|
|
10535
|
-
initPromise;
|
|
10536
|
-
constructor(config) {
|
|
10537
|
-
const validation = AdaptiveMemoryConfigSchema.safeParse(config);
|
|
10538
|
-
if (!validation.success) {
|
|
10539
|
-
const msg = validation.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
|
|
10540
|
-
throw new MemoryError(`Invalid AdaptiveMemoryBackend config: ${msg}`);
|
|
10541
|
-
}
|
|
10542
|
-
this.config = config;
|
|
10543
|
-
this.log = logger10;
|
|
10544
|
-
this.scoringConfig = mergeScoringConfig(config.scoring);
|
|
10545
|
-
this.base = new HybridMemoryBackend({ dbPath: config.dbPath, markdownDir: config.markdownDir });
|
|
10546
|
-
}
|
|
10547
|
-
async initialize() {
|
|
10548
|
-
if (this.initialized) return ok(void 0);
|
|
10549
|
-
this.initPromise ??= this.doInitialize().finally(() => {
|
|
10550
|
-
this.initPromise = void 0;
|
|
10551
|
-
});
|
|
10552
|
-
return this.initPromise;
|
|
10553
|
-
}
|
|
10554
|
-
async doInitialize() {
|
|
10555
|
-
const baseInit = await this.base.initialize();
|
|
10556
|
-
if (!baseInit.ok) return baseInit;
|
|
10557
|
-
try {
|
|
10558
|
-
const mod = await import("better-sqlite3").catch((cause) => {
|
|
10559
|
-
this.log.debug("better-sqlite3 import failed", { error: String(cause) });
|
|
10560
|
-
return null;
|
|
10561
|
-
});
|
|
10562
|
-
if (mod === null)
|
|
10563
|
-
return err(
|
|
10564
|
-
new MemoryError("better-sqlite3 not installed. Install: npm install better-sqlite3")
|
|
10565
|
-
);
|
|
10566
|
-
const Database = mod.default;
|
|
10567
|
-
this.db = new Database(this.config.dbPath);
|
|
10568
|
-
this.initialized = true;
|
|
10569
|
-
this.log.info("AdaptiveMemoryBackend initialized");
|
|
10570
|
-
return ok(void 0);
|
|
10571
|
-
} catch (error) {
|
|
10572
|
-
const cause = error instanceof Error ? error : new Error(String(error));
|
|
10573
|
-
return err(new MemoryError("Failed to initialize adaptive backend", { cause }));
|
|
10574
|
-
}
|
|
10575
|
-
}
|
|
10576
|
-
initializeWithDatabase(database) {
|
|
10577
|
-
this.base.initializeWithDatabase(database);
|
|
10578
|
-
this.db = database;
|
|
10579
|
-
this.initialized = true;
|
|
10580
|
-
this.log.info("AdaptiveMemoryBackend initialized with database");
|
|
10581
|
-
}
|
|
10582
|
-
getDb() {
|
|
10583
|
-
if (this.db === null) throw new MemoryError("Database not initialized");
|
|
10584
|
-
return this.db;
|
|
10585
|
-
}
|
|
10586
|
-
ensureInit() {
|
|
10587
|
-
if (!this.initialized) throw new MemoryError("AdaptiveMemoryBackend not initialized");
|
|
10588
|
-
}
|
|
10589
|
-
// =========================================================================
|
|
10590
|
-
// IMemoryBackend Methods (delegated to base)
|
|
10591
|
-
// =========================================================================
|
|
10592
|
-
store(key, value, metadata) {
|
|
10593
|
-
return this.base.store(key, value, metadata);
|
|
10594
|
-
}
|
|
10595
|
-
retrieve(key) {
|
|
10596
|
-
return this.base.retrieve(key);
|
|
10597
|
-
}
|
|
10598
|
-
search(query, limit) {
|
|
10599
|
-
return this.base.search(query, limit);
|
|
10600
|
-
}
|
|
10601
|
-
prune(olderThan) {
|
|
10602
|
-
return this.base.prune(olderThan);
|
|
10603
|
-
}
|
|
10604
|
-
// =========================================================================
|
|
10605
|
-
// IAdaptiveMemory Methods
|
|
10606
|
-
// =========================================================================
|
|
10607
|
-
retrieveByPriority(opts) {
|
|
10608
|
-
try {
|
|
10609
|
-
this.ensureInit();
|
|
10610
|
-
const db = this.getDb();
|
|
10611
|
-
const maxFetch = (opts?.limit ?? 100) * 2;
|
|
10612
|
-
const rows = getAllMemoryRows(db, maxFetch);
|
|
10613
|
-
const scored = scoreAndSortEntries(rows, opts, this.scoringConfig);
|
|
10614
|
-
this.log.debug("Retrieved by priority", { count: scored.length, query: opts?.query });
|
|
10615
|
-
return Promise.resolve(ok(scored));
|
|
10616
|
-
} catch (error) {
|
|
10617
|
-
const cause = error instanceof Error ? error : new Error(String(error));
|
|
10618
|
-
return Promise.resolve(err(new MemoryError("Failed to retrieve by priority", { cause })));
|
|
10619
|
-
}
|
|
10620
|
-
}
|
|
10621
|
-
getPriorityScore(key, query) {
|
|
10622
|
-
try {
|
|
10623
|
-
this.ensureInit();
|
|
10624
|
-
const db = this.getDb();
|
|
10625
|
-
if (!memoryExists(db, key)) {
|
|
10626
|
-
return Promise.resolve(err(new MemoryError(`Key not found: ${key}`)));
|
|
10627
|
-
}
|
|
10628
|
-
const row = getMemoryRow(db, key);
|
|
10629
|
-
if (row === void 0) {
|
|
10630
|
-
return Promise.resolve(err(new MemoryError(`Key not found: ${key}`)));
|
|
10631
|
-
}
|
|
10632
|
-
const entry = memoryRowToEntry(row);
|
|
10633
|
-
const priority = calculatePriorityScore({
|
|
10634
|
-
entry,
|
|
10635
|
-
now: new Date(getTimeProvider().now()),
|
|
10636
|
-
config: this.scoringConfig,
|
|
10637
|
-
...query !== void 0 && { query }
|
|
10638
|
-
});
|
|
10639
|
-
return Promise.resolve(ok(priority));
|
|
10640
|
-
} catch (error) {
|
|
10641
|
-
const cause = error instanceof Error ? error : new Error(String(error));
|
|
10642
|
-
return Promise.resolve(err(new MemoryError("Failed to get priority score", { cause })));
|
|
10643
|
-
}
|
|
10644
|
-
}
|
|
10645
|
-
touch(key) {
|
|
10646
|
-
try {
|
|
10647
|
-
this.ensureInit();
|
|
10648
|
-
const db = this.getDb();
|
|
10649
|
-
if (!memoryExists(db, key)) {
|
|
10650
|
-
return Promise.resolve(err(new MemoryError(`Key not found: ${key}`)));
|
|
10651
|
-
}
|
|
10652
|
-
const updated = touchMemory(db, key);
|
|
10653
|
-
if (!updated) {
|
|
10654
|
-
return Promise.resolve(err(new MemoryError(`Failed to touch: ${key}`)));
|
|
10655
|
-
}
|
|
10656
|
-
this.log.debug("Touched memory", { key });
|
|
10657
|
-
return Promise.resolve(ok(void 0));
|
|
10658
|
-
} catch (error) {
|
|
10659
|
-
const cause = error instanceof Error ? error : new Error(String(error));
|
|
10660
|
-
return Promise.resolve(err(new MemoryError("Failed to touch memory", { cause })));
|
|
10661
|
-
}
|
|
10662
|
-
}
|
|
10663
|
-
getScoringConfig() {
|
|
10664
|
-
return this.scoringConfig;
|
|
10665
|
-
}
|
|
10666
|
-
updateScoringConfig(config) {
|
|
10667
|
-
this.scoringConfig = mergeScoringConfig({ ...this.scoringConfig, ...config });
|
|
10668
|
-
this.log.info("Updated scoring config", { config: this.scoringConfig });
|
|
10669
|
-
}
|
|
10670
|
-
// =========================================================================
|
|
10671
|
-
// Lifecycle
|
|
10672
|
-
// =========================================================================
|
|
10673
|
-
close() {
|
|
10674
|
-
this.base.close();
|
|
10675
|
-
if (this.db !== null) {
|
|
10676
|
-
this.db.close();
|
|
10677
|
-
this.db = null;
|
|
10678
|
-
}
|
|
10679
|
-
this.initialized = false;
|
|
10680
|
-
this.log.info("AdaptiveMemoryBackend closed");
|
|
10681
|
-
}
|
|
10682
|
-
};
|
|
10683
|
-
|
|
10684
9837
|
// src/context/belief-memory-persistence.ts
|
|
10685
|
-
import * as
|
|
9838
|
+
import * as fs2 from "fs";
|
|
10686
9839
|
import * as os2 from "os";
|
|
10687
|
-
import * as
|
|
9840
|
+
import * as path2 from "path";
|
|
10688
9841
|
|
|
10689
9842
|
// src/context/belief-persistence-types.ts
|
|
10690
|
-
import { z as
|
|
10691
|
-
var BeliefSnapshotSchema =
|
|
10692
|
-
version:
|
|
10693
|
-
exportedAt:
|
|
10694
|
-
beliefs:
|
|
10695
|
-
|
|
10696
|
-
beliefId:
|
|
10697
|
-
subject:
|
|
10698
|
-
predicate:
|
|
10699
|
-
object:
|
|
9843
|
+
import { z as z16 } from "zod";
|
|
9844
|
+
var BeliefSnapshotSchema = z16.object({
|
|
9845
|
+
version: z16.number().int().min(1),
|
|
9846
|
+
exportedAt: z16.string(),
|
|
9847
|
+
beliefs: z16.array(
|
|
9848
|
+
z16.object({
|
|
9849
|
+
beliefId: z16.string(),
|
|
9850
|
+
subject: z16.string(),
|
|
9851
|
+
predicate: z16.string(),
|
|
9852
|
+
object: z16.string(),
|
|
10700
9853
|
confidence: BeliefConfidenceSchema,
|
|
10701
9854
|
sourceType: BeliefSourceTypeSchema,
|
|
10702
|
-
sourceRef:
|
|
10703
|
-
derivedFrom:
|
|
10704
|
-
version:
|
|
10705
|
-
createdAt:
|
|
10706
|
-
updatedAt:
|
|
10707
|
-
superseded:
|
|
10708
|
-
supersededBy:
|
|
10709
|
-
domain:
|
|
10710
|
-
metadata:
|
|
9855
|
+
sourceRef: z16.string().optional(),
|
|
9856
|
+
derivedFrom: z16.array(z16.string()).optional(),
|
|
9857
|
+
version: z16.number(),
|
|
9858
|
+
createdAt: z16.string(),
|
|
9859
|
+
updatedAt: z16.string(),
|
|
9860
|
+
superseded: z16.boolean(),
|
|
9861
|
+
supersededBy: z16.string().optional(),
|
|
9862
|
+
domain: z16.string().optional(),
|
|
9863
|
+
metadata: z16.record(z16.string(), z16.unknown()).optional()
|
|
10711
9864
|
})
|
|
10712
9865
|
),
|
|
10713
|
-
updates:
|
|
10714
|
-
|
|
10715
|
-
beliefId:
|
|
10716
|
-
records:
|
|
10717
|
-
|
|
10718
|
-
updateId:
|
|
10719
|
-
beliefId:
|
|
9866
|
+
updates: z16.array(
|
|
9867
|
+
z16.object({
|
|
9868
|
+
beliefId: z16.string(),
|
|
9869
|
+
records: z16.array(
|
|
9870
|
+
z16.object({
|
|
9871
|
+
updateId: z16.string(),
|
|
9872
|
+
beliefId: z16.string(),
|
|
10720
9873
|
updateType: BeliefUpdateTypeSchema,
|
|
10721
|
-
previousState:
|
|
10722
|
-
newState:
|
|
10723
|
-
reason:
|
|
10724
|
-
evidence:
|
|
10725
|
-
timestamp:
|
|
10726
|
-
updatedBy:
|
|
9874
|
+
previousState: z16.record(z16.string(), z16.unknown()).optional(),
|
|
9875
|
+
newState: z16.record(z16.string(), z16.unknown()),
|
|
9876
|
+
reason: z16.string().max(1e4),
|
|
9877
|
+
evidence: z16.string().max(1e4).optional(),
|
|
9878
|
+
timestamp: z16.string(),
|
|
9879
|
+
updatedBy: z16.string().optional()
|
|
10727
9880
|
})
|
|
10728
9881
|
)
|
|
10729
9882
|
})
|
|
10730
9883
|
),
|
|
10731
|
-
counterfactuals:
|
|
10732
|
-
|
|
10733
|
-
counterfactualId:
|
|
10734
|
-
hypothesis:
|
|
10735
|
-
affectedBeliefs:
|
|
10736
|
-
predictedOutcomes:
|
|
10737
|
-
actualOutcomes:
|
|
10738
|
-
validated:
|
|
10739
|
-
createdAt:
|
|
10740
|
-
taskContext:
|
|
9884
|
+
counterfactuals: z16.array(
|
|
9885
|
+
z16.object({
|
|
9886
|
+
counterfactualId: z16.string(),
|
|
9887
|
+
hypothesis: z16.string().max(1e4),
|
|
9888
|
+
affectedBeliefs: z16.array(z16.string()),
|
|
9889
|
+
predictedOutcomes: z16.array(z16.string()),
|
|
9890
|
+
actualOutcomes: z16.array(z16.string()).optional(),
|
|
9891
|
+
validated: z16.boolean(),
|
|
9892
|
+
createdAt: z16.string(),
|
|
9893
|
+
taskContext: z16.string().optional()
|
|
10741
9894
|
})
|
|
10742
9895
|
),
|
|
10743
|
-
hindsightRecords:
|
|
10744
|
-
|
|
10745
|
-
taskId:
|
|
10746
|
-
records:
|
|
10747
|
-
|
|
10748
|
-
hindsightId:
|
|
10749
|
-
taskId:
|
|
10750
|
-
priorBeliefs:
|
|
10751
|
-
expectedOutcome:
|
|
10752
|
-
actualOutcome:
|
|
10753
|
-
outcomeMatched:
|
|
10754
|
-
correctedBeliefs:
|
|
10755
|
-
newBeliefs:
|
|
10756
|
-
lessons:
|
|
10757
|
-
createdAt:
|
|
9896
|
+
hindsightRecords: z16.array(
|
|
9897
|
+
z16.object({
|
|
9898
|
+
taskId: z16.string(),
|
|
9899
|
+
records: z16.array(
|
|
9900
|
+
z16.object({
|
|
9901
|
+
hindsightId: z16.string(),
|
|
9902
|
+
taskId: z16.string(),
|
|
9903
|
+
priorBeliefs: z16.array(z16.string()),
|
|
9904
|
+
expectedOutcome: z16.string().max(1e4),
|
|
9905
|
+
actualOutcome: z16.string().max(1e4),
|
|
9906
|
+
outcomeMatched: z16.boolean(),
|
|
9907
|
+
correctedBeliefs: z16.array(z16.string()),
|
|
9908
|
+
newBeliefs: z16.array(z16.string()),
|
|
9909
|
+
lessons: z16.array(z16.string()),
|
|
9910
|
+
createdAt: z16.string()
|
|
10758
9911
|
})
|
|
10759
9912
|
)
|
|
10760
9913
|
})
|
|
@@ -10762,7 +9915,7 @@ var BeliefSnapshotSchema = z19.object({
|
|
|
10762
9915
|
});
|
|
10763
9916
|
|
|
10764
9917
|
// src/context/belief-memory-persistence.ts
|
|
10765
|
-
var BELIEFS_DIR =
|
|
9918
|
+
var BELIEFS_DIR = path2.join(os2.homedir(), ".nexus-agents", "memory", "beliefs");
|
|
10766
9919
|
var MAX_SNAPSHOT_FILES = 10;
|
|
10767
9920
|
var SNAPSHOT_VERSION = 1;
|
|
10768
9921
|
function optProp(key, value) {
|
|
@@ -10940,75 +10093,75 @@ function hydrateSnapshot(snapshot) {
|
|
|
10940
10093
|
};
|
|
10941
10094
|
}
|
|
10942
10095
|
function ensureBeliefsDir() {
|
|
10943
|
-
if (!
|
|
10096
|
+
if (!fs2.existsSync(BELIEFS_DIR)) fs2.mkdirSync(BELIEFS_DIR, { recursive: true });
|
|
10944
10097
|
}
|
|
10945
10098
|
function getSnapshotFiles() {
|
|
10946
10099
|
try {
|
|
10947
|
-
return
|
|
10100
|
+
return fs2.readdirSync(BELIEFS_DIR).filter((f) => f.startsWith("beliefs-") && f.endsWith(".json")).sort().reverse();
|
|
10948
10101
|
} catch {
|
|
10949
10102
|
return [];
|
|
10950
10103
|
}
|
|
10951
10104
|
}
|
|
10952
|
-
function enforceRetention(
|
|
10105
|
+
function enforceRetention(logger11) {
|
|
10953
10106
|
try {
|
|
10954
10107
|
const files = getSnapshotFiles();
|
|
10955
10108
|
if (files.length <= MAX_SNAPSHOT_FILES) return;
|
|
10956
10109
|
const toDelete = files.slice(MAX_SNAPSHOT_FILES);
|
|
10957
|
-
for (const file of toDelete)
|
|
10958
|
-
|
|
10110
|
+
for (const file of toDelete) fs2.unlinkSync(path2.join(BELIEFS_DIR, file));
|
|
10111
|
+
logger11.debug("Belief snapshot retention enforced", {
|
|
10959
10112
|
kept: MAX_SNAPSHOT_FILES,
|
|
10960
10113
|
deleted: toDelete.length
|
|
10961
10114
|
});
|
|
10962
10115
|
} catch (error) {
|
|
10963
|
-
|
|
10116
|
+
logger11.debug("Belief snapshot retention cleanup failed", {
|
|
10964
10117
|
error: getErrorMessage(error)
|
|
10965
10118
|
});
|
|
10966
10119
|
}
|
|
10967
10120
|
}
|
|
10968
|
-
function saveBeliefSnapshot(data,
|
|
10121
|
+
function saveBeliefSnapshot(data, logger11) {
|
|
10969
10122
|
try {
|
|
10970
10123
|
ensureBeliefsDir();
|
|
10971
10124
|
const snapshot = createSnapshot(data);
|
|
10972
10125
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
10973
10126
|
const filename = `beliefs-${timestamp}.json`;
|
|
10974
|
-
const filepath =
|
|
10975
|
-
|
|
10976
|
-
|
|
10977
|
-
enforceRetention(
|
|
10127
|
+
const filepath = path2.join(BELIEFS_DIR, filename);
|
|
10128
|
+
fs2.writeFileSync(filepath, JSON.stringify(snapshot, null, 2), "utf-8");
|
|
10129
|
+
logger11.info("Belief memory snapshot saved", { filename, beliefs: snapshot.beliefs.length });
|
|
10130
|
+
enforceRetention(logger11);
|
|
10978
10131
|
return ok(filepath);
|
|
10979
10132
|
} catch (error) {
|
|
10980
10133
|
const message = getErrorMessage(error);
|
|
10981
10134
|
return err(new Error(`Failed to save belief snapshot: ${message}`));
|
|
10982
10135
|
}
|
|
10983
10136
|
}
|
|
10984
|
-
function loadBeliefSnapshot(
|
|
10137
|
+
function loadBeliefSnapshot(logger11) {
|
|
10985
10138
|
try {
|
|
10986
10139
|
ensureBeliefsDir();
|
|
10987
10140
|
const files = getSnapshotFiles();
|
|
10988
10141
|
if (files.length === 0) {
|
|
10989
|
-
|
|
10142
|
+
logger11.debug("No belief snapshots found");
|
|
10990
10143
|
return ok(null);
|
|
10991
10144
|
}
|
|
10992
10145
|
for (const file of files.slice(0, 3)) {
|
|
10993
10146
|
try {
|
|
10994
|
-
const filepath =
|
|
10995
|
-
const raw = JSON.parse(
|
|
10147
|
+
const filepath = path2.join(BELIEFS_DIR, file);
|
|
10148
|
+
const raw = JSON.parse(fs2.readFileSync(filepath, "utf-8"));
|
|
10996
10149
|
const validation = BeliefSnapshotSchema.safeParse(raw);
|
|
10997
10150
|
if (!validation.success) {
|
|
10998
|
-
|
|
10151
|
+
logger11.warn("Invalid belief snapshot file", { file, errors: validation.error.issues });
|
|
10999
10152
|
continue;
|
|
11000
10153
|
}
|
|
11001
10154
|
const hydrated = hydrateSnapshot(validation.data);
|
|
11002
|
-
|
|
10155
|
+
logger11.info("Belief memory snapshot loaded", { file, beliefs: hydrated.beliefs.size });
|
|
11003
10156
|
return ok(hydrated);
|
|
11004
10157
|
} catch (error) {
|
|
11005
|
-
|
|
10158
|
+
logger11.warn("Failed to load belief snapshot file", {
|
|
11006
10159
|
file,
|
|
11007
10160
|
error: getErrorMessage(error)
|
|
11008
10161
|
});
|
|
11009
10162
|
}
|
|
11010
10163
|
}
|
|
11011
|
-
|
|
10164
|
+
logger11.warn("All recent belief snapshots are invalid");
|
|
11012
10165
|
return ok(null);
|
|
11013
10166
|
} catch (error) {
|
|
11014
10167
|
const message = getErrorMessage(error);
|
|
@@ -11017,81 +10170,81 @@ function loadBeliefSnapshot(logger13) {
|
|
|
11017
10170
|
}
|
|
11018
10171
|
|
|
11019
10172
|
// src/context/memory-types.ts
|
|
11020
|
-
import { z as
|
|
10173
|
+
import { z as z18 } from "zod";
|
|
11021
10174
|
|
|
11022
10175
|
// src/context/memory-module-types.ts
|
|
11023
|
-
import { z as
|
|
11024
|
-
var CoreMemoryDataSchema =
|
|
11025
|
-
agentId:
|
|
11026
|
-
role:
|
|
11027
|
-
name:
|
|
11028
|
-
constraints:
|
|
11029
|
-
capabilities:
|
|
11030
|
-
systemPrompt:
|
|
11031
|
-
temperament:
|
|
10176
|
+
import { z as z17 } from "zod";
|
|
10177
|
+
var CoreMemoryDataSchema = z17.object({
|
|
10178
|
+
agentId: z17.string().min(1),
|
|
10179
|
+
role: z17.string(),
|
|
10180
|
+
name: z17.string().min(1),
|
|
10181
|
+
constraints: z17.array(z17.string()),
|
|
10182
|
+
capabilities: z17.array(z17.string()),
|
|
10183
|
+
systemPrompt: z17.string().max(5e4).optional(),
|
|
10184
|
+
temperament: z17.enum(["cautious", "balanced", "exploratory"]).optional()
|
|
11032
10185
|
});
|
|
11033
|
-
var EpisodeDataSchema =
|
|
11034
|
-
episodeId:
|
|
11035
|
-
taskId:
|
|
11036
|
-
agentId:
|
|
11037
|
-
action:
|
|
11038
|
-
outcome:
|
|
11039
|
-
context:
|
|
11040
|
-
learnings:
|
|
11041
|
-
timestamp:
|
|
11042
|
-
durationMs:
|
|
10186
|
+
var EpisodeDataSchema = z17.object({
|
|
10187
|
+
episodeId: z17.string().min(1),
|
|
10188
|
+
taskId: z17.string().min(1),
|
|
10189
|
+
agentId: z17.string().min(1),
|
|
10190
|
+
action: z17.string().min(1),
|
|
10191
|
+
outcome: z17.enum(["success", "failure", "partial"]),
|
|
10192
|
+
context: z17.record(z17.string(), z17.unknown()),
|
|
10193
|
+
learnings: z17.array(z17.string()).optional(),
|
|
10194
|
+
timestamp: z17.date(),
|
|
10195
|
+
durationMs: z17.number().positive().optional()
|
|
11043
10196
|
});
|
|
11044
|
-
var SemanticFactSchema =
|
|
11045
|
-
factId:
|
|
11046
|
-
domain:
|
|
11047
|
-
subject:
|
|
11048
|
-
predicate:
|
|
11049
|
-
object:
|
|
11050
|
-
confidence:
|
|
11051
|
-
source:
|
|
11052
|
-
validUntil:
|
|
10197
|
+
var SemanticFactSchema = z17.object({
|
|
10198
|
+
factId: z17.string().min(1),
|
|
10199
|
+
domain: z17.string().min(1),
|
|
10200
|
+
subject: z17.string().min(1),
|
|
10201
|
+
predicate: z17.string().min(1),
|
|
10202
|
+
object: z17.string(),
|
|
10203
|
+
confidence: z17.number().min(0).max(1),
|
|
10204
|
+
source: z17.string().optional(),
|
|
10205
|
+
validUntil: z17.date().optional()
|
|
11053
10206
|
});
|
|
11054
|
-
var ProcedureStepSchema =
|
|
11055
|
-
stepId:
|
|
11056
|
-
action:
|
|
11057
|
-
parameters:
|
|
11058
|
-
preconditions:
|
|
11059
|
-
postconditions:
|
|
10207
|
+
var ProcedureStepSchema = z17.object({
|
|
10208
|
+
stepId: z17.string().min(1),
|
|
10209
|
+
action: z17.string().min(1),
|
|
10210
|
+
parameters: z17.record(z17.string(), z17.unknown()).optional(),
|
|
10211
|
+
preconditions: z17.array(z17.string()).optional(),
|
|
10212
|
+
postconditions: z17.array(z17.string()).optional()
|
|
11060
10213
|
});
|
|
11061
|
-
var ProcedureSchema =
|
|
11062
|
-
procedureId:
|
|
11063
|
-
name:
|
|
11064
|
-
description:
|
|
11065
|
-
steps:
|
|
11066
|
-
triggerConditions:
|
|
11067
|
-
successRate:
|
|
11068
|
-
executionCount:
|
|
11069
|
-
averageDurationMs:
|
|
11070
|
-
tags:
|
|
10214
|
+
var ProcedureSchema = z17.object({
|
|
10215
|
+
procedureId: z17.string().min(1),
|
|
10216
|
+
name: z17.string().min(1),
|
|
10217
|
+
description: z17.string().max(1e4),
|
|
10218
|
+
steps: z17.array(ProcedureStepSchema).max(100),
|
|
10219
|
+
triggerConditions: z17.array(z17.string()),
|
|
10220
|
+
successRate: z17.number().min(0).max(1),
|
|
10221
|
+
executionCount: z17.number().int().min(0),
|
|
10222
|
+
averageDurationMs: z17.number().positive().optional(),
|
|
10223
|
+
tags: z17.array(z17.string()).optional()
|
|
11071
10224
|
});
|
|
11072
|
-
var ResourceReferenceSchema =
|
|
11073
|
-
resourceId:
|
|
11074
|
-
type:
|
|
11075
|
-
location:
|
|
11076
|
-
name:
|
|
11077
|
-
mimeType:
|
|
11078
|
-
size:
|
|
11079
|
-
hash:
|
|
11080
|
-
lastAccessed:
|
|
11081
|
-
lastModified:
|
|
11082
|
-
metadata:
|
|
10225
|
+
var ResourceReferenceSchema = z17.object({
|
|
10226
|
+
resourceId: z17.string().min(1),
|
|
10227
|
+
type: z17.enum(["file", "url", "api", "database", "other"]),
|
|
10228
|
+
location: z17.string().min(1),
|
|
10229
|
+
name: z17.string().min(1),
|
|
10230
|
+
mimeType: z17.string().optional(),
|
|
10231
|
+
size: z17.number().int().positive().optional(),
|
|
10232
|
+
hash: z17.string().optional(),
|
|
10233
|
+
lastAccessed: z17.date(),
|
|
10234
|
+
lastModified: z17.date().optional(),
|
|
10235
|
+
metadata: z17.record(z17.string(), z17.unknown()).optional()
|
|
11083
10236
|
});
|
|
11084
|
-
var VaultEntrySchema =
|
|
11085
|
-
vaultId:
|
|
11086
|
-
category:
|
|
11087
|
-
title:
|
|
11088
|
-
content:
|
|
11089
|
-
importance:
|
|
11090
|
-
createdAt:
|
|
11091
|
-
updatedAt:
|
|
11092
|
-
expiresAt:
|
|
11093
|
-
tags:
|
|
11094
|
-
relatedIds:
|
|
10237
|
+
var VaultEntrySchema = z17.object({
|
|
10238
|
+
vaultId: z17.string().min(1),
|
|
10239
|
+
category: z17.enum(["insight", "decision", "pattern", "config", "archive"]),
|
|
10240
|
+
title: z17.string().min(1),
|
|
10241
|
+
content: z17.unknown(),
|
|
10242
|
+
importance: z17.enum(["critical", "high", "normal"]),
|
|
10243
|
+
createdAt: z17.date(),
|
|
10244
|
+
updatedAt: z17.date(),
|
|
10245
|
+
expiresAt: z17.date().optional(),
|
|
10246
|
+
tags: z17.array(z17.string()).optional(),
|
|
10247
|
+
relatedIds: z17.array(z17.string()).optional()
|
|
11095
10248
|
});
|
|
11096
10249
|
|
|
11097
10250
|
// src/context/memory-types.ts
|
|
@@ -11105,7 +10258,7 @@ var MemoryType = {
|
|
|
11105
10258
|
/** Hindsight Belief Memory for reasoning agents (arXiv:2512.12818) */
|
|
11106
10259
|
BELIEF: "belief"
|
|
11107
10260
|
};
|
|
11108
|
-
var MemoryTypeSchema =
|
|
10261
|
+
var MemoryTypeSchema = z18.enum([
|
|
11109
10262
|
"core",
|
|
11110
10263
|
"episodic",
|
|
11111
10264
|
"semantic",
|
|
@@ -11155,6 +10308,7 @@ var DEFAULT_RELEVANCE_CONFIG = {
|
|
|
11155
10308
|
MemoryType.VAULT
|
|
11156
10309
|
],
|
|
11157
10310
|
qa_expert: [MemoryType.SEMANTIC, MemoryType.EPISODIC, MemoryType.PROCEDURAL, MemoryType.BELIEF],
|
|
10311
|
+
data_visualization_expert: [MemoryType.SEMANTIC, MemoryType.RESOURCE, MemoryType.EPISODIC],
|
|
11158
10312
|
custom: [MemoryType.SEMANTIC, MemoryType.PROCEDURAL, MemoryType.RESOURCE],
|
|
11159
10313
|
// TRINITY roles (arXiv:2512.04695) - thinker and verifier benefit from belief memory
|
|
11160
10314
|
thinker: [MemoryType.SEMANTIC, MemoryType.CORE, MemoryType.VAULT, MemoryType.BELIEF],
|
|
@@ -11405,7 +10559,7 @@ var KnowledgeVaultImpl = class {
|
|
|
11405
10559
|
};
|
|
11406
10560
|
|
|
11407
10561
|
// src/context/typed-memory.ts
|
|
11408
|
-
var
|
|
10562
|
+
var logger9 = createLogger({ component: "typed-memory" });
|
|
11409
10563
|
var TypedMemory = class {
|
|
11410
10564
|
core;
|
|
11411
10565
|
episodic;
|
|
@@ -11426,7 +10580,7 @@ var TypedMemory = class {
|
|
|
11426
10580
|
this.resource = new ResourceMemoryImpl(backend);
|
|
11427
10581
|
this.vault = new KnowledgeVaultImpl(backend);
|
|
11428
10582
|
this.belief = new HindsightBeliefMemory();
|
|
11429
|
-
|
|
10583
|
+
logger9.info("TypedMemory initialized");
|
|
11430
10584
|
}
|
|
11431
10585
|
async queryByType(type, query, limit = 20) {
|
|
11432
10586
|
const result = await this.backend.search(`${type} ${query}`, limit);
|
|
@@ -11468,7 +10622,7 @@ var TypedMemory = class {
|
|
|
11468
10622
|
async pruneExpired() {
|
|
11469
10623
|
const result = await this.backend.prune(new Date(getTimeProvider().now()));
|
|
11470
10624
|
if (!result.ok) return result;
|
|
11471
|
-
|
|
10625
|
+
logger9.info("Pruned expired entries", { count: result.value });
|
|
11472
10626
|
return ok({
|
|
11473
10627
|
prunedCount: result.value,
|
|
11474
10628
|
prunedByType: {
|
|
@@ -11511,11 +10665,11 @@ var MemoryPromoter = class {
|
|
|
11511
10665
|
agentic;
|
|
11512
10666
|
config;
|
|
11513
10667
|
log;
|
|
11514
|
-
constructor(beliefs, agentic, config = {},
|
|
10668
|
+
constructor(beliefs, agentic, config = {}, logger11) {
|
|
11515
10669
|
this.beliefs = beliefs;
|
|
11516
10670
|
this.agentic = agentic;
|
|
11517
10671
|
this.config = { ...DEFAULT_PROMOTION_CONFIG, ...config };
|
|
11518
|
-
this.log =
|
|
10672
|
+
this.log = logger11 ?? createLogger({ component: "MemoryPromoter" });
|
|
11519
10673
|
}
|
|
11520
10674
|
/**
|
|
11521
10675
|
* Promote high-confidence session learnings to structured beliefs.
|
|
@@ -11652,7 +10806,7 @@ var MemoryPromoter = class {
|
|
|
11652
10806
|
};
|
|
11653
10807
|
|
|
11654
10808
|
// src/mcp/tools/memory-decay.ts
|
|
11655
|
-
var
|
|
10809
|
+
var DEFAULT_DECAY_CONFIG = {
|
|
11656
10810
|
enabled: true,
|
|
11657
10811
|
decayIntervalMs: 60 * 60 * 1e3,
|
|
11658
10812
|
// 1 hour
|
|
@@ -11668,8 +10822,8 @@ var DEFAULT_DECAY_CONFIG2 = {
|
|
|
11668
10822
|
var CrossReferenceTracker = class {
|
|
11669
10823
|
references = /* @__PURE__ */ new Map();
|
|
11670
10824
|
log;
|
|
11671
|
-
constructor(
|
|
11672
|
-
this.log =
|
|
10825
|
+
constructor(logger11) {
|
|
10826
|
+
this.log = logger11 ?? createLogger({ component: "CrossReferenceTracker" });
|
|
11673
10827
|
}
|
|
11674
10828
|
/**
|
|
11675
10829
|
* Register a cross-reference between two memories.
|
|
@@ -11754,9 +10908,9 @@ var MemoryDecayManager = class {
|
|
|
11754
10908
|
agentic = null;
|
|
11755
10909
|
adaptive = null;
|
|
11756
10910
|
mobimem = null;
|
|
11757
|
-
constructor(config = {},
|
|
11758
|
-
this.config = { ...
|
|
11759
|
-
this.log =
|
|
10911
|
+
constructor(config = {}, logger11) {
|
|
10912
|
+
this.config = { ...DEFAULT_DECAY_CONFIG, ...config };
|
|
10913
|
+
this.log = logger11 ?? createLogger({ component: "MemoryDecayManager" });
|
|
11760
10914
|
this.tracker = new CrossReferenceTracker(this.log);
|
|
11761
10915
|
}
|
|
11762
10916
|
/**
|
|
@@ -12111,16 +11265,16 @@ async function queryAdaptiveMemory(adaptive, query, keywords, limit, log) {
|
|
|
12111
11265
|
}
|
|
12112
11266
|
|
|
12113
11267
|
// src/mcp/tools/tool-memory.ts
|
|
12114
|
-
var MEMORY_BASE =
|
|
12115
|
-
var DEFAULT_MEMORY_DIR =
|
|
12116
|
-
var AGENTIC_DB_PATH =
|
|
12117
|
-
var ADAPTIVE_DB_PATH =
|
|
12118
|
-
var TYPED_DB_PATH =
|
|
12119
|
-
var MOBIMEM_DB_PATH =
|
|
12120
|
-
var MARKDOWN_DIR =
|
|
11268
|
+
var MEMORY_BASE = path3.join(os3.homedir(), ".nexus-agents", "memory");
|
|
11269
|
+
var DEFAULT_MEMORY_DIR = path3.join(MEMORY_BASE, "sessions");
|
|
11270
|
+
var AGENTIC_DB_PATH = path3.join(MEMORY_BASE, "agentic.db");
|
|
11271
|
+
var ADAPTIVE_DB_PATH = path3.join(MEMORY_BASE, "adaptive.db");
|
|
11272
|
+
var TYPED_DB_PATH = path3.join(MEMORY_BASE, "typed.db");
|
|
11273
|
+
var MOBIMEM_DB_PATH = path3.join(MEMORY_BASE, "mobimem.db");
|
|
11274
|
+
var MARKDOWN_DIR = path3.join(MEMORY_BASE, "markdown");
|
|
12121
11275
|
var sharedInstance = null;
|
|
12122
|
-
function getToolMemory(
|
|
12123
|
-
sharedInstance ??= new ToolMemoryManager(
|
|
11276
|
+
function getToolMemory(logger11) {
|
|
11277
|
+
sharedInstance ??= new ToolMemoryManager(logger11);
|
|
12124
11278
|
return sharedInstance;
|
|
12125
11279
|
}
|
|
12126
11280
|
function shutdownToolMemory() {
|
|
@@ -12141,8 +11295,8 @@ var ToolMemoryManager = class {
|
|
|
12141
11295
|
mobimem = null;
|
|
12142
11296
|
decayManager = null;
|
|
12143
11297
|
initPromise = null;
|
|
12144
|
-
constructor(
|
|
12145
|
-
this.log =
|
|
11298
|
+
constructor(logger11) {
|
|
11299
|
+
this.log = logger11 ?? createLogger({ component: "ToolMemory" });
|
|
12146
11300
|
this.memory = new SessionMemory({
|
|
12147
11301
|
memoryDir: DEFAULT_MEMORY_DIR,
|
|
12148
11302
|
logger: this.log
|
|
@@ -12166,7 +11320,7 @@ var ToolMemoryManager = class {
|
|
|
12166
11320
|
}
|
|
12167
11321
|
/** Try to activate SQLite backends (best-effort, non-blocking). */
|
|
12168
11322
|
async initSqliteBackends() {
|
|
12169
|
-
|
|
11323
|
+
fs3.mkdirSync(MARKDOWN_DIR, { recursive: true });
|
|
12170
11324
|
await this.initAgenticMemory();
|
|
12171
11325
|
await this.initAdaptiveMemory();
|
|
12172
11326
|
await this.initTypedMemory();
|
|
@@ -12824,14 +11978,14 @@ var ToolMemoryManager = class {
|
|
|
12824
11978
|
};
|
|
12825
11979
|
|
|
12826
11980
|
// src/orchestration/outcomes/outcome-store-persistence.ts
|
|
12827
|
-
import { appendFileSync, readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as
|
|
11981
|
+
import { appendFileSync, readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync3 } from "fs";
|
|
12828
11982
|
var PersistentOutcomeStore = class extends OutcomeStore {
|
|
12829
11983
|
filePath;
|
|
12830
11984
|
logger;
|
|
12831
|
-
constructor(config,
|
|
11985
|
+
constructor(config, logger11) {
|
|
12832
11986
|
super(config);
|
|
12833
11987
|
this.filePath = config?.filePath ?? OUTCOMES_FILE;
|
|
12834
|
-
this.logger =
|
|
11988
|
+
this.logger = logger11 ?? createLogger({ component: "PersistentOutcomeStore" });
|
|
12835
11989
|
const dataDir = config?.dataDir;
|
|
12836
11990
|
ensureLearningDir(dataDir);
|
|
12837
11991
|
this.hydrate();
|
|
@@ -12875,7 +12029,7 @@ var PersistentOutcomeStore = class extends OutcomeStore {
|
|
|
12875
12029
|
}
|
|
12876
12030
|
}
|
|
12877
12031
|
hydrate() {
|
|
12878
|
-
if (!
|
|
12032
|
+
if (!existsSync3(this.filePath)) {
|
|
12879
12033
|
this.logger.debug("No outcomes file found, starting fresh", {
|
|
12880
12034
|
path: this.filePath
|
|
12881
12035
|
});
|
|
@@ -12972,7 +12126,7 @@ function emitTrendDetected(bus, detail) {
|
|
|
12972
12126
|
}
|
|
12973
12127
|
|
|
12974
12128
|
// src/mcp/tools/consensus-vote-recording.ts
|
|
12975
|
-
var
|
|
12129
|
+
var logger10 = createLogger({ tool: "consensus-vote" });
|
|
12976
12130
|
function recordVoteSuccess(proposal, strategy, outcome, duration, votes) {
|
|
12977
12131
|
try {
|
|
12978
12132
|
const memory = getToolMemory();
|
|
@@ -12988,10 +12142,10 @@ function recordVoteSuccess(proposal, strategy, outcome, duration, votes) {
|
|
|
12988
12142
|
source: "consensus-vote"
|
|
12989
12143
|
});
|
|
12990
12144
|
void memory.runPromotionPipeline().catch((error) => {
|
|
12991
|
-
|
|
12145
|
+
logger10.warn("Promotion pipeline failed", { error });
|
|
12992
12146
|
});
|
|
12993
12147
|
} catch (error) {
|
|
12994
|
-
|
|
12148
|
+
logger10.warn("Failed to record vote success to memory", { error: getErrorMessage(error) });
|
|
12995
12149
|
}
|
|
12996
12150
|
if (votes !== void 0) {
|
|
12997
12151
|
recordVoteOutcomes(votes);
|
|
@@ -13006,7 +12160,7 @@ function recordVoteError(proposal, errorMessage) {
|
|
|
13006
12160
|
filePattern: "mcp/tools/consensus-vote"
|
|
13007
12161
|
});
|
|
13008
12162
|
} catch (error) {
|
|
13009
|
-
|
|
12163
|
+
logger10.warn("Failed to record vote error", { error: getErrorMessage(error) });
|
|
13010
12164
|
}
|
|
13011
12165
|
}
|
|
13012
12166
|
function recordVoteOutcomes(votes) {
|
|
@@ -13033,7 +12187,7 @@ function recordVoteOutcomes(votes) {
|
|
|
13033
12187
|
});
|
|
13034
12188
|
}
|
|
13035
12189
|
} catch (error) {
|
|
13036
|
-
|
|
12190
|
+
logger10.debug("Best-effort vote outcome recording failed", { error: getErrorMessage(error) });
|
|
13037
12191
|
}
|
|
13038
12192
|
}
|
|
13039
12193
|
|
|
@@ -13083,6 +12237,32 @@ function createEmptyConsensusResult(proposal, algorithm) {
|
|
|
13083
12237
|
durationMs: 0
|
|
13084
12238
|
};
|
|
13085
12239
|
}
|
|
12240
|
+
var CASCADE_THRESHOLDS = {
|
|
12241
|
+
majority: 0.5,
|
|
12242
|
+
supermajority: 0.67,
|
|
12243
|
+
unanimous: 1
|
|
12244
|
+
};
|
|
12245
|
+
function detectEarlyCascade(algorithm, approvals, rejections, total) {
|
|
12246
|
+
const threshold = CASCADE_THRESHOLDS[algorithm] ?? 0.5;
|
|
12247
|
+
if (total === 0) return { decided: false, reason: "" };
|
|
12248
|
+
if (algorithm === "unanimous" && rejections > 0) {
|
|
12249
|
+
return { decided: true, reason: `Unanimous rejected: ${String(rejections)} rejection(s)` };
|
|
12250
|
+
}
|
|
12251
|
+
if (approvals / total > threshold) {
|
|
12252
|
+
return {
|
|
12253
|
+
decided: true,
|
|
12254
|
+
reason: `Approval locked: ${String(approvals)}/${String(total)} > ${String(threshold)}`
|
|
12255
|
+
};
|
|
12256
|
+
}
|
|
12257
|
+
const remaining = total - approvals - rejections;
|
|
12258
|
+
if ((approvals + remaining) / total < threshold) {
|
|
12259
|
+
return {
|
|
12260
|
+
decided: true,
|
|
12261
|
+
reason: `Rejection locked: max possible ${String(approvals + remaining)}/${String(total)} < ${String(threshold)}`
|
|
12262
|
+
};
|
|
12263
|
+
}
|
|
12264
|
+
return { decided: false, reason: "" };
|
|
12265
|
+
}
|
|
13086
12266
|
async function processVotesThroughEngine(votes, proposal, algorithm) {
|
|
13087
12267
|
const validVotes = votes.filter((v) => v.source !== "error");
|
|
13088
12268
|
if (validVotes.length === 0) return createEmptyConsensusResult(proposal, algorithm);
|
|
@@ -13106,22 +12286,22 @@ async function processVotesThroughEngine(votes, proposal, algorithm) {
|
|
|
13106
12286
|
});
|
|
13107
12287
|
return resultRes.value;
|
|
13108
12288
|
}
|
|
13109
|
-
function runHigherOrderVoting(strategy, voteMap,
|
|
12289
|
+
function runHigherOrderVoting(strategy, voteMap, logger11) {
|
|
13110
12290
|
if (strategy !== "higher_order") return void 0;
|
|
13111
12291
|
const hovStrategy = new HigherOrderVotingStrategy();
|
|
13112
12292
|
const tracker = getOrCreateCorrelationTracker();
|
|
13113
12293
|
const result = hovStrategy.aggregate(voteMap, tracker);
|
|
13114
|
-
|
|
12294
|
+
logger11.info("Higher-Order Voting complete", {
|
|
13115
12295
|
method: result.method,
|
|
13116
12296
|
decision: result.decision,
|
|
13117
12297
|
posteriorApproval: result.posteriorApproval.toFixed(3)
|
|
13118
12298
|
});
|
|
13119
12299
|
return result;
|
|
13120
12300
|
}
|
|
13121
|
-
function recordVotesToTracker(votes, voteMap, outcome,
|
|
12301
|
+
function recordVotesToTracker(votes, voteMap, outcome, logger11) {
|
|
13122
12302
|
const allVotesReal = votes.every((v) => v.source === "llm");
|
|
13123
12303
|
if (!allVotesReal) {
|
|
13124
|
-
|
|
12304
|
+
logger11.warn("Skipping correlation recording due to non-LLM votes", {
|
|
13125
12305
|
count: votes.filter((v) => v.source !== "llm").length
|
|
13126
12306
|
});
|
|
13127
12307
|
return;
|
|
@@ -13129,39 +12309,106 @@ function recordVotesToTracker(votes, voteMap, outcome, logger13) {
|
|
|
13129
12309
|
const tracker = getOrCreateCorrelationTracker();
|
|
13130
12310
|
const id = `consensus-${String(getTimeProvider().now())}-${getRandomProvider().random().toString(36).slice(2, 9)}`;
|
|
13131
12311
|
tracker.recordProposalVotes(id, voteMap, outcome);
|
|
13132
|
-
|
|
12312
|
+
logger11.debug("Recorded votes to tracker", { proposalId: id, outcome });
|
|
13133
12313
|
try {
|
|
13134
12314
|
const persisted = createPersistedProposal(id, voteMap, outcome);
|
|
13135
12315
|
const saveResult = saveCorrelationData([persisted]);
|
|
13136
12316
|
if (!saveResult.ok) {
|
|
13137
|
-
|
|
12317
|
+
logger11.warn("Failed to persist correlation data", { error: saveResult.error.message });
|
|
13138
12318
|
}
|
|
13139
12319
|
} catch (error) {
|
|
13140
12320
|
const message = getErrorMessage(error);
|
|
13141
|
-
|
|
12321
|
+
logger11.warn("Error persisting correlation data", { error: message });
|
|
12322
|
+
}
|
|
12323
|
+
}
|
|
12324
|
+
async function processVotesWithCascade(votes, opts) {
|
|
12325
|
+
const validVotes = votes.filter((v) => v.source !== "error");
|
|
12326
|
+
const approvals = validVotes.filter((v) => v.vote.decision === "approve").length;
|
|
12327
|
+
const rejections = validVotes.filter((v) => v.vote.decision === "reject").length;
|
|
12328
|
+
const cascadeInfo = detectEarlyCascade(opts.algorithm, approvals, rejections, opts.totalRoles);
|
|
12329
|
+
if (cascadeInfo.decided) {
|
|
12330
|
+
opts.log.info("Vote cascade: outcome decided early", {
|
|
12331
|
+
approvals,
|
|
12332
|
+
rejections,
|
|
12333
|
+
total: opts.totalRoles,
|
|
12334
|
+
reason: cascadeInfo.reason
|
|
12335
|
+
});
|
|
12336
|
+
}
|
|
12337
|
+
const engineResult = await processVotesThroughEngine(votes, opts.proposal, opts.algorithm);
|
|
12338
|
+
const voteMap = /* @__PURE__ */ new Map();
|
|
12339
|
+
for (const { role, vote, source } of votes) {
|
|
12340
|
+
if (source !== "error") voteMap.set(role, vote);
|
|
12341
|
+
}
|
|
12342
|
+
const higherOrderResult = cascadeInfo.decided ? void 0 : runHigherOrderVoting(opts.strategy, voteMap, opts.log);
|
|
12343
|
+
const outcome = engineResult.outcome === "approved" ? "approved" : "rejected";
|
|
12344
|
+
return { engineResult, voteMap, higherOrderResult, outcome, cascaded: cascadeInfo.decided };
|
|
12345
|
+
}
|
|
12346
|
+
var CONTRARIAN_ESCALATION_THRESHOLD = 0.8;
|
|
12347
|
+
async function runContrarianCheck(proposal, log) {
|
|
12348
|
+
try {
|
|
12349
|
+
const { executeExpert } = await import("./expert-bridge-J36C7VES.js");
|
|
12350
|
+
const prompt = [
|
|
12351
|
+
"You are a contrarian analyst. Your job is to find reasons this proposal should be REJECTED.",
|
|
12352
|
+
"Look for: YAGNI (not needed), MISALIGNED (wrong tech/architecture), SECURITY_RISK, SCOPE_CREEP.",
|
|
12353
|
+
"",
|
|
12354
|
+
`Proposal: ${proposal.slice(0, 2e3)}`,
|
|
12355
|
+
"",
|
|
12356
|
+
"If you find a strong reason to reject, respond with JSON:",
|
|
12357
|
+
'{"decision":"reject","confidence":0.0-1.0,"reasoning":"your concern"}',
|
|
12358
|
+
"If the proposal is sound, respond with:",
|
|
12359
|
+
'{"decision":"approve","confidence":0.0-1.0,"reasoning":"why it is acceptable"}'
|
|
12360
|
+
].join("\n");
|
|
12361
|
+
const result = await executeExpert("architecture", prompt);
|
|
12362
|
+
if (!result.success) return { shouldEscalate: false, reason: "", confidence: 0 };
|
|
12363
|
+
const jsonMatch = result.text.match(/\{[\s\S]*\}/);
|
|
12364
|
+
if (jsonMatch === null) return { shouldEscalate: false, reason: "", confidence: 0 };
|
|
12365
|
+
const parsed = JSON.parse(jsonMatch[0]);
|
|
12366
|
+
const isRejection = parsed.decision === "reject";
|
|
12367
|
+
const confidence = typeof parsed.confidence === "number" ? parsed.confidence : 0;
|
|
12368
|
+
const reasoning = typeof parsed.reasoning === "string" ? parsed.reasoning : "";
|
|
12369
|
+
if (isRejection && confidence >= CONTRARIAN_ESCALATION_THRESHOLD) {
|
|
12370
|
+
log.info("Contrarian rejected with high confidence", {
|
|
12371
|
+
confidence,
|
|
12372
|
+
reasoning: reasoning.slice(0, 200)
|
|
12373
|
+
});
|
|
12374
|
+
return { shouldEscalate: true, reason: reasoning, confidence };
|
|
12375
|
+
}
|
|
12376
|
+
return { shouldEscalate: false, reason: "", confidence };
|
|
12377
|
+
} catch {
|
|
12378
|
+
return { shouldEscalate: false, reason: "", confidence: 0 };
|
|
13142
12379
|
}
|
|
13143
12380
|
}
|
|
13144
|
-
async function executeVoting(input,
|
|
12381
|
+
async function executeVoting(input, logger11) {
|
|
13145
12382
|
const strategy = resolveStrategy(input);
|
|
13146
12383
|
const algorithm = strategyToAlgorithm(strategy);
|
|
13147
12384
|
const roles = getVoterRoles(input.quickMode);
|
|
13148
12385
|
const startTime = getTimeProvider().now();
|
|
13149
|
-
|
|
12386
|
+
logger11.info("Starting consensus vote", { strategy, algorithm, roleCount: roles.length });
|
|
13150
12387
|
const votes = await collectRealVotes({
|
|
13151
12388
|
roles,
|
|
13152
12389
|
proposal: input.proposal,
|
|
13153
12390
|
simulate: input.simulateVotes
|
|
13154
12391
|
});
|
|
13155
|
-
const engineResult = await
|
|
13156
|
-
|
|
13157
|
-
|
|
13158
|
-
|
|
12392
|
+
const { engineResult, voteMap, higherOrderResult, outcome, cascaded } = await processVotesWithCascade(votes, {
|
|
12393
|
+
totalRoles: roles.length,
|
|
12394
|
+
proposal: input.proposal,
|
|
12395
|
+
algorithm,
|
|
12396
|
+
strategy,
|
|
12397
|
+
log: logger11
|
|
12398
|
+
});
|
|
12399
|
+
recordVotesToTracker(votes, voteMap, outcome, logger11);
|
|
12400
|
+
if (input.quickMode && outcome === "approved" && !input.simulateVotes) {
|
|
12401
|
+
const escalation = await runContrarianCheck(input.proposal, logger11);
|
|
12402
|
+
if (escalation.shouldEscalate) {
|
|
12403
|
+
logger11.warn("Contrarian escalation: re-running with full vote", {
|
|
12404
|
+
reason: escalation.reason,
|
|
12405
|
+
confidence: escalation.confidence
|
|
12406
|
+
});
|
|
12407
|
+
return executeVoting({ ...input, quickMode: false }, logger11);
|
|
12408
|
+
}
|
|
13159
12409
|
}
|
|
13160
|
-
const higherOrderResult = runHigherOrderVoting(strategy, voteMap, logger13);
|
|
13161
|
-
const outcome = engineResult.outcome === "approved" ? "approved" : "rejected";
|
|
13162
|
-
recordVotesToTracker(votes, voteMap, outcome, logger13);
|
|
13163
12410
|
const totalTimeMs = getTimeProvider().now() - startTime;
|
|
13164
|
-
|
|
12411
|
+
logger11.info("Consensus vote completed", { strategy, outcome, durationMs: totalTimeMs, cascaded });
|
|
13165
12412
|
const result = {
|
|
13166
12413
|
proposal: input.proposal,
|
|
13167
12414
|
threshold: algorithm,
|
|
@@ -13175,14 +12422,14 @@ async function executeVoting(input, logger13) {
|
|
|
13175
12422
|
return result;
|
|
13176
12423
|
}
|
|
13177
12424
|
async function handleConsensusVote(deps, args) {
|
|
13178
|
-
const
|
|
12425
|
+
const logger11 = deps.logger ?? createLogger({ tool: "consensus_vote" });
|
|
13179
12426
|
try {
|
|
13180
|
-
const result = await executeVoting(args,
|
|
12427
|
+
const result = await executeVoting(args, logger11);
|
|
13181
12428
|
const strategy = args.strategy ?? "simple_majority";
|
|
13182
12429
|
const errorVotes = result.votes.filter((v) => v.source === "error");
|
|
13183
12430
|
if (errorVotes.length === result.votes.length && result.votes.length > 0) {
|
|
13184
12431
|
const failures = errorVotes.map((v) => `${v.role}: ${v.error ?? "unknown error"}`).join("; ");
|
|
13185
|
-
|
|
12432
|
+
logger11.warn("All voters failed", { failureCount: errorVotes.length, failures });
|
|
13186
12433
|
recordVoteError(args.proposal, `All ${String(errorVotes.length)} voters failed: ${failures}`);
|
|
13187
12434
|
return {
|
|
13188
12435
|
ok: false,
|
|
@@ -13200,7 +12447,7 @@ async function handleConsensusVote(deps, args) {
|
|
|
13200
12447
|
} catch (error) {
|
|
13201
12448
|
const message = getErrorMessage(error);
|
|
13202
12449
|
const cause = error instanceof Error ? error : new Error(message);
|
|
13203
|
-
|
|
12450
|
+
logger11.error("Consensus vote failed", cause);
|
|
13204
12451
|
recordVoteError(args.proposal, message);
|
|
13205
12452
|
return { ok: false, error: `Voting failed: ${message}` };
|
|
13206
12453
|
}
|
|
@@ -13251,27 +12498,27 @@ function createConsensusVoteHandler(deps) {
|
|
|
13251
12498
|
};
|
|
13252
12499
|
}
|
|
13253
12500
|
var CONSENSUS_VOTE_OUTPUT_SCHEMA = {
|
|
13254
|
-
proposal:
|
|
12501
|
+
proposal: z19.string(),
|
|
13255
12502
|
strategy: VotingStrategySchema,
|
|
13256
|
-
decision:
|
|
13257
|
-
approvalPercentage:
|
|
13258
|
-
voteCounts:
|
|
13259
|
-
approve:
|
|
13260
|
-
reject:
|
|
13261
|
-
abstain:
|
|
13262
|
-
error:
|
|
12503
|
+
decision: z19.enum(["approved", "rejected", "no_quorum"]),
|
|
12504
|
+
approvalPercentage: z19.number(),
|
|
12505
|
+
voteCounts: z19.object({
|
|
12506
|
+
approve: z19.number(),
|
|
12507
|
+
reject: z19.number(),
|
|
12508
|
+
abstain: z19.number(),
|
|
12509
|
+
error: z19.number()
|
|
13263
12510
|
}),
|
|
13264
|
-
votes:
|
|
13265
|
-
|
|
13266
|
-
role:
|
|
13267
|
-
decision:
|
|
13268
|
-
confidence:
|
|
13269
|
-
reasoning:
|
|
13270
|
-
simulated:
|
|
13271
|
-
error:
|
|
13272
|
-
modelUsed:
|
|
13273
|
-
rejectionCategories:
|
|
13274
|
-
|
|
12511
|
+
votes: z19.array(
|
|
12512
|
+
z19.object({
|
|
12513
|
+
role: z19.string().max(100),
|
|
12514
|
+
decision: z19.enum(["approve", "reject", "abstain"]),
|
|
12515
|
+
confidence: z19.number(),
|
|
12516
|
+
reasoning: z19.string().max(4e3),
|
|
12517
|
+
simulated: z19.boolean(),
|
|
12518
|
+
error: z19.boolean(),
|
|
12519
|
+
modelUsed: z19.string().max(100).optional(),
|
|
12520
|
+
rejectionCategories: z19.array(
|
|
12521
|
+
z19.enum([
|
|
13275
12522
|
"YAGNI",
|
|
13276
12523
|
"DRY_VIOLATION",
|
|
13277
12524
|
"OVER_ENGINEERING",
|
|
@@ -13283,50 +12530,50 @@ var CONSENSUS_VOTE_OUTPUT_SCHEMA = {
|
|
|
13283
12530
|
).optional()
|
|
13284
12531
|
})
|
|
13285
12532
|
),
|
|
13286
|
-
threshold:
|
|
13287
|
-
durationMs:
|
|
13288
|
-
simulateVotes:
|
|
13289
|
-
higherOrderMetadata:
|
|
13290
|
-
posteriorApproval:
|
|
13291
|
-
posteriorRejection:
|
|
13292
|
-
effectiveVoteCount:
|
|
13293
|
-
method:
|
|
13294
|
-
usedCorrelationData:
|
|
13295
|
-
improvementOverBaseline:
|
|
13296
|
-
downweightedAgents:
|
|
13297
|
-
reasoning:
|
|
12533
|
+
threshold: z19.enum(["majority", "supermajority", "unanimous"]).optional(),
|
|
12534
|
+
durationMs: z19.number(),
|
|
12535
|
+
simulateVotes: z19.boolean(),
|
|
12536
|
+
higherOrderMetadata: z19.object({
|
|
12537
|
+
posteriorApproval: z19.number(),
|
|
12538
|
+
posteriorRejection: z19.number(),
|
|
12539
|
+
effectiveVoteCount: z19.number(),
|
|
12540
|
+
method: z19.enum(["ow", "isp", "simple"]),
|
|
12541
|
+
usedCorrelationData: z19.boolean(),
|
|
12542
|
+
improvementOverBaseline: z19.number(),
|
|
12543
|
+
downweightedAgents: z19.array(z19.string().max(100)).max(10),
|
|
12544
|
+
reasoning: z19.string().max(2e3)
|
|
13298
12545
|
}).optional()
|
|
13299
12546
|
};
|
|
13300
12547
|
function registerConsensusVoteTool(server, deps) {
|
|
13301
|
-
const
|
|
12548
|
+
const logger11 = deps.logger ?? createLogger({ tool: "consensus_vote" });
|
|
13302
12549
|
const notifier = deps.notifier ?? createMcpNotifier(server);
|
|
13303
12550
|
const depsWithNotifier = { ...deps, notifier };
|
|
13304
12551
|
const toolSchema = {
|
|
13305
|
-
proposal:
|
|
13306
|
-
threshold:
|
|
12552
|
+
proposal: z19.string().min(1).max(MAX_PROPOSAL_LENGTH).describe("Proposal text to vote on"),
|
|
12553
|
+
threshold: z19.enum(["majority", "supermajority", "unanimous"]).optional().describe("Voting threshold (legacy). Use strategy instead."),
|
|
13307
12554
|
strategy: VotingStrategySchema.optional().describe(
|
|
13308
12555
|
"Voting strategy: simple_majority (default), supermajority, unanimous, proof_of_learning, or higher_order"
|
|
13309
12556
|
),
|
|
13310
|
-
quickMode:
|
|
13311
|
-
simulateVotes:
|
|
12557
|
+
quickMode: z19.boolean().optional().default(false).describe("Use 3 agents instead of 6"),
|
|
12558
|
+
simulateVotes: z19.boolean().optional().default(false).describe("Use simulated votes")
|
|
13312
12559
|
};
|
|
13313
12560
|
const description = "Execute multi-model consensus voting on a proposal. Uses 6 specialized agent roles (architect, security, devex, ai_ml, pm, catfish) to vote on proposals with configurable strategies. Supports higher_order strategy for Bayesian-optimal aggregation with correlation awareness (Issue #514).";
|
|
13314
12561
|
const secureHandler = createSecureHandler(createConsensusVoteHandler(depsWithNotifier), {
|
|
13315
12562
|
toolName: "consensus_vote",
|
|
13316
12563
|
rateLimiter: deps.rateLimiter,
|
|
13317
|
-
logger:
|
|
12564
|
+
logger: logger11
|
|
13318
12565
|
});
|
|
13319
12566
|
const timeoutMs = getToolTimeout("consensus_vote", deps.security);
|
|
13320
12567
|
const wrappedHandler = wrapToolWithTimeout("consensus_vote", secureHandler, {
|
|
13321
12568
|
timeoutMs,
|
|
13322
|
-
logger:
|
|
12569
|
+
logger: logger11
|
|
13323
12570
|
});
|
|
13324
12571
|
server.registerTool(
|
|
13325
12572
|
"consensus_vote",
|
|
13326
12573
|
{ description, inputSchema: toolSchema, outputSchema: CONSENSUS_VOTE_OUTPUT_SCHEMA },
|
|
13327
12574
|
toSdkCallback(wrappedHandler)
|
|
13328
12575
|
);
|
|
13329
|
-
|
|
12576
|
+
logger11.info("Registered consensus_vote tool with secure handler and timeout protection");
|
|
13330
12577
|
}
|
|
13331
12578
|
|
|
13332
12579
|
export {
|
|
@@ -13367,11 +12614,8 @@ export {
|
|
|
13367
12614
|
createUnifiedRegistry,
|
|
13368
12615
|
getGlobalRegistry,
|
|
13369
12616
|
DEFAULT_RELEVANCE_CONFIG,
|
|
13370
|
-
MemoryImportance,
|
|
13371
|
-
MemoryError,
|
|
13372
12617
|
generateHyphenId,
|
|
13373
12618
|
generateUUID,
|
|
13374
|
-
calculateTextJaccardSimilarity,
|
|
13375
12619
|
validateToolInput,
|
|
13376
12620
|
createValidator,
|
|
13377
12621
|
RateLimiter,
|
|
@@ -13472,4 +12716,4 @@ export {
|
|
|
13472
12716
|
CONSENSUS_VOTE_OUTPUT_SCHEMA,
|
|
13473
12717
|
registerConsensusVoteTool
|
|
13474
12718
|
};
|
|
13475
|
-
//# sourceMappingURL=chunk-
|
|
12719
|
+
//# sourceMappingURL=chunk-J245RJGW.js.map
|