progmune-runtime 2.0.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.
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeActionCode = executeActionCode;
4
+ class ActionBuilder {
5
+ constructor() {
6
+ this.actions = [];
7
+ this.vars = {};
8
+ }
9
+ call(func, args, assignTo) {
10
+ const normalizedArgs = args.map(a => {
11
+ if (typeof a === 'object' && a !== null && !('name' in a && 'type' in a && 'value' in a)) {
12
+ return { name: '', type: 'any', value: a };
13
+ }
14
+ return a;
15
+ });
16
+ const action = { kind: "call", function: func, args: normalizedArgs };
17
+ if (assignTo) {
18
+ action.assignTo = assignTo;
19
+ this.vars[assignTo] = assignTo;
20
+ }
21
+ this.actions.push(action);
22
+ }
23
+ ifBlock(condition, thenFn) {
24
+ const sub = new ActionBuilder();
25
+ sub.vars = { ...this.vars };
26
+ thenFn();
27
+ this.actions.push({ kind: "if", condition, thenActions: sub.actions });
28
+ Object.assign(this.vars, sub.vars);
29
+ }
30
+ ifElse(condition, thenFn, elseFn) {
31
+ const thenBuilder = new ActionBuilder();
32
+ const elseBuilder = new ActionBuilder();
33
+ thenBuilder.vars = { ...this.vars };
34
+ elseBuilder.vars = { ...this.vars };
35
+ thenFn();
36
+ elseFn();
37
+ this.actions.push({
38
+ kind: "if",
39
+ condition,
40
+ thenActions: thenBuilder.actions,
41
+ elseActions: elseBuilder.actions
42
+ });
43
+ Object.assign(this.vars, thenBuilder.vars, elseBuilder.vars);
44
+ }
45
+ assign(target, value) {
46
+ this.actions.push({ kind: "assign", target, value });
47
+ this.vars[target] = target;
48
+ }
49
+ output(value) {
50
+ this.actions.push({ kind: "return", value });
51
+ }
52
+ }
53
+ let currentVars = {};
54
+ function executeActionCode(code) {
55
+ const root = new ActionBuilder();
56
+ currentVars = {};
57
+ const apiFuncs = {
58
+ call: (...args) => root.call(args[0], args.slice(1)),
59
+ callAssign: (...args) => {
60
+ const f = args[0];
61
+ const assignTo = args[1];
62
+ root.call(f, args.slice(2), assignTo);
63
+ },
64
+ ifBlock: (cond, fn) => root.ifBlock(cond, () => fn()),
65
+ ifElse: (cond, thenFn, elseFn) => root.ifElse(cond, () => thenFn(), () => elseFn()),
66
+ assign: (t, v) => {
67
+ root.assign(t, v);
68
+ currentVars[t] = v;
69
+ },
70
+ output: (v) => root.output(v),
71
+ };
72
+ const apiNames = ['call', 'callAssign', 'ifBlock', 'ifElse', 'assign', 'output'];
73
+ const apiValues = apiNames.map(n => apiFuncs[n]);
74
+ try {
75
+ const proxyVars = new Proxy(currentVars, {
76
+ get(target, prop) {
77
+ if (typeof prop === 'string' && prop in target)
78
+ return target[prop];
79
+ return undefined;
80
+ },
81
+ set(target, prop, value) {
82
+ if (typeof prop === 'string')
83
+ target[prop] = value;
84
+ return true;
85
+ }
86
+ });
87
+ const wrappedCode = `with(vars) { ${code} }`;
88
+ const fn = new Function('vars', ...apiNames, wrappedCode);
89
+ fn(proxyVars, ...apiValues);
90
+ return root.actions;
91
+ }
92
+ catch (e) {
93
+ console.error("执行 Action 代码失败:", e);
94
+ return null;
95
+ }
96
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const memory_layer_1 = require("./memory-layer");
4
+ console.log("═══ 记忆巩固 ═══");
5
+ const recent = (0, memory_layer_1.getRecentEpisodes)(10);
6
+ console.log(`情景记忆: ${recent.length} 条`);
7
+ console.log(`成功: ${recent.filter(e => e.success).length} 条, 失败: ${recent.filter(e => !e.success).length} 条`);
8
+ (0, memory_layer_1.consolidateSemantic)(3);
9
+ console.log("巩固完成。");
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.emitCode = emitCode;
37
+ const fs = __importStar(require("fs"));
38
+ const BASIC_TYPES = new Set([
39
+ "string", "number", "boolean", "any", "void", "undefined", "null",
40
+ "str", "int", "float", "bool", "list", "dict", "tuple", "bytes",
41
+ ]);
42
+ function getImportPath(file) {
43
+ return "./" + file.replace(/\.ts$|\.tsx$/, "");
44
+ }
45
+ function emitCode(actions) {
46
+ const ir = JSON.parse(fs.readFileSync("ir.json", "utf-8"));
47
+ const fnIndex = new Map();
48
+ const fnMeta = new Map();
49
+ for (const f of ir) {
50
+ fnIndex.set(f.name, f.file);
51
+ fnMeta.set(f.name, f);
52
+ }
53
+ const imports = new Map();
54
+ const typeImports = new Map();
55
+ const collect = (action) => {
56
+ if (action.kind === "call" && action.function) {
57
+ const file = fnIndex.get(action.function);
58
+ const meta = fnMeta.get(action.function);
59
+ if (file) {
60
+ if (!imports.has(file))
61
+ imports.set(file, new Set());
62
+ imports.get(file).add(action.function);
63
+ if (meta?.params) {
64
+ for (const p of meta.params) {
65
+ if (!BASIC_TYPES.has(p.type)) {
66
+ if (!typeImports.has(file))
67
+ typeImports.set(file, new Set());
68
+ typeImports.get(file).add(p.type);
69
+ }
70
+ }
71
+ }
72
+ }
73
+ }
74
+ else if (action.kind === "if") {
75
+ (action.thenActions || []).forEach(collect);
76
+ (action.elseActions || []).forEach(collect);
77
+ }
78
+ else if (action.kind === "for") {
79
+ (action.bodyActions || []).forEach(collect);
80
+ }
81
+ };
82
+ for (const a of actions)
83
+ collect(a);
84
+ let code = "";
85
+ for (const [file, funcSet] of imports)
86
+ code += `import { ${[...funcSet].join(", ")} } from "${getImportPath(file)}";\n`;
87
+ for (const [file, typeSet] of typeImports)
88
+ code += `import type { ${[...typeSet].join(", ")} } from "${getImportPath(file)}";\n`;
89
+ code += "\nexport function main() {\n";
90
+ const declared = new Set();
91
+ let counter = 0;
92
+ const convert = (action, indent = " ") => {
93
+ if (!action || !action.kind)
94
+ return "";
95
+ if (action.kind === "call") {
96
+ const meta = fnMeta.get(action.function || "");
97
+ const args = (action.args || []).map((a, i) => {
98
+ if (typeof a === "string") {
99
+ if (declared.has(a))
100
+ return a;
101
+ return JSON.stringify(a);
102
+ }
103
+ const val = a?.value;
104
+ if (typeof val === "string" && declared.has(val))
105
+ return val;
106
+ const paramType = meta?.params?.[i]?.type || "any";
107
+ if (BASIC_TYPES.has(paramType)) {
108
+ if (paramType === "string" || paramType === "str")
109
+ return `"defaultStr"`;
110
+ if (paramType === "number" || paramType === "int" || paramType === "float")
111
+ return "0";
112
+ if (paramType === "boolean" || paramType === "bool")
113
+ return "false";
114
+ return `"default"`;
115
+ }
116
+ if (paramType === "UserPayload")
117
+ return `{ id: 1, role: "user" } as UserPayload`;
118
+ if (paramType === "PasswordHash")
119
+ return `"defaultHash"`;
120
+ if (paramType === "Token")
121
+ return `"defaultToken"`;
122
+ return `{} as ${paramType}`;
123
+ }).join(", ");
124
+ const varName = action.assignTo || `result_${counter++}`;
125
+ declared.add(varName);
126
+ return `${indent}const ${varName} = ${action.function}(${args});`;
127
+ }
128
+ else if (action.kind === "if") {
129
+ let lines = `${indent}if (${action.condition}) {\n`;
130
+ for (const a of (action.thenActions || []))
131
+ lines += convert(a, indent + " ") + "\n";
132
+ lines += `${indent}}`;
133
+ if (action.elseActions && action.elseActions.length > 0) {
134
+ lines += ` else {\n`;
135
+ for (const a of action.elseActions)
136
+ lines += convert(a, indent + " ") + "\n";
137
+ lines += `${indent}}`;
138
+ }
139
+ return lines;
140
+ }
141
+ else if (action.kind === "for") {
142
+ let lines = `${indent}for (const ${action.variable} of ${action.iterable}) {\n`;
143
+ for (const a of (action.bodyActions || []))
144
+ lines += convert(a, indent + " ") + "\n";
145
+ lines += `${indent}}`;
146
+ return lines;
147
+ }
148
+ else if (action.kind === "assign") {
149
+ const val = typeof action.value === "string" ? JSON.stringify(action.value) : convert(action.value);
150
+ if (action.target)
151
+ declared.add(action.target);
152
+ return `${indent}const ${action.target} = ${val};`;
153
+ }
154
+ else if (action.kind === "return") {
155
+ const val = typeof action.value === "string" ?
156
+ (declared.has(action.value) ? action.value : JSON.stringify(action.value)) :
157
+ convert(action.value);
158
+ return `${indent}return ${val};`;
159
+ }
160
+ return "";
161
+ };
162
+ for (const a of actions)
163
+ code += convert(a) + "\n";
164
+ code += "}\nmain();\n";
165
+ return code;
166
+ }
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.extractIRPython = extractIRPython;
37
+ const child_process_1 = require("child_process");
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ function extractIRPython(projectRoot) {
41
+ const scriptPath = path.resolve(__dirname, "../tools/extract_ir.py");
42
+ const cmd = `python3 "${scriptPath}" "${projectRoot}"`;
43
+ try {
44
+ (0, child_process_1.execSync)(cmd, { encoding: "utf-8", stdio: "pipe" });
45
+ }
46
+ catch (e) {
47
+ console.error("Python IR 提取失败:", e.stderr?.toString() || e.toString());
48
+ return [];
49
+ }
50
+ const irPath = path.resolve("ir.json");
51
+ if (fs.existsSync(irPath)) {
52
+ return JSON.parse(fs.readFileSync(irPath, "utf-8"));
53
+ }
54
+ return [];
55
+ }
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.extractIR = extractIR;
37
+ const ts_morph_1 = require("ts-morph");
38
+ const path = __importStar(require("path"));
39
+ const fs = __importStar(require("fs"));
40
+ // 获取类型节点的结构化描述
41
+ function getTypeDetail(typeNode) {
42
+ if (!typeNode)
43
+ return "";
44
+ const text = typeNode.getText();
45
+ // 简单处理联合类型
46
+ if (ts_morph_1.Node.isUnionTypeNode(typeNode)) {
47
+ return typeNode.getTypeNodes().map((t) => getTypeDetail(t)).join(" | ");
48
+ }
49
+ // 处理泛型
50
+ if (ts_morph_1.Node.isTypeReference(typeNode)) {
51
+ const typeName = typeNode.getTypeName().getText();
52
+ const typeArgs = typeNode.getTypeArguments();
53
+ if (typeArgs.length > 0) {
54
+ const args = typeArgs.map((ta) => getTypeDetail(ta)).join(", ");
55
+ return `${typeName}<${args}>`;
56
+ }
57
+ return typeName;
58
+ }
59
+ // 处理数组/元组
60
+ if (ts_morph_1.Node.isArrayTypeNode(typeNode)) {
61
+ return getTypeDetail(typeNode.getElementTypeNode()) + "[]";
62
+ }
63
+ // 其他类型直接返回文本
64
+ return text;
65
+ }
66
+ function getParamType(param) {
67
+ const typeNode = param.getTypeNode?.();
68
+ return typeNode ? typeNode.getText() : "any";
69
+ }
70
+ function getParamTypeDetail(param) {
71
+ const typeNode = param.getTypeNode?.();
72
+ return typeNode ? getTypeDetail(typeNode) : "";
73
+ }
74
+ function getReturnType(func) {
75
+ const typeNode = func.getReturnTypeNode?.();
76
+ return typeNode ? typeNode.getText() : "any";
77
+ }
78
+ function getReturnTypeDetail(func) {
79
+ const typeNode = func.getReturnTypeNode?.();
80
+ return typeNode ? getTypeDetail(typeNode) : "";
81
+ }
82
+ function extractDirectCalls(func) {
83
+ const body = func.getBody();
84
+ if (!body)
85
+ return [];
86
+ const calls = [];
87
+ body.forEachDescendant((node, traversal) => {
88
+ if (ts_morph_1.Node.isCallExpression(node)) {
89
+ const expr = node.getExpression();
90
+ if (ts_morph_1.Node.isIdentifier(expr))
91
+ calls.push(expr.getText());
92
+ else if (ts_morph_1.Node.isPropertyAccessExpression(expr))
93
+ calls.push(expr.getName());
94
+ }
95
+ if (ts_morph_1.Node.isFunctionDeclaration(node) || ts_morph_1.Node.isArrowFunction(node))
96
+ traversal.skip();
97
+ });
98
+ return [...new Set(calls)];
99
+ }
100
+ function extractIR(projectRoot) {
101
+ const absRoot = path.resolve(projectRoot);
102
+ const project = new ts_morph_1.Project({
103
+ tsConfigFilePath: path.join(absRoot, "tsconfig.json"),
104
+ skipAddingFilesFromTsConfig: false,
105
+ });
106
+ if (!fs.existsSync(path.join(absRoot, "tsconfig.json"))) {
107
+ project.addSourceFilesAtPaths(path.join(absRoot, "**/*.ts"));
108
+ }
109
+ const funcs = [];
110
+ for (const sf of project.getSourceFiles()) {
111
+ const relPath = path.relative(absRoot, sf.getFilePath());
112
+ for (const f of sf.getFunctions()) {
113
+ const name = f.getName();
114
+ if (!name)
115
+ continue;
116
+ funcs.push({
117
+ name,
118
+ params: f.getParameters().map(p => ({
119
+ name: p.getName(),
120
+ type: getParamType(p),
121
+ typeDetail: getParamTypeDetail(p),
122
+ })),
123
+ returnType: getReturnType(f),
124
+ returnTypeDetail: getReturnTypeDetail(f),
125
+ file: relPath,
126
+ calls: extractDirectCalls(f),
127
+ });
128
+ }
129
+ // 箭头函数类似处理,略
130
+ }
131
+ return funcs;
132
+ }
133
+ // 若直接运行
134
+ if (require.main === module) {
135
+ const root = process.argv[2];
136
+ if (!root) {
137
+ console.error("用法: ts-node extract-ir.ts <项目根>");
138
+ process.exit(1);
139
+ }
140
+ const fns = extractIR(root);
141
+ fs.writeFileSync("ir.json", JSON.stringify(fns, null, 2));
142
+ console.log(`✅ IR 提取完成: ${fns.length} 个函数 -> ir.json`);
143
+ }
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.recordFailure = recordFailure;
37
+ exports.getAllFailures = getAllFailures;
38
+ exports.getFailuresBySVL = getFailuresBySVL;
39
+ exports.getTopFailurePatterns = getTopFailurePatterns;
40
+ exports.generateCandidateRules = generateCandidateRules;
41
+ const fs = __importStar(require("fs"));
42
+ const path = __importStar(require("path"));
43
+ const CORPUS_DIR = path.resolve(__dirname, "../failure_corpus");
44
+ function ensureDir(dir) {
45
+ if (!fs.existsSync(dir))
46
+ fs.mkdirSync(dir, { recursive: true });
47
+ }
48
+ function recordFailure(record) {
49
+ ensureDir(CORPUS_DIR);
50
+ const date = new Date().toISOString().slice(0, 10);
51
+ const dateDir = path.join(CORPUS_DIR, date);
52
+ ensureDir(dateDir);
53
+ const id = `fail_${Date.now()}`;
54
+ const fullRecord = {
55
+ ...record,
56
+ id,
57
+ timestamp: new Date().toISOString(),
58
+ };
59
+ const filename = `${id}.json`;
60
+ const filepath = path.join(dateDir, filename);
61
+ fs.writeFileSync(filepath, JSON.stringify(fullRecord, null, 2));
62
+ console.log(`[FailureCorpus] 记录失败案例: ${id} [${record.violatedSVL}]`);
63
+ }
64
+ function getAllFailures() {
65
+ const records = [];
66
+ if (!fs.existsSync(CORPUS_DIR))
67
+ return records;
68
+ const dirs = fs.readdirSync(CORPUS_DIR);
69
+ for (const dir of dirs) {
70
+ const dirPath = path.join(CORPUS_DIR, dir);
71
+ if (!fs.statSync(dirPath).isDirectory())
72
+ continue;
73
+ const files = fs.readdirSync(dirPath);
74
+ for (const file of files) {
75
+ if (file.endsWith(".json")) {
76
+ const content = fs.readFileSync(path.join(dirPath, file), "utf-8");
77
+ records.push(JSON.parse(content));
78
+ }
79
+ }
80
+ }
81
+ return records;
82
+ }
83
+ function getFailuresBySVL(level) {
84
+ return getAllFailures().filter(r => r.violatedSVL === level);
85
+ }
86
+ function getTopFailurePatterns(limit = 5) {
87
+ const counts = new Map();
88
+ const all = getAllFailures();
89
+ for (const r of all) {
90
+ const key = `${r.violatedSVL}:${r.constraintType}`;
91
+ counts.set(key, (counts.get(key) || 0) + 1);
92
+ }
93
+ return [...counts.entries()]
94
+ .map(([pattern, count]) => ({ pattern, count }))
95
+ .sort((a, b) => b.count - a.count)
96
+ .slice(0, limit);
97
+ }
98
+ function generateCandidateRules() {
99
+ const patterns = getTopFailurePatterns(3);
100
+ const rules = [];
101
+ for (const p of patterns) {
102
+ if (p.pattern === "SVL-4:protocol") {
103
+ rules.push("建议:为相关函数添加 SSG 协议约束,检查前置状态。");
104
+ }
105
+ else if (p.pattern === "SVL-1:symbol_existence") {
106
+ rules.push("建议:检查项目 IR 是否缺少必要的函数定义。");
107
+ }
108
+ else if (p.pattern === "SVL-3:dataflow") {
109
+ rules.push("建议:强化变量声明检查,确保变量使用前已初始化。");
110
+ }
111
+ }
112
+ return rules;
113
+ }
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.loadFeedback = loadFeedback;
37
+ exports.saveFeedback = saveFeedback;
38
+ exports.getFunctionSuccessRate = getFunctionSuccessRate;
39
+ exports.recordRun = recordRun;
40
+ const fs = __importStar(require("fs"));
41
+ const path = __importStar(require("path"));
42
+ const FEEDBACK_PATH = path.resolve(__dirname, "../feedback.json");
43
+ function loadFeedback() {
44
+ if (!fs.existsSync(FEEDBACK_PATH))
45
+ return [];
46
+ return JSON.parse(fs.readFileSync(FEEDBACK_PATH, "utf-8"));
47
+ }
48
+ function saveFeedback(record) {
49
+ const data = loadFeedback();
50
+ data.push(record);
51
+ fs.writeFileSync(FEEDBACK_PATH, JSON.stringify(data, null, 2));
52
+ }
53
+ function getFunctionSuccessRate(funcName) {
54
+ const records = loadFeedback();
55
+ const funcRecords = records.filter(r => r.functionName === funcName);
56
+ if (funcRecords.length === 0)
57
+ return 0.5; // 中性值
58
+ const successCount = funcRecords.filter(r => r.success).length;
59
+ return successCount / funcRecords.length;
60
+ }
61
+ function recordRun(intent, actions, success, error) {
62
+ for (const action of actions) {
63
+ if (action.kind === "call") {
64
+ saveFeedback({
65
+ intent,
66
+ functionName: action.function,
67
+ success,
68
+ errorType: error ? error.split("\n")[0] : undefined,
69
+ timestamp: new Date().toISOString(),
70
+ });
71
+ }
72
+ }
73
+ }