progmune-runtime 2.1.4 → 2.1.5

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.
@@ -37,6 +37,7 @@ exports.WorkMemory = void 0;
37
37
  exports.recordEpisode = recordEpisode;
38
38
  exports.getRecentEpisodes = getRecentEpisodes;
39
39
  exports.getSuccessfulEpisodes = getSuccessfulEpisodes;
40
+ exports.pruneEpisodicMemory = pruneEpisodicMemory;
40
41
  exports.consolidateSemantic = consolidateSemantic;
41
42
  exports.findSemanticTemplate = findSemanticTemplate;
42
43
  const fs = __importStar(require("fs"));
@@ -100,10 +101,14 @@ function recordEpisode(episode) {
100
101
  timestamp: new Date().toISOString(),
101
102
  };
102
103
  episodes.unshift(newEpisode);
103
- if (episodes.length > MAX_EPISODES) {
104
+ // Simple cap: trim to prevent runaway growth between GC cycles
105
+ if (episodes.length > MAX_EPISODES * 1.5) {
104
106
  episodes.length = MAX_EPISODES;
105
107
  }
106
108
  saveEpisodes(episodes);
109
+ // Run GC every 100 episodes
110
+ if (episodes.length % 100 === 0)
111
+ pruneEpisodicMemory();
107
112
  }
108
113
  /** @requires LIMIT @produces EPISODE_LIST */
