open-agents-ai 0.187.510 → 0.187.512

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
@@ -89665,7 +89665,7 @@ var require_auto = __commonJS({
89665
89665
  // ../node_modules/acme-client/src/client.js
89666
89666
  var require_client = __commonJS({
89667
89667
  "../node_modules/acme-client/src/client.js"(exports, module) {
89668
- var { createHash: createHash17 } = __require("crypto");
89668
+ var { createHash: createHash20 } = __require("crypto");
89669
89669
  var { getPemBodyAsB64u } = require_crypto();
89670
89670
  var { log: log22 } = require_logger();
89671
89671
  var HttpClient = require_http();
@@ -89976,14 +89976,14 @@ var require_client = __commonJS({
89976
89976
  */
89977
89977
  async getChallengeKeyAuthorization(challenge) {
89978
89978
  const jwk = this.http.getJwk();
89979
- const keysum = createHash17("sha256").update(JSON.stringify(jwk));
89979
+ const keysum = createHash20("sha256").update(JSON.stringify(jwk));
89980
89980
  const thumbprint = keysum.digest("base64url");
89981
89981
  const result = `${challenge.token}.${thumbprint}`;
89982
89982
  if (challenge.type === "http-01") {
89983
89983
  return result;
89984
89984
  }
89985
89985
  if (challenge.type === "dns-01") {
89986
- return createHash17("sha256").update(result).digest("base64url");
89986
+ return createHash20("sha256").update(result).digest("base64url");
89987
89987
  }
89988
89988
  if (challenge.type === "tls-alpn-01") {
89989
89989
  return result;
@@ -232663,7 +232663,7 @@ var require_websocket2 = __commonJS({
232663
232663
  var http6 = __require("http");
232664
232664
  var net5 = __require("net");
232665
232665
  var tls2 = __require("tls");
232666
- var { randomBytes: randomBytes25, createHash: createHash17 } = __require("crypto");
232666
+ var { randomBytes: randomBytes25, createHash: createHash20 } = __require("crypto");
232667
232667
  var { Duplex: Duplex3, Readable } = __require("stream");
232668
232668
  var { URL: URL3 } = __require("url");
232669
232669
  var PerMessageDeflate2 = require_permessage_deflate2();
@@ -233323,7 +233323,7 @@ var require_websocket2 = __commonJS({
233323
233323
  abortHandshake(websocket, socket, "Invalid Upgrade header");
233324
233324
  return;
233325
233325
  }
233326
- const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
233326
+ const digest3 = createHash20("sha1").update(key + GUID).digest("base64");
233327
233327
  if (res.headers["sec-websocket-accept"] !== digest3) {
233328
233328
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
233329
233329
  return;
@@ -233690,7 +233690,7 @@ var require_websocket_server = __commonJS({
233690
233690
  var EventEmitter13 = __require("events");
233691
233691
  var http6 = __require("http");
233692
233692
  var { Duplex: Duplex3 } = __require("stream");
233693
- var { createHash: createHash17 } = __require("crypto");
233693
+ var { createHash: createHash20 } = __require("crypto");
233694
233694
  var extension2 = require_extension2();
233695
233695
  var PerMessageDeflate2 = require_permessage_deflate2();
233696
233696
  var subprotocol2 = require_subprotocol();
@@ -233991,7 +233991,7 @@ var require_websocket_server = __commonJS({
233991
233991
  );
233992
233992
  }
233993
233993
  if (this._state > RUNNING) return abortHandshake(socket, 503);
233994
- const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
233994
+ const digest3 = createHash20("sha1").update(key + GUID).digest("base64");
233995
233995
  const headers = [
233996
233996
  "HTTP/1.1 101 Switching Protocols",
233997
233997
  "Upgrade: websocket",
@@ -246798,13 +246798,13 @@ Justification: ${justification || "(none provided)"}`,
246798
246798
  }
246799
246799
  const snapshot = JSON.stringify(this.selfState, null, 2);
246800
246800
  try {
246801
- const { createHash: createHash17 } = await import("node:crypto");
246801
+ const { createHash: createHash20 } = await import("node:crypto");
246802
246802
  const snapshotDir = join27(this.cwd, ".oa", "identity", "snapshots");
246803
246803
  await mkdir6(snapshotDir, { recursive: true });
246804
246804
  const version4 = this.selfState.version;
246805
246805
  const snapshotPath = join27(snapshotDir, `v${version4}.json`);
246806
246806
  await writeFile11(snapshotPath, snapshot, "utf8");
246807
- const hash = createHash17("sha256").update(snapshot).digest("hex");
246807
+ const hash = createHash20("sha256").update(snapshot).digest("hex");
246808
246808
  await writeFile11(join27(this.cwd, ".oa", "identity", "latest-hash.txt"), hash, "utf8");
246809
246809
  let ipfsCid = "";
246810
246810
  try {
@@ -246937,8 +246937,8 @@ New: ${newNarrative.slice(0, 200)}...`,
246937
246937
  }
246938
246938
  // ── Helpers ──────────────────────────────────────────────────────────────
246939
246939
  createDefaultState() {
246940
- const { createHash: createHash17 } = __require("node:crypto");
246941
- const machineId = createHash17("sha256").update(this.cwd).digest("hex").slice(0, 12);
246940
+ const { createHash: createHash20 } = __require("node:crypto");
246941
+ const machineId = createHash20("sha256").update(this.cwd).digest("hex").slice(0, 12);
246942
246942
  return {
246943
246943
  self_id: `oa-${machineId}`,
246944
246944
  version: 1,
@@ -247020,9 +247020,9 @@ New: ${newNarrative.slice(0, 200)}...`,
247020
247020
  let cid;
247021
247021
  if (this.selfState.version > prevVersion) {
247022
247022
  try {
247023
- const { createHash: createHash17 } = await import("node:crypto");
247023
+ const { createHash: createHash20 } = await import("node:crypto");
247024
247024
  const stateJson = JSON.stringify(this.selfState);
247025
- const hash = createHash17("sha256").update(stateJson).digest("hex").slice(0, 32);
247025
+ const hash = createHash20("sha256").update(stateJson).digest("hex").slice(0, 32);
247026
247026
  const cidsPath = join27(this.cwd, ".oa", "identity", "cids.json");
247027
247027
  const cidsData = { latest: "", hash, version: this.selfState.version };
247028
247028
  try {
@@ -516798,6 +516798,148 @@ var init_homeostaticRegulation = __esm({
516798
516798
  }
516799
516799
  });
516800
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
+
516801
516943
  // packages/memory/dist/pprRetrieval.js
516802
516944
  function readEpisodeAffect(metadata) {
516803
516945
  if (!metadata || typeof metadata !== "object")
@@ -516994,14 +517136,30 @@ function retrieveByPPR(query, graph, episodeStore, config) {
516994
517136
  }
516995
517137
  }
516996
517138
  let entries = [...episodeScores.entries()];
516997
- if (cfg.currentEmotionalState) {
517139
+ const engagementWeight = cfg.engagementWeight ?? 0;
517140
+ if (cfg.currentEmotionalState || cfg.influenceFor || engagementWeight !== 0) {
516998
517141
  const current = cfg.currentEmotionalState;
516999
517142
  entries = entries.map(([epId, payload]) => {
517000
517143
  const ep = episodeStore.get(epId);
517001
- const memoryAffect = ep ? readEpisodeAffect(ep.metadata) : null;
517002
- if (!memoryAffect)
517003
- return [epId, payload];
517004
- return [epId, { ...payload, score: modulateRetrievalScore(payload.score, current, memoryAffect) }];
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 }];
517005
517163
  });
517006
517164
  }
517007
517165
  const ranked = entries.sort((a2, b) => b[1].score - a2[1].score).slice(0, cfg.topK);
@@ -517025,6 +517183,8 @@ var init_pprRetrieval = __esm({
517025
517183
  "use strict";
517026
517184
  init_zettelkasten();
517027
517185
  init_homeostaticRegulation();
517186
+ init_socialInfluence();
517187
+ init_embodiedTrace();
517028
517188
  DEFAULT_CONFIG4 = {
517029
517189
  damping: 0.5,
517030
517190
  maxIterations: 50,
@@ -517050,6 +517210,28 @@ function readEpisodeAffect2(metadata) {
517050
517210
  return null;
517051
517211
  return sanitizeEmotionalState(affect);
517052
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
+ }
517053
517235
  function sanitizeImportance(raw, fallback = 5) {
517054
517236
  if (typeof raw !== "number" || !Number.isFinite(raw))
517055
517237
  return fallback;
@@ -517118,6 +517300,7 @@ var init_episodeStore = __esm({
517118
517300
  init_db();
517119
517301
  init_zettelkasten();
517120
517302
  init_homeostaticRegulation();
517303
+ init_socialInfluence();
517121
517304
  init_pprRetrieval();
517122
517305
  DECAY_TAU = {
517123
517306
  session: 36e5,
@@ -517139,6 +517322,38 @@ var init_episodeStore = __esm({
517139
517322
  graph = null;
517140
517323
  /** WO-AM-05: Zettelkasten config for neighbor linking */
517141
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
+ }
517341
+ /** MEM_PATH item #2: bump reuse_count for an episode. Called by the
517342
+ * orchestrator when an episode that was retrieved is detected to have
517343
+ * been mentioned in a subsequent assistant turn. Idempotent on missing
517344
+ * ids (no row → no-op). Returns the new count, or null if not found. */
517345
+ bumpReuseCount(id, delta = 1) {
517346
+ const safeDelta = Number.isFinite(delta) ? delta : 1;
517347
+ try {
517348
+ const result = this.db.prepare(`UPDATE episodes SET reuse_count = COALESCE(reuse_count, 0) + ? WHERE id = ?`).run(safeDelta, id);
517349
+ if (result.changes === 0)
517350
+ return null;
517351
+ const row = this.db.prepare(`SELECT reuse_count FROM episodes WHERE id = ?`).get(id);
517352
+ return row?.reuse_count ?? null;
517353
+ } catch {
517354
+ return null;
517355
+ }
517356
+ }
517142
517357
  constructor(dbPath, graph, zettelConfig) {
517143
517358
  const dir = dbPath === ":memory:" ? null : join75(dbPath, "..");
517144
517359
  if (dir && !existsSync59(dir))
@@ -517178,6 +517393,10 @@ var init_episodeStore = __esm({
517178
517393
  this.db.exec(`ALTER TABLE episodes ADD COLUMN clip_embedding BLOB`);
517179
517394
  } catch {
517180
517395
  }
517396
+ try {
517397
+ this.db.exec(`ALTER TABLE episodes ADD COLUMN reuse_count INTEGER DEFAULT 0`);
517398
+ } catch {
517399
+ }
517181
517400
  this.db.pragma("journal_mode = WAL");
517182
517401
  this.db.pragma("synchronous = NORMAL");
517183
517402
  }
@@ -517190,6 +517409,9 @@ var init_episodeStore = __esm({
517190
517409
  const rawImportance = ep.importance ?? autoImportance(ep.toolName ?? null, modality, ep.content);
517191
517410
  const modulated = ep.emotionalState ? modulateImportance(sanitizeImportance(rawImportance), ep.emotionalState) : sanitizeImportance(rawImportance);
517192
517411
  const importance = sanitizeImportance(modulated);
517412
+ if (this.importanceFloor > 0 && importance < this.importanceFloor) {
517413
+ return "";
517414
+ }
517193
517415
  const decayClass = ep.decayClass ?? autoDecayClass(ep.toolName ?? null, modality, ep.content);
517194
517416
  const existing = this.db.prepare("SELECT id FROM episodes WHERE content_hash = ? AND session_id = ? LIMIT 1").get(contentHash, ep.sessionId ?? null);
517195
517417
  if (existing)
@@ -517314,7 +517536,18 @@ var init_episodeStore = __esm({
517314
517536
  if (opts.currentEmotionalState) {
517315
517537
  const memoryAffect = readEpisodeAffect2(ep.metadata);
517316
517538
  if (memoryAffect) {
517317
- score = modulateRetrievalScore(baseScore, opts.currentEmotionalState, memoryAffect);
517539
+ score = modulateRetrievalScore(score, opts.currentEmotionalState, memoryAffect);
517540
+ }
517541
+ }
517542
+ if (opts.influenceFor) {
517543
+ const ctx3 = opts.influenceFor(ep);
517544
+ if (ctx3)
517545
+ score = applyInfluence(score, ctx3);
517546
+ }
517547
+ if ((opts.engagementWeight ?? 0) !== 0) {
517548
+ const eng = readEpisodeEngagement(ep.metadata);
517549
+ if (eng != null) {
517550
+ score = score * (1 + (eng - 0.5) * (opts.engagementWeight ?? 0));
517318
517551
  }
517319
517552
  }
517320
517553
  return { episode: ep, score };
@@ -517429,7 +517662,8 @@ var init_episodeStore = __esm({
517429
517662
  lastRetrieved: row.last_retrieved,
517430
517663
  clipEmbedding: row.clip_embedding ? new Float32Array(new Uint8Array(row.clip_embedding).buffer) : null,
517431
517664
  gist: row.gist,
517432
- sourceEpisodeId: row.source_episode_id
517665
+ sourceEpisodeId: row.source_episode_id,
517666
+ reuseCount: typeof row.reuse_count === "number" ? row.reuse_count : 0
517433
517667
  };
517434
517668
  }
517435
517669
  };
@@ -520702,7 +520936,7 @@ var init_selfModel = __esm({
520702
520936
  });
520703
520937
 
520704
520938
  // packages/memory/dist/predictionStore.js
520705
- function clamp012(x) {
520939
+ function clamp014(x) {
520706
520940
  if (!Number.isFinite(x))
520707
520941
  return 0.5;
520708
520942
  if (x < 0)
@@ -520733,7 +520967,7 @@ function durationError(predicted, actual) {
520733
520967
  return 0;
520734
520968
  const safePred = Math.max(predicted, 50);
520735
520969
  const ratio = Math.abs(predicted - actual) / safePred;
520736
- return clamp012(ratio);
520970
+ return clamp014(ratio);
520737
520971
  }
520738
520972
  var DEFAULT_AXIS_WEIGHTS, PredictionStore;
520739
520973
  var init_predictionStore = __esm({
@@ -520759,7 +520993,7 @@ var init_predictionStore = __esm({
520759
520993
  predict(p2) {
520760
520994
  const sanitized = {
520761
520995
  ...p2,
520762
- predictedConfidence: clamp012(p2.predictedConfidence),
520996
+ predictedConfidence: clamp014(p2.predictedConfidence),
520763
520997
  predictedDuration: p2.predictedDuration != null && Number.isFinite(p2.predictedDuration) ? Math.max(0, p2.predictedDuration) : null
520764
520998
  };
520765
520999
  this.pending.set(p2.correlationId, sanitized);
@@ -520773,14 +521007,14 @@ var init_predictionStore = __esm({
520773
521007
  this.pending.delete(correlationId);
520774
521008
  const actualDuration = observed.actualDuration != null && Number.isFinite(observed.actualDuration) ? Math.max(0, observed.actualDuration) : null;
520775
521009
  const sim = tokenSimilarity(pred.predictedOutcome, observed.actualOutcome);
520776
- const outcomeErr = clamp012(1 - sim);
521010
+ const outcomeErr = clamp014(1 - sim);
520777
521011
  const successErr = pred.predictedSuccess === observed.actualSuccess ? 0 : 1;
520778
- const confidenceErr = clamp012(observed.actualSuccess ? 1 - pred.predictedConfidence : pred.predictedConfidence);
521012
+ const confidenceErr = clamp014(observed.actualSuccess ? 1 - pred.predictedConfidence : pred.predictedConfidence);
520779
521013
  const durationErr = durationError(pred.predictedDuration, actualDuration);
520780
521014
  const w = this.axisWeights;
520781
521015
  const total = w.outcome * outcomeErr + w.success * successErr + w.confidence * confidenceErr + w.duration * durationErr;
520782
521016
  const sumWeights = w.outcome + w.success + w.confidence + w.duration;
520783
- const errorMagnitude = clamp012(sumWeights > 0 ? total / sumWeights : 0);
521017
+ const errorMagnitude = clamp014(sumWeights > 0 ? total / sumWeights : 0);
520784
521018
  const errorByAxis = {
520785
521019
  outcome: outcomeErr,
520786
521020
  success: successErr,
@@ -520798,7 +521032,7 @@ var init_predictionStore = __esm({
520798
521032
  errorByAxis,
520799
521033
  dominantAxis,
520800
521034
  // Learning signal: large errors with high confidence drive bigger updates
520801
- learningSignal: clamp012(errorMagnitude * (0.5 + 0.5 * pred.predictedConfidence))
521035
+ learningSignal: clamp014(errorMagnitude * (0.5 + 0.5 * pred.predictedConfidence))
520802
521036
  };
520803
521037
  this.history.push(err);
520804
521038
  if (this.history.length > this.capacity) {
@@ -520945,7 +521179,7 @@ var init_predictionStore = __esm({
520945
521179
  errorMagnitude: r2.error_magnitude ?? 0,
520946
521180
  errorByAxis: axes,
520947
521181
  dominantAxis: r2.dominant_axis ?? "outcome",
520948
- learningSignal: clamp012((r2.error_magnitude ?? 0) * 0.75)
521182
+ learningSignal: clamp014((r2.error_magnitude ?? 0) * 0.75)
520949
521183
  });
520950
521184
  }
520951
521185
  }
@@ -520953,90 +521187,6 @@ var init_predictionStore = __esm({
520953
521187
  }
520954
521188
  });
520955
521189
 
520956
- // packages/memory/dist/embodiedTrace.js
520957
- function clamp2(x, lo, hi) {
520958
- if (!Number.isFinite(x))
520959
- return (lo + hi) / 2;
520960
- if (x < lo)
520961
- return lo;
520962
- if (x > hi)
520963
- return hi;
520964
- return x;
520965
- }
520966
- function clamp013(x) {
520967
- return clamp2(x, 0, 1);
520968
- }
520969
- function nonNegative(x) {
520970
- if (!Number.isFinite(x) || x < 0)
520971
- return 0;
520972
- return x;
520973
- }
520974
- function buildTrace(input) {
520975
- const i2 = input ?? {};
520976
- const used = nonNegative(i2.contextTokensUsed ?? DEFAULT_TRACE.contextTokensUsed);
520977
- const max = nonNegative(i2.contextTokensMax ?? DEFAULT_TRACE.contextTokensMax);
520978
- const derivedLoad = max > 0 ? used / max : 0;
520979
- const load2 = i2.cognitiveLoad != null ? clamp013(i2.cognitiveLoad) : clamp013(derivedLoad);
520980
- return {
520981
- durationMs: nonNegative(i2.durationMs ?? DEFAULT_TRACE.durationMs),
520982
- hesitationCount: Math.max(0, Math.floor(i2.hesitationCount ?? 0)),
520983
- retryCount: Math.max(0, Math.floor(i2.retryCount ?? 0)),
520984
- intensity: clamp013(i2.intensity ?? DEFAULT_TRACE.intensity),
520985
- visualGist: typeof i2.visualGist === "string" ? i2.visualGist : void 0,
520986
- auditoryGist: typeof i2.auditoryGist === "string" ? i2.auditoryGist : void 0,
520987
- screenState: typeof i2.screenState === "string" ? i2.screenState : void 0,
520988
- confidence: clamp013(i2.confidence ?? DEFAULT_TRACE.confidence),
520989
- cognitiveLoad: load2,
520990
- contextTokensUsed: used,
520991
- contextTokensMax: max,
520992
- affect: sanitizeEmotionalState(i2.affect ?? NEUTRAL_AFFECT),
520993
- timeOfDay: clamp2(Math.floor(i2.timeOfDay ?? DEFAULT_TRACE.timeOfDay), 0, 23),
520994
- sessionDurationMin: nonNegative(i2.sessionDurationMin ?? 0),
520995
- consecutiveActions: Math.max(0, Math.floor(i2.consecutiveActions ?? 0))
520996
- };
520997
- }
520998
- function attachTrace(metadata, trace) {
520999
- return { ...metadata ?? {}, [EMBODIED_KEY]: trace };
521000
- }
521001
- function extractTrace(metadata) {
521002
- if (!metadata || typeof metadata !== "object")
521003
- return null;
521004
- const raw = metadata[EMBODIED_KEY];
521005
- if (!raw || typeof raw !== "object")
521006
- return null;
521007
- return buildTrace(raw);
521008
- }
521009
- function engagementScore(trace) {
521010
- const alertness = 1 - trace.cognitiveLoad;
521011
- return clamp013((trace.intensity + alertness + trace.confidence) / 3);
521012
- }
521013
- function wasHesitant(trace, threshold = 0.4) {
521014
- return trace.hesitationCount >= 2 || trace.retryCount >= 1 || trace.confidence < threshold;
521015
- }
521016
- var NEUTRAL_AFFECT, DEFAULT_TRACE, EMBODIED_KEY;
521017
- var init_embodiedTrace = __esm({
521018
- "packages/memory/dist/embodiedTrace.js"() {
521019
- "use strict";
521020
- init_homeostaticRegulation();
521021
- NEUTRAL_AFFECT = { valence: 0, arousal: 0 };
521022
- DEFAULT_TRACE = {
521023
- durationMs: 0,
521024
- hesitationCount: 0,
521025
- retryCount: 0,
521026
- intensity: 0,
521027
- confidence: 0.5,
521028
- cognitiveLoad: 0,
521029
- contextTokensUsed: 0,
521030
- contextTokensMax: 0,
521031
- affect: NEUTRAL_AFFECT,
521032
- timeOfDay: 0,
521033
- sessionDurationMin: 0,
521034
- consecutiveActions: 0
521035
- };
521036
- EMBODIED_KEY = "embodiedTrace";
521037
- }
521038
- });
521039
-
521040
521190
  // packages/memory/dist/sleepConsolidation.js
521041
521191
  function slowWaveReplay(db, options2 = {}) {
521042
521192
  const topK = options2.topK ?? 20;
@@ -521118,10 +521268,11 @@ function remDream(db, options2 = {}) {
521118
521268
  return { cycle: emptyCycle("rem", start2) };
521119
521269
  }
521120
521270
  const walkDepth = Math.max(1, options2.walkDepth ?? 3);
521271
+ const minSim = options2.minSimilarity ?? 0.6;
521121
521272
  for (const seed of seedRows) {
521122
- let temporalNeighbors = [];
521273
+ let candidateRows = [];
521123
521274
  try {
521124
- temporalNeighbors = db.prepare(`SELECT id FROM episodes
521275
+ candidateRows = db.prepare(`SELECT id, embedding, timestamp AS ts FROM episodes
521125
521276
  WHERE session_id IS (SELECT session_id FROM episodes WHERE id = ?)
521126
521277
  AND id != ?
521127
521278
  ORDER BY timestamp DESC
@@ -521129,11 +521280,40 @@ function remDream(db, options2 = {}) {
521129
521280
  } catch {
521130
521281
  continue;
521131
521282
  }
521132
- if (temporalNeighbors.length > walkDepth) {
521133
- const target = temporalNeighbors[walkDepth];
521283
+ if (candidateRows.length === 0)
521284
+ continue;
521285
+ let seedEmb = null;
521286
+ try {
521287
+ seedEmb = db.prepare(`SELECT embedding FROM episodes WHERE id = ?`).get(seed.id)?.embedding ?? null;
521288
+ } catch {
521289
+ }
521290
+ let chosen = null;
521291
+ const seedFloat = toFloat32(seedEmb);
521292
+ if (seedFloat) {
521293
+ const distantCandidates = candidateRows.slice(walkDepth);
521294
+ let bestSim = minSim;
521295
+ let bestId = null;
521296
+ for (const cand of distantCandidates) {
521297
+ const candFloat = toFloat32(cand.embedding);
521298
+ if (!candFloat || candFloat.length !== seedFloat.length)
521299
+ continue;
521300
+ const sim = cosineSim(seedFloat, candFloat);
521301
+ if (sim > bestSim) {
521302
+ bestSim = sim;
521303
+ bestId = cand.id;
521304
+ }
521305
+ }
521306
+ if (bestId) {
521307
+ chosen = { id: bestId, reason: `rem-embedding-similarity:${bestSim.toFixed(3)}` };
521308
+ }
521309
+ }
521310
+ if (!chosen && candidateRows.length > walkDepth) {
521311
+ const target = candidateRows[walkDepth];
521134
521312
  if (target)
521135
- novel.push({ from: seed.id, to: target.id, reason: "rem-temporal-distance" });
521313
+ chosen = { id: target.id, reason: "rem-temporal-distance" };
521136
521314
  }
521315
+ if (chosen)
521316
+ novel.push({ from: seed.id, to: chosen.id, reason: chosen.reason });
521137
521317
  }
521138
521318
  if (options2.graph && novel.length > 0) {
521139
521319
  for (const link of novel) {
@@ -521196,6 +521376,27 @@ function lightSleep(db, options2 = {}) {
521196
521376
  }
521197
521377
  } catch {
521198
521378
  }
521379
+ const promotedToDaily = [];
521380
+ const promotedToProcedural = [];
521381
+ try {
521382
+ const sessionPromos = db.prepare(`SELECT id FROM episodes WHERE decay_class = 'session' AND COALESCE(reuse_count, 0) >= 3 LIMIT 200`).all();
521383
+ for (const r2 of sessionPromos) {
521384
+ try {
521385
+ db.prepare(`UPDATE episodes SET decay_class = 'daily' WHERE id = ?`).run(r2.id);
521386
+ promotedToDaily.push(r2.id);
521387
+ } catch {
521388
+ }
521389
+ }
521390
+ const dailyPromos = db.prepare(`SELECT id FROM episodes WHERE decay_class = 'daily' AND COALESCE(reuse_count, 0) >= 8 LIMIT 200`).all();
521391
+ for (const r2 of dailyPromos) {
521392
+ try {
521393
+ db.prepare(`UPDATE episodes SET decay_class = 'procedural' WHERE id = ?`).run(r2.id);
521394
+ promotedToProcedural.push(r2.id);
521395
+ } catch {
521396
+ }
521397
+ }
521398
+ } catch {
521399
+ }
521199
521400
  const pruned = [];
521200
521401
  const compressed = [];
521201
521402
  const compressMode = !!options2.compressInsteadOfPrune;
@@ -521278,10 +521479,12 @@ function lightSleep(db, options2 = {}) {
521278
521479
  downscaledEpisodes: downscaled.map((r2) => r2.id),
521279
521480
  prunedEpisodes: pruned,
521280
521481
  novelAssociations: [],
521281
- energyCost: downscaled.length + pruned.length + compressed.length + flaggedHubs.length,
521482
+ energyCost: downscaled.length + pruned.length + compressed.length + flaggedHubs.length + promotedToDaily.length + promotedToProcedural.length,
521282
521483
  compressedEpisodes: compressed,
521283
521484
  flaggedHubs,
521284
- integratedNodes: []
521485
+ integratedNodes: [],
521486
+ promotedToDaily,
521487
+ promotedToProcedural
521285
521488
  }
521286
521489
  };
521287
521490
  }
@@ -521311,6 +521514,42 @@ function emptyCycle(phase, start2) {
521311
521514
  integratedNodes: []
521312
521515
  };
521313
521516
  }
521517
+ function toFloat32(raw) {
521518
+ if (raw == null)
521519
+ return null;
521520
+ if (raw instanceof Float32Array) {
521521
+ return new Float32Array(raw);
521522
+ }
521523
+ if (raw instanceof Uint8Array) {
521524
+ if (raw.byteLength === 0 || raw.byteLength % 4 !== 0)
521525
+ return null;
521526
+ const fresh = new Uint8Array(raw.byteLength);
521527
+ fresh.set(raw);
521528
+ return new Float32Array(fresh.buffer, 0, raw.byteLength / 4);
521529
+ }
521530
+ if (raw instanceof ArrayBuffer) {
521531
+ if (raw.byteLength === 0 || raw.byteLength % 4 !== 0)
521532
+ return null;
521533
+ return new Float32Array(raw.slice(0));
521534
+ }
521535
+ return null;
521536
+ }
521537
+ function cosineSim(a2, b) {
521538
+ if (a2.length !== b.length || a2.length === 0)
521539
+ return 0;
521540
+ let dot = 0, na = 0, nb = 0;
521541
+ for (let i2 = 0; i2 < a2.length; i2++) {
521542
+ const x = a2[i2];
521543
+ const y = b[i2];
521544
+ dot += x * y;
521545
+ na += x * x;
521546
+ nb += y * y;
521547
+ }
521548
+ const denom = Math.sqrt(na) * Math.sqrt(nb);
521549
+ if (denom === 0)
521550
+ return 0;
521551
+ return dot / denom;
521552
+ }
521314
521553
  function episodeCount(db) {
521315
521554
  try {
521316
521555
  const row = db.prepare(`SELECT COUNT(*) AS c FROM episodes`).get();
@@ -521328,7 +521567,7 @@ var init_sleepConsolidation = __esm({
521328
521567
 
521329
521568
  // packages/memory/dist/socialMemory.js
521330
521569
  import { randomUUID as randomUUID11 } from "node:crypto";
521331
- function clamp3(x, lo, hi) {
521570
+ function clamp4(x, lo, hi) {
521332
521571
  if (!Number.isFinite(x))
521333
521572
  return (lo + hi) / 2;
521334
521573
  if (x < lo)
@@ -521337,19 +521576,19 @@ function clamp3(x, lo, hi) {
521337
521576
  return hi;
521338
521577
  return x;
521339
521578
  }
521340
- function clamp014(x) {
521341
- return clamp3(x, 0, 1);
521579
+ function clamp015(x) {
521580
+ return clamp4(x, 0, 1);
521342
521581
  }
521343
521582
  function clampSigned(x) {
521344
- return clamp3(x, -1, 1);
521583
+ return clamp4(x, -1, 1);
521345
521584
  }
521346
521585
  function sanitizeBig5(p2) {
521347
521586
  return {
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)
521587
+ openness: clamp015(p2?.openness ?? NEUTRAL_BIG5.openness),
521588
+ conscientiousness: clamp015(p2?.conscientiousness ?? NEUTRAL_BIG5.conscientiousness),
521589
+ extraversion: clamp015(p2?.extraversion ?? NEUTRAL_BIG5.extraversion),
521590
+ agreeableness: clamp015(p2?.agreeableness ?? NEUTRAL_BIG5.agreeableness),
521591
+ neuroticism: clamp015(p2?.neuroticism ?? NEUTRAL_BIG5.neuroticism)
521353
521592
  };
521354
521593
  }
521355
521594
  function pairKey(a2, b) {
@@ -521468,13 +521707,13 @@ var init_socialMemory = __esm({
521468
521707
  const id = input.id ?? randomUUID11();
521469
521708
  const existing = this.getAgent(id);
521470
521709
  const personality = sanitizeBig5({ ...existing?.personality ?? {}, ...input.personality ?? {} });
521471
- const trustOverall = clamp014(input.trust?.overall ?? existing?.trust.overall ?? 0.5);
521710
+ const trustOverall = clamp015(input.trust?.overall ?? existing?.trust.overall ?? 0.5);
521472
521711
  const trustByDomain = {
521473
521712
  ...existing?.trust.byDomain ?? {},
521474
521713
  ...input.trust?.byDomain ?? {}
521475
521714
  };
521476
521715
  for (const k of Object.keys(trustByDomain))
521477
- trustByDomain[k] = clamp014(trustByDomain[k]);
521716
+ trustByDomain[k] = clamp015(trustByDomain[k]);
521478
521717
  const metadata = input.metadata ?? existing?.metadata ?? null;
521479
521718
  if (existing) {
521480
521719
  this.db.prepare(`UPDATE social_agents
@@ -521514,13 +521753,13 @@ var init_socialMemory = __esm({
521514
521753
  const agent = this.getAgent(agentId);
521515
521754
  if (!agent)
521516
521755
  return null;
521517
- const weight = clamp014(interaction.weight ?? 0.1);
521756
+ const weight = clamp015(interaction.weight ?? 0.1);
521518
521757
  const targetOverall = interaction.positive ? 1 : 0;
521519
- const newOverall = clamp014(agent.trust.overall + (targetOverall - agent.trust.overall) * weight);
521758
+ const newOverall = clamp015(agent.trust.overall + (targetOverall - agent.trust.overall) * weight);
521520
521759
  const newByDomain = { ...agent.trust.byDomain };
521521
521760
  if (interaction.domain) {
521522
521761
  const cur = newByDomain[interaction.domain] ?? 0.5;
521523
- newByDomain[interaction.domain] = clamp014(cur + (targetOverall - cur) * weight);
521762
+ newByDomain[interaction.domain] = clamp015(cur + (targetOverall - cur) * weight);
521524
521763
  }
521525
521764
  const now = Date.now();
521526
521765
  this.db.prepare(`UPDATE social_agents
@@ -521550,14 +521789,14 @@ var init_socialMemory = __esm({
521550
521789
  history.push(newEvent);
521551
521790
  if (history.length > 200)
521552
521791
  history.splice(0, history.length - 200);
521553
- const strength = clamp014(existing.strength + Math.abs(dStrength));
521792
+ const strength = clamp015(existing.strength + Math.abs(dStrength));
521554
521793
  const valence = clampSigned(existing.valence + dValence);
521555
- const reciprocity = clamp014(existing.reciprocity * 0.95 + 0.05 * 0.5);
521794
+ const reciprocity = clamp015(existing.reciprocity * 0.95 + 0.05 * 0.5);
521556
521795
  this.db.prepare(`UPDATE social_relationships
521557
521796
  SET strength = ?, valence = ?, reciprocity = ?, last_updated = ?, history = ?
521558
521797
  WHERE agent_a = ? AND agent_b = ?`).run(strength, valence, reciprocity, now, JSON.stringify(history), lo, hi);
521559
521798
  } else {
521560
- const strength = clamp014(Math.abs(dStrength));
521799
+ const strength = clamp015(Math.abs(dStrength));
521561
521800
  const valence = clampSigned(dValence);
521562
521801
  this.db.prepare(`INSERT INTO social_relationships
521563
521802
  (agent_a, agent_b, strength, valence, reciprocity, last_updated, history)
@@ -521580,7 +521819,7 @@ var init_socialMemory = __esm({
521580
521819
  recordLesson(input) {
521581
521820
  const id = randomUUID11();
521582
521821
  const now = Date.now();
521583
- const conf = clamp014(input.confidence ?? 0.5);
521822
+ const conf = clamp015(input.confidence ?? 0.5);
521584
521823
  const adopted = input.adopted ? 1 : 0;
521585
521824
  this.db.prepare(`INSERT INTO social_lessons (id, source_agent, lesson, confidence, adopted, timestamp)
521586
521825
  VALUES (?, ?, ?, ?, ?, ?)`).run(id, input.sourceAgent, input.lesson, conf, adopted, now);
@@ -521598,7 +521837,7 @@ var init_socialMemory = __esm({
521598
521837
  recordOpinion(input) {
521599
521838
  const id = randomUUID11();
521600
521839
  const now = Date.now();
521601
- const conf = clamp014(input.confidence ?? 0.5);
521840
+ const conf = clamp015(input.confidence ?? 0.5);
521602
521841
  this.db.prepare(`INSERT INTO social_shared_knowledge (id, topic, agent_id, opinion, confidence, timestamp)
521603
521842
  VALUES (?, ?, ?, ?, ?, ?)`).run(id, input.topic, input.agentId, input.opinion, conf, now);
521604
521843
  return { id, topic: input.topic, agentId: input.agentId, opinion: input.opinion, confidence: conf, timestamp: now };
@@ -521733,60 +521972,564 @@ var init_memoryStageContext = __esm({
521733
521972
  }
521734
521973
  });
521735
521974
 
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;
521975
+ // packages/memory/dist/sessionGist.js
521976
+ import { createHash as createHash9 } from "node:crypto";
521977
+ function inferDomain(input) {
521978
+ const blob = [
521979
+ input.goal,
521980
+ input.workingDirectory ?? "",
521981
+ input.topToolNames.join(" "),
521982
+ input.topErrorPatterns.join(" ")
521983
+ ].join(" ").toLowerCase();
521984
+ const scores = {};
521985
+ for (const [domain, kws] of Object.entries(DOMAIN_KEYWORDS)) {
521986
+ let s2 = 0;
521987
+ for (const kw of kws)
521988
+ if (blob.includes(kw))
521989
+ s2++;
521990
+ if (s2 > 0)
521991
+ scores[domain] = s2;
521992
+ }
521993
+ const ranked = Object.entries(scores).sort((a2, b) => b[1] - a2[1]);
521994
+ if (ranked.length === 0)
521995
+ return "general";
521996
+ if (ranked.length >= 2 && ranked[0][1] === ranked[1][1])
521997
+ return "mixed";
521998
+ return ranked[0][0];
521745
521999
  }
521746
- function clamp015(x) {
521747
- return clamp4(x, 0, 1);
522000
+ function computeGoalHash(goal) {
522001
+ return createHash9("sha256").update(goal.trim().toLowerCase()).digest("hex").slice(0, 16);
521748
522002
  }
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;
522003
+ function clip(text, n2) {
522004
+ if (!text)
522005
+ return "";
522006
+ const t2 = text.replace(/\s+/g, " ").trim();
522007
+ return t2.length <= n2 ? t2 : t2.slice(0, Math.max(0, n2 - 1)) + "…";
522008
+ }
522009
+ function buildGist(input) {
522010
+ const goalHash = computeGoalHash(input.goal);
522011
+ const domain = inferDomain(input);
522012
+ const goalClip = clip(input.goal, 60);
522013
+ const tools = input.topToolNames.slice(0, 3).join("/") || "none";
522014
+ const errs = input.topErrorPatterns.slice(0, 3).join(",") || "none";
522015
+ const learned = clip(input.whatWorked[0] ?? "", 60);
522016
+ const durMin = Math.round(input.durationMs / 6e4);
522017
+ const status = input.finalStatus;
522018
+ const parts = [
522019
+ `Session goal=${goalClip}`,
522020
+ `domain=${domain}`,
522021
+ `${input.toolCallCount}x tools (${tools})`,
522022
+ `${input.errorCount}x errs`,
522023
+ `pain=${errs}`,
522024
+ `${durMin}min`,
522025
+ `outcome=${status}`,
522026
+ `learned=${learned || "none"}`
522027
+ ];
522028
+ let content = parts.join("; ");
522029
+ if (content.length > 280)
522030
+ content = content.slice(0, 279) + "…";
522031
+ return {
522032
+ content,
522033
+ goalHash,
522034
+ metadata: {
522035
+ kind: "session_gist",
522036
+ domain,
522037
+ toolCount: input.toolCallCount,
522038
+ errorCount: input.errorCount,
522039
+ finalStatus: input.finalStatus,
522040
+ durationMs: input.durationMs,
522041
+ goalHash
522042
+ }
522043
+ };
521755
522044
  }
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;
522045
+ function goalHashOf(goal) {
522046
+ return computeGoalHash(goal);
521760
522047
  }
521761
- function noveltyBias(memoryDivergence, weight = 0.3) {
521762
- const d2 = clamp015(memoryDivergence);
521763
- const w = clamp015(weight);
521764
- return 1 + d2 * w;
522048
+ function isSessionGist(metadata) {
522049
+ if (!metadata || typeof metadata !== "object")
522050
+ return false;
522051
+ const m2 = metadata;
522052
+ return m2["kind"] === "session_gist" && typeof m2["goalHash"] === "string";
521765
522053
  }
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;
522054
+ var DOMAIN_KEYWORDS;
522055
+ var init_sessionGist = __esm({
522056
+ "packages/memory/dist/sessionGist.js"() {
522057
+ "use strict";
522058
+ DOMAIN_KEYWORDS = {
522059
+ typescript: ["tsc", "typescript", ".ts", ".tsx", "vitest", "jest"],
522060
+ node: ["npm", "pnpm", "yarn", "node_modules", "package.json", "node "],
522061
+ python: ["python", ".py", "pytest", "pip ", "poetry", "uv "],
522062
+ golang: [" go ", "go test", "go build", "go.mod"],
522063
+ rust: ["cargo", "rustc", ".rs", "rust "],
522064
+ shell: ["bash", "shell", "/bin/", "curl", "grep"],
522065
+ docs: ["readme", ".md", "markdown", "doc"],
522066
+ threejs: ["three.js", "three ", "webgl", "shader"]
522067
+ };
522068
+ }
522069
+ });
522070
+
522071
+ // packages/memory/dist/selfTrust.js
522072
+ function inferDomainFromEpisode(ep) {
522073
+ const md = ep.metadata && typeof ep.metadata === "object" ? ep.metadata : null;
522074
+ if (md && typeof md["domain"] === "string" && md["domain"])
522075
+ return md["domain"];
522076
+ const blob = [ep.toolName ?? "", ep.content ?? ""].join(" ").toLowerCase();
522077
+ if (!blob.trim())
522078
+ return "general";
522079
+ let best = null;
522080
+ for (const [name10, kws] of Object.entries(DOMAIN_KEYWORDS2)) {
522081
+ let s2 = 0;
522082
+ for (const kw of kws)
522083
+ if (blob.includes(kw))
522084
+ s2++;
522085
+ if (s2 > 0 && (!best || s2 > best.score))
522086
+ best = { name: name10, score: s2 };
522087
+ }
522088
+ return best?.name ?? "general";
522089
+ }
522090
+ function selfTrustFor(domain, calibration) {
522091
+ if (!domain || !calibration || !calibration.byDomain)
522092
+ return 0.7;
522093
+ const d2 = calibration.byDomain[domain];
522094
+ if (!d2 || d2.n < 3)
522095
+ return 0.7;
522096
+ const overconfBy = d2.confidence - d2.accuracy;
522097
+ if (overconfBy >= 0.3)
522098
+ return 0.4;
522099
+ return 1;
522100
+ }
522101
+ function buildSelfTrustInfluence(calibration) {
522102
+ if (!calibration)
522103
+ return null;
522104
+ return (ep) => {
522105
+ const domain = inferDomainFromEpisode(ep);
522106
+ const trust = selfTrustFor(domain, calibration);
522107
+ return { sourceTrust: trust };
522108
+ };
521771
522109
  }
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);
522110
+ var DOMAIN_KEYWORDS2;
522111
+ var init_selfTrust = __esm({
522112
+ "packages/memory/dist/selfTrust.js"() {
522113
+ "use strict";
522114
+ DOMAIN_KEYWORDS2 = {
522115
+ typescript: ["tsc", "typescript", ".ts", ".tsx", "vitest", "jest"],
522116
+ node: ["npm", "pnpm", "yarn", "node_modules", "package.json", "node "],
522117
+ python: ["python", ".py", "pytest", "pip ", "poetry"],
522118
+ golang: [" go ", "go test", "go build", "go.mod"],
522119
+ rust: ["cargo", "rustc", ".rs"],
522120
+ shell: ["bash", "shell", "/bin/", "curl"],
522121
+ docs: ["readme", ".md", "markdown"],
522122
+ threejs: ["three.js", "webgl", "shader"]
522123
+ };
521776
522124
  }
521777
- if (ctx3.sourceTrust != null) {
521778
- m2 *= authorityBias(ctx3.sourceTrust, ctx3.weights?.authority);
522125
+ });
522126
+
522127
+ // packages/memory/dist/toolOutcomes.js
522128
+ var MAX_PER_KEY, DEFAULT_WINDOW_MS, ToolOutcomeTracker;
522129
+ var init_toolOutcomes = __esm({
522130
+ "packages/memory/dist/toolOutcomes.js"() {
522131
+ "use strict";
522132
+ MAX_PER_KEY = 500;
522133
+ DEFAULT_WINDOW_MS = 6 * 60 * 60 * 1e3;
522134
+ ToolOutcomeTracker = class {
522135
+ byKey = /* @__PURE__ */ new Map();
522136
+ key(tool, domain) {
522137
+ return `${tool}::${domain}`;
522138
+ }
522139
+ /** Append an outcome. Trims to MAX_PER_KEY (oldest dropped). */
522140
+ record(o2) {
522141
+ const k = this.key(o2.tool, o2.domain);
522142
+ const arr = this.byKey.get(k) ?? [];
522143
+ arr.push(o2);
522144
+ if (arr.length > MAX_PER_KEY)
522145
+ arr.splice(0, arr.length - MAX_PER_KEY);
522146
+ this.byKey.set(k, arr);
522147
+ }
522148
+ /**
522149
+ * Recent success rate for (tool, domain) within `windowMs`. Returns
522150
+ * null when fewer than `minSamples` recent outcomes (default 5) —
522151
+ * caller treats null as "insufficient data, skip forecasting".
522152
+ */
522153
+ recentRate(tool, domain, windowMs = DEFAULT_WINDOW_MS, minSamples = 5) {
522154
+ const arr = this.byKey.get(this.key(tool, domain));
522155
+ if (!arr || arr.length === 0)
522156
+ return null;
522157
+ const cutoff = Date.now() - windowMs;
522158
+ let n2 = 0, succ = 0;
522159
+ for (const o2 of arr) {
522160
+ if (o2.ts >= cutoff) {
522161
+ n2++;
522162
+ if (o2.success)
522163
+ succ++;
522164
+ }
522165
+ }
522166
+ if (n2 < minSamples)
522167
+ return null;
522168
+ return { n: n2, rate: succ / n2 };
522169
+ }
522170
+ /**
522171
+ * All-time stats. Returns rate even with low n (caller decides).
522172
+ * If domain is omitted, aggregates across all domains for that tool.
522173
+ */
522174
+ stats(tool, domain) {
522175
+ let n2 = 0, succ = 0;
522176
+ if (domain) {
522177
+ const arr = this.byKey.get(this.key(tool, domain)) ?? [];
522178
+ for (const o2 of arr) {
522179
+ n2++;
522180
+ if (o2.success)
522181
+ succ++;
522182
+ }
522183
+ } else {
522184
+ for (const [k, arr] of this.byKey.entries()) {
522185
+ if (!k.startsWith(tool + "::"))
522186
+ continue;
522187
+ for (const o2 of arr) {
522188
+ n2++;
522189
+ if (o2.success)
522190
+ succ++;
522191
+ }
522192
+ }
522193
+ }
522194
+ return { n: n2, rate: n2 === 0 ? 0 : succ / n2 };
522195
+ }
522196
+ /** Total outcomes recorded across all keys. */
522197
+ size() {
522198
+ let n2 = 0;
522199
+ for (const arr of this.byKey.values())
522200
+ n2 += arr.length;
522201
+ return n2;
522202
+ }
522203
+ /** Reset (e.g., on session start before restoring from store). */
522204
+ clear() {
522205
+ this.byKey.clear();
522206
+ }
522207
+ };
521779
522208
  }
521780
- if (ctx3.memoryDivergence != null) {
521781
- m2 *= noveltyBias(ctx3.memoryDivergence, ctx3.weights?.novelty);
522209
+ });
522210
+
522211
+ // packages/memory/dist/stagnationRecipes.js
522212
+ import { createHash as createHash10 } from "node:crypto";
522213
+ function fingerprintSignature(fp) {
522214
+ const normClusters = (fp.errorClusters ?? []).map((s2) => (s2 || "").toLowerCase().replace(/[0-9]+/g, "N").replace(/\s+/g, " ").trim()).filter(Boolean).sort();
522215
+ const tool = (fp.stuckTool ?? "").toLowerCase().trim();
522216
+ const blob = `tool=${tool};clusters=${normClusters.join("|")}`;
522217
+ return createHash10("sha256").update(blob).digest("hex").slice(0, 16);
522218
+ }
522219
+ function crystallize(store2, input) {
522220
+ const sig = fingerprintSignature(input.fingerprint);
522221
+ const content = [
522222
+ `When stuck on ${(input.fingerprint.errorClusters[0] || "<unknown>").slice(0, 60)}`,
522223
+ input.fingerprint.stuckTool ? `with tool=${input.fingerprint.stuckTool}` : "",
522224
+ input.toolShift ? `, switching ${input.toolShift.from}→${input.toolShift.to}` : "",
522225
+ ` worked: ${input.whatWorked.slice(0, 100)}`
522226
+ ].filter(Boolean).join(" ");
522227
+ return store2.insert({
522228
+ modality: "reflection",
522229
+ toolName: "stagnation_recipe",
522230
+ content,
522231
+ importance: 8,
522232
+ decayClass: "procedural",
522233
+ metadata: {
522234
+ kind: "stagnation_recipe",
522235
+ signature: sig,
522236
+ errorClusters: input.fingerprint.errorClusters.slice(0, 3),
522237
+ stuckTool: input.fingerprint.stuckTool ?? null,
522238
+ toolShift: input.toolShift ?? null
522239
+ }
522240
+ });
522241
+ }
522242
+ function lookupBySignature(store2, signature, limit = 3) {
522243
+ const lim = Math.max(1, Math.min(20, limit));
522244
+ try {
522245
+ const db = store2.getDb();
522246
+ const rows = db.prepare(`SELECT id, content, metadata, timestamp FROM episodes
522247
+ WHERE tool_name = 'stagnation_recipe'
522248
+ ORDER BY timestamp DESC
522249
+ LIMIT 200`).all();
522250
+ const out = [];
522251
+ for (const r2 of rows) {
522252
+ try {
522253
+ const m2 = r2.metadata ? JSON.parse(r2.metadata) : null;
522254
+ if (m2 && m2.signature === signature) {
522255
+ out.push({ id: r2.id, content: r2.content, signature: m2.signature, ts: r2.timestamp });
522256
+ if (out.length >= lim)
522257
+ break;
522258
+ }
522259
+ } catch {
522260
+ }
522261
+ }
522262
+ return out;
522263
+ } catch {
522264
+ return [];
521782
522265
  }
521783
- if (ctx3.relationshipStrength != null && ctx3.relationshipValence != null) {
521784
- m2 *= reciprocityBias(ctx3.relationshipStrength, ctx3.relationshipValence, ctx3.weights?.reciprocity);
522266
+ }
522267
+ var init_stagnationRecipes = __esm({
522268
+ "packages/memory/dist/stagnationRecipes.js"() {
522269
+ "use strict";
521785
522270
  }
521786
- return baseScore * m2;
522271
+ });
522272
+
522273
+ // packages/memory/dist/codebaseMap.js
522274
+ import { createHash as createHash11, randomUUID as randomUUID12 } from "node:crypto";
522275
+ function freshNodeId() {
522276
+ return randomUUID12();
521787
522277
  }
521788
- var init_socialInfluence = __esm({
521789
- "packages/memory/dist/socialInfluence.js"() {
522278
+ var CodebaseMap;
522279
+ var init_codebaseMap = __esm({
522280
+ "packages/memory/dist/codebaseMap.js"() {
522281
+ "use strict";
522282
+ CodebaseMap = class {
522283
+ db;
522284
+ repoFp;
522285
+ touchCount = /* @__PURE__ */ new Map();
522286
+ constructor(db, repoRoot, commitSha) {
522287
+ this.db = db;
522288
+ this.repoFp = createHash11("sha256").update(`${repoRoot}::${commitSha ?? "no-commit"}`).digest("hex").slice(0, 16);
522289
+ this.ensureSchema();
522290
+ }
522291
+ ensureSchema() {
522292
+ try {
522293
+ this.db.exec(`
522294
+ CREATE TABLE IF NOT EXISTS codebase_map_node (
522295
+ id TEXT PRIMARY KEY,
522296
+ repo_fp TEXT NOT NULL,
522297
+ kind TEXT NOT NULL,
522298
+ path TEXT NOT NULL,
522299
+ last_touched_ts INTEGER,
522300
+ last_result TEXT,
522301
+ metadata TEXT
522302
+ );
522303
+ CREATE INDEX IF NOT EXISTS idx_cmnode_fp ON codebase_map_node(repo_fp);
522304
+ CREATE INDEX IF NOT EXISTS idx_cmnode_path ON codebase_map_node(path);
522305
+ CREATE TABLE IF NOT EXISTS codebase_map_edge (
522306
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
522307
+ repo_fp TEXT NOT NULL,
522308
+ src_id TEXT NOT NULL,
522309
+ dst_id TEXT NOT NULL,
522310
+ relation TEXT NOT NULL,
522311
+ ts INTEGER NOT NULL
522312
+ );
522313
+ CREATE INDEX IF NOT EXISTS idx_cmedge_fp ON codebase_map_edge(repo_fp);
522314
+ `);
522315
+ } catch {
522316
+ }
522317
+ }
522318
+ fingerprint() {
522319
+ return this.repoFp;
522320
+ }
522321
+ /** Restore in-memory caches. Returns counts for caller status. */
522322
+ restore() {
522323
+ let nodes = 0;
522324
+ let edges = 0;
522325
+ try {
522326
+ const rows = this.db.prepare(`SELECT path FROM codebase_map_node WHERE repo_fp = ?`).all(this.repoFp);
522327
+ nodes = rows.length;
522328
+ for (const r2 of rows) {
522329
+ this.touchCount.set(r2.path, 1);
522330
+ }
522331
+ const erows = this.db.prepare(`SELECT COUNT(*) AS c FROM codebase_map_edge WHERE repo_fp = ?`).get(this.repoFp);
522332
+ edges = erows?.c ?? 0;
522333
+ } catch {
522334
+ }
522335
+ return { nodes, edges };
522336
+ }
522337
+ noteFile(path8, op) {
522338
+ if (!path8)
522339
+ return;
522340
+ this.touchCount.set(path8, (this.touchCount.get(path8) ?? 0) + 1);
522341
+ try {
522342
+ const id = this.idFor("file", path8);
522343
+ const now = Date.now();
522344
+ this.db.prepare(`INSERT INTO codebase_map_node (id, repo_fp, kind, path, last_touched_ts, last_result, metadata)
522345
+ VALUES (?, ?, 'file', ?, ?, ?, ?)
522346
+ ON CONFLICT(id) DO UPDATE SET
522347
+ last_touched_ts = excluded.last_touched_ts,
522348
+ last_result = excluded.last_result,
522349
+ metadata = excluded.metadata`).run(id, this.repoFp, path8, now, op, JSON.stringify({ op, count: this.touchCount.get(path8) ?? 1 }));
522350
+ } catch {
522351
+ }
522352
+ }
522353
+ noteTest(name10, result) {
522354
+ if (!name10)
522355
+ return;
522356
+ try {
522357
+ const id = this.idFor("test", name10);
522358
+ const now = Date.now();
522359
+ this.db.prepare(`INSERT INTO codebase_map_node (id, repo_fp, kind, path, last_touched_ts, last_result, metadata)
522360
+ VALUES (?, ?, 'test', ?, ?, ?, ?)
522361
+ ON CONFLICT(id) DO UPDATE SET
522362
+ last_touched_ts = excluded.last_touched_ts,
522363
+ last_result = excluded.last_result,
522364
+ metadata = excluded.metadata`).run(id, this.repoFp, name10, now, result, JSON.stringify({ result }));
522365
+ } catch {
522366
+ }
522367
+ }
522368
+ noteReference(fromPath, toPath) {
522369
+ if (!fromPath || !toPath || fromPath === toPath)
522370
+ return;
522371
+ try {
522372
+ const srcId = this.idFor("file", fromPath);
522373
+ const dstId = this.idFor("file", toPath);
522374
+ const now = Date.now();
522375
+ this.db.prepare(`INSERT INTO codebase_map_edge (repo_fp, src_id, dst_id, relation, ts) VALUES (?, ?, ?, 'referenced', ?)`).run(this.repoFp, srcId, dstId, now);
522376
+ } catch {
522377
+ }
522378
+ }
522379
+ topFiles(limit = 15) {
522380
+ const lim = Math.max(1, Math.min(100, limit));
522381
+ try {
522382
+ const rows = this.db.prepare(`SELECT path, last_touched_ts, metadata FROM codebase_map_node
522383
+ WHERE repo_fp = ? AND kind = 'file'
522384
+ ORDER BY last_touched_ts DESC
522385
+ LIMIT ?`).all(this.repoFp, lim);
522386
+ const out = [];
522387
+ for (const r2 of rows) {
522388
+ let count = 1;
522389
+ try {
522390
+ const m2 = r2.metadata ? JSON.parse(r2.metadata) : null;
522391
+ if (m2 && typeof m2.count === "number")
522392
+ count = m2.count;
522393
+ } catch {
522394
+ }
522395
+ out.push({ path: r2.path, touchCount: count, lastTs: r2.last_touched_ts });
522396
+ }
522397
+ return out;
522398
+ } catch {
522399
+ return [];
522400
+ }
522401
+ }
522402
+ topTests(limit = 15) {
522403
+ const lim = Math.max(1, Math.min(100, limit));
522404
+ try {
522405
+ const rows = this.db.prepare(`SELECT path AS name, last_result AS result, last_touched_ts AS ts FROM codebase_map_node
522406
+ WHERE repo_fp = ? AND kind = 'test'
522407
+ ORDER BY last_touched_ts DESC
522408
+ LIMIT ?`).all(this.repoFp, lim);
522409
+ return rows.map((r2) => ({ name: r2.name, result: r2.result || "?", ts: r2.ts }));
522410
+ } catch {
522411
+ return [];
522412
+ }
522413
+ }
522414
+ /** Compact one-line summary used for the [CODEBASE MEMORY] inject. */
522415
+ summarize() {
522416
+ const files = this.topFiles(8);
522417
+ const tests = this.topTests(5);
522418
+ const fileLine = files.length > 0 ? files.slice(0, 5).map((f2) => f2.path.split("/").slice(-2).join("/")).join(", ") : "<none>";
522419
+ const testLine = tests.length > 0 ? tests.map((t2) => `${t2.name.split("/").slice(-1)[0]}=${t2.result}`).join(", ") : "<none>";
522420
+ return `repo=${this.repoFp} files-touched=${files.length} (top: ${fileLine}); tests-tracked=${tests.length} (recent: ${testLine})`;
522421
+ }
522422
+ /** Stable composite id: `<kind>:<sha16(path)>` so insert ON CONFLICT works. */
522423
+ idFor(kind, path8) {
522424
+ const h = createHash11("sha256").update(`${this.repoFp}:${kind}:${path8}`).digest("hex").slice(0, 24);
522425
+ return `${kind}-${h}`;
522426
+ }
522427
+ };
522428
+ }
522429
+ });
522430
+
522431
+ // packages/memory/dist/embeddingDrift.js
522432
+ function ensureSchema(db) {
522433
+ try {
522434
+ db.exec(`CREATE TABLE IF NOT EXISTS embedding_meta (
522435
+ id INTEGER PRIMARY KEY CHECK (id = 1),
522436
+ model_name TEXT NOT NULL,
522437
+ dim INTEGER NOT NULL,
522438
+ set_at_ts INTEGER NOT NULL
522439
+ )`);
522440
+ } catch {
522441
+ }
522442
+ }
522443
+ function checkEmbeddingDrift(db, current) {
522444
+ ensureSchema(db);
522445
+ try {
522446
+ const row = db.prepare(`SELECT model_name, dim, set_at_ts FROM embedding_meta WHERE id = 1`).get();
522447
+ if (!row)
522448
+ return { driftDetected: false };
522449
+ const prev = { model: row.model_name, dim: row.dim, ts: row.set_at_ts };
522450
+ const drift = prev.model !== current.model || prev.dim !== current.dim;
522451
+ return { driftDetected: drift, previous: prev };
522452
+ } catch {
522453
+ return { driftDetected: false };
522454
+ }
522455
+ }
522456
+ function recordEmbeddingMeta(db, sig) {
522457
+ ensureSchema(db);
522458
+ try {
522459
+ db.prepare(`INSERT INTO embedding_meta (id, model_name, dim, set_at_ts)
522460
+ VALUES (1, ?, ?, ?)
522461
+ ON CONFLICT(id) DO UPDATE SET
522462
+ model_name = excluded.model_name,
522463
+ dim = excluded.dim,
522464
+ set_at_ts = excluded.set_at_ts`).run(sig.model, sig.dim, Date.now());
522465
+ } catch {
522466
+ }
522467
+ }
522468
+ async function reembedAll(db, embedFn, opts = {}) {
522469
+ const batch2 = Math.max(1, Math.min(500, opts.batchSize ?? 50));
522470
+ let total = 0;
522471
+ try {
522472
+ const r2 = db.prepare(`SELECT COUNT(*) AS c FROM episodes WHERE content IS NOT NULL AND length(content) > 0`).get();
522473
+ total = r2?.c ?? 0;
522474
+ } catch {
522475
+ return { reembedded: 0, skipped: 0, total: 0 };
522476
+ }
522477
+ if (total === 0)
522478
+ return { reembedded: 0, skipped: 0, total: 0 };
522479
+ let done = 0;
522480
+ let reembedded = 0;
522481
+ let skipped = 0;
522482
+ let offset = 0;
522483
+ while (offset < total) {
522484
+ let rows = [];
522485
+ try {
522486
+ rows = db.prepare(`SELECT id, content FROM episodes
522487
+ WHERE content IS NOT NULL AND length(content) > 0
522488
+ ORDER BY rowid ASC LIMIT ? OFFSET ?`).all(batch2, offset);
522489
+ } catch {
522490
+ break;
522491
+ }
522492
+ if (rows.length === 0)
522493
+ break;
522494
+ const updates = [];
522495
+ for (const r2 of rows) {
522496
+ try {
522497
+ const vec = await embedFn(r2.content);
522498
+ if (vec && vec.length > 0) {
522499
+ updates.push({ id: r2.id, vec });
522500
+ } else {
522501
+ skipped++;
522502
+ }
522503
+ } catch {
522504
+ skipped++;
522505
+ }
522506
+ }
522507
+ if (updates.length > 0) {
522508
+ try {
522509
+ const stmt = db.prepare(`UPDATE episodes SET embedding = ? WHERE id = ?`);
522510
+ const tx = db.transaction((batch3) => {
522511
+ for (const u of batch3) {
522512
+ stmt.run(Buffer.from(u.vec.buffer, u.vec.byteOffset, u.vec.byteLength), u.id);
522513
+ }
522514
+ });
522515
+ tx(updates);
522516
+ reembedded += updates.length;
522517
+ } catch {
522518
+ }
522519
+ }
522520
+ done += rows.length;
522521
+ if (opts.onProgress) {
522522
+ try {
522523
+ opts.onProgress(done, total);
522524
+ } catch {
522525
+ }
522526
+ }
522527
+ offset += rows.length;
522528
+ }
522529
+ return { reembedded, skipped, total };
522530
+ }
522531
+ var init_embeddingDrift = __esm({
522532
+ "packages/memory/dist/embeddingDrift.js"() {
521790
522533
  "use strict";
521791
522534
  }
521792
522535
  });
@@ -521804,12 +522547,14 @@ __export(dist_exports2, {
521804
522547
  CRLParser: () => CRLParser,
521805
522548
  CRLTemplateResolver: () => CRLTemplateResolver,
521806
522549
  CRL_SYMBOLS: () => CRL_SYMBOLS,
522550
+ CodebaseMap: () => CodebaseMap,
521807
522551
  ConfidenceTracker: () => ConfidenceTracker,
521808
522552
  DECAY_TAU: () => DECAY_TAU,
521809
522553
  DEFAULT_CRL_CONFIG: () => DEFAULT_CRL_CONFIG,
521810
522554
  DEFAULT_ENCODING: () => DEFAULT_ENCODING,
521811
522555
  DEFAULT_RETRIEVAL: () => DEFAULT_RETRIEVAL,
521812
522556
  DEFAULT_TARGET: () => DEFAULT_TARGET,
522557
+ DEFAULT_WINDOW_MS: () => DEFAULT_WINDOW_MS,
521813
522558
  EmbeddingAligner: () => EmbeddingAligner,
521814
522559
  EpisodeStore: () => EpisodeStore,
521815
522560
  FailureStore: () => FailureStore,
@@ -521824,6 +522569,7 @@ __export(dist_exports2, {
521824
522569
  SocialMemoryStore: () => SocialMemoryStore,
521825
522570
  TaskMemoryStore: () => TaskMemoryStore,
521826
522571
  TemporalGraph: () => TemporalGraph,
522572
+ ToolOutcomeTracker: () => ToolOutcomeTracker,
521827
522573
  ToolPatternStore: () => ToolPatternStore,
521828
522574
  ValidationStore: () => ValidationStore,
521829
522575
  applyInfluence: () => applyInfluence,
@@ -521832,9 +522578,12 @@ __export(dist_exports2, {
521832
522578
  autoDecayClass: () => autoDecayClass,
521833
522579
  autoImportance: () => autoImportance,
521834
522580
  batchLink: () => batchLink,
522581
+ buildGist: () => buildGist,
522582
+ buildSelfTrustInfluence: () => buildSelfTrustInfluence,
521835
522583
  buildTrace: () => buildTrace,
521836
522584
  characteristicsForStage: () => characteristicsForStage,
521837
522585
  checkEmbeddingAvailable: () => checkEmbeddingAvailable,
522586
+ checkEmbeddingDrift: () => checkEmbeddingDrift,
521838
522587
  closeDb: () => closeDb,
521839
522588
  compressAndStore: () => compressAndStore,
521840
522589
  compressToGist: () => compressToGist,
@@ -521843,6 +522592,7 @@ __export(dist_exports2, {
521843
522592
  cosineSimilarity: () => cosineSimilarity2,
521844
522593
  createCRLMemoryStore: () => createCRLMemoryStore,
521845
522594
  createHomeostaticState: () => createHomeostaticState,
522595
+ crystallize: () => crystallize,
521846
522596
  detectStage: () => detectStage,
521847
522597
  developmentalReport: () => report,
521848
522598
  deviationFromTarget: () => deviationFromTarget,
@@ -521853,24 +522603,33 @@ __export(dist_exports2, {
521853
522603
  extractQueryEntities: () => extractQueryEntities,
521854
522604
  extractTrace: () => extractTrace,
521855
522605
  findNeighbors: () => findNeighbors,
522606
+ fingerprintSignature: () => fingerprintSignature,
522607
+ freshNodeId: () => freshNodeId,
521856
522608
  generateEmbedding: () => generateEmbedding,
521857
522609
  generateEmbeddingBatch: () => generateEmbeddingBatch,
521858
522610
  getCRLConfigStore: () => getCRLConfigStore,
522611
+ goalHashOf: () => goalHashOf,
521859
522612
  importanceMultiplier: () => importanceMultiplier,
522613
+ inferDomainFromEpisode: () => inferDomainFromEpisode,
521860
522614
  initDb: () => initDb,
522615
+ isSessionGist: () => isSessionGist,
521861
522616
  lightSleep: () => lightSleep,
521862
522617
  linkEpisode: () => linkEpisode,
522618
+ lookupBySignature: () => lookupBySignature,
521863
522619
  modulateImportance: () => modulateImportance,
521864
522620
  modulateRetrievalScore: () => modulateRetrievalScore,
521865
522621
  noveltyBias: () => noveltyBias,
521866
522622
  observeEmotionalState: () => observeEmotionalState,
521867
522623
  personalizedPageRank: () => personalizedPageRank,
521868
522624
  reciprocityBias: () => reciprocityBias,
522625
+ recordEmbeddingMeta: () => recordEmbeddingMeta,
522626
+ reembedAll: () => reembedAll,
521869
522627
  remDream: () => remDream,
521870
522628
  resetCRLConfigStore: () => resetCRLConfigStore,
521871
522629
  retrieveByPPR: () => retrieveByPPR,
521872
522630
  runConsolidationCycle: () => runConsolidationCycle,
521873
522631
  sanitizeEmotionalState: () => sanitizeEmotionalState,
522632
+ selfTrustFor: () => selfTrustFor,
521874
522633
  slowWaveReplay: () => slowWaveReplay,
521875
522634
  splanifoldCosine: () => cosine,
521876
522635
  splanifoldDeserialize: () => deserialize,
@@ -521914,6 +522673,12 @@ var init_dist7 = __esm({
521914
522673
  init_developmentalStage();
521915
522674
  init_memoryStageContext();
521916
522675
  init_socialInfluence();
522676
+ init_sessionGist();
522677
+ init_selfTrust();
522678
+ init_toolOutcomes();
522679
+ init_stagnationRecipes();
522680
+ init_codebaseMap();
522681
+ init_embeddingDrift();
521917
522682
  }
521918
522683
  });
521919
522684
 
@@ -523547,7 +524312,7 @@ import { existsSync as existsSync66, readFileSync as readFileSync54, statSync as
523547
524312
  import { execSync as execSync45 } from "node:child_process";
523548
524313
  import { homedir as homedir22, platform as platform2, arch as arch2, totalmem as totalmem2, freemem as freemem2, hostname as hostname3 } from "node:os";
523549
524314
  import { join as join82 } from "node:path";
523550
- import { createHash as createHash9 } from "node:crypto";
524315
+ import { createHash as createHash12 } from "node:crypto";
523551
524316
  function capturePreflightSnapshot(workingDir) {
523552
524317
  const warnings = [];
523553
524318
  const configFingerprints = {};
@@ -523714,7 +524479,7 @@ function expandPath(p2) {
523714
524479
  return p2;
523715
524480
  }
523716
524481
  function sha2563(s2) {
523717
- return createHash9("sha256").update(s2).digest("hex").slice(0, 16);
524482
+ return createHash12("sha256").update(s2).digest("hex").slice(0, 16);
523718
524483
  }
523719
524484
  function freeDiskBytes(path8 = "/tmp") {
523720
524485
  try {
@@ -524987,6 +525752,37 @@ var init_agenticRunner = __esm({
524987
525752
  _patchHistoryStore = null;
524988
525753
  _toolSequence = [];
524989
525754
  // Track tool calls for pattern detection
525755
+ // MEM_PATH item #1: per-run signals consumed by sessionGist at task_complete.
525756
+ _runStartTime = 0;
525757
+ _runErrorCount = 0;
525758
+ _runErrorPatterns = [];
525759
+ // top-N short error keys collected this run
525760
+ _runWhatWorked = [];
525761
+ // strings extracted from StuckMetaAnalyzer / lessons
525762
+ // MEM_PATH item #2: retrieved-episode IDs surfaced last turn. The next
525763
+ // assistant turn scans its output for content fingerprints from these
525764
+ // episodes; matches bump reuse_count via episodeStore.bumpReuseCount.
525765
+ _lastRetrievedEpisodes = [];
525766
+ // MEM_PATH item #4: per-(tool, domain) success-rate tracker. Populated
525767
+ // post-tool-result; consulted pre-tool-call to inject [FORECAST]
525768
+ // warnings when historical success rate is low.
525769
+ _toolOutcomeTracker = null;
525770
+ // lazy-init: ToolOutcomeTracker
525771
+ // Track turns where a forecast was emitted so we don't pile on.
525772
+ _lastForecastTurn = -10;
525773
+ // MEM_PATH item #5: most-recent stagnation entry fingerprint. When the
525774
+ // cooldown expires and the next 3 turns succeed, this is consumed by
525775
+ // the crystallization block to persist a recipe. Reset after consumption
525776
+ // (to prevent double-write) or when stagnation re-enters.
525777
+ _pendingStagnationEntry = null;
525778
+ // MEM_PATH item #8: persistent codebase map (lazy-init at session start).
525779
+ _codebaseMap = null;
525780
+ // MEM_PATH item #9: adaptive retrieval cache. When the (goalHash, recent-tool-sig)
525781
+ // hasn't changed since last retrieval, skip the PPR call entirely and reuse
525782
+ // the previous memoryLines.
525783
+ _lastPprSig = null;
525784
+ _lastPprMemoryLines = [];
525785
+ _pprSkipCount = 0;
524990
525786
  // Phase 2 — tool subset expansion and usage tracking.
524991
525787
  // Tools promoted from deferred → inline by tool_search (or by subset
524992
525788
  // expansion). They stay inline for the rest of the run unless idle past
@@ -527116,6 +527912,10 @@ Respond with your assessment, then take action.`;
527116
527912
  modifiedFiles: /* @__PURE__ */ new Map(),
527117
527913
  toolCallCount: 0
527118
527914
  };
527915
+ this._runStartTime = Date.now();
527916
+ this._runErrorCount = 0;
527917
+ this._runErrorPatterns = [];
527918
+ this._runWhatWorked = [];
527119
527919
  this._fileRegistry.clear();
527120
527920
  this._memexArchive.clear();
527121
527921
  this._sessionId = process.env["OA_SESSION_ID"] && String(process.env["OA_SESSION_ID"]) || `session-${Date.now()}`;
@@ -527169,6 +527969,13 @@ Respond with your assessment, then take action.`;
527169
527969
  totalEpisodes,
527170
527970
  creativeAssociationCount: 0
527171
527971
  });
527972
+ if (this._episodeStore) {
527973
+ try {
527974
+ this._episodeStore.setZettelConfig?.(stageCtx.toZettelkastenConfig());
527975
+ this._episodeStore.setImportanceFloor?.(stageCtx.importanceFloor());
527976
+ } catch {
527977
+ }
527978
+ }
527172
527979
  this.emit({
527173
527980
  type: "status",
527174
527981
  content: `Memory stage: ${snap.stage} (importanceFloor=${snap.thresholds.importanceFloor}, linkThreshold=${snap.thresholds.linkThreshold})`,
@@ -527177,6 +527984,46 @@ Respond with your assessment, then take action.`;
527177
527984
  } catch {
527178
527985
  }
527179
527986
  }
527987
+ if (process.env["OA_DISABLE_EMBEDDING_DRIFT_CHECK"] !== "1" && this._episodeStore) {
527988
+ try {
527989
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
527990
+ const currentModel = process.env["OA_EMBEDDING_MODEL"] || "default";
527991
+ const currentDim = parseInt(process.env["OA_EMBEDDING_DIM"] || "0", 10) || 768;
527992
+ const drift = memMod.checkEmbeddingDrift(this._episodeStore.getDb(), { model: currentModel, dim: currentDim });
527993
+ if (drift.driftDetected && drift.previous) {
527994
+ this.emit({
527995
+ type: "status",
527996
+ content: `[EMBEDDING DRIFT] previous=${drift.previous.model}/${drift.previous.dim}d, current=${currentModel}/${currentDim}d — REM cosine similarity will be unreliable until reembedAll runs`,
527997
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
527998
+ });
527999
+ } else if (!drift.previous) {
528000
+ memMod.recordEmbeddingMeta(this._episodeStore.getDb(), { model: currentModel, dim: currentDim });
528001
+ }
528002
+ } catch {
528003
+ }
528004
+ }
528005
+ if (process.env["OA_DISABLE_CODEBASE_MAP"] !== "1" && this._episodeStore && this._workingDirectory) {
528006
+ try {
528007
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
528008
+ let commitSha = "no-commit";
528009
+ try {
528010
+ const { execSync: execSync59 } = await import("node:child_process");
528011
+ commitSha = execSync59("git rev-parse HEAD", { cwd: this._workingDirectory, stdio: ["ignore", "pipe", "ignore"] }).toString().trim().slice(0, 12) || "no-commit";
528012
+ } catch {
528013
+ }
528014
+ const cm = new memMod.CodebaseMap(this._episodeStore.getDb(), this._workingDirectory, commitSha);
528015
+ const restored = cm.restore();
528016
+ this._codebaseMap = cm;
528017
+ if (restored.nodes > 0) {
528018
+ this.emit({
528019
+ type: "status",
528020
+ content: `[CODEBASE MEMORY] restored ${restored.nodes} files / ${restored.edges} edges from prior sessions: ${cm.summarize().slice(0, 220)}`,
528021
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
528022
+ });
528023
+ }
528024
+ } catch {
528025
+ }
528026
+ }
527180
528027
  const contextComposition = await this.assembleContext(task, context2);
527181
528028
  const systemPrompt = contextComposition.assembled;
527182
528029
  this._contextTree = new ContextTree(`sys-${systemPrompt.length}`, cleanedTask.slice(0, 200));
@@ -527513,6 +528360,9 @@ TASK: ${task}` : task;
527513
528360
  minSamples: STAG_MIN_SAMPLES
527514
528361
  })) {
527515
528362
  let _stagBody = buildStagnationDiagnostic(signals);
528363
+ if (process.env["OA_DISABLE_STAGNATION_REPLAN"] !== "1") {
528364
+ _stagBody += "\n\n[STAGNATION REPLAN — required structure]\nYou have made repeated unsuccessful attempts. STOP retrying.\nRespond with EXACTLY this structure before your next tool call:\n\n HYPOTHESES (3 distinct theories why progress stalled):\n 1. ...\n 2. ...\n 3. ...\n PICK: <number 1-3>\n WHY: <one sentence>\n FALSIFICATION: <observable signal that would refute the pick>\n NEXT ACTION: <single tool call to test the picked hypothesis>\n\nIf you cannot list 3 distinct hypotheses, ask the human via task_complete with a 'blocked' summary.";
528365
+ }
527516
528366
  if (this._runLessons.length > 0) {
527517
528367
  const _query = `${this._taskState.goal || ""} ${signals.variantList.join(" ")}`;
527518
528368
  const _topLessons = select2({
@@ -527534,11 +528384,89 @@ TASK: ${task}` : task;
527534
528384
  }
527535
528385
  messages2.push({ role: "system", content: _stagBody });
527536
528386
  stagnationCooldownUntilTurn = turn + 5;
528387
+ try {
528388
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
528389
+ const errClusters = [];
528390
+ try {
528391
+ const ec = this._errorClusterTracker;
528392
+ if (ec && typeof ec.topClusters === "function") {
528393
+ const top = ec.topClusters(3);
528394
+ for (const c9 of top)
528395
+ errClusters.push(c9.pattern);
528396
+ }
528397
+ } catch {
528398
+ }
528399
+ if (errClusters.length === 0 && this._runErrorPatterns.length > 0) {
528400
+ errClusters.push(...this._runErrorPatterns.slice(0, 3));
528401
+ }
528402
+ const stuckTool = this._toolSequence.length > 0 ? this._toolSequence[this._toolSequence.length - 1] : null;
528403
+ const fingerprint = { errorClusters: errClusters.slice(0, 3), stuckTool };
528404
+ this._pendingStagnationEntry = {
528405
+ fingerprint,
528406
+ cooldownExpiresAtTurn: turn + 5,
528407
+ successesSinceExpiry: 0,
528408
+ stuckTool
528409
+ };
528410
+ const sig = memMod.fingerprintSignature(fingerprint);
528411
+ const recipes = this._episodeStore ? memMod.lookupBySignature(this._episodeStore, sig, 1) : [];
528412
+ if (recipes.length > 0) {
528413
+ const r2 = recipes[0];
528414
+ messages2.push({
528415
+ role: "system",
528416
+ content: `[STAGNATION RECIPE — found from prior run with same failure shape]
528417
+ ${r2.content}
528418
+ If this matches your current shape, try it before continuing.`
528419
+ });
528420
+ this.emit({
528421
+ type: "status",
528422
+ content: `[STAGNATION RECIPE] surfaced prior recipe (sig=${sig}) for current failure shape`,
528423
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
528424
+ });
528425
+ }
528426
+ } catch {
528427
+ }
527537
528428
  this.emit({
527538
528429
  type: "status",
527539
528430
  content: `STAGNATION DETECTED — injected diagnostic mode at turn ${turn} (${signals.variantCount} variants, ${signals.failureSum} failures, ${signals.filesDelta} files in window)`,
527540
528431
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
527541
528432
  });
528433
+ try {
528434
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
528435
+ const hs = this._homeostat;
528436
+ if (hs) {
528437
+ const actions = memMod.suggestRegulationActions(hs);
528438
+ for (const a2 of actions) {
528439
+ this.emit({
528440
+ type: "status",
528441
+ content: `[REGULATION SUGGESTION] ${a2} — homeostat is off-target (current valence=${hs.current.valence.toFixed(2)}, arousal=${hs.current.arousal.toFixed(2)}, streak=${hs.streak})`,
528442
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
528443
+ });
528444
+ }
528445
+ }
528446
+ if (this._selfModel && this._episodeStore) {
528447
+ const sm = this._selfModel;
528448
+ const report2 = sm.snapshot();
528449
+ for (const [domain, c9] of Object.entries(report2.calibration.byDomain)) {
528450
+ if (c9.n >= 5 && c9.confidence - c9.accuracy > 0.2) {
528451
+ this.emit({
528452
+ type: "status",
528453
+ 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.`,
528454
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
528455
+ });
528456
+ }
528457
+ }
528458
+ this._episodeStore.insert({
528459
+ sessionId: this._sessionId,
528460
+ modality: "reflection",
528461
+ toolName: "self_model_snapshot",
528462
+ 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}`,
528463
+ importance: 7,
528464
+ decayClass: "session",
528465
+ metadata: { selfReport: report2, stagnationTurn: turn }
528466
+ });
528467
+ }
528468
+ } catch {
528469
+ }
527542
528470
  }
527543
528471
  }
527544
528472
  }
@@ -528390,19 +529318,96 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
528390
529318
  }
528391
529319
  }
528392
529320
  if (turn > 0 && turn % 3 === 0 && this._temporalGraph && this._episodeStore) {
529321
+ let shouldRetrieve = true;
528393
529322
  try {
528394
- const taskGoal = this._taskState.goal || cleanedTask.slice(0, 200);
528395
- const pprResult = retrieveByPPR(taskGoal, this._temporalGraph, this._episodeStore, { topK: 3 });
528396
- if (pprResult.episodes.length > 0) {
528397
- const memoryLines = pprResult.episodes.map(({ episode, pprScore, matchedNodes }) => `- [${episode.toolName ?? episode.modality}] ${episode.content.slice(0, 120)} (via: ${matchedNodes.slice(0, 2).join(", ")})`);
528398
- compacted.push({
528399
- role: "system",
528400
- content: `[Associative Memory — related prior experience]
528401
- ${memoryLines.join("\n")}`
528402
- });
529323
+ if (process.env["OA_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
529324
+ const goalForSig = (this._taskState.goal || "").slice(0, 200);
529325
+ const recentTools = this._toolSequence.slice(-5).join("|");
529326
+ const { createHash: createHash20 } = await import("node:crypto");
529327
+ const sig = createHash20("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
529328
+ if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
529329
+ compacted.push({
529330
+ role: "system",
529331
+ content: `[Associative Memory — related prior experience]
529332
+ ${this._lastPprMemoryLines.join("\n")}`
529333
+ });
529334
+ this._pprSkipCount++;
529335
+ this.emit({
529336
+ type: "status",
529337
+ content: `[ppr-skip] reused previous retrieval (skipCount=${this._pprSkipCount}) — goal+tools unchanged`,
529338
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
529339
+ });
529340
+ shouldRetrieve = false;
529341
+ } else {
529342
+ this._lastPprSig = sig;
529343
+ this._pprSkipCount = 0;
529344
+ }
528403
529345
  }
528404
529346
  } catch {
528405
529347
  }
529348
+ if (!shouldRetrieve) {
529349
+ } else {
529350
+ try {
529351
+ if (this._lastRetrievedEpisodes.length > 0) {
529352
+ const recentAsst = messages2.slice(-10).filter((m2) => m2.role === "assistant" && typeof m2.content === "string").map((m2) => m2.content.toLowerCase()).join(" ");
529353
+ let bumped = 0;
529354
+ for (const { id, fingerprint } of this._lastRetrievedEpisodes) {
529355
+ if (fingerprint && fingerprint.length >= 10 && recentAsst.includes(fingerprint)) {
529356
+ this._episodeStore.bumpReuseCount(id, 1);
529357
+ bumped++;
529358
+ }
529359
+ }
529360
+ if (bumped > 0) {
529361
+ this.emit({
529362
+ type: "status",
529363
+ content: `[reuse] ${bumped} retrieved episode(s) referenced — bumping reuse_count`,
529364
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
529365
+ });
529366
+ }
529367
+ this._lastRetrievedEpisodes = [];
529368
+ }
529369
+ } catch {
529370
+ }
529371
+ try {
529372
+ const taskGoal = this._taskState.goal || cleanedTask.slice(0, 200);
529373
+ const _hs = this._homeostat;
529374
+ let _influenceFor = void 0;
529375
+ try {
529376
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
529377
+ const sm = this._selfModel;
529378
+ if (sm) {
529379
+ const cal = sm.snapshot()?.calibration;
529380
+ const closure = memMod.buildSelfTrustInfluence(cal);
529381
+ if (closure)
529382
+ _influenceFor = closure;
529383
+ }
529384
+ } catch {
529385
+ }
529386
+ const pprResult = retrieveByPPR(taskGoal, this._temporalGraph, this._episodeStore, {
529387
+ topK: 3,
529388
+ currentEmotionalState: _hs?.current,
529389
+ engagementWeight: 0.2,
529390
+ influenceFor: _influenceFor
529391
+ });
529392
+ if (pprResult.episodes.length > 0) {
529393
+ const memoryLines = pprResult.episodes.map(({ episode, pprScore, matchedNodes }) => `- [${episode.toolName ?? episode.modality}] ${episode.content.slice(0, 120)} (via: ${matchedNodes.slice(0, 2).join(", ")})`);
529394
+ compacted.push({
529395
+ role: "system",
529396
+ content: `[Associative Memory — related prior experience]
529397
+ ${memoryLines.join("\n")}`
529398
+ });
529399
+ this._lastRetrievedEpisodes = pprResult.episodes.map(({ episode }) => ({
529400
+ id: episode.id,
529401
+ fingerprint: (episode.content || "").trim().slice(0, 50).toLowerCase()
529402
+ }));
529403
+ this._lastPprMemoryLines = memoryLines;
529404
+ } else {
529405
+ this._lastRetrievedEpisodes = [];
529406
+ this._lastPprMemoryLines = [];
529407
+ }
529408
+ } catch {
529409
+ }
529410
+ }
528406
529411
  }
528407
529412
  if (this.options.environmentProvider) {
528408
529413
  try {
@@ -529160,6 +530165,22 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
529160
530165
  }
529161
530166
  } else {
529162
530167
  const finalArgs = hookCheck.modifiedArgs ?? tc.arguments;
530168
+ if (this._toolOutcomeTracker && process.env["OA_DISABLE_TOOL_FORECAST"] !== "1") {
530169
+ try {
530170
+ const argBlob = JSON.stringify(finalArgs || {}).toLowerCase();
530171
+ const fdomain = /\.tsx?\b|tsc|typescript|vitest|jest/.test(argBlob) ? "typescript" : /\.py\b|pytest|python/.test(argBlob) ? "python" : /\.rs\b|cargo/.test(argBlob) ? "rust" : /\bgo\.mod\b|\.go\b|go test|go build/.test(argBlob) ? "golang" : /node_modules|package\.json|npm |pnpm |yarn /.test(argBlob) ? "node" : "general";
530172
+ const recent = this._toolOutcomeTracker.recentRate(tc.name, fdomain);
530173
+ const inStagnation = stagnationCooldownUntilTurn > turn;
530174
+ const cooldownExpired = turn - this._lastForecastTurn >= 3;
530175
+ if (recent && recent.rate < 0.3 && !inStagnation && cooldownExpired) {
530176
+ this._lastForecastTurn = turn;
530177
+ const fc = `[FORECAST] historical success rate for tool "${tc.name}" in domain "${fdomain}" is ${Math.round(recent.rate * 100)}% over ${recent.n} recent calls. Consider an alternative approach or break the task down before retrying.`;
530178
+ messages2.push({ role: "system", content: fc });
530179
+ this.emit({ type: "status", content: fc, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
530180
+ }
530181
+ } catch {
530182
+ }
530183
+ }
529163
530184
  try {
529164
530185
  if (typeof tool.executeStream === "function") {
529165
530186
  const gen = tool.executeStream(finalArgs);
@@ -529923,6 +530944,103 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
529923
530944
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
529924
530945
  });
529925
530946
  this._taskState.toolCallCount++;
530947
+ if (result && result.success === false) {
530948
+ this._runErrorCount++;
530949
+ const errMsg = result.error || "";
530950
+ if (typeof errMsg === "string" && errMsg.length > 0) {
530951
+ const sig = errMsg.replace(/[0-9]+/g, "N").slice(0, 60);
530952
+ if (!this._runErrorPatterns.includes(sig)) {
530953
+ this._runErrorPatterns.push(sig);
530954
+ if (this._runErrorPatterns.length > 5)
530955
+ this._runErrorPatterns.length = 5;
530956
+ }
530957
+ }
530958
+ try {
530959
+ if (process.env["OA_DISABLE_MIDTURN_RETRIEVAL"] !== "1" && this._episodeStore && stagnationCooldownUntilTurn <= turn && typeof errMsg === "string" && errMsg.length >= 8) {
530960
+ const query = `${tc.name} ${errMsg}`.slice(0, 240);
530961
+ const past = this._episodeStore.search({ query, limit: 2 });
530962
+ const useful = past.filter((p2) => p2.content && p2.content.length > 10).slice(0, 1);
530963
+ if (useful.length > 0) {
530964
+ const u = useful[0];
530965
+ messages2.push({
530966
+ role: "system",
530967
+ content: `[Past-error memory] when "${tc.name}" failed before with similar error, episode said: ${u.content.slice(0, 200)}`
530968
+ });
530969
+ this.emit({
530970
+ type: "status",
530971
+ content: `[midturn] surfaced past-error memory for tool=${tc.name}`,
530972
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
530973
+ });
530974
+ }
530975
+ }
530976
+ } catch {
530977
+ }
530978
+ }
530979
+ try {
530980
+ if (this._pendingStagnationEntry && process.env["OA_DISABLE_STAGNATION_RECIPES"] !== "1") {
530981
+ if (turn > this._pendingStagnationEntry.cooldownExpiresAtTurn) {
530982
+ if (result && result.success !== false) {
530983
+ this._pendingStagnationEntry.successesSinceExpiry++;
530984
+ if (this._pendingStagnationEntry.successesSinceExpiry >= 3 && this._episodeStore) {
530985
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
530986
+ const recoveryTool = tc.name;
530987
+ const stuck = this._pendingStagnationEntry.stuckTool || null;
530988
+ const toolShift = stuck && stuck !== recoveryTool ? { from: stuck, to: recoveryTool } : null;
530989
+ const recId = memMod.crystallize(this._episodeStore, {
530990
+ fingerprint: this._pendingStagnationEntry.fingerprint,
530991
+ toolShift,
530992
+ whatWorked: this._runLessons.slice(-1).map((l2) => l2?.whatWorked).join(" ").slice(0, 120) || `recovered after switching to ${recoveryTool}`
530993
+ });
530994
+ this.emit({
530995
+ type: "status",
530996
+ content: `[STAGNATION CRYSTALLIZED] recipe id=${recId.slice(0, 8)} for failure shape (sig=${memMod.fingerprintSignature(this._pendingStagnationEntry.fingerprint)})`,
530997
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
530998
+ });
530999
+ this._pendingStagnationEntry = null;
531000
+ }
531001
+ } else {
531002
+ this._pendingStagnationEntry.successesSinceExpiry = 0;
531003
+ }
531004
+ }
531005
+ }
531006
+ } catch {
531007
+ }
531008
+ try {
531009
+ if (this._codebaseMap) {
531010
+ const args = tc.arguments || {};
531011
+ const path8 = typeof args.path === "string" ? args.path : "";
531012
+ const command = typeof args.command === "string" ? args.command : "";
531013
+ const isWrite = /^(file_(write|edit|patch)|batch_edit|edit)$/i.test(tc.name);
531014
+ const isRead = /^(file_read|read)$/i.test(tc.name);
531015
+ if (path8)
531016
+ this._codebaseMap.noteFile(path8, isWrite ? "write" : "read");
531017
+ if (command && /\b(vitest|jest|pytest|go test|cargo test)\b/.test(command)) {
531018
+ const ok2 = result && result.success !== false;
531019
+ this._codebaseMap.noteTest(command.slice(0, 80), ok2 ? "pass" : "fail");
531020
+ }
531021
+ if (typeof args.from === "string" && typeof args.to === "string") {
531022
+ this._codebaseMap.noteReference(args.from, args.to);
531023
+ }
531024
+ }
531025
+ } catch {
531026
+ }
531027
+ try {
531028
+ if (process.env["OA_DISABLE_TOOL_FORECAST"] !== "1") {
531029
+ if (!this._toolOutcomeTracker) {
531030
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
531031
+ this._toolOutcomeTracker = new memMod.ToolOutcomeTracker();
531032
+ }
531033
+ const argBlob = JSON.stringify(tc.arguments || {}).toLowerCase();
531034
+ const domain = /\.tsx?\b|tsc|typescript|vitest|jest/.test(argBlob) ? "typescript" : /\.py\b|pytest|python/.test(argBlob) ? "python" : /\.rs\b|cargo/.test(argBlob) ? "rust" : /\bgo\.mod\b|\.go\b|go test|go build/.test(argBlob) ? "golang" : /node_modules|package\.json|npm |pnpm |yarn /.test(argBlob) ? "node" : "general";
531035
+ this._toolOutcomeTracker.record({
531036
+ tool: tc.name,
531037
+ domain,
531038
+ success: result && result.success !== false,
531039
+ ts: Date.now()
531040
+ });
531041
+ }
531042
+ } catch {
531043
+ }
529926
531044
  const filePath = typeof tc.arguments?.path === "string" ? tc.arguments.path : "";
529927
531045
  recordToolExecution(this._appState, tc.name, performance.now() - toolStart, result.success, filePath || void 0);
529928
531046
  if (tc.name === "todo_write") {
@@ -531165,6 +532283,45 @@ Full content available via: repl_exec(code="data = retrieve('${handleId}')") or
531165
532283
  } catch {
531166
532284
  }
531167
532285
  }
532286
+ if (process.env["OA_DISABLE_SESSION_GIST"] !== "1") {
532287
+ try {
532288
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
532289
+ const goal = this._taskState.originalGoal || this._taskState.goal || "";
532290
+ const durationMs2 = this._runStartTime > 0 ? Math.max(0, Date.now() - this._runStartTime) : 0;
532291
+ const toolCounts = /* @__PURE__ */ new Map();
532292
+ for (const t2 of this._toolSequence)
532293
+ toolCounts.set(t2, (toolCounts.get(t2) ?? 0) + 1);
532294
+ const topToolNames = [...toolCounts.entries()].sort((a2, b) => b[1] - a2[1]).slice(0, 3).map(([n2]) => n2);
532295
+ const whatWorked = this._runLessons.slice(-3).map((l2) => l2.whatWorked).filter(Boolean);
532296
+ const finalStatus = completed ? "complete" : this._runErrorCount > this._taskState.toolCallCount * 0.5 ? "abandoned" : "abandoned";
532297
+ const gist2 = memMod.buildGist({
532298
+ goal,
532299
+ durationMs: durationMs2,
532300
+ toolCallCount: this._taskState.toolCallCount,
532301
+ errorCount: this._runErrorCount,
532302
+ finalStatus,
532303
+ topToolNames,
532304
+ topErrorPatterns: this._runErrorPatterns.slice(0, 3),
532305
+ whatWorked,
532306
+ workingDirectory: this._workingDirectory || void 0
532307
+ });
532308
+ this._episodeStore.insert({
532309
+ sessionId: this._sessionId,
532310
+ modality: "gist",
532311
+ toolName: "session_gist",
532312
+ content: gist2.content,
532313
+ importance: 8,
532314
+ decayClass: "procedural",
532315
+ metadata: gist2.metadata
532316
+ });
532317
+ this.emit({
532318
+ type: "status",
532319
+ content: `[SESSION GIST] domain=${gist2.metadata.domain} status=${gist2.metadata.finalStatus} tools=${gist2.metadata.toolCount} errs=${gist2.metadata.errorCount} goalHash=${gist2.goalHash}`,
532320
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
532321
+ });
532322
+ } catch {
532323
+ }
532324
+ }
531168
532325
  if (process.env["OA_DISABLE_PREDICTION_PERSISTENCE"] !== "1") {
531169
532326
  try {
531170
532327
  const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
@@ -540355,7 +541512,7 @@ var require_websocket3 = __commonJS({
540355
541512
  var http6 = __require("http");
540356
541513
  var net5 = __require("net");
540357
541514
  var tls2 = __require("tls");
540358
- var { randomBytes: randomBytes25, createHash: createHash17 } = __require("crypto");
541515
+ var { randomBytes: randomBytes25, createHash: createHash20 } = __require("crypto");
540359
541516
  var { Duplex: Duplex3, Readable } = __require("stream");
540360
541517
  var { URL: URL3 } = __require("url");
540361
541518
  var PerMessageDeflate2 = require_permessage_deflate3();
@@ -541015,7 +542172,7 @@ var require_websocket3 = __commonJS({
541015
542172
  abortHandshake(websocket, socket, "Invalid Upgrade header");
541016
542173
  return;
541017
542174
  }
541018
- const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
542175
+ const digest3 = createHash20("sha1").update(key + GUID).digest("base64");
541019
542176
  if (res.headers["sec-websocket-accept"] !== digest3) {
541020
542177
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
541021
542178
  return;
@@ -541382,7 +542539,7 @@ var require_websocket_server2 = __commonJS({
541382
542539
  var EventEmitter13 = __require("events");
541383
542540
  var http6 = __require("http");
541384
542541
  var { Duplex: Duplex3 } = __require("stream");
541385
- var { createHash: createHash17 } = __require("crypto");
542542
+ var { createHash: createHash20 } = __require("crypto");
541386
542543
  var extension2 = require_extension3();
541387
542544
  var PerMessageDeflate2 = require_permessage_deflate3();
541388
542545
  var subprotocol2 = require_subprotocol2();
@@ -541683,7 +542840,7 @@ var require_websocket_server2 = __commonJS({
541683
542840
  );
541684
542841
  }
541685
542842
  if (this._state > RUNNING) return abortHandshake(socket, 503);
541686
- const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
542843
+ const digest3 = createHash20("sha1").update(key + GUID).digest("base64");
541687
542844
  const headers = [
541688
542845
  "HTTP/1.1 101 Switching Protocols",
541689
542846
  "Upgrade: websocket",
@@ -542743,7 +543900,7 @@ __export(oa_directory_exports, {
542743
543900
  import { existsSync as existsSync73, mkdirSync as mkdirSync39, readFileSync as readFileSync58, writeFileSync as writeFileSync35, readdirSync as readdirSync21, statSync as statSync25, unlinkSync as unlinkSync14, openSync as openSync2, closeSync as closeSync2, renameSync as renameSync3 } from "node:fs";
542744
543901
  import { join as join90, relative as relative8, basename as basename14, dirname as dirname27 } from "node:path";
542745
543902
  import { homedir as homedir26 } from "node:os";
542746
- import { createHash as createHash10 } from "node:crypto";
543903
+ import { createHash as createHash13 } from "node:crypto";
542747
543904
  function findGitRoot(startDir) {
542748
543905
  let dir = startDir;
542749
543906
  const visited = /* @__PURE__ */ new Set();
@@ -543108,7 +544265,7 @@ function buildHandoffPrompt(repoRoot) {
543108
544265
  return lines.join("\n");
543109
544266
  }
543110
544267
  function computeDedupeHash(task, savedAt) {
543111
- return createHash10("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
544268
+ return createHash13("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
543112
544269
  }
543113
544270
  function generateSessionId() {
543114
544271
  const timestamp = Date.now().toString(36);
@@ -571639,7 +572796,7 @@ var init_types = __esm({
571639
572796
  });
571640
572797
 
571641
572798
  // packages/cli/src/tui/p2p/secret-vault.ts
571642
- import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes19, scryptSync as scryptSync2, createHash as createHash11 } from "node:crypto";
572799
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes19, scryptSync as scryptSync2, createHash as createHash14 } from "node:crypto";
571643
572800
  import { readFileSync as readFileSync68, writeFileSync as writeFileSync43, existsSync as existsSync85, mkdirSync as mkdirSync47 } from "node:fs";
571644
572801
  import { dirname as dirname31 } from "node:path";
571645
572802
  var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
@@ -571884,7 +573041,7 @@ var init_secret_vault = __esm({
571884
573041
  /** Generate a deterministic fingerprint of vault contents (for sync verification) */
571885
573042
  fingerprint() {
571886
573043
  const names = Array.from(this.secrets.keys()).sort();
571887
- const hash = createHash11("sha256");
573044
+ const hash = createHash14("sha256");
571888
573045
  for (const name10 of names) {
571889
573046
  hash.update(name10 + ":");
571890
573047
  hash.update(this.secrets.get(name10).value);
@@ -571899,7 +573056,7 @@ var init_secret_vault = __esm({
571899
573056
  // packages/cli/src/tui/p2p/peer-mesh.ts
571900
573057
  import { EventEmitter as EventEmitter7 } from "node:events";
571901
573058
  import { createServer as createServer5 } from "node:http";
571902
- import { randomBytes as randomBytes20, createHash as createHash12, generateKeyPairSync } from "node:crypto";
573059
+ import { randomBytes as randomBytes20, createHash as createHash15, generateKeyPairSync } from "node:crypto";
571903
573060
  var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
571904
573061
  var init_peer_mesh = __esm({
571905
573062
  "packages/cli/src/tui/p2p/peer-mesh.ts"() {
@@ -571916,7 +573073,7 @@ var init_peer_mesh = __esm({
571916
573073
  const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
571917
573074
  this.publicKey = publicKey2.export({ type: "spki", format: "der" });
571918
573075
  this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
571919
- this.peerId = createHash12("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
573076
+ this.peerId = createHash15("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
571920
573077
  this.capabilities = options2.capabilities;
571921
573078
  this.displayName = options2.displayName;
571922
573079
  this._authKey = options2.authKey ?? randomBytes20(24).toString("base64url");
@@ -579796,7 +580953,7 @@ __export(chat_session_exports, {
579796
580953
  startInFlightChat: () => startInFlightChat,
579797
580954
  trackSessionTokens: () => trackSessionTokens
579798
580955
  });
579799
- import { randomUUID as randomUUID12 } from "node:crypto";
580956
+ import { randomUUID as randomUUID13 } from "node:crypto";
579800
580957
  import {
579801
580958
  existsSync as existsSync94,
579802
580959
  readFileSync as readFileSync76,
@@ -579953,7 +581110,7 @@ function getSession(sessionId, model, cwd4) {
579953
581110
  } catch {
579954
581111
  }
579955
581112
  }
579956
- const id = sessionId || randomUUID12();
581113
+ const id = sessionId || randomUUID13();
579957
581114
  const systemPrompt = buildSystemPrompt(cwd4);
579958
581115
  const session = {
579959
581116
  id,
@@ -580220,7 +581377,7 @@ __export(projects_exports, {
580220
581377
  import { readFileSync as readFileSync77, writeFileSync as writeFileSync49, mkdirSync as mkdirSync55, existsSync as existsSync95, statSync as statSync31, renameSync as renameSync6 } from "node:fs";
580221
581378
  import { homedir as homedir35 } from "node:os";
580222
581379
  import { basename as basename20, join as join112, resolve as resolve35 } from "node:path";
580223
- import { randomUUID as randomUUID13 } from "node:crypto";
581380
+ import { randomUUID as randomUUID14 } from "node:crypto";
580224
581381
  function readAll2() {
580225
581382
  try {
580226
581383
  if (!existsSync95(PROJECTS_FILE)) return { projects: [], schemaVersion: 1 };
@@ -580234,7 +581391,7 @@ function readAll2() {
580234
581391
  }
580235
581392
  function writeAll(file) {
580236
581393
  mkdirSync55(OA_DIR3, { recursive: true });
580237
- const tmp = `${PROJECTS_FILE}.${randomUUID13().slice(0, 8)}.tmp`;
581394
+ const tmp = `${PROJECTS_FILE}.${randomUUID14().slice(0, 8)}.tmp`;
580238
581395
  writeFileSync49(tmp, JSON.stringify(file, null, 2), "utf8");
580239
581396
  renameSync6(tmp, PROJECTS_FILE);
580240
581397
  }
@@ -581023,14 +582180,14 @@ var init_access_policy = __esm({
581023
582180
  });
581024
582181
 
581025
582182
  // packages/cli/src/api/project-preferences.ts
581026
- import { createHash as createHash13 } from "node:crypto";
582183
+ import { createHash as createHash16 } from "node:crypto";
581027
582184
  import { existsSync as existsSync96, mkdirSync as mkdirSync56, readFileSync as readFileSync78, renameSync as renameSync7, writeFileSync as writeFileSync50, unlinkSync as unlinkSync22 } from "node:fs";
581028
582185
  import { homedir as homedir36 } from "node:os";
581029
582186
  import { join as join113, resolve as resolve36 } from "node:path";
581030
- import { randomUUID as randomUUID14 } from "node:crypto";
582187
+ import { randomUUID as randomUUID15 } from "node:crypto";
581031
582188
  function projectKey(root) {
581032
582189
  const canonical = resolve36(root);
581033
- return createHash13("sha256").update(canonical).digest("hex").slice(0, 16);
582190
+ return createHash16("sha256").update(canonical).digest("hex").slice(0, 16);
581034
582191
  }
581035
582192
  function projectDir(root) {
581036
582193
  return join113(PROJECTS_DIR, projectKey(root));
@@ -581075,7 +582232,7 @@ function writeProjectPreferences(root, partial) {
581075
582232
  updatedAt: Date.now()
581076
582233
  };
581077
582234
  const file = prefsPath(root);
581078
- const tmp = `${file}.${randomUUID14().slice(0, 8)}.tmp`;
582235
+ const tmp = `${file}.${randomUUID15().slice(0, 8)}.tmp`;
581079
582236
  writeFileSync50(tmp, JSON.stringify(merged, null, 2), "utf8");
581080
582237
  try {
581081
582238
  renameSync7(tmp, file);
@@ -582208,7 +583365,7 @@ var init_disk_task_output = __esm({
582208
583365
  });
582209
583366
 
582210
583367
  // packages/cli/src/api/http.ts
582211
- import { createHash as createHash14 } from "node:crypto";
583368
+ import { createHash as createHash17 } from "node:crypto";
582212
583369
  function problemDetails(opts) {
582213
583370
  const p2 = {
582214
583371
  type: opts.type ?? "about:blank",
@@ -582271,7 +583428,7 @@ function paginated(items, page2, total) {
582271
583428
  }
582272
583429
  function computeEtag(payload) {
582273
583430
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
582274
- const hash = createHash14("sha1").update(json).digest("hex").slice(0, 16);
583431
+ const hash = createHash17("sha1").update(json).digest("hex").slice(0, 16);
582275
583432
  return `W/"${hash}"`;
582276
583433
  }
582277
583434
  function checkNotModified(req2, res, etag) {
@@ -593886,8 +595043,8 @@ import { dirname as dirname36, join as join121, resolve as resolve38 } from "nod
593886
595043
  import { homedir as homedir42 } from "node:os";
593887
595044
  import { spawn as spawn25, execSync as execSync57 } from "node:child_process";
593888
595045
  import { mkdirSync as mkdirSync63, writeFileSync as writeFileSync55, readFileSync as readFileSync85, readdirSync as readdirSync36, existsSync as existsSync105, watch as fsWatch3, renameSync as renameSync8, unlinkSync as unlinkSync24 } from "node:fs";
593889
- import { randomBytes as randomBytes23, randomUUID as randomUUID15 } from "node:crypto";
593890
- import { createHash as createHash16 } from "node:crypto";
595046
+ import { randomBytes as randomBytes23, randomUUID as randomUUID16 } from "node:crypto";
595047
+ import { createHash as createHash19 } from "node:crypto";
593891
595048
  function getVersion3() {
593892
595049
  try {
593893
595050
  const thisDir = dirname36(fileURLToPath17(import.meta.url));
@@ -596971,7 +598128,7 @@ async function handleRequest(req2, res, ollamaUrl, verbose) {
596971
598128
  const urlObj = new URL(req2.url ?? "/", `http://${req2.headers.host ?? "localhost"}`);
596972
598129
  const pathname = urlObj.pathname;
596973
598130
  const startMs = performance.now();
596974
- const requestId = req2.headers["x-request-id"] || randomUUID15();
598131
+ const requestId = req2.headers["x-request-id"] || randomUUID16();
596975
598132
  res.setHeader("X-Request-ID", requestId);
596976
598133
  res.setHeader("X-API-Version", API_VERSION);
596977
598134
  if (method === "OPTIONS") {
@@ -599085,7 +600242,7 @@ function listScheduledTasks() {
599085
600242
  const schedule = String(t2?.schedule || t2?.cron || t2?.when || "");
599086
600243
  const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
599087
600244
  const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
599088
- const fallbackId = createHash16("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
600245
+ const fallbackId = createHash19("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
599089
600246
  const uid = realId || fallbackId;
599090
600247
  const key = `${uid}`;
599091
600248
  if (seen.has(key)) return;
@@ -599202,8 +600359,8 @@ function deleteScheduledById(id) {
599202
600359
  if (id) candidates.push(id);
599203
600360
  if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id)) candidates.push(entry.id);
599204
600361
  try {
599205
- const { createHash: createHash17 } = require3("node:crypto");
599206
- const fallback = createHash17("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
600362
+ const { createHash: createHash20 } = require3("node:crypto");
600363
+ const fallback = createHash20("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
599207
600364
  if (!candidates.includes(fallback)) candidates.push(fallback);
599208
600365
  } catch {
599209
600366
  }
@@ -606610,13 +607767,13 @@ NEW TASK: ${fullInput}`;
606610
607767
  writeContent(() => renderError2(errMsg));
606611
607768
  if (failureStore) {
606612
607769
  try {
606613
- const { createHash: createHash17 } = await import("node:crypto");
607770
+ const { createHash: createHash20 } = await import("node:crypto");
606614
607771
  failureStore.insert({
606615
607772
  taskId: "",
606616
607773
  sessionId: `${Date.now()}`,
606617
607774
  repoRoot,
606618
607775
  failureType: "runtime-error",
606619
- fingerprint: createHash17("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
607776
+ fingerprint: createHash20("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
606620
607777
  filePath: null,
606621
607778
  errorMessage: errMsg.slice(0, 500),
606622
607779
  context: null,