open-agents-ai 0.187.509 → 0.187.511
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 +858 -148
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
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
|
|
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"() {
|
|
@@ -516761,6 +516798,148 @@ var init_homeostaticRegulation = __esm({
|
|
|
516761
516798
|
}
|
|
516762
516799
|
});
|
|
516763
516800
|
|
|
516801
|
+
// packages/memory/dist/socialInfluence.js
|
|
516802
|
+
function clamp2(x, lo, hi) {
|
|
516803
|
+
if (!Number.isFinite(x))
|
|
516804
|
+
return (lo + hi) / 2;
|
|
516805
|
+
if (x < lo)
|
|
516806
|
+
return lo;
|
|
516807
|
+
if (x > hi)
|
|
516808
|
+
return hi;
|
|
516809
|
+
return x;
|
|
516810
|
+
}
|
|
516811
|
+
function clamp012(x) {
|
|
516812
|
+
return clamp2(x, 0, 1);
|
|
516813
|
+
}
|
|
516814
|
+
function conformityBias(myConfidence, groupAgreement, memoryAlignsWithGroup, weight = 0.5) {
|
|
516815
|
+
const conf = clamp012(myConfidence);
|
|
516816
|
+
const agree = clamp012(groupAgreement);
|
|
516817
|
+
const w = clamp012(weight);
|
|
516818
|
+
const pull = (agree - 0.5) * 2 * conf * w;
|
|
516819
|
+
return memoryAlignsWithGroup ? 1 + pull : 1 - pull;
|
|
516820
|
+
}
|
|
516821
|
+
function authorityBias(sourceTrust, weight = 0.4) {
|
|
516822
|
+
const t2 = clamp012(sourceTrust);
|
|
516823
|
+
const w = clamp012(weight);
|
|
516824
|
+
return 1 + (t2 - 0.5) * 2 * w;
|
|
516825
|
+
}
|
|
516826
|
+
function noveltyBias(memoryDivergence, weight = 0.3) {
|
|
516827
|
+
const d2 = clamp012(memoryDivergence);
|
|
516828
|
+
const w = clamp012(weight);
|
|
516829
|
+
return 1 + d2 * w;
|
|
516830
|
+
}
|
|
516831
|
+
function reciprocityBias(relationshipStrength, relationshipValence, weight = 0.3) {
|
|
516832
|
+
const s2 = clamp012(relationshipStrength);
|
|
516833
|
+
const v = clamp2(relationshipValence, -1, 1);
|
|
516834
|
+
const w = clamp012(weight);
|
|
516835
|
+
return 1 + s2 * v * w;
|
|
516836
|
+
}
|
|
516837
|
+
function applyInfluence(baseScore, ctx3) {
|
|
516838
|
+
let m2 = 1;
|
|
516839
|
+
if (ctx3.myConfidence != null && ctx3.groupAgreement != null && ctx3.memoryAlignsWithGroup != null) {
|
|
516840
|
+
m2 *= conformityBias(ctx3.myConfidence, ctx3.groupAgreement, ctx3.memoryAlignsWithGroup, ctx3.weights?.conformity);
|
|
516841
|
+
}
|
|
516842
|
+
if (ctx3.sourceTrust != null) {
|
|
516843
|
+
m2 *= authorityBias(ctx3.sourceTrust, ctx3.weights?.authority);
|
|
516844
|
+
}
|
|
516845
|
+
if (ctx3.memoryDivergence != null) {
|
|
516846
|
+
m2 *= noveltyBias(ctx3.memoryDivergence, ctx3.weights?.novelty);
|
|
516847
|
+
}
|
|
516848
|
+
if (ctx3.relationshipStrength != null && ctx3.relationshipValence != null) {
|
|
516849
|
+
m2 *= reciprocityBias(ctx3.relationshipStrength, ctx3.relationshipValence, ctx3.weights?.reciprocity);
|
|
516850
|
+
}
|
|
516851
|
+
return baseScore * m2;
|
|
516852
|
+
}
|
|
516853
|
+
var init_socialInfluence = __esm({
|
|
516854
|
+
"packages/memory/dist/socialInfluence.js"() {
|
|
516855
|
+
"use strict";
|
|
516856
|
+
}
|
|
516857
|
+
});
|
|
516858
|
+
|
|
516859
|
+
// packages/memory/dist/embodiedTrace.js
|
|
516860
|
+
function clamp3(x, lo, hi) {
|
|
516861
|
+
if (!Number.isFinite(x))
|
|
516862
|
+
return (lo + hi) / 2;
|
|
516863
|
+
if (x < lo)
|
|
516864
|
+
return lo;
|
|
516865
|
+
if (x > hi)
|
|
516866
|
+
return hi;
|
|
516867
|
+
return x;
|
|
516868
|
+
}
|
|
516869
|
+
function clamp013(x) {
|
|
516870
|
+
return clamp3(x, 0, 1);
|
|
516871
|
+
}
|
|
516872
|
+
function nonNegative(x) {
|
|
516873
|
+
if (!Number.isFinite(x) || x < 0)
|
|
516874
|
+
return 0;
|
|
516875
|
+
return x;
|
|
516876
|
+
}
|
|
516877
|
+
function buildTrace(input) {
|
|
516878
|
+
const i2 = input ?? {};
|
|
516879
|
+
const used = nonNegative(i2.contextTokensUsed ?? DEFAULT_TRACE.contextTokensUsed);
|
|
516880
|
+
const max = nonNegative(i2.contextTokensMax ?? DEFAULT_TRACE.contextTokensMax);
|
|
516881
|
+
const derivedLoad = max > 0 ? used / max : 0;
|
|
516882
|
+
const load2 = i2.cognitiveLoad != null ? clamp013(i2.cognitiveLoad) : clamp013(derivedLoad);
|
|
516883
|
+
return {
|
|
516884
|
+
durationMs: nonNegative(i2.durationMs ?? DEFAULT_TRACE.durationMs),
|
|
516885
|
+
hesitationCount: Math.max(0, Math.floor(i2.hesitationCount ?? 0)),
|
|
516886
|
+
retryCount: Math.max(0, Math.floor(i2.retryCount ?? 0)),
|
|
516887
|
+
intensity: clamp013(i2.intensity ?? DEFAULT_TRACE.intensity),
|
|
516888
|
+
visualGist: typeof i2.visualGist === "string" ? i2.visualGist : void 0,
|
|
516889
|
+
auditoryGist: typeof i2.auditoryGist === "string" ? i2.auditoryGist : void 0,
|
|
516890
|
+
screenState: typeof i2.screenState === "string" ? i2.screenState : void 0,
|
|
516891
|
+
confidence: clamp013(i2.confidence ?? DEFAULT_TRACE.confidence),
|
|
516892
|
+
cognitiveLoad: load2,
|
|
516893
|
+
contextTokensUsed: used,
|
|
516894
|
+
contextTokensMax: max,
|
|
516895
|
+
affect: sanitizeEmotionalState(i2.affect ?? NEUTRAL_AFFECT),
|
|
516896
|
+
timeOfDay: clamp3(Math.floor(i2.timeOfDay ?? DEFAULT_TRACE.timeOfDay), 0, 23),
|
|
516897
|
+
sessionDurationMin: nonNegative(i2.sessionDurationMin ?? 0),
|
|
516898
|
+
consecutiveActions: Math.max(0, Math.floor(i2.consecutiveActions ?? 0))
|
|
516899
|
+
};
|
|
516900
|
+
}
|
|
516901
|
+
function attachTrace(metadata, trace) {
|
|
516902
|
+
return { ...metadata ?? {}, [EMBODIED_KEY]: trace };
|
|
516903
|
+
}
|
|
516904
|
+
function extractTrace(metadata) {
|
|
516905
|
+
if (!metadata || typeof metadata !== "object")
|
|
516906
|
+
return null;
|
|
516907
|
+
const raw = metadata[EMBODIED_KEY];
|
|
516908
|
+
if (!raw || typeof raw !== "object")
|
|
516909
|
+
return null;
|
|
516910
|
+
return buildTrace(raw);
|
|
516911
|
+
}
|
|
516912
|
+
function engagementScore(trace) {
|
|
516913
|
+
const alertness = 1 - trace.cognitiveLoad;
|
|
516914
|
+
return clamp013((trace.intensity + alertness + trace.confidence) / 3);
|
|
516915
|
+
}
|
|
516916
|
+
function wasHesitant(trace, threshold = 0.4) {
|
|
516917
|
+
return trace.hesitationCount >= 2 || trace.retryCount >= 1 || trace.confidence < threshold;
|
|
516918
|
+
}
|
|
516919
|
+
var NEUTRAL_AFFECT, DEFAULT_TRACE, EMBODIED_KEY;
|
|
516920
|
+
var init_embodiedTrace = __esm({
|
|
516921
|
+
"packages/memory/dist/embodiedTrace.js"() {
|
|
516922
|
+
"use strict";
|
|
516923
|
+
init_homeostaticRegulation();
|
|
516924
|
+
NEUTRAL_AFFECT = { valence: 0, arousal: 0 };
|
|
516925
|
+
DEFAULT_TRACE = {
|
|
516926
|
+
durationMs: 0,
|
|
516927
|
+
hesitationCount: 0,
|
|
516928
|
+
retryCount: 0,
|
|
516929
|
+
intensity: 0,
|
|
516930
|
+
confidence: 0.5,
|
|
516931
|
+
cognitiveLoad: 0,
|
|
516932
|
+
contextTokensUsed: 0,
|
|
516933
|
+
contextTokensMax: 0,
|
|
516934
|
+
affect: NEUTRAL_AFFECT,
|
|
516935
|
+
timeOfDay: 0,
|
|
516936
|
+
sessionDurationMin: 0,
|
|
516937
|
+
consecutiveActions: 0
|
|
516938
|
+
};
|
|
516939
|
+
EMBODIED_KEY = "embodiedTrace";
|
|
516940
|
+
}
|
|
516941
|
+
});
|
|
516942
|
+
|
|
516764
516943
|
// packages/memory/dist/pprRetrieval.js
|
|
516765
516944
|
function readEpisodeAffect(metadata) {
|
|
516766
516945
|
if (!metadata || typeof metadata !== "object")
|
|
@@ -516957,14 +517136,30 @@ function retrieveByPPR(query, graph, episodeStore, config) {
|
|
|
516957
517136
|
}
|
|
516958
517137
|
}
|
|
516959
517138
|
let entries = [...episodeScores.entries()];
|
|
516960
|
-
|
|
517139
|
+
const engagementWeight = cfg.engagementWeight ?? 0;
|
|
517140
|
+
if (cfg.currentEmotionalState || cfg.influenceFor || engagementWeight !== 0) {
|
|
516961
517141
|
const current = cfg.currentEmotionalState;
|
|
516962
517142
|
entries = entries.map(([epId, payload]) => {
|
|
516963
517143
|
const ep = episodeStore.get(epId);
|
|
516964
|
-
|
|
516965
|
-
if (
|
|
516966
|
-
|
|
516967
|
-
|
|
517144
|
+
let score = payload.score;
|
|
517145
|
+
if (current) {
|
|
517146
|
+
const memoryAffect = ep ? readEpisodeAffect(ep.metadata) : null;
|
|
517147
|
+
if (memoryAffect)
|
|
517148
|
+
score = modulateRetrievalScore(score, current, memoryAffect);
|
|
517149
|
+
}
|
|
517150
|
+
if (cfg.influenceFor) {
|
|
517151
|
+
const ctx3 = cfg.influenceFor(epId);
|
|
517152
|
+
if (ctx3)
|
|
517153
|
+
score = applyInfluence(score, ctx3);
|
|
517154
|
+
}
|
|
517155
|
+
if (engagementWeight !== 0 && ep) {
|
|
517156
|
+
const trace = extractTrace(ep.metadata);
|
|
517157
|
+
if (trace) {
|
|
517158
|
+
const eng = engagementScore(trace);
|
|
517159
|
+
score = score * (1 + (eng - 0.5) * engagementWeight);
|
|
517160
|
+
}
|
|
517161
|
+
}
|
|
517162
|
+
return [epId, { ...payload, score }];
|
|
516968
517163
|
});
|
|
516969
517164
|
}
|
|
516970
517165
|
const ranked = entries.sort((a2, b) => b[1].score - a2[1].score).slice(0, cfg.topK);
|
|
@@ -516988,6 +517183,8 @@ var init_pprRetrieval = __esm({
|
|
|
516988
517183
|
"use strict";
|
|
516989
517184
|
init_zettelkasten();
|
|
516990
517185
|
init_homeostaticRegulation();
|
|
517186
|
+
init_socialInfluence();
|
|
517187
|
+
init_embodiedTrace();
|
|
516991
517188
|
DEFAULT_CONFIG4 = {
|
|
516992
517189
|
damping: 0.5,
|
|
516993
517190
|
maxIterations: 50,
|
|
@@ -517013,6 +517210,28 @@ function readEpisodeAffect2(metadata) {
|
|
|
517013
517210
|
return null;
|
|
517014
517211
|
return sanitizeEmotionalState(affect);
|
|
517015
517212
|
}
|
|
517213
|
+
function readEpisodeEngagement(metadata) {
|
|
517214
|
+
if (!metadata || typeof metadata !== "object")
|
|
517215
|
+
return null;
|
|
517216
|
+
const trace = metadata["embodiedTrace"];
|
|
517217
|
+
if (!trace || typeof trace !== "object")
|
|
517218
|
+
return null;
|
|
517219
|
+
const t2 = trace;
|
|
517220
|
+
const intensity = typeof t2["intensity"] === "number" ? clamp01Local(t2["intensity"]) : 0;
|
|
517221
|
+
const cogLoad = typeof t2["cognitiveLoad"] === "number" ? clamp01Local(t2["cognitiveLoad"]) : 0;
|
|
517222
|
+
const conf = typeof t2["confidence"] === "number" ? clamp01Local(t2["confidence"]) : 0.5;
|
|
517223
|
+
const alertness = 1 - cogLoad;
|
|
517224
|
+
return clamp01Local((intensity + alertness + conf) / 3);
|
|
517225
|
+
}
|
|
517226
|
+
function clamp01Local(x) {
|
|
517227
|
+
if (!Number.isFinite(x))
|
|
517228
|
+
return 0;
|
|
517229
|
+
if (x < 0)
|
|
517230
|
+
return 0;
|
|
517231
|
+
if (x > 1)
|
|
517232
|
+
return 1;
|
|
517233
|
+
return x;
|
|
517234
|
+
}
|
|
517016
517235
|
function sanitizeImportance(raw, fallback = 5) {
|
|
517017
517236
|
if (typeof raw !== "number" || !Number.isFinite(raw))
|
|
517018
517237
|
return fallback;
|
|
@@ -517081,6 +517300,7 @@ var init_episodeStore = __esm({
|
|
|
517081
517300
|
init_db();
|
|
517082
517301
|
init_zettelkasten();
|
|
517083
517302
|
init_homeostaticRegulation();
|
|
517303
|
+
init_socialInfluence();
|
|
517084
517304
|
init_pprRetrieval();
|
|
517085
517305
|
DECAY_TAU = {
|
|
517086
517306
|
session: 36e5,
|
|
@@ -517102,6 +517322,22 @@ var init_episodeStore = __esm({
|
|
|
517102
517322
|
graph = null;
|
|
517103
517323
|
/** WO-AM-05: Zettelkasten config for neighbor linking */
|
|
517104
517324
|
zettelConfig = { topK: 5, minSimilarity: 0.7, evolutionThreshold: 0.6, maxLinksPerEpisode: 10 };
|
|
517325
|
+
/** AUDIT-3 (A2 completion): minimum importance an inserted episode must
|
|
517326
|
+
* meet (or beat) to actually persist. When 0 (default), all episodes
|
|
517327
|
+
* pass the gate — preserves backward-compatible behavior. The
|
|
517328
|
+
* orchestrator sets this from `MemoryStageContext.importanceFloor()`
|
|
517329
|
+
* so wisdom-stage agents store fewer routine episodes than
|
|
517330
|
+
* exploration-stage agents. */
|
|
517331
|
+
importanceFloor = 0;
|
|
517332
|
+
/** AUDIT-3: opt-in setter so the orchestrator can override the
|
|
517333
|
+
* hardcoded zettelConfig at session start (and after sleep
|
|
517334
|
+
* consolidation) with stage-derived values. */
|
|
517335
|
+
setZettelConfig(partial) {
|
|
517336
|
+
this.zettelConfig = { ...this.zettelConfig, ...partial };
|
|
517337
|
+
}
|
|
517338
|
+
setImportanceFloor(floor) {
|
|
517339
|
+
this.importanceFloor = Number.isFinite(floor) && floor > 0 ? floor : 0;
|
|
517340
|
+
}
|
|
517105
517341
|
constructor(dbPath, graph, zettelConfig) {
|
|
517106
517342
|
const dir = dbPath === ":memory:" ? null : join75(dbPath, "..");
|
|
517107
517343
|
if (dir && !existsSync59(dir))
|
|
@@ -517153,6 +517389,9 @@ var init_episodeStore = __esm({
|
|
|
517153
517389
|
const rawImportance = ep.importance ?? autoImportance(ep.toolName ?? null, modality, ep.content);
|
|
517154
517390
|
const modulated = ep.emotionalState ? modulateImportance(sanitizeImportance(rawImportance), ep.emotionalState) : sanitizeImportance(rawImportance);
|
|
517155
517391
|
const importance = sanitizeImportance(modulated);
|
|
517392
|
+
if (this.importanceFloor > 0 && importance < this.importanceFloor) {
|
|
517393
|
+
return "";
|
|
517394
|
+
}
|
|
517156
517395
|
const decayClass = ep.decayClass ?? autoDecayClass(ep.toolName ?? null, modality, ep.content);
|
|
517157
517396
|
const existing = this.db.prepare("SELECT id FROM episodes WHERE content_hash = ? AND session_id = ? LIMIT 1").get(contentHash, ep.sessionId ?? null);
|
|
517158
517397
|
if (existing)
|
|
@@ -517277,7 +517516,18 @@ var init_episodeStore = __esm({
|
|
|
517277
517516
|
if (opts.currentEmotionalState) {
|
|
517278
517517
|
const memoryAffect = readEpisodeAffect2(ep.metadata);
|
|
517279
517518
|
if (memoryAffect) {
|
|
517280
|
-
score = modulateRetrievalScore(
|
|
517519
|
+
score = modulateRetrievalScore(score, opts.currentEmotionalState, memoryAffect);
|
|
517520
|
+
}
|
|
517521
|
+
}
|
|
517522
|
+
if (opts.influenceFor) {
|
|
517523
|
+
const ctx3 = opts.influenceFor(ep);
|
|
517524
|
+
if (ctx3)
|
|
517525
|
+
score = applyInfluence(score, ctx3);
|
|
517526
|
+
}
|
|
517527
|
+
if ((opts.engagementWeight ?? 0) !== 0) {
|
|
517528
|
+
const eng = readEpisodeEngagement(ep.metadata);
|
|
517529
|
+
if (eng != null) {
|
|
517530
|
+
score = score * (1 + (eng - 0.5) * (opts.engagementWeight ?? 0));
|
|
517281
517531
|
}
|
|
517282
517532
|
}
|
|
517283
517533
|
return { episode: ep, score };
|
|
@@ -520490,7 +520740,10 @@ var init_selfModel = __esm({
|
|
|
520490
520740
|
stats,
|
|
520491
520741
|
calibration: this.tracker.compute(),
|
|
520492
520742
|
approachingDecay: this.approachingDecay(),
|
|
520493
|
-
blindSpots: this.blindSpots()
|
|
520743
|
+
blindSpots: this.blindSpots(),
|
|
520744
|
+
// MEM_GAP B1: metaKnowledge always present (the agent introspecting
|
|
520745
|
+
// about its knowledge patterns is core, not optional).
|
|
520746
|
+
metaKnowledge: this.metaKnowledge()
|
|
520494
520747
|
};
|
|
520495
520748
|
if (this.opts.predictionStore) {
|
|
520496
520749
|
const ps = this.opts.predictionStore;
|
|
@@ -520507,6 +520760,21 @@ var init_selfModel = __esm({
|
|
|
520507
520760
|
}
|
|
520508
520761
|
return report2;
|
|
520509
520762
|
}
|
|
520763
|
+
/** MEM_GAP B1: compute metaKnowledge from base stores. */
|
|
520764
|
+
metaKnowledge(opts = {}) {
|
|
520765
|
+
const k = opts.topK ?? 10;
|
|
520766
|
+
return {
|
|
520767
|
+
mostRetrievedTopics: this.queryEpisodeTopics(`SELECT id, content, COALESCE(strength, 1) AS score FROM episodes ORDER BY score DESC LIMIT ?`, k),
|
|
520768
|
+
leastRetrievedTopics: this.queryEpisodeTopics(`SELECT id, content, COALESCE(strength, 1) AS score
|
|
520769
|
+
FROM episodes
|
|
520770
|
+
WHERE importance >= ?
|
|
520771
|
+
ORDER BY score ASC LIMIT ?`, k, [4]),
|
|
520772
|
+
mostValuableMemories: this.queryEpisodeTopics(`SELECT id, content, (importance * COALESCE(strength, 1)) AS score
|
|
520773
|
+
FROM episodes ORDER BY score DESC LIMIT ?`, k),
|
|
520774
|
+
mostUsefulProceduralMemories: this.queryProceduralTopics(k),
|
|
520775
|
+
learningTrajectory: this.computeLearningTrajectory()
|
|
520776
|
+
};
|
|
520777
|
+
}
|
|
520510
520778
|
// ── private helpers ────────────────────────────────────────────────────────
|
|
520511
520779
|
scalarCount(sql) {
|
|
520512
520780
|
try {
|
|
@@ -520578,12 +520846,76 @@ var init_selfModel = __esm({
|
|
|
520578
520846
|
return [];
|
|
520579
520847
|
}
|
|
520580
520848
|
}
|
|
520849
|
+
/** B1 helper: run a query expected to return rows of {id, content, score}
|
|
520850
|
+
* and convert to MetaKnowledgeTopic[]. Tolerates missing tables. */
|
|
520851
|
+
queryEpisodeTopics(sql, k, prefixArgs = []) {
|
|
520852
|
+
try {
|
|
520853
|
+
const rows = this.db.prepare(sql).all(...prefixArgs, k);
|
|
520854
|
+
return rows.map((r2) => ({
|
|
520855
|
+
id: r2.id,
|
|
520856
|
+
label: (r2.content ?? "").slice(0, 80),
|
|
520857
|
+
score: typeof r2.score === "number" ? r2.score : 0
|
|
520858
|
+
}));
|
|
520859
|
+
} catch {
|
|
520860
|
+
return [];
|
|
520861
|
+
}
|
|
520862
|
+
}
|
|
520863
|
+
/** B1 helper: top-K procedural memories by utility × confidence,
|
|
520864
|
+
* filtered to active (non-soft-deleted) rows. */
|
|
520865
|
+
queryProceduralTopics(k) {
|
|
520866
|
+
try {
|
|
520867
|
+
const rows = this.db.prepare(`SELECT id, content, (COALESCE(utility, 0.5) * COALESCE(confidence, 0.5)) AS score
|
|
520868
|
+
FROM procedural_memory
|
|
520869
|
+
WHERE deleted_at IS NULL
|
|
520870
|
+
ORDER BY score DESC
|
|
520871
|
+
LIMIT ?`).all(k);
|
|
520872
|
+
return rows.map((r2) => ({
|
|
520873
|
+
id: r2.id,
|
|
520874
|
+
label: (r2.content ?? "").slice(0, 80),
|
|
520875
|
+
score: typeof r2.score === "number" ? r2.score : 0
|
|
520876
|
+
}));
|
|
520877
|
+
} catch {
|
|
520878
|
+
return [];
|
|
520879
|
+
}
|
|
520880
|
+
}
|
|
520881
|
+
/** B1 helper: compute time-bucketed counts of episodes added vs forgotten.
|
|
520882
|
+
* Bucket width: 1 day. Last 7 buckets, oldest first. Forgotten ≈ count
|
|
520883
|
+
* of soft-deleted procedural rows with updated_at in the bucket window
|
|
520884
|
+
* (the closest persistent "removed memory" signal we have). */
|
|
520885
|
+
computeLearningTrajectory() {
|
|
520886
|
+
const buckets = [];
|
|
520887
|
+
const dayMs = 24 * 60 * 60 * 1e3;
|
|
520888
|
+
const now = Date.now();
|
|
520889
|
+
for (let i2 = 6; i2 >= 0; i2--) {
|
|
520890
|
+
const start2 = now - (i2 + 1) * dayMs;
|
|
520891
|
+
const end = now - i2 * dayMs;
|
|
520892
|
+
let added = 0;
|
|
520893
|
+
let forgotten = 0;
|
|
520894
|
+
try {
|
|
520895
|
+
const r2 = this.db.prepare(`SELECT COUNT(*) AS c FROM episodes WHERE timestamp >= ? AND timestamp < ?`).get(start2, end);
|
|
520896
|
+
added = r2?.c ?? 0;
|
|
520897
|
+
} catch {
|
|
520898
|
+
}
|
|
520899
|
+
try {
|
|
520900
|
+
const startIso = new Date(start2).toISOString();
|
|
520901
|
+
const endIso = new Date(end).toISOString();
|
|
520902
|
+
const r2 = this.db.prepare(`SELECT COUNT(*) AS c FROM procedural_memory
|
|
520903
|
+
WHERE deleted_at IS NOT NULL
|
|
520904
|
+
AND updated_at >= ?
|
|
520905
|
+
AND updated_at < ?`).get(startIso, endIso);
|
|
520906
|
+
forgotten = r2?.c ?? 0;
|
|
520907
|
+
} catch {
|
|
520908
|
+
}
|
|
520909
|
+
buckets.push({ bucketStart: start2, bucketWidthMs: dayMs, added, forgotten });
|
|
520910
|
+
}
|
|
520911
|
+
return buckets;
|
|
520912
|
+
}
|
|
520581
520913
|
};
|
|
520582
520914
|
}
|
|
520583
520915
|
});
|
|
520584
520916
|
|
|
520585
520917
|
// packages/memory/dist/predictionStore.js
|
|
520586
|
-
function
|
|
520918
|
+
function clamp014(x) {
|
|
520587
520919
|
if (!Number.isFinite(x))
|
|
520588
520920
|
return 0.5;
|
|
520589
520921
|
if (x < 0)
|
|
@@ -520614,7 +520946,7 @@ function durationError(predicted, actual) {
|
|
|
520614
520946
|
return 0;
|
|
520615
520947
|
const safePred = Math.max(predicted, 50);
|
|
520616
520948
|
const ratio = Math.abs(predicted - actual) / safePred;
|
|
520617
|
-
return
|
|
520949
|
+
return clamp014(ratio);
|
|
520618
520950
|
}
|
|
520619
520951
|
var DEFAULT_AXIS_WEIGHTS, PredictionStore;
|
|
520620
520952
|
var init_predictionStore = __esm({
|
|
@@ -520640,7 +520972,7 @@ var init_predictionStore = __esm({
|
|
|
520640
520972
|
predict(p2) {
|
|
520641
520973
|
const sanitized = {
|
|
520642
520974
|
...p2,
|
|
520643
|
-
predictedConfidence:
|
|
520975
|
+
predictedConfidence: clamp014(p2.predictedConfidence),
|
|
520644
520976
|
predictedDuration: p2.predictedDuration != null && Number.isFinite(p2.predictedDuration) ? Math.max(0, p2.predictedDuration) : null
|
|
520645
520977
|
};
|
|
520646
520978
|
this.pending.set(p2.correlationId, sanitized);
|
|
@@ -520654,14 +520986,14 @@ var init_predictionStore = __esm({
|
|
|
520654
520986
|
this.pending.delete(correlationId);
|
|
520655
520987
|
const actualDuration = observed.actualDuration != null && Number.isFinite(observed.actualDuration) ? Math.max(0, observed.actualDuration) : null;
|
|
520656
520988
|
const sim = tokenSimilarity(pred.predictedOutcome, observed.actualOutcome);
|
|
520657
|
-
const outcomeErr =
|
|
520989
|
+
const outcomeErr = clamp014(1 - sim);
|
|
520658
520990
|
const successErr = pred.predictedSuccess === observed.actualSuccess ? 0 : 1;
|
|
520659
|
-
const confidenceErr =
|
|
520991
|
+
const confidenceErr = clamp014(observed.actualSuccess ? 1 - pred.predictedConfidence : pred.predictedConfidence);
|
|
520660
520992
|
const durationErr = durationError(pred.predictedDuration, actualDuration);
|
|
520661
520993
|
const w = this.axisWeights;
|
|
520662
520994
|
const total = w.outcome * outcomeErr + w.success * successErr + w.confidence * confidenceErr + w.duration * durationErr;
|
|
520663
520995
|
const sumWeights = w.outcome + w.success + w.confidence + w.duration;
|
|
520664
|
-
const errorMagnitude =
|
|
520996
|
+
const errorMagnitude = clamp014(sumWeights > 0 ? total / sumWeights : 0);
|
|
520665
520997
|
const errorByAxis = {
|
|
520666
520998
|
outcome: outcomeErr,
|
|
520667
520999
|
success: successErr,
|
|
@@ -520679,7 +521011,7 @@ var init_predictionStore = __esm({
|
|
|
520679
521011
|
errorByAxis,
|
|
520680
521012
|
dominantAxis,
|
|
520681
521013
|
// Learning signal: large errors with high confidence drive bigger updates
|
|
520682
|
-
learningSignal:
|
|
521014
|
+
learningSignal: clamp014(errorMagnitude * (0.5 + 0.5 * pred.predictedConfidence))
|
|
520683
521015
|
};
|
|
520684
521016
|
this.history.push(err);
|
|
520685
521017
|
if (this.history.length > this.capacity) {
|
|
@@ -520826,7 +521158,7 @@ var init_predictionStore = __esm({
|
|
|
520826
521158
|
errorMagnitude: r2.error_magnitude ?? 0,
|
|
520827
521159
|
errorByAxis: axes,
|
|
520828
521160
|
dominantAxis: r2.dominant_axis ?? "outcome",
|
|
520829
|
-
learningSignal:
|
|
521161
|
+
learningSignal: clamp014((r2.error_magnitude ?? 0) * 0.75)
|
|
520830
521162
|
});
|
|
520831
521163
|
}
|
|
520832
521164
|
}
|
|
@@ -520834,90 +521166,6 @@ var init_predictionStore = __esm({
|
|
|
520834
521166
|
}
|
|
520835
521167
|
});
|
|
520836
521168
|
|
|
520837
|
-
// packages/memory/dist/embodiedTrace.js
|
|
520838
|
-
function clamp2(x, lo, hi) {
|
|
520839
|
-
if (!Number.isFinite(x))
|
|
520840
|
-
return (lo + hi) / 2;
|
|
520841
|
-
if (x < lo)
|
|
520842
|
-
return lo;
|
|
520843
|
-
if (x > hi)
|
|
520844
|
-
return hi;
|
|
520845
|
-
return x;
|
|
520846
|
-
}
|
|
520847
|
-
function clamp012(x) {
|
|
520848
|
-
return clamp2(x, 0, 1);
|
|
520849
|
-
}
|
|
520850
|
-
function nonNegative(x) {
|
|
520851
|
-
if (!Number.isFinite(x) || x < 0)
|
|
520852
|
-
return 0;
|
|
520853
|
-
return x;
|
|
520854
|
-
}
|
|
520855
|
-
function buildTrace(input) {
|
|
520856
|
-
const i2 = input ?? {};
|
|
520857
|
-
const used = nonNegative(i2.contextTokensUsed ?? DEFAULT_TRACE.contextTokensUsed);
|
|
520858
|
-
const max = nonNegative(i2.contextTokensMax ?? DEFAULT_TRACE.contextTokensMax);
|
|
520859
|
-
const derivedLoad = max > 0 ? used / max : 0;
|
|
520860
|
-
const load2 = i2.cognitiveLoad != null ? clamp012(i2.cognitiveLoad) : clamp012(derivedLoad);
|
|
520861
|
-
return {
|
|
520862
|
-
durationMs: nonNegative(i2.durationMs ?? DEFAULT_TRACE.durationMs),
|
|
520863
|
-
hesitationCount: Math.max(0, Math.floor(i2.hesitationCount ?? 0)),
|
|
520864
|
-
retryCount: Math.max(0, Math.floor(i2.retryCount ?? 0)),
|
|
520865
|
-
intensity: clamp012(i2.intensity ?? DEFAULT_TRACE.intensity),
|
|
520866
|
-
visualGist: typeof i2.visualGist === "string" ? i2.visualGist : void 0,
|
|
520867
|
-
auditoryGist: typeof i2.auditoryGist === "string" ? i2.auditoryGist : void 0,
|
|
520868
|
-
screenState: typeof i2.screenState === "string" ? i2.screenState : void 0,
|
|
520869
|
-
confidence: clamp012(i2.confidence ?? DEFAULT_TRACE.confidence),
|
|
520870
|
-
cognitiveLoad: load2,
|
|
520871
|
-
contextTokensUsed: used,
|
|
520872
|
-
contextTokensMax: max,
|
|
520873
|
-
affect: sanitizeEmotionalState(i2.affect ?? NEUTRAL_AFFECT),
|
|
520874
|
-
timeOfDay: clamp2(Math.floor(i2.timeOfDay ?? DEFAULT_TRACE.timeOfDay), 0, 23),
|
|
520875
|
-
sessionDurationMin: nonNegative(i2.sessionDurationMin ?? 0),
|
|
520876
|
-
consecutiveActions: Math.max(0, Math.floor(i2.consecutiveActions ?? 0))
|
|
520877
|
-
};
|
|
520878
|
-
}
|
|
520879
|
-
function attachTrace(metadata, trace) {
|
|
520880
|
-
return { ...metadata ?? {}, [EMBODIED_KEY]: trace };
|
|
520881
|
-
}
|
|
520882
|
-
function extractTrace(metadata) {
|
|
520883
|
-
if (!metadata || typeof metadata !== "object")
|
|
520884
|
-
return null;
|
|
520885
|
-
const raw = metadata[EMBODIED_KEY];
|
|
520886
|
-
if (!raw || typeof raw !== "object")
|
|
520887
|
-
return null;
|
|
520888
|
-
return buildTrace(raw);
|
|
520889
|
-
}
|
|
520890
|
-
function engagementScore(trace) {
|
|
520891
|
-
const alertness = 1 - trace.cognitiveLoad;
|
|
520892
|
-
return clamp012((trace.intensity + alertness + trace.confidence) / 3);
|
|
520893
|
-
}
|
|
520894
|
-
function wasHesitant(trace, threshold = 0.4) {
|
|
520895
|
-
return trace.hesitationCount >= 2 || trace.retryCount >= 1 || trace.confidence < threshold;
|
|
520896
|
-
}
|
|
520897
|
-
var NEUTRAL_AFFECT, DEFAULT_TRACE, EMBODIED_KEY;
|
|
520898
|
-
var init_embodiedTrace = __esm({
|
|
520899
|
-
"packages/memory/dist/embodiedTrace.js"() {
|
|
520900
|
-
"use strict";
|
|
520901
|
-
init_homeostaticRegulation();
|
|
520902
|
-
NEUTRAL_AFFECT = { valence: 0, arousal: 0 };
|
|
520903
|
-
DEFAULT_TRACE = {
|
|
520904
|
-
durationMs: 0,
|
|
520905
|
-
hesitationCount: 0,
|
|
520906
|
-
retryCount: 0,
|
|
520907
|
-
intensity: 0,
|
|
520908
|
-
confidence: 0.5,
|
|
520909
|
-
cognitiveLoad: 0,
|
|
520910
|
-
contextTokensUsed: 0,
|
|
520911
|
-
contextTokensMax: 0,
|
|
520912
|
-
affect: NEUTRAL_AFFECT,
|
|
520913
|
-
timeOfDay: 0,
|
|
520914
|
-
sessionDurationMin: 0,
|
|
520915
|
-
consecutiveActions: 0
|
|
520916
|
-
};
|
|
520917
|
-
EMBODIED_KEY = "embodiedTrace";
|
|
520918
|
-
}
|
|
520919
|
-
});
|
|
520920
|
-
|
|
520921
521169
|
// packages/memory/dist/sleepConsolidation.js
|
|
520922
521170
|
function slowWaveReplay(db, options2 = {}) {
|
|
520923
521171
|
const topK = options2.topK ?? 20;
|
|
@@ -520951,6 +521199,21 @@ function slowWaveReplay(db, options2 = {}) {
|
|
|
520951
521199
|
WHERE id IN (${placeholders})`).run(safeDelta, start2, ...ids);
|
|
520952
521200
|
} catch {
|
|
520953
521201
|
}
|
|
521202
|
+
const integratedNodes = [];
|
|
521203
|
+
if (options2.graph) {
|
|
521204
|
+
for (const id of ids) {
|
|
521205
|
+
try {
|
|
521206
|
+
const referenced = db.prepare(`SELECT 1 FROM kg_edges WHERE source_episode_id = ? LIMIT 1`).get(id);
|
|
521207
|
+
if (!referenced) {
|
|
521208
|
+
const nodeText = `episode:${id}`;
|
|
521209
|
+
const newNodeId = options2.graph.upsertNode({ text: nodeText, nodeType: "event" });
|
|
521210
|
+
if (newNodeId)
|
|
521211
|
+
integratedNodes.push(newNodeId);
|
|
521212
|
+
}
|
|
521213
|
+
} catch {
|
|
521214
|
+
}
|
|
521215
|
+
}
|
|
521216
|
+
}
|
|
520954
521217
|
return {
|
|
520955
521218
|
cycle: {
|
|
520956
521219
|
phase: "slow_wave",
|
|
@@ -520960,7 +521223,10 @@ function slowWaveReplay(db, options2 = {}) {
|
|
|
520960
521223
|
downscaledEpisodes: [],
|
|
520961
521224
|
prunedEpisodes: [],
|
|
520962
521225
|
novelAssociations: [],
|
|
520963
|
-
energyCost: ids.length
|
|
521226
|
+
energyCost: ids.length + integratedNodes.length,
|
|
521227
|
+
compressedEpisodes: [],
|
|
521228
|
+
flaggedHubs: [],
|
|
521229
|
+
integratedNodes
|
|
520964
521230
|
}
|
|
520965
521231
|
};
|
|
520966
521232
|
}
|
|
@@ -520981,10 +521247,11 @@ function remDream(db, options2 = {}) {
|
|
|
520981
521247
|
return { cycle: emptyCycle("rem", start2) };
|
|
520982
521248
|
}
|
|
520983
521249
|
const walkDepth = Math.max(1, options2.walkDepth ?? 3);
|
|
521250
|
+
const minSim = options2.minSimilarity ?? 0.6;
|
|
520984
521251
|
for (const seed of seedRows) {
|
|
520985
|
-
let
|
|
521252
|
+
let candidateRows = [];
|
|
520986
521253
|
try {
|
|
520987
|
-
|
|
521254
|
+
candidateRows = db.prepare(`SELECT id, embedding, timestamp AS ts FROM episodes
|
|
520988
521255
|
WHERE session_id IS (SELECT session_id FROM episodes WHERE id = ?)
|
|
520989
521256
|
AND id != ?
|
|
520990
521257
|
ORDER BY timestamp DESC
|
|
@@ -520992,10 +521259,58 @@ function remDream(db, options2 = {}) {
|
|
|
520992
521259
|
} catch {
|
|
520993
521260
|
continue;
|
|
520994
521261
|
}
|
|
520995
|
-
if (
|
|
520996
|
-
|
|
521262
|
+
if (candidateRows.length === 0)
|
|
521263
|
+
continue;
|
|
521264
|
+
let seedEmb = null;
|
|
521265
|
+
try {
|
|
521266
|
+
seedEmb = db.prepare(`SELECT embedding FROM episodes WHERE id = ?`).get(seed.id)?.embedding ?? null;
|
|
521267
|
+
} catch {
|
|
521268
|
+
}
|
|
521269
|
+
let chosen = null;
|
|
521270
|
+
const seedFloat = toFloat32(seedEmb);
|
|
521271
|
+
if (seedFloat) {
|
|
521272
|
+
const distantCandidates = candidateRows.slice(walkDepth);
|
|
521273
|
+
let bestSim = minSim;
|
|
521274
|
+
let bestId = null;
|
|
521275
|
+
for (const cand of distantCandidates) {
|
|
521276
|
+
const candFloat = toFloat32(cand.embedding);
|
|
521277
|
+
if (!candFloat || candFloat.length !== seedFloat.length)
|
|
521278
|
+
continue;
|
|
521279
|
+
const sim = cosineSim(seedFloat, candFloat);
|
|
521280
|
+
if (sim > bestSim) {
|
|
521281
|
+
bestSim = sim;
|
|
521282
|
+
bestId = cand.id;
|
|
521283
|
+
}
|
|
521284
|
+
}
|
|
521285
|
+
if (bestId) {
|
|
521286
|
+
chosen = { id: bestId, reason: `rem-embedding-similarity:${bestSim.toFixed(3)}` };
|
|
521287
|
+
}
|
|
521288
|
+
}
|
|
521289
|
+
if (!chosen && candidateRows.length > walkDepth) {
|
|
521290
|
+
const target = candidateRows[walkDepth];
|
|
520997
521291
|
if (target)
|
|
520998
|
-
|
|
521292
|
+
chosen = { id: target.id, reason: "rem-temporal-distance" };
|
|
521293
|
+
}
|
|
521294
|
+
if (chosen)
|
|
521295
|
+
novel.push({ from: seed.id, to: chosen.id, reason: chosen.reason });
|
|
521296
|
+
}
|
|
521297
|
+
if (options2.graph && novel.length > 0) {
|
|
521298
|
+
for (const link of novel) {
|
|
521299
|
+
try {
|
|
521300
|
+
const srcId = options2.graph.upsertNode({ text: `episode:${link.from}`, nodeType: "event" });
|
|
521301
|
+
const dstId = options2.graph.upsertNode({ text: `episode:${link.to}`, nodeType: "event" });
|
|
521302
|
+
if (srcId && dstId) {
|
|
521303
|
+
options2.graph.addEdge({
|
|
521304
|
+
srcId,
|
|
521305
|
+
dstId,
|
|
521306
|
+
relation: "associated_via_rem",
|
|
521307
|
+
edgeType: "associative",
|
|
521308
|
+
confidence: 0.4,
|
|
521309
|
+
sourceEpisodeId: link.from
|
|
521310
|
+
});
|
|
521311
|
+
}
|
|
521312
|
+
} catch {
|
|
521313
|
+
}
|
|
520999
521314
|
}
|
|
521000
521315
|
}
|
|
521001
521316
|
return {
|
|
@@ -521007,7 +521322,10 @@ function remDream(db, options2 = {}) {
|
|
|
521007
521322
|
downscaledEpisodes: [],
|
|
521008
521323
|
prunedEpisodes: [],
|
|
521009
521324
|
novelAssociations: novel,
|
|
521010
|
-
energyCost: seedRows.length + novel.length
|
|
521325
|
+
energyCost: seedRows.length + novel.length,
|
|
521326
|
+
compressedEpisodes: [],
|
|
521327
|
+
flaggedHubs: [],
|
|
521328
|
+
integratedNodes: []
|
|
521011
521329
|
}
|
|
521012
521330
|
};
|
|
521013
521331
|
}
|
|
@@ -521038,32 +521356,78 @@ function lightSleep(db, options2 = {}) {
|
|
|
521038
521356
|
} catch {
|
|
521039
521357
|
}
|
|
521040
521358
|
const pruned = [];
|
|
521359
|
+
const compressed = [];
|
|
521360
|
+
const compressMode = !!options2.compressInsteadOfPrune;
|
|
521361
|
+
const gistMaxChars = Math.max(20, options2.gistMaxChars ?? 80);
|
|
521041
521362
|
for (const klass of prunableClasses) {
|
|
521042
521363
|
const stale = stalePerClass[klass];
|
|
521043
521364
|
const cutoff = start2 - stale;
|
|
521365
|
+
const remaining = maxPrune - (pruned.length + compressed.length);
|
|
521366
|
+
if (remaining <= 0)
|
|
521367
|
+
break;
|
|
521044
521368
|
let rows = [];
|
|
521045
521369
|
try {
|
|
521046
|
-
rows = db.prepare(`SELECT id FROM episodes
|
|
521370
|
+
rows = db.prepare(`SELECT id, content FROM episodes
|
|
521047
521371
|
WHERE decay_class = ?
|
|
521048
521372
|
AND importance < ?
|
|
521049
521373
|
AND timestamp < ?
|
|
521050
521374
|
ORDER BY timestamp ASC
|
|
521051
|
-
LIMIT ?`).all(klass, pruneImportance, cutoff,
|
|
521375
|
+
LIMIT ?`).all(klass, pruneImportance, cutoff, remaining);
|
|
521052
521376
|
} catch {
|
|
521053
521377
|
rows = [];
|
|
521054
521378
|
}
|
|
521055
521379
|
if (rows.length === 0)
|
|
521056
521380
|
continue;
|
|
521057
|
-
|
|
521058
|
-
|
|
521059
|
-
|
|
521060
|
-
|
|
521061
|
-
|
|
521062
|
-
|
|
521381
|
+
if (compressMode) {
|
|
521382
|
+
try {
|
|
521383
|
+
const updateStmt = db.prepare(`UPDATE episodes
|
|
521384
|
+
SET content = ?,
|
|
521385
|
+
metadata = json_patch(COALESCE(metadata, '{}'), json_object('compressedAt', ?))
|
|
521386
|
+
WHERE id = ?`);
|
|
521387
|
+
for (const row of rows) {
|
|
521388
|
+
const truncated = (row.content ?? "").slice(0, gistMaxChars);
|
|
521389
|
+
const gist = (row.content ?? "").length > gistMaxChars ? truncated + "…" : truncated;
|
|
521390
|
+
try {
|
|
521391
|
+
updateStmt.run(gist, start2, row.id);
|
|
521392
|
+
compressed.push(row.id);
|
|
521393
|
+
} catch {
|
|
521394
|
+
try {
|
|
521395
|
+
db.prepare(`UPDATE episodes SET content = ? WHERE id = ?`).run(gist, row.id);
|
|
521396
|
+
compressed.push(row.id);
|
|
521397
|
+
} catch {
|
|
521398
|
+
}
|
|
521399
|
+
}
|
|
521400
|
+
}
|
|
521401
|
+
} catch {
|
|
521402
|
+
}
|
|
521403
|
+
} else {
|
|
521404
|
+
const ids = rows.map((r2) => r2.id);
|
|
521405
|
+
try {
|
|
521406
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
521407
|
+
db.prepare(`DELETE FROM episodes WHERE id IN (${placeholders})`).run(...ids);
|
|
521408
|
+
pruned.push(...ids);
|
|
521409
|
+
} catch {
|
|
521410
|
+
}
|
|
521063
521411
|
}
|
|
521064
|
-
if (pruned.length >= maxPrune)
|
|
521412
|
+
if (pruned.length + compressed.length >= maxPrune)
|
|
521065
521413
|
break;
|
|
521066
521414
|
}
|
|
521415
|
+
const hubThreshold = Math.max(1, options2.hubThreshold ?? 50);
|
|
521416
|
+
const flaggedHubs = [];
|
|
521417
|
+
try {
|
|
521418
|
+
const rows = db.prepare(`SELECT node_id, edge_count FROM (
|
|
521419
|
+
SELECT src_id AS node_id, COUNT(*) AS edge_count FROM kg_edges GROUP BY src_id
|
|
521420
|
+
UNION ALL
|
|
521421
|
+
SELECT dst_id AS node_id, COUNT(*) AS edge_count FROM kg_edges GROUP BY dst_id
|
|
521422
|
+
)
|
|
521423
|
+
GROUP BY node_id
|
|
521424
|
+
HAVING SUM(edge_count) >= ?
|
|
521425
|
+
ORDER BY SUM(edge_count) DESC
|
|
521426
|
+
LIMIT 50`).all(hubThreshold);
|
|
521427
|
+
for (const r2 of rows)
|
|
521428
|
+
flaggedHubs.push(r2.node_id);
|
|
521429
|
+
} catch {
|
|
521430
|
+
}
|
|
521067
521431
|
return {
|
|
521068
521432
|
cycle: {
|
|
521069
521433
|
phase: "light",
|
|
@@ -521073,7 +521437,10 @@ function lightSleep(db, options2 = {}) {
|
|
|
521073
521437
|
downscaledEpisodes: downscaled.map((r2) => r2.id),
|
|
521074
521438
|
prunedEpisodes: pruned,
|
|
521075
521439
|
novelAssociations: [],
|
|
521076
|
-
energyCost: downscaled.length + pruned.length
|
|
521440
|
+
energyCost: downscaled.length + pruned.length + compressed.length + flaggedHubs.length,
|
|
521441
|
+
compressedEpisodes: compressed,
|
|
521442
|
+
flaggedHubs,
|
|
521443
|
+
integratedNodes: []
|
|
521077
521444
|
}
|
|
521078
521445
|
};
|
|
521079
521446
|
}
|
|
@@ -521097,9 +521464,48 @@ function emptyCycle(phase, start2) {
|
|
|
521097
521464
|
downscaledEpisodes: [],
|
|
521098
521465
|
prunedEpisodes: [],
|
|
521099
521466
|
novelAssociations: [],
|
|
521100
|
-
energyCost: 0
|
|
521467
|
+
energyCost: 0,
|
|
521468
|
+
compressedEpisodes: [],
|
|
521469
|
+
flaggedHubs: [],
|
|
521470
|
+
integratedNodes: []
|
|
521101
521471
|
};
|
|
521102
521472
|
}
|
|
521473
|
+
function toFloat32(raw) {
|
|
521474
|
+
if (raw == null)
|
|
521475
|
+
return null;
|
|
521476
|
+
if (raw instanceof Float32Array) {
|
|
521477
|
+
return new Float32Array(raw);
|
|
521478
|
+
}
|
|
521479
|
+
if (raw instanceof Uint8Array) {
|
|
521480
|
+
if (raw.byteLength === 0 || raw.byteLength % 4 !== 0)
|
|
521481
|
+
return null;
|
|
521482
|
+
const fresh = new Uint8Array(raw.byteLength);
|
|
521483
|
+
fresh.set(raw);
|
|
521484
|
+
return new Float32Array(fresh.buffer, 0, raw.byteLength / 4);
|
|
521485
|
+
}
|
|
521486
|
+
if (raw instanceof ArrayBuffer) {
|
|
521487
|
+
if (raw.byteLength === 0 || raw.byteLength % 4 !== 0)
|
|
521488
|
+
return null;
|
|
521489
|
+
return new Float32Array(raw.slice(0));
|
|
521490
|
+
}
|
|
521491
|
+
return null;
|
|
521492
|
+
}
|
|
521493
|
+
function cosineSim(a2, b) {
|
|
521494
|
+
if (a2.length !== b.length || a2.length === 0)
|
|
521495
|
+
return 0;
|
|
521496
|
+
let dot = 0, na = 0, nb = 0;
|
|
521497
|
+
for (let i2 = 0; i2 < a2.length; i2++) {
|
|
521498
|
+
const x = a2[i2];
|
|
521499
|
+
const y = b[i2];
|
|
521500
|
+
dot += x * y;
|
|
521501
|
+
na += x * x;
|
|
521502
|
+
nb += y * y;
|
|
521503
|
+
}
|
|
521504
|
+
const denom = Math.sqrt(na) * Math.sqrt(nb);
|
|
521505
|
+
if (denom === 0)
|
|
521506
|
+
return 0;
|
|
521507
|
+
return dot / denom;
|
|
521508
|
+
}
|
|
521103
521509
|
function episodeCount(db) {
|
|
521104
521510
|
try {
|
|
521105
521511
|
const row = db.prepare(`SELECT COUNT(*) AS c FROM episodes`).get();
|
|
@@ -521117,7 +521523,7 @@ var init_sleepConsolidation = __esm({
|
|
|
521117
521523
|
|
|
521118
521524
|
// packages/memory/dist/socialMemory.js
|
|
521119
521525
|
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
521120
|
-
function
|
|
521526
|
+
function clamp4(x, lo, hi) {
|
|
521121
521527
|
if (!Number.isFinite(x))
|
|
521122
521528
|
return (lo + hi) / 2;
|
|
521123
521529
|
if (x < lo)
|
|
@@ -521126,24 +521532,34 @@ function clamp3(x, lo, hi) {
|
|
|
521126
521532
|
return hi;
|
|
521127
521533
|
return x;
|
|
521128
521534
|
}
|
|
521129
|
-
function
|
|
521130
|
-
return
|
|
521535
|
+
function clamp015(x) {
|
|
521536
|
+
return clamp4(x, 0, 1);
|
|
521131
521537
|
}
|
|
521132
521538
|
function clampSigned(x) {
|
|
521133
|
-
return
|
|
521539
|
+
return clamp4(x, -1, 1);
|
|
521134
521540
|
}
|
|
521135
521541
|
function sanitizeBig5(p2) {
|
|
521136
521542
|
return {
|
|
521137
|
-
openness:
|
|
521138
|
-
conscientiousness:
|
|
521139
|
-
extraversion:
|
|
521140
|
-
agreeableness:
|
|
521141
|
-
neuroticism:
|
|
521543
|
+
openness: clamp015(p2?.openness ?? NEUTRAL_BIG5.openness),
|
|
521544
|
+
conscientiousness: clamp015(p2?.conscientiousness ?? NEUTRAL_BIG5.conscientiousness),
|
|
521545
|
+
extraversion: clamp015(p2?.extraversion ?? NEUTRAL_BIG5.extraversion),
|
|
521546
|
+
agreeableness: clamp015(p2?.agreeableness ?? NEUTRAL_BIG5.agreeableness),
|
|
521547
|
+
neuroticism: clamp015(p2?.neuroticism ?? NEUTRAL_BIG5.neuroticism)
|
|
521142
521548
|
};
|
|
521143
521549
|
}
|
|
521144
521550
|
function pairKey(a2, b) {
|
|
521145
521551
|
return a2 <= b ? { lo: a2, hi: b } : { lo: b, hi: a2 };
|
|
521146
521552
|
}
|
|
521553
|
+
function rowToOpinion(row) {
|
|
521554
|
+
return {
|
|
521555
|
+
id: row.id,
|
|
521556
|
+
topic: row.topic,
|
|
521557
|
+
agentId: row.agent_id,
|
|
521558
|
+
opinion: row.opinion,
|
|
521559
|
+
confidence: row.confidence,
|
|
521560
|
+
timestamp: row.timestamp
|
|
521561
|
+
};
|
|
521562
|
+
}
|
|
521147
521563
|
function rowToAgent(row) {
|
|
521148
521564
|
return {
|
|
521149
521565
|
id: row.id,
|
|
@@ -521226,6 +521642,16 @@ var init_socialMemory = __esm({
|
|
|
521226
521642
|
adopted INTEGER NOT NULL DEFAULT 0,
|
|
521227
521643
|
timestamp INTEGER NOT NULL
|
|
521228
521644
|
);
|
|
521645
|
+
-- MEM_GAP B6: collective memory — opinions across agents on a topic
|
|
521646
|
+
CREATE TABLE IF NOT EXISTS social_shared_knowledge (
|
|
521647
|
+
id TEXT PRIMARY KEY,
|
|
521648
|
+
topic TEXT NOT NULL,
|
|
521649
|
+
agent_id TEXT NOT NULL,
|
|
521650
|
+
opinion TEXT NOT NULL,
|
|
521651
|
+
confidence REAL NOT NULL,
|
|
521652
|
+
timestamp INTEGER NOT NULL
|
|
521653
|
+
);
|
|
521654
|
+
CREATE INDEX IF NOT EXISTS idx_shared_topic ON social_shared_knowledge(topic);
|
|
521229
521655
|
CREATE INDEX IF NOT EXISTS idx_lessons_source ON social_lessons(source_agent);
|
|
521230
521656
|
CREATE INDEX IF NOT EXISTS idx_rels_agent_a ON social_relationships(agent_a);
|
|
521231
521657
|
CREATE INDEX IF NOT EXISTS idx_rels_agent_b ON social_relationships(agent_b);
|
|
@@ -521237,13 +521663,13 @@ var init_socialMemory = __esm({
|
|
|
521237
521663
|
const id = input.id ?? randomUUID11();
|
|
521238
521664
|
const existing = this.getAgent(id);
|
|
521239
521665
|
const personality = sanitizeBig5({ ...existing?.personality ?? {}, ...input.personality ?? {} });
|
|
521240
|
-
const trustOverall =
|
|
521666
|
+
const trustOverall = clamp015(input.trust?.overall ?? existing?.trust.overall ?? 0.5);
|
|
521241
521667
|
const trustByDomain = {
|
|
521242
521668
|
...existing?.trust.byDomain ?? {},
|
|
521243
521669
|
...input.trust?.byDomain ?? {}
|
|
521244
521670
|
};
|
|
521245
521671
|
for (const k of Object.keys(trustByDomain))
|
|
521246
|
-
trustByDomain[k] =
|
|
521672
|
+
trustByDomain[k] = clamp015(trustByDomain[k]);
|
|
521247
521673
|
const metadata = input.metadata ?? existing?.metadata ?? null;
|
|
521248
521674
|
if (existing) {
|
|
521249
521675
|
this.db.prepare(`UPDATE social_agents
|
|
@@ -521283,13 +521709,13 @@ var init_socialMemory = __esm({
|
|
|
521283
521709
|
const agent = this.getAgent(agentId);
|
|
521284
521710
|
if (!agent)
|
|
521285
521711
|
return null;
|
|
521286
|
-
const weight =
|
|
521712
|
+
const weight = clamp015(interaction.weight ?? 0.1);
|
|
521287
521713
|
const targetOverall = interaction.positive ? 1 : 0;
|
|
521288
|
-
const newOverall =
|
|
521714
|
+
const newOverall = clamp015(agent.trust.overall + (targetOverall - agent.trust.overall) * weight);
|
|
521289
521715
|
const newByDomain = { ...agent.trust.byDomain };
|
|
521290
521716
|
if (interaction.domain) {
|
|
521291
521717
|
const cur = newByDomain[interaction.domain] ?? 0.5;
|
|
521292
|
-
newByDomain[interaction.domain] =
|
|
521718
|
+
newByDomain[interaction.domain] = clamp015(cur + (targetOverall - cur) * weight);
|
|
521293
521719
|
}
|
|
521294
521720
|
const now = Date.now();
|
|
521295
521721
|
this.db.prepare(`UPDATE social_agents
|
|
@@ -521319,14 +521745,14 @@ var init_socialMemory = __esm({
|
|
|
521319
521745
|
history.push(newEvent);
|
|
521320
521746
|
if (history.length > 200)
|
|
521321
521747
|
history.splice(0, history.length - 200);
|
|
521322
|
-
const strength =
|
|
521748
|
+
const strength = clamp015(existing.strength + Math.abs(dStrength));
|
|
521323
521749
|
const valence = clampSigned(existing.valence + dValence);
|
|
521324
|
-
const reciprocity =
|
|
521750
|
+
const reciprocity = clamp015(existing.reciprocity * 0.95 + 0.05 * 0.5);
|
|
521325
521751
|
this.db.prepare(`UPDATE social_relationships
|
|
521326
521752
|
SET strength = ?, valence = ?, reciprocity = ?, last_updated = ?, history = ?
|
|
521327
521753
|
WHERE agent_a = ? AND agent_b = ?`).run(strength, valence, reciprocity, now, JSON.stringify(history), lo, hi);
|
|
521328
521754
|
} else {
|
|
521329
|
-
const strength =
|
|
521755
|
+
const strength = clamp015(Math.abs(dStrength));
|
|
521330
521756
|
const valence = clampSigned(dValence);
|
|
521331
521757
|
this.db.prepare(`INSERT INTO social_relationships
|
|
521332
521758
|
(agent_a, agent_b, strength, valence, reciprocity, last_updated, history)
|
|
@@ -521349,7 +521775,7 @@ var init_socialMemory = __esm({
|
|
|
521349
521775
|
recordLesson(input) {
|
|
521350
521776
|
const id = randomUUID11();
|
|
521351
521777
|
const now = Date.now();
|
|
521352
|
-
const conf =
|
|
521778
|
+
const conf = clamp015(input.confidence ?? 0.5);
|
|
521353
521779
|
const adopted = input.adopted ? 1 : 0;
|
|
521354
521780
|
this.db.prepare(`INSERT INTO social_lessons (id, source_agent, lesson, confidence, adopted, timestamp)
|
|
521355
521781
|
VALUES (?, ?, ?, ?, ?, ?)`).run(id, input.sourceAgent, input.lesson, conf, adopted, now);
|
|
@@ -521363,6 +521789,47 @@ var init_socialMemory = __esm({
|
|
|
521363
521789
|
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
521790
|
return rows.map(rowToLesson);
|
|
521365
521791
|
}
|
|
521792
|
+
// ── MEM_GAP B6: collective memory ────────────────────────────────────────
|
|
521793
|
+
recordOpinion(input) {
|
|
521794
|
+
const id = randomUUID11();
|
|
521795
|
+
const now = Date.now();
|
|
521796
|
+
const conf = clamp015(input.confidence ?? 0.5);
|
|
521797
|
+
this.db.prepare(`INSERT INTO social_shared_knowledge (id, topic, agent_id, opinion, confidence, timestamp)
|
|
521798
|
+
VALUES (?, ?, ?, ?, ?, ?)`).run(id, input.topic, input.agentId, input.opinion, conf, now);
|
|
521799
|
+
return { id, topic: input.topic, agentId: input.agentId, opinion: input.opinion, confidence: conf, timestamp: now };
|
|
521800
|
+
}
|
|
521801
|
+
/**
|
|
521802
|
+
* Compute consensus on a topic. Returns:
|
|
521803
|
+
* - contributors: count of distinct agents
|
|
521804
|
+
* - agreementScore: 1 = unanimous, 0 = perfectly split. Scored by the
|
|
521805
|
+
* largest opinion-cluster's share (Jaccard-style on normalized text).
|
|
521806
|
+
* - divergence: 1 - agreementScore.
|
|
521807
|
+
*/
|
|
521808
|
+
getConsensus(topic) {
|
|
521809
|
+
const rows = this.db.prepare(`SELECT * FROM social_shared_knowledge WHERE topic = ? ORDER BY timestamp DESC`).all(topic);
|
|
521810
|
+
const opinions = rows.map(rowToOpinion);
|
|
521811
|
+
if (opinions.length === 0) {
|
|
521812
|
+
return { contributors: 0, agreementScore: 1, divergence: 0, opinions };
|
|
521813
|
+
}
|
|
521814
|
+
const agents = new Set(opinions.map((o2) => o2.agentId));
|
|
521815
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
521816
|
+
for (const o2 of opinions) {
|
|
521817
|
+
const norm = o2.opinion.toLowerCase().replace(/\s+/g, " ").trim();
|
|
521818
|
+
buckets.set(norm, (buckets.get(norm) ?? 0) + 1);
|
|
521819
|
+
}
|
|
521820
|
+
const top = Math.max(...buckets.values());
|
|
521821
|
+
const agreementScore = top / opinions.length;
|
|
521822
|
+
return {
|
|
521823
|
+
contributors: agents.size,
|
|
521824
|
+
agreementScore,
|
|
521825
|
+
divergence: 1 - agreementScore,
|
|
521826
|
+
opinions
|
|
521827
|
+
};
|
|
521828
|
+
}
|
|
521829
|
+
listOpinions(topic) {
|
|
521830
|
+
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();
|
|
521831
|
+
return rows.map(rowToOpinion);
|
|
521832
|
+
}
|
|
521366
521833
|
};
|
|
521367
521834
|
}
|
|
521368
521835
|
});
|
|
@@ -521496,7 +521963,9 @@ __export(dist_exports2, {
|
|
|
521496
521963
|
TemporalGraph: () => TemporalGraph,
|
|
521497
521964
|
ToolPatternStore: () => ToolPatternStore,
|
|
521498
521965
|
ValidationStore: () => ValidationStore,
|
|
521966
|
+
applyInfluence: () => applyInfluence,
|
|
521499
521967
|
attachTrace: () => attachTrace,
|
|
521968
|
+
authorityBias: () => authorityBias,
|
|
521500
521969
|
autoDecayClass: () => autoDecayClass,
|
|
521501
521970
|
autoImportance: () => autoImportance,
|
|
521502
521971
|
batchLink: () => batchLink,
|
|
@@ -521506,6 +521975,7 @@ __export(dist_exports2, {
|
|
|
521506
521975
|
closeDb: () => closeDb,
|
|
521507
521976
|
compressAndStore: () => compressAndStore,
|
|
521508
521977
|
compressToGist: () => compressToGist,
|
|
521978
|
+
conformityBias: () => conformityBias,
|
|
521509
521979
|
congruenceMultiplier: () => congruenceMultiplier,
|
|
521510
521980
|
cosineSimilarity: () => cosineSimilarity2,
|
|
521511
521981
|
createCRLMemoryStore: () => createCRLMemoryStore,
|
|
@@ -521529,8 +521999,10 @@ __export(dist_exports2, {
|
|
|
521529
521999
|
linkEpisode: () => linkEpisode,
|
|
521530
522000
|
modulateImportance: () => modulateImportance,
|
|
521531
522001
|
modulateRetrievalScore: () => modulateRetrievalScore,
|
|
522002
|
+
noveltyBias: () => noveltyBias,
|
|
521532
522003
|
observeEmotionalState: () => observeEmotionalState,
|
|
521533
522004
|
personalizedPageRank: () => personalizedPageRank,
|
|
522005
|
+
reciprocityBias: () => reciprocityBias,
|
|
521534
522006
|
remDream: () => remDream,
|
|
521535
522007
|
resetCRLConfigStore: () => resetCRLConfigStore,
|
|
521536
522008
|
retrieveByPPR: () => retrieveByPPR,
|
|
@@ -521544,6 +522016,7 @@ __export(dist_exports2, {
|
|
|
521544
522016
|
splanifoldRmse: () => rmse,
|
|
521545
522017
|
splanifoldSerialize: () => serialize,
|
|
521546
522018
|
suggestRegulation: () => suggestRegulation,
|
|
522019
|
+
suggestRegulationActions: () => suggestRegulationActions,
|
|
521547
522020
|
thresholdsForStage: () => thresholdsForStage,
|
|
521548
522021
|
tokenSimilarity: () => tokenSimilarity,
|
|
521549
522022
|
wasHesitant: () => wasHesitant
|
|
@@ -521577,6 +522050,7 @@ var init_dist7 = __esm({
|
|
|
521577
522050
|
init_socialMemory();
|
|
521578
522051
|
init_developmentalStage();
|
|
521579
522052
|
init_memoryStageContext();
|
|
522053
|
+
init_socialInfluence();
|
|
521580
522054
|
}
|
|
521581
522055
|
});
|
|
521582
522056
|
|
|
@@ -526814,6 +527288,39 @@ Respond with your assessment, then take action.`;
|
|
|
526814
527288
|
} catch {
|
|
526815
527289
|
}
|
|
526816
527290
|
}
|
|
527291
|
+
if (process.env["OA_DISABLE_STAGE_CONTEXT"] !== "1") {
|
|
527292
|
+
try {
|
|
527293
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
527294
|
+
if (!this._stageContext) {
|
|
527295
|
+
this._stageContext = new memMod.MemoryStageContext();
|
|
527296
|
+
}
|
|
527297
|
+
const stageCtx = this._stageContext;
|
|
527298
|
+
const totalEpisodes = this._episodeStore ? this._episodeStore.count() : 0;
|
|
527299
|
+
const sessionCount = typeof this._historicalSessionCount === "number" ? this._historicalSessionCount : 0;
|
|
527300
|
+
const recentPredictionError = this._predictionStore ? this._predictionStore.averageError(50) : 1;
|
|
527301
|
+
const snap = stageCtx.refresh({
|
|
527302
|
+
sessionCount,
|
|
527303
|
+
domainCount: 0,
|
|
527304
|
+
recentPredictionError,
|
|
527305
|
+
crossDomainLinks: 0,
|
|
527306
|
+
totalEpisodes,
|
|
527307
|
+
creativeAssociationCount: 0
|
|
527308
|
+
});
|
|
527309
|
+
if (this._episodeStore) {
|
|
527310
|
+
try {
|
|
527311
|
+
this._episodeStore.setZettelConfig?.(stageCtx.toZettelkastenConfig());
|
|
527312
|
+
this._episodeStore.setImportanceFloor?.(stageCtx.importanceFloor());
|
|
527313
|
+
} catch {
|
|
527314
|
+
}
|
|
527315
|
+
}
|
|
527316
|
+
this.emit({
|
|
527317
|
+
type: "status",
|
|
527318
|
+
content: `Memory stage: ${snap.stage} (importanceFloor=${snap.thresholds.importanceFloor}, linkThreshold=${snap.thresholds.linkThreshold})`,
|
|
527319
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
527320
|
+
});
|
|
527321
|
+
} catch {
|
|
527322
|
+
}
|
|
527323
|
+
}
|
|
526817
527324
|
const contextComposition = await this.assembleContext(task, context2);
|
|
526818
527325
|
const systemPrompt = contextComposition.assembled;
|
|
526819
527326
|
this._contextTree = new ContextTree(`sys-${systemPrompt.length}`, cleanedTask.slice(0, 200));
|
|
@@ -527176,6 +527683,43 @@ TASK: ${task}` : task;
|
|
|
527176
527683
|
content: `STAGNATION DETECTED — injected diagnostic mode at turn ${turn} (${signals.variantCount} variants, ${signals.failureSum} failures, ${signals.filesDelta} files in window)`,
|
|
527177
527684
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
527178
527685
|
});
|
|
527686
|
+
try {
|
|
527687
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
527688
|
+
const hs = this._homeostat;
|
|
527689
|
+
if (hs) {
|
|
527690
|
+
const actions = memMod.suggestRegulationActions(hs);
|
|
527691
|
+
for (const a2 of actions) {
|
|
527692
|
+
this.emit({
|
|
527693
|
+
type: "status",
|
|
527694
|
+
content: `[REGULATION SUGGESTION] ${a2} — homeostat is off-target (current valence=${hs.current.valence.toFixed(2)}, arousal=${hs.current.arousal.toFixed(2)}, streak=${hs.streak})`,
|
|
527695
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
527696
|
+
});
|
|
527697
|
+
}
|
|
527698
|
+
}
|
|
527699
|
+
if (this._selfModel && this._episodeStore) {
|
|
527700
|
+
const sm = this._selfModel;
|
|
527701
|
+
const report2 = sm.snapshot();
|
|
527702
|
+
for (const [domain, c9] of Object.entries(report2.calibration.byDomain)) {
|
|
527703
|
+
if (c9.n >= 5 && c9.confidence - c9.accuracy > 0.2) {
|
|
527704
|
+
this.emit({
|
|
527705
|
+
type: "status",
|
|
527706
|
+
content: `[SELF-MODEL CALIBRATION mid-session] overconfident in '${domain}': stated ${c9.confidence.toFixed(2)} vs actual ${c9.accuracy.toFixed(2)} across ${c9.n} samples — temper next-action confidence in this domain.`,
|
|
527707
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
527708
|
+
});
|
|
527709
|
+
}
|
|
527710
|
+
}
|
|
527711
|
+
this._episodeStore.insert({
|
|
527712
|
+
sessionId: this._sessionId,
|
|
527713
|
+
modality: "reflection",
|
|
527714
|
+
toolName: "self_model_snapshot",
|
|
527715
|
+
content: `mid-session self-report (stagnation @ turn ${turn}): stage=${report2.developmental?.stage ?? "?"} calGap=${report2.calibration.calibrationGap.toFixed(2)} (n=${report2.calibration.sampleCount}) blindSpots=${report2.blindSpots.length}`,
|
|
527716
|
+
importance: 7,
|
|
527717
|
+
decayClass: "session",
|
|
527718
|
+
metadata: { selfReport: report2, stagnationTurn: turn }
|
|
527719
|
+
});
|
|
527720
|
+
}
|
|
527721
|
+
} catch {
|
|
527722
|
+
}
|
|
527179
527723
|
}
|
|
527180
527724
|
}
|
|
527181
527725
|
}
|
|
@@ -528029,7 +528573,12 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
|
|
|
528029
528573
|
if (turn > 0 && turn % 3 === 0 && this._temporalGraph && this._episodeStore) {
|
|
528030
528574
|
try {
|
|
528031
528575
|
const taskGoal = this._taskState.goal || cleanedTask.slice(0, 200);
|
|
528032
|
-
const
|
|
528576
|
+
const _hs = this._homeostat;
|
|
528577
|
+
const pprResult = retrieveByPPR(taskGoal, this._temporalGraph, this._episodeStore, {
|
|
528578
|
+
topK: 3,
|
|
528579
|
+
currentEmotionalState: _hs?.current,
|
|
528580
|
+
engagementWeight: 0.2
|
|
528581
|
+
});
|
|
528033
528582
|
if (pprResult.episodes.length > 0) {
|
|
528034
528583
|
const memoryLines = pprResult.episodes.map(({ episode, pprScore, matchedNodes }) => `- [${episode.toolName ?? episode.modality}] ${episode.content.slice(0, 120)} (via: ${matchedNodes.slice(0, 2).join(", ")})`);
|
|
528035
528584
|
compacted.push({
|
|
@@ -528402,6 +528951,15 @@ ${memoryLines.join("\n")}`
|
|
|
528402
528951
|
if (!this._predictionStore) {
|
|
528403
528952
|
this._predictionStore = new memMod.PredictionStore({ capacity: 256 });
|
|
528404
528953
|
this._toolDurationAvg = /* @__PURE__ */ new Map();
|
|
528954
|
+
try {
|
|
528955
|
+
if (this._episodeStore && process.env["OA_DISABLE_PREDICTION_PERSISTENCE"] !== "1") {
|
|
528956
|
+
this._predictionStore.restore(this._episodeStore.getDb());
|
|
528957
|
+
}
|
|
528958
|
+
} catch {
|
|
528959
|
+
}
|
|
528960
|
+
}
|
|
528961
|
+
if (!this._homeostat) {
|
|
528962
|
+
this._homeostat = memMod.createHomeostaticState();
|
|
528405
528963
|
}
|
|
528406
528964
|
const ps = this._predictionStore;
|
|
528407
528965
|
const avgs = this._toolDurationAvg;
|
|
@@ -529024,9 +529582,63 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
|
|
|
529024
529582
|
importance: Math.min(10, 7 + Math.round(err.errorMagnitude * 3)),
|
|
529025
529583
|
metadata: { predictionError: { magnitude: err.errorMagnitude, axis: err.dominantAxis } }
|
|
529026
529584
|
});
|
|
529585
|
+
if (process.env["OA_DISABLE_SOCIAL_MEMORY"] !== "1") {
|
|
529586
|
+
if (!this._socialMemory) {
|
|
529587
|
+
this._socialMemory = new memMod.SocialMemoryStore(this._episodeStore.getDb());
|
|
529588
|
+
}
|
|
529589
|
+
const social = this._socialMemory;
|
|
529590
|
+
social.recordLesson({
|
|
529591
|
+
sourceAgent: "self",
|
|
529592
|
+
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"}.`,
|
|
529593
|
+
confidence: Math.min(0.95, 0.5 + err.errorMagnitude * 0.5)
|
|
529594
|
+
});
|
|
529595
|
+
}
|
|
529027
529596
|
} catch {
|
|
529028
529597
|
}
|
|
529029
529598
|
}
|
|
529599
|
+
if (process.env["OA_DISABLE_SOCIAL_MEMORY"] !== "1") {
|
|
529600
|
+
const SUB_AGENT_TOOLS = /* @__PURE__ */ new Set(["sub_agent", "background_run", "priority_delegate", "skill_execute"]);
|
|
529601
|
+
if (SUB_AGENT_TOOLS.has(tc.name)) {
|
|
529602
|
+
try {
|
|
529603
|
+
if (!this._socialMemory) {
|
|
529604
|
+
this._socialMemory = new memMod.SocialMemoryStore(this._episodeStore.getDb());
|
|
529605
|
+
}
|
|
529606
|
+
const social = this._socialMemory;
|
|
529607
|
+
const otherId = `${tc.name}:${String(tc.arguments?.["agent_id"] ?? tc.arguments?.["name"] ?? tc.arguments?.["target"] ?? "anonymous").slice(0, 60)}`;
|
|
529608
|
+
social.upsertAgent({ id: otherId, name: otherId, type: "agent" });
|
|
529609
|
+
social.recordRelationshipEvent("self", otherId, {
|
|
529610
|
+
event: groundTruthSuccess ? "successful collaboration" : "failed collaboration",
|
|
529611
|
+
impactOnStrength: 0.05,
|
|
529612
|
+
impactOnValence: groundTruthSuccess ? 0.1 : -0.1
|
|
529613
|
+
});
|
|
529614
|
+
} catch {
|
|
529615
|
+
}
|
|
529616
|
+
}
|
|
529617
|
+
}
|
|
529618
|
+
if (this._homeostat) {
|
|
529619
|
+
const ctxUsed = typeof this._lastContextTokens === "number" ? this._lastContextTokens : 0;
|
|
529620
|
+
const ctxMax = typeof this._contextWindowMax === "number" ? this._contextWindowMax : 0;
|
|
529621
|
+
const cogLoad = ctxMax > 0 ? Math.max(0, Math.min(1, ctxUsed / ctxMax)) : 0;
|
|
529622
|
+
let valence = 0;
|
|
529623
|
+
const verifierDowngrade = v && v.trustworthy === false;
|
|
529624
|
+
if (verifierDowngrade)
|
|
529625
|
+
valence -= 0.6;
|
|
529626
|
+
else if (groundTruthSuccess)
|
|
529627
|
+
valence += 0.3;
|
|
529628
|
+
else
|
|
529629
|
+
valence -= 0.3;
|
|
529630
|
+
if (err && err.errorMagnitude > 0.5)
|
|
529631
|
+
valence -= 0.4;
|
|
529632
|
+
if (valence < -1)
|
|
529633
|
+
valence = -1;
|
|
529634
|
+
if (valence > 1)
|
|
529635
|
+
valence = 1;
|
|
529636
|
+
const recentFailures = ps ? ps.axisProfile(8).success : 0;
|
|
529637
|
+
let arousal = Math.max(0, Math.min(1, cogLoad * 0.7 + recentFailures * 0.4));
|
|
529638
|
+
if (arousal < 0.05)
|
|
529639
|
+
arousal = 0.05;
|
|
529640
|
+
this._homeostat = memMod.observeEmotionalState(this._homeostat, { valence, arousal });
|
|
529641
|
+
}
|
|
529030
529642
|
}
|
|
529031
529643
|
} catch {
|
|
529032
529644
|
}
|
|
@@ -530665,6 +531277,89 @@ Full content available via: repl_exec(code="data = retrieve('${handleId}')") or
|
|
|
530665
531277
|
if (pruned > 0) {
|
|
530666
531278
|
this.emit({ type: "status", content: `Pruned ${pruned} expired session episodes`, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
530667
531279
|
}
|
|
531280
|
+
if (process.env["OA_DISABLE_SELF_MODEL"] !== "1") {
|
|
531281
|
+
try {
|
|
531282
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
531283
|
+
const tracker = this._confidenceTracker;
|
|
531284
|
+
const ps = this._predictionStore;
|
|
531285
|
+
if (!this._selfModel) {
|
|
531286
|
+
const db = this._episodeStore.getDb();
|
|
531287
|
+
this._selfModel = new memMod.SelfModel(db, tracker, {
|
|
531288
|
+
predictionStore: ps,
|
|
531289
|
+
// MEM_GAP B7: real metrics from observable corpus state.
|
|
531290
|
+
metricsBuilder: (stats, prediction) => {
|
|
531291
|
+
let creativeAssociationCount = 0;
|
|
531292
|
+
try {
|
|
531293
|
+
const r2 = db.prepare(`SELECT COUNT(*) AS c FROM episodes WHERE tool_name IN ('rem_association', 'sleep_integration')`).get();
|
|
531294
|
+
creativeAssociationCount = r2?.c ?? 0;
|
|
531295
|
+
} catch {
|
|
531296
|
+
}
|
|
531297
|
+
let crossDomainLinks = 0;
|
|
531298
|
+
try {
|
|
531299
|
+
const r2 = db.prepare(`SELECT COUNT(DISTINCT
|
|
531300
|
+
substr(src.text, 1, instr(src.text, ':') - 1) || '|' ||
|
|
531301
|
+
substr(dst.text, 1, instr(dst.text, ':') - 1)
|
|
531302
|
+
) AS c
|
|
531303
|
+
FROM kg_edges e
|
|
531304
|
+
JOIN kg_nodes src ON src.id = e.src_id
|
|
531305
|
+
JOIN kg_nodes dst ON dst.id = e.dst_id
|
|
531306
|
+
WHERE instr(src.text, ':') > 0
|
|
531307
|
+
AND instr(dst.text, ':') > 0
|
|
531308
|
+
AND substr(src.text, 1, instr(src.text, ':') - 1) <>
|
|
531309
|
+
substr(dst.text, 1, instr(dst.text, ':') - 1)`).get();
|
|
531310
|
+
crossDomainLinks = r2?.c ?? 0;
|
|
531311
|
+
} catch {
|
|
531312
|
+
}
|
|
531313
|
+
let domainCount = 0;
|
|
531314
|
+
try {
|
|
531315
|
+
const r2 = db.prepare(`SELECT COUNT(DISTINCT substr(text, 1, instr(text, ':') - 1)) AS c
|
|
531316
|
+
FROM kg_nodes WHERE instr(text, ':') > 0`).get();
|
|
531317
|
+
domainCount = r2?.c ?? 0;
|
|
531318
|
+
} catch {
|
|
531319
|
+
}
|
|
531320
|
+
return {
|
|
531321
|
+
sessionCount: typeof this._historicalSessionCount === "number" ? this._historicalSessionCount : 0,
|
|
531322
|
+
domainCount,
|
|
531323
|
+
recentPredictionError: prediction?.averageError ?? 1,
|
|
531324
|
+
crossDomainLinks,
|
|
531325
|
+
totalEpisodes: stats.totalEpisodes,
|
|
531326
|
+
creativeAssociationCount
|
|
531327
|
+
};
|
|
531328
|
+
}
|
|
531329
|
+
});
|
|
531330
|
+
}
|
|
531331
|
+
const sm = this._selfModel;
|
|
531332
|
+
const report2 = sm.snapshot();
|
|
531333
|
+
this._episodeStore.insert({
|
|
531334
|
+
sessionId: this._sessionId,
|
|
531335
|
+
modality: "reflection",
|
|
531336
|
+
toolName: "self_model_snapshot",
|
|
531337
|
+
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}`,
|
|
531338
|
+
importance: 7,
|
|
531339
|
+
decayClass: "procedural",
|
|
531340
|
+
metadata: { selfReport: report2 }
|
|
531341
|
+
});
|
|
531342
|
+
for (const [domain, c9] of Object.entries(report2.calibration.byDomain)) {
|
|
531343
|
+
if (c9.n >= 5 && c9.confidence - c9.accuracy > 0.2) {
|
|
531344
|
+
this.emit({
|
|
531345
|
+
type: "status",
|
|
531346
|
+
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.`,
|
|
531347
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
531348
|
+
});
|
|
531349
|
+
}
|
|
531350
|
+
}
|
|
531351
|
+
} catch {
|
|
531352
|
+
}
|
|
531353
|
+
}
|
|
531354
|
+
if (process.env["OA_DISABLE_PREDICTION_PERSISTENCE"] !== "1") {
|
|
531355
|
+
try {
|
|
531356
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
531357
|
+
const ps = this._predictionStore;
|
|
531358
|
+
if (ps)
|
|
531359
|
+
ps.snapshot(this._episodeStore.getDb());
|
|
531360
|
+
} catch {
|
|
531361
|
+
}
|
|
531362
|
+
}
|
|
530668
531363
|
if (process.env["OA_DISABLE_SOCIAL_MEMORY"] !== "1") {
|
|
530669
531364
|
try {
|
|
530670
531365
|
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
@@ -530693,10 +531388,25 @@ Full content available via: repl_exec(code="data = retrieve('${handleId}')") or
|
|
|
530693
531388
|
if (process.env["OA_DISABLE_SLEEP_CONSOLIDATION"] !== "1") {
|
|
530694
531389
|
try {
|
|
530695
531390
|
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
531391
|
+
const stageCtx = this._stageContext;
|
|
531392
|
+
const lightTune = stageCtx ? stageCtx.toLightSleepTunables() : {};
|
|
530696
531393
|
const cycle = memMod.runConsolidationCycle(this._episodeStore.getDb(), {
|
|
530697
|
-
|
|
530698
|
-
|
|
531394
|
+
slowWave: this._temporalGraph ? { graph: this._temporalGraph } : {},
|
|
531395
|
+
rem: this._temporalGraph ? { graph: this._temporalGraph } : {},
|
|
531396
|
+
light: { prunableClasses: ["session"], ...lightTune }
|
|
530699
531397
|
});
|
|
531398
|
+
if (stageCtx) {
|
|
531399
|
+
const totalEpisodes = this._episodeStore.count();
|
|
531400
|
+
const recentPredictionError = this._predictionStore ? this._predictionStore.averageError(50) : 1;
|
|
531401
|
+
stageCtx.refresh({
|
|
531402
|
+
sessionCount: typeof this._historicalSessionCount === "number" ? this._historicalSessionCount : 0,
|
|
531403
|
+
domainCount: 0,
|
|
531404
|
+
recentPredictionError,
|
|
531405
|
+
crossDomainLinks: 0,
|
|
531406
|
+
totalEpisodes,
|
|
531407
|
+
creativeAssociationCount: cycle.rem.novelAssociations.length
|
|
531408
|
+
});
|
|
531409
|
+
}
|
|
530700
531410
|
if (this._temporalGraph && cycle.rem.novelAssociations.length > 0) {
|
|
530701
531411
|
try {
|
|
530702
531412
|
for (const link of cycle.rem.novelAssociations) {
|
|
@@ -577628,7 +578338,7 @@ function appraiseEvent(event) {
|
|
|
577628
578338
|
return null;
|
|
577629
578339
|
}
|
|
577630
578340
|
}
|
|
577631
|
-
function
|
|
578341
|
+
function clamp5(value2, min, max) {
|
|
577632
578342
|
return Math.max(min, Math.min(max, value2));
|
|
577633
578343
|
}
|
|
577634
578344
|
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;
|
|
@@ -577766,8 +578476,8 @@ var init_emotion_engine = __esm({
|
|
|
577766
578476
|
if (this.consecutiveFailures >= 2) {
|
|
577767
578477
|
momentum = 1 + (this.consecutiveFailures - 1) * 0.25;
|
|
577768
578478
|
}
|
|
577769
|
-
this.state.valence =
|
|
577770
|
-
this.state.arousal =
|
|
578479
|
+
this.state.valence = clamp5(this.state.valence + delta.valence * momentum, -1, 1);
|
|
578480
|
+
this.state.arousal = clamp5(this.state.arousal + delta.arousal * momentum, 0, 1);
|
|
577771
578481
|
this.state.updatedAt = Date.now();
|
|
577772
578482
|
const deterministicLabel = labelFromCoordinates(this.state.valence, this.state.arousal);
|
|
577773
578483
|
this.state.label = deterministicLabel.label;
|
|
@@ -580598,7 +581308,7 @@ __export(voicechat_exports, {
|
|
|
580598
581308
|
VoiceChatSession: () => VoiceChatSession
|
|
580599
581309
|
});
|
|
580600
581310
|
import { EventEmitter as EventEmitter11 } from "node:events";
|
|
580601
|
-
function
|
|
581311
|
+
function clamp016(x) {
|
|
580602
581312
|
return x < 0 ? 0 : x > 1 ? 1 : x;
|
|
580603
581313
|
}
|
|
580604
581314
|
function alnumRatio(s2) {
|
|
@@ -580637,9 +581347,9 @@ function computeSignalFromText(text, confidence) {
|
|
|
580637
581347
|
else score = 0.15;
|
|
580638
581348
|
score -= repeatingCharPenalty(t2) * 0.4;
|
|
580639
581349
|
if (typeof confidence === "number" && !Number.isNaN(confidence)) {
|
|
580640
|
-
score = 0.7 * score + 0.3 *
|
|
581350
|
+
score = 0.7 * score + 0.3 * clamp016(confidence);
|
|
580641
581351
|
}
|
|
580642
|
-
return
|
|
581352
|
+
return clamp016(score);
|
|
580643
581353
|
}
|
|
580644
581354
|
function truncateForLog(s2, n2) {
|
|
580645
581355
|
return s2.length <= n2 ? s2 : s2.slice(0, n2 - 1) + "…";
|
|
@@ -580909,7 +581619,7 @@ Rules:
|
|
|
580909
581619
|
}, MAX_SEGMENT_MS);
|
|
580910
581620
|
}
|
|
580911
581621
|
this.captureBuffer = text;
|
|
580912
|
-
this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ?
|
|
581622
|
+
this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp016(snr) : computeSignalFromText(text, confidence);
|
|
580913
581623
|
this.emit("snr", { score: this.lastSignalScore });
|
|
580914
581624
|
this.onPartialTranscript(text);
|
|
580915
581625
|
if (this.silenceTimer) clearTimeout(this.silenceTimer);
|