109
114
  function getRecentEpisodes(limit = 10) {
@@ -112,6 +117,35 @@ function getRecentEpisodes(limit = 10) {
112
117
  function getSuccessfulEpisodes(limit = 10) {
113
118
  return loadEpisodes().filter(e => e.success).slice(0, limit);
114
119
  }
120
+ // ── Semantic GC: prune episodic memory ──
121
+ const MAX_EPISODE_COUNT = 1000;
122
+ const MAX_AGE_DAYS = 30;
123
+ /** Prune episodic memory: keep high-value, recent, diverse episodes.
124
+ * Removes: old failures (>30 days), low-value duplicates, excess beyond max.
125
+ * Called periodically after recording new episodes. */
126
+ function pruneEpisodicMemory() {
127
+ const episodes = loadEpisodes();
128
+ if (episodes.length <= MAX_EPISODE_COUNT)
129
+ return 0;
130
+ const now = Date.now();
131
+ const scored = episodes.map((ep, i) => {
132
+ const ageDays = (now - new Date(ep.timestamp).getTime()) / 86400000;
133
+ // Score: success=+2, recent=+3, older=-1/day
134
+ let score = ep.success ? 2 : 0;
135
+ score += Math.max(0, 3 - ageDays * 0.5); // recent bonus, decays over 6 days
136
+ score -= Math.max(0, (ageDays - MAX_AGE_DAYS) * 0.5); // penalty for >30 days
137
+ return { ep, score, index: i };
138
+ });
139
+ // Keep top MAX_EPISODES by score
140
+ scored.sort((a, b) => b.score - a.score);
141
+ const kept = scored.slice(0, MAX_EPISODE_COUNT).sort((a, b) => a.index - b.index);
142
+ const removed = episodes.length - kept.length;
143
+ if (removed > 0) {
144
+ saveEpisodes(kept.map(s => s.ep));
145
+ console.error(`[Memory] Semantic GC: removed ${removed} low-value episodes, kept ${kept.length}`);
146
+ }
147
+ return removed;
148
+ }
115
149
  const SEMANTIC_FILE = path.join(MEMORY_DIR, "semantic.json");
116
150
  const SEMANTIC_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 天
117
151
  function loadSemantic() {
@@ -174,18 +208,28 @@ function consolidateSemantic(minOccurrences = 3) {
174
208
  saveSemantic(templates);
175
209
  console.error(`[语义记忆] 巩固完成,模板数量: ${templates.length}`);
176
210
  }
177
- /** @requires INTENT @produces TEMPLATE */
211
+ /** @requires INTENT @produces TEMPLATE
212
+ * Uses keyword overlap (replaces prefix matching) for semantic recall. */
178
213
  function findSemanticTemplate(intent) {
179
214
  const templates = loadSemantic();
180
215
  if (templates.length === 0)
181
216
  return undefined;
182
- const prefix = intent.substring(0, 20).toLowerCase();
183
- const exactMatch = templates.find(t => t.intentPattern.toLowerCase() === prefix);
184
- if (exactMatch && exactMatch.successRate >= 0.7)
185
- return exactMatch;
186
- const fuzzyMatch = templates.find(t => {
187
- const pattern = t.intentPattern.toLowerCase();
188
- return (prefix.includes(pattern) || pattern.includes(prefix)) && t.successRate >= 0.8;
189
- });
190
- return fuzzyMatch;
217
+ // Extract keywords from intent
218
+ const words = new Set(intent.toLowerCase().split(/[\s,,]+/).filter(w => w.length > 2));
219
+ if (words.size === 0)
220
+ return undefined;
221
+ // Score templates by keyword overlap
222
+ let best;
223
+ let bestScore = 0;
224
+ for (const t of templates) {
225
+ const tWords = t.intentPattern.toLowerCase().split(/[\s,,]+/);
226
+ const shared = tWords.filter(w => words.has(w)).length;
227
+ const total = new Set([...words, ...new Set(tWords)]).size;
228
+ const score = shared / (total || 1); // Jaccard-like
229
+ if (score > 0.5 && t.successRate >= 0.7 && score > bestScore) {
230
+ bestScore = score;
231
+ best = t;
232
+ }
233
+ }
234
+ return best;
191
235
  }
package/dist/planner.js CHANGED
@@ -750,6 +750,17 @@ async function plan(userIntent) {
750
750
  score += matchCount * 0.2;
751
751
  }
752
752
  }
753
+ // Semantic Capability: useWhen scenario matching
754
+ if (f.useWhen) {
755
+ for (const scenario of f.useWhen) {
756
+ const scenarioWords = scenario.toLowerCase().split(/[\s,]+/);
757
+ const matchCount = scenarioWords.filter((w) => w.length > 3 && intentLower.includes(w)).length;
758
+ if (matchCount >= 2)
759
+ score += 3.0; // strong signal: intent matches use case
760
+ else if (matchCount === 1)
761
+ score += 1.0;
762
+ }
763
+ }
753
764
  // Capability Graph: tag match
754
765
  if (f.tags) {
755
766
  for (const tag of f.tags) {
@@ -758,7 +769,7 @@ async function plan(userIntent) {
758
769
  }
759
770
  }
760
771
  // Dynamic Credit: multiply by actual success rate (0.1-1.0)
761
- const successRate = (0, feedback_1.getFunctionSuccessRate)(f.name);
772
+ const successRate = (0, feedback_1.getFailureAdjustedCredit)(f.name);
762
773
  const creditFactor = 0.3 + successRate * 0.7; // range: 0.3 (always fail) to 1.0 (always succeed)
763
774
  if (f.exported && !f.external)
764
775
  score *= creditFactor;
@@ -6,6 +6,7 @@ exports.formatSessionCounts = formatSessionCounts;
6
6
  * @requires SESSION_LIST @produces RESOLVED_COUNT
7
7
  * @tags session, count, statistics
8
8
  */
9
+ /** @useWhen checking how many sessions succeeded; computing success rate */
9
10
  function countResolved(sessions) {
10
11
  const resolved = sessions.filter((s) => s.resolved).length;
11
12
  return { resolved, unresolved: sessions.length - resolved, total: sessions.length };
package/dist/stdlib.js CHANGED
@@ -32,10 +32,12 @@ exports.retry = retry;
32
32
  exports.debounce = debounce;
33
33
  // ── String ──
34
34
  /** @requires STRING @produces VALIDATION_RESULT @tags string, email, validation */
35
+ /** @useWhen validating user input; form validation; email checking */
35
36
  function isValidEmail(str) {
36
37
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
37
38
  }
38
39
  /** @requires STRING @produces TRUNCATED_STRING @tags string, format */
40
+ /** @useWhen displaying preview text; limiting UI output; shortening strings */
39
41
  function truncate(str, maxLen, ellipsis = "...") {
40
42
  return str.length <= maxLen ? str : str.slice(0, maxLen - ellipsis.length) + ellipsis;
41
43
  }
@@ -88,6 +90,7 @@ function arrayDiff(a, b) {
88
90
  }
89
91
  // ── Math ──
90
92
  /** @requires NUMBERS @produces AVERAGE @tags math, statistics */
93
+ /** @useWhen computing statistics; data analysis; metrics calculation */
91
94
  function average(nums) {
92
95
  return nums.length === 0 ? 0 : nums.reduce((a, b) => a + b, 0) / nums.length;
93
96
  }
@@ -12,6 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.selectCapabilityChains = selectCapabilityChains;
13
13
  exports.formatChainHint = formatChainHint;
14
14
  const utils_1 = require("./utils");
15
+ const feedback_1 = require("./feedback");
15
16
  /** Build a capability graph from IR functions. */
16
17
  function buildCapabilityGraph(ir) {
17
18
  const graph = new Map();
@@ -55,7 +56,10 @@ function scoreNode(node, intentLower, keywords) {
55
56
  if (w.length > 2 && purposeLower.includes(w))
56
57
  score += 0.5;
57
58
  }
58
- return score;
59
+ // Dynamic Credit: multiply by actual success rate
60
+ const successRate = (0, feedback_1.getFailureAdjustedCredit)(node.name);
61
+ const creditFactor = 0.3 + successRate * 0.7;
62
+ return score * creditFactor;
59
63
  }
60
64
  /** Find all capability nodes that produce a given capability label. */
61
65
  function findProducers(graph, capability) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "progmune-runtime",
3
- "version": "2.1.4",
3
+ "version": "2.1.5",
4
4
  "description": "Progmune Runtime — Program Immunology: Constraint-Guided Program Synthesis Runtime",
5
5
  "main": "dist/mcp-server.mjs",
6
6
  "bin": {