open-agents-ai 0.187.508 → 0.187.510

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/index.js CHANGED
@@ -516650,6 +516650,15 @@ function clamp(x, lo, hi) {
516650
516650
  return hi;
516651
516651
  return x;
516652
516652
  }
516653
+ function clamp01(x) {
516654
+ if (!Number.isFinite(x))
516655
+ return 0;
516656
+ if (x < 0)
516657
+ return 0;
516658
+ if (x > 1)
516659
+ return 1;
516660
+ return x;
516661
+ }
516653
516662
  function sanitizeEmotionalState(raw) {
516654
516663
  if (!raw)
516655
516664
  return { valence: 0, arousal: 0 };
@@ -516692,21 +516701,29 @@ function modulateRetrievalScore(baseScore, current, memory, tuning = DEFAULT_RET
516692
516701
  return baseScore;
516693
516702
  return baseScore * congruenceMultiplier(current, memory, tuning);
516694
516703
  }
516695
- function createHomeostaticState(initial, target = DEFAULT_TARGET, windowSize = DEFAULT_WINDOW) {
516704
+ function createHomeostaticState(initial, target = DEFAULT_TARGET, windowSize = DEFAULT_WINDOW, regulationRate = 0) {
516696
516705
  const current = sanitizeEmotionalState(initial ?? { valence: 0, arousal: 0 });
516697
516706
  return {
516698
516707
  current,
516699
516708
  streak: 1,
516700
516709
  target: sanitizeEmotionalState(target),
516701
516710
  recent: [current],
516702
- windowSize: Math.max(1, Math.floor(windowSize))
516711
+ windowSize: Math.max(1, Math.floor(windowSize)),
516712
+ regulationRate: clamp01(regulationRate)
516703
516713
  };
516704
516714
  }
516705
516715
  function inSameBand(a2, b) {
516706
516716
  return Math.abs(clampValence(a2.valence) - clampValence(b.valence)) < STREAK_TOLERANCE && Math.abs(clampArousal(a2.arousal) - clampArousal(b.arousal)) < STREAK_TOLERANCE;
516707
516717
  }
516708
516718
  function observeEmotionalState(prev, next) {
516709
- const sample = sanitizeEmotionalState(next);
516719
+ const raw = sanitizeEmotionalState(next);
516720
+ const r2 = clamp01(prev.regulationRate ?? 0);
516721
+ const drifted = r2 === 0 ? raw : {
516722
+ valence: raw.valence + (prev.target.valence - raw.valence) * r2,
516723
+ arousal: raw.arousal + (prev.target.arousal - raw.arousal) * r2,
516724
+ emotion: raw.emotion
516725
+ };
516726
+ const sample = sanitizeEmotionalState(drifted);
516710
516727
  const continued = inSameBand(prev.current, sample);
516711
516728
  const recent = [sample, ...prev.recent].slice(0, prev.windowSize);
516712
516729
  return {
@@ -516740,6 +516757,26 @@ function suggestRegulation(state) {
516740
516757
  return "anchor-attention";
516741
516758
  return null;
516742
516759
  }
516760
+ function suggestRegulationActions(state) {
516761
+ const out = [];
516762
+ const dv = clampValence(state.current.valence) - clampValence(state.target.valence);
516763
+ const da = clampArousal(state.current.arousal) - clampArousal(state.target.arousal);
516764
+ const NEAR = 0.15;
516765
+ if (state.streak > 8 && Math.abs(dv) >= NEAR) {
516766
+ out.push(dv < 0 ? "seek-positive-experience" : "introduce-novelty");
516767
+ }
516768
+ if (da > NEAR && state.current.arousal > 0.85)
516769
+ out.push("calming-activity");
516770
+ if (da < -NEAR && state.current.arousal < 0.15)
516771
+ out.push("energizing-activity");
516772
+ if (dv < -NEAR && !out.includes("seek-positive-experience"))
516773
+ out.push("self-compassion");
516774
+ if (dv > NEAR && !out.includes("introduce-novelty"))
516775
+ out.push("anchor-attention");
516776
+ if (out.length === 0 && state.streak > 12)
516777
+ out.push("introduce-novelty");
516778
+ return out;
516779
+ }
516743
516780
  var DEFAULT_ENCODING, DEFAULT_RETRIEVAL, clampValence, clampArousal, DEFAULT_TARGET, DEFAULT_WINDOW, STREAK_TOLERANCE;
516744
516781
  var init_homeostaticRegulation = __esm({
516745
516782
  "packages/memory/dist/homeostaticRegulation.js"() {
@@ -520490,7 +520527,10 @@ var init_selfModel = __esm({
520490
520527
  stats,
520491
520528
  calibration: this.tracker.compute(),
520492
520529
  approachingDecay: this.approachingDecay(),
520493
- blindSpots: this.blindSpots()
520530
+ blindSpots: this.blindSpots(),
520531
+ // MEM_GAP B1: metaKnowledge always present (the agent introspecting
520532
+ // about its knowledge patterns is core, not optional).
520533
+ metaKnowledge: this.metaKnowledge()
520494
520534
  };
520495
520535
  if (this.opts.predictionStore) {
520496
520536
  const ps = this.opts.predictionStore;
@@ -520507,6 +520547,21 @@ var init_selfModel = __esm({
520507
520547
  }
520508
520548
  return report2;
520509
520549
  }
520550
+ /** MEM_GAP B1: compute metaKnowledge from base stores. */
520551
+ metaKnowledge(opts = {}) {
520552
+ const k = opts.topK ?? 10;
520553
+ return {
520554
+ mostRetrievedTopics: this.queryEpisodeTopics(`SELECT id, content, COALESCE(strength, 1) AS score FROM episodes ORDER BY score DESC LIMIT ?`, k),
520555
+ leastRetrievedTopics: this.queryEpisodeTopics(`SELECT id, content, COALESCE(strength, 1) AS score
520556
+ FROM episodes
520557
+ WHERE importance >= ?
520558
+ ORDER BY score ASC LIMIT ?`, k, [4]),
520559
+ mostValuableMemories: this.queryEpisodeTopics(`SELECT id, content, (importance * COALESCE(strength, 1)) AS score
520560
+ FROM episodes ORDER BY score DESC LIMIT ?`, k),
520561
+ mostUsefulProceduralMemories: this.queryProceduralTopics(k),
520562
+ learningTrajectory: this.computeLearningTrajectory()
520563
+ };
520564
+ }
520510
520565
  // ── private helpers ────────────────────────────────────────────────────────
520511
520566
  scalarCount(sql) {
520512
520567
  try {
@@ -520578,12 +520633,76 @@ var init_selfModel = __esm({
520578
520633
  return [];
520579
520634
  }
520580
520635
  }
520636
+ /** B1 helper: run a query expected to return rows of {id, content, score}
520637
+ * and convert to MetaKnowledgeTopic[]. Tolerates missing tables. */
520638
+ queryEpisodeTopics(sql, k, prefixArgs = []) {
520639
+ try {
520640
+ const rows = this.db.prepare(sql).all(...prefixArgs, k);
520641
+ return rows.map((r2) => ({
520642
+ id: r2.id,
520643
+ label: (r2.content ?? "").slice(0, 80),
520644
+ score: typeof r2.score === "number" ? r2.score : 0
520645
+ }));
520646
+ } catch {
520647
+ return [];
520648
+ }
520649
+ }
520650
+ /** B1 helper: top-K procedural memories by utility × confidence,
520651
+ * filtered to active (non-soft-deleted) rows. */
520652
+ queryProceduralTopics(k) {
520653
+ try {
520654
+ const rows = this.db.prepare(`SELECT id, content, (COALESCE(utility, 0.5) * COALESCE(confidence, 0.5)) AS score
520655
+ FROM procedural_memory
520656
+ WHERE deleted_at IS NULL
520657
+ ORDER BY score DESC
520658
+ LIMIT ?`).all(k);
520659
+ return rows.map((r2) => ({
520660
+ id: r2.id,
520661
+ label: (r2.content ?? "").slice(0, 80),
520662
+ score: typeof r2.score === "number" ? r2.score : 0
520663
+ }));
520664
+ } catch {
520665
+ return [];
520666
+ }
520667
+ }
520668
+ /** B1 helper: compute time-bucketed counts of episodes added vs forgotten.
520669
+ * Bucket width: 1 day. Last 7 buckets, oldest first. Forgotten ≈ count
520670
+ * of soft-deleted procedural rows with updated_at in the bucket window
520671
+ * (the closest persistent "removed memory" signal we have). */
520672
+ computeLearningTrajectory() {
520673
+ const buckets = [];
520674
+ const dayMs = 24 * 60 * 60 * 1e3;
520675
+ const now = Date.now();
520676
+ for (let i2 = 6; i2 >= 0; i2--) {
520677
+ const start2 = now - (i2 + 1) * dayMs;
520678
+ const end = now - i2 * dayMs;
520679
+ let added = 0;
520680
+ let forgotten = 0;
520681
+ try {
520682
+ const r2 = this.db.prepare(`SELECT COUNT(*) AS c FROM episodes WHERE timestamp >= ? AND timestamp < ?`).get(start2, end);
520683
+ added = r2?.c ?? 0;
520684
+ } catch {
520685
+ }
520686
+ try {
520687
+ const startIso = new Date(start2).toISOString();
520688
+ const endIso = new Date(end).toISOString();
520689
+ const r2 = this.db.prepare(`SELECT COUNT(*) AS c FROM procedural_memory
520690
+ WHERE deleted_at IS NOT NULL
520691
+ AND updated_at >= ?
520692
+ AND updated_at < ?`).get(startIso, endIso);
520693
+ forgotten = r2?.c ?? 0;
520694
+ } catch {
520695
+ }
520696
+ buckets.push({ bucketStart: start2, bucketWidthMs: dayMs, added, forgotten });
520697
+ }
520698
+ return buckets;
520699
+ }
520581
520700
  };
520582
520701
  }
520583
520702
  });
520584
520703
 
520585
520704
  // packages/memory/dist/predictionStore.js
520586
- function clamp01(x) {
520705
+ function clamp012(x) {
520587
520706
  if (!Number.isFinite(x))
520588
520707
  return 0.5;
520589
520708
  if (x < 0)
@@ -520614,7 +520733,7 @@ function durationError(predicted, actual) {
520614
520733
  return 0;
520615
520734
  const safePred = Math.max(predicted, 50);
520616
520735
  const ratio = Math.abs(predicted - actual) / safePred;
520617
- return clamp01(ratio);
520736
+ return clamp012(ratio);
520618
520737
  }
520619
520738
  var DEFAULT_AXIS_WEIGHTS, PredictionStore;
520620
520739
  var init_predictionStore = __esm({
@@ -520640,7 +520759,7 @@ var init_predictionStore = __esm({
520640
520759
  predict(p2) {
520641
520760
  const sanitized = {
520642
520761
  ...p2,
520643
- predictedConfidence: clamp01(p2.predictedConfidence),
520762
+ predictedConfidence: clamp012(p2.predictedConfidence),
520644
520763
  predictedDuration: p2.predictedDuration != null && Number.isFinite(p2.predictedDuration) ? Math.max(0, p2.predictedDuration) : null
520645
520764
  };
520646
520765
  this.pending.set(p2.correlationId, sanitized);
@@ -520654,14 +520773,14 @@ var init_predictionStore = __esm({
520654
520773
  this.pending.delete(correlationId);
520655
520774
  const actualDuration = observed.actualDuration != null && Number.isFinite(observed.actualDuration) ? Math.max(0, observed.actualDuration) : null;
520656
520775
  const sim = tokenSimilarity(pred.predictedOutcome, observed.actualOutcome);
520657
- const outcomeErr = clamp01(1 - sim);
520776
+ const outcomeErr = clamp012(1 - sim);
520658
520777
  const successErr = pred.predictedSuccess === observed.actualSuccess ? 0 : 1;
520659
- const confidenceErr = clamp01(observed.actualSuccess ? 1 - pred.predictedConfidence : pred.predictedConfidence);
520778
+ const confidenceErr = clamp012(observed.actualSuccess ? 1 - pred.predictedConfidence : pred.predictedConfidence);
520660
520779
  const durationErr = durationError(pred.predictedDuration, actualDuration);
520661
520780
  const w = this.axisWeights;
520662
520781
  const total = w.outcome * outcomeErr + w.success * successErr + w.confidence * confidenceErr + w.duration * durationErr;
520663
520782
  const sumWeights = w.outcome + w.success + w.confidence + w.duration;
520664
- const errorMagnitude = clamp01(sumWeights > 0 ? total / sumWeights : 0);
520783
+ const errorMagnitude = clamp012(sumWeights > 0 ? total / sumWeights : 0);
520665
520784
  const errorByAxis = {
520666
520785
  outcome: outcomeErr,
520667
520786
  success: successErr,
@@ -520679,7 +520798,7 @@ var init_predictionStore = __esm({
520679
520798
  errorByAxis,
520680
520799
  dominantAxis,
520681
520800
  // Learning signal: large errors with high confidence drive bigger updates
520682
- learningSignal: clamp01(errorMagnitude * (0.5 + 0.5 * pred.predictedConfidence))
520801
+ learningSignal: clamp012(errorMagnitude * (0.5 + 0.5 * pred.predictedConfidence))
520683
520802
  };
520684
520803
  this.history.push(err);
520685
520804
  if (this.history.length > this.capacity) {
@@ -520826,7 +520945,7 @@ var init_predictionStore = __esm({
520826
520945
  errorMagnitude: r2.error_magnitude ?? 0,
520827
520946
  errorByAxis: axes,
520828
520947
  dominantAxis: r2.dominant_axis ?? "outcome",
520829
- learningSignal: clamp01((r2.error_magnitude ?? 0) * 0.75)
520948
+ learningSignal: clamp012((r2.error_magnitude ?? 0) * 0.75)
520830
520949
  });
520831
520950
  }
520832
520951
  }
@@ -520844,7 +520963,7 @@ function clamp2(x, lo, hi) {
520844
520963
  return hi;
520845
520964
  return x;
520846
520965
  }
520847
- function clamp012(x) {
520966
+ function clamp013(x) {
520848
520967
  return clamp2(x, 0, 1);
520849
520968
  }
520850
520969
  function nonNegative(x) {
@@ -520857,16 +520976,16 @@ function buildTrace(input) {
520857
520976
  const used = nonNegative(i2.contextTokensUsed ?? DEFAULT_TRACE.contextTokensUsed);
520858
520977
  const max = nonNegative(i2.contextTokensMax ?? DEFAULT_TRACE.contextTokensMax);
520859
520978
  const derivedLoad = max > 0 ? used / max : 0;
520860
- const load2 = i2.cognitiveLoad != null ? clamp012(i2.cognitiveLoad) : clamp012(derivedLoad);
520979
+ const load2 = i2.cognitiveLoad != null ? clamp013(i2.cognitiveLoad) : clamp013(derivedLoad);
520861
520980
  return {
520862
520981
  durationMs: nonNegative(i2.durationMs ?? DEFAULT_TRACE.durationMs),
520863
520982
  hesitationCount: Math.max(0, Math.floor(i2.hesitationCount ?? 0)),
520864
520983
  retryCount: Math.max(0, Math.floor(i2.retryCount ?? 0)),
520865
- intensity: clamp012(i2.intensity ?? DEFAULT_TRACE.intensity),
520984
+ intensity: clamp013(i2.intensity ?? DEFAULT_TRACE.intensity),
520866
520985
  visualGist: typeof i2.visualGist === "string" ? i2.visualGist : void 0,
520867
520986
  auditoryGist: typeof i2.auditoryGist === "string" ? i2.auditoryGist : void 0,
520868
520987
  screenState: typeof i2.screenState === "string" ? i2.screenState : void 0,
520869
- confidence: clamp012(i2.confidence ?? DEFAULT_TRACE.confidence),
520988
+ confidence: clamp013(i2.confidence ?? DEFAULT_TRACE.confidence),
520870
520989
  cognitiveLoad: load2,
520871
520990
  contextTokensUsed: used,
520872
520991
  contextTokensMax: max,
@@ -520889,7 +521008,7 @@ function extractTrace(metadata) {
520889
521008
  }
520890
521009
  function engagementScore(trace) {
520891
521010
  const alertness = 1 - trace.cognitiveLoad;
520892
- return clamp012((trace.intensity + alertness + trace.confidence) / 3);
521011
+ return clamp013((trace.intensity + alertness + trace.confidence) / 3);
520893
521012
  }
520894
521013
  function wasHesitant(trace, threshold = 0.4) {
520895
521014
  return trace.hesitationCount >= 2 || trace.retryCount >= 1 || trace.confidence < threshold;
@@ -520951,6 +521070,21 @@ function slowWaveReplay(db, options2 = {}) {
520951
521070
  WHERE id IN (${placeholders})`).run(safeDelta, start2, ...ids);
520952
521071
  } catch {
520953
521072
  }
521073
+ const integratedNodes = [];
521074
+ if (options2.graph) {
521075
+ for (const id of ids) {
521076
+ try {
521077
+ const referenced = db.prepare(`SELECT 1 FROM kg_edges WHERE source_episode_id = ? LIMIT 1`).get(id);
521078
+ if (!referenced) {
521079
+ const nodeText = `episode:${id}`;
521080
+ const newNodeId = options2.graph.upsertNode({ text: nodeText, nodeType: "event" });
521081
+ if (newNodeId)
521082
+ integratedNodes.push(newNodeId);
521083
+ }
521084
+ } catch {
521085
+ }
521086
+ }
521087
+ }
520954
521088
  return {
520955
521089
  cycle: {
520956
521090
  phase: "slow_wave",
@@ -520960,7 +521094,10 @@ function slowWaveReplay(db, options2 = {}) {
520960
521094
  downscaledEpisodes: [],
520961
521095
  prunedEpisodes: [],
520962
521096
  novelAssociations: [],
520963
- energyCost: ids.length
521097
+ energyCost: ids.length + integratedNodes.length,
521098
+ compressedEpisodes: [],
521099
+ flaggedHubs: [],
521100
+ integratedNodes
520964
521101
  }
520965
521102
  };
520966
521103
  }
@@ -520998,6 +521135,25 @@ function remDream(db, options2 = {}) {
520998
521135
  novel.push({ from: seed.id, to: target.id, reason: "rem-temporal-distance" });
520999
521136
  }
521000
521137
  }
521138
+ if (options2.graph && novel.length > 0) {
521139
+ for (const link of novel) {
521140
+ try {
521141
+ const srcId = options2.graph.upsertNode({ text: `episode:${link.from}`, nodeType: "event" });
521142
+ const dstId = options2.graph.upsertNode({ text: `episode:${link.to}`, nodeType: "event" });
521143
+ if (srcId && dstId) {
521144
+ options2.graph.addEdge({
521145
+ srcId,
521146
+ dstId,
521147
+ relation: "associated_via_rem",
521148
+ edgeType: "associative",
521149
+ confidence: 0.4,
521150
+ sourceEpisodeId: link.from
521151
+ });
521152
+ }
521153
+ } catch {
521154
+ }
521155
+ }
521156
+ }
521001
521157
  return {
521002
521158
  cycle: {
521003
521159
  phase: "rem",
@@ -521007,7 +521163,10 @@ function remDream(db, options2 = {}) {
521007
521163
  downscaledEpisodes: [],
521008
521164
  prunedEpisodes: [],
521009
521165
  novelAssociations: novel,
521010
- energyCost: seedRows.length + novel.length
521166
+ energyCost: seedRows.length + novel.length,
521167
+ compressedEpisodes: [],
521168
+ flaggedHubs: [],
521169
+ integratedNodes: []
521011
521170
  }
521012
521171
  };
521013
521172
  }
@@ -521038,32 +521197,78 @@ function lightSleep(db, options2 = {}) {
521038
521197
  } catch {
521039
521198
  }
521040
521199
  const pruned = [];
521200
+ const compressed = [];
521201
+ const compressMode = !!options2.compressInsteadOfPrune;
521202
+ const gistMaxChars = Math.max(20, options2.gistMaxChars ?? 80);
521041
521203
  for (const klass of prunableClasses) {
521042
521204
  const stale = stalePerClass[klass];
521043
521205
  const cutoff = start2 - stale;
521206
+ const remaining = maxPrune - (pruned.length + compressed.length);
521207
+ if (remaining <= 0)
521208
+ break;
521044
521209
  let rows = [];
521045
521210
  try {
521046
- rows = db.prepare(`SELECT id FROM episodes
521211
+ rows = db.prepare(`SELECT id, content FROM episodes
521047
521212
  WHERE decay_class = ?
521048
521213
  AND importance < ?
521049
521214
  AND timestamp < ?
521050
521215
  ORDER BY timestamp ASC
521051
- LIMIT ?`).all(klass, pruneImportance, cutoff, maxPrune - pruned.length);
521216
+ LIMIT ?`).all(klass, pruneImportance, cutoff, remaining);
521052
521217
  } catch {
521053
521218
  rows = [];
521054
521219
  }
521055
521220
  if (rows.length === 0)
521056
521221
  continue;
521057
- const ids = rows.map((r2) => r2.id);
521058
- try {
521059
- const placeholders = ids.map(() => "?").join(",");
521060
- db.prepare(`DELETE FROM episodes WHERE id IN (${placeholders})`).run(...ids);
521061
- pruned.push(...ids);
521062
- } catch {
521222
+ if (compressMode) {
521223
+ try {
521224
+ const updateStmt = db.prepare(`UPDATE episodes
521225
+ SET content = ?,
521226
+ metadata = json_patch(COALESCE(metadata, '{}'), json_object('compressedAt', ?))
521227
+ WHERE id = ?`);
521228
+ for (const row of rows) {
521229
+ const truncated = (row.content ?? "").slice(0, gistMaxChars);
521230
+ const gist = (row.content ?? "").length > gistMaxChars ? truncated + "…" : truncated;
521231
+ try {
521232
+ updateStmt.run(gist, start2, row.id);
521233
+ compressed.push(row.id);
521234
+ } catch {
521235
+ try {
521236
+ db.prepare(`UPDATE episodes SET content = ? WHERE id = ?`).run(gist, row.id);
521237
+ compressed.push(row.id);
521238
+ } catch {
521239
+ }
521240
+ }
521241
+ }
521242
+ } catch {
521243
+ }
521244
+ } else {
521245
+ const ids = rows.map((r2) => r2.id);
521246
+ try {
521247
+ const placeholders = ids.map(() => "?").join(",");
521248
+ db.prepare(`DELETE FROM episodes WHERE id IN (${placeholders})`).run(...ids);
521249
+ pruned.push(...ids);
521250
+ } catch {
521251
+ }
521063
521252
  }
521064
- if (pruned.length >= maxPrune)
521253
+ if (pruned.length + compressed.length >= maxPrune)
521065
521254
  break;
521066
521255
  }
521256
+ const hubThreshold = Math.max(1, options2.hubThreshold ?? 50);
521257
+ const flaggedHubs = [];
521258
+ try {
521259
+ const rows = db.prepare(`SELECT node_id, edge_count FROM (
521260
+ SELECT src_id AS node_id, COUNT(*) AS edge_count FROM kg_edges GROUP BY src_id
521261
+ UNION ALL
521262
+ SELECT dst_id AS node_id, COUNT(*) AS edge_count FROM kg_edges GROUP BY dst_id
521263
+ )
521264
+ GROUP BY node_id
521265
+ HAVING SUM(edge_count) >= ?
521266
+ ORDER BY SUM(edge_count) DESC
521267
+ LIMIT 50`).all(hubThreshold);
521268
+ for (const r2 of rows)
521269
+ flaggedHubs.push(r2.node_id);
521270
+ } catch {
521271
+ }
521067
521272
  return {
521068
521273
  cycle: {
521069
521274
  phase: "light",
@@ -521073,7 +521278,10 @@ function lightSleep(db, options2 = {}) {
521073
521278
  downscaledEpisodes: downscaled.map((r2) => r2.id),
521074
521279
  prunedEpisodes: pruned,
521075
521280
  novelAssociations: [],
521076
- energyCost: downscaled.length + pruned.length
521281
+ energyCost: downscaled.length + pruned.length + compressed.length + flaggedHubs.length,
521282
+ compressedEpisodes: compressed,
521283
+ flaggedHubs,
521284
+ integratedNodes: []
521077
521285
  }
521078
521286
  };
521079
521287
  }
@@ -521097,7 +521305,10 @@ function emptyCycle(phase, start2) {
521097
521305
  downscaledEpisodes: [],
521098
521306
  prunedEpisodes: [],
521099
521307
  novelAssociations: [],
521100
- energyCost: 0
521308
+ energyCost: 0,
521309
+ compressedEpisodes: [],
521310
+ flaggedHubs: [],
521311
+ integratedNodes: []
521101
521312
  };
521102
521313
  }
521103
521314
  function episodeCount(db) {
@@ -521126,7 +521337,7 @@ function clamp3(x, lo, hi) {
521126
521337
  return hi;
521127
521338
  return x;
521128
521339
  }
521129
- function clamp013(x) {
521340
+ function clamp014(x) {
521130
521341
  return clamp3(x, 0, 1);
521131
521342
  }
521132
521343
  function clampSigned(x) {
@@ -521134,16 +521345,26 @@ function clampSigned(x) {
521134
521345
  }
521135
521346
  function sanitizeBig5(p2) {
521136
521347
  return {
521137
- openness: clamp013(p2?.openness ?? NEUTRAL_BIG5.openness),
521138
- conscientiousness: clamp013(p2?.conscientiousness ?? NEUTRAL_BIG5.conscientiousness),
521139
- extraversion: clamp013(p2?.extraversion ?? NEUTRAL_BIG5.extraversion),
521140
- agreeableness: clamp013(p2?.agreeableness ?? NEUTRAL_BIG5.agreeableness),
521141
- neuroticism: clamp013(p2?.neuroticism ?? NEUTRAL_BIG5.neuroticism)
521348
+ openness: clamp014(p2?.openness ?? NEUTRAL_BIG5.openness),
521349
+ conscientiousness: clamp014(p2?.conscientiousness ?? NEUTRAL_BIG5.conscientiousness),
521350
+ extraversion: clamp014(p2?.extraversion ?? NEUTRAL_BIG5.extraversion),
521351
+ agreeableness: clamp014(p2?.agreeableness ?? NEUTRAL_BIG5.agreeableness),
521352
+ neuroticism: clamp014(p2?.neuroticism ?? NEUTRAL_BIG5.neuroticism)
521142
521353
  };
521143
521354
  }
521144
521355
  function pairKey(a2, b) {
521145
521356
  return a2 <= b ? { lo: a2, hi: b } : { lo: b, hi: a2 };
521146
521357
  }
521358
+ function rowToOpinion(row) {
521359
+ return {
521360
+ id: row.id,
521361
+ topic: row.topic,
521362
+ agentId: row.agent_id,
521363
+ opinion: row.opinion,
521364
+ confidence: row.confidence,
521365
+ timestamp: row.timestamp
521366
+ };
521367
+ }
521147
521368
  function rowToAgent(row) {
521148
521369
  return {
521149
521370
  id: row.id,
@@ -521226,6 +521447,16 @@ var init_socialMemory = __esm({
521226
521447
  adopted INTEGER NOT NULL DEFAULT 0,
521227
521448
  timestamp INTEGER NOT NULL
521228
521449
  );
521450
+ -- MEM_GAP B6: collective memory — opinions across agents on a topic
521451
+ CREATE TABLE IF NOT EXISTS social_shared_knowledge (
521452
+ id TEXT PRIMARY KEY,
521453
+ topic TEXT NOT NULL,
521454
+ agent_id TEXT NOT NULL,
521455
+ opinion TEXT NOT NULL,
521456
+ confidence REAL NOT NULL,
521457
+ timestamp INTEGER NOT NULL
521458
+ );
521459
+ CREATE INDEX IF NOT EXISTS idx_shared_topic ON social_shared_knowledge(topic);
521229
521460
  CREATE INDEX IF NOT EXISTS idx_lessons_source ON social_lessons(source_agent);
521230
521461
  CREATE INDEX IF NOT EXISTS idx_rels_agent_a ON social_relationships(agent_a);
521231
521462
  CREATE INDEX IF NOT EXISTS idx_rels_agent_b ON social_relationships(agent_b);
@@ -521237,13 +521468,13 @@ var init_socialMemory = __esm({
521237
521468
  const id = input.id ?? randomUUID11();
521238
521469
  const existing = this.getAgent(id);
521239
521470
  const personality = sanitizeBig5({ ...existing?.personality ?? {}, ...input.personality ?? {} });
521240
- const trustOverall = clamp013(input.trust?.overall ?? existing?.trust.overall ?? 0.5);
521471
+ const trustOverall = clamp014(input.trust?.overall ?? existing?.trust.overall ?? 0.5);
521241
521472
  const trustByDomain = {
521242
521473
  ...existing?.trust.byDomain ?? {},
521243
521474
  ...input.trust?.byDomain ?? {}
521244
521475
  };
521245
521476
  for (const k of Object.keys(trustByDomain))
521246
- trustByDomain[k] = clamp013(trustByDomain[k]);
521477
+ trustByDomain[k] = clamp014(trustByDomain[k]);
521247
521478
  const metadata = input.metadata ?? existing?.metadata ?? null;
521248
521479
  if (existing) {
521249
521480
  this.db.prepare(`UPDATE social_agents
@@ -521283,13 +521514,13 @@ var init_socialMemory = __esm({
521283
521514
  const agent = this.getAgent(agentId);
521284
521515
  if (!agent)
521285
521516
  return null;
521286
- const weight = clamp013(interaction.weight ?? 0.1);
521517
+ const weight = clamp014(interaction.weight ?? 0.1);
521287
521518
  const targetOverall = interaction.positive ? 1 : 0;
521288
- const newOverall = clamp013(agent.trust.overall + (targetOverall - agent.trust.overall) * weight);
521519
+ const newOverall = clamp014(agent.trust.overall + (targetOverall - agent.trust.overall) * weight);
521289
521520
  const newByDomain = { ...agent.trust.byDomain };
521290
521521
  if (interaction.domain) {
521291
521522
  const cur = newByDomain[interaction.domain] ?? 0.5;
521292
- newByDomain[interaction.domain] = clamp013(cur + (targetOverall - cur) * weight);
521523
+ newByDomain[interaction.domain] = clamp014(cur + (targetOverall - cur) * weight);
521293
521524
  }
521294
521525
  const now = Date.now();
521295
521526
  this.db.prepare(`UPDATE social_agents
@@ -521319,14 +521550,14 @@ var init_socialMemory = __esm({
521319
521550
  history.push(newEvent);
521320
521551
  if (history.length > 200)
521321
521552
  history.splice(0, history.length - 200);
521322
- const strength = clamp013(existing.strength + Math.abs(dStrength));
521553
+ const strength = clamp014(existing.strength + Math.abs(dStrength));
521323
521554
  const valence = clampSigned(existing.valence + dValence);
521324
- const reciprocity = clamp013(existing.reciprocity * 0.95 + 0.05 * 0.5);
521555
+ const reciprocity = clamp014(existing.reciprocity * 0.95 + 0.05 * 0.5);
521325
521556
  this.db.prepare(`UPDATE social_relationships
521326
521557
  SET strength = ?, valence = ?, reciprocity = ?, last_updated = ?, history = ?
521327
521558
  WHERE agent_a = ? AND agent_b = ?`).run(strength, valence, reciprocity, now, JSON.stringify(history), lo, hi);
521328
521559
  } else {
521329
- const strength = clamp013(Math.abs(dStrength));
521560
+ const strength = clamp014(Math.abs(dStrength));
521330
521561
  const valence = clampSigned(dValence);
521331
521562
  this.db.prepare(`INSERT INTO social_relationships
521332
521563
  (agent_a, agent_b, strength, valence, reciprocity, last_updated, history)
@@ -521349,7 +521580,7 @@ var init_socialMemory = __esm({
521349
521580
  recordLesson(input) {
521350
521581
  const id = randomUUID11();
521351
521582
  const now = Date.now();
521352
- const conf = clamp013(input.confidence ?? 0.5);
521583
+ const conf = clamp014(input.confidence ?? 0.5);
521353
521584
  const adopted = input.adopted ? 1 : 0;
521354
521585
  this.db.prepare(`INSERT INTO social_lessons (id, source_agent, lesson, confidence, adopted, timestamp)
521355
521586
  VALUES (?, ?, ?, ?, ?, ?)`).run(id, input.sourceAgent, input.lesson, conf, adopted, now);
@@ -521363,6 +521594,47 @@ var init_socialMemory = __esm({
521363
521594
  const rows = sourceAgent ? this.db.prepare(`SELECT * FROM social_lessons WHERE source_agent = ? ORDER BY timestamp DESC`).all(sourceAgent) : this.db.prepare(`SELECT * FROM social_lessons ORDER BY timestamp DESC`).all();
521364
521595
  return rows.map(rowToLesson);
521365
521596
  }
521597
+ // ── MEM_GAP B6: collective memory ────────────────────────────────────────
521598
+ recordOpinion(input) {
521599
+ const id = randomUUID11();
521600
+ const now = Date.now();
521601
+ const conf = clamp014(input.confidence ?? 0.5);
521602
+ this.db.prepare(`INSERT INTO social_shared_knowledge (id, topic, agent_id, opinion, confidence, timestamp)
521603
+ VALUES (?, ?, ?, ?, ?, ?)`).run(id, input.topic, input.agentId, input.opinion, conf, now);
521604
+ return { id, topic: input.topic, agentId: input.agentId, opinion: input.opinion, confidence: conf, timestamp: now };
521605
+ }
521606
+ /**
521607
+ * Compute consensus on a topic. Returns:
521608
+ * - contributors: count of distinct agents
521609
+ * - agreementScore: 1 = unanimous, 0 = perfectly split. Scored by the
521610
+ * largest opinion-cluster's share (Jaccard-style on normalized text).
521611
+ * - divergence: 1 - agreementScore.
521612
+ */
521613
+ getConsensus(topic) {
521614
+ const rows = this.db.prepare(`SELECT * FROM social_shared_knowledge WHERE topic = ? ORDER BY timestamp DESC`).all(topic);
521615
+ const opinions = rows.map(rowToOpinion);
521616
+ if (opinions.length === 0) {
521617
+ return { contributors: 0, agreementScore: 1, divergence: 0, opinions };
521618
+ }
521619
+ const agents = new Set(opinions.map((o2) => o2.agentId));
521620
+ const buckets = /* @__PURE__ */ new Map();
521621
+ for (const o2 of opinions) {
521622
+ const norm = o2.opinion.toLowerCase().replace(/\s+/g, " ").trim();
521623
+ buckets.set(norm, (buckets.get(norm) ?? 0) + 1);
521624
+ }
521625
+ const top = Math.max(...buckets.values());
521626
+ const agreementScore = top / opinions.length;
521627
+ return {
521628
+ contributors: agents.size,
521629
+ agreementScore,
521630
+ divergence: 1 - agreementScore,
521631
+ opinions
521632
+ };
521633
+ }
521634
+ listOpinions(topic) {
521635
+ const rows = topic ? this.db.prepare(`SELECT * FROM social_shared_knowledge WHERE topic = ? ORDER BY timestamp DESC`).all(topic) : this.db.prepare(`SELECT * FROM social_shared_knowledge ORDER BY timestamp DESC`).all();
521636
+ return rows.map(rowToOpinion);
521637
+ }
521366
521638
  };
521367
521639
  }
521368
521640
  });
@@ -521461,6 +521733,64 @@ var init_memoryStageContext = __esm({
521461
521733
  }
521462
521734
  });
521463
521735
 
521736
+ // packages/memory/dist/socialInfluence.js
521737
+ function clamp4(x, lo, hi) {
521738
+ if (!Number.isFinite(x))
521739
+ return (lo + hi) / 2;
521740
+ if (x < lo)
521741
+ return lo;
521742
+ if (x > hi)
521743
+ return hi;
521744
+ return x;
521745
+ }
521746
+ function clamp015(x) {
521747
+ return clamp4(x, 0, 1);
521748
+ }
521749
+ function conformityBias(myConfidence, groupAgreement, memoryAlignsWithGroup, weight = 0.5) {
521750
+ const conf = clamp015(myConfidence);
521751
+ const agree = clamp015(groupAgreement);
521752
+ const w = clamp015(weight);
521753
+ const pull = (agree - 0.5) * 2 * conf * w;
521754
+ return memoryAlignsWithGroup ? 1 + pull : 1 - pull;
521755
+ }
521756
+ function authorityBias(sourceTrust, weight = 0.4) {
521757
+ const t2 = clamp015(sourceTrust);
521758
+ const w = clamp015(weight);
521759
+ return 1 + (t2 - 0.5) * 2 * w;
521760
+ }
521761
+ function noveltyBias(memoryDivergence, weight = 0.3) {
521762
+ const d2 = clamp015(memoryDivergence);
521763
+ const w = clamp015(weight);
521764
+ return 1 + d2 * w;
521765
+ }
521766
+ function reciprocityBias(relationshipStrength, relationshipValence, weight = 0.3) {
521767
+ const s2 = clamp015(relationshipStrength);
521768
+ const v = clamp4(relationshipValence, -1, 1);
521769
+ const w = clamp015(weight);
521770
+ return 1 + s2 * v * w;
521771
+ }
521772
+ function applyInfluence(baseScore, ctx3) {
521773
+ let m2 = 1;
521774
+ if (ctx3.myConfidence != null && ctx3.groupAgreement != null && ctx3.memoryAlignsWithGroup != null) {
521775
+ m2 *= conformityBias(ctx3.myConfidence, ctx3.groupAgreement, ctx3.memoryAlignsWithGroup, ctx3.weights?.conformity);
521776
+ }
521777
+ if (ctx3.sourceTrust != null) {
521778
+ m2 *= authorityBias(ctx3.sourceTrust, ctx3.weights?.authority);
521779
+ }
521780
+ if (ctx3.memoryDivergence != null) {
521781
+ m2 *= noveltyBias(ctx3.memoryDivergence, ctx3.weights?.novelty);
521782
+ }
521783
+ if (ctx3.relationshipStrength != null && ctx3.relationshipValence != null) {
521784
+ m2 *= reciprocityBias(ctx3.relationshipStrength, ctx3.relationshipValence, ctx3.weights?.reciprocity);
521785
+ }
521786
+ return baseScore * m2;
521787
+ }
521788
+ var init_socialInfluence = __esm({
521789
+ "packages/memory/dist/socialInfluence.js"() {
521790
+ "use strict";
521791
+ }
521792
+ });
521793
+
521464
521794
  // packages/memory/dist/index.js
521465
521795
  var dist_exports2 = {};
521466
521796
  __export(dist_exports2, {
@@ -521496,7 +521826,9 @@ __export(dist_exports2, {
521496
521826
  TemporalGraph: () => TemporalGraph,
521497
521827
  ToolPatternStore: () => ToolPatternStore,
521498
521828
  ValidationStore: () => ValidationStore,
521829
+ applyInfluence: () => applyInfluence,
521499
521830
  attachTrace: () => attachTrace,
521831
+ authorityBias: () => authorityBias,
521500
521832
  autoDecayClass: () => autoDecayClass,
521501
521833
  autoImportance: () => autoImportance,
521502
521834
  batchLink: () => batchLink,
@@ -521506,6 +521838,7 @@ __export(dist_exports2, {
521506
521838
  closeDb: () => closeDb,
521507
521839
  compressAndStore: () => compressAndStore,
521508
521840
  compressToGist: () => compressToGist,
521841
+ conformityBias: () => conformityBias,
521509
521842
  congruenceMultiplier: () => congruenceMultiplier,
521510
521843
  cosineSimilarity: () => cosineSimilarity2,
521511
521844
  createCRLMemoryStore: () => createCRLMemoryStore,
@@ -521529,8 +521862,10 @@ __export(dist_exports2, {
521529
521862
  linkEpisode: () => linkEpisode,
521530
521863
  modulateImportance: () => modulateImportance,
521531
521864
  modulateRetrievalScore: () => modulateRetrievalScore,
521865
+ noveltyBias: () => noveltyBias,
521532
521866
  observeEmotionalState: () => observeEmotionalState,
521533
521867
  personalizedPageRank: () => personalizedPageRank,
521868
+ reciprocityBias: () => reciprocityBias,
521534
521869
  remDream: () => remDream,
521535
521870
  resetCRLConfigStore: () => resetCRLConfigStore,
521536
521871
  retrieveByPPR: () => retrieveByPPR,
@@ -521544,6 +521879,7 @@ __export(dist_exports2, {
521544
521879
  splanifoldRmse: () => rmse,
521545
521880
  splanifoldSerialize: () => serialize,
521546
521881
  suggestRegulation: () => suggestRegulation,
521882
+ suggestRegulationActions: () => suggestRegulationActions,
521547
521883
  thresholdsForStage: () => thresholdsForStage,
521548
521884
  tokenSimilarity: () => tokenSimilarity,
521549
521885
  wasHesitant: () => wasHesitant
@@ -521577,6 +521913,7 @@ var init_dist7 = __esm({
521577
521913
  init_socialMemory();
521578
521914
  init_developmentalStage();
521579
521915
  init_memoryStageContext();
521916
+ init_socialInfluence();
521580
521917
  }
521581
521918
  });
521582
521919
 
@@ -523505,13 +523842,7 @@ function checkMutateMtimeDelta(intent, cwd4, ctx3, _result) {
523505
523842
  bestNewest = auxNewest;
523506
523843
  }
523507
523844
  if (bestNewest <= 0) {
523508
- return {
523509
- trustworthy: false,
523510
- syntheticError: `Command (${intent.verb}) reported success but ${cwd4} contains no files. The action either didn't run or had no effect.`,
523511
- intentBucket: bucket,
523512
- outcomeClass: "broken",
523513
- detail: "no files under cwd after mutate intent"
523514
- };
523845
+ return { trustworthy: true, intentBucket: bucket, outcomeClass: "unknown", detail: "empty cwd — verifier abstaining" };
523515
523846
  }
523516
523847
  if (bestNewest < ctx3.startedAt - MTIME_GRACE_MS) {
523517
523848
  const ageSec = Math.round(((ctx3.now ? ctx3.now() : Date.now()) - bestNewest) / 1e3);
@@ -523918,6 +524249,248 @@ var init_postActionVerifier = __esm({
523918
524249
  }
523919
524250
  });
523920
524251
 
524252
+ // packages/orchestrator/dist/errorClusterTracker.js
524253
+ var errorClusterTracker_exports = {};
524254
+ __export(errorClusterTracker_exports, {
524255
+ ErrorClusterTracker: () => ErrorClusterTracker,
524256
+ parseErrors: () => parseErrors
524257
+ });
524258
+ function parseErrors(output) {
524259
+ if (!output || typeof output !== "string")
524260
+ return [];
524261
+ const seen = /* @__PURE__ */ new Set();
524262
+ const out = [];
524263
+ for (const { re, build } of ERROR_PATTERNS) {
524264
+ re.lastIndex = 0;
524265
+ let m2;
524266
+ while ((m2 = re.exec(output)) !== null) {
524267
+ const err = build(m2);
524268
+ if (!err)
524269
+ continue;
524270
+ const key = `${err.file}|${err.line ?? ""}|${err.col ?? ""}|${err.code}|${err.message.slice(0, 32)}`;
524271
+ if (seen.has(key))
524272
+ continue;
524273
+ seen.add(key);
524274
+ out.push(err);
524275
+ }
524276
+ }
524277
+ return out;
524278
+ }
524279
+ function clusterKey(scope, file, code8) {
524280
+ return `${scope}\0${file}\0${code8}`;
524281
+ }
524282
+ function parseClusterKey(key) {
524283
+ const parts = key.split("\0");
524284
+ return { file: parts[1] ?? "", code: parts[2] ?? "" };
524285
+ }
524286
+ function shortFile(p2) {
524287
+ const parts = p2.split("/");
524288
+ return parts.length <= 2 ? p2 : `…/${parts.slice(-2).join("/")}`;
524289
+ }
524290
+ function formatStagnantLine(c9, critical) {
524291
+ const codeLabel = c9.key.code ? `× ${c9.key.code}` : "× errors";
524292
+ const tag = critical ? "STAGNANT-CRIT" : "STAGNANT";
524293
+ return `${tag}: ${shortFile(c9.key.file)} ${c9.count}${codeLabel} unchanged across ${c9.attemptsSinceCountChange} attempts — per-line edits aren't converging; consider reverting the affected region or rewriting it as a unit`;
524294
+ }
524295
+ var ERROR_PATTERNS, DEFAULTS, ErrorClusterTracker;
524296
+ var init_errorClusterTracker = __esm({
524297
+ "packages/orchestrator/dist/errorClusterTracker.js"() {
524298
+ "use strict";
524299
+ ERROR_PATTERNS = [
524300
+ // Style A: file:line:col: severity[: code]: message
524301
+ // Matches gcc, clang, eslint, golangci-lint, ruby, generic POSIX tools.
524302
+ {
524303
+ re: /^([^\s:()]+):(\d+):(\d+):\s*(error|warning|note)(?::\s*([A-Za-z][\w/-]*))?\s*:?\s*(.*)$/gm,
524304
+ build: (m2) => {
524305
+ const file = m2[1];
524306
+ if (/^https?:\/\//.test(file))
524307
+ return null;
524308
+ return {
524309
+ file,
524310
+ line: parseInt(m2[2], 10),
524311
+ col: parseInt(m2[3], 10),
524312
+ severity: m2[4],
524313
+ code: (m2[5] ?? "").trim(),
524314
+ message: (m2[6] ?? "").trim().slice(0, 240)
524315
+ };
524316
+ }
524317
+ },
524318
+ // Style B: file(line,col): severity CODE: message (TypeScript)
524319
+ {
524320
+ re: /^([^\s(]+):?\s*\((\d+),(\d+)\)\s*:?\s*(error|warning|note)\s+([A-Z]+\d+)\s*:\s*(.*)$/gm,
524321
+ build: (m2) => ({
524322
+ file: m2[1],
524323
+ line: parseInt(m2[2], 10),
524324
+ col: parseInt(m2[3], 10),
524325
+ severity: m2[4],
524326
+ code: m2[5],
524327
+ message: (m2[6] ?? "").trim().slice(0, 240)
524328
+ })
524329
+ },
524330
+ // Style C: error[CODE]: message ... --> file:line:col (Rust-style)
524331
+ {
524332
+ re: /^error(?:\[([A-Z]\d+)\])?:\s*(.+?)\n\s*-->\s*([^\s:]+):(\d+):(\d+)/gms,
524333
+ build: (m2) => ({
524334
+ file: m2[3],
524335
+ line: parseInt(m2[4], 10),
524336
+ col: parseInt(m2[5], 10),
524337
+ severity: "error",
524338
+ code: (m2[1] ?? "").trim(),
524339
+ message: (m2[2] ?? "").trim().slice(0, 240)
524340
+ })
524341
+ },
524342
+ // Style D: FAILED file::test_id [- message] (pytest, similar)
524343
+ {
524344
+ re: /^FAILED\s+([^\s:]+)::([\w\-.[\]/]+)(?:\s+-\s+(.*))?$/gm,
524345
+ build: (m2) => ({
524346
+ file: m2[1],
524347
+ severity: "error",
524348
+ // Treat the test id as the cluster code so a flapping test stays in
524349
+ // its own bucket, while many distinct tests in the same file each
524350
+ // form their own cluster (more accurate than collapsing all
524351
+ // pytest failures in a file into one).
524352
+ code: m2[2],
524353
+ message: (m2[3] ?? "").trim().slice(0, 240)
524354
+ })
524355
+ }
524356
+ ];
524357
+ DEFAULTS = {
524358
+ warnAttempts: 3,
524359
+ criticalAttempts: 5,
524360
+ cooldownAttempts: 2,
524361
+ maxClusters: 200
524362
+ };
524363
+ ErrorClusterTracker = class {
524364
+ opts;
524365
+ now;
524366
+ clusters = /* @__PURE__ */ new Map();
524367
+ lastEmittedAt = /* @__PURE__ */ new Map();
524368
+ // key → observations counter at last emit
524369
+ observationCounter = 0;
524370
+ constructor(options2 = {}) {
524371
+ this.opts = { ...DEFAULTS, ...options2 };
524372
+ this.now = options2.now ?? Date.now;
524373
+ }
524374
+ /**
524375
+ * Feed a new tool output into the tracker. Returns the changes for this
524376
+ * observation plus a one-line summary suitable for context injection.
524377
+ *
524378
+ * @param output raw stdout/stderr from the tool
524379
+ * @param toolKey optional caller-supplied scope (e.g. "tsc:/path/to/cwd").
524380
+ * If two distinct tools emit similar errors in the same
524381
+ * file but in different scopes, pass distinct keys to
524382
+ * keep their clusters separate. Default: "" (shared).
524383
+ */
524384
+ observe(output, toolKey = "") {
524385
+ this.observationCounter++;
524386
+ const errors = parseErrors(output);
524387
+ const observedClusters = /* @__PURE__ */ new Map();
524388
+ for (const e2 of errors) {
524389
+ const key = clusterKey(toolKey, e2.file, e2.code);
524390
+ const cur = observedClusters.get(key);
524391
+ if (cur)
524392
+ cur.count += 1;
524393
+ else
524394
+ observedClusters.set(key, { count: 1, sample: e2.message });
524395
+ }
524396
+ const changes = [];
524397
+ const lines = [];
524398
+ let hasCritical = false;
524399
+ const nowMs = this.now();
524400
+ for (const [key, { count, sample }] of observedClusters) {
524401
+ const prior = this.clusters.get(key);
524402
+ if (!prior) {
524403
+ const ck = parseClusterKey(key);
524404
+ const entry = {
524405
+ key: ck,
524406
+ count,
524407
+ sample,
524408
+ observations: 1,
524409
+ attemptsSinceCountChange: 1,
524410
+ lastUpdated: nowMs,
524411
+ previousCount: 0
524412
+ };
524413
+ this.clusters.set(key, entry);
524414
+ changes.push({ kind: "new", cluster: entry });
524415
+ continue;
524416
+ }
524417
+ prior.observations++;
524418
+ prior.lastUpdated = nowMs;
524419
+ prior.sample = sample;
524420
+ if (count === prior.count) {
524421
+ prior.attemptsSinceCountChange++;
524422
+ } else {
524423
+ prior.previousCount = prior.count;
524424
+ prior.count = count;
524425
+ prior.attemptsSinceCountChange = 1;
524426
+ }
524427
+ if (count > prior.previousCount && prior.attemptsSinceCountChange === 1) {
524428
+ changes.push({ kind: "grown", cluster: prior, from: prior.previousCount, to: count });
524429
+ lines.push(`${shortFile(prior.key.file)}: ${prior.previousCount}→${count}× ${prior.key.code || "errors"} (regressed)`);
524430
+ } else if (count < prior.previousCount && prior.attemptsSinceCountChange === 1) {
524431
+ changes.push({ kind: "shrunk", cluster: prior, from: prior.previousCount, to: count });
524432
+ lines.push(`${shortFile(prior.key.file)}: ${prior.previousCount}→${count}× ${prior.key.code || "errors"} (improving)`);
524433
+ } else if (prior.attemptsSinceCountChange >= this.opts.warnAttempts) {
524434
+ if (this.lastEmittedAt.has(key)) {
524435
+ const last2 = this.lastEmittedAt.get(key);
524436
+ const sinceEmit = this.observationCounter - last2;
524437
+ if (sinceEmit < this.opts.cooldownAttempts)
524438
+ continue;
524439
+ }
524440
+ const isCritical = prior.attemptsSinceCountChange >= this.opts.criticalAttempts;
524441
+ if (isCritical)
524442
+ hasCritical = true;
524443
+ changes.push({
524444
+ kind: "stagnant",
524445
+ cluster: prior,
524446
+ attempts: prior.attemptsSinceCountChange,
524447
+ severity: isCritical ? "critical" : "warn"
524448
+ });
524449
+ lines.push(formatStagnantLine(prior, isCritical));
524450
+ this.lastEmittedAt.set(key, this.observationCounter);
524451
+ }
524452
+ }
524453
+ for (const [key, prior] of [...this.clusters]) {
524454
+ if (observedClusters.has(key))
524455
+ continue;
524456
+ if (prior.count > 0 && nowMs - prior.lastUpdated < 6e4) {
524457
+ changes.push({ kind: "resolved", key: prior.key });
524458
+ lines.push(`${shortFile(prior.key.file)}: ${prior.count}× ${prior.key.code || "errors"} → 0 (resolved)`);
524459
+ this.clusters.delete(key);
524460
+ this.lastEmittedAt.delete(key);
524461
+ }
524462
+ }
524463
+ this.evictIfNeeded();
524464
+ return {
524465
+ changes,
524466
+ summaryLine: lines.length === 0 ? "" : `[ERROR CLUSTERS] ${lines.join(" | ").slice(0, 360)}`,
524467
+ hasCritical
524468
+ };
524469
+ }
524470
+ /** Read-only snapshot of currently tracked clusters (defensive copy). */
524471
+ snapshot() {
524472
+ return [...this.clusters.values()].map((c9) => ({ ...c9, key: { ...c9.key } }));
524473
+ }
524474
+ /** Remove all state — useful at session boundaries. */
524475
+ reset() {
524476
+ this.clusters.clear();
524477
+ this.lastEmittedAt.clear();
524478
+ this.observationCounter = 0;
524479
+ }
524480
+ evictIfNeeded() {
524481
+ if (this.clusters.size <= this.opts.maxClusters)
524482
+ return;
524483
+ const sorted = [...this.clusters.entries()].sort((a2, b) => a2[1].lastUpdated - b[1].lastUpdated);
524484
+ const toEvict = sorted.slice(0, this.clusters.size - this.opts.maxClusters);
524485
+ for (const [key] of toEvict) {
524486
+ this.clusters.delete(key);
524487
+ this.lastEmittedAt.delete(key);
524488
+ }
524489
+ }
524490
+ };
524491
+ }
524492
+ });
524493
+
523921
524494
  // packages/orchestrator/dist/agenticRunner.js
523922
524495
  import { existsSync as _fsExistsSync, readFileSync as _fsReadFileSync } from "node:fs";
523923
524496
  import { join as _pathJoin } from "node:path";
@@ -526578,6 +527151,32 @@ Respond with your assessment, then take action.`;
526578
527151
  } catch {
526579
527152
  }
526580
527153
  }
527154
+ if (process.env["OA_DISABLE_STAGE_CONTEXT"] !== "1") {
527155
+ try {
527156
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
527157
+ if (!this._stageContext) {
527158
+ this._stageContext = new memMod.MemoryStageContext();
527159
+ }
527160
+ const stageCtx = this._stageContext;
527161
+ const totalEpisodes = this._episodeStore ? this._episodeStore.count() : 0;
527162
+ const sessionCount = typeof this._historicalSessionCount === "number" ? this._historicalSessionCount : 0;
527163
+ const recentPredictionError = this._predictionStore ? this._predictionStore.averageError(50) : 1;
527164
+ const snap = stageCtx.refresh({
527165
+ sessionCount,
527166
+ domainCount: 0,
527167
+ recentPredictionError,
527168
+ crossDomainLinks: 0,
527169
+ totalEpisodes,
527170
+ creativeAssociationCount: 0
527171
+ });
527172
+ this.emit({
527173
+ type: "status",
527174
+ content: `Memory stage: ${snap.stage} (importanceFloor=${snap.thresholds.importanceFloor}, linkThreshold=${snap.thresholds.linkThreshold})`,
527175
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
527176
+ });
527177
+ } catch {
527178
+ }
527179
+ }
526581
527180
  const contextComposition = await this.assembleContext(task, context2);
526582
527181
  const systemPrompt = contextComposition.assembled;
526583
527182
  this._contextTree = new ContextTree(`sys-${systemPrompt.length}`, cleanedTask.slice(0, 200));
@@ -528166,6 +528765,15 @@ ${memoryLines.join("\n")}`
528166
528765
  if (!this._predictionStore) {
528167
528766
  this._predictionStore = new memMod.PredictionStore({ capacity: 256 });
528168
528767
  this._toolDurationAvg = /* @__PURE__ */ new Map();
528768
+ try {
528769
+ if (this._episodeStore && process.env["OA_DISABLE_PREDICTION_PERSISTENCE"] !== "1") {
528770
+ this._predictionStore.restore(this._episodeStore.getDb());
528771
+ }
528772
+ } catch {
528773
+ }
528774
+ }
528775
+ if (!this._homeostat) {
528776
+ this._homeostat = memMod.createHomeostaticState();
528169
528777
  }
528170
528778
  const ps = this._predictionStore;
528171
528779
  const avgs = this._toolDurationAvg;
@@ -528604,6 +529212,25 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
528604
529212
  toolCallLog[_toolLogTailIdx].intentBucket = _verifierResult.intentBucket;
528605
529213
  toolCallLog[_toolLogTailIdx].outcomeClass = _verifierResult.outcomeClass;
528606
529214
  }
529215
+ if (tc.name === "shell" && (result.output || result.error)) {
529216
+ try {
529217
+ const ecMod = await Promise.resolve().then(() => (init_errorClusterTracker(), errorClusterTracker_exports));
529218
+ if (!this._errorClusterTracker) {
529219
+ this._errorClusterTracker = new ecMod.ErrorClusterTracker();
529220
+ }
529221
+ const tracker = this._errorClusterTracker;
529222
+ const scope = _verifierResult?.intentBucket ?? "shell";
529223
+ const obs = tracker.observe(((result.output ?? "") + "\n" + (result.error ?? "")).slice(0, 1e5), scope);
529224
+ if (obs.summaryLine) {
529225
+ if (obs.hasCritical) {
529226
+ messages2.push({ role: "system", content: obs.summaryLine });
529227
+ } else {
529228
+ pushSoftInjection("system", obs.summaryLine);
529229
+ }
529230
+ }
529231
+ } catch {
529232
+ }
529233
+ }
528607
529234
  this._hookManager.runPostToolUse(tc.name, finalArgs, (result.output ?? "").slice(0, 2e3), this._sessionId);
528608
529235
  } catch (err) {
528609
529236
  result = { success: false, output: "", error: err instanceof Error ? err.message : String(err) };
@@ -528769,9 +529396,63 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
528769
529396
  importance: Math.min(10, 7 + Math.round(err.errorMagnitude * 3)),
528770
529397
  metadata: { predictionError: { magnitude: err.errorMagnitude, axis: err.dominantAxis } }
528771
529398
  });
529399
+ if (process.env["OA_DISABLE_SOCIAL_MEMORY"] !== "1") {
529400
+ if (!this._socialMemory) {
529401
+ this._socialMemory = new memMod.SocialMemoryStore(this._episodeStore.getDb());
529402
+ }
529403
+ const social = this._socialMemory;
529404
+ social.recordLesson({
529405
+ sourceAgent: "self",
529406
+ lesson: `${err.prediction.action} produced ${err.dominantAxis}-axis prediction error (magnitude ${err.errorMagnitude.toFixed(2)}). Predicted ${err.prediction.predictedSuccess ? "success" : "failure"}; observed ${err.actualSuccess ? "success" : "failure"}.`,
529407
+ confidence: Math.min(0.95, 0.5 + err.errorMagnitude * 0.5)
529408
+ });
529409
+ }
528772
529410
  } catch {
528773
529411
  }
528774
529412
  }
529413
+ if (process.env["OA_DISABLE_SOCIAL_MEMORY"] !== "1") {
529414
+ const SUB_AGENT_TOOLS = /* @__PURE__ */ new Set(["sub_agent", "background_run", "priority_delegate", "skill_execute"]);
529415
+ if (SUB_AGENT_TOOLS.has(tc.name)) {
529416
+ try {
529417
+ if (!this._socialMemory) {
529418
+ this._socialMemory = new memMod.SocialMemoryStore(this._episodeStore.getDb());
529419
+ }
529420
+ const social = this._socialMemory;
529421
+ const otherId = `${tc.name}:${String(tc.arguments?.["agent_id"] ?? tc.arguments?.["name"] ?? tc.arguments?.["target"] ?? "anonymous").slice(0, 60)}`;
529422
+ social.upsertAgent({ id: otherId, name: otherId, type: "agent" });
529423
+ social.recordRelationshipEvent("self", otherId, {
529424
+ event: groundTruthSuccess ? "successful collaboration" : "failed collaboration",
529425
+ impactOnStrength: 0.05,
529426
+ impactOnValence: groundTruthSuccess ? 0.1 : -0.1
529427
+ });
529428
+ } catch {
529429
+ }
529430
+ }
529431
+ }
529432
+ if (this._homeostat) {
529433
+ const ctxUsed = typeof this._lastContextTokens === "number" ? this._lastContextTokens : 0;
529434
+ const ctxMax = typeof this._contextWindowMax === "number" ? this._contextWindowMax : 0;
529435
+ const cogLoad = ctxMax > 0 ? Math.max(0, Math.min(1, ctxUsed / ctxMax)) : 0;
529436
+ let valence = 0;
529437
+ const verifierDowngrade = v && v.trustworthy === false;
529438
+ if (verifierDowngrade)
529439
+ valence -= 0.6;
529440
+ else if (groundTruthSuccess)
529441
+ valence += 0.3;
529442
+ else
529443
+ valence -= 0.3;
529444
+ if (err && err.errorMagnitude > 0.5)
529445
+ valence -= 0.4;
529446
+ if (valence < -1)
529447
+ valence = -1;
529448
+ if (valence > 1)
529449
+ valence = 1;
529450
+ const recentFailures = ps ? ps.axisProfile(8).success : 0;
529451
+ let arousal = Math.max(0, Math.min(1, cogLoad * 0.7 + recentFailures * 0.4));
529452
+ if (arousal < 0.05)
529453
+ arousal = 0.05;
529454
+ this._homeostat = memMod.observeEmotionalState(this._homeostat, { valence, arousal });
529455
+ }
528775
529456
  }
528776
529457
  } catch {
528777
529458
  }
@@ -530410,6 +531091,89 @@ Full content available via: repl_exec(code="data = retrieve('${handleId}')") or
530410
531091
  if (pruned > 0) {
530411
531092
  this.emit({ type: "status", content: `Pruned ${pruned} expired session episodes`, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
530412
531093
  }
531094
+ if (process.env["OA_DISABLE_SELF_MODEL"] !== "1") {
531095
+ try {
531096
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
531097
+ const tracker = this._confidenceTracker;
531098
+ const ps = this._predictionStore;
531099
+ if (!this._selfModel) {
531100
+ const db = this._episodeStore.getDb();
531101
+ this._selfModel = new memMod.SelfModel(db, tracker, {
531102
+ predictionStore: ps,
531103
+ // MEM_GAP B7: real metrics from observable corpus state.
531104
+ metricsBuilder: (stats, prediction) => {
531105
+ let creativeAssociationCount = 0;
531106
+ try {
531107
+ const r2 = db.prepare(`SELECT COUNT(*) AS c FROM episodes WHERE tool_name IN ('rem_association', 'sleep_integration')`).get();
531108
+ creativeAssociationCount = r2?.c ?? 0;
531109
+ } catch {
531110
+ }
531111
+ let crossDomainLinks = 0;
531112
+ try {
531113
+ const r2 = db.prepare(`SELECT COUNT(DISTINCT
531114
+ substr(src.text, 1, instr(src.text, ':') - 1) || '|' ||
531115
+ substr(dst.text, 1, instr(dst.text, ':') - 1)
531116
+ ) AS c
531117
+ FROM kg_edges e
531118
+ JOIN kg_nodes src ON src.id = e.src_id
531119
+ JOIN kg_nodes dst ON dst.id = e.dst_id
531120
+ WHERE instr(src.text, ':') > 0
531121
+ AND instr(dst.text, ':') > 0
531122
+ AND substr(src.text, 1, instr(src.text, ':') - 1) <>
531123
+ substr(dst.text, 1, instr(dst.text, ':') - 1)`).get();
531124
+ crossDomainLinks = r2?.c ?? 0;
531125
+ } catch {
531126
+ }
531127
+ let domainCount = 0;
531128
+ try {
531129
+ const r2 = db.prepare(`SELECT COUNT(DISTINCT substr(text, 1, instr(text, ':') - 1)) AS c
531130
+ FROM kg_nodes WHERE instr(text, ':') > 0`).get();
531131
+ domainCount = r2?.c ?? 0;
531132
+ } catch {
531133
+ }
531134
+ return {
531135
+ sessionCount: typeof this._historicalSessionCount === "number" ? this._historicalSessionCount : 0,
531136
+ domainCount,
531137
+ recentPredictionError: prediction?.averageError ?? 1,
531138
+ crossDomainLinks,
531139
+ totalEpisodes: stats.totalEpisodes,
531140
+ creativeAssociationCount
531141
+ };
531142
+ }
531143
+ });
531144
+ }
531145
+ const sm = this._selfModel;
531146
+ const report2 = sm.snapshot();
531147
+ this._episodeStore.insert({
531148
+ sessionId: this._sessionId,
531149
+ modality: "reflection",
531150
+ toolName: "self_model_snapshot",
531151
+ content: `Self-report: stage=${report2.developmental?.stage ?? "?"} totalEpisodes=${report2.stats.totalEpisodes} avgImp=${(report2.stats.averageImportance ?? 0).toFixed(2)} calGap=${report2.calibration.calibrationGap.toFixed(2)} (n=${report2.calibration.sampleCount}) approachingDecay=${report2.approachingDecay.session.length}/${report2.approachingDecay.daily.length}/${report2.approachingDecay.procedural.length}`,
531152
+ importance: 7,
531153
+ decayClass: "procedural",
531154
+ metadata: { selfReport: report2 }
531155
+ });
531156
+ for (const [domain, c9] of Object.entries(report2.calibration.byDomain)) {
531157
+ if (c9.n >= 5 && c9.confidence - c9.accuracy > 0.2) {
531158
+ this.emit({
531159
+ type: "status",
531160
+ content: `[SELF-MODEL CALIBRATION] overconfident in domain '${domain}': stated avg ${c9.confidence.toFixed(2)} vs actual ${c9.accuracy.toFixed(2)} across ${c9.n} samples — temper next-action confidence in this domain.`,
531161
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
531162
+ });
531163
+ }
531164
+ }
531165
+ } catch {
531166
+ }
531167
+ }
531168
+ if (process.env["OA_DISABLE_PREDICTION_PERSISTENCE"] !== "1") {
531169
+ try {
531170
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
531171
+ const ps = this._predictionStore;
531172
+ if (ps)
531173
+ ps.snapshot(this._episodeStore.getDb());
531174
+ } catch {
531175
+ }
531176
+ }
530413
531177
  if (process.env["OA_DISABLE_SOCIAL_MEMORY"] !== "1") {
530414
531178
  try {
530415
531179
  const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
@@ -530438,10 +531202,25 @@ Full content available via: repl_exec(code="data = retrieve('${handleId}')") or
530438
531202
  if (process.env["OA_DISABLE_SLEEP_CONSOLIDATION"] !== "1") {
530439
531203
  try {
530440
531204
  const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
531205
+ const stageCtx = this._stageContext;
531206
+ const lightTune = stageCtx ? stageCtx.toLightSleepTunables() : {};
530441
531207
  const cycle = memMod.runConsolidationCycle(this._episodeStore.getDb(), {
530442
- light: { prunableClasses: ["session"] }
530443
- // never auto-prune daily/permanent
531208
+ slowWave: this._temporalGraph ? { graph: this._temporalGraph } : {},
531209
+ rem: this._temporalGraph ? { graph: this._temporalGraph } : {},
531210
+ light: { prunableClasses: ["session"], ...lightTune }
530444
531211
  });
531212
+ if (stageCtx) {
531213
+ const totalEpisodes = this._episodeStore.count();
531214
+ const recentPredictionError = this._predictionStore ? this._predictionStore.averageError(50) : 1;
531215
+ stageCtx.refresh({
531216
+ sessionCount: typeof this._historicalSessionCount === "number" ? this._historicalSessionCount : 0,
531217
+ domainCount: 0,
531218
+ recentPredictionError,
531219
+ crossDomainLinks: 0,
531220
+ totalEpisodes,
531221
+ creativeAssociationCount: cycle.rem.novelAssociations.length
531222
+ });
531223
+ }
530445
531224
  if (this._temporalGraph && cycle.rem.novelAssociations.length > 0) {
530446
531225
  try {
530447
531226
  for (const link of cycle.rem.novelAssociations) {
@@ -577373,7 +578152,7 @@ function appraiseEvent(event) {
577373
578152
  return null;
577374
578153
  }
577375
578154
  }
577376
- function clamp4(value2, min, max) {
578155
+ function clamp5(value2, min, max) {
577377
578156
  return Math.max(min, Math.min(max, value2));
577378
578157
  }
577379
578158
  var BASELINE_VALENCE, BASELINE_AROUSAL, DECAY_HALF_LIFE_MS, LABEL_UPDATE_INTERVAL_MS, EXCITEMENT_THRESHOLD, DISTRESS_THRESHOLD, OUTREACH_COOLDOWN_MS, OUTREACH_MIN_STREAK, LABEL_REGEN_THRESHOLD, EmotionEngine;
@@ -577511,8 +578290,8 @@ var init_emotion_engine = __esm({
577511
578290
  if (this.consecutiveFailures >= 2) {
577512
578291
  momentum = 1 + (this.consecutiveFailures - 1) * 0.25;
577513
578292
  }
577514
- this.state.valence = clamp4(this.state.valence + delta.valence * momentum, -1, 1);
577515
- this.state.arousal = clamp4(this.state.arousal + delta.arousal * momentum, 0, 1);
578293
+ this.state.valence = clamp5(this.state.valence + delta.valence * momentum, -1, 1);
578294
+ this.state.arousal = clamp5(this.state.arousal + delta.arousal * momentum, 0, 1);
577516
578295
  this.state.updatedAt = Date.now();
577517
578296
  const deterministicLabel = labelFromCoordinates(this.state.valence, this.state.arousal);
577518
578297
  this.state.label = deterministicLabel.label;
@@ -580343,7 +581122,7 @@ __export(voicechat_exports, {
580343
581122
  VoiceChatSession: () => VoiceChatSession
580344
581123
  });
580345
581124
  import { EventEmitter as EventEmitter11 } from "node:events";
580346
- function clamp014(x) {
581125
+ function clamp016(x) {
580347
581126
  return x < 0 ? 0 : x > 1 ? 1 : x;
580348
581127
  }
580349
581128
  function alnumRatio(s2) {
@@ -580382,9 +581161,9 @@ function computeSignalFromText(text, confidence) {
580382
581161
  else score = 0.15;
580383
581162
  score -= repeatingCharPenalty(t2) * 0.4;
580384
581163
  if (typeof confidence === "number" && !Number.isNaN(confidence)) {
580385
- score = 0.7 * score + 0.3 * clamp014(confidence);
581164
+ score = 0.7 * score + 0.3 * clamp016(confidence);
580386
581165
  }
580387
- return clamp014(score);
581166
+ return clamp016(score);
580388
581167
  }
580389
581168
  function truncateForLog(s2, n2) {
580390
581169
  return s2.length <= n2 ? s2 : s2.slice(0, n2 - 1) + "…";
@@ -580654,7 +581433,7 @@ Rules:
580654
581433
  }, MAX_SEGMENT_MS);
580655
581434
  }
580656
581435
  this.captureBuffer = text;
580657
- this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp014(snr) : computeSignalFromText(text, confidence);
581436
+ this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp016(snr) : computeSignalFromText(text, confidence);
580658
581437
  this.emit("snr", { score: this.lastSignalScore });
580659
581438
  this.onPartialTranscript(text);
580660
581439
  if (this.silenceTimer) clearTimeout(this.silenceTimer);
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "open-agents-ai",
3
- "version": "0.187.508",
3
+ "version": "0.187.510",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "open-agents-ai",
9
- "version": "0.187.508",
9
+ "version": "0.187.510",
10
10
  "hasInstallScript": true,
11
11
  "license": "CC-BY-NC-4.0",
12
12
  "dependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "open-agents-ai",
3
- "version": "0.187.508",
3
+ "version": "0.187.510",
4
4
  "description": "AI coding agent powered by open-source models (Ollama/vLLM) — interactive TUI with agentic tool-calling loop",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",