micro-models-agent 0.39.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/bin/mma.mjs +41 -41
  2. package/dist/cli/commands.js +116 -3
  3. package/dist/cli/main.js +35 -8
  4. package/dist/cli/repl-commands.js +633 -0
  5. package/dist/cli/repl.js +110 -611
  6. package/dist/cli/setup.js +32 -12
  7. package/dist/config/config.js +46 -30
  8. package/dist/config/defaults.js +10 -1
  9. package/dist/config/security.js +15 -8
  10. package/dist/core/agent-moe.js +24 -12
  11. package/dist/core/agent.js +281 -47
  12. package/dist/core/bootstrap.js +52 -36
  13. package/dist/core/session-logger.js +35 -2
  14. package/dist/core/workspace.js +76 -0
  15. package/dist/i18n/en.json +79 -15
  16. package/dist/i18n/index.js +12 -9
  17. package/dist/i18n/ru.json +79 -15
  18. package/dist/index.js +13 -13
  19. package/dist/llm/openai-compat.js +39 -10
  20. package/dist/logger/app-logger.js +83 -16
  21. package/dist/logger/file-log.js +151 -0
  22. package/dist/main.js +537 -284
  23. package/dist/modules/browser/bridge-server.mjs +113 -105
  24. package/dist/modules/browser/session.js +108 -60
  25. package/dist/modules/certification/cli.js +176 -0
  26. package/dist/modules/certification/fact-checker.js +84 -0
  27. package/dist/modules/certification/loader.js +111 -0
  28. package/dist/modules/certification/manifest.js +50 -0
  29. package/dist/modules/certification/runner.js +162 -0
  30. package/dist/modules/certification/scenarios.js +124 -0
  31. package/dist/modules/certification/types.js +1 -0
  32. package/dist/modules/context/manager.js +119 -10
  33. package/dist/modules/execution/auditor.js +33 -39
  34. package/dist/modules/execution/index.js +8 -6
  35. package/dist/modules/execution/module.js +474 -32
  36. package/dist/modules/execution/moe-executor.js +97 -40
  37. package/dist/modules/execution/plan-coverage.js +68 -0
  38. package/dist/modules/execution/plan-persister.js +46 -0
  39. package/dist/modules/execution/plan-store.js +159 -0
  40. package/dist/modules/execution/planner.js +63 -13
  41. package/dist/modules/execution/stuck-detector.js +252 -39
  42. package/dist/modules/execution/tracker.js +21 -7
  43. package/dist/modules/execution/verifier.js +46 -17
  44. package/dist/modules/hallucination/confidence.js +7 -2
  45. package/dist/modules/hallucination/consistency.js +8 -42
  46. package/dist/modules/hallucination/detector.js +26 -21
  47. package/dist/modules/hallucination/factual.js +170 -150
  48. package/dist/modules/hallucination/index.js +5 -4
  49. package/dist/modules/hallucination/js-identifiers.js +72 -0
  50. package/dist/modules/hallucination/llm-judge.js +103 -0
  51. package/dist/modules/index.js +5 -5
  52. package/dist/modules/lsp/client.js +235 -0
  53. package/dist/modules/lsp/config.js +81 -0
  54. package/dist/modules/lsp/index.js +3 -0
  55. package/dist/modules/lsp/module.js +68 -0
  56. package/dist/modules/lsp/types.js +1 -0
  57. package/dist/modules/mcp/client.js +8 -2
  58. package/dist/modules/memory/store.js +4 -0
  59. package/dist/modules/plugins/builtin/lint-on-write.js +143 -38
  60. package/dist/modules/processes/index.js +1 -2
  61. package/dist/modules/processes/registry.js +125 -35
  62. package/dist/modules/processes/runner.js +9 -110
  63. package/dist/modules/security/audit-log.js +30 -10
  64. package/dist/modules/security/command-validator.js +42 -16
  65. package/dist/modules/security/content-scanner.js +9 -8
  66. package/dist/modules/security/network-validator.js +2 -2
  67. package/dist/modules/security/path-validator.js +64 -10
  68. package/dist/modules/security/security-policies.js +221 -67
  69. package/dist/modules/security/session-encryption.js +42 -25
  70. package/dist/modules/session/manager.js +15 -10
  71. package/dist/modules/session/store.js +62 -8
  72. package/dist/modules/skills/index.js +2 -3
  73. package/dist/modules/skills/module.js +10 -23
  74. package/dist/tools/bash.js +287 -90
  75. package/dist/tools/create-dir.js +0 -1
  76. package/dist/tools/delete-file.js +0 -1
  77. package/dist/tools/edit-file.js +10 -8
  78. package/dist/tools/executor.js +57 -7
  79. package/dist/tools/grep-tool.js +51 -29
  80. package/dist/tools/index.js +55 -40
  81. package/dist/tools/load-skill.js +14 -18
  82. package/dist/tools/move-file.js +3 -2
  83. package/dist/tools/pipeline-run.js +1 -1
  84. package/dist/tools/read-file.js +15 -5
  85. package/dist/tools/search-history.js +42 -22
  86. package/dist/tools/subagent.js +21 -12
  87. package/dist/tools/web-browse.js +54 -25
  88. package/dist/tools/web-fetch.js +60 -34
  89. package/dist/tools/web-search.js +39 -20
  90. package/dist/tools/write-file.js +13 -10
  91. package/dist/ui/diff.js +9 -16
  92. package/dist/ui/renderer.js +69 -6
  93. package/package.json +48 -45
  94. package/dist/modules/context/history.js +0 -15
  95. package/dist/modules/processes/detect.js +0 -34
  96. package/dist/modules/skills/matcher.js +0 -27
