open-agents-ai 0.187.511 → 0.187.513

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 {
@@ -517338,6 +517338,22 @@ var init_episodeStore = __esm({
517338
517338
  setImportanceFloor(floor) {
517339
517339
  this.importanceFloor = Number.isFinite(floor) && floor > 0 ? floor : 0;
517340
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
+ }
517341
517357
  constructor(dbPath, graph, zettelConfig) {
517342
517358
  const dir = dbPath === ":memory:" ? null : join75(dbPath, "..");
517343
517359
  if (dir && !existsSync59(dir))
@@ -517377,6 +517393,10 @@ var init_episodeStore = __esm({
517377
517393
  this.db.exec(`ALTER TABLE episodes ADD COLUMN clip_embedding BLOB`);
517378
517394
  } catch {
517379
517395
  }
517396
+ try {
517397
+ this.db.exec(`ALTER TABLE episodes ADD COLUMN reuse_count INTEGER DEFAULT 0`);
517398
+ } catch {
517399
+ }
517380
517400
  this.db.pragma("journal_mode = WAL");
517381
517401
  this.db.pragma("synchronous = NORMAL");
517382
517402
  }
@@ -517642,7 +517662,8 @@ var init_episodeStore = __esm({
517642
517662
  lastRetrieved: row.last_retrieved,
517643
517663
  clipEmbedding: row.clip_embedding ? new Float32Array(new Uint8Array(row.clip_embedding).buffer) : null,
517644
517664
  gist: row.gist,
517645
- sourceEpisodeId: row.source_episode_id
517665
+ sourceEpisodeId: row.source_episode_id,
517666
+ reuseCount: typeof row.reuse_count === "number" ? row.reuse_count : 0
517646
517667
  };
517647
517668
  }
517648
517669
  };
@@ -521355,6 +521376,27 @@ function lightSleep(db, options2 = {}) {
521355
521376
  }
521356
521377
  } catch {
521357
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
+ }
521358
521400
  const pruned = [];
521359
521401
  const compressed = [];
521360
521402
  const compressMode = !!options2.compressInsteadOfPrune;
@@ -521437,10 +521479,12 @@ function lightSleep(db, options2 = {}) {
521437
521479
  downscaledEpisodes: downscaled.map((r2) => r2.id),
521438
521480
  prunedEpisodes: pruned,
521439
521481
  novelAssociations: [],
521440
- energyCost: downscaled.length + pruned.length + compressed.length + flaggedHubs.length,
521482
+ energyCost: downscaled.length + pruned.length + compressed.length + flaggedHubs.length + promotedToDaily.length + promotedToProcedural.length,
521441
521483
  compressedEpisodes: compressed,
521442
521484
  flaggedHubs,
521443
- integratedNodes: []
521485
+ integratedNodes: [],
521486
+ promotedToDaily,
521487
+ promotedToProcedural
521444
521488
  }
521445
521489
  };
521446
521490
  }
@@ -521928,6 +521972,568 @@ var init_memoryStageContext = __esm({
521928
521972
  }
521929
521973
  });
521930
521974
 
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];
521999
+ }
522000
+ function computeGoalHash(goal) {
522001
+ return createHash9("sha256").update(goal.trim().toLowerCase()).digest("hex").slice(0, 16);
522002
+ }
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
+ };
522044
+ }
522045
+ function goalHashOf(goal) {
522046
+ return computeGoalHash(goal);
522047
+ }
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";
522053
+ }
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
+ };
522109
+ }
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
+ };
522124
+ }
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
+ };
522208
+ }
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 [];
522265
+ }
522266
+ }
522267
+ var init_stagnationRecipes = __esm({
522268
+ "packages/memory/dist/stagnationRecipes.js"() {
522269
+ "use strict";
522270
+ }
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();
522277
+ }
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"() {
522533
+ "use strict";
522534
+ }
522535
+ });
522536
+
521931
522537
  // packages/memory/dist/index.js
521932
522538
  var dist_exports2 = {};
