open-agents-ai 0.187.511 → 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 {
@@ -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,37 @@ 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
+ // 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;
525127
525786
  // Phase 2 — tool subset expansion and usage tracking.
525128
525787
  // Tools promoted from deferred → inline by tool_search (or by subset
525129
525788
  // expansion). They stay inline for the rest of the run unless idle past
@@ -527253,6 +527912,10 @@ Respond with your assessment, then take action.`;
527253
527912
  modifiedFiles: /* @__PURE__ */ new Map(),
527254
527913
  toolCallCount: 0
527255
527914
  };
527915
+ this._runStartTime = Date.now();
527916
+ this._runErrorCount = 0;
527917
+ this._runErrorPatterns = [];
527918
+ this._runWhatWorked = [];
527256
527919
  this._fileRegistry.clear();
527257
527920
  this._memexArchive.clear();
527258
527921
  this._sessionId = process.env["OA_SESSION_ID"] && String(process.env["OA_SESSION_ID"]) || `session-${Date.now()}`;
@@ -527321,6 +527984,46 @@ Respond with your assessment, then take action.`;
527321
527984
  } catch {
527322
527985
  }
527323
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
+ }
527324
528027
  const contextComposition = await this.assembleContext(task, context2);
527325
528028
  const systemPrompt = contextComposition.assembled;
527326
528029
  this._contextTree = new ContextTree(`sys-${systemPrompt.length}`, cleanedTask.slice(0, 200));
@@ -527657,6 +528360,9 @@ TASK: ${task}` : task;
527657
528360
  minSamples: STAG_MIN_SAMPLES
527658
528361
  })) {
527659
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
+ }
527660
528366
  if (this._runLessons.length > 0) {
527661
528367
  const _query = `${this._taskState.goal || ""} ${signals.variantList.join(" ")}`;
527662
528368
  const _topLessons = select2({
@@ -527678,6 +528384,47 @@ TASK: ${task}` : task;
527678
528384
  }
527679
528385
  messages2.push({ role: "system", content: _stagBody });
527680
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
+ }
527681
528428
  this.emit({
527682
528429
  type: "status",
527683
528430
  content: `STAGNATION DETECTED — injected diagnostic mode at turn ${turn} (${signals.variantCount} variants, ${signals.failureSum} failures, ${signals.filesDelta} files in window)`,
@@ -528571,24 +529318,96 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
528571
529318
  }
528572
529319
  }
528573
529320
  if (turn > 0 && turn % 3 === 0 && this._temporalGraph && this._episodeStore) {
529321
+ let shouldRetrieve = true;
528574
529322
  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
- });
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
+ }
528589
529345
  }
528590
529346
  } catch {
528591
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
+ }
528592
529411
  }
528593
529412
  if (this.options.environmentProvider) {
528594
529413
  try {
@@ -529346,6 +530165,22 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
529346
530165
  }
529347
530166
  } else {
529348
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
+ }
529349
530184
  try {
529350
530185
  if (typeof tool.executeStream === "function") {
529351
530186
  const gen = tool.executeStream(finalArgs);
@@ -530109,6 +530944,103 @@ ${criticDecision.cachedResult.slice(0, 500)}` : `[BLOCKED — the observer confi
530109
530944
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
530110
530945
  });
530111
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
+ }
530112
531044
  const filePath = typeof tc.arguments?.path === "string" ? tc.arguments.path : "";
530113
531045
  recordToolExecution(this._appState, tc.name, performance.now() - toolStart, result.success, filePath || void 0);
530114
531046
  if (tc.name === "todo_write") {
@@ -531351,6 +532283,45 @@ Full content available via: repl_exec(code="data = retrieve('${handleId}')") or
531351
532283
  } catch {
531352
532284
  }
