open-agents-ai 0.187.503 → 0.187.506

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
@@ -4609,17 +4609,17 @@ var init_memory_search = __esm({
4609
4609
  try {
4610
4610
  const { join: pathJoin } = await import("node:path");
4611
4611
  const { existsSync: pathExists } = await import("node:fs");
4612
- const { createRequire: createRequire7 } = await import("node:module");
4612
+ const { createRequire: createRequire8 } = await import("node:module");
4613
4613
  const oaDir = pathJoin(this.workingDir, ".oa");
4614
4614
  const epDbPath = pathJoin(oaDir, "episodes.db");
4615
4615
  const kgDbPath = pathJoin(oaDir, "knowledge.db");
4616
4616
  if (!pathExists(epDbPath)) {
4617
4617
  return { success: true, output: `No episode store found. Run tasks to build the knowledge graph.`, durationMs: performance.now() - start2 };
4618
4618
  }
4619
- const req2 = createRequire7(import.meta.url);
4620
- const Database2 = req2("better-sqlite3");
4619
+ const req2 = createRequire8(import.meta.url);
4620
+ const Database = req2("better-sqlite3");
4621
4621
  if (mode === "episodes") {
4622
- const db = new Database2(epDbPath, { readonly: true });
4622
+ const db = new Database(epDbPath, { readonly: true });
4623
4623
  const queryLower = query.toLowerCase();
4624
4624
  const rows = db.prepare(`
4625
4625
  SELECT * FROM episodes
@@ -4642,7 +4642,7 @@ ${lines.join("\n\n")}`,
4642
4642
  };
4643
4643
  }
4644
4644
  if (mode === "graph" && pathExists(kgDbPath)) {
4645
- const db = new Database2(kgDbPath, { readonly: true });
4645
+ const db = new Database(kgDbPath, { readonly: true });
4646
4646
  const queryLower = query.toLowerCase();
4647
4647
  const nodes = db.prepare(`
4648
4648
  SELECT * FROM kg_nodes WHERE text LIKE ? ORDER BY mention_count DESC LIMIT 20
@@ -4662,7 +4662,7 @@ ${lines.join("\n\n")}`,
4662
4662
  db.close();
4663
4663
  const epLines = [];
4664
4664
  if (episodeIds.size > 0 && pathExists(epDbPath)) {
4665
- const epDb = new Database2(epDbPath, { readonly: true });
4665
+ const epDb = new Database(epDbPath, { readonly: true });
4666
4666
  for (const epId of [...episodeIds].slice(0, maxResults)) {
4667
4667
  const ep = epDb.prepare("SELECT * FROM episodes WHERE id = ?").get(epId);
4668
4668
  if (ep)
@@ -5446,51 +5446,51 @@ var init_aiwg_health = __esm({
5446
5446
  const start2 = performance.now();
5447
5447
  const projectDir2 = args["project_dir"] || this.workingDir;
5448
5448
  const detailed = args["detailed"] ?? false;
5449
- const report = [];
5450
- report.push("# SDLC Health Report\n");
5449
+ const report2 = [];
5450
+ report2.push("# SDLC Health Report\n");
5451
5451
  const aiwgDir = join14(projectDir2, ".aiwg");
5452
5452
  const hasAiwg = existsSync10(aiwgDir);
5453
- report.push(`## AIWG Framework: ${hasAiwg ? "DEPLOYED" : "NOT DEPLOYED"}`);
5453
+ report2.push(`## AIWG Framework: ${hasAiwg ? "DEPLOYED" : "NOT DEPLOYED"}`);
5454
5454
  if (hasAiwg) {
5455
5455
  const aiwgArtifacts = this.scanAiwgArtifacts(aiwgDir);
5456
- report.push(` Artifacts found: ${aiwgArtifacts.total}`);
5456
+ report2.push(` Artifacts found: ${aiwgArtifacts.total}`);
5457
5457
  for (const [category, count] of Object.entries(aiwgArtifacts.categories)) {
5458
- report.push(` ${category}: ${count} file(s)`);
5458
+ report2.push(` ${category}: ${count} file(s)`);
5459
5459
  }
5460
5460
  } else {
5461
- report.push(" Tip: Run aiwg_setup to deploy SDLC framework");
5461
+ report2.push(" Tip: Run aiwg_setup to deploy SDLC framework");
5462
5462
  }
5463
- report.push("");
5464
- report.push("## Project Structure");
5463
+ report2.push("");
5464
+ report2.push("## Project Structure");
5465
5465
  const structure = this.analyzeStructure(projectDir2);
5466
- report.push(` Package manager: ${structure.packageManager}`);
5467
- report.push(` Language: ${structure.language}`);
5468
- report.push(` Has tests: ${structure.hasTests ? "YES" : "NO"}`);
5469
- report.push(` Has CI/CD: ${structure.hasCiCd ? "YES" : "NO"}`);
5470
- report.push(` Has README: ${structure.hasReadme ? "YES" : "NO"}`);
5471
- report.push(` Has LICENSE: ${structure.hasLicense ? "YES" : "NO"}`);
5472
- report.push(` Has .gitignore: ${structure.hasGitignore ? "YES" : "NO"}`);
5473
- report.push("");
5474
- report.push("## Documentation");
5466
+ report2.push(` Package manager: ${structure.packageManager}`);
5467
+ report2.push(` Language: ${structure.language}`);
5468
+ report2.push(` Has tests: ${structure.hasTests ? "YES" : "NO"}`);
5469
+ report2.push(` Has CI/CD: ${structure.hasCiCd ? "YES" : "NO"}`);
5470
+ report2.push(` Has README: ${structure.hasReadme ? "YES" : "NO"}`);
5471
+ report2.push(` Has LICENSE: ${structure.hasLicense ? "YES" : "NO"}`);
5472
+ report2.push(` Has .gitignore: ${structure.hasGitignore ? "YES" : "NO"}`);
5473
+ report2.push("");
5474
+ report2.push("## Documentation");
5475
5475
  const docs = this.analyzeDocumentation(projectDir2);
5476
- report.push(` README quality: ${docs.readmeQuality}`);
5477
- report.push(` API docs: ${docs.hasApiDocs ? "YES" : "NO"}`);
5478
- report.push(` Architecture docs: ${docs.hasArchDocs ? "YES" : "NO"}`);
5479
- report.push(` Doc files found: ${docs.docFileCount}`);
5480
- report.push("");
5476
+ report2.push(` README quality: ${docs.readmeQuality}`);
5477
+ report2.push(` API docs: ${docs.hasApiDocs ? "YES" : "NO"}`);
5478
+ report2.push(` Architecture docs: ${docs.hasArchDocs ? "YES" : "NO"}`);
5479
+ report2.push(` Doc files found: ${docs.docFileCount}`);
5480
+ report2.push("");
5481
5481
  const score = this.calculateMaturityScore(hasAiwg, structure, docs);
5482
- report.push("## SDLC Maturity Score");
5483
- report.push(` Score: ${score.total}/100`);
5484
- report.push(` Level: ${score.level}`);
5485
- report.push("");
5486
- report.push(" Breakdown:");
5482
+ report2.push("## SDLC Maturity Score");
5483
+ report2.push(` Score: ${score.total}/100`);
5484
+ report2.push(` Level: ${score.level}`);
5485
+ report2.push("");
5486
+ report2.push(" Breakdown:");
5487
5487
  for (const [area, pts] of Object.entries(score.breakdown)) {
5488
- report.push(` ${area}: ${pts}`);
5488
+ report2.push(` ${area}: ${pts}`);
5489
5489
  }
5490
- report.push("");
5491
- report.push("## Recommendations");
5490
+ report2.push("");
5491
+ report2.push("## Recommendations");
5492
5492
  for (const rec of score.recommendations) {
5493
- report.push(` - ${rec}`);
5493
+ report2.push(` - ${rec}`);
5494
5494
  }
5495
5495
  if (this.isAiwgInstalled()) {
5496
5496
  try {
@@ -5499,14 +5499,14 @@ var init_aiwg_health = __esm({
5499
5499
  encoding: "utf8",
5500
5500
  timeout: 15e3
5501
5501
  });
5502
- report.push("\n## AIWG Runtime Info");
5503
- report.push(runtimeInfo.trim());
5502
+ report2.push("\n## AIWG Runtime Info");
5503
+ report2.push(runtimeInfo.trim());
5504
5504
  } catch {
5505
5505
  }
5506
5506
  }
5507
5507
  return {
5508
5508
  success: true,
5509
- output: report.join("\n"),
5509
+ output: report2.join("\n"),
5510
5510
  durationMs: performance.now() - start2
5511
5511
  };
5512
5512
  }
@@ -6087,41 +6087,41 @@ var init_codebase_map = __esm({
6087
6087
  const maxDepth = args["depth"] || 3;
6088
6088
  const showFiles = args["show_files"] || false;
6089
6089
  try {
6090
- const report = [];
6091
- report.push("# Codebase Map\n");
6090
+ const report2 = [];
6091
+ report2.push("# Codebase Map\n");
6092
6092
  const projectInfo = this.detectProjectInfo(rootDir);
6093
6093
  if (projectInfo.name)
6094
- report.push(`**Project**: ${projectInfo.name}`);
6094
+ report2.push(`**Project**: ${projectInfo.name}`);
6095
6095
  if (projectInfo.description)
6096
- report.push(`**Description**: ${projectInfo.description}`);
6096
+ report2.push(`**Description**: ${projectInfo.description}`);
6097
6097
  if (projectInfo.language)
6098
- report.push(`**Language**: ${projectInfo.language}`);
6099
- report.push("");
6100
- report.push("## Key Files");
6098
+ report2.push(`**Language**: ${projectInfo.language}`);
6099
+ report2.push("");
6100
+ report2.push("## Key Files");
6101
6101
  const keyFiles = this.findKeyFiles(rootDir);
6102
6102
  for (const kf of keyFiles) {
6103
- report.push(` ${kf}`);
6103
+ report2.push(` ${kf}`);
6104
6104
  }
6105
- report.push("");
6106
- report.push("## Directory Structure");
6105
+ report2.push("");
6106
+ report2.push("## Directory Structure");
6107
6107
  const tree2 = this.buildTree(rootDir, rootDir, 0, maxDepth, showFiles);
6108
- report.push(tree2);
6109
- report.push("");
6110
- report.push("## Language Breakdown");
6108
+ report2.push(tree2);
6109
+ report2.push("");
6110
+ report2.push("## Language Breakdown");
6111
6111
  const languages = this.countLanguages(rootDir, 0, maxDepth + 1);
6112
6112
  const sortedLangs = [...languages.entries()].sort((a2, b) => b[1] - a2[1]);
6113
6113
  for (const [lang, count] of sortedLangs.slice(0, 10)) {
6114
- report.push(` ${lang.padEnd(16)} ${count} file(s)`);
6114
+ report2.push(` ${lang.padEnd(16)} ${count} file(s)`);
6115
6115
  }
6116
- report.push("");
6116
+ report2.push("");
6117
6117
  const stats = this.countStats(rootDir, 0, maxDepth + 1);
6118
- report.push("## Stats");
6119
- report.push(` Total files: ${stats.files}`);
6120
- report.push(` Total directories: ${stats.dirs}`);
6121
- report.push(` Estimated lines: ${stats.estimatedLines.toLocaleString()}`);
6118
+ report2.push("## Stats");
6119
+ report2.push(` Total files: ${stats.files}`);
6120
+ report2.push(` Total directories: ${stats.dirs}`);
6121
+ report2.push(` Estimated lines: ${stats.estimatedLines.toLocaleString()}`);
6122
6122
  return {
6123
6123
  success: true,
6124
- output: report.join("\n"),
6124
+ output: report2.join("\n"),
6125
6125
  durationMs: performance.now() - start2
6126
6126
  };
6127
6127
  } catch (error) {
@@ -6528,72 +6528,72 @@ var init_git_info = __esm({
6528
6528
  durationMs: performance.now() - start2
6529
6529
  };
6530
6530
  }
6531
- const report = [];
6532
- report.push("# Git Info\n");
6531
+ const report2 = [];
6532
+ report2.push("# Git Info\n");
6533
6533
  const branch = this.git(repoDir, "rev-parse --abbrev-ref HEAD");
6534
- report.push(`**Branch**: ${branch}`);
6534
+ report2.push(`**Branch**: ${branch}`);
6535
6535
  const remote = this.git(repoDir, "rev-parse --abbrev-ref @{upstream} 2>/dev/null || echo '(none)'");
6536
- report.push(`**Tracking**: ${remote}`);
6536
+ report2.push(`**Tracking**: ${remote}`);
6537
6537
  if (remote !== "(none)") {
6538
6538
  const ahead = this.git(repoDir, `rev-list --count @{upstream}..HEAD 2>/dev/null || echo 0`);
6539
6539
  const behind = this.git(repoDir, `rev-list --count HEAD..@{upstream} 2>/dev/null || echo 0`);
6540
- report.push(`**Ahead/Behind**: +${ahead}/-${behind}`);
6540
+ report2.push(`**Ahead/Behind**: +${ahead}/-${behind}`);
6541
6541
  }
6542
- report.push("");
6543
- report.push("## Status");
6542
+ report2.push("");
6543
+ report2.push("## Status");
6544
6544
  const status = this.git(repoDir, "status --short");
6545
6545
  if (status) {
6546
6546
  const lines = status.split("\n").filter((l2) => l2.trim());
6547
6547
  const staged = lines.filter((l2) => l2[0] !== " " && l2[0] !== "?").length;
6548
6548
  const unstaged = lines.filter((l2) => l2[1] === "M" || l2[1] === "D").length;
6549
6549
  const untracked = lines.filter((l2) => l2.startsWith("??")).length;
6550
- report.push(` Staged: ${staged} file(s)`);
6551
- report.push(` Unstaged: ${unstaged} file(s)`);
6552
- report.push(` Untracked: ${untracked} file(s)`);
6553
- report.push("");
6550
+ report2.push(` Staged: ${staged} file(s)`);
6551
+ report2.push(` Unstaged: ${unstaged} file(s)`);
6552
+ report2.push(` Untracked: ${untracked} file(s)`);
6553
+ report2.push("");
6554
6554
  for (const line of lines.slice(0, 30)) {
6555
- report.push(` ${line}`);
6555
+ report2.push(` ${line}`);
6556
6556
  }
6557
6557
  if (lines.length > 30) {
6558
- report.push(` ... ${lines.length - 30} more`);
6558
+ report2.push(` ... ${lines.length - 30} more`);
6559
6559
  }
6560
6560
  } else {
6561
- report.push(" Working tree clean");
6561
+ report2.push(" Working tree clean");
6562
6562
  }
6563
- report.push("");
6564
- report.push("## Recent Commits");
6563
+ report2.push("");
6564
+ report2.push("## Recent Commits");
6565
6565
  const log22 = this.git(repoDir, `log --oneline -${logCount} --no-decorate`);
6566
6566
  if (log22) {
6567
6567
  for (const line of log22.split("\n").filter((l2) => l2.trim())) {
6568
- report.push(` ${line}`);
6568
+ report2.push(` ${line}`);
6569
6569
  }
6570
6570
  } else {
6571
- report.push(" (no commits)");
6571
+ report2.push(" (no commits)");
6572
6572
  }
6573
- report.push("");
6573
+ report2.push("");
6574
6574
  if (showDiff) {
6575
- report.push("## Diff (staged + unstaged)");
6575
+ report2.push("## Diff (staged + unstaged)");
6576
6576
  const diff = this.git(repoDir, "diff HEAD 2>/dev/null || git diff");
6577
6577
  if (diff) {
6578
6578
  const truncated = diff.length > 5e3 ? diff.slice(0, 5e3) + "\n... (truncated)" : diff;
6579
- report.push("```diff");
6580
- report.push(truncated);
6581
- report.push("```");
6579
+ report2.push("```diff");
6580
+ report2.push(truncated);
6581
+ report2.push("```");
6582
6582
  } else {
6583
- report.push(" (no changes)");
6583
+ report2.push(" (no changes)");
6584
6584
  }
6585
6585
  } else {
6586
- report.push("## Diff Summary");
6586
+ report2.push("## Diff Summary");
6587
6587
  const diffStat = this.git(repoDir, "diff --stat HEAD 2>/dev/null || git diff --stat");
6588
6588
  if (diffStat) {
6589
- report.push(diffStat);
6589
+ report2.push(diffStat);
6590
6590
  } else {
6591
- report.push(" (no changes)");
6591
+ report2.push(" (no changes)");
6592
6592
  }
6593
6593
  }
6594
6594
  return {
6595
6595
  success: true,
6596
- output: report.join("\n"),
6596
+ output: report2.join("\n"),
6597
6597
  durationMs: performance.now() - start2
6598
6598
  };
6599
6599
  }
@@ -15371,8 +15371,8 @@ async function loadTranscribeCli() {
15371
15371
  }).trim();
15372
15372
  const tcPath = join24(globalRoot, "transcribe-cli");
15373
15373
  if (existsSync19(join24(tcPath, "dist", "index.js"))) {
15374
- const { createRequire: createRequire7 } = await import("node:module");
15375
- const req2 = createRequire7(import.meta.url);
15374
+ const { createRequire: createRequire8 } = await import("node:module");
15375
+ const req2 = createRequire8(import.meta.url);
15376
15376
  _tcModule = req2(join24(tcPath, "dist", "index.js"));
15377
15377
  return _tcModule;
15378
15378
  }
@@ -15385,8 +15385,8 @@ async function loadTranscribeCli() {
15385
15385
  for (const ver of readdirSync38(nvmBase)) {
15386
15386
  const tcPath = join24(nvmBase, ver, "lib", "node_modules", "transcribe-cli");
15387
15387
  if (existsSync19(join24(tcPath, "dist", "index.js"))) {
15388
- const { createRequire: createRequire7 } = await import("node:module");
15389
- const req2 = createRequire7(import.meta.url);
15388
+ const { createRequire: createRequire8 } = await import("node:module");
15389
+ const req2 = createRequire8(import.meta.url);
15390
15390
  _tcModule = req2(join24(tcPath, "dist", "index.js"));
15391
15391
  return _tcModule;
15392
15392
  }
@@ -228359,17 +228359,17 @@ var init_RTCPeerConnection = __esm({
228359
228359
  }
228360
228360
  getStats() {
228361
228361
  return new Promise((resolve43) => {
228362
- const report = /* @__PURE__ */ new Map();
228362
+ const report2 = /* @__PURE__ */ new Map();
228363
228363
  const cp2 = __privateGet9(this, _peerConnection)?.getSelectedCandidatePair();
228364
228364
  const bytesSent = __privateGet9(this, _peerConnection)?.bytesSent();
228365
228365
  const bytesReceived = __privateGet9(this, _peerConnection)?.bytesReceived();
228366
228366
  const rtt = __privateGet9(this, _peerConnection)?.rtt();
228367
228367
  if (!cp2) {
228368
- return resolve43(report);
228368
+ return resolve43(report2);
228369
228369
  }
228370
228370
  const localIdRs = getRandomString(8);
228371
228371
  const localId = "RTCIceCandidate_" + localIdRs;
228372
- report.set(localId, {
228372
+ report2.set(localId, {
228373
228373
  id: localId,
228374
228374
  type: "local-candidate",
228375
228375
  timestamp: Date.now(),
@@ -228379,7 +228379,7 @@ var init_RTCPeerConnection = __esm({
228379
228379
  });
228380
228380
  const remoteIdRs = getRandomString(8);
228381
228381
  const remoteId = "RTCIceCandidate_" + remoteIdRs;
228382
- report.set(remoteId, {
228382
+ report2.set(remoteId, {
228383
228383
  id: remoteId,
228384
228384
  type: "remote-candidate",
228385
228385
  timestamp: Date.now(),
@@ -228388,7 +228388,7 @@ var init_RTCPeerConnection = __esm({
228388
228388
  port: cp2.remote.port
228389
228389
  });
228390
228390
  const candidateId = "RTCIceCandidatePair_" + localIdRs + "_" + remoteIdRs;
228391
- report.set(candidateId, {
228391
+ report2.set(candidateId, {
228392
228392
  id: candidateId,
228393
228393
  type: "candidate-pair",
228394
228394
  timestamp: Date.now(),
@@ -228403,7 +228403,7 @@ var init_RTCPeerConnection = __esm({
228403
228403
  currentRoundTripTime: rtt
228404
228404
  });
228405
228405
  const transportId = "RTCTransport_0_1";
228406
- report.set(transportId, {
228406
+ report2.set(transportId, {
228407
228407
  id: transportId,
228408
228408
  timestamp: Date.now(),
228409
228409
  type: "transport",
@@ -228413,14 +228413,14 @@ var init_RTCPeerConnection = __esm({
228413
228413
  selectedCandidatePairId: candidateId,
228414
228414
  selectedCandidatePairChanges: 1
228415
228415
  });
228416
- report.set("P", {
228416
+ report2.set("P", {
228417
228417
  id: "P",
228418
228418
  type: "peer-connection",
228419
228419
  timestamp: Date.now(),
228420
228420
  dataChannelsOpened: __privateGet9(this, _dataChannels).size,
228421
228421
  dataChannelsClosed: __privateGet9(this, _dataChannelsClosed)
228422
228422
  });
228423
- return resolve43(report);
228423
+ return resolve43(report2);
228424
228424
  });
228425
228425
  }
228426
228426
  getTransceivers() {
@@ -474718,22 +474718,22 @@ var require_dist2 = __commonJS({
474718
474718
  return state.paths.slice(0, state.options.maxFiles);
474719
474719
  };
474720
474720
  var onlyCountsAsync = (state, error, callback$1) => {
474721
- report(error, callback$1, state.counts, state.options.suppressErrors);
474721
+ report2(error, callback$1, state.counts, state.options.suppressErrors);
474722
474722
  return null;
474723
474723
  };
474724
474724
  var defaultAsync = (state, error, callback$1) => {
474725
- report(error, callback$1, state.paths, state.options.suppressErrors);
474725
+ report2(error, callback$1, state.paths, state.options.suppressErrors);
474726
474726
  return null;
474727
474727
  };
474728
474728
  var limitFilesAsync = (state, error, callback$1) => {
474729
- report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
474729
+ report2(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
474730
474730
  return null;
474731
474731
  };
474732
474732
  var groupsAsync = (state, error, callback$1) => {
474733
- report(error, callback$1, state.groups, state.options.suppressErrors);
474733
+ report2(error, callback$1, state.groups, state.options.suppressErrors);
474734
474734
  return null;
474735
474735
  };
474736
- function report(error, callback$1, output, suppressErrors) {
474736
+ function report2(error, callback$1, output, suppressErrors) {
474737
474737
  if (error && !suppressErrors) callback$1(error, output);
474738
474738
  else callback$1(null, output);
474739
474739
  }
@@ -500899,10 +500899,29 @@ var init_ts_morph_parser = __esm({
500899
500899
  });
500900
500900
 
500901
500901
  // packages/indexer/dist/code-graph-db.js
500902
- import Database from "better-sqlite3";
500902
+ import { createRequire as createRequire2 } from "node:module";
500903
500903
  import { createHash as createHash5 } from "node:crypto";
500904
500904
  import { mkdirSync as mkdirSync12, readFileSync as readFileSync26 } from "node:fs";
500905
500905
  import { join as join50, dirname as dirname14, extname as extname9 } from "node:path";
500906
+ function loadDatabaseCtor() {
500907
+ if (_DatabaseCtor)
500908
+ return _DatabaseCtor;
500909
+ try {
500910
+ const req2 = createRequire2(import.meta.url);
500911
+ _DatabaseCtor = req2("better-sqlite3");
500912
+ return _DatabaseCtor;
500913
+ } catch (err) {
500914
+ const msg = err?.message ?? String(err);
500915
+ throw new Error(`CodeGraphDB requires the optional 'better-sqlite3' native module, but it failed to load.
500916
+ Install it manually:
500917
+ npm i -g better-sqlite3 (matches your global open-agents-ai install)
500918
+ If the install fails, install build tools first:
500919
+ Debian/Ubuntu: sudo apt install -y python3 build-essential
500920
+ Fedora/RHEL: sudo dnf install -y python3 gcc-c++ make
500921
+ macOS: xcode-select --install
500922
+ Underlying error: ${msg}`);
500923
+ }
500924
+ }
500906
500925
  function extractFileSymbols(content, filePath) {
500907
500926
  const isPython = /\.py$/.test(filePath);
500908
500927
  const patterns = isPython ? [{ kind: "function", re: /^\s*(async\s+)?def\s+(\w+)/m }, { kind: "class", re: /^\s*class\s+(\w+)/m }] : TS_PATTERNS2;
@@ -500958,11 +500977,12 @@ function hashContent(content) {
500958
500977
  function detectLanguage(filePath) {
500959
500978
  return EXT_TO_LANG[extname9(filePath)] ?? "unknown";
500960
500979
  }
500961
- var TS_PATTERNS2, EXT_TO_LANG, CodeGraphDB;
500980
+ var _DatabaseCtor, TS_PATTERNS2, EXT_TO_LANG, CodeGraphDB;
500962
500981
  var init_code_graph_db = __esm({
500963
500982
  "packages/indexer/dist/code-graph-db.js"() {
500964
500983
  "use strict";
500965
500984
  init_ts_morph_parser();
500985
+ _DatabaseCtor = null;
500966
500986
  TS_PATTERNS2 = [
500967
500987
  { kind: "function", re: /^\s*(export\s+)?(async\s+)?function\s+(\w+)/m },
500968
500988
  { kind: "class", re: /^\s*(export\s+)?(abstract\s+)?class\s+(\w+)/m },
@@ -501003,6 +501023,7 @@ var init_code_graph_db = __esm({
501003
501023
  this.rootDir = rootDir;
501004
501024
  const resolvedPath = dbPath ?? join50(rootDir, ".oa", "index", "code-graph.db");
501005
501025
  mkdirSync12(dirname14(resolvedPath), { recursive: true });
501026
+ const Database = loadDatabaseCtor();
501006
501027
  this.db = new Database(resolvedPath);
501007
501028
  this.db.pragma("journal_mode = WAL");
501008
501029
  this.db.pragma("foreign_keys = ON");
@@ -506701,9 +506722,9 @@ function _findNemotronScript() {
506701
506722
  return null;
506702
506723
  }
506703
506724
  function _wordSimilarity(a2, b) {
506704
- const tokenize4 = (s2) => new Set(s2.toLowerCase().replace(/[^a-z0-9\s']/g, " ").split(/\s+/).filter(Boolean));
506705
- const sa = tokenize4(a2);
506706
- const sb = tokenize4(b);
506725
+ const tokenize5 = (s2) => new Set(s2.toLowerCase().replace(/[^a-z0-9\s']/g, " ").split(/\s+/).filter(Boolean));
506726
+ const sa = tokenize5(a2);
506727
+ const sb = tokenize5(b);
506707
506728
  if (sa.size === 0 && sb.size === 0)
506708
506729
  return 1;
506709
506730
  let inter = 0;
@@ -515581,12 +515602,12 @@ var init_pressure_gate = __esm({
515581
515602
  });
515582
515603
 
515583
515604
  // packages/memory/dist/db.js
515584
- import { createRequire as createRequire2 } from "node:module";
515605
+ import { createRequire as createRequire3 } from "node:module";
515585
515606
  function getDatabase() {
515586
515607
  if (_Database !== null)
515587
515608
  return _Database;
515588
515609
  try {
515589
- const req2 = createRequire2(import.meta.url);
515610
+ const req2 = createRequire3(import.meta.url);
515590
515611
  _Database = req2("better-sqlite3");
515591
515612
  } catch {
515592
515613
  throw new Error("better-sqlite3 is not available (native module build may have failed).\nTry: npm rebuild better-sqlite3\nMemory features (SQLite) are disabled until this is resolved.");
@@ -515594,8 +515615,8 @@ function getDatabase() {
515594
515615
  return _Database;
515595
515616
  }
515596
515617
  function initDb(dbPath) {
515597
- const Database2 = getDatabase();
515598
- const db = new Database2(dbPath);
515618
+ const Database = getDatabase();
515619
+ const db = new Database(dbPath);
515599
515620
  db.pragma("journal_mode = WAL");
515600
515621
  db.pragma("foreign_keys = ON");
515601
515622
  runMigrations(db);
@@ -516834,6 +516855,11 @@ var init_episodeStore = __esm({
516834
516855
  };
516835
516856
  EpisodeStore = class {
516836
516857
  db;
516858
+ /** Read-only access to the underlying SQLite handle for cross-cutting tools
516859
+ * like SelfModel that need to query multiple tables atomically. */
516860
+ getDb() {
516861
+ return this.db;
516862
+ }
516837
516863
  /** WO-AM-05: Optional TemporalGraph for Zettelkasten auto-linking */
516838
516864
  graph = null;
516839
516865
  /** WO-AM-05: Zettelkasten config for neighbor linking */
@@ -519874,6 +519900,1173 @@ var init_crl = __esm({
519874
519900
  }
519875
519901
  });
519876
519902
 
519903
+ // packages/memory/dist/homeostaticRegulation.js
519904
+ function clamp(x, lo, hi) {
519905
+ if (!Number.isFinite(x))
519906
+ return (lo + hi) / 2;
519907
+ if (x < lo)
519908
+ return lo;
519909
+ if (x > hi)
519910
+ return hi;
519911
+ return x;
519912
+ }
519913
+ function sanitizeEmotionalState(raw) {
519914
+ if (!raw)
519915
+ return { valence: 0, arousal: 0 };
519916
+ return {
519917
+ valence: clampValence(raw.valence ?? 0),
519918
+ arousal: clampArousal(raw.arousal ?? 0),
519919
+ emotion: typeof raw.emotion === "string" ? raw.emotion : void 0
519920
+ };
519921
+ }
519922
+ function importanceMultiplier(state, tuning = DEFAULT_ENCODING) {
519923
+ const v = clampValence(state.valence);
519924
+ const a2 = clampArousal(state.arousal);
519925
+ const valenceBoost = Math.max(0, v) * tuning.valenceWeight;
519926
+ const arousalBoost = a2 * tuning.arousalWeight;
519927
+ const raw = 1 + valenceBoost + arousalBoost;
519928
+ return Math.min(raw, tuning.maxMultiplier);
519929
+ }
519930
+ function modulateImportance(baseImportance, state, tuning = DEFAULT_ENCODING) {
519931
+ if (!state)
519932
+ return baseImportance;
519933
+ const mult = importanceMultiplier(state, tuning);
519934
+ const adjusted = baseImportance * mult;
519935
+ if (adjusted < 0)
519936
+ return 0;
519937
+ if (adjusted > 10)
519938
+ return 10;
519939
+ return adjusted;
519940
+ }
519941
+ function congruenceMultiplier(current, memory, tuning = DEFAULT_RETRIEVAL) {
519942
+ const valenceDist = Math.abs(clampValence(current.valence) - clampValence(memory.valence));
519943
+ const arousalDist = Math.abs(clampArousal(current.arousal) - clampArousal(memory.arousal));
519944
+ const valenceSim = 1 - valenceDist / 2;
519945
+ const arousalSim = 1 - arousalDist;
519946
+ const valenceBonus = (valenceSim - 0.5) * tuning.valenceCongruence;
519947
+ const arousalBonus = (arousalSim - 0.5) * tuning.arousalCongruence;
519948
+ return 1 + valenceBonus + arousalBonus;
519949
+ }
519950
+ function modulateRetrievalScore(baseScore, current, memory, tuning = DEFAULT_RETRIEVAL) {
519951
+ if (!current || !memory)
519952
+ return baseScore;
519953
+ return baseScore * congruenceMultiplier(current, memory, tuning);
519954
+ }
519955
+ function createHomeostaticState(initial, target = DEFAULT_TARGET, windowSize = DEFAULT_WINDOW) {
519956
+ const current = sanitizeEmotionalState(initial ?? { valence: 0, arousal: 0 });
519957
+ return {
519958
+ current,
519959
+ streak: 1,
519960
+ target: sanitizeEmotionalState(target),
519961
+ recent: [current],
519962
+ windowSize: Math.max(1, Math.floor(windowSize))
519963
+ };
519964
+ }
519965
+ function inSameBand(a2, b) {
519966
+ return Math.abs(clampValence(a2.valence) - clampValence(b.valence)) < STREAK_TOLERANCE && Math.abs(clampArousal(a2.arousal) - clampArousal(b.arousal)) < STREAK_TOLERANCE;
519967
+ }
519968
+ function observeEmotionalState(prev, next) {
519969
+ const sample = sanitizeEmotionalState(next);
519970
+ const continued = inSameBand(prev.current, sample);
519971
+ const recent = [sample, ...prev.recent].slice(0, prev.windowSize);
519972
+ return {
519973
+ ...prev,
519974
+ current: sample,
519975
+ streak: continued ? prev.streak + 1 : 1,
519976
+ recent
519977
+ };
519978
+ }
519979
+ function deviationFromTarget(state) {
519980
+ const dv = clampValence(state.current.valence) - clampValence(state.target.valence);
519981
+ const da = clampArousal(state.current.arousal) - clampArousal(state.target.arousal);
519982
+ return Math.sqrt(dv * dv + da * da);
519983
+ }
519984
+ function suggestRegulation(state) {
519985
+ const dv = clampValence(state.current.valence) - clampValence(state.target.valence);
519986
+ const da = clampArousal(state.current.arousal) - clampArousal(state.target.arousal);
519987
+ const NEAR = 0.15;
519988
+ if (Math.abs(dv) < NEAR && Math.abs(da) < NEAR)
519989
+ return null;
519990
+ if (state.streak > 8 && Math.abs(dv) >= NEAR) {
519991
+ return dv < 0 ? "seek-positive-experience" : "introduce-novelty";
519992
+ }
519993
+ if (da > NEAR && state.current.arousal > 0.85)
519994
+ return "calming-activity";
519995
+ if (da < -NEAR && state.current.arousal < 0.15)
519996
+ return "energizing-activity";
519997
+ if (dv < -NEAR)
519998
+ return "self-compassion";
519999
+ if (dv > NEAR)
520000
+ return "anchor-attention";
520001
+ return null;
520002
+ }
520003
+ var DEFAULT_ENCODING, DEFAULT_RETRIEVAL, clampValence, clampArousal, DEFAULT_TARGET, DEFAULT_WINDOW, STREAK_TOLERANCE;
520004
+ var init_homeostaticRegulation = __esm({
520005
+ "packages/memory/dist/homeostaticRegulation.js"() {
520006
+ "use strict";
520007
+ DEFAULT_ENCODING = {
520008
+ valenceWeight: 0.3,
520009
+ arousalWeight: 0.2,
520010
+ maxMultiplier: 1.5
520011
+ };
520012
+ DEFAULT_RETRIEVAL = {
520013
+ valenceCongruence: 0.5,
520014
+ arousalCongruence: 0.3
520015
+ };
520016
+ clampValence = (v) => clamp(v, -1, 1);
520017
+ clampArousal = (a2) => clamp(a2, 0, 1);
520018
+ DEFAULT_TARGET = { valence: 0.2, arousal: 0.4 };
520019
+ DEFAULT_WINDOW = 16;
520020
+ STREAK_TOLERANCE = 0.15;
520021
+ }
520022
+ });
520023
+
520024
+ // packages/memory/dist/selfModel.js
520025
+ var ConfidenceTracker, MODALITIES, DECAY_CLASSES, DEFAULT_OPTIONS, SelfModel;
520026
+ var init_selfModel = __esm({
520027
+ "packages/memory/dist/selfModel.js"() {
520028
+ "use strict";
520029
+ init_episodeStore();
520030
+ ConfidenceTracker = class {
520031
+ windowSize;
520032
+ samples = [];
520033
+ constructor(windowSize = 200) {
520034
+ this.windowSize = windowSize;
520035
+ if (this.windowSize <= 0)
520036
+ throw new Error("windowSize must be > 0");
520037
+ }
520038
+ record(sample) {
520039
+ this.samples.push(sample);
520040
+ if (this.samples.length > this.windowSize) {
520041
+ this.samples.splice(0, this.samples.length - this.windowSize);
520042
+ }
520043
+ }
520044
+ size() {
520045
+ return this.samples.length;
520046
+ }
520047
+ /** Compute calibration statistics. Empty samples → neutral (0.5/0.5/0). */
520048
+ compute() {
520049
+ const n2 = this.samples.length;
520050
+ if (n2 === 0) {
520051
+ return {
520052
+ averageConfidence: 0.5,
520053
+ actualAccuracy: 0.5,
520054
+ calibrationGap: 0,
520055
+ byDomain: {},
520056
+ sampleCount: 0
520057
+ };
520058
+ }
520059
+ let sumConf = 0;
520060
+ let sumCorrect = 0;
520061
+ const byDomain2 = /* @__PURE__ */ new Map();
520062
+ for (const s2 of this.samples) {
520063
+ sumConf += s2.stated;
520064
+ if (s2.correct)
520065
+ sumCorrect++;
520066
+ if (s2.domain) {
520067
+ const d2 = byDomain2.get(s2.domain) ?? { conf: 0, correct: 0, n: 0 };
520068
+ d2.conf += s2.stated;
520069
+ d2.correct += s2.correct ? 1 : 0;
520070
+ d2.n += 1;
520071
+ byDomain2.set(s2.domain, d2);
520072
+ }
520073
+ }
520074
+ const avgConf = sumConf / n2;
520075
+ const acc = sumCorrect / n2;
520076
+ const byDomainOut = {};
520077
+ for (const [name10, d2] of byDomain2) {
520078
+ byDomainOut[name10] = {
520079
+ confidence: d2.conf / d2.n,
520080
+ accuracy: d2.correct / d2.n,
520081
+ n: d2.n
520082
+ };
520083
+ }
520084
+ return {
520085
+ averageConfidence: avgConf,
520086
+ actualAccuracy: acc,
520087
+ calibrationGap: avgConf - acc,
520088
+ byDomain: byDomainOut,
520089
+ sampleCount: n2
520090
+ };
520091
+ }
520092
+ };
520093
+ MODALITIES = [
520094
+ "tool_call",
520095
+ "tool_result",
520096
+ "visual",
520097
+ "audio",
520098
+ "code",
520099
+ "social",
520100
+ "spatial",
520101
+ "text",
520102
+ "reflection",
520103
+ "gist"
520104
+ ];
520105
+ DECAY_CLASSES = ["session", "daily", "procedural", "permanent"];
520106
+ DEFAULT_OPTIONS = {
520107
+ importanceBands: { low: 3, medium: 6, high: 8, critical: 10 },
520108
+ approachingDecayFrac: 0.25,
520109
+ proceduralWeakness: 0.5
520110
+ };
520111
+ SelfModel = class {
520112
+ db;
520113
+ tracker;
520114
+ opts;
520115
+ constructor(db, tracker = new ConfidenceTracker(), options2 = {}) {
520116
+ this.db = db;
520117
+ this.tracker = tracker;
520118
+ this.opts = { ...DEFAULT_OPTIONS, ...options2 };
520119
+ }
520120
+ computeStats() {
520121
+ const total = this.scalarCount("SELECT COUNT(*) AS c FROM episodes");
520122
+ const byModality = this.bucketCount("modality", MODALITIES);
520123
+ const byDecayClass = this.bucketCount("decay_class", DECAY_CLASSES);
520124
+ const byImportance = this.importanceBuckets();
520125
+ const avg = this.db.prepare("SELECT AVG(importance) AS imp, AVG(strength) AS str FROM episodes").get();
520126
+ return {
520127
+ totalEpisodes: total,
520128
+ byModality,
520129
+ byDecayClass,
520130
+ byImportance,
520131
+ totalKnowledgeGraphNodes: this.tableCount("kg_nodes"),
520132
+ totalKnowledgeGraphEdges: this.tableCount("kg_edges"),
520133
+ // Real table is `procedural_memory` (singular). Filter soft-deleted rows.
520134
+ totalProceduralMemories: this.scalarCount("SELECT COUNT(*) AS c FROM procedural_memory WHERE deleted_at IS NULL"),
520135
+ averageImportance: avg?.imp ?? 0,
520136
+ averageStrength: avg?.str ?? 0
520137
+ };
520138
+ }
520139
+ approachingDecay(now = Date.now()) {
520140
+ const frac = this.opts.approachingDecayFrac;
520141
+ const sessionCutoff = now - DECAY_TAU.session * (1 - frac);
520142
+ const dailyCutoff = now - DECAY_TAU.daily * (1 - frac);
520143
+ const session = this.idsByDecay("session", sessionCutoff);
520144
+ const daily = this.idsByDecay("daily", dailyCutoff);
520145
+ const procedural = this.weakProcedural(this.opts.proceduralWeakness);
520146
+ return { session, daily, procedural };
520147
+ }
520148
+ blindSpots() {
520149
+ const stats = this.computeStats();
520150
+ if (stats.totalEpisodes === 0)
520151
+ return [];
520152
+ const expected = stats.totalEpisodes / MODALITIES.length;
520153
+ const out = [];
520154
+ for (const m2 of MODALITIES) {
520155
+ const observed = stats.byModality[m2] ?? 0;
520156
+ if (observed >= expected * 0.5)
520157
+ continue;
520158
+ const ratio = observed / Math.max(1, expected);
520159
+ const severity = ratio < 0.05 ? "high" : ratio < 0.2 ? "medium" : "low";
520160
+ out.push({ modality: m2, observed, expected, severity });
520161
+ }
520162
+ return out.sort((a2, b) => a2.observed - b.observed);
520163
+ }
520164
+ /** Compose a single snapshot — what you'd hand the agent to introspect. */
520165
+ snapshot() {
520166
+ return {
520167
+ generatedAt: Date.now(),
520168
+ stats: this.computeStats(),
520169
+ calibration: this.tracker.compute(),
520170
+ approachingDecay: this.approachingDecay(),
520171
+ blindSpots: this.blindSpots()
520172
+ };
520173
+ }
520174
+ // ── private helpers ────────────────────────────────────────────────────────
520175
+ scalarCount(sql) {
520176
+ try {
520177
+ const row = this.db.prepare(sql).get();
520178
+ return row?.c ?? 0;
520179
+ } catch {
520180
+ return 0;
520181
+ }
520182
+ }
520183
+ tableCount(name10) {
520184
+ try {
520185
+ const row = this.db.prepare(`SELECT COUNT(*) AS c FROM ${name10}`).get();
520186
+ return row?.c ?? 0;
520187
+ } catch {
520188
+ return 0;
520189
+ }
520190
+ }
520191
+ bucketCount(column, keys) {
520192
+ const out = {};
520193
+ for (const k of keys)
520194
+ out[k] = 0;
520195
+ try {
520196
+ const rows = this.db.prepare(`SELECT ${column} AS k, COUNT(*) AS c FROM episodes GROUP BY ${column}`).all();
520197
+ for (const r2 of rows)
520198
+ out[r2.k] = r2.c;
520199
+ } catch {
520200
+ }
520201
+ return out;
520202
+ }
520203
+ importanceBuckets() {
520204
+ const b = this.opts.importanceBands;
520205
+ const safe = (n2, fallback) => Number.isFinite(n2) ? n2 : fallback;
520206
+ const lowEnd = safe(b.low, 3) + 1;
520207
+ const medEnd = safe(b.medium, 6) + 1;
520208
+ const highEnd = safe(b.high, 8) + 1;
520209
+ const critEnd = safe(b.critical, 10) + 1;
520210
+ const q = (lo, hi) => {
520211
+ try {
520212
+ const row = this.db.prepare(`SELECT COUNT(*) AS c FROM episodes WHERE importance >= ? AND importance < ?`).get(lo, hi);
520213
+ return row?.c ?? 0;
520214
+ } catch {
520215
+ return 0;
520216
+ }
520217
+ };
520218
+ return {
520219
+ low: q(0, lowEnd),
520220
+ medium: q(lowEnd, medEnd),
520221
+ high: q(medEnd, highEnd),
520222
+ critical: q(highEnd, critEnd)
520223
+ };
520224
+ }
520225
+ idsByDecay(klass, cutoff) {
520226
+ try {
520227
+ const rows = this.db.prepare(`SELECT id FROM episodes WHERE decay_class = ? AND timestamp <= ? ORDER BY timestamp ASC LIMIT 200`).all(klass, cutoff);
520228
+ return rows.map((r2) => r2.id);
520229
+ } catch {
520230
+ return [];
520231
+ }
520232
+ }
520233
+ weakProcedural(threshold) {
520234
+ try {
520235
+ const rows = this.db.prepare(`SELECT id FROM procedural_memory
520236
+ WHERE deleted_at IS NULL
520237
+ AND COALESCE(utility, 0.5) < ?
520238
+ ORDER BY utility ASC
520239
+ LIMIT 200`).all(threshold);
520240
+ return rows.map((r2) => r2.id);
520241
+ } catch {
520242
+ return [];
520243
+ }
520244
+ }
520245
+ };
520246
+ }
520247
+ });
520248
+
520249
+ // packages/memory/dist/predictionStore.js
520250
+ function clamp01(x) {
520251
+ if (!Number.isFinite(x))
520252
+ return 0.5;
520253
+ if (x < 0)
520254
+ return 0;
520255
+ if (x > 1)
520256
+ return 1;
520257
+ return x;
520258
+ }
520259
+ function tokenSimilarity(a2, b) {
520260
+ const tokensA = tokenize4(a2);
520261
+ const tokensB = tokenize4(b);
520262
+ if (tokensA.size === 0 && tokensB.size === 0)
520263
+ return 1;
520264
+ if (tokensA.size === 0 || tokensB.size === 0)
520265
+ return 0;
520266
+ let inter = 0;
520267
+ for (const t2 of tokensA)
520268
+ if (tokensB.has(t2))
520269
+ inter++;
520270
+ const union = tokensA.size + tokensB.size - inter;
520271
+ return union > 0 ? inter / union : 0;
520272
+ }
520273
+ function tokenize4(s2) {
520274
+ return new Set(s2.toLowerCase().split(/[^a-z0-9_]+/).filter((t2) => t2.length > 1));
520275
+ }
520276
+ function durationError(predicted, actual) {
520277
+ if (predicted == null || actual == null)
520278
+ return 0;
520279
+ const safePred = Math.max(predicted, 50);
520280
+ const ratio = Math.abs(predicted - actual) / safePred;
520281
+ return clamp01(ratio);
520282
+ }
520283
+ var DEFAULT_AXIS_WEIGHTS, PredictionStore;
520284
+ var init_predictionStore = __esm({
520285
+ "packages/memory/dist/predictionStore.js"() {
520286
+ "use strict";
520287
+ DEFAULT_AXIS_WEIGHTS = {
520288
+ outcome: 0.4,
520289
+ success: 0.3,
520290
+ confidence: 0.15,
520291
+ duration: 0.15
520292
+ };
520293
+ PredictionStore = class {
520294
+ capacity;
520295
+ axisWeights;
520296
+ pending = /* @__PURE__ */ new Map();
520297
+ history = [];
520298
+ constructor(options2 = {}) {
520299
+ this.capacity = Math.max(1, options2.capacity ?? 256);
520300
+ this.axisWeights = { ...DEFAULT_AXIS_WEIGHTS, ...options2.axisWeights ?? {} };
520301
+ }
520302
+ /** Record an outgoing prediction. Replaces any prior prediction with the
520303
+ * same correlationId — the latest is what we'll match against. */
520304
+ predict(p2) {
520305
+ const sanitized = {
520306
+ ...p2,
520307
+ predictedConfidence: clamp01(p2.predictedConfidence),
520308
+ predictedDuration: p2.predictedDuration != null && Number.isFinite(p2.predictedDuration) ? Math.max(0, p2.predictedDuration) : null
520309
+ };
520310
+ this.pending.set(p2.correlationId, sanitized);
520311
+ }
520312
+ /** Match an observation to a pending prediction. Returns the error or null
520313
+ * if no prediction was recorded for this correlationId (drop silently). */
520314
+ observe(correlationId, observed) {
520315
+ const pred = this.pending.get(correlationId);
520316
+ if (!pred)
520317
+ return null;
520318
+ this.pending.delete(correlationId);
520319
+ const actualDuration = observed.actualDuration != null && Number.isFinite(observed.actualDuration) ? Math.max(0, observed.actualDuration) : null;
520320
+ const sim = tokenSimilarity(pred.predictedOutcome, observed.actualOutcome);
520321
+ const outcomeErr = clamp01(1 - sim);
520322
+ const successErr = pred.predictedSuccess === observed.actualSuccess ? 0 : 1;
520323
+ const confidenceErr = clamp01(observed.actualSuccess ? 1 - pred.predictedConfidence : pred.predictedConfidence);
520324
+ const durationErr = durationError(pred.predictedDuration, actualDuration);
520325
+ const w = this.axisWeights;
520326
+ const total = w.outcome * outcomeErr + w.success * successErr + w.confidence * confidenceErr + w.duration * durationErr;
520327
+ const sumWeights = w.outcome + w.success + w.confidence + w.duration;
520328
+ const errorMagnitude = clamp01(sumWeights > 0 ? total / sumWeights : 0);
520329
+ const errorByAxis = {
520330
+ outcome: outcomeErr,
520331
+ success: successErr,
520332
+ confidence: confidenceErr,
520333
+ duration: durationErr
520334
+ };
520335
+ const dominantAxis = Object.entries(errorByAxis).reduce((best, cur) => cur[1] > best[1] ? cur : best, ["outcome", -1])[0];
520336
+ const err = {
520337
+ prediction: pred,
520338
+ actualOutcome: observed.actualOutcome,
520339
+ actualSuccess: observed.actualSuccess,
520340
+ actualDuration,
520341
+ observedAt: Date.now(),
520342
+ errorMagnitude,
520343
+ errorByAxis,
520344
+ dominantAxis,
520345
+ // Learning signal: large errors with high confidence drive bigger updates
520346
+ learningSignal: clamp01(errorMagnitude * (0.5 + 0.5 * pred.predictedConfidence))
520347
+ };
520348
+ this.history.push(err);
520349
+ if (this.history.length > this.capacity) {
520350
+ this.history.splice(0, this.history.length - this.capacity);
520351
+ }
520352
+ return err;
520353
+ }
520354
+ /** All pending predictions — predictions submitted but not yet observed. */
520355
+ pendingCount() {
520356
+ return this.pending.size;
520357
+ }
520358
+ /** All recorded errors, oldest-first. */
520359
+ getHistory() {
520360
+ return [...this.history];
520361
+ }
520362
+ /** Average error magnitude over the last N samples. Useful for self-model. */
520363
+ averageError(lastN) {
520364
+ if (this.history.length === 0)
520365
+ return 0;
520366
+ const slice2 = lastN ? this.history.slice(-lastN) : this.history;
520367
+ return slice2.reduce((s2, e2) => s2 + e2.errorMagnitude, 0) / slice2.length;
520368
+ }
520369
+ /** Current per-axis bias — points at the axis we're systematically wrong on. */
520370
+ axisProfile(lastN) {
520371
+ const slice2 = lastN ? this.history.slice(-lastN) : this.history;
520372
+ const out = { outcome: 0, success: 0, confidence: 0, duration: 0 };
520373
+ if (slice2.length === 0)
520374
+ return out;
520375
+ for (const e2 of slice2) {
520376
+ out.outcome += e2.errorByAxis.outcome;
520377
+ out.success += e2.errorByAxis.success;
520378
+ out.confidence += e2.errorByAxis.confidence;
520379
+ out.duration += e2.errorByAxis.duration;
520380
+ }
520381
+ out.outcome /= slice2.length;
520382
+ out.success /= slice2.length;
520383
+ out.confidence /= slice2.length;
520384
+ out.duration /= slice2.length;
520385
+ return out;
520386
+ }
520387
+ /** Drop everything — useful between sessions / on context switch. */
520388
+ clear() {
520389
+ this.pending.clear();
520390
+ this.history.length = 0;
520391
+ }
520392
+ };
520393
+ }
520394
+ });
520395
+
520396
+ // packages/memory/dist/embodiedTrace.js
520397
+ function clamp2(x, lo, hi) {
520398
+ if (!Number.isFinite(x))
520399
+ return (lo + hi) / 2;
520400
+ if (x < lo)
520401
+ return lo;
520402
+ if (x > hi)
520403
+ return hi;
520404
+ return x;
520405
+ }
520406
+ function clamp012(x) {
520407
+ return clamp2(x, 0, 1);
520408
+ }
520409
+ function nonNegative(x) {
520410
+ if (!Number.isFinite(x) || x < 0)
520411
+ return 0;
520412
+ return x;
520413
+ }
520414
+ function buildTrace(input) {
520415
+ const i2 = input ?? {};
520416
+ const used = nonNegative(i2.contextTokensUsed ?? DEFAULT_TRACE.contextTokensUsed);
520417
+ const max = nonNegative(i2.contextTokensMax ?? DEFAULT_TRACE.contextTokensMax);
520418
+ const derivedLoad = max > 0 ? used / max : 0;
520419
+ const load2 = i2.cognitiveLoad != null ? clamp012(i2.cognitiveLoad) : clamp012(derivedLoad);
520420
+ return {
520421
+ durationMs: nonNegative(i2.durationMs ?? DEFAULT_TRACE.durationMs),
520422
+ hesitationCount: Math.max(0, Math.floor(i2.hesitationCount ?? 0)),
520423
+ retryCount: Math.max(0, Math.floor(i2.retryCount ?? 0)),
520424
+ intensity: clamp012(i2.intensity ?? DEFAULT_TRACE.intensity),
520425
+ visualGist: typeof i2.visualGist === "string" ? i2.visualGist : void 0,
520426
+ auditoryGist: typeof i2.auditoryGist === "string" ? i2.auditoryGist : void 0,
520427
+ screenState: typeof i2.screenState === "string" ? i2.screenState : void 0,
520428
+ confidence: clamp012(i2.confidence ?? DEFAULT_TRACE.confidence),
520429
+ cognitiveLoad: load2,
520430
+ contextTokensUsed: used,
520431
+ contextTokensMax: max,
520432
+ affect: sanitizeEmotionalState(i2.affect ?? NEUTRAL_AFFECT),
520433
+ timeOfDay: clamp2(Math.floor(i2.timeOfDay ?? DEFAULT_TRACE.timeOfDay), 0, 23),
520434
+ sessionDurationMin: nonNegative(i2.sessionDurationMin ?? 0),
520435
+ consecutiveActions: Math.max(0, Math.floor(i2.consecutiveActions ?? 0))
520436
+ };
520437
+ }
520438
+ function attachTrace(metadata, trace) {
520439
+ return { ...metadata ?? {}, [EMBODIED_KEY]: trace };
520440
+ }
520441
+ function extractTrace(metadata) {
520442
+ if (!metadata || typeof metadata !== "object")
520443
+ return null;
520444
+ const raw = metadata[EMBODIED_KEY];
520445
+ if (!raw || typeof raw !== "object")
520446
+ return null;
520447
+ return buildTrace(raw);
520448
+ }
520449
+ function engagementScore(trace) {
520450
+ const alertness = 1 - trace.cognitiveLoad;
520451
+ return clamp012((trace.intensity + alertness + trace.confidence) / 3);
520452
+ }
520453
+ function wasHesitant(trace, threshold = 0.4) {
520454
+ return trace.hesitationCount >= 2 || trace.retryCount >= 1 || trace.confidence < threshold;
520455
+ }
520456
+ var NEUTRAL_AFFECT, DEFAULT_TRACE, EMBODIED_KEY;
520457
+ var init_embodiedTrace = __esm({
520458
+ "packages/memory/dist/embodiedTrace.js"() {
520459
+ "use strict";
520460
+ init_homeostaticRegulation();
520461
+ NEUTRAL_AFFECT = { valence: 0, arousal: 0 };
520462
+ DEFAULT_TRACE = {
520463
+ durationMs: 0,
520464
+ hesitationCount: 0,
520465
+ retryCount: 0,
520466
+ intensity: 0,
520467
+ confidence: 0.5,
520468
+ cognitiveLoad: 0,
520469
+ contextTokensUsed: 0,
520470
+ contextTokensMax: 0,
520471
+ affect: NEUTRAL_AFFECT,
520472
+ timeOfDay: 0,
520473
+ sessionDurationMin: 0,
520474
+ consecutiveActions: 0
520475
+ };
520476
+ EMBODIED_KEY = "embodiedTrace";
520477
+ }
520478
+ });
520479
+
520480
+ // packages/memory/dist/sleepConsolidation.js
520481
+ function slowWaveReplay(db, options2 = {}) {
520482
+ const topK = options2.topK ?? 20;
520483
+ const lookback = options2.lookbackMs ?? 2 * 60 * 60 * 1e3;
520484
+ const minImp = options2.minImportance ?? 6;
520485
+ const delta = options2.strengthDelta ?? 1;
520486
+ const start2 = Date.now();
520487
+ const cutoff = start2 - lookback;
520488
+ let rows = [];
520489
+ try {
520490
+ rows = db.prepare(`SELECT id FROM episodes
520491
+ WHERE importance >= ?
520492
+ AND timestamp >= ?
520493
+ ORDER BY importance DESC, timestamp DESC
520494
+ LIMIT ?`).all(minImp, cutoff, topK);
520495
+ } catch {
520496
+ rows = [];
520497
+ }
520498
+ if (rows.length === 0) {
520499
+ return {
520500
+ cycle: emptyCycle("slow_wave", start2)
520501
+ };
520502
+ }
520503
+ const ids = rows.map((r2) => r2.id);
520504
+ const placeholders = ids.map(() => "?").join(",");
520505
+ const safeDelta = Number.isFinite(delta) ? delta : 1;
520506
+ try {
520507
+ db.prepare(`UPDATE episodes
520508
+ SET strength = COALESCE(strength, 1) + ?,
520509
+ last_retrieved = ?
520510
+ WHERE id IN (${placeholders})`).run(safeDelta, start2, ...ids);
520511
+ } catch {
520512
+ }
520513
+ return {
520514
+ cycle: {
520515
+ phase: "slow_wave",
520516
+ startTime: start2,
520517
+ endTime: Date.now(),
520518
+ replayedEpisodes: ids,
520519
+ downscaledEpisodes: [],
520520
+ prunedEpisodes: [],
520521
+ novelAssociations: [],
520522
+ energyCost: ids.length
520523
+ }
520524
+ };
520525
+ }
520526
+ function remDream(db, options2 = {}) {
520527
+ const seeds = Math.max(1, options2.seeds ?? 8);
520528
+ const start2 = Date.now();
520529
+ const novel = [];
520530
+ let seedRows = [];
520531
+ try {
520532
+ seedRows = db.prepare(`SELECT id FROM episodes
520533
+ WHERE importance >= 4
520534
+ ORDER BY importance * COALESCE(strength, 1) DESC, RANDOM()
520535
+ LIMIT ?`).all(seeds);
520536
+ } catch {
520537
+ seedRows = [];
520538
+ }
520539
+ if (seedRows.length === 0) {
520540
+ return { cycle: emptyCycle("rem", start2) };
520541
+ }
520542
+ const walkDepth = Math.max(1, options2.walkDepth ?? 3);
520543
+ for (const seed of seedRows) {
520544
+ let temporalNeighbors = [];
520545
+ try {
520546
+ temporalNeighbors = db.prepare(`SELECT id FROM episodes
520547
+ WHERE session_id IS (SELECT session_id FROM episodes WHERE id = ?)
520548
+ AND id != ?
520549
+ ORDER BY timestamp DESC
520550
+ LIMIT 100`).all(seed.id, seed.id);
520551
+ } catch {
520552
+ continue;
520553
+ }
520554
+ if (temporalNeighbors.length > walkDepth) {
520555
+ const target = temporalNeighbors[walkDepth];
520556
+ if (target)
520557
+ novel.push({ from: seed.id, to: target.id, reason: "rem-temporal-distance" });
520558
+ }
520559
+ }
520560
+ return {
520561
+ cycle: {
520562
+ phase: "rem",
520563
+ startTime: start2,
520564
+ endTime: Date.now(),
520565
+ replayedEpisodes: seedRows.map((r2) => r2.id),
520566
+ downscaledEpisodes: [],
520567
+ prunedEpisodes: [],
520568
+ novelAssociations: novel,
520569
+ energyCost: seedRows.length + novel.length
520570
+ }
520571
+ };
520572
+ }
520573
+ function lightSleep(db, options2 = {}) {
520574
+ const start2 = Date.now();
520575
+ const downThreshold = options2.downscaleThreshold ?? 0.3;
520576
+ const downDelta = options2.downscaleDelta ?? 0.1;
520577
+ const pruneImportance = options2.pruneImportanceCeiling ?? 2;
520578
+ const maxPrune = Math.max(0, options2.maxPrune ?? 200);
520579
+ const prunableClasses = options2.prunableClasses ?? ["session", "daily"];
520580
+ const stalePerClass = {};
520581
+ for (const c9 of prunableClasses) {
520582
+ stalePerClass[c9] = options2.pruneStaleAfterMs ?? DECAY_TAU[c9] * 2;
520583
+ }
520584
+ let downscaled = [];
520585
+ try {
520586
+ downscaled = db.prepare(`SELECT id FROM episodes
520587
+ WHERE COALESCE(strength, 1) < ?
520588
+ ORDER BY strength ASC
520589
+ LIMIT 500`).all(downThreshold);
520590
+ if (downscaled.length > 0) {
520591
+ const placeholders = downscaled.map(() => "?").join(",");
520592
+ const safeDelta = Number.isFinite(downDelta) ? downDelta : 0.1;
520593
+ db.prepare(`UPDATE episodes
520594
+ SET strength = MAX(0.05, COALESCE(strength, 1) - ?)
520595
+ WHERE id IN (${placeholders})`).run(safeDelta, ...downscaled.map((r2) => r2.id));
520596
+ }
520597
+ } catch {
520598
+ }
520599
+ const pruned = [];
520600
+ for (const klass of prunableClasses) {
520601
+ const stale = stalePerClass[klass];
520602
+ const cutoff = start2 - stale;
520603
+ let rows = [];
520604
+ try {
520605
+ rows = db.prepare(`SELECT id FROM episodes
520606
+ WHERE decay_class = ?
520607
+ AND importance < ?
520608
+ AND timestamp < ?
520609
+ ORDER BY timestamp ASC
520610
+ LIMIT ?`).all(klass, pruneImportance, cutoff, maxPrune - pruned.length);
520611
+ } catch {
520612
+ rows = [];
520613
+ }
520614
+ if (rows.length === 0)
520615
+ continue;
520616
+ const ids = rows.map((r2) => r2.id);
520617
+ try {
520618
+ const placeholders = ids.map(() => "?").join(",");
520619
+ db.prepare(`DELETE FROM episodes WHERE id IN (${placeholders})`).run(...ids);
520620
+ pruned.push(...ids);
520621
+ } catch {
520622
+ }
520623
+ if (pruned.length >= maxPrune)
520624
+ break;
520625
+ }
520626
+ return {
520627
+ cycle: {
520628
+ phase: "light",
520629
+ startTime: start2,
520630
+ endTime: Date.now(),
520631
+ replayedEpisodes: [],
520632
+ downscaledEpisodes: downscaled.map((r2) => r2.id),
520633
+ prunedEpisodes: pruned,
520634
+ novelAssociations: [],
520635
+ energyCost: downscaled.length + pruned.length
520636
+ }
520637
+ };
520638
+ }
520639
+ function runConsolidationCycle(db, opts = {}) {
520640
+ const slow = slowWaveReplay(db, opts.slowWave).cycle;
520641
+ const rem = remDream(db, opts.rem).cycle;
520642
+ const light = lightSleep(db, opts.light).cycle;
520643
+ return {
520644
+ slowWave: slow,
520645
+ rem,
520646
+ light,
520647
+ totalEnergy: slow.energyCost + rem.energyCost + light.energyCost
520648
+ };
520649
+ }
520650
+ function emptyCycle(phase, start2) {
520651
+ return {
520652
+ phase,
520653
+ startTime: start2,
520654
+ endTime: Date.now(),
520655
+ replayedEpisodes: [],
520656
+ downscaledEpisodes: [],
520657
+ prunedEpisodes: [],
520658
+ novelAssociations: [],
520659
+ energyCost: 0
520660
+ };
520661
+ }
520662
+ function episodeCount(db) {
520663
+ try {
520664
+ const row = db.prepare(`SELECT COUNT(*) AS c FROM episodes`).get();
520665
+ return row?.c ?? 0;
520666
+ } catch {
520667
+ return 0;
520668
+ }
520669
+ }
520670
+ var init_sleepConsolidation = __esm({
520671
+ "packages/memory/dist/sleepConsolidation.js"() {
520672
+ "use strict";
520673
+ init_episodeStore();
520674
+ }
520675
+ });
520676
+
520677
+ // packages/memory/dist/socialMemory.js
520678
+ import { randomUUID as randomUUID11 } from "node:crypto";
520679
+ function clamp3(x, lo, hi) {
520680
+ if (!Number.isFinite(x))
520681
+ return (lo + hi) / 2;
520682
+ if (x < lo)
520683
+ return lo;
520684
+ if (x > hi)
520685
+ return hi;
520686
+ return x;
520687
+ }
520688
+ function clamp013(x) {
520689
+ return clamp3(x, 0, 1);
520690
+ }
520691
+ function clampSigned(x) {
520692
+ return clamp3(x, -1, 1);
520693
+ }
520694
+ function sanitizeBig5(p2) {
520695
+ return {
520696
+ openness: clamp013(p2?.openness ?? NEUTRAL_BIG5.openness),
520697
+ conscientiousness: clamp013(p2?.conscientiousness ?? NEUTRAL_BIG5.conscientiousness),
520698
+ extraversion: clamp013(p2?.extraversion ?? NEUTRAL_BIG5.extraversion),
520699
+ agreeableness: clamp013(p2?.agreeableness ?? NEUTRAL_BIG5.agreeableness),
520700
+ neuroticism: clamp013(p2?.neuroticism ?? NEUTRAL_BIG5.neuroticism)
520701
+ };
520702
+ }
520703
+ function pairKey(a2, b) {
520704
+ return a2 <= b ? { lo: a2, hi: b } : { lo: b, hi: a2 };
520705
+ }
520706
+ function rowToAgent(row) {
520707
+ return {
520708
+ id: row.id,
520709
+ name: row.name,
520710
+ type: row.type,
520711
+ firstMet: row.first_met,
520712
+ lastInteraction: row.last_interaction,
520713
+ interactionCount: row.interaction_count,
520714
+ personality: sanitizeBig5(JSON.parse(row.personality)),
520715
+ trust: JSON.parse(row.trust),
520716
+ metadata: row.metadata ? JSON.parse(row.metadata) : null
520717
+ };
520718
+ }
520719
+ function rowToRelationship(row) {
520720
+ return {
520721
+ agentA: row.agent_a,
520722
+ agentB: row.agent_b,
520723
+ strength: row.strength,
520724
+ valence: row.valence,
520725
+ reciprocity: row.reciprocity,
520726
+ lastUpdated: row.last_updated,
520727
+ history: JSON.parse(row.history ?? "[]")
520728
+ };
520729
+ }
520730
+ function rowToLesson(row) {
520731
+ return {
520732
+ id: row.id,
520733
+ sourceAgent: row.source_agent,
520734
+ lesson: row.lesson,
520735
+ confidence: row.confidence,
520736
+ adopted: row.adopted === 1,
520737
+ timestamp: row.timestamp
520738
+ };
520739
+ }
520740
+ var NEUTRAL_BIG5, SocialMemoryStore;
520741
+ var init_socialMemory = __esm({
520742
+ "packages/memory/dist/socialMemory.js"() {
520743
+ "use strict";
520744
+ NEUTRAL_BIG5 = {
520745
+ openness: 0.5,
520746
+ conscientiousness: 0.5,
520747
+ extraversion: 0.5,
520748
+ agreeableness: 0.5,
520749
+ neuroticism: 0.5
520750
+ };
520751
+ SocialMemoryStore = class {
520752
+ db;
520753
+ constructor(db) {
520754
+ this.db = db;
520755
+ this.initSchema();
520756
+ }
520757
+ initSchema() {
520758
+ this.db.exec(`
520759
+ CREATE TABLE IF NOT EXISTS social_agents (
520760
+ id TEXT PRIMARY KEY,
520761
+ name TEXT NOT NULL,
520762
+ type TEXT NOT NULL,
520763
+ first_met INTEGER NOT NULL,
520764
+ last_interaction INTEGER NOT NULL,
520765
+ interaction_count INTEGER NOT NULL DEFAULT 0,
520766
+ personality TEXT NOT NULL,
520767
+ trust TEXT NOT NULL,
520768
+ metadata TEXT
520769
+ );
520770
+ CREATE TABLE IF NOT EXISTS social_relationships (
520771
+ agent_a TEXT NOT NULL,
520772
+ agent_b TEXT NOT NULL,
520773
+ strength REAL NOT NULL DEFAULT 0,
520774
+ valence REAL NOT NULL DEFAULT 0,
520775
+ reciprocity REAL NOT NULL DEFAULT 0.5,
520776
+ last_updated INTEGER NOT NULL,
520777
+ history TEXT NOT NULL DEFAULT '[]',
520778
+ PRIMARY KEY (agent_a, agent_b)
520779
+ );
520780
+ CREATE TABLE IF NOT EXISTS social_lessons (
520781
+ id TEXT PRIMARY KEY,
520782
+ source_agent TEXT NOT NULL,
520783
+ lesson TEXT NOT NULL,
520784
+ confidence REAL NOT NULL,
520785
+ adopted INTEGER NOT NULL DEFAULT 0,
520786
+ timestamp INTEGER NOT NULL
520787
+ );
520788
+ CREATE INDEX IF NOT EXISTS idx_lessons_source ON social_lessons(source_agent);
520789
+ CREATE INDEX IF NOT EXISTS idx_rels_agent_a ON social_relationships(agent_a);
520790
+ CREATE INDEX IF NOT EXISTS idx_rels_agent_b ON social_relationships(agent_b);
520791
+ `);
520792
+ }
520793
+ // ── Agent profiles ────────────────────────────────────────────────────────
520794
+ upsertAgent(input) {
520795
+ const now = Date.now();
520796
+ const id = input.id ?? randomUUID11();
520797
+ const existing = this.getAgent(id);
520798
+ const personality = sanitizeBig5({ ...existing?.personality ?? {}, ...input.personality ?? {} });
520799
+ const trustOverall = clamp013(input.trust?.overall ?? existing?.trust.overall ?? 0.5);
520800
+ const trustByDomain = {
520801
+ ...existing?.trust.byDomain ?? {},
520802
+ ...input.trust?.byDomain ?? {}
520803
+ };
520804
+ for (const k of Object.keys(trustByDomain))
520805
+ trustByDomain[k] = clamp013(trustByDomain[k]);
520806
+ const metadata = input.metadata ?? existing?.metadata ?? null;
520807
+ if (existing) {
520808
+ this.db.prepare(`UPDATE social_agents
520809
+ SET name = ?, type = ?, last_interaction = ?,
520810
+ personality = ?, trust = ?, metadata = ?
520811
+ WHERE id = ?`).run(input.name, input.type ?? existing.type, now, JSON.stringify(personality), JSON.stringify({ overall: trustOverall, byDomain: trustByDomain }), metadata ? JSON.stringify(metadata) : null, id);
520812
+ } else {
520813
+ this.db.prepare(`INSERT INTO social_agents
520814
+ (id, name, type, first_met, last_interaction, interaction_count, personality, trust, metadata)
520815
+ VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?)`).run(id, input.name, input.type ?? "agent", now, now, JSON.stringify(personality), JSON.stringify({ overall: trustOverall, byDomain: trustByDomain }), metadata ? JSON.stringify(metadata) : null);
520816
+ }
520817
+ return this.getAgent(id);
520818
+ }
520819
+ getAgent(id) {
520820
+ const row = this.db.prepare(`SELECT * FROM social_agents WHERE id = ?`).get(id);
520821
+ if (!row)
520822
+ return null;
520823
+ return rowToAgent(row);
520824
+ }
520825
+ listAgents() {
520826
+ const rows = this.db.prepare(`SELECT * FROM social_agents ORDER BY last_interaction DESC`).all();
520827
+ return rows.map(rowToAgent);
520828
+ }
520829
+ updateAgent(id, update2) {
520830
+ if (!this.getAgent(id))
520831
+ return null;
520832
+ return this.upsertAgent({
520833
+ id,
520834
+ name: update2.name ?? this.getAgent(id).name,
520835
+ type: this.getAgent(id).type,
520836
+ personality: update2.personality,
520837
+ trust: update2.trust,
520838
+ metadata: update2.metadata
520839
+ });
520840
+ }
520841
+ recordInteraction(agentId, interaction) {
520842
+ const agent = this.getAgent(agentId);
520843
+ if (!agent)
520844
+ return null;
520845
+ const weight = clamp013(interaction.weight ?? 0.1);
520846
+ const targetOverall = interaction.positive ? 1 : 0;
520847
+ const newOverall = clamp013(agent.trust.overall + (targetOverall - agent.trust.overall) * weight);
520848
+ const newByDomain = { ...agent.trust.byDomain };
520849
+ if (interaction.domain) {
520850
+ const cur = newByDomain[interaction.domain] ?? 0.5;
520851
+ newByDomain[interaction.domain] = clamp013(cur + (targetOverall - cur) * weight);
520852
+ }
520853
+ const now = Date.now();
520854
+ this.db.prepare(`UPDATE social_agents
520855
+ SET interaction_count = interaction_count + 1,
520856
+ last_interaction = ?,
520857
+ trust = ?
520858
+ WHERE id = ?`).run(now, JSON.stringify({ overall: newOverall, byDomain: newByDomain }), agentId);
520859
+ return this.getAgent(agentId);
520860
+ }
520861
+ // ── Relationships ─────────────────────────────────────────────────────────
520862
+ recordRelationshipEvent(agentA, agentB, event) {
520863
+ if (agentA === agentB)
520864
+ throw new Error("agentA and agentB must differ");
520865
+ const { lo, hi } = pairKey(agentA, agentB);
520866
+ const now = Date.now();
520867
+ const existing = this.db.prepare(`SELECT * FROM social_relationships WHERE agent_a = ? AND agent_b = ?`).get(lo, hi);
520868
+ const dStrength = clampSigned(event.impactOnStrength);
520869
+ const dValence = clampSigned(event.impactOnValence);
520870
+ const newEvent = {
520871
+ timestamp: now,
520872
+ event: event.event,
520873
+ impactOnStrength: dStrength,
520874
+ impactOnValence: dValence
520875
+ };
520876
+ if (existing) {
520877
+ const history = JSON.parse(existing.history ?? "[]");
520878
+ history.push(newEvent);
520879
+ if (history.length > 200)
520880
+ history.splice(0, history.length - 200);
520881
+ const strength = clamp013(existing.strength + Math.abs(dStrength));
520882
+ const valence = clampSigned(existing.valence + dValence);
520883
+ const reciprocity = clamp013(existing.reciprocity * 0.95 + 0.05 * 0.5);
520884
+ this.db.prepare(`UPDATE social_relationships
520885
+ SET strength = ?, valence = ?, reciprocity = ?, last_updated = ?, history = ?
520886
+ WHERE agent_a = ? AND agent_b = ?`).run(strength, valence, reciprocity, now, JSON.stringify(history), lo, hi);
520887
+ } else {
520888
+ const strength = clamp013(Math.abs(dStrength));
520889
+ const valence = clampSigned(dValence);
520890
+ this.db.prepare(`INSERT INTO social_relationships
520891
+ (agent_a, agent_b, strength, valence, reciprocity, last_updated, history)
520892
+ VALUES (?, ?, ?, ?, 0.5, ?, ?)`).run(lo, hi, strength, valence, now, JSON.stringify([newEvent]));
520893
+ }
520894
+ return this.getRelationship(agentA, agentB);
520895
+ }
520896
+ getRelationship(agentA, agentB) {
520897
+ const { lo, hi } = pairKey(agentA, agentB);
520898
+ const row = this.db.prepare(`SELECT * FROM social_relationships WHERE agent_a = ? AND agent_b = ?`).get(lo, hi);
520899
+ if (!row)
520900
+ return null;
520901
+ return rowToRelationship(row);
520902
+ }
520903
+ listRelationshipsFor(agent) {
520904
+ const rows = this.db.prepare(`SELECT * FROM social_relationships WHERE agent_a = ? OR agent_b = ?`).all(agent, agent);
520905
+ return rows.map(rowToRelationship);
520906
+ }
520907
+ // ── Social lessons ────────────────────────────────────────────────────────
520908
+ recordLesson(input) {
520909
+ const id = randomUUID11();
520910
+ const now = Date.now();
520911
+ const conf = clamp013(input.confidence ?? 0.5);
520912
+ const adopted = input.adopted ? 1 : 0;
520913
+ this.db.prepare(`INSERT INTO social_lessons (id, source_agent, lesson, confidence, adopted, timestamp)
520914
+ VALUES (?, ?, ?, ?, ?, ?)`).run(id, input.sourceAgent, input.lesson, conf, adopted, now);
520915
+ return { id, sourceAgent: input.sourceAgent, lesson: input.lesson, confidence: conf, adopted: !!adopted, timestamp: now };
520916
+ }
520917
+ adoptLesson(id) {
520918
+ const r2 = this.db.prepare(`UPDATE social_lessons SET adopted = 1 WHERE id = ?`).run(id);
520919
+ return (r2.changes ?? 0) > 0;
520920
+ }
520921
+ listLessons(sourceAgent) {
520922
+ const rows = sourceAgent ? this.db.prepare(`SELECT * FROM social_lessons WHERE source_agent = ? ORDER BY timestamp DESC`).all(sourceAgent) : this.db.prepare(`SELECT * FROM social_lessons ORDER BY timestamp DESC`).all();
520923
+ return rows.map(rowToLesson);
520924
+ }
520925
+ };
520926
+ }
520927
+ });
520928
+
520929
+ // packages/memory/dist/developmentalStage.js
520930
+ function meetsGate(m2, g) {
520931
+ return m2.sessionCount >= g.minSessions && m2.recentPredictionError <= g.maxRecentError && m2.crossDomainLinks >= g.minCrossDomain && m2.totalEpisodes >= g.minTotalEpisodes;
520932
+ }
520933
+ function detectStage(metrics2) {
520934
+ if (meetsGate(metrics2, STAGE_GATES.wisdom))
520935
+ return "wisdom";
520936
+ if (meetsGate(metrics2, STAGE_GATES.integration))
520937
+ return "integration";
520938
+ if (meetsGate(metrics2, STAGE_GATES.specialization))
520939
+ return "specialization";
520940
+ return "exploration";
520941
+ }
520942
+ function thresholdsForStage(stage) {
520943
+ return { ...STAGE_THRESHOLDS[stage] };
520944
+ }
520945
+ function characteristicsForStage(stage) {
520946
+ return { ...STAGE_CHARACTERISTICS[stage] };
520947
+ }
520948
+ function report(metrics2) {
520949
+ const stage = detectStage(metrics2);
520950
+ const thresholds = thresholdsForStage(stage);
520951
+ const characteristics = characteristicsForStage(stage);
520952
+ const nextStage = computeNextStage(stage, metrics2);
520953
+ return { stage, metrics: metrics2, thresholds, characteristics, nextStage };
520954
+ }
520955
+ function computeNextStage(current, m2) {
520956
+ const next = current === "exploration" ? "specialization" : current === "specialization" ? "integration" : current === "integration" ? "wisdom" : null;
520957
+ if (!next)
520958
+ return null;
520959
+ const gate = STAGE_GATES[next];
520960
+ const gates = [];
520961
+ if (m2.sessionCount < gate.minSessions)
520962
+ gates.push(`sessionCount ≥ ${gate.minSessions} (now ${m2.sessionCount})`);
520963
+ if (m2.recentPredictionError > gate.maxRecentError)
520964
+ gates.push(`recentPredictionError ≤ ${gate.maxRecentError} (now ${m2.recentPredictionError.toFixed(2)})`);
520965
+ if (m2.crossDomainLinks < gate.minCrossDomain)
520966
+ gates.push(`crossDomainLinks ≥ ${gate.minCrossDomain} (now ${m2.crossDomainLinks})`);
520967
+ if (m2.totalEpisodes < gate.minTotalEpisodes)
520968
+ gates.push(`totalEpisodes ≥ ${gate.minTotalEpisodes} (now ${m2.totalEpisodes})`);
520969
+ return { name: next, gates };
520970
+ }
520971
+ function emptyMetrics() {
520972
+ return {
520973
+ sessionCount: 0,
520974
+ domainCount: 0,
520975
+ recentPredictionError: 1,
520976
+ crossDomainLinks: 0,
520977
+ totalEpisodes: 0,
520978
+ creativeAssociationCount: 0
520979
+ };
520980
+ }
520981
+ var STAGE_THRESHOLDS, STAGE_CHARACTERISTICS, STAGE_GATES;
520982
+ var init_developmentalStage = __esm({
520983
+ "packages/memory/dist/developmentalStage.js"() {
520984
+ "use strict";
520985
+ STAGE_THRESHOLDS = {
520986
+ exploration: {
520987
+ importanceFloor: 2,
520988
+ linkThreshold: 0.5,
520989
+ // be generous with links
520990
+ evolutionThreshold: 0.4,
520991
+ // gist updates often
520992
+ pruningAggressiveness: 0.1
520993
+ },
520994
+ specialization: {
520995
+ importanceFloor: 4,
520996
+ linkThreshold: 0.6,
520997
+ evolutionThreshold: 0.55,
520998
+ pruningAggressiveness: 0.3
520999
+ },
521000
+ integration: {
521001
+ importanceFloor: 5,
521002
+ linkThreshold: 0.65,
521003
+ evolutionThreshold: 0.65,
521004
+ pruningAggressiveness: 0.5
521005
+ },
521006
+ wisdom: {
521007
+ importanceFloor: 6,
521008
+ linkThreshold: 0.7,
521009
+ evolutionThreshold: 0.7,
521010
+ pruningAggressiveness: 0.7
521011
+ }
521012
+ };
521013
+ STAGE_CHARACTERISTICS = {
521014
+ exploration: {
521015
+ memoryBreadth: 0.9,
521016
+ memoryDepth: 0.3,
521017
+ retrievalSpecificity: 0.3,
521018
+ abstractionLevel: 0.2,
521019
+ creativityIndex: 0.7,
521020
+ predictionAccuracy: 0.4
521021
+ },
521022
+ specialization: {
521023
+ memoryBreadth: 0.6,
521024
+ memoryDepth: 0.6,
521025
+ retrievalSpecificity: 0.6,
521026
+ abstractionLevel: 0.4,
521027
+ creativityIndex: 0.5,
521028
+ predictionAccuracy: 0.6
521029
+ },
521030
+ integration: {
521031
+ memoryBreadth: 0.7,
521032
+ memoryDepth: 0.7,
521033
+ retrievalSpecificity: 0.7,
521034
+ abstractionLevel: 0.7,
521035
+ creativityIndex: 0.7,
521036
+ predictionAccuracy: 0.75
521037
+ },
521038
+ wisdom: {
521039
+ memoryBreadth: 0.8,
521040
+ memoryDepth: 0.8,
521041
+ retrievalSpecificity: 0.8,
521042
+ abstractionLevel: 0.9,
521043
+ creativityIndex: 0.85,
521044
+ predictionAccuracy: 0.85
521045
+ }
521046
+ };
521047
+ STAGE_GATES = {
521048
+ specialization: {
521049
+ minSessions: 100,
521050
+ maxRecentError: 0.5,
521051
+ minCrossDomain: 0,
521052
+ minTotalEpisodes: 100
521053
+ },
521054
+ integration: {
521055
+ minSessions: 500,
521056
+ maxRecentError: 0.4,
521057
+ minCrossDomain: 20,
521058
+ minTotalEpisodes: 1e3
521059
+ },
521060
+ wisdom: {
521061
+ minSessions: 2e3,
521062
+ maxRecentError: 0.25,
521063
+ minCrossDomain: 100,
521064
+ minTotalEpisodes: 5e3
521065
+ }
521066
+ };
521067
+ }
521068
+ });
521069
+
519877
521070
  // packages/memory/dist/index.js
519878
521071
  var dist_exports2 = {};
519879
521072
  __export(dist_exports2, {
@@ -519887,45 +521080,78 @@ __export(dist_exports2, {
519887
521080
  CRLParser: () => CRLParser,
519888
521081
  CRLTemplateResolver: () => CRLTemplateResolver,
519889
521082
  CRL_SYMBOLS: () => CRL_SYMBOLS,
521083
+ ConfidenceTracker: () => ConfidenceTracker,
519890
521084
  DECAY_TAU: () => DECAY_TAU,
519891
521085
  DEFAULT_CRL_CONFIG: () => DEFAULT_CRL_CONFIG,
521086
+ DEFAULT_ENCODING: () => DEFAULT_ENCODING,
521087
+ DEFAULT_RETRIEVAL: () => DEFAULT_RETRIEVAL,
521088
+ DEFAULT_TARGET: () => DEFAULT_TARGET,
519892
521089
  EmbeddingAligner: () => EmbeddingAligner,
519893
521090
  EpisodeStore: () => EpisodeStore,
519894
521091
  FailureStore: () => FailureStore,
519895
521092
  FileSummaryStore: () => FileSummaryStore,
519896
521093
  PatchHistoryStore: () => PatchHistoryStore,
521094
+ PredictionStore: () => PredictionStore,
519897
521095
  ProceduralMemoryStore: () => ProceduralMemoryStore,
519898
521096
  RepoProfileStore: () => RepoProfileStore,
519899
521097
  SYMBOL_MEANINGS: () => SYMBOL_MEANINGS,
521098
+ SelfModel: () => SelfModel,
521099
+ SocialMemoryStore: () => SocialMemoryStore,
519900
521100
  TaskMemoryStore: () => TaskMemoryStore,
519901
521101
  TemporalGraph: () => TemporalGraph,
519902
521102
  ToolPatternStore: () => ToolPatternStore,
519903
521103
  ValidationStore: () => ValidationStore,
521104
+ attachTrace: () => attachTrace,
519904
521105
  autoDecayClass: () => autoDecayClass,
519905
521106
  autoImportance: () => autoImportance,
519906
521107
  batchLink: () => batchLink,
521108
+ buildTrace: () => buildTrace,
521109
+ characteristicsForStage: () => characteristicsForStage,
519907
521110
  checkEmbeddingAvailable: () => checkEmbeddingAvailable,
519908
521111
  closeDb: () => closeDb,
519909
521112
  compressAndStore: () => compressAndStore,
519910
521113
  compressToGist: () => compressToGist,
521114
+ congruenceMultiplier: () => congruenceMultiplier,
519911
521115
  cosineSimilarity: () => cosineSimilarity2,
519912
521116
  createCRLMemoryStore: () => createCRLMemoryStore,
521117
+ createHomeostaticState: () => createHomeostaticState,
521118
+ detectStage: () => detectStage,
521119
+ developmentalReport: () => report,
521120
+ deviationFromTarget: () => deviationFromTarget,
521121
+ durationError: () => durationError,
521122
+ emptyDevelopmentalMetrics: () => emptyMetrics,
521123
+ engagementScore: () => engagementScore,
521124
+ episodeCount: () => episodeCount,
519913
521125
  extractQueryEntities: () => extractQueryEntities,
521126
+ extractTrace: () => extractTrace,
519914
521127
  findNeighbors: () => findNeighbors,
519915
521128
  generateEmbedding: () => generateEmbedding,
519916
521129
  generateEmbeddingBatch: () => generateEmbeddingBatch,
519917
521130
  getCRLConfigStore: () => getCRLConfigStore,
521131
+ importanceMultiplier: () => importanceMultiplier,
519918
521132
  initDb: () => initDb,
521133
+ lightSleep: () => lightSleep,
519919
521134
  linkEpisode: () => linkEpisode,
521135
+ modulateImportance: () => modulateImportance,
521136
+ modulateRetrievalScore: () => modulateRetrievalScore,
521137
+ observeEmotionalState: () => observeEmotionalState,
519920
521138
  personalizedPageRank: () => personalizedPageRank,
521139
+ remDream: () => remDream,
519921
521140
  resetCRLConfigStore: () => resetCRLConfigStore,
519922
521141
  retrieveByPPR: () => retrieveByPPR,
521142
+ runConsolidationCycle: () => runConsolidationCycle,
521143
+ sanitizeEmotionalState: () => sanitizeEmotionalState,
521144
+ slowWaveReplay: () => slowWaveReplay,
519923
521145
  splanifoldCosine: () => cosine,
519924
521146
  splanifoldDeserialize: () => deserialize,
519925
521147
  splanifoldEvaluate: () => evaluate2,
519926
521148
  splanifoldFit: () => fit,
519927
521149
  splanifoldRmse: () => rmse,
519928
- splanifoldSerialize: () => serialize
521150
+ splanifoldSerialize: () => serialize,
521151
+ suggestRegulation: () => suggestRegulation,
521152
+ thresholdsForStage: () => thresholdsForStage,
521153
+ tokenSimilarity: () => tokenSimilarity,
521154
+ wasHesitant: () => wasHesitant
519929
521155
  });
519930
521156
  var init_dist7 = __esm({
519931
521157
  "packages/memory/dist/index.js"() {
@@ -519948,6 +521174,13 @@ var init_dist7 = __esm({
519948
521174
  init_splanifold();
519949
521175
  init_embeddingAligner();
519950
521176
  init_crl();
521177
+ init_homeostaticRegulation();
521178
+ init_selfModel();
521179
+ init_predictionStore();
521180
+ init_embodiedTrace();
521181
+ init_sleepConsolidation();
521182
+ init_socialMemory();
521183
+ init_developmentalStage();
519951
521184
  }
519952
521185
  });
519953
521186
 
@@ -533170,28 +534403,28 @@ function loadAgentTaskSidecars() {
533170
534403
  }
533171
534404
  }
533172
534405
  async function restoreAgentTasks(taskMgr) {
533173
- const report = { restored: 0, reAttached: 0, markedFailed: 0 };
534406
+ const report2 = { restored: 0, reAttached: 0, markedFailed: 0 };
533174
534407
  const sidecars = loadAgentTaskSidecars();
533175
534408
  for (const task of sidecars) {
533176
534409
  taskMgr.adopt(task);
533177
- report.restored++;
534410
+ report2.restored++;
533178
534411
  if (task.status === "running") {
533179
534412
  const pid = task.pid;
533180
534413
  if (pid && pid > 0) {
533181
534414
  try {
533182
534415
  process.kill(pid, 0);
533183
- report.reAttached++;
534416
+ report2.reAttached++;
533184
534417
  } catch {
533185
534418
  taskMgr.fail(task.id, "Daemon restart while subprocess was still running");
533186
- report.markedFailed++;
534419
+ report2.markedFailed++;
533187
534420
  }
533188
534421
  } else {
533189
534422
  taskMgr.fail(task.id, "Daemon restart — in-process sub-agent lost");
533190
- report.markedFailed++;
534423
+ report2.markedFailed++;
533191
534424
  }
533192
534425
  }
533193
534426
  }
533194
- return report;
534427
+ return report2;
533195
534428
  }
533196
534429
  function purgeOldSidecars(maxAgeHours = 24) {
533197
534430
  let purged = 0;
@@ -534341,8 +535574,8 @@ var init_listen = __esm({
534341
535574
  /** Load transcribe-cli — bundled as a dependency of open-agents-ai. */
534342
535575
  async loadTranscribeCli() {
534343
535576
  try {
534344
- const { createRequire: createRequire7 } = await import("node:module");
534345
- const req2 = createRequire7(import.meta.url);
535577
+ const { createRequire: createRequire8 } = await import("node:module");
535578
+ const req2 = createRequire8(import.meta.url);
534346
535579
  return req2("transcribe-cli");
534347
535580
  } catch {
534348
535581
  }
@@ -534354,8 +535587,8 @@ var init_listen = __esm({
534354
535587
  }).trim();
534355
535588
  const tcPath = join85(globalRoot, "transcribe-cli");
534356
535589
  if (existsSync69(join85(tcPath, "dist", "index.js"))) {
534357
- const { createRequire: createRequire7 } = await import("node:module");
534358
- const req2 = createRequire7(import.meta.url);
535590
+ const { createRequire: createRequire8 } = await import("node:module");
535591
+ const req2 = createRequire8(import.meta.url);
534359
535592
  return req2(join85(tcPath, "dist", "index.js"));
534360
535593
  }
534361
535594
  } catch {
@@ -534367,8 +535600,8 @@ var init_listen = __esm({
534367
535600
  for (const ver of readdirSync38(nvmBase)) {
534368
535601
  const tcPath = join85(nvmBase, ver, "lib", "node_modules", "transcribe-cli");
534369
535602
  if (existsSync69(join85(tcPath, "dist", "index.js"))) {
534370
- const { createRequire: createRequire7 } = await import("node:module");
534371
- const req2 = createRequire7(import.meta.url);
535603
+ const { createRequire: createRequire8 } = await import("node:module");
535604
+ const req2 = createRequire8(import.meta.url);
534372
535605
  return req2(join85(tcPath, "dist", "index.js"));
534373
535606
  }
534374
535607
  }
@@ -553676,7 +554909,7 @@ import { existsSync as existsSync80, mkdirSync as mkdirSync44, writeFileSync as
553676
554909
  import { join as join96, dirname as dirname30 } from "node:path";
553677
554910
  import { homedir as homedir30, tmpdir as tmpdir20, platform as platform4 } from "node:os";
553678
554911
  import { execSync as execSync50, spawn as nodeSpawn } from "node:child_process";
553679
- import { createRequire as createRequire3 } from "node:module";
554912
+ import { createRequire as createRequire4 } from "node:module";
553680
554913
  function sanitizeForTTS(text) {
553681
554914
  return text.replace(/^#{1,6}\s+/gm, "").replace(/\*{1,3}([^*]+)\*{1,3}/g, "$1").replace(/_{1,3}([^_]+)_{1,3}/g, "$1").replace(/~~([^~]+)~~/g, "$1").replace(/`([^`]+)`/g, "$1").replace(/```[\s\S]*?```/g, "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1").replace(/^[\s]*[-*+]\s+/gm, "").replace(/^[\s]*\d+\.\s+/gm, "").replace(/^>\s+/gm, "").replace(/^[-*_]{3,}$/gm, "").replace(/\[[ xX]\]\s*/g, "").replace(/[\u{1F600}-\u{1F64F}]/gu, "").replace(/[\u{1F300}-\u{1F5FF}]/gu, "").replace(/[\u{1F680}-\u{1F6FF}]/gu, "").replace(/[\u{1F1E0}-\u{1F1FF}]/gu, "").replace(/[\u{2600}-\u{26FF}]/gu, "").replace(/[\u{2700}-\u{27BF}]/gu, "").replace(/[\u{FE00}-\u{FE0F}]/gu, "").replace(/[\u{1F900}-\u{1F9FF}]/gu, "").replace(/[\u{1FA00}-\u{1FA6F}]/gu, "").replace(/[\u{1FA70}-\u{1FAFF}]/gu, "").replace(/[\u{200D}]/gu, "").replace(/[\u{20E3}]/gu, "").replace(/[✓✔✗✘✕✖⚠️⏸⏹⏵●○◆◇■□▪▫►▼▲◀⬆⬇⬅➡↑↓←→⇐⇒⇑⇓]/g, "").replace(/[─━│┃┌┐└┘├┤┬┴┼╔╗╚╝╠╣╦╩╬⎿⎾▕▏⏐░▒▓█⠀-⣿]/g, "").replace(/\s{2,}/g, " ").trim();
553682
554915
  }
@@ -556324,7 +557557,7 @@ if __name__ == '__main__':
556324
557557
  dependencies: expectedDeps
556325
557558
  }, null, 2));
556326
557559
  }
556327
- const voiceRequire = createRequire3(join96(voiceDir(), "index.js"));
557560
+ const voiceRequire = createRequire4(join96(voiceDir(), "index.js"));
556328
557561
  const probeOnnx = async () => {
556329
557562
  try {
556330
557563
  const output = await this.asyncShell(
@@ -563158,11 +564391,11 @@ async function handleUpdate(subcommand, ctx3) {
563158
564391
  }
563159
564392
  let currentVersion = "0.0.0";
563160
564393
  try {
563161
- const { createRequire: createRequire7 } = await import("node:module");
564394
+ const { createRequire: createRequire8 } = await import("node:module");
563162
564395
  const { fileURLToPath: fileURLToPath20 } = await import("node:url");
563163
564396
  const { dirname: dirname39, join: join125 } = await import("node:path");
563164
564397
  const { existsSync: existsSync107 } = await import("node:fs");
563165
- const req2 = createRequire7(import.meta.url);
564398
+ const req2 = createRequire8(import.meta.url);
563166
564399
  const thisDir = dirname39(fileURLToPath20(import.meta.url));
563167
564400
  const candidates = [
563168
564401
  join125(thisDir, "..", "package.json"),
@@ -564294,10 +565527,10 @@ var init_commands = __esm({
564294
565527
  return "handled";
564295
565528
  }
564296
565529
  try {
564297
- const { createRequire: createRequire7 } = await import("node:module");
565530
+ const { createRequire: createRequire8 } = await import("node:module");
564298
565531
  const { fileURLToPath: fileURLToPath20 } = await import("node:url");
564299
565532
  const { dirname: pathDirname, join: pathJoin } = await import("node:path");
564300
- const localRequire = createRequire7(import.meta.url);
565533
+ const localRequire = createRequire8(import.meta.url);
564301
565534
  const here = pathDirname(fileURLToPath20(import.meta.url));
564302
565535
  let version4 = "?";
564303
565536
  for (const up of ["..", "../..", "../../.."]) {
@@ -572912,7 +574145,7 @@ Call task_complete with a human-readable summary of the autoresearch session.`,
572912
574145
  onEvent
572913
574146
  );
572914
574147
  const reportPath = join105(this.dreamsDir, `cycle-${cycleNum}-autoresearch-report.md`);
572915
- const report = `# Autoresearch Swarm Report — Cycle ${cycleNum}
574148
+ const report2 = `# Autoresearch Swarm Report — Cycle ${cycleNum}
572916
574149
 
572917
574150
  **Date**: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}
572918
574151
  **Rounds completed**: ${workspace.roundsCompleted}
@@ -572934,7 +574167,7 @@ ${summaryResult}
572934
574167
  `;
572935
574168
  try {
572936
574169
  mkdirSync51(this.dreamsDir, { recursive: true });
572937
- writeFileSync46(reportPath, report, "utf-8");
574170
+ writeFileSync46(reportPath, report2, "utf-8");
572938
574171
  } catch {
572939
574172
  }
572940
574173
  renderSwarmComplete(workspace);
@@ -574798,7 +576031,7 @@ function appraiseEvent(event) {
574798
576031
  return null;
574799
576032
  }
574800
576033
  }
574801
- function clamp(value2, min, max) {
576034
+ function clamp4(value2, min, max) {
574802
576035
  return Math.max(min, Math.min(max, value2));
574803
576036
  }
574804
576037
  var BASELINE_VALENCE, BASELINE_AROUSAL, DECAY_HALF_LIFE_MS, LABEL_UPDATE_INTERVAL_MS, EXCITEMENT_THRESHOLD, DISTRESS_THRESHOLD, OUTREACH_COOLDOWN_MS, OUTREACH_MIN_STREAK, LABEL_REGEN_THRESHOLD, EmotionEngine;
@@ -574936,8 +576169,8 @@ var init_emotion_engine = __esm({
574936
576169
  if (this.consecutiveFailures >= 2) {
574937
576170
  momentum = 1 + (this.consecutiveFailures - 1) * 0.25;
574938
576171
  }
574939
- this.state.valence = clamp(this.state.valence + delta.valence * momentum, -1, 1);
574940
- this.state.arousal = clamp(this.state.arousal + delta.arousal * momentum, 0, 1);
576172
+ this.state.valence = clamp4(this.state.valence + delta.valence * momentum, -1, 1);
576173
+ this.state.arousal = clamp4(this.state.arousal + delta.arousal * momentum, 0, 1);
574941
576174
  this.state.updatedAt = Date.now();
574942
576175
  const deterministicLabel = labelFromCoordinates(this.state.valence, this.state.arousal);
574943
576176
  this.state.label = deterministicLabel.label;
@@ -576442,7 +577675,7 @@ __export(chat_session_exports, {
576442
577675
  startInFlightChat: () => startInFlightChat,
576443
577676
  trackSessionTokens: () => trackSessionTokens
576444
577677
  });
576445
- import { randomUUID as randomUUID11 } from "node:crypto";
577678
+ import { randomUUID as randomUUID12 } from "node:crypto";
576446
577679
  import {
576447
577680
  existsSync as existsSync92,
576448
577681
  readFileSync as readFileSync74,
@@ -576493,10 +577726,10 @@ function deleteInFlightFile(id) {
576493
577726
  }
576494
577727
  }
576495
577728
  function loadPersistedSessions() {
576496
- const report = { restored: 0, staleInFlight: 0 };
577729
+ const report2 = { restored: 0, staleInFlight: 0 };
576497
577730
  try {
576498
577731
  const dir = sessionsDir();
576499
- if (!existsSync92(dir)) return report;
577732
+ if (!existsSync92(dir)) return report2;
576500
577733
  const cutoff = Date.now() - SESSION_TTL_MS;
576501
577734
  for (const f2 of readdirSync31(dir)) {
576502
577735
  if (!f2.endsWith(".json") || f2.includes(".tmp.")) continue;
@@ -576515,7 +577748,7 @@ function loadPersistedSessions() {
576515
577748
  writeFileSync48(fp, JSON.stringify(parsed, null, 2), "utf-8");
576516
577749
  } catch {
576517
577750
  }
576518
- report.staleInFlight++;
577751
+ report2.staleInFlight++;
576519
577752
  }
576520
577753
  }
576521
577754
  continue;
@@ -576523,7 +577756,7 @@ function loadPersistedSessions() {
576523
577756
  if (parsed && typeof parsed === "object" && parsed.id) {
576524
577757
  if ((parsed.lastActivity ?? 0) >= cutoff) {
576525
577758
  sessions.set(parsed.id, parsed);
576526
- report.restored++;
577759
+ report2.restored++;
576527
577760
  }
576528
577761
  }
576529
577762
  } catch {
@@ -576531,7 +577764,7 @@ function loadPersistedSessions() {
576531
577764
  }
576532
577765
  } catch {
576533
577766
  }
576534
- return report;
577767
+ return report2;
576535
577768
  }
576536
577769
  function buildSystemPrompt(cwd4) {
576537
577770
  const parts = [];
@@ -576599,7 +577832,7 @@ function getSession(sessionId, model, cwd4) {
576599
577832
  } catch {
576600
577833
  }
576601
577834
  }
576602
- const id = sessionId || randomUUID11();
577835
+ const id = sessionId || randomUUID12();
576603
577836
  const systemPrompt = buildSystemPrompt(cwd4);
576604
577837
  const session = {
576605
577838
  id,
@@ -576866,7 +578099,7 @@ __export(projects_exports, {
576866
578099
  import { readFileSync as readFileSync75, writeFileSync as writeFileSync49, mkdirSync as mkdirSync55, existsSync as existsSync93, statSync as statSync29, renameSync as renameSync6 } from "node:fs";
576867
578100
  import { homedir as homedir34 } from "node:os";
576868
578101
  import { basename as basename20, join as join110, resolve as resolve35 } from "node:path";
576869
- import { randomUUID as randomUUID12 } from "node:crypto";
578102
+ import { randomUUID as randomUUID13 } from "node:crypto";
576870
578103
  function readAll2() {
576871
578104
  try {
576872
578105
  if (!existsSync93(PROJECTS_FILE)) return { projects: [], schemaVersion: 1 };
@@ -576880,7 +578113,7 @@ function readAll2() {
576880
578113
  }
576881
578114
  function writeAll(file) {
576882
578115
  mkdirSync55(OA_DIR3, { recursive: true });
576883
- const tmp = `${PROJECTS_FILE}.${randomUUID12().slice(0, 8)}.tmp`;
578116
+ const tmp = `${PROJECTS_FILE}.${randomUUID13().slice(0, 8)}.tmp`;
576884
578117
  writeFileSync49(tmp, JSON.stringify(file, null, 2), "utf8");
576885
578118
  renameSync6(tmp, PROJECTS_FILE);
576886
578119
  }
@@ -577673,7 +578906,7 @@ import { createHash as createHash12 } from "node:crypto";
577673
578906
  import { existsSync as existsSync94, mkdirSync as mkdirSync56, readFileSync as readFileSync76, renameSync as renameSync7, writeFileSync as writeFileSync50, unlinkSync as unlinkSync22 } from "node:fs";
577674
578907
  import { homedir as homedir35 } from "node:os";
577675
578908
  import { join as join111, resolve as resolve36 } from "node:path";
577676
- import { randomUUID as randomUUID13 } from "node:crypto";
578909
+ import { randomUUID as randomUUID14 } from "node:crypto";
577677
578910
  function projectKey(root) {
577678
578911
  const canonical = resolve36(root);
577679
578912
  return createHash12("sha256").update(canonical).digest("hex").slice(0, 16);
@@ -577721,7 +578954,7 @@ function writeProjectPreferences(root, partial) {
577721
578954
  updatedAt: Date.now()
577722
578955
  };
577723
578956
  const file = prefsPath(root);
577724
- const tmp = `${file}.${randomUUID13().slice(0, 8)}.tmp`;
578957
+ const tmp = `${file}.${randomUUID14().slice(0, 8)}.tmp`;
577725
578958
  writeFileSync50(tmp, JSON.stringify(merged, null, 2), "utf8");
577726
578959
  try {
577727
578960
  renameSync7(tmp, file);
@@ -577768,7 +579001,7 @@ __export(voicechat_exports, {
577768
579001
  VoiceChatSession: () => VoiceChatSession
577769
579002
  });
577770
579003
  import { EventEmitter as EventEmitter11 } from "node:events";
577771
- function clamp01(x) {
579004
+ function clamp014(x) {
577772
579005
  return x < 0 ? 0 : x > 1 ? 1 : x;
577773
579006
  }
577774
579007
  function alnumRatio(s2) {
@@ -577807,9 +579040,9 @@ function computeSignalFromText(text, confidence) {
577807
579040
  else score = 0.15;
577808
579041
  score -= repeatingCharPenalty(t2) * 0.4;
577809
579042
  if (typeof confidence === "number" && !Number.isNaN(confidence)) {
577810
- score = 0.7 * score + 0.3 * clamp01(confidence);
579043
+ score = 0.7 * score + 0.3 * clamp014(confidence);
577811
579044
  }
577812
- return clamp01(score);
579045
+ return clamp014(score);
577813
579046
  }
577814
579047
  function truncateForLog(s2, n2) {
577815
579048
  return s2.length <= n2 ? s2 : s2.slice(0, n2 - 1) + "…";
@@ -578079,7 +579312,7 @@ Rules:
578079
579312
  }, MAX_SEGMENT_MS);
578080
579313
  }
578081
579314
  this.captureBuffer = text;
578082
- this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp01(snr) : computeSignalFromText(text, confidence);
579315
+ this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp014(snr) : computeSignalFromText(text, confidence);
578083
579316
  this.emit("snr", { score: this.lastSignalScore });
578084
579317
  this.onPartialTranscript(text);
578085
579318
  if (this.silenceTimer) clearTimeout(this.silenceTimer);
@@ -590526,13 +591759,13 @@ __export(serve_exports, {
590526
591759
  });
590527
591760
  import * as http5 from "node:http";
590528
591761
  import * as https3 from "node:https";
590529
- import { createRequire as createRequire4 } from "node:module";
591762
+ import { createRequire as createRequire5 } from "node:module";
590530
591763
  import { fileURLToPath as fileURLToPath17 } from "node:url";
590531
591764
  import { dirname as dirname36, join as join119, resolve as resolve38 } from "node:path";
590532
591765
  import { homedir as homedir41 } from "node:os";
590533
591766
  import { spawn as spawn25, execSync as execSync56 } from "node:child_process";
590534
591767
  import { mkdirSync as mkdirSync63, writeFileSync as writeFileSync55, readFileSync as readFileSync83, readdirSync as readdirSync35, existsSync as existsSync103, watch as fsWatch3, renameSync as renameSync8, unlinkSync as unlinkSync24 } from "node:fs";
590535
- import { randomBytes as randomBytes23, randomUUID as randomUUID14 } from "node:crypto";
591768
+ import { randomBytes as randomBytes23, randomUUID as randomUUID15 } from "node:crypto";
590536
591769
  import { createHash as createHash15 } from "node:crypto";
590537
591770
  function getVersion3() {
590538
591771
  try {
@@ -593617,7 +594850,7 @@ async function handleRequest(req2, res, ollamaUrl, verbose) {
593617
594850
  const urlObj = new URL(req2.url ?? "/", `http://${req2.headers.host ?? "localhost"}`);
593618
594851
  const pathname = urlObj.pathname;
593619
594852
  const startMs = performance.now();
593620
- const requestId = req2.headers["x-request-id"] || randomUUID14();
594853
+ const requestId = req2.headers["x-request-id"] || randomUUID15();
593621
594854
  res.setHeader("X-Request-ID", requestId);
593622
594855
  res.setHeader("X-API-Version", API_VERSION);
593623
594856
  if (method === "OPTIONS") {
@@ -593696,8 +594929,8 @@ async function handleRequest(req2, res, ollamaUrl, verbose) {
593696
594929
  const entry = fileMap[pathname];
593697
594930
  if (entry) {
593698
594931
  try {
593699
- const { createRequire: createRequire7 } = await import("node:module");
593700
- const req22 = createRequire7(import.meta.url);
594932
+ const { createRequire: createRequire8 } = await import("node:module");
594933
+ const req22 = createRequire8(import.meta.url);
593701
594934
  const cssEntry = req22.resolve("swagger-ui-dist/swagger-ui.css");
593702
594935
  const fs7 = await import("node:fs");
593703
594936
  const path8 = await import("node:path");
@@ -596357,9 +597590,9 @@ function startApiServer(options2 = {}) {
596357
597590
  taskMgr.onEviction((taskId) => {
596358
597591
  deleteAgentTaskSidecar(taskId);
596359
597592
  });
596360
- restoreAgentTasks(taskMgr).then((report) => {
596361
- if (report.restored > 0) {
596362
- log22(` task recovery: restored=${report.restored} re-attached=${report.reAttached} marked-failed=${report.markedFailed}
597593
+ restoreAgentTasks(taskMgr).then((report2) => {
597594
+ if (report2.restored > 0) {
597595
+ log22(` task recovery: restored=${report2.restored} re-attached=${report2.reAttached} marked-failed=${report2.markedFailed}
596363
597596
  `);
596364
597597
  }
596365
597598
  }).catch(() => {
@@ -596373,9 +597606,9 @@ function startApiServer(options2 = {}) {
596373
597606
  } catch {
596374
597607
  }
596375
597608
  try {
596376
- const report = loadPersistedSessions();
596377
- if (report.restored > 0 || report.staleInFlight > 0) {
596378
- log22(` chat sessions: restored=${report.restored} stale-in-flight=${report.staleInFlight}
597609
+ const report2 = loadPersistedSessions();
597610
+ if (report2.restored > 0 || report2.staleInFlight > 0) {
597611
+ log22(` chat sessions: restored=${report2.restored} stale-in-flight=${report2.staleInFlight}
596379
597612
  `);
596380
597613
  }
596381
597614
  } catch {
@@ -597173,7 +598406,7 @@ var init_serve = __esm({
597173
598406
  init_profiles();
597174
598407
  init_docker();
597175
598408
  init_typed_node_events();
597176
- require3 = createRequire4(import.meta.url);
598409
+ require3 = createRequire5(import.meta.url);
597177
598410
  endpointRegistry = [];
597178
598411
  modelRouteMap = /* @__PURE__ */ new Map();
597179
598412
  endpointUsage = /* @__PURE__ */ new Map();
@@ -597195,7 +598428,7 @@ var init_serve = __esm({
597195
598428
  // packages/cli/src/tui/interactive.ts
597196
598429
  import { cwd } from "node:process";
597197
598430
  import { resolve as resolve39, join as join120, dirname as dirname37, extname as extname12 } from "node:path";
597198
- import { createRequire as createRequire5 } from "node:module";
598431
+ import { createRequire as createRequire6 } from "node:module";
597199
598432
  import { fileURLToPath as fileURLToPath18 } from "node:url";
597200
598433
  import { readFileSync as readFileSync84, writeFileSync as writeFileSync56, appendFileSync as appendFileSync8, rmSync as rmSync5, readdirSync as readdirSync36, mkdirSync as mkdirSync64 } from "node:fs";
597201
598434
  import { existsSync as existsSync104 } from "node:fs";
@@ -597213,7 +598446,7 @@ function formatTimeAgo2(date) {
597213
598446
  }
597214
598447
  function getVersion4() {
597215
598448
  try {
597216
- const require4 = createRequire5(import.meta.url);
598449
+ const require4 = createRequire6(import.meta.url);
597217
598450
  const thisDir = dirname37(fileURLToPath18(import.meta.url));
597218
598451
  const candidates = [
597219
598452
  join120(thisDir, "..", "package.json"),
@@ -604740,18 +605973,18 @@ async function evalCommand(opts, config) {
604740
605973
  const start2 = Date.now();
604741
605974
  let result;
604742
605975
  try {
604743
- const report = await loop.run(task.request, evalRepoRoot);
604744
- const passed2 = task.expectedStatuses.includes(report.status);
605976
+ const report2 = await loop.run(task.request, evalRepoRoot);
605977
+ const passed2 = task.expectedStatuses.includes(report2.status);
604745
605978
  result = {
604746
605979
  task,
604747
- status: report.status,
605980
+ status: report2.status,
604748
605981
  passed: passed2,
604749
605982
  durationMs: Date.now() - start2
604750
605983
  };
604751
605984
  if (passed2) {
604752
- spinner.succeed(`[${task.id}] PASS (${report.status})`);
605985
+ spinner.succeed(`[${task.id}] PASS (${report2.status})`);
604753
605986
  } else {
604754
- spinner.fail(`[${task.id}] FAIL (got: ${report.status})`);
605987
+ spinner.fail(`[${task.id}] FAIL (got: ${report2.status})`);
604755
605988
  }
604756
605989
  } catch (err) {
604757
605990
  result = {
@@ -604863,7 +606096,7 @@ init_output();
604863
606096
  init_updater();
604864
606097
  init_typed_node_events();
604865
606098
  import { parseArgs as nodeParseArgs2 } from "node:util";
604866
- import { createRequire as createRequire6 } from "node:module";
606099
+ import { createRequire as createRequire7 } from "node:module";
604867
606100
  import { fileURLToPath as fileURLToPath19 } from "node:url";
604868
606101
  import { dirname as dirname38, join as join124 } from "node:path";
604869
606102
 
@@ -604943,7 +606176,7 @@ function createCli(options2) {
604943
606176
  import { parseArgs as nodeParseArgs } from "node:util";
604944
606177
 
604945
606178
  // packages/cli/src/types.ts
604946
- var DEFAULT_OPTIONS = {
606179
+ var DEFAULT_OPTIONS2 = {
604947
606180
  model: "qwen-2.5-coder-32b",
604948
606181
  backendUrl: "http://localhost:8000/v1",
604949
606182
  projectRoot: process.cwd(),
@@ -604972,12 +606205,12 @@ function parseArgs(argv) {
604972
606205
  process.exit(0);
604973
606206
  }
604974
606207
  return {
604975
- model: values.model ?? DEFAULT_OPTIONS.model,
604976
- backendUrl: values["backend-url"] ?? DEFAULT_OPTIONS.backendUrl,
604977
- projectRoot: values["project-root"] ?? DEFAULT_OPTIONS.projectRoot,
604978
- maxIterations: values["max-iterations"] ? parseInt(values["max-iterations"], 10) : DEFAULT_OPTIONS.maxIterations,
604979
- temperature: values.temperature ? parseFloat(values.temperature) : DEFAULT_OPTIONS.temperature,
604980
- verbose: values.verbose ?? DEFAULT_OPTIONS.verbose
606208
+ model: values.model ?? DEFAULT_OPTIONS2.model,
606209
+ backendUrl: values["backend-url"] ?? DEFAULT_OPTIONS2.backendUrl,
606210
+ projectRoot: values["project-root"] ?? DEFAULT_OPTIONS2.projectRoot,
606211
+ maxIterations: values["max-iterations"] ? parseInt(values["max-iterations"], 10) : DEFAULT_OPTIONS2.maxIterations,
606212
+ temperature: values.temperature ? parseFloat(values.temperature) : DEFAULT_OPTIONS2.temperature,
606213
+ verbose: values.verbose ?? DEFAULT_OPTIONS2.verbose
604981
606214
  };
604982
606215
  }
604983
606216
  function printHelp() {
@@ -605004,7 +606237,7 @@ init_spinner();
605004
606237
  init_output();
605005
606238
  function getVersion5() {
605006
606239
  try {
605007
- const require4 = createRequire6(import.meta.url);
606240
+ const require4 = createRequire7(import.meta.url);
605008
606241
  const pkgPath = join124(dirname38(fileURLToPath19(import.meta.url)), "..", "package.json");
605009
606242
  const pkg = require4(pkgPath);
605010
606243
  return pkg.version;