@@ -1,17 +1,17 @@
1
- import { FactualCheck } from './factual';
2
- import { ConsistencyCheck } from './consistency';
3
- import { ConfidenceCheck } from './confidence';
1
+ import { ConsistencyCheck } from "./consistency";
2
+ import { ConfidenceCheck } from "./confidence";
3
+ import { FactualCheck } from "./factual";
4
+ import { LLMJudge } from "./llm-judge";
4
5
  export class HallucinationDetector {
5
- factual;
6
6
  consistency;
7
7
  confidence;
8
- constructor() {
9
- this.factual = new FactualCheck();
8
+ factual;
9
+ judge;
10
+ constructor(baseDir, llmProvider) {
10
11
  this.consistency = new ConsistencyCheck();
11
12
  this.confidence = new ConfidenceCheck();
12
- }
13
- getFactualCheck() {
14
- return this.factual;
13
+ this.factual = baseDir ? new FactualCheck(baseDir) : null;
14
+ this.judge = llmProvider ? new LLMJudge(llmProvider) : null;
15
15
  }
16
16
  getConsistencyCheck() {
17
17
  return this.consistency;
@@ -19,23 +19,28 @@ export class HallucinationDetector {
19
19
  getConfidenceCheck() {
20
20
  return this.confidence;
21
21
  }
22
- validate(response) {
22
+ async validate(response) {
23
23
  const confidenceResult = this.confidence.validate(response);
24
- if (confidenceResult.status === 'retry' || confidenceResult.status === 'block') {
24
+ if (confidenceResult.status === "retry" ||
25
+ confidenceResult.status === "block") {
25
26
  return confidenceResult;
26
27
  }
27
- const factualResult = this.factual.validate(response);
28
- const consistencyResult = this.consistency.validate(response);
28
+ const factualResult = this.factual?.validate(response);
29
+ if (factualResult && factualResult.status !== "pass") {
30
+ return factualResult;
31
+ }
32
+ // LLM-as-judge consistency: fast path (no decisions) skips any LLM call.
33
+ const judgeResult = this.judge
34
+ ? await this.judge.validate(response, this.consistency)
35
+ : null;
29
36
  const warnings = [];
30
- if (factualResult.status === 'warn')
31
- warnings.push(factualResult.reason || '');
32
- if (consistencyResult.status === 'warn')
33
- warnings.push(consistencyResult.reason || '');
34
- if (confidenceResult.status === 'warn')
35
- warnings.push(confidenceResult.reason || '');
37
+ if (judgeResult && judgeResult.status === "warn")
38
+ warnings.push(judgeResult.reason || "");
39
+ if (confidenceResult.status === "warn")
40
+ warnings.push(confidenceResult.reason || "");
36
41
  if (warnings.length > 0) {
37
- return { status: 'warn', reason: warnings.join('; ') };
42
+ return { status: "warn", reason: warnings.join("; ") };
38
43
  }
39
- return { status: 'pass' };
44
+ return { status: "pass" };
40
45
  }
41
46
  }
@@ -1,170 +1,190 @@
1
+ import { existsSync, readdirSync } from "fs";
2
+ import { resolve, isAbsolute, join } from "path";
1
3
  import { t } from "../../i18n/index";
2
- import { existsSync } from "fs";
3
- import { join } from "path";
4
- const FILE_EXTENSIONS = new Set([
5
- "ts",
6
- "tsx",
7
- "js",
8
- "jsx",
9
- "mjs",
10
- "cjs",
11
- "mts",
12
- "cts",
13
- "json",
14
- "md",
15
- "yaml",
16
- "yml",
17
- "py",
18
- "rs",
19
- "go",
20
- "java",
21
- "c",
22
- "cpp",
23
- "h",
24
- "hpp",
25
- "html",
26
- "css",
27
- "scss",
28
- "less",
29
- "vue",
30
- "svelte",
31
- "sh",
32
- "bash",
33
- "zsh",
34
- "ps1",
35
- "bat",
36
- "cmd",
37
- "txt",
38
- "env",
39
- "env.local",
40
- "env.production",
41
- "gitignore",
42
- "dockerignore",
43
- "dockerfile",
44
- "makefile",
45
- "cmake",
46
- "toml",
47
- "lock",
48
- "config",
49
- "log",
50
- "xml",
51
- "sql",
52
- "graphql",
53
- "proto",
54
- "wasm",
4
+ import { isJsMemberAccess } from "./js-identifiers";
5
+ /** Generated/cached dirs to skip when scanning for bare file names. */
6
+ const IGNORED_DIRS = new Set([
7
+ "node_modules",
8
+ ".git",
9
+ "dist",
10
+ "build",
11
+ "coverage",
12
+ ".mma",
13
+ "_testing",
55
14
  ]);
56
- const VERSION_PATTERN = /^\d+(\.\d+)*$/;
57
- const COMMON_WORDS = new Set([
58
- "node.js", "Node.js",
59
- "console.log", "console.error", "console.warn", "console.info",
60
- "Math.floor", "Math.ceil", "Math.round", "Math.max", "Math.min",
61
- "JSON.parse", "JSON.stringify",
62
- "Object.keys", "Object.values", "Object.entries",
63
- "Array.from", "Array.isArray",
64
- "Date.now", "Date.parse",
65
- "RegExp", "Promise",
15
+ const NON_FILE_EXTENSIONS = new Set([
16
+ "com",
17
+ "org",
18
+ "net",
19
+ "gov",
20
+ "edu",
21
+ "io",
22
+ "dev",
23
+ "app",
24
+ "co",
25
+ "ai",
26
+ "ru",
27
+ "de",
28
+ "fr",
29
+ "uk",
30
+ "us",
31
+ "es",
32
+ "it",
33
+ "jp",
34
+ "cn",
35
+ "br",
66
36
  ]);
37
+ /** Well-known runtime/library names that end in .js/.ts but are NOT files. */
38
+ const TECH_NAMES = new Set([
39
+ "node.js",
40
+ "react.js",
41
+ "vue.js",
42
+ "next.js",
43
+ "angular.js",
44
+ "express.js",
45
+ "deno.js",
46
+ "qwik.js",
47
+ "svelte.js",
48
+ "jquery.js",
49
+ ]);
50
+ /**
51
+ * JS/TS global identifiers whose member access (`process.env`, `console.log`)
52
+ * looks like a file path to the regex but is code, not a file.
53
+ */
54
+ function looksLikeFilePath(s) {
55
+ const lower = s.toLowerCase();
56
+ // "Node.js" etc. are technologies, not files — never flag them.
57
+ if (TECH_NAMES.has(lower))
58
+ return false;
59
+ if (!s.includes("/") && !s.includes("\\") && !s.match(/^\w+\.[a-z]{2,4}$/i))
60
+ return false;
61
+ // process.env / console.log / Math.max — member access on JS globals,
62
+ // not file paths. Only applies to bare `word.word` (no slashes).
63
+ if (isJsMemberAccess(s))
64
+ return false;
65
+ const ext = s.split(".").pop()?.toLowerCase() || "";
66
+ return !NON_FILE_EXTENSIONS.has(ext);
67
+ }
67
68
  export class FactualCheck {
68
- knownPaths = new Set();
69
- createdPaths = new Set();
70
- readFiles = new Set();
71
- baseDir = process.cwd();
72
- setBaseDir(dir) {
73
- this.baseDir = dir;
69
+ baseDir;
70
+ nameCache = null;
71
+ nameCacheTime = 0;
72
+ lastRescan = 0;
73
+ static NAME_CACHE_TTL_MS = 5_000;
74
+ static RESCAN_COOLDOWN_MS = 2_000;
75
+ static MAX_INDEXED_FILES = 20_000;
76
+ constructor(baseDir) {
77
+ this.baseDir = baseDir;
74
78
  }
75
- trackReadPath(path) {
76
- this.knownPaths.add(path);
77
- const base = path.split(/[/\\]/).pop();
78
- if (base && base !== path)
79
- this.knownPaths.add(base);
80
- // Track that this file was actually read by the agent
81
- this.readFiles.add(base || path);
79
+ validate(response) {
80
+ const filePaths = this.extractFilePaths(response);
81
+ if (filePaths.length === 0)
82
+ return { status: "pass" };
83
+ const nonExistent = [];
84
+ for (const fp of filePaths) {
85
+ if (!this.pathExists(fp)) {
86
+ nonExistent.push(fp);
87
+ }
88
+ }
89
+ if (nonExistent.length > 0) {
90
+ return {
91
+ status: "warn",
92
+ reason: t("hall.unknown_paths", {
93
+ paths: nonExistent.slice(0, 5).join(", "),
94
+ }),
95
+ };
96
+ }
97
+ return { status: "pass" };
98
+ }
99
+ /**
100
+ * Bare filenames ("bikes.json") and relative paths ("src/data/bikes.json")
101
+ * both land on the project tree. Absolute paths are checked as-is.
102
+ */
103
+ pathExists(fp) {
104
+ if (isAbsolute(fp))
105
+ return existsSync(fp);
106
+ // "foo.json" has no directory part — treat it as a bare name that may
107
+ // live anywhere under baseDir (e.g. src/data/bikes.json). Resolving it
108
+ // against the workspace root alone produced false "unknown file" warnings.
109
+ if (!fp.includes("/") && !fp.includes("\\")) {
110
+ return this.bareNameExists(fp);
111
+ }
112
+ return existsSync(resolve(this.baseDir, fp));
82
113
  }
83
- trackCreatedPath(path) {
84
- this.knownPaths.add(path);
85
- const base = path.split(/[/\\]/).pop();
86
- if (base && base !== path)
87
- this.knownPaths.add(base);
88
- this.createdPaths.add(path);
114
+ bareNameExists(name) {
115
+ if (existsSync(resolve(this.baseDir, name)))
116
+ return true;
117
+ if (this.indexHas(name))
118
+ return true;
119
+ // A write_file from this session may have created the file after the
120
+ // index was built. Do a one-off rescan (rate-limited) before warning.
121
+ const now = Date.now();
122
+ if (now - this.lastRescan < FactualCheck.RESCAN_COOLDOWN_MS)
123
+ return false;
124
+ this.lastRescan = now;
125
+ this.nameCache = null;
126
+ this.nameCacheTime = 0;
127
+ return this.indexHas(name);
89
128
  }
90
- trackDeletedPath(path) {
91
- this.knownPaths.add(path);
92
- const base = path.split(/[/\\]/).pop();
93
- if (base && base !== path)
94
- this.knownPaths.add(base);
95
- this.createdPaths.delete(path);
129
+ indexHas(name) {
130
+ return (this.getNameIndex().get(name)?.length ?? 0) > 0;
96
131
  }
97
132
  /**
98
- * Register file paths found in a document (e.g. structure.md, README).
99
- * Files mentioned in project documentation are not hallucinations.
133
+ * Basename paths index, rebuilt every NAME_CACHE_TTL_MS so newly created
134
+ * files (write_file) are picked up without a full scan on every response.
100
135
  */
101
- trackDocumentContent(content) {
102
- // Match common path patterns in documentation
103
- const pathPatterns = /(?:^|\s)([\w\-./]+\.\w{1,10})(?:\s|$|[,;)])/gm;
104
- let match;
105
- while ((match = pathPatterns.exec(content)) !== null) {
106
- const file = match[1];
107
- if (file.includes('/') || file.includes('\\')) {
108
- this.knownPaths.add(file);
109
- }
110
- const base = file.split(/[/\\]/).pop();
111
- if (base)
112
- this.knownPaths.add(base);
136
+ getNameIndex() {
137
+ const now = Date.now();
138
+ if (this.nameCache &&
139
+ now - this.nameCacheTime < FactualCheck.NAME_CACHE_TTL_MS) {
140
+ return this.nameCache;
113
141
  }
142
+ const index = new Map();
143
+ const scanned = this.scanDir(this.baseDir, index, 0);
144
+ if (scanned > 0 || index.size > 0) {
145
+ this.nameCache = index;
146
+ this.nameCacheTime = now;
147
+ }
148
+ return index;
114
149
  }
115
- pathExistsOnDisk(path) {
150
+ scanDir(dir, index, count) {
151
+ if (count >= FactualCheck.MAX_INDEXED_FILES)
152
+ return count;
153
+ let entries;
116
154
  try {
117
- // Skip absolute paths they're either system paths or outside the project.
118
- // On Windows, existsSync('/...') can hang on certain paths.
119
- if (path.startsWith("/") || path.startsWith("~") || /^[A-Za-z]:/.test(path)) {
120
- return false;
121
- }
122
- return existsSync(join(this.baseDir, path));
155
+ entries = readdirSync(dir, { withFileTypes: true });
123
156
  }
124
157
  catch {
125
- return false;
158
+ return count;
126
159
  }
127
- }
128
- validate(response) {
129
- const pathRegex = /[\w\-./]+\.\w+/g;
130
- const mentionedPaths = response.match(pathRegex) || [];
131
- const unknownPaths = mentionedPaths.filter((p) => {
132
- if (this.knownPaths.has(p))
133
- return false;
134
- if (VERSION_PATTERN.test(p))
135
- return false;
136
- if (COMMON_WORDS.has(p))
137
- return false;
138
- // Skip absolute paths — agent responses use relative paths; absolute
139
- // paths are either system paths or URLs, and existsSync can hang on
140
- // Windows for root-relative paths like "/page.html".
141
- if (p.startsWith("/") || p.startsWith("~") || /^[A-Za-z]:/.test(p))
142
- return false;
143
- if (this.pathExistsOnDisk(p))
144
- return false;
145
- const ext = p.split(".").pop()?.toLowerCase() || "";
146
- if (!FILE_EXTENSIONS.has(ext))
147
- return false;
148
- const basename = p
149
- .split("/")
150
- .pop()
151
- ?.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
152
- if (basename) {
153
- const urlPattern = new RegExp(`(https?|file)://[^\\s]*${basename}`);
154
- if (urlPattern.test(response))
155
- return false;
160
+ for (const entry of entries) {
161
+ if (count >= FactualCheck.MAX_INDEXED_FILES)
162
+ break;
163
+ const full = join(dir, entry.name);
164
+ if (entry.isDirectory()) {
165
+ if (!IGNORED_DIRS.has(entry.name)) {
166
+ count = this.scanDir(full, index, count);
167
+ }
168
+ }
169
+ else if (entry.isFile()) {
170
+ const list = index.get(entry.name);
171
+ if (list)
172
+ list.push(full);
173
+ else
174
+ index.set(entry.name, [full]);
175
+ count++;
156
176
  }
157
- return true;
158
- });
159
- if (unknownPaths.length > 0) {
160
- const uniquePaths = [...new Set(unknownPaths)];
161
- return {
162
- status: "warn",
163
- reason: t("hall.unknown_paths", {
164
- paths: uniquePaths.slice(0, 3).join(", "),
165
- }),
166
- };
167
177
  }
168
- return { status: "pass" };
178
+ return count;
179
+ }
180
+ extractFilePaths(text) {
181
+ // Capture absolute Windows paths (with drive letter) and relative paths.
182
+ // The old pattern started at a word boundary, so "E:\project\src\a.ts"
183
+ // only matched "project\src\a.ts" — resolve() then glued that onto
184
+ // baseDir producing a bogus path and a false "unknown file" warning
185
+ // even for files that actually exist on disk.
186
+ const pattern = /\b(?:[a-zA-Z]:[\\/])?[\w./\\-]+\.[a-z]{2,6}\b/gi;
187
+ const matches = text.match(pattern) || [];
188
+ return [...new Set(matches)].filter(looksLikeFilePath);
169
189
  }
170
190
  }
@@ -1,4 +1,5 @@
1
- export { HallucinationDetector } from './detector';
2
- export { FactualCheck } from './factual';
3
- export { ConsistencyCheck } from './consistency';
4
- export { ConfidenceCheck } from './confidence';
1
+ export { HallucinationDetector, } from "./detector";
2
+ export { ConsistencyCheck } from "./consistency";
3
+ export { ConfidenceCheck } from "./confidence";
4
+ export { FactualCheck } from "./factual";
5
+ export { LLMJudge } from "./llm-judge";
@@ -0,0 +1,72 @@
1
+ /**
2
+ * JS/TS global identifiers whose member access (`process.env`, `console.log`,
3
+ * `Math.max`) looks like a file path to `\b[\w./\\-]+\.[a-z]+\b`-style regexes
4
+ * but is code, not a file. Shared by the hallucination factual check and the
5
+ * execution auditor so both stop flagging member access as "missing files".
6
+ */
7
+ const JS_GLOBALS = new Set([
8
+ "process",
9
+ "console",
10
+ "math",
11
+ "json",
12
+ "global",
13
+ "globalthis",
14
+ "window",
15
+ "document",
16
+ "buffer",
17
+ "module",
18
+ "require",
19
+ "exports",
20
+ "url",
21
+ "promise",
22
+ "array",
23
+ "object",
24
+ "string",
25
+ "number",
26
+ "boolean",
27
+ "symbol",
28
+ "date",
29
+ "regexp",
30
+ "error",
31
+ "map",
32
+ "set",
33
+ "weakmap",
34
+ "weakset",
35
+ "proxy",
36
+ "reflect",
37
+ "intl",
38
+ "crypto",
39
+ "performance",
40
+ "fetch",
41
+ "navigator",
42
+ "location",
43
+ "settimeout",
44
+ "setinterval",
45
+ "cleartimeout",
46
+ "clearinterval",
47
+ "queuemicrotask",
48
+ "structuredclone",
49
+ "textencoder",
50
+ "textdecoder",
51
+ "atomics",
52
+ "sharedarraybuffer",
53
+ "dataview",
54
+ "arraybuffer",
55
+ "bigint",
56
+ "infinity",
57
+ "nan",
58
+ "undefined",
59
+ "bun",
60
+ "deno",
61
+ "node",
62
+ ]);
63
+ /**
64
+ * True when `candidate` starts with a known JS/TS global followed by a dot
65
+ * (`process.env`, `console.log`, `process.env.NODE` partial matches from
66
+ * `\b[\w./\\-]+\.[a-z]+`-style regexes) — member access, not a file path.
67
+ */
68
+ export function isJsMemberAccess(candidate) {
69
+ const lower = candidate.toLowerCase();
70
+ const m = lower.match(/^([\w-]+)\./);
71
+ return m !== null && JS_GLOBALS.has(m[1]);
72
+ }
@@ -0,0 +1,103 @@
1
+ import { t } from "../../i18n/index";
2
+ const JUDGE_TIMEOUT_MS = 15000;
3
+ const MAX_DECISIONS_SHOWN = 6;
4
+ const MAX_RESPONSE_CHARS = 2000;
5
+ /**
6
+ * LLM-as-judge consistency check. Asks a model whether the agent's latest
7
+ * response contradicts any of its earlier decisions — replacing the fragile
8
+ * word-matching heuristic that only caught exact substring reversals.
9
+ *
10
+ * Fast path: when no decisions are tracked, returns pass without any LLM call.
11
+ * Any judge failure (timeout, provider error, unparseable verdict) degrades to
12
+ * pass so the agent loop is never blocked by the judge.
13
+ */
14
+ export class LLMJudge {
15
+ provider;
16
+ constructor(provider) {
17
+ this.provider = provider;
18
+ }
19
+ async validate(response, consistency) {
20
+ const decisions = consistency.getDecisions();
21
+ if (decisions.length === 0) {
22
+ return { status: "pass" };
23
+ }
24
+ const shown = decisions.slice(-MAX_DECISIONS_SHOWN);
25
+ const decisionLines = shown
26
+ .map((d, i) => `${i + 1}. [${d.location || "agent"}] "${d.decision}"`)
27
+ .join("\n");
28
+ const system = `You are a consistency checker for an AI coding agent. The agent previously made these decisions:
29
+
30
+ ${decisionLines}
31
+
32
+ Decide whether the agent's NEW response contradicts any of these decisions. A contradiction means reversing or abandoning a previously stated approach (e.g. switching to a different framework, changing a chosen strategy, or undoing a decision that was explicitly made).
33
+
34
+ Reply with ONLY valid JSON, no other text:
35
+ - {"contradicts": false}
36
+ - {"contradicts": true, "reason": "short explanation"}`;
37
+ const user = `Agent's new response:\n\n${response.slice(0, MAX_RESPONSE_CHARS)}`;
38
+ try {
39
+ const verdictText = await this.askJudge([
40
+ { role: "system", content: system },
41
+ { role: "user", content: user },
42
+ ]);
43
+ const verdict = this.parseVerdict(verdictText);
44
+ if (verdict.contradicts) {
45
+ const reason = verdict.reason?.trim()
46
+ ? ` — ${verdict.reason.trim()}`
47
+ : "";
48
+ return {
49
+ status: "warn",
50
+ reason: t("hall.contradiction_llm", { reason }),
51
+ };
52
+ }
53
+ return { status: "pass" };
54
+ }
55
+ catch {
56
+ return { status: "pass" };
57
+ }
58
+ }
59
+ async askJudge(messages) {
60
+ let text = "";
61
+ let timer;
62
+ const consume = (async () => {
63
+ for await (const chunk of this.provider.chat(messages, [])) {
64
+ if (chunk.type === "text" && chunk.content) {
65
+ text += chunk.content;
66
+ }
67
+ }
68
+ return text;
69
+ })();
70
+ const timeout = new Promise((_, reject) => {
71
+ timer = setTimeout(() => reject(new Error("LLM judge timed out")), JUDGE_TIMEOUT_MS);
72
+ });
73
+ try {
74
+ return await Promise.race([consume, timeout]);
75
+ }
76
+ finally {
77
+ if (timer)
78
+ clearTimeout(timer);
79
+ }
80
+ }
81
+ parseVerdict(text) {
82
+ const block = text.match(/\{[\s\S]*\}/);
83
+ if (block) {
84
+ try {
85
+ const obj = JSON.parse(block[0]);
86
+ if (typeof obj.contradicts === "boolean") {
87
+ return {
88
+ contradicts: obj.contradicts,
89
+ reason: typeof obj.reason === "string" ? obj.reason : undefined,
90
+ };
91
+ }
92
+ }
93
+ catch {
94
+ // fall through to lenient parsing
95
+ }
96
+ }
97
+ const lower = text.toLowerCase();
98
+ if (lower.includes('"contradicts": true') || /^yes\b/.test(lower.trim())) {
99
+ return { contradicts: true, reason: text.slice(0, 200) };
100
+ }
101
+ return { contradicts: false };
102
+ }
103
+ }
@@ -1,5 +1,5 @@
1
- export { ModuleRegistry } from './registry';
2
- export { SkillsLoader, SkillsMatcher, SkillsModule } from './skills';
3
- export { PluginManager } from './plugins';
4
- export { PluginLoader } from './plugins/loader';
5
- export { MCPClient, MCPRegistry } from './mcp';
1
+ export { ModuleRegistry } from "./registry";
2
+ export { SkillsLoader, SkillsModule } from "./skills";
3
+ export { PluginManager } from "./plugins";
4
+ export { PluginLoader } from "./plugins/loader";
5
+ export { MCPClient, MCPRegistry } from "./mcp";