531353
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
+ }
531354
532325
  if (process.env["OA_DISABLE_PREDICTION_PERSISTENCE"] !== "1") {
531355
532326
  try {
531356
532327
  const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
@@ -540541,7 +541512,7 @@ var require_websocket3 = __commonJS({
540541
541512
  var http6 = __require("http");
540542
541513
  var net5 = __require("net");
540543
541514
  var tls2 = __require("tls");
540544
- var { randomBytes: randomBytes25, createHash: createHash17 } = __require("crypto");
541515
+ var { randomBytes: randomBytes25, createHash: createHash20 } = __require("crypto");
540545
541516
  var { Duplex: Duplex3, Readable } = __require("stream");
540546
541517
  var { URL: URL3 } = __require("url");
540547
541518
  var PerMessageDeflate2 = require_permessage_deflate3();
@@ -541201,7 +542172,7 @@ var require_websocket3 = __commonJS({
541201
542172
  abortHandshake(websocket, socket, "Invalid Upgrade header");
541202
542173
  return;
541203
542174
  }
541204
- const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
542175
+ const digest3 = createHash20("sha1").update(key + GUID).digest("base64");
541205
542176
  if (res.headers["sec-websocket-accept"] !== digest3) {
541206
542177
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
541207
542178
  return;
@@ -541568,7 +542539,7 @@ var require_websocket_server2 = __commonJS({
541568
542539
  var EventEmitter13 = __require("events");
541569
542540
  var http6 = __require("http");
541570
542541
  var { Duplex: Duplex3 } = __require("stream");
541571
- var { createHash: createHash17 } = __require("crypto");
542542
+ var { createHash: createHash20 } = __require("crypto");
541572
542543
  var extension2 = require_extension3();
541573
542544
  var PerMessageDeflate2 = require_permessage_deflate3();
541574
542545
  var subprotocol2 = require_subprotocol2();
@@ -541869,7 +542840,7 @@ var require_websocket_server2 = __commonJS({
541869
542840
  );
541870
542841
  }
541871
542842
  if (this._state > RUNNING) return abortHandshake(socket, 503);
541872
- const digest3 = createHash17("sha1").update(key + GUID).digest("base64");
542843
+ const digest3 = createHash20("sha1").update(key + GUID).digest("base64");
541873
542844
  const headers = [
541874
542845
  "HTTP/1.1 101 Switching Protocols",
541875
542846
  "Upgrade: websocket",
@@ -542929,7 +543900,7 @@ __export(oa_directory_exports, {
542929
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";
542930
543901
  import { join as join90, relative as relative8, basename as basename14, dirname as dirname27 } from "node:path";
542931
543902
  import { homedir as homedir26 } from "node:os";
542932
- import { createHash as createHash10 } from "node:crypto";
543903
+ import { createHash as createHash13 } from "node:crypto";
542933
543904
  function findGitRoot(startDir) {
542934
543905
  let dir = startDir;
542935
543906
  const visited = /* @__PURE__ */ new Set();
@@ -543294,7 +544265,7 @@ function buildHandoffPrompt(repoRoot) {
543294
544265
  return lines.join("\n");
543295
544266
  }
543296
544267
  function computeDedupeHash(task, savedAt) {
543297
- return createHash10("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
544268
+ return createHash13("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
543298
544269
  }
543299
544270
  function generateSessionId() {
543300
544271
  const timestamp = Date.now().toString(36);
@@ -571825,7 +572796,7 @@ var init_types = __esm({
571825
572796
  });
571826
572797
 
571827
572798
  // 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";
572799
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes19, scryptSync as scryptSync2, createHash as createHash14 } from "node:crypto";
571829
572800
  import { readFileSync as readFileSync68, writeFileSync as writeFileSync43, existsSync as existsSync85, mkdirSync as mkdirSync47 } from "node:fs";
571830
572801
  import { dirname as dirname31 } from "node:path";
571831
572802
  var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
@@ -572070,7 +573041,7 @@ var init_secret_vault = __esm({
572070
573041
  /** Generate a deterministic fingerprint of vault contents (for sync verification) */
572071
573042
  fingerprint() {
572072
573043
  const names = Array.from(this.secrets.keys()).sort();
572073
- const hash = createHash11("sha256");
573044
+ const hash = createHash14("sha256");
572074
573045
  for (const name10 of names) {
572075
573046
  hash.update(name10 + ":");
572076
573047
  hash.update(this.secrets.get(name10).value);
@@ -572085,7 +573056,7 @@ var init_secret_vault = __esm({
572085
573056
  // packages/cli/src/tui/p2p/peer-mesh.ts
572086
573057
  import { EventEmitter as EventEmitter7 } from "node:events";
572087
573058
  import { createServer as createServer5 } from "node:http";
572088
- import { randomBytes as randomBytes20, createHash as createHash12, generateKeyPairSync } from "node:crypto";
573059
+ import { randomBytes as randomBytes20, createHash as createHash15, generateKeyPairSync } from "node:crypto";
572089
573060
  var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
572090
573061
  var init_peer_mesh = __esm({
572091
573062
  "packages/cli/src/tui/p2p/peer-mesh.ts"() {
@@ -572102,7 +573073,7 @@ var init_peer_mesh = __esm({
572102
573073
  const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
572103
573074
  this.publicKey = publicKey2.export({ type: "spki", format: "der" });
572104
573075
  this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
572105
- 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);
572106
573077
  this.capabilities = options2.capabilities;
572107
573078
  this.displayName = options2.displayName;
572108
573079
  this._authKey = options2.authKey ?? randomBytes20(24).toString("base64url");
@@ -579982,7 +580953,7 @@ __export(chat_session_exports, {
579982
580953
  startInFlightChat: () => startInFlightChat,
579983
580954
  trackSessionTokens: () => trackSessionTokens
579984
580955
  });
579985
- import { randomUUID as randomUUID12 } from "node:crypto";
580956
+ import { randomUUID as randomUUID13 } from "node:crypto";
579986
580957
  import {
579987
580958
  existsSync as existsSync94,
579988
580959
  readFileSync as readFileSync76,
@@ -580139,7 +581110,7 @@ function getSession(sessionId, model, cwd4) {
580139
581110
  } catch {
580140
581111
  }
580141
581112
  }
580142
- const id = sessionId || randomUUID12();
581113
+ const id = sessionId || randomUUID13();
580143
581114
  const systemPrompt = buildSystemPrompt(cwd4);
580144
581115
  const session = {
580145
581116
  id,
@@ -580406,7 +581377,7 @@ __export(projects_exports, {
580406
581377
  import { readFileSync as readFileSync77, writeFileSync as writeFileSync49, mkdirSync as mkdirSync55, existsSync as existsSync95, statSync as statSync31, renameSync as renameSync6 } from "node:fs";
580407
581378
  import { homedir as homedir35 } from "node:os";
580408
581379
  import { basename as basename20, join as join112, resolve as resolve35 } from "node:path";
580409
- import { randomUUID as randomUUID13 } from "node:crypto";
581380
+ import { randomUUID as randomUUID14 } from "node:crypto";
580410
581381
  function readAll2() {
580411
581382
  try {
580412
581383
  if (!existsSync95(PROJECTS_FILE)) return { projects: [], schemaVersion: 1 };
@@ -580420,7 +581391,7 @@ function readAll2() {
580420
581391
  }
580421
581392
  function writeAll(file) {
580422
581393
  mkdirSync55(OA_DIR3, { recursive: true });
580423
- const tmp = `${PROJECTS_FILE}.${randomUUID13().slice(0, 8)}.tmp`;
581394
+ const tmp = `${PROJECTS_FILE}.${randomUUID14().slice(0, 8)}.tmp`;
580424
581395
  writeFileSync49(tmp, JSON.stringify(file, null, 2), "utf8");
580425
581396
  renameSync6(tmp, PROJECTS_FILE);
580426
581397
  }
@@ -581209,14 +582180,14 @@ var init_access_policy = __esm({
581209
582180
  });
581210
582181
 
581211
582182
  // packages/cli/src/api/project-preferences.ts
581212
- import { createHash as createHash13 } from "node:crypto";
582183
+ import { createHash as createHash16 } from "node:crypto";
581213
582184
  import { existsSync as existsSync96, mkdirSync as mkdirSync56, readFileSync as readFileSync78, renameSync as renameSync7, writeFileSync as writeFileSync50, unlinkSync as unlinkSync22 } from "node:fs";
581214
582185
  import { homedir as homedir36 } from "node:os";
581215
582186
  import { join as join113, resolve as resolve36 } from "node:path";
581216
- import { randomUUID as randomUUID14 } from "node:crypto";
582187
+ import { randomUUID as randomUUID15 } from "node:crypto";
581217
582188
  function projectKey(root) {
581218
582189
  const canonical = resolve36(root);
581219
- return createHash13("sha256").update(canonical).digest("hex").slice(0, 16);
582190
+ return createHash16("sha256").update(canonical).digest("hex").slice(0, 16);
581220
582191
  }
581221
582192
  function projectDir(root) {
581222
582193
  return join113(PROJECTS_DIR, projectKey(root));
@@ -581261,7 +582232,7 @@ function writeProjectPreferences(root, partial) {
581261
582232
  updatedAt: Date.now()
581262
582233
  };
581263
582234
  const file = prefsPath(root);
581264
- const tmp = `${file}.${randomUUID14().slice(0, 8)}.tmp`;
582235
+ const tmp = `${file}.${randomUUID15().slice(0, 8)}.tmp`;
581265
582236
  writeFileSync50(tmp, JSON.stringify(merged, null, 2), "utf8");
581266
582237
  try {
581267
582238
  renameSync7(tmp, file);
@@ -582394,7 +583365,7 @@ var init_disk_task_output = __esm({
582394
583365
  });
582395
583366
 
582396
583367
  // packages/cli/src/api/http.ts
582397
- import { createHash as createHash14 } from "node:crypto";
583368
+ import { createHash as createHash17 } from "node:crypto";
582398
583369
  function problemDetails(opts) {
582399
583370
  const p2 = {
582400
583371
  type: opts.type ?? "about:blank",
@@ -582457,7 +583428,7 @@ function paginated(items, page2, total) {
582457
583428
  }
582458
583429
  function computeEtag(payload) {
582459
583430
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
582460
- const hash = createHash14("sha1").update(json).digest("hex").slice(0, 16);
583431
+ const hash = createHash17("sha1").update(json).digest("hex").slice(0, 16);
582461
583432
  return `W/"${hash}"`;
582462
583433
  }
582463
583434
  function checkNotModified(req2, res, etag) {
@@ -594072,8 +595043,8 @@ import { dirname as dirname36, join as join121, resolve as resolve38 } from "nod
594072
595043
  import { homedir as homedir42 } from "node:os";
594073
595044
  import { spawn as spawn25, execSync as execSync57 } from "node:child_process";
594074
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";
594075
- import { randomBytes as randomBytes23, randomUUID as randomUUID15 } from "node:crypto";
594076
- 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";
594077
595048
  function getVersion3() {
594078
595049
  try {
594079
595050
  const thisDir = dirname36(fileURLToPath17(import.meta.url));
@@ -597157,7 +598128,7 @@ async function handleRequest(req2, res, ollamaUrl, verbose) {
597157
598128
  const urlObj = new URL(req2.url ?? "/", `http://${req2.headers.host ?? "localhost"}`);
597158
598129
  const pathname = urlObj.pathname;
597159
598130
  const startMs = performance.now();
597160
- const requestId = req2.headers["x-request-id"] || randomUUID15();
598131
+ const requestId = req2.headers["x-request-id"] || randomUUID16();
597161
598132
  res.setHeader("X-Request-ID", requestId);
597162
598133
  res.setHeader("X-API-Version", API_VERSION);
597163
598134
  if (method === "OPTIONS") {
@@ -599271,7 +600242,7 @@ function listScheduledTasks() {
599271
600242
  const schedule = String(t2?.schedule || t2?.cron || t2?.when || "");
599272
600243
  const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
599273
600244
  const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
599274
- 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);
599275
600246
  const uid = realId || fallbackId;
599276
600247
  const key = `${uid}`;
599277
600248
  if (seen.has(key)) return;
@@ -599388,8 +600359,8 @@ function deleteScheduledById(id) {
599388
600359
  if (id) candidates.push(id);
599389
600360
  if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id)) candidates.push(entry.id);
599390
600361
  try {
599391
- const { createHash: createHash17 } = require3("node:crypto");
599392
- 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);
599393
600364
  if (!candidates.includes(fallback)) candidates.push(fallback);
599394
600365
  } catch {
599395
600366
  }
@@ -606796,13 +607767,13 @@ NEW TASK: ${fullInput}`;
606796
607767
  writeContent(() => renderError2(errMsg));
606797
607768
  if (failureStore) {
606798
607769
  try {
606799
- const { createHash: createHash17 } = await import("node:crypto");
607770
+ const { createHash: createHash20 } = await import("node:crypto");
606800
607771
  failureStore.insert({
606801
607772
  taskId: "",
606802
607773
  sessionId: `${Date.now()}`,
606803
607774
  repoRoot,
606804
607775
  failureType: "runtime-error",
606805
- 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),
606806
607777
  filePath: null,
606807
607778
  errorMessage: errMsg.slice(0, 500),
606808
607779
  context: null,