521933
522539
  __export(dist_exports2, {
@@ -521941,12 +522547,14 @@ __export(dist_exports2, {
521941
522547
  CRLParser: () => CRLParser,
521942
522548
  CRLTemplateResolver: () => CRLTemplateResolver,
521943
522549
  CRL_SYMBOLS: () => CRL_SYMBOLS,
522550
+ CodebaseMap: () => CodebaseMap,
521944
522551
  ConfidenceTracker: () => ConfidenceTracker,
521945
522552
  DECAY_TAU: () => DECAY_TAU,
521946
522553
  DEFAULT_CRL_CONFIG: () => DEFAULT_CRL_CONFIG,
521947
522554
  DEFAULT_ENCODING: () => DEFAULT_ENCODING,
521948
522555
  DEFAULT_RETRIEVAL: () => DEFAULT_RETRIEVAL,
521949
522556
  DEFAULT_TARGET: () => DEFAULT_TARGET,
522557
+ DEFAULT_WINDOW_MS: () => DEFAULT_WINDOW_MS,
521950
522558
  EmbeddingAligner: () => EmbeddingAligner,
521951
522559
  EpisodeStore: () => EpisodeStore,
521952
522560
  FailureStore: () => FailureStore,
@@ -521961,6 +522569,7 @@ __export(dist_exports2, {
521961
522569
  SocialMemoryStore: () => SocialMemoryStore,
521962
522570
  TaskMemoryStore: () => TaskMemoryStore,
521963
522571
  TemporalGraph: () => TemporalGraph,
522572
+ ToolOutcomeTracker: () => ToolOutcomeTracker,
521964
522573
  ToolPatternStore: () => ToolPatternStore,
521965
522574
  ValidationStore: () => ValidationStore,
521966
522575
  applyInfluence: () => applyInfluence,
@@ -521969,9 +522578,12 @@ __export(dist_exports2, {
521969
522578
  autoDecayClass: () => autoDecayClass,
521970
522579
  autoImportance: () => autoImportance,
521971
522580
  batchLink: () => batchLink,
522581
+ buildGist: () => buildGist,
522582
+ buildSelfTrustInfluence: () => buildSelfTrustInfluence,
521972
522583
  buildTrace: () => buildTrace,
521973
522584
  characteristicsForStage: () => characteristicsForStage,
521974
522585
  checkEmbeddingAvailable: () => checkEmbeddingAvailable,
522586
+ checkEmbeddingDrift: () => checkEmbeddingDrift,
521975
522587
  closeDb: () => closeDb,
521976
522588
  compressAndStore: () => compressAndStore,
521977
522589
  compressToGist: () => compressToGist,
@@ -521980,6 +522592,7 @@ __export(dist_exports2, {
521980
522592
  cosineSimilarity: () => cosineSimilarity2,
521981
522593
  createCRLMemoryStore: () => createCRLMemoryStore,
521982
522594
  createHomeostaticState: () => createHomeostaticState,
522595
+ crystallize: () => crystallize,
521983
522596
  detectStage: () => detectStage,
521984
522597
  developmentalReport: () => report,
521985
522598
  deviationFromTarget: () => deviationFromTarget,
@@ -521990,24 +522603,33 @@ __export(dist_exports2, {
521990
522603
  extractQueryEntities: () => extractQueryEntities,
521991
522604
  extractTrace: () => extractTrace,
521992
522605
  findNeighbors: () => findNeighbors,
522606
+ fingerprintSignature: () => fingerprintSignature,
522607
+ freshNodeId: () => freshNodeId,
521993
522608
  generateEmbedding: () => generateEmbedding,
521994
522609
  generateEmbeddingBatch: () => generateEmbeddingBatch,
521995
522610
  getCRLConfigStore: () => getCRLConfigStore,
522611
+ goalHashOf: () => goalHashOf,
521996
522612
  importanceMultiplier: () => importanceMultiplier,
522613
+ inferDomainFromEpisode: () => inferDomainFromEpisode,
521997
522614
  initDb: () => initDb,
522615
+ isSessionGist: () => isSessionGist,
521998
522616
  lightSleep: () => lightSleep,
521999
522617
  linkEpisode: () => linkEpisode,
522618
+ lookupBySignature: () => lookupBySignature,
522000
522619
  modulateImportance: () => modulateImportance,
522001
522620
  modulateRetrievalScore: () => modulateRetrievalScore,
522002
522621
  noveltyBias: () => noveltyBias,
522003
522622
  observeEmotionalState: () => observeEmotionalState,
522004
522623
  personalizedPageRank: () => personalizedPageRank,
522005
522624
  reciprocityBias: () => reciprocityBias,
522625
+ recordEmbeddingMeta: () => recordEmbeddingMeta,
522626
+ reembedAll: () => reembedAll,
522006
522627
  remDream: () => remDream,
522007
522628
  resetCRLConfigStore: () => resetCRLConfigStore,
522008
522629
  retrieveByPPR: () => retrieveByPPR,
522009
522630
  runConsolidationCycle: () => runConsolidationCycle,
522010
522631
  sanitizeEmotionalState: () => sanitizeEmotionalState,
522632
+ selfTrustFor: () => selfTrustFor,
522011
522633
  slowWaveReplay: () => slowWaveReplay,
522012
522634
  splanifoldCosine: () => cosine,
522013
522635
  splanifoldDeserialize: () => deserialize,
@@ -522051,6 +522673,12 @@ var init_dist7 = __esm({
522051
522673
  init_developmentalStage();
522052
522674
  init_memoryStageContext();
522053
522675
  init_socialInfluence();
522676
+ init_sessionGist();
522677
+ init_selfTrust();
522678
+ init_toolOutcomes();
522679
+ init_stagnationRecipes();
522680
+ init_codebaseMap();
522681
+ init_embeddingDrift();
522054
522682
  }
522055
522683
  });
522056
522684
 
@@ -523684,7 +524312,7 @@ import { existsSync as existsSync66, readFileSync as readFileSync54, statSync as
523684
524312
  import { execSync as execSync45 } from "node:child_process";
523685
524313
  import { homedir as homedir22, platform as platform2, arch as arch2, totalmem as totalmem2, freemem as freemem2, hostname as hostname3 } from "node:os";
523686
524314
  import { join as join82 } from "node:path";
523687
- import { createHash as createHash9 } from "node:crypto";
524315
+ import { createHash as createHash12 } from "node:crypto";
523688
524316
  function capturePreflightSnapshot(workingDir) {
523689
524317
  const warnings = [];
523690
524318
  const configFingerprints = {};
@@ -523851,7 +524479,7 @@ function expandPath(p2) {
523851
524479
  return p2;
523852
524480
  }
523853
524481
  function sha2563(s2) {
523854
- return createHash9("sha256").update(s2).digest("hex").slice(0, 16);
524482
+ return createHash12("sha256").update(s2).digest("hex").slice(0, 16);
523855
524483
  }
523856
524484
  function freeDiskBytes(path8 = "/tmp") {
523857
524485
  try {
@@ -525124,6 +525752,45 @@ var init_agenticRunner = __esm({
525124
525752
  _patchHistoryStore = null;
525125
525753
  _toolSequence = [];
525126
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
+ // REG-58 (root-cause from stax stuck-loop triage): track the most recent
525781
+ // turn where a *creative* edit landed (file_write / file_edit / batch_edit
525782
+ // / file_patch). When too many turns elapse without one, the agent is in
525783
+ // "exploration without action" mode — read-loops on the same file at
525784
+ // different offsets, repeated tsc invocations producing identical errors,
525785
+ // etc. Fires stagnation independent of failure/variant thresholds because
525786
+ // those metrics get diluted by successful file_reads.
525787
+ _lastFileWriteTurn = -1;
525788
+ // MEM_PATH item #9: adaptive retrieval cache. When the (goalHash, recent-tool-sig)
525789
+ // hasn't changed since last retrieval, skip the PPR call entirely and reuse
525790
+ // the previous memoryLines.
525791
+ _lastPprSig = null;
525792
+ _lastPprMemoryLines = [];
525793
+ _pprSkipCount = 0;
525127
525794
  // Phase 2 — tool subset expansion and usage tracking.
525128
525795
  // Tools promoted from deferred → inline by tool_search (or by subset
525129
525796
  // expansion). They stay inline for the rest of the run unless idle past
@@ -527253,6 +527920,11 @@ Respond with your assessment, then take action.`;
527253
527920
  modifiedFiles: /* @__PURE__ */ new Map(),
527254
527921
  toolCallCount: 0
527255
527922
  };
527923
+ this._runStartTime = Date.now();
527924
+ this._runErrorCount = 0;
527925
+ this._runErrorPatterns = [];
527926
+ this._runWhatWorked = [];
527927
+ this._lastFileWriteTurn = -1;
527256
527928
  this._fileRegistry.clear();
527257
527929
  this._memexArchive.clear();
527258
527930
  this._sessionId = process.env["OA_SESSION_ID"] && String(process.env["OA_SESSION_ID"]) || `session-${Date.now()}`;
@@ -527321,6 +527993,46 @@ Respond with your assessment, then take action.`;
527321
527993
  } catch {
527322
527994
  }
527323
527995
  }
527996
+ if (process.env["OA_DISABLE_EMBEDDING_DRIFT_CHECK"] !== "1" && this._episodeStore) {
527997
+ try {
527998
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
527999
+ const currentModel = process.env["OA_EMBEDDING_MODEL"] || "default";
528000
+ const currentDim = parseInt(process.env["OA_EMBEDDING_DIM"] || "0", 10) || 768;
528001
+ const drift = memMod.checkEmbeddingDrift(this._episodeStore.getDb(), { model: currentModel, dim: currentDim });
528002
+ if (drift.driftDetected && drift.previous) {
528003
+ this.emit({
528004
+ type: "status",
528005
+ content: `[EMBEDDING DRIFT] previous=${drift.previous.model}/${drift.previous.dim}d, current=${currentModel}/${currentDim}d — REM cosine similarity will be unreliable until reembedAll runs`,
528006
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
528007
+ });
528008
+ } else if (!drift.previous) {
528009
+ memMod.recordEmbeddingMeta(this._episodeStore.getDb(), { model: currentModel, dim: currentDim });
528010
+ }
528011
+ } catch {
528012
+ }
528013
+ }
528014
+ if (process.env["OA_DISABLE_CODEBASE_MAP"] !== "1" && this._episodeStore && this._workingDirectory) {
528015
+ try {
528016
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
528017
+ let commitSha = "no-commit";
528018
+ try {
528019
+ const { execSync: execSync59 } = await import("node:child_process");
528020
+ commitSha = execSync59("git rev-parse HEAD", { cwd: this._workingDirectory, stdio: ["ignore", "pipe", "ignore"] }).toString().trim().slice(0, 12) || "no-commit";
528021
+ } catch {
528022
+ }
528023
+ const cm = new memMod.CodebaseMap(this._episodeStore.getDb(), this._workingDirectory, commitSha);
528024
+ const restored = cm.restore();
528025
+ this._codebaseMap = cm;
528026
+ if (restored.nodes > 0) {
528027
+ this.emit({
528028
+ type: "status",
528029
+ content: `[CODEBASE MEMORY] restored ${restored.nodes} files / ${restored.edges} edges from prior sessions: ${cm.summarize().slice(0, 220)}`,
528030
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
528031
+ });
528032
+ }
528033
+ } catch {
528034
+ }
528035
+ }
527324
528036
  const contextComposition = await this.assembleContext(task, context2);
527325
528037
  const systemPrompt = contextComposition.assembled;
527326
528038
  this._contextTree = new ContextTree(`sys-${systemPrompt.length}`, cleanedTask.slice(0, 200));
@@ -527625,6 +528337,32 @@ TASK: ${task}` : task;
527625
528337
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
527626
528338
  });
527627
528339
  }
528340
+ const REG58_NO_WRITE_BUDGET = 30;
528341
+ if (turn > stagnationCooldownUntilTurn && this._lastFileWriteTurn >= 0 && turn - this._lastFileWriteTurn >= REG58_NO_WRITE_BUDGET && process.env["OA_DISABLE_REG58"] !== "1") {
528342
+ const gap = turn - this._lastFileWriteTurn;
528343
+ const replan = `[STAGNATION REPLAN — REG-58 no-write convergence]
528344
+ You have made ${gap} tool calls without a single file_write/file_edit/batch_edit/file_patch since turn ${this._lastFileWriteTurn}. That is exploration-without-action. STOP retrying the current approach.
528345
+
528346
+ Respond with EXACTLY this structure before your next tool call:
528347
+ HYPOTHESES (3 distinct theories why progress stalled):
528348
+ 1. ...
528349
+ 2. ...
528350
+ 3. ...
528351
+ PICK: <number 1-3>
528352
+ WHY: <one sentence>
528353
+ FALSIFICATION: <observable signal that would refute the pick>
528354
+ NEXT ACTION: <a single creative edit — file_write / file_edit / batch_edit — that tests the picked hypothesis>
528355
+
528356
+ If the hypothesis cannot be tested by a creative edit, ask the human via task_complete with summary 'BLOCKED: <reason>'.`;
528357
+ messages2.push({ role: "system", content: replan });
528358
+ stagnationCooldownUntilTurn = turn + 8;
528359
+ this.emit({
528360
+ type: "status",
528361
+ content: `REG-58 NO-WRITE STAGNATION — ${gap} turns since last creative edit (turn ${this._lastFileWriteTurn})`,
528362
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
528363
+ });
528364
+ this._lastFileWriteTurn = turn;
528365
+ }
527628
528366
  if (turn > stagnationCooldownUntilTurn && stagnationWindow.length >= STAG_MIN_SAMPLES) {
527629
528367
  const cutoffTurn = turn - STAG_WINDOW_TURNS;
527630
528368
  const cutoffTs = Date.now() - STAG_WINDOW_MS;
@@ -527657,6 +528395,9 @@ TASK: ${task}` : task;
527657
528395
  minSamples: STAG_MIN_SAMPLES
527658
528396
  })) {
527659
528397
  let _stagBody = buildStagnationDiagnostic(signals);
528398
+ if (process.env["OA_DISABLE_STAGNATION_REPLAN"] !== "1") {
528399
+ _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.";
528400
+ }
527660
528401
  if (this._runLessons.length > 0) {
527661
528402
  const _query = `${this._taskState.goal || ""} ${signals.variantList.join(" ")}`;
527662
528403
  const _topLessons = select2({
@@ -527678,6 +528419,47 @@ TASK: ${task}` : task;
527678
528419
  }
527679
528420
  messages2.push({ role: "system", content: _stagBody });
527680
528421
  stagnationCooldownUntilTurn = turn + 5;
528422
+ try {
528423
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
528424
+ const errClusters = [];
528425
+ try {
528426
+ const ec = this._errorClusterTracker;
528427
+ if (ec && typeof ec.topClusters === "function") {
528428
+ const top = ec.topClusters(3);
528429
+ for (const c9 of top)
528430
+ errClusters.push(c9.pattern);
528431
+ }
528432
+ } catch {
528433
+ }
528434
+ if (errClusters.length === 0 && this._runErrorPatterns.length > 0) {
528435
+ errClusters.push(...this._runErrorPatterns.slice(0, 3));
528436
+ }
528437
+ const stuckTool = this._toolSequence.length > 0 ? this._toolSequence[this._toolSequence.length - 1] : null;
528438
+ const fingerprint = { errorClusters: errClusters.slice(0, 3), stuckTool };
528439
+ this._pendingStagnationEntry = {
528440
+ fingerprint,
528441
+ cooldownExpiresAtTurn: turn + 5,
528442
+ successesSinceExpiry: 0,
528443
+ stuckTool
528444
+ };
528445
+ const sig = memMod.fingerprintSignature(fingerprint);
528446
+ const recipes = this._episodeStore ? memMod.lookupBySignature(this._episodeStore, sig, 1) : [];
528447
+ if (recipes.length > 0) {
528448
+ const r2 = recipes[0];
528449
+ messages2.push({
528450
+ role: "system",
528451
+ content: `[STAGNATION RECIPE — found from prior run with same failure shape]
528452
+ ${r2.content}
528453
+ If this matches your current shape, try it before continuing.`
528454
+ });
528455
+ this.emit({
528456
+ type: "status",
528457
+ content: `[STAGNATION RECIPE] surfaced prior recipe (sig=${sig}) for current failure shape`,
528458
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
528459
+ });
528460
+ }
528461
+ } catch {
528462
+ }
527681
528463
  this.emit({
527682
528464
  type: "status",
527683
528465
  content: `STAGNATION DETECTED — injected diagnostic mode at turn ${turn} (${signals.variantCount} variants, ${signals.failureSum} failures, ${signals.filesDelta} files in window)`,
@@ -528571,24 +529353,96 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
528571
529353
  }
528572
529354
  }
528573
529355
  if (turn > 0 && turn % 3 === 0 && this._temporalGraph && this._episodeStore) {
529356
+ let shouldRetrieve = true;
528574
529357
  try {
528575
- const taskGoal = this._taskState.goal || cleanedTask.slice(0, 200);
528576
- const _hs = this._homeostat;
528577
- const pprResult = retrieveByPPR(taskGoal, this._temporalGraph, this._episodeStore, {
528578
- topK: 3,
528579
- currentEmotionalState: _hs?.current,
528580
- engagementWeight: 0.2
528581
- });
528582
- if (pprResult.episodes.length > 0) {
528583
- const memoryLines = pprResult.episodes.map(({ episode, pprScore, matchedNodes }) => `- [${episode.toolName ?? episode.modality}] ${episode.content.slice(0, 120)} (via: ${matchedNodes.slice(0, 2).join(", ")})`);
528584
- compacted.push({
528585
- role: "system",
528586
- content: `[Associative Memory — related prior experience]
528587
- ${memoryLines.join("\n")}`
528588
- });
529358
+ if (process.env["OA_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
529359
+ const goalForSig = (this._taskState.goal || "").slice(0, 200);
529360
+ const recentTools = this._toolSequence.slice(-5).join("|");
529361
+ const { createHash: createHash20 } = await import("node:crypto");
529362
+ const sig = createHash20("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
529363
+ if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
529364
+ compacted.push({
529365
+ role: "system",
529366
+ content: `[Associative Memory related prior experience]
529367
+ ${this._lastPprMemoryLines.join("\n")}`
529368
+ });
529369
+ this._pprSkipCount++;
529370
+ this.emit({
529371
+ type: "status",
529372
+ content: `[ppr-skip] reused previous retrieval (skipCount=${this._pprSkipCount}) — goal+tools unchanged`,
529373
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
529374
+ });
529375
+ shouldRetrieve = false;
529376
+ } else {
529377
+ this._lastPprSig = sig;
529378
+ this._pprSkipCount = 0;
529379
+ }
528589
529380
  }
528590
529381
  } catch {
528591
529382
  }
529383
+ if (!shouldRetrieve) {
529384
+ } else {
529385
+ try {
529386
+ if (this._lastRetrievedEpisodes.length > 0) {
529387
+ const recentAsst = messages2.slice(-10).filter((m2) => m2.role === "assistant" && typeof m2.content === "string").map((m2) => m2.content.toLowerCase()).join(" ");
529388
+ let bumped = 0;
529389
+ for (const { id, fingerprint } of this._lastRetrievedEpisodes) {
529390
+ if (fingerprint && fingerprint.length >= 10 && recentAsst.includes(fingerprint)) {
529391
+ this._episodeStore.bumpReuseCount(id, 1);
529392
+ bumped++;
529393
+ }
529394
+ }
529395
+ if (bumped > 0) {
529396
+ this.emit({
529397
+ type: "status",
529398
+ content: `[reuse] ${bumped} retrieved episode(s) referenced — bumping reuse_count`,
529399
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
529400
+ });
529401
+ }
529402
+ this._lastRetrievedEpisodes = [];
529403
+ }
529404
+ } catch {
529405
+ }
529406
+ try {
529407
+ const taskGoal = this._taskState.goal || cleanedTask.slice(0, 200);
529408
+ const _hs = this._homeostat;
529409
+ let _influenceFor = void 0;
529410
+ try {
529411
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
529412
+ const sm = this._selfModel;
529413
+ if (sm) {
529414
+ const cal = sm.snapshot()?.calibration;
529415
+ const closure = memMod.buildSelfTrustInfluence(cal);
529416
+ if (closure)
529417
+ _influenceFor = closure;
529418
+ }
529419
+ } catch {
529420
+ }
529421
+ const pprResult = retrieveByPPR(taskGoal, this._temporalGraph, this._episodeStore, {
529422
+ topK: 3,
529423
+ currentEmotionalState: _hs?.current,
529424
+ engagementWeight: 0.2,
529425
+ influenceFor: _influenceFor
529426
+ });
529427
+ if (pprResult.episodes.length > 0) {
529428
+ const memoryLines = pprResult.episodes.map(({ episode, pprScore, matchedNodes }) => `- [${episode.toolName ?? episode.modality}] ${episode.content.slice(0, 120)} (via: ${matchedNodes.slice(0, 2).join(", ")})`);
529429
+ compacted.push({
529430
+ role: "system",
529431
+ content: `[Associative Memory — related prior experience]
529432
+ ${memoryLines.join("\n")}`
529433
+ });
529434
+ this._lastRetrievedEpisodes = pprResult.episodes.map(({ episode }) => ({
529435
+ id: episode.id,
529436
+ fingerprint: (episode.content || "").trim().slice(0, 50).toLowerCase()
529437
+ }));
529438
+ this._lastPprMemoryLines = memoryLines;
529439
+ } else {
529440
+ this._lastRetrievedEpisodes = [];
529441
+ this._lastPprMemoryLines = [];
529442
+ }
529443
+ } catch {
529444
+ }
529445
+ }
528592
529446
  }
528593
529447
  if (this.options.environmentProvider) {
528594
529448
  try {
@@ -529346,6 +530200,22 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
529346
530200
  }
529347
530201
  } else {
529348
530202
  const finalArgs = hookCheck.modifiedArgs ?? tc.arguments;
530203
+ if (this._toolOutcomeTracker && process.env["OA_DISABLE_TOOL_FORECAST"] !== "1") {
530204
+ try {
530205
+ const argBlob = JSON.stringify(finalArgs || {}).toLowerCase();
530206
+ 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";
530207
+ const recent = this._toolOutcomeTracker.recentRate(tc.name, fdomain);
530208
+ const inStagnation = stagnationCooldownUntilTurn > turn;
530209
+ const cooldownExpired = turn - this._lastForecastTurn >= 3;
530210
+ if (recent && recent.rate < 0.3 && !inStagnation && cooldownExpired) {
530211
+ this._lastForecastTurn = turn;
530212
+ 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.`;
530213
+ messages2.push({ role: "system", content: fc });
530214
+ this.emit({ type: "status", content: fc, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
530215
+ }
530216
+ } catch {
530217
+ }
530218
+ }
529349
530219
  try {
529350
530220
  if (typeof tool.executeStream === "function") {
529351
530221
  const gen = tool.executeStream(finalArgs);
@@ -529410,6 +530280,29 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
529410
530280
  if (obs.summaryLine) {
529411
530281
  if (obs.hasCritical) {
529412
530282
  messages2.push({ role: "system", content: obs.summaryLine });
530283
+ if (process.env["OA_DISABLE_REG59"] !== "1") {
530284
+ messages2.push({
530285
+ role: "system",
530286
+ content: `[STAGNATION REPLAN — REG-59 same-error escalation]
530287
+ The error cluster you keep hitting has occurred 5+ times. Your current approach is NOT working. STOP retrying it.
530288
+
530289
+ Respond with EXACTLY this structure before your next tool call:
530290
+ HYPOTHESES (3 NEW theories — must be DIFFERENT from anything tried so far):
530291
+ 1. ...
530292
+ 2. ...
530293
+ 3. ...
530294
+ PICK: <number 1-3>
530295
+ WHY: <one sentence — what makes this hypothesis NEW>
530296
+ FALSIFICATION: <observable signal that would refute the pick>
530297
+ NEXT ACTION: <single tool call that tests the picked hypothesis — preferably a creative edit, not a read>`
530298
+ });
530299
+ stagnationCooldownUntilTurn = turn + 8;
530300
+ this.emit({
530301
+ type: "status",
530302
+ content: `REG-59 SAME-ERROR ESCALATION — forcing structured re-plan after 5+ identical cluster hits`,
530303
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
530304
+ });
530305
+ }
529413
530306
  } else {
529414
530307
  pushSoftInjection("system", obs.summaryLine);
529415
530308
  }
@@ -530109,6 +531002,109 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
530109
531002
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
530110
531003
  });
530111
531004
  this._taskState.toolCallCount++;
531005
+ if (result && result.success !== false) {
531006
+ const creativeTools = ["file_write", "file_edit", "batch_edit", "file_patch"];
531007
+ if (creativeTools.includes(tc.name)) {
531008
+ this._lastFileWriteTurn = turn;
531009
+ }
531010
+ }
531011
+ if (result && result.success === false) {
531012
+ this._runErrorCount++;
531013
+ const errMsg = result.error || "";
531014
+ if (typeof errMsg === "string" && errMsg.length > 0) {
531015
+ const sig = errMsg.replace(/[0-9]+/g, "N").slice(0, 60);
531016
+ if (!this._runErrorPatterns.includes(sig)) {
531017
+ this._runErrorPatterns.push(sig);
531018
+ if (this._runErrorPatterns.length > 5)
531019
+ this._runErrorPatterns.length = 5;
531020
+ }
531021
+ }
531022
+ try {
531023
+ if (process.env["OA_DISABLE_MIDTURN_RETRIEVAL"] !== "1" && this._episodeStore && stagnationCooldownUntilTurn <= turn && typeof errMsg === "string" && errMsg.length >= 8) {
531024
+ const query = `${tc.name} ${errMsg}`.slice(0, 240);
531025
+ const past = this._episodeStore.search({ query, limit: 2 });
531026
+ const useful = past.filter((p2) => p2.content && p2.content.length > 10).slice(0, 1);
531027
+ if (useful.length > 0) {
531028
+ const u = useful[0];
531029
+ messages2.push({
531030
+ role: "system",
531031
+ content: `[Past-error memory] when "${tc.name}" failed before with similar error, episode said: ${u.content.slice(0, 200)}`
531032
+ });
531033
+ this.emit({
531034
+ type: "status",
531035
+ content: `[midturn] surfaced past-error memory for tool=${tc.name}`,
531036
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
531037
+ });
531038
+ }
531039
+ }
531040
+ } catch {
531041
+ }
531042
+ }
531043
+ try {
531044
+ if (this._pendingStagnationEntry && process.env["OA_DISABLE_STAGNATION_RECIPES"] !== "1") {
531045
+ if (turn > this._pendingStagnationEntry.cooldownExpiresAtTurn) {
531046
+ if (result && result.success !== false) {
531047
+ this._pendingStagnationEntry.successesSinceExpiry++;
531048
+ if (this._pendingStagnationEntry.successesSinceExpiry >= 3 && this._episodeStore) {
531049
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
531050
+ const recoveryTool = tc.name;
531051
+ const stuck = this._pendingStagnationEntry.stuckTool || null;
531052
+ const toolShift = stuck && stuck !== recoveryTool ? { from: stuck, to: recoveryTool } : null;
531053
+ const recId = memMod.crystallize(this._episodeStore, {
531054
+ fingerprint: this._pendingStagnationEntry.fingerprint,
531055
+ toolShift,
531056
+ whatWorked: this._runLessons.slice(-1).map((l2) => l2?.whatWorked).join(" ").slice(0, 120) || `recovered after switching to ${recoveryTool}`
531057
+ });
531058
+ this.emit({
531059
+ type: "status",
531060
+ content: `[STAGNATION CRYSTALLIZED] recipe id=${recId.slice(0, 8)} for failure shape (sig=${memMod.fingerprintSignature(this._pendingStagnationEntry.fingerprint)})`,
531061
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
531062
+ });
531063
+ this._pendingStagnationEntry = null;
531064
+ }
531065
+ } else {
531066
+ this._pendingStagnationEntry.successesSinceExpiry = 0;
531067
+ }
531068
+ }
531069
+ }
531070
+ } catch {
531071
+ }
531072
+ try {
531073
+ if (this._codebaseMap) {
531074
+ const args = tc.arguments || {};
531075
+ const path8 = typeof args.path === "string" ? args.path : "";
531076
+ const command = typeof args.command === "string" ? args.command : "";
531077
+ const isWrite = /^(file_(write|edit|patch)|batch_edit|edit)$/i.test(tc.name);
531078
+ const isRead = /^(file_read|read)$/i.test(tc.name);
531079
+ if (path8)
531080
+ this._codebaseMap.noteFile(path8, isWrite ? "write" : "read");
531081
+ if (command && /\b(vitest|jest|pytest|go test|cargo test)\b/.test(command)) {
531082
+ const ok2 = result && result.success !== false;
531083
+ this._codebaseMap.noteTest(command.slice(0, 80), ok2 ? "pass" : "fail");
531084
+ }
531085
+ if (typeof args.from === "string" && typeof args.to === "string") {
531086
+ this._codebaseMap.noteReference(args.from, args.to);
531087
+ }
531088
+ }
531089
+ } catch {
531090
+ }
531091
+ try {
531092
+ if (process.env["OA_DISABLE_TOOL_FORECAST"] !== "1") {
531093
+ if (!this._toolOutcomeTracker) {
531094
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
531095
+ this._toolOutcomeTracker = new memMod.ToolOutcomeTracker();
531096
+ }
531097
+ const argBlob = JSON.stringify(tc.arguments || {}).toLowerCase();
531098
+ 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";
531099
+ this._toolOutcomeTracker.record({
531100
+ tool: tc.name,
531101
+ domain,
531102
+ success: result && result.success !== false,
531103
+ ts: Date.now()
531104
+ });
531105
+ }
531106
+ } catch {
531107
+ }
530112
531108
  const filePath = typeof tc.arguments?.path === "string" ? tc.arguments.path : "";
530113
531109
  recordToolExecution(this._appState, tc.name, performance.now() - toolStart, result.success, filePath || void 0);
530114
531110
  if (tc.name === "todo_write") {
@@ -531351,6 +532347,45 @@ Full content available via: repl_exec(code="data = retrieve('${handleId}')") or
531351
532347
  } catch {
531352
532348
  }
531353
532349
  }
532350
+ if (process.env["OA_DISABLE_SESSION_GIST"] !== "1") {
532351
+ try {
532352
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
532353
+ const goal = this._taskState.originalGoal || this._taskState.goal || "";
532354
+ const durationMs2 = this._runStartTime > 0 ? Math.max(0, Date.now() - this._runStartTime) : 0;
532355
+ const toolCounts = /* @__PURE__ */ new Map();
532356
+ for (const t2 of this._toolSequence)
532357
+ toolCounts.set(t2, (toolCounts.get(t2) ?? 0) + 1);
532358
+ const topToolNames = [...toolCounts.entries()].sort((a2, b) => b[1] - a2[1]).slice(0, 3).map(([n2]) => n2);
532359
+ const whatWorked = this._runLessons.slice(-3).map((l2) => l2.whatWorked).filter(Boolean);
532360
+ const finalStatus = completed ? "complete" : this._runErrorCount > this._taskState.toolCallCount * 0.5 ? "abandoned" : "abandoned";
532361
+ const gist2 = memMod.buildGist({
532362
+ goal,
532363
+ durationMs: durationMs2,
532364
+ toolCallCount: this._taskState.toolCallCount,
532365
+ errorCount: this._runErrorCount,
532366
+ finalStatus,
532367
+ topToolNames,
532368
+ topErrorPatterns: this._runErrorPatterns.slice(0, 3),
532369
+ whatWorked,
532370
+ workingDirectory: this._workingDirectory || void 0
532371
+ });
532372
+ this._episodeStore.insert({
532373
+ sessionId: this._sessionId,
532374
+ modality: "gist",
532375
+ toolName: "session_gist",
532376
+ content: gist2.content,
532377
+ importance: 8,
532378
+ decayClass: "procedural",
532379
+ metadata: gist2.metadata
532380
+ });
532381
+ this.emit({
532382
+ type: "status",
532383
+ content: `[SESSION GIST] domain=${gist2.metadata.domain} status=${gist2.metadata.finalStatus} tools=${gist2.metadata.toolCount} errs=${gist2.metadata.errorCount} goalHash=${gist2.goalHash}`,
532384
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
532385
+ });
532386
+ } catch {
532387
+ }
532388
+ }
531354
532389
  if (process.env["OA_DISABLE_PREDICTION_PERSISTENCE"] !== "1") {
531355
532390
  try {
531356
532391
  const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
@@ -540541,7 +541576,7 @@ var require_websocket3 = __commonJS({
540541
541576
  var http6 = __require("http");
540542
541577
  var net5 = __require("net");
540543
541578
  var tls2 = __require("tls");
540544
- var { randomBytes: randomBytes25, createHash: createHash17 } = __require("crypto");
541579
+ var { randomBytes: randomBytes25, createHash: createHash20 } = __require("crypto");
540545
541580
  var { Duplex: Duplex3, Readable } = __require("stream");
540546
541581
  var { URL: URL3 } = __require("url");
540547
541582
  var PerMessageDeflate2 = require_permessage_deflate3();
@@ -541201,7 +542236,7 @@ var require_websocket3 = __commonJS({
541201
542236
  abortHandshake(websocket, socket, "Invalid Upgrade header");
541202
542237
  return;
541203
542238
  }
541204
- const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
542239
+ const digest3 = createHash20("sha1").update(key + GUID).digest("base64");
541205
542240
  if (res.headers["sec-websocket-accept"] !== digest3) {
541206
542241
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
541207
542242
  return;
@@ -541568,7 +542603,7 @@ var require_websocket_server2 = __commonJS({
541568
542603
  var EventEmitter13 = __require("events");
541569
542604
  var http6 = __require("http");
541570
542605
  var { Duplex: Duplex3 } = __require("stream");
541571
- var { createHash: createHash17 } = __require("crypto");
542606
+ var { createHash: createHash20 } = __require("crypto");
541572
542607
  var extension2 = require_extension3();
541573
542608
  var PerMessageDeflate2 = require_permessage_deflate3();
541574
542609
  var subprotocol2 = require_subprotocol2();
@@ -541869,7 +542904,7 @@ var require_websocket_server2 = __commonJS({
541869
542904
  );
541870
542905
  }
541871
542906
  if (this._state > RUNNING) return abortHandshake(socket, 503);
541872
- const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
542907
+ const digest3 = createHash20("sha1").update(key + GUID).digest("base64");
541873
542908
  const headers = [
541874
542909
  "HTTP/1.1 101 Switching Protocols",
541875
542910
  "Upgrade: websocket",
@@ -542929,7 +543964,7 @@ __export(oa_directory_exports, {
542929
543964
  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";
542930
543965
  import { join as join90, relative as relative8, basename as basename14, dirname as dirname27 } from "node:path";
542931
543966
  import { homedir as homedir26 } from "node:os";
542932
- import { createHash as createHash10 } from "node:crypto";
543967
+ import { createHash as createHash13 } from "node:crypto";
542933
543968
  function findGitRoot(startDir) {
542934
543969
  let dir = startDir;
542935
543970
  const visited = /* @__PURE__ */ new Set();
@@ -543294,7 +544329,7 @@ function buildHandoffPrompt(repoRoot) {
543294
544329
  return lines.join("\n");
543295
544330
  }
543296
544331
  function computeDedupeHash(task, savedAt) {
543297
- return createHash10("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
544332
+ return createHash13("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
543298
544333
  }
543299
544334
  function generateSessionId() {
543300
544335
  const timestamp = Date.now().toString(36);
@@ -571825,7 +572860,7 @@ var init_types = __esm({
571825
572860
  });
571826
572861
 
571827
572862
  // packages/cli/src/tui/p2p/secret-vault.ts
571828
- import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes19, scryptSync as scryptSync2, createHash as createHash11 } from "node:crypto";
572863
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes19, scryptSync as scryptSync2, createHash as createHash14 } from "node:crypto";
571829
572864
  import { readFileSync as readFileSync68, writeFileSync as writeFileSync43, existsSync as existsSync85, mkdirSync as mkdirSync47 } from "node:fs";
571830
572865
  import { dirname as dirname31 } from "node:path";
571831
572866
  var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
@@ -572070,7 +573105,7 @@ var init_secret_vault = __esm({
572070
573105
  /** Generate a deterministic fingerprint of vault contents (for sync verification) */
572071
573106
  fingerprint() {
572072
573107
  const names = Array.from(this.secrets.keys()).sort();
572073
- const hash = createHash11("sha256");
573108
+ const hash = createHash14("sha256");
572074
573109
  for (const name10 of names) {
572075
573110
  hash.update(name10 + ":");
572076
573111
  hash.update(this.secrets.get(name10).value);
@@ -572085,7 +573120,7 @@ var init_secret_vault = __esm({
572085
573120
  // packages/cli/src/tui/p2p/peer-mesh.ts
572086
573121
  import { EventEmitter as EventEmitter7 } from "node:events";
572087
573122
  import { createServer as createServer5 } from "node:http";
572088
- import { randomBytes as randomBytes20, createHash as createHash12, generateKeyPairSync } from "node:crypto";
573123
+ import { randomBytes as randomBytes20, createHash as createHash15, generateKeyPairSync } from "node:crypto";
572089
573124
  var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
572090
573125
  var init_peer_mesh = __esm({
572091
573126
  "packages/cli/src/tui/p2p/peer-mesh.ts"() {
@@ -572102,7 +573137,7 @@ var init_peer_mesh = __esm({
572102
573137
  const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
572103
573138
  this.publicKey = publicKey2.export({ type: "spki", format: "der" });
572104
573139
  this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
572105
- this.peerId = createHash12("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
573140
+ this.peerId = createHash15("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
572106
573141
  this.capabilities = options2.capabilities;
572107
573142
  this.displayName = options2.displayName;
572108
573143
  this._authKey = options2.authKey ?? randomBytes20(24).toString("base64url");
@@ -579982,7 +581017,7 @@ __export(chat_session_exports, {
579982
581017
  startInFlightChat: () => startInFlightChat,
579983
581018
  trackSessionTokens: () => trackSessionTokens
579984
581019
  });
579985
- import { randomUUID as randomUUID12 } from "node:crypto";
581020
+ import { randomUUID as randomUUID13 } from "node:crypto";
579986
581021
  import {
579987
581022
  existsSync as existsSync94,
579988
581023
  readFileSync as readFileSync76,
@@ -580139,7 +581174,7 @@ function getSession(sessionId, model, cwd4) {
580139
581174
  } catch {
580140
581175
  }
580141
581176
  }
580142
- const id = sessionId || randomUUID12();
581177
+ const id = sessionId || randomUUID13();
580143
581178
  const systemPrompt = buildSystemPrompt(cwd4);
580144
581179
  const session = {
580145
581180
  id,
@@ -580406,7 +581441,7 @@ __export(projects_exports, {
580406
581441
  import { readFileSync as readFileSync77, writeFileSync as writeFileSync49, mkdirSync as mkdirSync55, existsSync as existsSync95, statSync as statSync31, renameSync as renameSync6 } from "node:fs";
580407
581442
  import { homedir as homedir35 } from "node:os";
580408
581443
  import { basename as basename20, join as join112, resolve as resolve35 } from "node:path";
580409
- import { randomUUID as randomUUID13 } from "node:crypto";
581444
+ import { randomUUID as randomUUID14 } from "node:crypto";
580410
581445
  function readAll2() {
580411
581446
  try {
580412
581447
  if (!existsSync95(PROJECTS_FILE)) return { projects: [], schemaVersion: 1 };
@@ -580420,7 +581455,7 @@ function readAll2() {
580420
581455
  }
580421
581456
  function writeAll(file) {
580422
581457
  mkdirSync55(OA_DIR3, { recursive: true });
580423
- const tmp = `${PROJECTS_FILE}.${randomUUID13().slice(0, 8)}.tmp`;
581458
+ const tmp = `${PROJECTS_FILE}.${randomUUID14().slice(0, 8)}.tmp`;
580424
581459
  writeFileSync49(tmp, JSON.stringify(file, null, 2), "utf8");
580425
581460
  renameSync6(tmp, PROJECTS_FILE);
580426
581461
  }
@@ -581209,14 +582244,14 @@ var init_access_policy = __esm({
581209
582244
  });
581210
582245
 
581211
582246
  // packages/cli/src/api/project-preferences.ts
581212
- import { createHash as createHash13 } from "node:crypto";
582247
+ import { createHash as createHash16 } from "node:crypto";
581213
582248
  import { existsSync as existsSync96, mkdirSync as mkdirSync56, readFileSync as readFileSync78, renameSync as renameSync7, writeFileSync as writeFileSync50, unlinkSync as unlinkSync22 } from "node:fs";
581214
582249
  import { homedir as homedir36 } from "node:os";
581215
582250
  import { join as join113, resolve as resolve36 } from "node:path";
581216
- import { randomUUID as randomUUID14 } from "node:crypto";
582251
+ import { randomUUID as randomUUID15 } from "node:crypto";
581217
582252
  function projectKey(root) {
581218
582253
  const canonical = resolve36(root);
581219
- return createHash13("sha256").update(canonical).digest("hex").slice(0, 16);
582254
+ return createHash16("sha256").update(canonical).digest("hex").slice(0, 16);
581220
582255
  }
581221
582256
  function projectDir(root) {
581222
582257
  return join113(PROJECTS_DIR, projectKey(root));
@@ -581261,7 +582296,7 @@ function writeProjectPreferences(root, partial) {
581261
582296
  updatedAt: Date.now()
581262
582297
  };
581263
582298
  const file = prefsPath(root);
581264
- const tmp = `${file}.${randomUUID14().slice(0, 8)}.tmp`;
582299
+ const tmp = `${file}.${randomUUID15().slice(0, 8)}.tmp`;
581265
582300
  writeFileSync50(tmp, JSON.stringify(merged, null, 2), "utf8");
581266
582301
  try {
581267
582302
  renameSync7(tmp, file);
@@ -582394,7 +583429,7 @@ var init_disk_task_output = __esm({
582394
583429
  });
582395
583430
 
582396
583431
  // packages/cli/src/api/http.ts
582397
- import { createHash as createHash14 } from "node:crypto";
583432
+ import { createHash as createHash17 } from "node:crypto";
582398
583433
  function problemDetails(opts) {
582399
583434
  const p2 = {
582400
583435
  type: opts.type ?? "about:blank",
@@ -582457,7 +583492,7 @@ function paginated(items, page2, total) {
582457
583492
  }
582458
583493
  function computeEtag(payload) {
582459
583494
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
582460
- const hash = createHash14("sha1").update(json).digest("hex").slice(0, 16);
583495
+ const hash = createHash17("sha1").update(json).digest("hex").slice(0, 16);
582461
583496
  return `W/"${hash}"`;
582462
583497
  }
582463
583498
  function checkNotModified(req2, res, etag) {
@@ -594072,8 +595107,8 @@ import { dirname as dirname36, join as join121, resolve as resolve38 } from "nod
594072
595107
  import { homedir as homedir42 } from "node:os";
594073
595108
  import { spawn as spawn25, execSync as execSync57 } from "node:child_process";
594074
595109
  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";
594075
- import { randomBytes as randomBytes23, randomUUID as randomUUID15 } from "node:crypto";
594076
- import { createHash as createHash16 } from "node:crypto";
595110
+ import { randomBytes as randomBytes23, randomUUID as randomUUID16 } from "node:crypto";
595111
+ import { createHash as createHash19 } from "node:crypto";
594077
595112
  function getVersion3() {
594078
595113
  try {
594079
595114
  const thisDir = dirname36(fileURLToPath17(import.meta.url));
@@ -597157,7 +598192,7 @@ async function handleRequest(req2, res, ollamaUrl, verbose) {
597157
598192
  const urlObj = new URL(req2.url ?? "/", `http://${req2.headers.host ?? "localhost"}`);
597158
598193
  const pathname = urlObj.pathname;
597159
598194
  const startMs = performance.now();
597160
- const requestId = req2.headers["x-request-id"] || randomUUID15();
598195
+ const requestId = req2.headers["x-request-id"] || randomUUID16();
597161
598196
  res.setHeader("X-Request-ID", requestId);
597162
598197
  res.setHeader("X-API-Version", API_VERSION);
597163
598198
  if (method === "OPTIONS") {
@@ -599271,7 +600306,7 @@ function listScheduledTasks() {
599271
600306
  const schedule = String(t2?.schedule || t2?.cron || t2?.when || "");
599272
600307
  const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
599273
600308
  const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
599274
- const fallbackId = createHash16("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
600309
+ const fallbackId = createHash19("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
599275
600310
  const uid = realId || fallbackId;
599276
600311
  const key = `${uid}`;
599277
600312
  if (seen.has(key)) return;
@@ -599388,8 +600423,8 @@ function deleteScheduledById(id) {
599388
600423
  if (id) candidates.push(id);
599389
600424
  if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id)) candidates.push(entry.id);
599390
600425
  try {
599391
- const { createHash: createHash17 } = require3("node:crypto");
599392
- const fallback = createHash17("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
600426
+ const { createHash: createHash20 } = require3("node:crypto");
600427
+ const fallback = createHash20("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
599393
600428
  if (!candidates.includes(fallback)) candidates.push(fallback);
599394
600429
  } catch {
599395
600430
  }
@@ -606796,13 +607831,13 @@ NEW TASK: ${fullInput}`;
606796
607831
  writeContent(() => renderError2(errMsg));
606797
607832
  if (failureStore) {
606798
607833
  try {
606799
- const { createHash: createHash17 } = await import("node:crypto");
607834
+ const { createHash: createHash20 } = await import("node:crypto");
606800
607835
  failureStore.insert({
606801
607836
  taskId: "",
606802
607837
  sessionId: `${Date.now()}`,
606803
607838
  repoRoot,
606804
607839
  failureType: "runtime-error",
606805
- fingerprint: createHash17("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
607840
+ fingerprint: createHash20("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
606806
607841
  filePath: null,
606807
607842
  errorMessage: errMsg.slice(0, 500),
606808
607843
  context: null,