omnius 1.0.166 → 1.0.167

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
@@ -97800,7 +97800,7 @@ var require_auto = __commonJS({
97800
97800
  // ../node_modules/acme-client/src/client.js
97801
97801
  var require_client = __commonJS({
97802
97802
  "../node_modules/acme-client/src/client.js"(exports, module) {
97803
- var { createHash: createHash35 } = __require("crypto");
97803
+ var { createHash: createHash36 } = __require("crypto");
97804
97804
  var { getPemBodyAsB64u } = require_crypto();
97805
97805
  var { log: log22 } = require_logger();
97806
97806
  var HttpClient = require_http();
@@ -98111,14 +98111,14 @@ var require_client = __commonJS({
98111
98111
  */
98112
98112
  async getChallengeKeyAuthorization(challenge) {
98113
98113
  const jwk = this.http.getJwk();
98114
- const keysum = createHash35("sha256").update(JSON.stringify(jwk));
98114
+ const keysum = createHash36("sha256").update(JSON.stringify(jwk));
98115
98115
  const thumbprint = keysum.digest("base64url");
98116
98116
  const result = `${challenge.token}.${thumbprint}`;
98117
98117
  if (challenge.type === "http-01") {
98118
98118
  return result;
98119
98119
  }
98120
98120
  if (challenge.type === "dns-01") {
98121
- return createHash35("sha256").update(result).digest("base64url");
98121
+ return createHash36("sha256").update(result).digest("base64url");
98122
98122
  }
98123
98123
  if (challenge.type === "tls-alpn-01") {
98124
98124
  return result;
@@ -240798,7 +240798,7 @@ var require_websocket2 = __commonJS({
240798
240798
  var http6 = __require("http");
240799
240799
  var net5 = __require("net");
240800
240800
  var tls2 = __require("tls");
240801
- var { randomBytes: randomBytes29, createHash: createHash35 } = __require("crypto");
240801
+ var { randomBytes: randomBytes29, createHash: createHash36 } = __require("crypto");
240802
240802
  var { Duplex: Duplex3, Readable } = __require("stream");
240803
240803
  var { URL: URL3 } = __require("url");
240804
240804
  var PerMessageDeflate3 = require_permessage_deflate2();
@@ -241458,7 +241458,7 @@ var require_websocket2 = __commonJS({
241458
241458
  abortHandshake(websocket, socket, "Invalid Upgrade header");
241459
241459
  return;
241460
241460
  }
241461
- const digest3 = createHash35("sha1").update(key + GUID).digest("base64");
241461
+ const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
241462
241462
  if (res.headers["sec-websocket-accept"] !== digest3) {
241463
241463
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
241464
241464
  return;
@@ -241825,7 +241825,7 @@ var require_websocket_server = __commonJS({
241825
241825
  var EventEmitter15 = __require("events");
241826
241826
  var http6 = __require("http");
241827
241827
  var { Duplex: Duplex3 } = __require("stream");
241828
- var { createHash: createHash35 } = __require("crypto");
241828
+ var { createHash: createHash36 } = __require("crypto");
241829
241829
  var extension3 = require_extension2();
241830
241830
  var PerMessageDeflate3 = require_permessage_deflate2();
241831
241831
  var subprotocol3 = require_subprotocol();
@@ -242126,7 +242126,7 @@ var require_websocket_server = __commonJS({
242126
242126
  );
242127
242127
  }
242128
242128
  if (this._state > RUNNING) return abortHandshake(socket, 503);
242129
- const digest3 = createHash35("sha1").update(key + GUID).digest("base64");
242129
+ const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
242130
242130
  const headers = [
242131
242131
  "HTTP/1.1 101 Switching Protocols",
242132
242132
  "Upgrade: websocket",
@@ -254933,13 +254933,13 @@ Justification: ${justification || "(none provided)"}`,
254933
254933
  }
254934
254934
  const snapshot = JSON.stringify(this.selfState, null, 2);
254935
254935
  try {
254936
- const { createHash: createHash35 } = await import("node:crypto");
254936
+ const { createHash: createHash36 } = await import("node:crypto");
254937
254937
  const snapshotDir = join33(this.cwd, ".omnius", "identity", "snapshots");
254938
254938
  await mkdir7(snapshotDir, { recursive: true });
254939
254939
  const version4 = this.selfState.version;
254940
254940
  const snapshotPath = join33(snapshotDir, `v${version4}.json`);
254941
254941
  await writeFile12(snapshotPath, snapshot, "utf8");
254942
- const hash = createHash35("sha256").update(snapshot).digest("hex");
254942
+ const hash = createHash36("sha256").update(snapshot).digest("hex");
254943
254943
  await writeFile12(join33(this.cwd, ".omnius", "identity", "latest-hash.txt"), hash, "utf8");
254944
254944
  let ipfsCid = "";
254945
254945
  try {
@@ -255072,8 +255072,8 @@ New: ${newNarrative.slice(0, 200)}...`,
255072
255072
  }
255073
255073
  // ── Helpers ──────────────────────────────────────────────────────────────
255074
255074
  createDefaultState() {
255075
- const { createHash: createHash35 } = __require("node:crypto");
255076
- const machineId = createHash35("sha256").update(this.cwd).digest("hex").slice(0, 12);
255075
+ const { createHash: createHash36 } = __require("node:crypto");
255076
+ const machineId = createHash36("sha256").update(this.cwd).digest("hex").slice(0, 12);
255077
255077
  return {
255078
255078
  self_id: `omnius-${machineId}`,
255079
255079
  version: 1,
@@ -255155,9 +255155,9 @@ New: ${newNarrative.slice(0, 200)}...`,
255155
255155
  let cid;
255156
255156
  if (this.selfState.version > prevVersion) {
255157
255157
  try {
255158
- const { createHash: createHash35 } = await import("node:crypto");
255158
+ const { createHash: createHash36 } = await import("node:crypto");
255159
255159
  const stateJson = JSON.stringify(this.selfState);
255160
- const hash = createHash35("sha256").update(stateJson).digest("hex").slice(0, 32);
255160
+ const hash = createHash36("sha256").update(stateJson).digest("hex").slice(0, 32);
255161
255161
  const cidsPath = join33(this.cwd, ".omnius", "identity", "cids.json");
255162
255162
  const cidsData = { latest: "", hash, version: this.selfState.version };
255163
255163
  try {
@@ -534419,7 +534419,7 @@ var init_world_state_disk_scan = __esm({
534419
534419
  import { existsSync as existsSync70, statSync as statSync29 } from "node:fs";
534420
534420
  import { isAbsolute as isAbsolute4, join as join83 } from "node:path";
534421
534421
  function tokenize3(content) {
534422
- const STOP = /* @__PURE__ */ new Set([
534422
+ const STOP2 = /* @__PURE__ */ new Set([
534423
534423
  "the",
534424
534424
  "and",
534425
534425
  "or",
@@ -534450,7 +534450,7 @@ function tokenize3(content) {
534450
534450
  "into",
534451
534451
  "from"
534452
534452
  ]);
534453
- return Array.from(new Set(content.toLowerCase().split(/[^a-z0-9]+/g).filter((s2) => s2.length >= 3 && !STOP.has(s2))));
534453
+ return Array.from(new Set(content.toLowerCase().split(/[^a-z0-9]+/g).filter((s2) => s2.length >= 3 && !STOP2.has(s2))));
534454
534454
  }
534455
534455
  function heuristicMatch(rel, tokens) {
534456
534456
  if (tokens.length === 0)
@@ -543572,6 +543572,480 @@ var init_embeddingDrift = __esm({
543572
543572
  }
543573
543573
  });
543574
543574
 
543575
+ // packages/memory/dist/semanticContext.js
543576
+ import { createHash as createHash20 } from "node:crypto";
543577
+ function estimateTokens(text) {
543578
+ return Math.max(0, Math.ceil((text || "").length / 4));
543579
+ }
543580
+ function estimateContextTokens(content, supplied) {
543581
+ return Number.isFinite(supplied) ? Math.max(0, Math.ceil(supplied)) : estimateTokens(content);
543582
+ }
543583
+ function stableId(parts) {
543584
+ return createHash20("sha256").update(parts.join("\n")).digest("hex").slice(0, 16);
543585
+ }
543586
+ function clamp016(x) {
543587
+ if (!Number.isFinite(x))
543588
+ return 0;
543589
+ if (x < 0)
543590
+ return 0;
543591
+ if (x > 1)
543592
+ return 1;
543593
+ return x;
543594
+ }
543595
+ function tokenCount(item) {
543596
+ const supplied = Number.isFinite(item.tokenCount) ? item.tokenCount : item.tokenEstimate;
543597
+ return estimateContextTokens(item.content, supplied);
543598
+ }
543599
+ function itemId(item) {
543600
+ return item.id ?? `ctx_${stableId([item.source, item.kind, item.content.slice(0, 240)])}`;
543601
+ }
543602
+ function isConsolidated(item) {
543603
+ if (item.consolidated !== void 0)
543604
+ return item.consolidated;
543605
+ const metadataConsolidated = item.metadata?.["consolidated"] ?? item.metadata?.["isConsolidated"];
543606
+ if (typeof metadataConsolidated === "boolean")
543607
+ return metadataConsolidated;
543608
+ const haystack = `${item.kind} ${item.source} ${String(item.metadata?.["stage"] ?? "")}`.toLowerCase();
543609
+ return /\b(gist|summary|semantic|memory|reflection|self_model|social_state|compressed|context_frame|anchor)\b/.test(haystack);
543610
+ }
543611
+ function addBucket(buckets, key, tokens, consolidated) {
543612
+ const k = key || "unknown";
543613
+ const bucket = buckets[k] ?? { items: 0, itemCount: 0, tokens: 0, totalTokens: 0, rawTokens: 0, consolidatedTokens: 0 };
543614
+ bucket.items += 1;
543615
+ bucket.itemCount += 1;
543616
+ bucket.tokens += tokens;
543617
+ bucket.totalTokens += tokens;
543618
+ if (consolidated)
543619
+ bucket.consolidatedTokens += tokens;
543620
+ else
543621
+ bucket.rawTokens += tokens;
543622
+ buckets[k] = bucket;
543623
+ }
543624
+ function buildContextPressureSnapshot(items, opts = {}) {
543625
+ const targetRawTokenBudget = Math.max(0, Math.floor(opts.targetRawTokenBudget ?? 2e3));
543626
+ const perSource = {};
543627
+ const perKind = {};
543628
+ let rawTokens = 0;
543629
+ let consolidatedTokens = 0;
543630
+ for (const item of items) {
543631
+ const tokens = tokenCount(item);
543632
+ const consolidated = isConsolidated(item);
543633
+ if (consolidated)
543634
+ consolidatedTokens += tokens;
543635
+ else
543636
+ rawTokens += tokens;
543637
+ addBucket(perSource, item.source, tokens, consolidated);
543638
+ addBucket(perKind, item.kind, tokens, consolidated);
543639
+ }
543640
+ const totalTokens = rawTokens + consolidatedTokens;
543641
+ const compressionTargetTokens = Math.ceil(rawTokens * 0.6);
543642
+ return {
543643
+ generatedAt: opts.now ?? Date.now(),
543644
+ itemCount: items.length,
543645
+ semanticChunkCount: opts.semanticChunkCount ?? new SemanticChunker().chunk(items, { now: opts.now }).length,
543646
+ totalTokens,
543647
+ rawTokens,
543648
+ consolidatedTokens,
543649
+ rawRatio: totalTokens > 0 ? rawTokens / totalTokens : 0,
543650
+ consolidatedRatio: totalTokens > 0 ? consolidatedTokens / totalTokens : 0,
543651
+ compressionTargetTokens,
543652
+ targetRawTokenBudget,
543653
+ rawTokensToTarget: Math.max(0, rawTokens - targetRawTokenBudget),
543654
+ perSource,
543655
+ perKind
543656
+ };
543657
+ }
543658
+ function extractSemanticEntities(text) {
543659
+ const out = /* @__PURE__ */ new Set();
543660
+ const add2 = (raw) => {
543661
+ const value2 = raw.trim().replace(/[.,;:!?)]$/, "");
543662
+ if (value2.length < 2)
543663
+ return;
543664
+ if (STOP.has(value2.toLowerCase()))
543665
+ return;
543666
+ out.add(value2);
543667
+ };
543668
+ for (const m2 of text.matchAll(/(?:[\w.-]+\/)+[\w./-]+\.[A-Za-z0-9]+|[\w.-]+\.(?:ts|tsx|js|jsx|json|md|py|rs|go|c|cpp|h|css|html)\b/g))
543669
+ add2(m2[0]);
543670
+ for (const m2 of text.matchAll(/@[A-Za-z0-9_]{2,}/g))
543671
+ add2(m2[0].toLowerCase());
543672
+ for (const m2 of text.matchAll(/\b[A-Za-z_][A-Za-z0-9_]*(?:Error|Exception|Failure|Failed)\b/g))
543673
+ add2(m2[0]);
543674
+ for (const m2 of text.matchAll(/\b[a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]+)+\b/g))
543675
+ add2(m2[0]);
543676
+ for (const m2 of text.matchAll(/\b[A-Z][A-Za-z0-9]*(?:[A-Z][A-Za-z0-9]*)?\b/g))
543677
+ add2(m2[0]);
543678
+ for (const m2 of text.matchAll(/\b(?:memory|context|telegram|router|tool|shell|diagnostic|consolidation|forgetting|chunk|reply|notes|voice|trust|semantic)\b/gi))
543679
+ add2(m2[0].toLowerCase());
543680
+ return [...out].slice(0, 24);
543681
+ }
543682
+ function semanticLabelFor(item) {
543683
+ const explicit = item.semanticLabels?.[0] || (Array.isArray(item.metadata?.["semanticLabels"]) ? String(item.metadata["semanticLabels"][0] ?? "") : "");
543684
+ if (explicit.trim())
543685
+ return explicit.trim().toLowerCase();
543686
+ const h = `${item.kind} ${item.source} ${item.content}`.toLowerCase();
543687
+ if (/telegram|@\w|reply|chat|relationship|social/.test(h))
543688
+ return "telegram conversation and relationship state";
543689
+ if (/error|failed|failure|diagnostic|stderr|exit code|exception/.test(h))
543690
+ return "diagnostic errors and recovery";
543691
+ if (/todo|task|goal|plan|current step|completed/.test(h))
543692
+ return "active task and plan";
543693
+ if (/memory|gist|reflection|lesson|prior experience/.test(h))
543694
+ return "retrieved memory and lessons";
543695
+ if (/tool|shell|command|output|stdout|stderr/.test(h))
543696
+ return "tool results and execution evidence";
543697
+ if (/identity|persona|voice|policy|instruction|system prompt/.test(h))
543698
+ return "identity and behavioral constraints";
543699
+ if (/(?:[\w.-]+\/)+[\w./-]+|\.ts\b|\.tsx\b|\.js\b|function|class|export/.test(h))
543700
+ return "codebase files and symbols";
543701
+ return "general working context";
543702
+ }
543703
+ function itemUtility(item, now) {
543704
+ const priority = (item.priority ?? 0) / 100;
543705
+ const importance = (item.importance ?? 5) / 10;
543706
+ const strength = Math.min(1, Math.log2(Math.max(1, item.strength ?? 1)) / 4);
543707
+ const reuse = Math.min(1, (item.reuseCount ?? 0) / 8);
543708
+ const age = item.timestamp ? Math.max(0, now - item.timestamp) : 0;
543709
+ const recency = item.timestamp ? Math.exp(-age / (24 * 60 * 6e4)) : 0.5;
543710
+ return clamp016(0.25 + priority * 0.25 + importance * 0.25 + strength * 0.12 + reuse * 0.08 + recency * 0.05);
543711
+ }
543712
+ function stalenessFor(items, now) {
543713
+ const timestamps = items.map((i2) => i2.timestamp).filter((v) => Number.isFinite(v));
543714
+ if (timestamps.length === 0)
543715
+ return 0.5;
543716
+ const newest = Math.max(...timestamps);
543717
+ return clamp016(1 - Math.exp(-Math.max(0, now - newest) / (6 * 60 * 6e4)));
543718
+ }
543719
+ function summarize(items, maxChars = 420) {
543720
+ const ranked = [...items].sort((a2, b) => (b.priority ?? 0) - (a2.priority ?? 0) || tokenCount(b) - tokenCount(a2));
543721
+ const parts = [];
543722
+ for (const item of ranked.slice(0, 4)) {
543723
+ const text = item.content.replace(/\s+/g, " ").trim();
543724
+ if (!text)
543725
+ continue;
543726
+ parts.push(text.length > 140 ? text.slice(0, 139).trimEnd() + "..." : text);
543727
+ if (parts.join(" ").length >= maxChars)
543728
+ break;
543729
+ }
543730
+ const summary = parts.join(" ");
543731
+ return summary.length > maxChars ? summary.slice(0, maxChars - 3).trimEnd() + "..." : summary;
543732
+ }
543733
+ function openQuestionsFor(items) {
543734
+ const out = [];
543735
+ for (const item of items) {
543736
+ for (const line of item.content.split(/\n+/)) {
543737
+ const trimmed = line.trim();
543738
+ if (!trimmed)
543739
+ continue;
543740
+ if (/[?]$|\b(unresolved|blocked|unknown|gap|needs?|todo|fixme)\b/i.test(trimmed)) {
543741
+ out.push(trimmed.replace(/\s+/g, " ").slice(0, 180));
543742
+ }
543743
+ if (out.length >= 6)
543744
+ return [...new Set(out)];
543745
+ }
543746
+ }
543747
+ return [...new Set(out)];
543748
+ }
543749
+ function entityOverlap(a2, b) {
543750
+ const as = new Set(a2.map((v) => v.toLowerCase()));
543751
+ const bs = new Set(b.map((v) => v.toLowerCase()));
543752
+ if (as.size === 0 || bs.size === 0)
543753
+ return 0;
543754
+ let inter = 0;
543755
+ for (const x of as)
543756
+ if (bs.has(x))
543757
+ inter++;
543758
+ return inter / Math.min(as.size, bs.size);
543759
+ }
543760
+ function groupUtility(items, now) {
543761
+ if (items.length === 0)
543762
+ return 0;
543763
+ const raw = items.reduce((sum, item) => sum + itemUtility(item, now), 0) / items.length;
543764
+ const evidenceBoost = Math.min(0.2, Math.log1p(items.length) / 15);
543765
+ return clamp016(raw + evidenceBoost);
543766
+ }
543767
+ function chunkItemLike(chunk) {
543768
+ const newest = Math.max(0, ...chunk.items.map((i2) => i2.timestamp ?? 0));
543769
+ return {
543770
+ id: chunk.id,
543771
+ source: chunk.sourceKinds.join(","),
543772
+ kind: chunk.kinds.join(","),
543773
+ content: chunk.summary,
543774
+ tokenCount: chunk.tokenEstimate,
543775
+ priority: Math.round(chunk.utilityScore * 100),
543776
+ timestamp: newest || void 0,
543777
+ importance: chunk.items.reduce((s2, i2) => s2 + (i2.importance ?? 5), 0) / Math.max(1, chunk.items.length),
543778
+ strength: chunk.items.reduce((s2, i2) => s2 + (i2.strength ?? 1), 0) / Math.max(1, chunk.items.length),
543779
+ reuseCount: chunk.items.reduce((s2, i2) => s2 + (i2.reuseCount ?? 0), 0),
543780
+ entities: chunk.entities
543781
+ };
543782
+ }
543783
+ function buildActiveForgettingReport(chunksOrItems, opts = {}) {
543784
+ const now = opts.now ?? Date.now();
543785
+ const items = chunksOrItems.map((entry) => "summary" in entry ? chunkItemLike(entry) : entry);
543786
+ const selectiveForgetCandidates = [];
543787
+ const rehearseCandidates = [];
543788
+ const presentButUnused = [];
543789
+ const interferencePairs = [];
543790
+ for (const item of items) {
543791
+ const utility = itemUtility(item, now);
543792
+ const label = semanticLabelFor(item);
543793
+ const unused = (item.reuseCount ?? 0) === 0 && (item.strength ?? 1) <= 1.2;
543794
+ const ageMs = item.lastRetrieved ? Math.max(0, now - item.lastRetrieved) : item.timestamp ? Math.max(0, now - item.timestamp) : Infinity;
543795
+ if (utility < 0.42 && (item.importance ?? 5) <= 5) {
543796
+ selectiveForgetCandidates.push({ id: itemId(item), label, score: 1 - utility, reason: "low utility, low importance, or stale context" });
543797
+ }
543798
+ if ((item.importance ?? 5) >= 7 && ((item.reuseCount ?? 0) > 0 || (item.strength ?? 1) > 1) && ageMs > 30 * 6e4) {
543799
+ rehearseCandidates.push({ id: itemId(item), label, score: utility, reason: "important memory has evidence of reuse but is aging" });
543800
+ }
543801
+ if (unused) {
543802
+ presentButUnused.push({ id: itemId(item), label, score: utility, reason: "present in context without reuse evidence" });
543803
+ }
543804
+ }
543805
+ for (let i2 = 0; i2 < items.length; i2++) {
543806
+ for (let j = i2 + 1; j < items.length; j++) {
543807
+ const a2 = items[i2];
543808
+ const b = items[j];
543809
+ const aEnt = a2.entities ?? extractSemanticEntities(a2.content);
543810
+ const bEnt = b.entities ?? extractSemanticEntities(b.content);
543811
+ const overlap = entityOverlap(aEnt, bEnt);
543812
+ const contradiction = /\b(no longer|superseded|instead|not|failed|wrong|obsolete)\b/i.test(`${a2.content}
543813
+ ${b.content}`);
543814
+ const score = overlap + (contradiction ? 0.35 : 0);
543815
+ if (score >= 0.45 && a2.content.trim() !== b.content.trim()) {
543816
+ const aId = itemId(a2);
543817
+ const bId = itemId(b);
543818
+ const sharedEntities = aEnt.filter((entity) => bEnt.map((v) => v.toLowerCase()).includes(entity.toLowerCase()));
543819
+ interferencePairs.push({
543820
+ a: aId,
543821
+ b: bId,
543822
+ aId,
543823
+ bId,
543824
+ aLabel: semanticLabelFor(a2),
543825
+ bLabel: semanticLabelFor(b),
543826
+ score: clamp016(score),
543827
+ overlap: clamp016(score),
543828
+ sharedEntities,
543829
+ reason: contradiction ? "overlapping entities with supersession/negation language" : "overlapping entities compete for recall"
543830
+ });
543831
+ }
543832
+ }
543833
+ }
543834
+ const useful = items.filter((i2) => itemUtility(i2, now) >= 0.5 || (i2.reuseCount ?? 0) > 0).length;
543835
+ const interferencePenalty = Math.min(0.25, interferencePairs.length * 0.03);
543836
+ const activeRetentionEstimate = clamp016(items.length === 0 ? 1 : useful / items.length - interferencePenalty);
543837
+ return {
543838
+ generatedAt: now,
543839
+ activeRetentionEstimate,
543840
+ selectiveForgetCandidates: selectiveForgetCandidates.sort((a2, b) => b.score - a2.score).slice(0, 12),
543841
+ rehearseCandidates: rehearseCandidates.sort((a2, b) => b.score - a2.score).slice(0, 12),
543842
+ presentButUnused: presentButUnused.sort((a2, b) => a2.score - b.score).slice(0, 12),
543843
+ interferencePairs: interferencePairs.sort((a2, b) => b.score - a2.score).slice(0, 20)
543844
+ };
543845
+ }
543846
+ function shouldTriggerContextConsolidation(snapshot, forgetting, opts = {}) {
543847
+ const minRawTokens = opts.minRawTokens ?? snapshot.targetRawTokenBudget;
543848
+ const maxRawRatio = opts.maxRawRatio ?? 0.35;
543849
+ const minRetention = opts.minRetention ?? 0.7;
543850
+ const reasons = [];
543851
+ let score = 0;
543852
+ if (snapshot.rawTokens > minRawTokens) {
543853
+ reasons.push(`raw tokens ${snapshot.rawTokens} exceed target ${minRawTokens}`);
543854
+ score += 0.4;
543855
+ }
543856
+ if (snapshot.rawRatio > maxRawRatio) {
543857
+ reasons.push(`raw ratio ${snapshot.rawRatio.toFixed(2)} exceeds ${maxRawRatio.toFixed(2)}`);
543858
+ score += 0.25;
543859
+ }
543860
+ if (snapshot.rawTokensToTarget > 0) {
543861
+ reasons.push(`${snapshot.rawTokensToTarget} raw tokens must move to reach target`);
543862
+ score += Math.min(0.25, snapshot.rawTokensToTarget / Math.max(1, snapshot.rawTokens));
543863
+ }
543864
+ if (forgetting && forgetting.activeRetentionEstimate < minRetention) {
543865
+ reasons.push(`active retention estimate ${forgetting.activeRetentionEstimate.toFixed(2)} below ${minRetention.toFixed(2)}`);
543866
+ score += 0.25;
543867
+ }
543868
+ if (forgetting && forgetting.interferencePairs.length > 0) {
543869
+ reasons.push(`${forgetting.interferencePairs.length} interference pair(s) detected`);
543870
+ score += Math.min(0.2, forgetting.interferencePairs.length * 0.04);
543871
+ }
543872
+ const minScore = opts.minScore ?? 0.45;
543873
+ return { shouldConsolidate: score >= minScore, reasons, score: clamp016(score) };
543874
+ }
543875
+ function ingestContextFeedbackMarkdown(markdown, opts = {}) {
543876
+ const metrics2 = {};
543877
+ for (const line of markdown.split(/\n/)) {
543878
+ const m2 = line.match(/^\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|/);
543879
+ if (!m2)
543880
+ continue;
543881
+ const key = m2[1].trim();
543882
+ const value2 = m2[2].trim();
543883
+ if (!key || key === "Metric" || /^-+$/.test(key))
543884
+ continue;
543885
+ metrics2[key] = parseMetricValue2(value2);
543886
+ }
543887
+ const gaps = [];
543888
+ const gapRegex = /^##\s+GAP\s+(\d+):\s+(.+?)\s*$/gim;
543889
+ const matches = [...markdown.matchAll(gapRegex)];
543890
+ for (let i2 = 0; i2 < matches.length; i2++) {
543891
+ const match = matches[i2];
543892
+ const start2 = match.index + match[0].length;
543893
+ const end = matches[i2 + 1]?.index ?? markdown.search(/\n## Summary:/);
543894
+ const body = markdown.slice(start2, end === -1 ? void 0 : end).trim();
543895
+ const title = match[2].trim();
543896
+ const labels = [
543897
+ "context_window",
543898
+ title.toLowerCase().includes("sleep") ? "dynamic_consolidation" : "",
543899
+ title.toLowerCase().includes("forget") ? "active_forgetting" : "",
543900
+ title.toLowerCase().includes("chunk") ? "semantic_chunking" : ""
543901
+ ].filter(Boolean);
543902
+ gaps.push({ id: `gap_${match[1]}`, title, body, labels, metrics: extractInlineMetrics(body) });
543903
+ }
543904
+ const summary = gaps.map((g) => `${g.id}=${g.title}`).join("; ");
543905
+ const source = opts.sourcePath ?? "context-feedback";
543906
+ const items = gaps.map((gap) => ({
543907
+ id: `feedback_${gap.id}`,
543908
+ source,
543909
+ kind: "agent_feedback_gap",
543910
+ content: `${gap.title}
543911
+ ${gap.body}`,
543912
+ consolidated: false,
543913
+ priority: 90,
543914
+ timestamp: opts.now,
543915
+ importance: 8,
543916
+ semanticLabels: gap.labels,
543917
+ metadata: { sourcePath: opts.sourcePath, gapId: gap.id }
543918
+ }));
543919
+ const episode = {
543920
+ sessionId: opts.sessionId,
543921
+ modality: "reflection",
543922
+ toolName: "context_feedback_ingest",
543923
+ content: `External agent memory feedback: ${summary || "context organization gaps"}`,
543924
+ importance: 8,
543925
+ decayClass: "procedural",
543926
+ metadata: {
543927
+ kind: "context_feedback",
543928
+ sourcePath: opts.sourcePath,
543929
+ metrics: metrics2,
543930
+ gaps: gaps.map(({ id, title, labels }) => ({ id, title, labels })),
543931
+ semanticLabels: ["context_window", "dynamic_consolidation", "active_forgetting", "semantic_chunking"]
543932
+ }
543933
+ };
543934
+ return { episode, items, chunkItems: items, metrics: metrics2, gaps };
543935
+ }
543936
+ function parseMetricValue2(raw) {
543937
+ const cleaned = raw.trim().replace(/\*\*/g, "");
543938
+ const match = cleaned.match(/-?\d[\d,]*(?:\.\d+)?/);
543939
+ if (!match)
543940
+ return cleaned;
543941
+ const n2 = Number(match[0].replace(/,/g, ""));
543942
+ return Number.isFinite(n2) ? n2 : cleaned;
543943
+ }
543944
+ function extractInlineMetrics(text) {
543945
+ const metrics2 = {};
543946
+ for (const line of text.split(/\n/)) {
543947
+ const bullet = line.match(/^\s*[-*]\s*(?:\*\*)?([^:*]+?)(?:\*\*)?:\s*(.+)$/);
543948
+ if (bullet)
543949
+ metrics2[bullet[1].trim()] = parseMetricValue2(bullet[2]);
543950
+ const bold = line.match(/^\s*(?:\*\*)?([^:*]+):(?:\*\*)?\s*(.+)$/);
543951
+ if (bold)
543952
+ metrics2[bold[1].trim()] = parseMetricValue2(bold[2]);
543953
+ }
543954
+ return metrics2;
543955
+ }
543956
+ var STOP, SemanticChunker, snapshotContextPressure, analyzeActiveForgetting, buildFeedbackIngestion;
543957
+ var init_semanticContext = __esm({
543958
+ "packages/memory/dist/semanticContext.js"() {
543959
+ "use strict";
543960
+ STOP = /* @__PURE__ */ new Set([
543961
+ "the",
543962
+ "and",
543963
+ "for",
543964
+ "with",
543965
+ "that",
543966
+ "this",
543967
+ "from",
543968
+ "into",
543969
+ "have",
543970
+ "has",
543971
+ "was",
543972
+ "were",
543973
+ "will",
543974
+ "should",
543975
+ "would",
543976
+ "could",
543977
+ "about",
543978
+ "because"
543979
+ ]);
543980
+ SemanticChunker = class {
543981
+ chunk(items, options2 = {}) {
543982
+ const maxChunks = Math.max(1, Math.floor(options2.maxChunks ?? 7));
543983
+ const now = options2.now ?? Date.now();
543984
+ const groups = [];
543985
+ for (const item of items.filter((i2) => i2.content.trim())) {
543986
+ const entities = [.../* @__PURE__ */ new Set([...item.entities ?? [], ...extractSemanticEntities(item.content)])];
543987
+ const label = semanticLabelFor(item);
543988
+ let target = groups.find((g) => g.label === label && (entityOverlap(g.entities, entities) >= 0.2 || g.items.length < 3));
543989
+ if (!target) {
543990
+ target = groups.find((g) => entityOverlap(g.entities, entities) >= 0.45);
543991
+ }
543992
+ if (!target) {
543993
+ target = { label, items: [], entities: [] };
543994
+ groups.push(target);
543995
+ }
543996
+ target.items.push({ ...item, entities });
543997
+ target.entities = [.../* @__PURE__ */ new Set([...target.entities, ...entities])].slice(0, 32);
543998
+ }
543999
+ while (groups.length > maxChunks) {
544000
+ groups.sort((a2, b) => groupUtility(a2.items, now) - groupUtility(b.items, now));
544001
+ const smallest = groups.shift();
544002
+ let bestIdx = 0;
544003
+ let bestScore = -1;
544004
+ for (let i2 = 0; i2 < groups.length; i2++) {
544005
+ const score = entityOverlap(smallest.entities, groups[i2].entities) + (smallest.label === groups[i2].label ? 1 : 0);
544006
+ if (score > bestScore) {
544007
+ bestScore = score;
544008
+ bestIdx = i2;
544009
+ }
544010
+ }
544011
+ groups[bestIdx].items.push(...smallest.items);
544012
+ groups[bestIdx].entities = [.../* @__PURE__ */ new Set([...groups[bestIdx].entities, ...smallest.entities])].slice(0, 32);
544013
+ }
544014
+ const maxSummaryChars = Math.max(180, Math.floor((options2.targetRawTokenBudget ?? 2e3) / maxChunks) * 4);
544015
+ return groups.map((g) => this.buildChunk(g.label, g.items, g.entities, now, maxSummaryChars)).sort((a2, b) => b.utilityScore - a2.utilityScore || a2.label.localeCompare(b.label));
544016
+ }
544017
+ buildChunk(label, items, entities, now, maxSummaryChars) {
544018
+ const rawTokenEstimate = items.reduce((sum, item) => sum + tokenCount(item), 0);
544019
+ const summary = summarize(items, maxSummaryChars);
544020
+ const tokenEstimate = Math.max(1, estimateTokens(summary));
544021
+ const utilityScore = groupUtility(items, now);
544022
+ const kinds = [...new Set(items.map((i2) => i2.kind))].sort();
544023
+ const sources = [...new Set(items.map((i2) => `${i2.source}:${i2.kind}`))].sort();
544024
+ return {
544025
+ id: `sem_${stableId([label, ...items.map((i2) => itemId(i2)).sort()])}`,
544026
+ label,
544027
+ summary,
544028
+ sourceIds: items.map((i2) => itemId(i2)),
544029
+ entities: entities.slice(0, 16),
544030
+ kinds,
544031
+ sourceKinds: sources,
544032
+ tokenEstimate,
544033
+ rawTokenEstimate,
544034
+ density: tokenEstimate > 0 ? rawTokenEstimate / tokenEstimate : 1,
544035
+ utilityScore,
544036
+ staleness: stalenessFor(items, now),
544037
+ openQuestions: openQuestionsFor(items),
544038
+ evidenceCount: items.length,
544039
+ items
544040
+ };
544041
+ }
544042
+ };
544043
+ snapshotContextPressure = buildContextPressureSnapshot;
544044
+ analyzeActiveForgetting = buildActiveForgettingReport;
544045
+ buildFeedbackIngestion = ingestContextFeedbackMarkdown;
544046
+ }
544047
+ });
544048
+
543575
544049
  // packages/memory/dist/index.js
543576
544050
  var dist_exports2 = {};
543577
544051
  __export(dist_exports2, {
@@ -543605,18 +544079,23 @@ __export(dist_exports2, {
543605
544079
  RepoProfileStore: () => RepoProfileStore,
543606
544080
  SYMBOL_MEANINGS: () => SYMBOL_MEANINGS,
543607
544081
  SelfModel: () => SelfModel,
544082
+ SemanticChunker: () => SemanticChunker,
543608
544083
  SocialMemoryStore: () => SocialMemoryStore,
543609
544084
  TaskMemoryStore: () => TaskMemoryStore,
543610
544085
  TemporalGraph: () => TemporalGraph,
543611
544086
  ToolOutcomeTracker: () => ToolOutcomeTracker,
543612
544087
  ToolPatternStore: () => ToolPatternStore,
543613
544088
  ValidationStore: () => ValidationStore,
544089
+ analyzeActiveForgetting: () => analyzeActiveForgetting,
543614
544090
  applyInfluence: () => applyInfluence,
543615
544091
  attachTrace: () => attachTrace,
543616
544092
  authorityBias: () => authorityBias,
543617
544093
  autoDecayClass: () => autoDecayClass,
543618
544094
  autoImportance: () => autoImportance,
543619
544095
  batchLink: () => batchLink,
544096
+ buildActiveForgettingReport: () => buildActiveForgettingReport,
544097
+ buildContextPressureSnapshot: () => buildContextPressureSnapshot,
544098
+ buildFeedbackIngestion: () => buildFeedbackIngestion,
543620
544099
  buildGist: () => buildGist,
543621
544100
  buildSelfTrustInfluence: () => buildSelfTrustInfluence,
543622
544101
  buildTrace: () => buildTrace,
@@ -543640,7 +544119,9 @@ __export(dist_exports2, {
543640
544119
  emptyDevelopmentalMetrics: () => emptyMetrics,
543641
544120
  engagementScore: () => engagementScore,
543642
544121
  episodeCount: () => episodeCount,
544122
+ estimateContextTokens: () => estimateContextTokens,
543643
544123
  extractQueryEntities: () => extractQueryEntities,
544124
+ extractSemanticEntities: () => extractSemanticEntities,
543644
544125
  extractTrace: () => extractTrace,
543645
544126
  findNeighbors: () => findNeighbors,
543646
544127
  fingerprintSignature: () => fingerprintSignature,
@@ -543651,6 +544132,7 @@ __export(dist_exports2, {
543651
544132
  goalHashOf: () => goalHashOf,
543652
544133
  importanceMultiplier: () => importanceMultiplier,
543653
544134
  inferDomainFromEpisode: () => inferDomainFromEpisode,
544135
+ ingestContextFeedbackMarkdown: () => ingestContextFeedbackMarkdown,
543654
544136
  initDb: () => initDb,
543655
544137
  isSessionGist: () => isSessionGist,
543656
544138
  lightSleep: () => lightSleep,
@@ -543672,7 +544154,9 @@ __export(dist_exports2, {
543672
544154
  selectAndWalkGraphCandidate: () => selectAndWalkGraphCandidate,
543673
544155
  selectInnerGraphCandidates: () => selectInnerGraphCandidates,
543674
544156
  selfTrustFor: () => selfTrustFor,
544157
+ shouldTriggerContextConsolidation: () => shouldTriggerContextConsolidation,
543675
544158
  slowWaveReplay: () => slowWaveReplay,
544159
+ snapshotContextPressure: () => snapshotContextPressure,
543676
544160
  splanifoldCosine: () => cosine,
543677
544161
  splanifoldDeserialize: () => deserialize,
543678
544162
  splanifoldEvaluate: () => evaluate2,
@@ -543724,6 +544208,7 @@ var init_dist7 = __esm({
543724
544208
  init_stagnationRecipes();
543725
544209
  init_codebaseMap();
543726
544210
  init_embeddingDrift();
544211
+ init_semanticContext();
543727
544212
  }
543728
544213
  });
543729
544214
 
@@ -546196,7 +546681,7 @@ var init_failureHandoff = __esm({
546196
546681
  });
546197
546682
 
546198
546683
  // packages/orchestrator/dist/context-fabric.js
546199
- function estimateTokens(text) {
546684
+ function estimateTokens2(text) {
546200
546685
  return Math.ceil(text.length / 4);
546201
546686
  }
546202
546687
  function normalizeSignalContent(content) {
@@ -546213,6 +546698,54 @@ function truncateText2(text, maxChars) {
546213
546698
  truncated: true
546214
546699
  };
546215
546700
  }
546701
+ function compactDiagnosticValue(value2, depth = 0) {
546702
+ if (value2 == null)
546703
+ return value2;
546704
+ if (typeof value2 === "string") {
546705
+ return value2.length > 240 ? `${value2.slice(0, 237)}...` : value2;
546706
+ }
546707
+ if (typeof value2 === "number" || typeof value2 === "boolean")
546708
+ return value2;
546709
+ if (Array.isArray(value2)) {
546710
+ if (depth >= 2)
546711
+ return `[array:${value2.length}]`;
546712
+ return value2.slice(0, 8).map((entry) => compactDiagnosticValue(entry, depth + 1));
546713
+ }
546714
+ if (typeof value2 === "object") {
546715
+ if (depth >= 2)
546716
+ return "[object]";
546717
+ const out = {};
546718
+ for (const [key, entry] of Object.entries(value2).slice(0, 12)) {
546719
+ if (/^(content|text|prompt|messages|transcript)$/i.test(key)) {
546720
+ out[key] = typeof entry === "string" ? `[omitted:${entry.length}]` : "[omitted]";
546721
+ } else {
546722
+ out[key] = compactDiagnosticValue(entry, depth + 1);
546723
+ }
546724
+ }
546725
+ return out;
546726
+ }
546727
+ return String(value2);
546728
+ }
546729
+ function collectMetadataReports(signals) {
546730
+ const pressureReports = [];
546731
+ const forgettingReports = [];
546732
+ for (const signal of signals) {
546733
+ const metadata = signal.metadata ?? {};
546734
+ for (const [key, value2] of Object.entries(metadata)) {
546735
+ if (value2 == null)
546736
+ continue;
546737
+ if (/pressure/i.test(key))
546738
+ pressureReports.push(compactDiagnosticValue(value2));
546739
+ if (/forgetting|retention|interference/i.test(key)) {
546740
+ forgettingReports.push(compactDiagnosticValue(value2));
546741
+ }
546742
+ }
546743
+ }
546744
+ return {
546745
+ pressureReports: pressureReports.length > 0 ? pressureReports : void 0,
546746
+ forgettingReports: forgettingReports.length > 0 ? forgettingReports : void 0
546747
+ };
546748
+ }
546216
546749
  function signalFromBlock(kind, source, content, options2 = {}) {
546217
546750
  const normalized = normalizeSignalContent(content ?? "");
546218
546751
  if (!normalized)
@@ -546243,6 +546776,7 @@ var init_context_fabric = __esm({
546243
546776
  "tool_cache",
546244
546777
  "skill_manifest",
546245
546778
  "memory",
546779
+ "semantic_chunk",
546246
546780
  "session_history",
546247
546781
  "anchor",
546248
546782
  "handoff",
@@ -546258,6 +546792,7 @@ var init_context_fabric = __esm({
546258
546792
  tool_cache: "Tool Cache",
546259
546793
  skill_manifest: "Skill Manifest",
546260
546794
  memory: "Memory",
546795
+ semantic_chunk: "Semantic Context",
546261
546796
  session_history: "Session History",
546262
546797
  anchor: "Relevant Anchors",
546263
546798
  handoff: "Handoff",
@@ -546273,6 +546808,7 @@ var init_context_fabric = __esm({
546273
546808
  tool_cache: 2200,
546274
546809
  skill_manifest: 900,
546275
546810
  memory: 1500,
546811
+ semantic_chunk: 2200,
546276
546812
  session_history: 1400,
546277
546813
  anchor: 1100,
546278
546814
  handoff: 1600,
@@ -546362,6 +546898,7 @@ var init_context_fabric = __esm({
546362
546898
  const dropped = [];
546363
546899
  const sectionLines = [];
546364
546900
  const sectionDiagnostics = [];
546901
+ const metadataReports = collectMetadataReports(sanitized);
546365
546902
  let truncatedSignals = 0;
546366
546903
  for (const kind of KIND_ORDER) {
546367
546904
  const bucket = byKind.get(kind);
@@ -546424,6 +546961,8 @@ var init_context_fabric = __esm({
546424
546961
  truncatedSignals: 0,
546425
546962
  estimatedTokens: 0,
546426
546963
  totalChars: 0,
546964
+ semanticChunkCount: 0,
546965
+ ...metadataReports,
546427
546966
  sections: []
546428
546967
  },
546429
546968
  included: [],
@@ -546443,7 +546982,7 @@ var init_context_fabric = __esm({
546443
546982
  if (options2.includeDiagnostics) {
546444
546983
  content += `
546445
546984
 
546446
- context_fabric: included=${included.length} dropped=${dropped.length} truncated=${truncatedSignals} est_tokens=${estimateTokens(content)}`;
546985
+ context_fabric: included=${included.length} dropped=${dropped.length} truncated=${truncatedSignals} est_tokens=${estimateTokens2(content)}`;
546447
546986
  }
546448
546987
  return {
546449
546988
  content,
@@ -546451,8 +546990,10 @@ context_fabric: included=${included.length} dropped=${dropped.length} truncated=
546451
546990
  includedSignals: included.length,
546452
546991
  droppedSignals: dropped.length,
546453
546992
  truncatedSignals,
546454
- estimatedTokens: estimateTokens(content),
546993
+ estimatedTokens: estimateTokens2(content),
546455
546994
  totalChars: content.length,
546995
+ semanticChunkCount: included.filter((signal) => signal.kind === "semantic_chunk").length,
546996
+ ...metadataReports,
546456
546997
  sections: sectionDiagnostics
546457
546998
  },
546458
546999
  included,
@@ -546474,7 +547015,7 @@ import { existsSync as existsSync81, readFileSync as readFileSync62, statSync as
546474
547015
  import { execSync as execSync46 } from "node:child_process";
546475
547016
  import { homedir as homedir29, platform as platform3, arch as arch2, totalmem as totalmem3, freemem as freemem3, hostname as hostname3 } from "node:os";
546476
547017
  import { join as join94 } from "node:path";
546477
- import { createHash as createHash20 } from "node:crypto";
547018
+ import { createHash as createHash21 } from "node:crypto";
546478
547019
  function capturePreflightSnapshot(workingDir) {
546479
547020
  const warnings = [];
546480
547021
  const configFingerprints = {};
@@ -546641,7 +547182,7 @@ function expandPath(p2) {
546641
547182
  return p2;
546642
547183
  }
546643
547184
  function sha2563(s2) {
546644
- return createHash20("sha256").update(s2).digest("hex").slice(0, 16);
547185
+ return createHash21("sha256").update(s2).digest("hex").slice(0, 16);
546645
547186
  }
546646
547187
  function freeDiskBytes(path12 = "/tmp") {
546647
547188
  try {
@@ -547517,6 +548058,115 @@ import { join as _pathJoin, resolve as _pathResolve } from "node:path";
547517
548058
  import { tmpdir as _osTmpdir } from "node:os";
547518
548059
  import { homedir as _osHomedir } from "node:os";
547519
548060
  import { z as z15 } from "zod";
548061
+ function textFromMessageContent(content) {
548062
+ if (typeof content === "string")
548063
+ return content;
548064
+ if (!Array.isArray(content))
548065
+ return "";
548066
+ return content.map((part) => part.type === "text" ? part.text ?? "" : "[image]").join("\n");
548067
+ }
548068
+ function normalizeContextSnippet(text, maxChars = 900) {
548069
+ const normalized = text.replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
548070
+ if (normalized.length <= maxChars)
548071
+ return normalized;
548072
+ return `${normalized.slice(0, maxChars - 18).trimEnd()}
548073
+ ... [bounded]`;
548074
+ }
548075
+ function estimateMessagesTokens(messages2) {
548076
+ let chars = 0;
548077
+ for (const message2 of messages2) {
548078
+ chars += textFromMessageContent(message2.content).length;
548079
+ if (message2.tool_calls) {
548080
+ for (const call of message2.tool_calls) {
548081
+ chars += call.function.arguments.length + call.function.name.length;
548082
+ }
548083
+ }
548084
+ }
548085
+ return Math.ceil(chars / 4);
548086
+ }
548087
+ function buildFallbackSemanticChunks(items, maxChunks = 7) {
548088
+ const normalized = items.map((item) => ({ ...item, content: normalizeContextSnippet(item.content, 900) })).filter((item) => item.content.length > 0);
548089
+ const bucketOrder = [
548090
+ { label: "Goal and Plan", kinds: ["goal", "task_state"] },
548091
+ { label: "Failure and Risk", kinds: ["recent_failure"] },
548092
+ { label: "Files and Anchors", kinds: ["known_files", "anchor"] },
548093
+ { label: "Knowledge and Memory", kinds: ["tool_cache", "memory"] },
548094
+ { label: "Recent Dialogue", kinds: ["recent_message", "session_history"] },
548095
+ { label: "Environment", kinds: ["environment"] }
548096
+ ];
548097
+ const chunks = [];
548098
+ for (const bucket of bucketOrder) {
548099
+ const bucketItems = normalized.filter((item) => bucket.kinds.includes(item.kind)).sort((a2, b) => (b.priority ?? 0) - (a2.priority ?? 0));
548100
+ if (bucketItems.length === 0)
548101
+ continue;
548102
+ const rawChars = bucketItems.reduce((sum, item) => sum + item.content.length, 0);
548103
+ const lines = bucketItems.slice(0, 5).map((item) => {
548104
+ const oneLine = item.content.replace(/\s+/g, " ").trim();
548105
+ return `- ${item.label}: ${oneLine.slice(0, 360)}`;
548106
+ });
548107
+ const content = normalizeContextSnippet(lines.join("\n"), 850);
548108
+ chunks.push({
548109
+ id: bucket.label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),
548110
+ label: bucket.label,
548111
+ content,
548112
+ sourceIds: bucketItems.map((item) => item.id).slice(0, 12),
548113
+ priority: Math.max(...bucketItems.map((item) => item.priority ?? 0)),
548114
+ metadata: {
548115
+ labels: bucketItems.map((item) => item.label).slice(0, 8),
548116
+ compression: {
548117
+ rawChars,
548118
+ chunkChars: content.length,
548119
+ ratio: rawChars > 0 ? Number((content.length / rawChars).toFixed(3)) : 1
548120
+ }
548121
+ }
548122
+ });
548123
+ if (chunks.length >= maxChunks)
548124
+ break;
548125
+ }
548126
+ if (chunks.length < maxChunks) {
548127
+ const used = new Set(chunks.flatMap((chunk) => chunk.sourceIds));
548128
+ const leftovers = normalized.filter((item) => !used.has(item.id));
548129
+ for (const item of leftovers.slice(0, maxChunks - chunks.length)) {
548130
+ chunks.push({
548131
+ id: item.id,
548132
+ label: item.label,
548133
+ content: normalizeContextSnippet(item.content, 650),
548134
+ sourceIds: [item.id],
548135
+ priority: item.priority ?? 0,
548136
+ metadata: {
548137
+ labels: [item.label],
548138
+ compression: {
548139
+ rawChars: item.content.length,
548140
+ chunkChars: item.content.length,
548141
+ ratio: 1
548142
+ }
548143
+ }
548144
+ });
548145
+ }
548146
+ }
548147
+ return chunks.slice(0, maxChunks);
548148
+ }
548149
+ function shouldRunDynamicContextConsolidation(input) {
548150
+ const reasons = [];
548151
+ const rawRatio = input.snapshot.rawRatio;
548152
+ if (input.snapshot.rawTokens > input.snapshot.targetTokens)
548153
+ reasons.push("raw_tokens_over_target");
548154
+ if (rawRatio >= 0.85)
548155
+ reasons.push("raw_ratio_high");
548156
+ const dropped = input.frameDiagnostics?.droppedSignals ?? input.snapshot.droppedSignals ?? 0;
548157
+ const truncated = input.frameDiagnostics?.truncatedSignals ?? input.snapshot.truncatedSignals ?? 0;
548158
+ if (dropped > 0 || truncated > 0)
548159
+ reasons.push("fabric_pressure");
548160
+ const retention = Number(input.forgettingReport?.["retentionScore"] ?? input.forgettingReport?.["retention"] ?? NaN);
548161
+ const interference = Number(input.forgettingReport?.["interferenceScore"] ?? input.forgettingReport?.["interference"] ?? NaN);
548162
+ if (Number.isFinite(retention) && retention < 0.45)
548163
+ reasons.push("low_retention");
548164
+ if (Number.isFinite(interference) && interference > 0.65)
548165
+ reasons.push("high_interference");
548166
+ if (input.memoryHelperDecision === true)
548167
+ reasons.push("memory_helper_trigger");
548168
+ return { shouldRun: reasons.length > 0, reasons: [...new Set(reasons)], rawRatio };
548169
+ }
547520
548170
  function repairJson(raw) {
547521
548171
  if (!raw || typeof raw !== "string")
547522
548172
  return null;
@@ -548254,6 +548904,10 @@ var init_agenticRunner = __esm({
548254
548904
  // ledger and emitted as one bounded frame before each model call.
548255
548905
  _contextLedger = new ContextLedger();
548256
548906
  _contextFrameBuilder = new ContextFrameBuilder();
548907
+ _lastContextFrameDiagnostics = null;
548908
+ _lastContextPressureSnapshot = null;
548909
+ _lastActiveForgettingReport = null;
548910
+ _lastContextConsolidationTurn = -1e3;
548257
548911
  /** WO-AM-10: Process pending episode embeddings in background batches */
548258
548912
  async processPendingEmbeddings() {
548259
548913
  if (this._pendingEmbeddings.length === 0 || !this._episodeStore)
@@ -550424,52 +551078,361 @@ ${latest.output || ""}`.trim();
550424
551078
  const insertAt = Math.max(0, messages2.length - 1);
550425
551079
  messages2.splice(insertAt, 0, { role: "system", content: frame });
550426
551080
  }
550427
- _buildTurnContextFrame(turn, messages2, recentToolResults, environmentBlock) {
551081
+ _activeContextItem(kind, id, source, label, content, priority = 0, metadata) {
551082
+ const normalized = normalizeContextSnippet(content ?? "", 1200);
551083
+ if (!normalized)
551084
+ return null;
551085
+ return { id, kind, source, label, content: normalized, priority, metadata };
551086
+ }
551087
+ _normalizeExternalContextItems(raw) {
551088
+ const arr = Array.isArray(raw) ? raw : [];
551089
+ return arr.map((entry, index) => {
551090
+ if (typeof entry === "string") {
551091
+ return this._activeContextItem("recent_message", `external-message-${index}`, "memory.contextItemsFromMessages", "Recent message", entry, 20);
551092
+ }
551093
+ if (!entry || typeof entry !== "object")
551094
+ return null;
551095
+ const obj = entry;
551096
+ const content = String(obj["content"] ?? obj["text"] ?? obj["summary"] ?? "");
551097
+ const kind = String(obj["kind"] ?? obj["type"] ?? "recent_message");
551098
+ return this._activeContextItem(kind, String(obj["id"] ?? `external-message-${index}`), String(obj["source"] ?? "memory.contextItemsFromMessages"), String(obj["label"] ?? obj["title"] ?? kind), content, typeof obj["priority"] === "number" ? obj["priority"] : 20, typeof obj["metadata"] === "object" && obj["metadata"] !== null ? obj["metadata"] : void 0);
551099
+ }).filter(Boolean);
551100
+ }
551101
+ async _collectActiveSemanticContextItems(input) {
551102
+ const items = [];
551103
+ const add2 = (item) => {
551104
+ if (item)
551105
+ items.push(item);
551106
+ };
551107
+ add2(this._activeContextItem("goal", "active-task", "run.goal", "Active task", input.goalBlock, 100));
551108
+ add2(this._activeContextItem("known_files", "filesystem-state", "turn.files", "Filesystem state", input.filesystemBlock, 70));
551109
+ add2(this._activeContextItem("task_state", "todo-state", "turn.todos", "Todo state", input.todoBlock, 80));
551110
+ add2(this._activeContextItem("recent_failure", "recent-failures", "turn.failures", "Recent failures", input.failureBlock, 95));
551111
+ add2(this._activeContextItem("recent_failure", "write-churn", "turn.churn", "Write churn", input.churnBlock, 75));
551112
+ add2(this._activeContextItem("tool_cache", "tool-cache", "turn.tool-cache", "Tool cache", input.toolCacheBlock, 65));
551113
+ add2(this._activeContextItem("anchor", "anchors", "turn.anchors", "Relevant anchors", input.anchorsBlock, 50));
551114
+ add2(this._activeContextItem("environment", "environment", "turn.environment", "Environment", input.environmentBlock, 35));
551115
+ if (this._lastPprMemoryLines.length > 0) {
551116
+ add2(this._activeContextItem("memory", "ppr-memory", "turn.ppr-memory", "Associative memory", this._lastPprMemoryLines.slice(0, 5).join("\n"), 60));
551117
+ }
551118
+ let helperItems = [];
551119
+ try {
551120
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
551121
+ if (typeof memMod.contextItemsFromMessages === "function") {
551122
+ helperItems = this._normalizeExternalContextItems(await memMod.contextItemsFromMessages(input.messages.slice(-12)));
551123
+ }
551124
+ } catch {
551125
+ helperItems = [];
551126
+ }
551127
+ if (helperItems.length > 0) {
551128
+ items.push(...helperItems.slice(0, 8));
551129
+ } else {
551130
+ const tail = input.messages.filter((message2) => message2.role !== "tool").slice(-8);
551131
+ tail.forEach((message2, index) => {
551132
+ const text = textFromMessageContent(message2.content);
551133
+ add2(this._activeContextItem("recent_message", `recent-message-${index}`, "turn.messages", `${message2.role} message`, text, message2.role === "user" ? 45 : 25));
551134
+ });
551135
+ }
551136
+ return items;
551137
+ }
551138
+ _normalizeSemanticChunks(raw) {
551139
+ const arr = Array.isArray(raw) ? raw : [];
551140
+ return arr.map((entry, index) => {
551141
+ if (typeof entry === "string") {
551142
+ const content2 = normalizeContextSnippet(entry, 850);
551143
+ if (!content2)
551144
+ return null;
551145
+ return {
551146
+ id: `semantic-${index}`,
551147
+ label: `Semantic chunk ${index + 1}`,
551148
+ content: content2,
551149
+ sourceIds: [],
551150
+ priority: 0,
551151
+ metadata: { labels: [`Semantic chunk ${index + 1}`] }
551152
+ };
551153
+ }
551154
+ if (!entry || typeof entry !== "object")
551155
+ return null;
551156
+ const obj = entry;
551157
+ const content = normalizeContextSnippet(String(obj["content"] ?? obj["text"] ?? obj["summary"] ?? ""), 850);
551158
+ if (!content)
551159
+ return null;
551160
+ const label = String(obj["label"] ?? obj["title"] ?? obj["topic"] ?? `Semantic chunk ${index + 1}`);
551161
+ const sourceIds = Array.isArray(obj["sourceIds"]) ? obj["sourceIds"].map(String) : Array.isArray(obj["sources"]) ? obj["sources"].map(String) : [];
551162
+ return {
551163
+ id: String(obj["id"] ?? (label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `semantic-${index}`)),
551164
+ label,
551165
+ content,
551166
+ sourceIds,
551167
+ priority: typeof obj["priority"] === "number" ? obj["priority"] : 0,
551168
+ metadata: typeof obj["metadata"] === "object" && obj["metadata"] !== null ? obj["metadata"] : { labels: [label] }
551169
+ };
551170
+ }).filter(Boolean);
551171
+ }
551172
+ async _buildPressureSnapshot(input) {
551173
+ let snapshot = {
551174
+ rawTokens: input.rawTokens,
551175
+ targetTokens: input.targetTokens,
551176
+ rawRatio: input.targetTokens > 0 ? Number((input.rawTokens / input.targetTokens).toFixed(3)) : 0,
551177
+ semanticChunkCount: input.semanticChunkCount
551178
+ };
551179
+ try {
551180
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
551181
+ if (typeof memMod.buildContextPressureSnapshot === "function") {
551182
+ const helperSnapshot = await memMod.buildContextPressureSnapshot({
551183
+ items: input.items,
551184
+ messages: input.messages,
551185
+ rawTokens: input.rawTokens,
551186
+ targetTokens: input.targetTokens
551187
+ });
551188
+ if (helperSnapshot && typeof helperSnapshot === "object") {
551189
+ snapshot = { ...snapshot, ...helperSnapshot };
551190
+ snapshot.rawTokens = Number(snapshot.rawTokens ?? input.rawTokens);
551191
+ snapshot.targetTokens = Number(snapshot.targetTokens ?? input.targetTokens);
551192
+ snapshot.rawRatio = Number(snapshot.rawRatio ?? (snapshot.targetTokens > 0 ? (snapshot.rawTokens / snapshot.targetTokens).toFixed(3) : 0));
551193
+ }
551194
+ }
551195
+ } catch {
551196
+ }
551197
+ return snapshot;
551198
+ }
551199
+ async _buildActiveForgettingReport(input) {
551200
+ try {
551201
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
551202
+ if (typeof memMod.buildActiveForgettingReport !== "function")
551203
+ return null;
551204
+ const report2 = await memMod.buildActiveForgettingReport(input);
551205
+ return report2 && typeof report2 === "object" ? report2 : null;
551206
+ } catch {
551207
+ return null;
551208
+ }
551209
+ }
551210
+ async _buildSemanticContextSignals(input) {
551211
+ let chunks = [];
551212
+ try {
551213
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
551214
+ const Chunker = memMod.SemanticChunker;
551215
+ if (typeof Chunker === "function") {
551216
+ const chunker = new Chunker({ maxChunks: 7 });
551217
+ const rawChunks = typeof chunker.chunk === "function" ? await chunker.chunk(input.items, { maxChunks: 7 }) : typeof chunker.buildChunks === "function" ? await chunker.buildChunks(input.items, { maxChunks: 7 }) : typeof chunker.run === "function" ? await chunker.run(input.items, { maxChunks: 7 }) : null;
551218
+ chunks = this._normalizeSemanticChunks(rawChunks);
551219
+ }
551220
+ } catch {
551221
+ chunks = [];
551222
+ }
551223
+ if (chunks.length === 0)
551224
+ chunks = buildFallbackSemanticChunks(input.items, 7);
551225
+ chunks = chunks.slice(0, 7);
551226
+ const snapshot = await this._buildPressureSnapshot({
551227
+ items: input.items,
551228
+ messages: input.messages,
551229
+ rawTokens: input.rawTokens,
551230
+ targetTokens: input.targetTokens,
551231
+ semanticChunkCount: chunks.length
551232
+ });
551233
+ const forgettingReport = await this._buildActiveForgettingReport({
551234
+ items: input.items,
551235
+ chunks,
551236
+ snapshot
551237
+ });
551238
+ this._lastContextPressureSnapshot = snapshot;
551239
+ this._lastActiveForgettingReport = forgettingReport;
551240
+ const signals = chunks.map((chunk, index) => signalFromBlock("semantic_chunk", "turn.semantic", `### ${chunk.label}
551241
+ ${chunk.content}`, {
551242
+ id: `semantic-${index}-${chunk.id}`,
551243
+ dedupeKey: `turn.semantic.${index}`,
551244
+ priority: 62 + Math.max(0, Math.min(20, chunk.priority ?? 0)),
551245
+ createdTurn: input.turn,
551246
+ ttlTurns: 1,
551247
+ tags: ["semantic_context"],
551248
+ metadata: {
551249
+ semanticLabels: chunk.metadata["labels"] ?? [chunk.label],
551250
+ compressionMetrics: chunk.metadata["compression"],
551251
+ sourceIds: chunk.sourceIds,
551252
+ ...index === 0 ? { pressureSnapshot: snapshot, activeForgettingReport: forgettingReport } : {}
551253
+ }
551254
+ })).filter(Boolean);
551255
+ return { signals, snapshot, forgettingReport };
551256
+ }
551257
+ async _memoryHelperWantsConsolidation(input) {
551258
+ try {
551259
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
551260
+ if (typeof memMod.shouldTriggerConsolidation !== "function")
551261
+ return null;
551262
+ return Boolean(await memMod.shouldTriggerConsolidation({
551263
+ pressure: input.snapshot,
551264
+ forgetting: input.forgettingReport,
551265
+ diagnostics: input.diagnostics
551266
+ }));
551267
+ } catch {
551268
+ return null;
551269
+ }
551270
+ }
551271
+ async _maybeRunDynamicContextConsolidation(input) {
551272
+ if (process.env["OMNIUS_DISABLE_DYNAMIC_CONTEXT_CONSOLIDATION"] === "1")
551273
+ return;
551274
+ if (!this._episodeStore)
551275
+ return;
551276
+ const debounceTurns = Math.max(4, Number(process.env["OMNIUS_CONTEXT_CONSOLIDATION_DEBOUNCE_TURNS"] ?? 10));
551277
+ if (input.turn - this._lastContextConsolidationTurn < debounceTurns)
551278
+ return;
551279
+ const helperDecision = await this._memoryHelperWantsConsolidation({
551280
+ snapshot: input.snapshot,
551281
+ forgettingReport: input.forgettingReport,
551282
+ diagnostics: input.diagnostics
551283
+ });
551284
+ const decision2 = shouldRunDynamicContextConsolidation({
551285
+ snapshot: input.snapshot,
551286
+ forgettingReport: input.forgettingReport,
551287
+ frameDiagnostics: input.diagnostics,
551288
+ memoryHelperDecision: helperDecision
551289
+ });
551290
+ if (!decision2.shouldRun)
551291
+ return;
551292
+ this._lastContextConsolidationTurn = input.turn;
551293
+ let cycleSummary = null;
551294
+ try {
551295
+ const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
551296
+ if (typeof memMod.runConsolidationCycle === "function" && typeof this._episodeStore.getDb === "function") {
551297
+ const cycle = memMod.runConsolidationCycle(this._episodeStore.getDb(), {
551298
+ slowWave: this._temporalGraph ? { graph: this._temporalGraph, maxReplay: 8 } : { maxReplay: 8 },
551299
+ rem: this._temporalGraph ? { graph: this._temporalGraph, maxAssociations: 4 } : { maxAssociations: 4 },
551300
+ light: { prunableClasses: ["session"], maxPrune: 8 }
551301
+ });
551302
+ cycleSummary = {
551303
+ slowWaveReplayed: cycle?.slowWave?.replayedEpisodes?.length ?? 0,
551304
+ lightPruned: cycle?.light?.prunedEpisodes?.length ?? 0,
551305
+ remAssociations: cycle?.rem?.novelAssociations?.length ?? 0,
551306
+ totalEnergy: cycle?.totalEnergy
551307
+ };
551308
+ }
551309
+ } catch {
551310
+ cycleSummary = { failed: true };
551311
+ }
551312
+ const semanticLabels = input.semanticSignals.flatMap((signal) => {
551313
+ const labels = signal.metadata?.["semanticLabels"];
551314
+ return Array.isArray(labels) ? labels.map(String) : [];
551315
+ }).slice(0, 20);
551316
+ const compressionMetrics = input.semanticSignals.map((signal) => signal.metadata?.["compressionMetrics"]).filter(Boolean).slice(0, 7);
551317
+ const content = [
551318
+ `Context pressure snapshot: ${decision2.reasons.join(", ")}.`,
551319
+ `raw=${input.snapshot.rawTokens}/${input.snapshot.targetTokens} tokens ratio=${decision2.rawRatio.toFixed(2)}; semantic_chunks=${input.diagnostics.semanticChunkCount}.`,
551320
+ input.diagnostics.droppedSignals || input.diagnostics.truncatedSignals ? `fabric dropped=${input.diagnostics.droppedSignals} truncated=${input.diagnostics.truncatedSignals}.` : null
551321
+ ].filter(Boolean).join(" ");
551322
+ try {
551323
+ this._episodeStore.insert({
551324
+ sessionId: this._sessionId,
551325
+ modality: "reflection",
551326
+ toolName: "context_pressure_snapshot",
551327
+ content: content.slice(0, 600),
551328
+ importance: 5,
551329
+ decayClass: "session",
551330
+ metadata: {
551331
+ pressure: input.snapshot,
551332
+ forgetting: input.forgettingReport,
551333
+ reasons: decision2.reasons,
551334
+ semanticLabels,
551335
+ compressionMetrics,
551336
+ frameDiagnostics: {
551337
+ includedSignals: input.diagnostics.includedSignals,
551338
+ droppedSignals: input.diagnostics.droppedSignals,
551339
+ truncatedSignals: input.diagnostics.truncatedSignals,
551340
+ estimatedTokens: input.diagnostics.estimatedTokens,
551341
+ semanticChunkCount: input.diagnostics.semanticChunkCount
551342
+ },
551343
+ consolidation: cycleSummary
551344
+ }
551345
+ });
551346
+ this.emit({
551347
+ type: "status",
551348
+ content: `Context consolidation: ${decision2.reasons.join(", ")} (semantic chunks=${input.diagnostics.semanticChunkCount})`,
551349
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
551350
+ });
551351
+ } catch {
551352
+ }
551353
+ }
551354
+ async _buildTurnContextFrame(turn, messages2, recentToolResults, environmentBlock) {
550428
551355
  this._contextLedger.clearSources("turn.");
550429
551356
  this._contextLedger.prune(turn);
551357
+ const goalBlock = this._taskState.goal ? `Active task: ${this._taskState.goal}` : null;
551358
+ const filesystemBlock = this._renderFilesystemStateBlock(turn);
551359
+ const todoBlock = this._renderTodoStateBlock(turn);
551360
+ const failureBlock = this._renderRecentFailuresBlock(turn);
551361
+ const churnBlock = this._renderWriteChurnBlock(turn);
551362
+ const toolCacheBlock = recentToolResults ? this._renderKnowledgeBlock(recentToolResults) : null;
551363
+ const anchorsBlock = this.surfaceAnchors(messages2);
551364
+ const pprMemoryBlock = this._lastPprMemoryLines.length > 0 ? `[Associative Memory - related prior experience]
551365
+ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
551366
+ const activeItems = await this._collectActiveSemanticContextItems({
551367
+ goalBlock,
551368
+ filesystemBlock,
551369
+ todoBlock,
551370
+ failureBlock,
551371
+ churnBlock,
551372
+ toolCacheBlock,
551373
+ anchorsBlock,
551374
+ environmentBlock: environmentBlock ?? null,
551375
+ messages: messages2
551376
+ });
551377
+ const targetTokens2 = this.contextLimits().compactionThreshold;
551378
+ const semantic = await this._buildSemanticContextSignals({
551379
+ turn,
551380
+ items: activeItems,
551381
+ messages: messages2,
551382
+ rawTokens: estimateMessagesTokens(messages2),
551383
+ targetTokens: targetTokens2
551384
+ });
550430
551385
  const signals = [
550431
- signalFromBlock("goal", "run.goal", this._taskState.goal ? `Active task: ${this._taskState.goal}` : null, {
551386
+ signalFromBlock("goal", "run.goal", goalBlock, {
550432
551387
  id: "active-task",
550433
551388
  dedupeKey: "run.goal",
550434
551389
  priority: 100,
550435
551390
  createdTurn: turn
550436
551391
  }),
550437
- signalFromBlock("known_files", "turn.files", this._renderFilesystemStateBlock(turn), {
551392
+ signalFromBlock("known_files", "turn.files", filesystemBlock, {
550438
551393
  id: "filesystem-state",
550439
551394
  dedupeKey: "turn.files",
550440
551395
  priority: 70,
550441
551396
  createdTurn: turn,
550442
551397
  ttlTurns: 1
550443
551398
  }),
550444
- signalFromBlock("task_state", "turn.todos", this._renderTodoStateBlock(turn), {
551399
+ signalFromBlock("task_state", "turn.todos", todoBlock, {
550445
551400
  id: "todo-state",
550446
551401
  dedupeKey: "turn.todos",
550447
551402
  priority: 80,
550448
551403
  createdTurn: turn,
550449
551404
  ttlTurns: 1
550450
551405
  }),
550451
- signalFromBlock("recent_failure", "turn.failures", this._renderRecentFailuresBlock(turn), {
551406
+ signalFromBlock("recent_failure", "turn.failures", failureBlock, {
550452
551407
  id: "recent-failures",
550453
551408
  dedupeKey: "turn.failures",
550454
551409
  priority: 95,
550455
551410
  createdTurn: turn,
550456
551411
  ttlTurns: 1
550457
551412
  }),
550458
- signalFromBlock("recent_failure", "turn.churn", this._renderWriteChurnBlock(turn), {
551413
+ signalFromBlock("recent_failure", "turn.churn", churnBlock, {
550459
551414
  id: "write-churn",
550460
551415
  dedupeKey: "turn.churn",
550461
551416
  priority: 75,
550462
551417
  createdTurn: turn,
550463
551418
  ttlTurns: 1
550464
551419
  }),
550465
- signalFromBlock("tool_cache", "turn.tool-cache", recentToolResults ? this._renderKnowledgeBlock(recentToolResults) : null, {
551420
+ signalFromBlock("tool_cache", "turn.tool-cache", toolCacheBlock, {
550466
551421
  id: "tool-cache",
550467
551422
  dedupeKey: "turn.tool-cache",
550468
551423
  priority: 65,
550469
551424
  createdTurn: turn,
550470
551425
  ttlTurns: 1
550471
551426
  }),
550472
- signalFromBlock("anchor", "turn.anchors", this.surfaceAnchors(messages2), {
551427
+ signalFromBlock("memory", "turn.ppr-memory", pprMemoryBlock, {
551428
+ id: "ppr-memory",
551429
+ dedupeKey: "turn.ppr-memory",
551430
+ priority: 60,
551431
+ createdTurn: turn,
551432
+ ttlTurns: 1
551433
+ }),
551434
+ ...semantic.signals,
551435
+ signalFromBlock("anchor", "turn.anchors", anchorsBlock, {
550473
551436
  id: "anchors",
550474
551437
  dedupeKey: "turn.anchors",
550475
551438
  priority: 50,
@@ -550490,6 +551453,18 @@ ${latest.output || ""}`.trim();
550490
551453
  maxChars: 1e4,
550491
551454
  includeDiagnostics: process.env["OMNIUS_CONTEXT_FABRIC_DIAGNOSTICS"] === "1"
550492
551455
  });
551456
+ this._lastContextFrameDiagnostics = frame.diagnostics;
551457
+ semantic.snapshot.frameTokens = frame.diagnostics.estimatedTokens;
551458
+ semantic.snapshot.droppedSignals = frame.diagnostics.droppedSignals;
551459
+ semantic.snapshot.truncatedSignals = frame.diagnostics.truncatedSignals;
551460
+ semantic.snapshot.semanticChunkCount = frame.diagnostics.semanticChunkCount;
551461
+ await this._maybeRunDynamicContextConsolidation({
551462
+ turn,
551463
+ snapshot: semantic.snapshot,
551464
+ forgettingReport: semantic.forgettingReport,
551465
+ diagnostics: frame.diagnostics,
551466
+ semanticSignals: semantic.signals
551467
+ });
550493
551468
  return frame.content;
550494
551469
  }
550495
551470
  makePhaseSummarizer() {
@@ -551331,7 +552306,14 @@ Respond with your assessment, then take action.`;
551331
552306
  this._contextTree = null;
551332
552307
  this._lastSurfacedAnchorIds.clear();
551333
552308
  this._contextLedger = new ContextLedger();
552309
+ this._lastContextFrameDiagnostics = null;
552310
+ this._lastContextPressureSnapshot = null;
552311
+ this._lastActiveForgettingReport = null;
552312
+ this._lastContextConsolidationTurn = -1e3;
551334
552313
  this._contextFrameBuilder = new ContextFrameBuilder();
552314
+ this._lastContextPressureSnapshot = null;
552315
+ this._lastActiveForgettingReport = null;
552316
+ this._lastContextConsolidationTurn = -1e3;
551335
552317
  if (!this.options.disablePersistentMemory && !this._memoryInitialized) {
551336
552318
  try {
551337
552319
  const path12 = await import("node:path");
@@ -553052,8 +554034,8 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
553052
554034
  if (process.env["OMNIUS_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
553053
554035
  const goalForSig = (this._taskState.goal || "").slice(0, 200);
553054
554036
  const recentTools = this._toolSequence.slice(-5).join("|");
553055
- const { createHash: createHash35 } = await import("node:crypto");
553056
- const sig = createHash35("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
554037
+ const { createHash: createHash36 } = await import("node:crypto");
554038
+ const sig = createHash36("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
553057
554039
  if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
553058
554040
  compacted.push({
553059
554041
  role: "system",
@@ -553151,7 +554133,7 @@ ${memoryLines.join("\n")}`
553151
554133
  this._lastAssistantTimestamp = Date.now();
553152
554134
  this.proactivePrune(compacted, turn);
553153
554135
  this.microcompact(compacted, recentToolResults);
553154
- this._insertContextFrame(compacted, this._buildTurnContextFrame(turn, compacted, recentToolResults, environmentBlock));
554136
+ this._insertContextFrame(compacted, await this._buildTurnContextFrame(turn, compacted, recentToolResults, environmentBlock));
553155
554137
  const { maxOutputTokens: effectiveMaxTokens } = this.contextLimits();
553156
554138
  const chatRequest = {
553157
554139
  messages: compacted,
@@ -555943,7 +556925,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
555943
556925
  } catch {
555944
556926
  }
555945
556927
  }
555946
- this._insertContextFrame(compactedMsgs, this._buildTurnContextFrame(turn, compactedMsgs, void 0, bfEnvironmentBlock));
556928
+ this._insertContextFrame(compactedMsgs, await this._buildTurnContextFrame(turn, compactedMsgs, void 0, bfEnvironmentBlock));
555947
556929
  const chatRequest = {
555948
556930
  messages: compactedMsgs,
555949
556931
  tools: toolDefs,
@@ -569051,7 +570033,7 @@ var require_websocket3 = __commonJS({
569051
570033
  var http6 = __require("http");
569052
570034
  var net5 = __require("net");
569053
570035
  var tls2 = __require("tls");
569054
- var { randomBytes: randomBytes29, createHash: createHash35 } = __require("crypto");
570036
+ var { randomBytes: randomBytes29, createHash: createHash36 } = __require("crypto");
569055
570037
  var { Duplex: Duplex3, Readable } = __require("stream");
569056
570038
  var { URL: URL3 } = __require("url");
569057
570039
  var PerMessageDeflate3 = require_permessage_deflate3();
@@ -569711,7 +570693,7 @@ var require_websocket3 = __commonJS({
569711
570693
  abortHandshake(websocket, socket, "Invalid Upgrade header");
569712
570694
  return;
569713
570695
  }
569714
- const digest3 = createHash35("sha1").update(key + GUID).digest("base64");
570696
+ const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
569715
570697
  if (res.headers["sec-websocket-accept"] !== digest3) {
569716
570698
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
569717
570699
  return;
@@ -570078,7 +571060,7 @@ var require_websocket_server2 = __commonJS({
570078
571060
  var EventEmitter15 = __require("events");
570079
571061
  var http6 = __require("http");
570080
571062
  var { Duplex: Duplex3 } = __require("stream");
570081
- var { createHash: createHash35 } = __require("crypto");
571063
+ var { createHash: createHash36 } = __require("crypto");
570082
571064
  var extension3 = require_extension3();
570083
571065
  var PerMessageDeflate3 = require_permessage_deflate3();
570084
571066
  var subprotocol3 = require_subprotocol2();
@@ -570379,7 +571361,7 @@ var require_websocket_server2 = __commonJS({
570379
571361
  );
570380
571362
  }
570381
571363
  if (this._state > RUNNING) return abortHandshake(socket, 503);
570382
- const digest3 = createHash35("sha1").update(key + GUID).digest("base64");
571364
+ const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
570383
571365
  const headers = [
570384
571366
  "HTTP/1.1 101 Switching Protocols",
570385
571367
  "Upgrade: websocket",
@@ -575228,14 +576210,14 @@ var init_voice_session = __esm({
575228
576210
  });
575229
576211
 
575230
576212
  // packages/cli/src/tui/scoped-personality.ts
575231
- import { createHash as createHash21 } from "node:crypto";
576213
+ import { createHash as createHash22 } from "node:crypto";
575232
576214
  import { appendFileSync as appendFileSync5, existsSync as existsSync89, mkdirSync as mkdirSync49, readFileSync as readFileSync69, writeFileSync as writeFileSync44 } from "node:fs";
575233
576215
  import { join as join104, resolve as resolve39 } from "node:path";
575234
576216
  function safeName(input) {
575235
576217
  return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
575236
576218
  }
575237
576219
  function scopeHash(scope) {
575238
- return createHash21("sha1").update(`${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
576220
+ return createHash22("sha1").update(`${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
575239
576221
  }
575240
576222
  function scopedPersonalityDir(repoRoot, kind) {
575241
576223
  return resolve39(repoRoot, ".omnius", "scoped-personality", kind);
@@ -575607,7 +576589,7 @@ var init_scoped_personality = __esm({
575607
576589
  });
575608
576590
 
575609
576591
  // packages/cli/src/tui/voice-soul.ts
575610
- import { createHash as createHash22 } from "node:crypto";
576592
+ import { createHash as createHash23 } from "node:crypto";
575611
576593
  import { existsSync as existsSync90, readdirSync as readdirSync29, readFileSync as readFileSync70 } from "node:fs";
575612
576594
  import { basename as basename20, join as join105, resolve as resolve40 } from "node:path";
575613
576595
  function compactText(text, limit) {
@@ -575622,7 +576604,7 @@ function blockText(text, limit) {
575622
576604
  ... [truncated]`;
575623
576605
  }
575624
576606
  function scopeStateKey(scope, surface) {
575625
- return createHash22("sha1").update(`${surface}:${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
576607
+ return createHash23("sha1").update(`${surface}:${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
575626
576608
  }
575627
576609
  function safeName2(input) {
575628
576610
  return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
@@ -578225,7 +579207,7 @@ var init_types = __esm({
578225
579207
  });
578226
579208
 
578227
579209
  // packages/cli/src/tui/p2p/secret-vault.ts
578228
- import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes21, scryptSync as scryptSync2, createHash as createHash23 } from "node:crypto";
579210
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes21, scryptSync as scryptSync2, createHash as createHash24 } from "node:crypto";
578229
579211
  import { readFileSync as readFileSync72, writeFileSync as writeFileSync46, existsSync as existsSync92, mkdirSync as mkdirSync51 } from "node:fs";
578230
579212
  import { dirname as dirname28 } from "node:path";
578231
579213
  var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
@@ -578470,7 +579452,7 @@ var init_secret_vault = __esm({
578470
579452
  /** Generate a deterministic fingerprint of vault contents (for sync verification) */
578471
579453
  fingerprint() {
578472
579454
  const names = Array.from(this.secrets.keys()).sort();
578473
- const hash = createHash23("sha256");
579455
+ const hash = createHash24("sha256");
578474
579456
  for (const name10 of names) {
578475
579457
  hash.update(name10 + ":");
578476
579458
  hash.update(this.secrets.get(name10).value);
@@ -578485,7 +579467,7 @@ var init_secret_vault = __esm({
578485
579467
  // packages/cli/src/tui/p2p/peer-mesh.ts
578486
579468
  import { EventEmitter as EventEmitter9 } from "node:events";
578487
579469
  import { createServer as createServer6 } from "node:http";
578488
- import { randomBytes as randomBytes22, createHash as createHash24, generateKeyPairSync } from "node:crypto";
579470
+ import { randomBytes as randomBytes22, createHash as createHash25, generateKeyPairSync } from "node:crypto";
578489
579471
  var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
578490
579472
  var init_peer_mesh = __esm({
578491
579473
  "packages/cli/src/tui/p2p/peer-mesh.ts"() {
@@ -578502,7 +579484,7 @@ var init_peer_mesh = __esm({
578502
579484
  const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
578503
579485
  this.publicKey = publicKey2.export({ type: "spki", format: "der" });
578504
579486
  this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
578505
- this.peerId = createHash24("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
579487
+ this.peerId = createHash25("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
578506
579488
  this.capabilities = options2.capabilities;
578507
579489
  this.displayName = options2.displayName;
578508
579490
  this._authKey = options2.authKey ?? randomBytes22(24).toString("base64url");
@@ -579840,7 +580822,7 @@ __export(omnius_directory_exports, {
579840
580822
  import { appendFileSync as appendFileSync6, cpSync as cpSync2, existsSync as existsSync95, mkdirSync as mkdirSync53, readFileSync as readFileSync75, writeFileSync as writeFileSync48, readdirSync as readdirSync31, statSync as statSync36, unlinkSync as unlinkSync17, openSync as openSync2, closeSync as closeSync2, renameSync as renameSync4, watch as fsWatch2 } from "node:fs";
579841
580823
  import { join as join111, relative as relative9, basename as basename21, dirname as dirname31, resolve as resolve41 } from "node:path";
579842
580824
  import { homedir as homedir34 } from "node:os";
579843
- import { createHash as createHash25 } from "node:crypto";
580825
+ import { createHash as createHash26 } from "node:crypto";
579844
580826
  function isGitRoot(dir) {
579845
580827
  const gitPath = join111(dir, ".git");
579846
580828
  if (!existsSync95(gitPath)) return false;
@@ -580294,7 +581276,7 @@ function buildHandoffPrompt(repoRoot) {
580294
581276
  return lines.join("\n");
580295
581277
  }
580296
581278
  function computeDedupeHash(task, savedAt) {
580297
- return createHash25("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
581279
+ return createHash26("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
580298
581280
  }
580299
581281
  function generateSessionId() {
580300
581282
  const timestamp = Date.now().toString(36);
@@ -600476,7 +601458,7 @@ __export(commands_exports, {
600476
601458
  });
600477
601459
  import * as nodeOs from "node:os";
600478
601460
  import { execSync as nodeExecSync } from "node:child_process";
600479
- import { createHash as createHash26 } from "node:crypto";
601461
+ import { createHash as createHash27 } from "node:crypto";
600480
601462
  import {
600481
601463
  existsSync as existsSync108,
600482
601464
  readFileSync as readFileSync86,
@@ -610952,7 +611934,7 @@ async function collectSponsorMediaStream(args) {
610952
611934
  return { ok: false, error: `Artifact size mismatch for ${artifactId}: ${bytes.length}/${artifact.sizeBytes}` };
610953
611935
  }
610954
611936
  if (artifact.sha256) {
610955
- const sha = createHash26("sha256").update(bytes).digest("hex");
611937
+ const sha = createHash27("sha256").update(bytes).digest("hex");
610956
611938
  if (sha !== artifact.sha256) return { ok: false, error: `Artifact hash mismatch for ${artifactId}` };
610957
611939
  }
610958
611940
  const safeName3 = basename23(artifact.filename).replace(/[^\w.-]/g, "_") || `artifact${defaultExtensionForMime(artifact.mime)}`;
@@ -614933,7 +615915,7 @@ function normalizePersonName(name10) {
614933
615915
  function personKey(name10) {
614934
615916
  return `person:${normalizePersonName(name10)}`;
614935
615917
  }
614936
- function clamp016(value2, fallback = 0) {
615918
+ function clamp017(value2, fallback = 0) {
614937
615919
  if (typeof value2 !== "number" || !Number.isFinite(value2)) return fallback;
614938
615920
  return Math.max(0, Math.min(1, value2));
614939
615921
  }
@@ -614950,7 +615932,7 @@ function parseStructuredIdentifyResult(result) {
614950
615932
  const matches = faces.filter((face) => face["identified"] === true && typeof face["name"] === "string" && String(face["name"]).trim()).map((face) => ({
614951
615933
  name: String(face["name"]).trim(),
614952
615934
  personId: typeof face["person_id"] === "string" ? face["person_id"] : void 0,
614953
- confidence: clamp016(face["confidence"], 0),
615935
+ confidence: clamp017(face["confidence"], 0),
614954
615936
  margin: typeof face["margin"] === "number" ? face["margin"] : void 0,
614955
615937
  bbox: Array.isArray(face["bbox"]) ? face["bbox"].map((n2) => Number(n2)).filter(Number.isFinite) : void 0
614956
615938
  }));
@@ -615033,7 +616015,7 @@ function activePendingVisualIdentities(store2, scope, sessionId, limit = 3) {
615033
616015
  pendingId,
615034
616016
  name: name10,
615035
616017
  relation: String(meta["relation"] || "depicts"),
615036
- confidence: clamp016(meta["confidence"], 0.92),
616018
+ confidence: clamp017(meta["confidence"], 0.92),
615037
616019
  note: typeof meta["note"] === "string" ? meta["note"] : void 0,
615038
616020
  episodeId: ep.id,
615039
616021
  createdAt: ep.timestamp,
@@ -615143,7 +616125,7 @@ function stageVisualIdentityAssertion(options2) {
615143
616125
  target: "next_visual_media",
615144
616126
  name: name10,
615145
616127
  relation: options2.relation || "depicts",
615146
- confidence: clamp016(options2.confidence, 0.92),
616128
+ confidence: clamp017(options2.confidence, 0.92),
615147
616129
  note: options2.note,
615148
616130
  createdAt: Date.now(),
615149
616131
  expiresAt
@@ -615152,7 +616134,7 @@ function stageVisualIdentityAssertion(options2) {
615152
616134
  identityAssertions: [{
615153
616135
  name: name10,
615154
616136
  relation: options2.relation || "named_as",
615155
- confidence: clamp016(options2.confidence, 0.92),
616137
+ confidence: clamp017(options2.confidence, 0.92),
615156
616138
  assertedBy: options2.sender,
615157
616139
  note: options2.note || "Explicit user-provided identity staged for the next visual media."
615158
616140
  }]
@@ -622977,7 +623959,7 @@ ${result.output}`,
622977
623959
  });
622978
623960
 
622979
623961
  // packages/cli/src/tui/stimulation.ts
622980
- function clamp017(value2) {
623962
+ function clamp018(value2) {
622981
623963
  return Math.max(0, Math.min(1, value2));
622982
623964
  }
622983
623965
  function cloneState(state) {
@@ -623033,7 +624015,7 @@ var init_stimulation = __esm({
623033
624015
  ...DEFAULT_STATE,
623034
624016
  ...state,
623035
624017
  phase: normalizePhase(state.phase) ?? DEFAULT_STATE.phase,
623036
- attention: clamp017(Number.isFinite(state.attention) ? Number(state.attention) : DEFAULT_STATE.attention),
624018
+ attention: clamp018(Number.isFinite(state.attention) ? Number(state.attention) : DEFAULT_STATE.attention),
623037
624019
  updatedAtMs: Number.isFinite(state.updatedAtMs) ? Number(state.updatedAtMs) : now,
623038
624020
  lastStimulusAtMs: Number.isFinite(state.lastStimulusAtMs) ? Number(state.lastStimulusAtMs) : now,
623039
624021
  messagesSinceAnalysis: Math.max(0, Math.floor(Number(state.messagesSinceAnalysis ?? 0))),
@@ -623074,11 +624056,11 @@ var init_stimulation = __esm({
623074
624056
  applyAgentDecision(channelId, decision2, nowMs = Date.now()) {
623075
624057
  const state = this.stateFor(channelId, nowMs);
623076
624058
  if (Number.isFinite(decision2.attentionScore)) {
623077
- state.attention = clamp017(Number(decision2.attentionScore));
624059
+ state.attention = clamp018(Number(decision2.attentionScore));
623078
624060
  } else if (Number.isFinite(decision2.attentionDelta)) {
623079
- state.attention = clamp017(state.attention + Number(decision2.attentionDelta));
624061
+ state.attention = clamp018(state.attention + Number(decision2.attentionDelta));
623080
624062
  } else {
623081
- state.attention = clamp017(state.attention + (decision2.shouldReply ? 0.22 : -0.1));
624063
+ state.attention = clamp018(state.attention + (decision2.shouldReply ? 0.22 : -0.1));
623082
624064
  }
623083
624065
  if (decision2.phase) {
623084
624066
  state.attention = Math.max(state.attention, PHASE_FLOORS[decision2.phase]);
@@ -623134,7 +624116,7 @@ var init_stimulation = __esm({
623134
624116
  });
623135
624117
 
623136
624118
  // packages/cli/src/tui/pid-controller.ts
623137
- function clamp018(x) {
624119
+ function clamp019(x) {
623138
624120
  if (!Number.isFinite(x)) return 0;
623139
624121
  if (x < 0) return 0;
623140
624122
  if (x > 1) return 1;
@@ -623198,7 +624180,7 @@ var init_pid_controller = __esm({
623198
624180
  const dt = st.lastSampleAt > 0 ? now - st.lastSampleAt : 1e3;
623199
624181
  const derivative = dt > 0 ? (error - st.lastError) / dt : 0;
623200
624182
  const u = st.config.kp * error + st.config.ki * st.integral + st.config.kd * derivative;
623201
- st.output = clamp018(st.output + u);
624183
+ st.output = clamp019(st.output + u);
623202
624184
  st.lastError = error;
623203
624185
  st.lastSampleAt = now;
623204
624186
  st.samples += 1;
@@ -623430,7 +624412,7 @@ var init_soul_observations = __esm({
623430
624412
  // packages/cli/src/tui/telegram-channel-dmn.ts
623431
624413
  import { existsSync as existsSync119, mkdirSync as mkdirSync68, readdirSync as readdirSync42, readFileSync as readFileSync96, writeFileSync as writeFileSync61 } from "node:fs";
623432
624414
  import { join as join133 } from "node:path";
623433
- import { createHash as createHash27 } from "node:crypto";
624415
+ import { createHash as createHash28 } from "node:crypto";
623434
624416
  function safeFilePart(value2) {
623435
624417
  return value2.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 80) || "telegram";
623436
624418
  }
@@ -623438,7 +624420,7 @@ function daydreamRoot(repoRoot) {
623438
624420
  return join133(repoRoot, ".omnius", "telegram-daydreams");
623439
624421
  }
623440
624422
  function sessionDir(repoRoot, sessionKey) {
623441
- const hash = createHash27("sha1").update(sessionKey).digest("hex").slice(0, 20);
624423
+ const hash = createHash28("sha1").update(sessionKey).digest("hex").slice(0, 20);
623442
624424
  return join133(daydreamRoot(repoRoot), safeFilePart(hash));
623443
624425
  }
623444
624426
  function compactLine2(value2, max = 220) {
@@ -623523,9 +624505,9 @@ function buildReplyOpportunities(input, openQuestions) {
623523
624505
  return opportunities;
623524
624506
  }
623525
624507
  function daydreamOpportunityId(input, trigger) {
623526
- return createHash27("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
624508
+ return createHash28("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
623527
624509
  }
623528
- function clamp019(value2) {
624510
+ function clamp0110(value2) {
623529
624511
  if (!Number.isFinite(value2)) return 0;
623530
624512
  return Math.max(0, Math.min(1, value2));
623531
624513
  }
@@ -623536,7 +624518,7 @@ function pushStimulationSignal(signals, signal, source, weight) {
623536
624518
  const cleanSignal = compactLine2(signal, 120);
623537
624519
  const cleanSource = compactLine2(source, 180);
623538
624520
  if (!cleanSignal || signals.some((entry) => entry.signal === cleanSignal && entry.source === cleanSource)) return;
623539
- signals.push({ signal: cleanSignal, source: cleanSource, weight: clamp019(weight) });
624521
+ signals.push({ signal: cleanSignal, source: cleanSource, weight: clamp0110(weight) });
623540
624522
  }
623541
624523
  function buildMetaAnalysisSignals(input) {
623542
624524
  const chatLabel = input.chatTitle || input.chatId;
@@ -623611,7 +624593,7 @@ function buildCuriosityThreads(input, openQuestions, stimulationSignals) {
623611
624593
  question: text.endsWith("?") || text.endsWith("?") ? text : `What should be learned or clarified from: ${text || entry.mediaSummary || "recent media"}?`,
623612
624594
  rationale: "Human curiosity, uncertainty, or multimodal content makes this a useful idle exploration target.",
623613
624595
  sourceMessages: messageId,
623614
- intensity: clamp019(0.5 + replyBoost + mediaBoost + questionBoost)
624596
+ intensity: clamp0110(0.5 + replyBoost + mediaBoost + questionBoost)
623615
624597
  });
623616
624598
  }
623617
624599
  for (const question of openQuestions.slice(-4)) {
@@ -623631,7 +624613,7 @@ function buildCuriosityThreads(input, openQuestions, stimulationSignals) {
623631
624613
  question: `Is there a useful clarification or memory consolidation around ${strongest.source}?`,
623632
624614
  rationale: "Strongest stimulation signal can seed a low-intrusion reflection target.",
623633
624615
  sourceMessages: [],
623634
- intensity: clamp019(strongest.weight * 0.72)
624616
+ intensity: clamp0110(strongest.weight * 0.72)
623635
624617
  });
623636
624618
  }
623637
624619
  return threads.sort((a2, b) => b.intensity - a2.intensity).slice(0, 8);
@@ -623705,7 +624687,7 @@ function buildOutreachPlans(input, curiosityThreads) {
623705
624687
  purpose: "Continue the public thread only when the live model judges that the group would benefit from a concise follow-up.",
623706
624688
  draftIntent: "Ask one concrete clarification, offer one useful synthesis, or stay silent if the room has moved on.",
623707
624689
  gate: "model_decision",
623708
- confidence: clamp019(thread.intensity * 0.86)
624690
+ confidence: clamp0110(thread.intensity * 0.86)
623709
624691
  });
623710
624692
  const participant = participantForThread(input, thread);
623711
624693
  if (!participant) continue;
@@ -623717,7 +624699,7 @@ function buildOutreachPlans(input, curiosityThreads) {
623717
624699
  purpose: "Offer a one-to-one follow-up only if private contact is allowed and the issue is personal, unresolved, or better handled outside the group.",
623718
624700
  draftIntent: "Reference the public thread briefly, ask permission to continue privately, and do not reveal hidden meta-analysis.",
623719
624701
  gate: "admin_review",
623720
- confidence: clamp019(thread.intensity * 0.58)
624702
+ confidence: clamp0110(thread.intensity * 0.58)
623721
624703
  });
623722
624704
  }
623723
624705
  return plans.slice(0, 8);
@@ -623843,7 +624825,7 @@ function buildTelegramChannelDaydream(input, corpus, extraction, extractionCommi
623843
624825
  const seed = `${input.sessionKey}:${input.generatedAtMs}:${input.history.length}`;
623844
624826
  return {
623845
624827
  version: 3,
623846
- id: createHash27("sha1").update(seed).digest("hex").slice(0, 16),
624828
+ id: createHash28("sha1").update(seed).digest("hex").slice(0, 16),
623847
624829
  sessionKey: input.sessionKey,
623848
624830
  chatId: input.chatId,
623849
624831
  chatTitle: input.chatTitle,
@@ -624056,12 +625038,12 @@ var init_telegram_channel_dmn = __esm({
624056
625038
  });
624057
625039
 
624058
625040
  // packages/cli/src/tui/telegram-reflection-corpus.ts
624059
- import { createHash as createHash28 } from "node:crypto";
625041
+ import { createHash as createHash29 } from "node:crypto";
624060
625042
  function telegramReflectionMemoryDbPaths(repoRoot) {
624061
625043
  return omniusMemoryDbPaths(repoRoot);
624062
625044
  }
624063
625045
  function stableHash2(value2, length4 = 16) {
624064
- return createHash28("sha1").update(value2).digest("hex").slice(0, length4);
625046
+ return createHash29("sha1").update(value2).digest("hex").slice(0, length4);
624065
625047
  }
624066
625048
  function clean3(value2) {
624067
625049
  return String(value2 ?? "").replace(/\s+/g, " ").trim();
@@ -624791,7 +625773,7 @@ var init_telegram_reflection_extraction = __esm({
624791
625773
  });
624792
625774
 
624793
625775
  // packages/cli/src/tui/telegram-social-state-types.ts
624794
- import { createHash as createHash29 } from "node:crypto";
625776
+ import { createHash as createHash30 } from "node:crypto";
624795
625777
  function telegramSocialActorKey(actor) {
624796
625778
  if (!actor) return "unknown";
624797
625779
  if (typeof actor.userId === "number") return `user:${actor.userId}`;
@@ -624824,7 +625806,7 @@ function appendUnique(items, value2, max) {
624824
625806
  return next.slice(-max);
624825
625807
  }
624826
625808
  function hashTelegramSocialId(parts) {
624827
- return createHash29("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
625809
+ return createHash30("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
624828
625810
  }
624829
625811
  function cleanUsername(value2) {
624830
625812
  if (typeof value2 !== "string") return void 0;
@@ -624849,7 +625831,7 @@ function numberOr(value2, fallback) {
624849
625831
  function isNumber(value2) {
624850
625832
  return typeof value2 === "number" && Number.isFinite(value2);
624851
625833
  }
624852
- function clamp0110(value2) {
625834
+ function clamp0111(value2) {
624853
625835
  return Math.max(0, Math.min(1, Number.isFinite(value2) ? value2 : 0));
624854
625836
  }
624855
625837
  function iso(ts) {
@@ -625033,8 +626015,8 @@ function normalizeRelationship(raw) {
625033
626015
  kind: value2.kind,
625034
626016
  fromKey: String(value2.fromKey),
625035
626017
  toKey: String(value2.toKey),
625036
- confidence: clamp0110(numberOr(value2.confidence, 0)),
625037
- weight: clamp0110(numberOr(value2.weight, 0)),
626018
+ confidence: clamp0111(numberOr(value2.confidence, 0)),
626019
+ weight: clamp0111(numberOr(value2.weight, 0)),
625038
626020
  firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
625039
626021
  lastSeenAt: numberOr(value2.lastSeenAt, Date.now()),
625040
626022
  evidenceMessageIds: Array.isArray(value2.evidenceMessageIds) ? value2.evidenceMessageIds.filter(isNumber).slice(-40) : [],
@@ -625053,7 +626035,7 @@ function normalizePreferences(raw) {
625053
626035
  if (!evidence || typeof evidence !== "object") continue;
625054
626036
  out[actorKey][key] = {
625055
626037
  value: Math.max(-1, Math.min(1, numberOr(evidence.value, 0))),
625056
- confidence: clamp0110(numberOr(evidence.confidence, 0)),
626038
+ confidence: clamp0111(numberOr(evidence.confidence, 0)),
625057
626039
  updatedAt: numberOr(evidence.updatedAt, Date.now()),
625058
626040
  evidenceMessageIds: Array.isArray(evidence.evidenceMessageIds) ? evidence.evidenceMessageIds.filter(isNumber).slice(-12) : [],
625059
626041
  note: compactOptional(evidence.note, 220)
@@ -625067,7 +626049,7 @@ function normalizePreferences(raw) {
625067
626049
  out[actorKey].replyMode = {
625068
626050
  mode,
625069
626051
  scope: normalizeReplyPreferenceScope(record["scope"]),
625070
- confidence: clamp0110(numberOr(record["confidence"], 0.8)),
626052
+ confidence: clamp0111(numberOr(record["confidence"], 0.8)),
625071
626053
  updatedAt: numberOr(record["updatedAt"], Date.now()),
625072
626054
  evidenceMessageIds: Array.isArray(record["evidenceMessageIds"]) ? record["evidenceMessageIds"].filter(isNumber).slice(-12) : [],
625073
626055
  note: compactOptional(record["note"], 220),
@@ -625157,7 +626139,7 @@ function normalizeOutcome(raw) {
625157
626139
  replyToMessageId: typeof value2.replyToMessageId === "number" ? value2.replyToMessageId : void 0,
625158
626140
  route: value2.route === "action" ? "action" : "chat",
625159
626141
  shouldReply: value2.shouldReply === true,
625160
- confidence: clamp0110(numberOr(value2.confidence, 0)),
626142
+ confidence: clamp0111(numberOr(value2.confidence, 0)),
625161
626143
  reason: compact2(value2.reason || "", 280),
625162
626144
  source: compact2(value2.source || "unknown", 80),
625163
626145
  silentDisposition: compactOptional(value2.silentDisposition, 280),
@@ -625169,7 +626151,7 @@ function normalizeOutcome(raw) {
625169
626151
  scenarioNote: compactOptional(value2.scenarioNote, 360),
625170
626152
  scenarioId: compactOptional(value2.scenarioId, 160),
625171
626153
  scenarioLabel: compactOptional(value2.scenarioLabel, 160),
625172
- scenarioConfidence: typeof value2.scenarioConfidence === "number" && Number.isFinite(value2.scenarioConfidence) ? clamp0110(value2.scenarioConfidence) : void 0,
626154
+ scenarioConfidence: typeof value2.scenarioConfidence === "number" && Number.isFinite(value2.scenarioConfidence) ? clamp0111(value2.scenarioConfidence) : void 0,
625173
626155
  scenarioObjective: compactOptional(value2.scenarioObjective, 360),
625174
626156
  scenarioStateLoop: compactOptional(value2.scenarioStateLoop, 360),
625175
626157
  salienceSignals: Array.isArray(value2.salienceSignals) ? value2.salienceSignals.map(String).slice(0, 16) : [],
@@ -625187,7 +626169,7 @@ function normalizeDaydreamOpportunity(raw) {
625187
626169
  artifactId: String(value2.artifactId || "unknown"),
625188
626170
  generatedAt: String(value2.generatedAt || (/* @__PURE__ */ new Date()).toISOString()),
625189
626171
  trigger: compact2(value2.trigger || "", 240),
625190
- confidence: clamp0110(numberOr(value2.confidence, 0)),
626172
+ confidence: clamp0111(numberOr(value2.confidence, 0)),
625191
626173
  lifecycle,
625192
626174
  firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
625193
626175
  updatedAt: numberOr(value2.updatedAt, Date.now()),
@@ -625244,7 +626226,7 @@ function commitTelegramSocialDecision(state, input) {
625244
626226
  replyToMessageId: input.replyToMessageId,
625245
626227
  route: input.route,
625246
626228
  shouldReply: input.shouldReply,
625247
- confidence: clamp0110(input.confidence),
626229
+ confidence: clamp0111(input.confidence),
625248
626230
  reason: compact2(input.reason, 280),
625249
626231
  source: compact2(input.source, 80),
625250
626232
  silentDisposition: compactOptional(input.silentDisposition, 280),
@@ -625256,7 +626238,7 @@ function commitTelegramSocialDecision(state, input) {
625256
626238
  scenarioNote: compactOptional(input.scenarioNote, 360),
625257
626239
  scenarioId: compactOptional(input.scenarioId, 160),
625258
626240
  scenarioLabel: compactOptional(input.scenarioLabel, 160),
625259
- scenarioConfidence: input.scenarioConfidence === void 0 ? void 0 : clamp0110(input.scenarioConfidence),
626241
+ scenarioConfidence: input.scenarioConfidence === void 0 ? void 0 : clamp0111(input.scenarioConfidence),
625260
626242
  scenarioObjective: compactOptional(input.scenarioObjective, 360),
625261
626243
  scenarioStateLoop: compactOptional(input.scenarioStateLoop, 360),
625262
626244
  salienceSignals: [...new Set((input.salienceSignals ?? []).map(String))].slice(0, 16),
@@ -625280,7 +626262,7 @@ function registerDaydreamOpportunities(state, opportunities, now = Date.now()) {
625280
626262
  artifactId: opportunity.artifactId || "unknown",
625281
626263
  generatedAt: opportunity.generatedAt || new Date(now).toISOString(),
625282
626264
  trigger: compact2(opportunity.trigger, 240),
625283
- confidence: clamp0110(opportunity.confidence),
626265
+ confidence: clamp0111(opportunity.confidence),
625284
626266
  lifecycle: "proposed",
625285
626267
  firstSeenAt: now,
625286
626268
  updatedAt: now,
@@ -625290,7 +626272,7 @@ function registerDaydreamOpportunities(state, opportunities, now = Date.now()) {
625290
626272
  };
625291
626273
  if (existing) {
625292
626274
  item.trigger = compact2(opportunity.trigger, 240) || item.trigger;
625293
- item.confidence = clamp0110(opportunity.confidence);
626275
+ item.confidence = clamp0111(opportunity.confidence);
625294
626276
  item.updatedAt = now;
625295
626277
  }
625296
626278
  state.daydreamOpportunities[id] = item;
@@ -625317,7 +626299,7 @@ function setTelegramReplyModePreference(state, input) {
625317
626299
  const next = {
625318
626300
  mode: input.mode,
625319
626301
  scope: input.scope,
625320
- confidence: Math.max(existing?.confidence ?? 0, clamp0110(input.confidence ?? 0.84)),
626302
+ confidence: Math.max(existing?.confidence ?? 0, clamp0111(input.confidence ?? 0.84)),
625321
626303
  updatedAt: now,
625322
626304
  evidenceMessageIds: appendUnique(existing?.evidenceMessageIds ?? [], input.messageId, 12),
625323
626305
  note: compactOptional(input.note, 220),
@@ -625497,8 +626479,8 @@ function upsertRelationship(state, kind, fromKey, toKey, messageId, confidence2,
625497
626479
  evidenceMessageIds: [],
625498
626480
  source
625499
626481
  };
625500
- edge.confidence = Math.max(edge.confidence, clamp0110(confidence2));
625501
- edge.weight = Math.min(1, edge.weight + 0.12 + clamp0110(confidence2) * 0.2);
626482
+ edge.confidence = Math.max(edge.confidence, clamp0111(confidence2));
626483
+ edge.weight = Math.min(1, edge.weight + 0.12 + clamp0111(confidence2) * 0.2);
625502
626484
  edge.lastSeenAt = now;
625503
626485
  edge.evidenceMessageIds = appendUnique(edge.evidenceMessageIds, messageId, 40);
625504
626486
  edge.note = compactOptional(note, 260) || edge.note;
@@ -625540,7 +626522,7 @@ function setPreference(vector, key, value2, confidence2, messageId, now, note) {
625540
626522
  const existing = vector[key];
625541
626523
  vector[key] = {
625542
626524
  value: existing ? existing.value * 0.7 + value2 * 0.3 : value2,
625543
- confidence: Math.max(existing?.confidence ?? 0, clamp0110(confidence2)),
626525
+ confidence: Math.max(existing?.confidence ?? 0, clamp0111(confidence2)),
625544
626526
  updatedAt: now,
625545
626527
  evidenceMessageIds: appendUnique(existing?.evidenceMessageIds ?? [], messageId, 12),
625546
626528
  note
@@ -625751,7 +626733,7 @@ import { mkdirSync as mkdirSync69, existsSync as existsSync121, unlinkSync as un
625751
626733
  import { join as join135, resolve as resolve48, basename as basename33, relative as relative13, isAbsolute as isAbsolute8, extname as extname16 } from "node:path";
625752
626734
  import { homedir as homedir43 } from "node:os";
625753
626735
  import { writeFile as writeFileAsync } from "node:fs/promises";
625754
- import { createHash as createHash30, randomBytes as randomBytes24, randomInt } from "node:crypto";
626736
+ import { createHash as createHash31, randomBytes as randomBytes24, randomInt } from "node:crypto";
625755
626737
  function cleanTelegramDecisionNote(value2, maxLength = 260) {
625756
626738
  if (typeof value2 !== "string") return void 0;
625757
626739
  const clean5 = stripTelegramHiddenThinking(value2).replace(/\s+/g, " ").trim();
@@ -626718,7 +627700,7 @@ function buildTelegramRuntimeContext(now = /* @__PURE__ */ new Date(), repoRoot)
626718
627700
  ].filter(Boolean).join("\n");
626719
627701
  }
626720
627702
  function telegramSessionIdFromKey(sessionKey) {
626721
- return `telegram-${createHash30("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
627703
+ return `telegram-${createHash31("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
626722
627704
  }
626723
627705
  function normalizeTelegramSubAgentLimit(value2) {
626724
627706
  const parsed = typeof value2 === "number" ? value2 : typeof value2 === "string" && value2.trim() ? Number(value2.trim()) : TELEGRAM_SUB_AGENT_DEFAULT_LIMIT;
@@ -627535,7 +628517,7 @@ function renderTelegramSubAgentError(username, error) {
627535
628517
  process.stdout.write(` ${c3.dim("│")} ${c3.magenta("✘")} @${username}: ${c3.dim(preview)}
627536
628518
  `);
627537
628519
  }
627538
- var TELEGRAM_TOOL_ACTION_GROUPS, TELEGRAM_TOOL_ACTION_GROUP, TELEGRAM_TOOL_MUTATING_GROUPS, DEFAULT_TELEGRAM_TOOL_GROUP_POLICY, TELEGRAM_TOOL_BUTTON_LABELS, TELEGRAM_SAFETY_PROMPT, ADMIN_DM_PROMPT, ADMIN_GROUP_PROMPT, TELEGRAM_PUBLIC_SOUL_PROFILE, TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT, TELEGRAM_PUBLIC_MEMORY_SCOPE_CONTRACT, TELEGRAM_PUBLIC_VISION_STACK_CONTRACT, GROUP_REPLY_DISCRETION_PROMPT, TELEGRAM_CHAT_MODE_PROMPT, ADMIN_CHAT_PROFILE_PROMPT, TELEGRAM_ACTION_RESPONSE_CONTRACT, TELEGRAM_EXTERNAL_ACQUISITION_CONTRACT, TELEGRAM_INTERACTION_DECISION_RESPONSE_FORMAT, TELEGRAM_CHAT_REPLY_RESPONSE_FORMAT, TELEGRAM_STUCK_SELF_TALK_PREFIXES, TELEGRAM_CHAT_HISTORY_LIMIT, TELEGRAM_CONTEXT_RECENT_DEFAULT, TELEGRAM_CONTEXT_LINE_LIMIT, TELEGRAM_CONTEXT_SAMPLE_LIMIT, TELEGRAM_MEMORY_CARD_LIMIT, TELEGRAM_MEMORY_NOTE_LIMIT, TELEGRAM_ASSOCIATIVE_FACT_LIMIT, TELEGRAM_ASSOCIATIVE_USER_FACT_LIMIT, TELEGRAM_ASSOCIATIVE_ACTION_LIMIT, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT, TELEGRAM_MEMORY_STOPWORDS, TELEGRAM_MEMORY_GENERIC_QUERY_TOKENS, TELEGRAM_SUB_AGENT_BOUNDED_OPTIONS, TELEGRAM_SUB_AGENT_DEFAULT_LIMIT, TELEGRAM_SUB_AGENT_MAX_LIMIT, TELEGRAM_SUB_AGENT_BURST_CONTEXT_LIMIT, TELEGRAM_PUBLIC_HELP_COMMANDS2, TELEGRAM_REMINDER_SLASH_COMMANDS, TELEGRAM_REFLECTION_SLASH_COMMANDS, TELEGRAM_PUBLIC_BOT_COMMAND_NAMES, TELEGRAM_IMAGE_EXTENSIONS, MEDIA_CACHE_TTL_MS, TELEGRAM_CHANNEL_DMN_SWEEP_MS, TELEGRAM_CHANNEL_DMN_IDLE_AFTER_MS, TELEGRAM_CHANNEL_DMN_MIN_INTERVAL_MS, TELEGRAM_CHANNEL_DMN_MIN_MESSAGES, TELEGRAM_ALLOWED_UPDATES, TELEGRAM_PUBLIC_TOOL_QUOTAS, TelegramBridge;
628520
+ var TELEGRAM_TOOL_ACTION_GROUPS, TELEGRAM_TOOL_ACTION_GROUP, TELEGRAM_TOOL_MUTATING_GROUPS, DEFAULT_TELEGRAM_TOOL_GROUP_POLICY, TELEGRAM_TOOL_BUTTON_LABELS, TELEGRAM_SAFETY_PROMPT, ADMIN_DM_PROMPT, ADMIN_GROUP_PROMPT, TELEGRAM_PUBLIC_SOUL_PROFILE, TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT, TELEGRAM_PUBLIC_MEMORY_SCOPE_CONTRACT, TELEGRAM_PUBLIC_VISION_STACK_CONTRACT, GROUP_REPLY_DISCRETION_PROMPT, TELEGRAM_CHAT_MODE_PROMPT, ADMIN_CHAT_PROFILE_PROMPT, TELEGRAM_ACTION_RESPONSE_CONTRACT, TELEGRAM_EXTERNAL_ACQUISITION_CONTRACT, TELEGRAM_INTERACTION_DECISION_RESPONSE_FORMAT, TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA, TELEGRAM_INTERACTION_DECISION_REPAIR_SCHEMA, TELEGRAM_CHAT_REPLY_RESPONSE_FORMAT, TELEGRAM_STUCK_SELF_TALK_PREFIXES, TELEGRAM_CHAT_HISTORY_LIMIT, TELEGRAM_CONTEXT_RECENT_DEFAULT, TELEGRAM_CONTEXT_LINE_LIMIT, TELEGRAM_CONTEXT_SAMPLE_LIMIT, TELEGRAM_MEMORY_CARD_LIMIT, TELEGRAM_MEMORY_NOTE_LIMIT, TELEGRAM_ASSOCIATIVE_FACT_LIMIT, TELEGRAM_ASSOCIATIVE_USER_FACT_LIMIT, TELEGRAM_ASSOCIATIVE_ACTION_LIMIT, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT, TELEGRAM_MEMORY_STOPWORDS, TELEGRAM_MEMORY_GENERIC_QUERY_TOKENS, TELEGRAM_SUB_AGENT_BOUNDED_OPTIONS, TELEGRAM_SUB_AGENT_DEFAULT_LIMIT, TELEGRAM_SUB_AGENT_MAX_LIMIT, TELEGRAM_SUB_AGENT_BURST_CONTEXT_LIMIT, TELEGRAM_PUBLIC_HELP_COMMANDS2, TELEGRAM_REMINDER_SLASH_COMMANDS, TELEGRAM_REFLECTION_SLASH_COMMANDS, TELEGRAM_PUBLIC_BOT_COMMAND_NAMES, TELEGRAM_IMAGE_EXTENSIONS, MEDIA_CACHE_TTL_MS, TELEGRAM_CHANNEL_DMN_SWEEP_MS, TELEGRAM_CHANNEL_DMN_IDLE_AFTER_MS, TELEGRAM_CHANNEL_DMN_MIN_INTERVAL_MS, TELEGRAM_CHANNEL_DMN_MIN_MESSAGES, TELEGRAM_ALLOWED_UPDATES, TELEGRAM_PUBLIC_TOOL_QUOTAS, TelegramBridge;
627539
628521
  var init_telegram_bridge = __esm({
627540
628522
  "packages/cli/src/tui/telegram-bridge.ts"() {
627541
628523
  "use strict";
@@ -627807,6 +628789,8 @@ External acquisition contract:
627807
628789
  TELEGRAM_INTERACTION_DECISION_RESPONSE_FORMAT = {
627808
628790
  type: "json_object"
627809
628791
  };
628792
+ TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA = `{"route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","attention_state":"idle"|"observing"|"engaged"|"cooldown","attention_delta":-1.0..1.0,"next_check_after_messages":1..12,"reply_mode_preference":null|{"scope":"current_user_in_chat"|"current_user_global"|"current_group","reply_mode":"reply_then_notes"|"notes_then_reply"|"reply_only","confidence":0.0-1.0,"note":"explicit durable cadence preference"}}`;
628793
+ TELEGRAM_INTERACTION_DECISION_REPAIR_SCHEMA = `{"recoverable":true|false,"route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","attention_state":"idle"|"observing"|"engaged"|"cooldown","attention_delta":-1.0..1.0,"next_check_after_messages":1..12,"reply_mode_preference":null|{"scope":"current_user_in_chat"|"current_user_global"|"current_group","reply_mode":"reply_then_notes"|"notes_then_reply"|"reply_only","confidence":0.0-1.0,"note":"explicit durable cadence preference"}}`;
627810
628794
  TELEGRAM_CHAT_REPLY_RESPONSE_FORMAT = {
627811
628795
  type: "json_schema",
627812
628796
  json_schema: {
@@ -628333,7 +629317,7 @@ External acquisition contract:
628333
629317
  return !!this.adminAuthChallenge && this.adminAuthChallenge.expiresAtMs > Date.now();
628334
629318
  }
628335
629319
  hashAdminAuthCode(code8) {
628336
- return createHash30("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
629320
+ return createHash31("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
628337
629321
  }
628338
629322
  viewIdForMessage(msg) {
628339
629323
  return `telegram-${this.sessionKeyForMessage(msg).replace(/[^A-Za-z0-9_-]/g, "-")}`;
@@ -629260,11 +630244,11 @@ ${mediaContext}` : ""
629260
630244
  return payload;
629261
630245
  }
629262
630246
  telegramConversationPath(sessionKey) {
629263
- const safe = createHash30("sha1").update(sessionKey).digest("hex").slice(0, 20);
630247
+ const safe = createHash31("sha1").update(sessionKey).digest("hex").slice(0, 20);
629264
630248
  return join135(this.telegramConversationDir, `${safe}.json`);
629265
630249
  }
629266
630250
  telegramConversationLedgerPath(sessionKey) {
629267
- const safe = createHash30("sha1").update(sessionKey).digest("hex").slice(0, 20);
630251
+ const safe = createHash31("sha1").update(sessionKey).digest("hex").slice(0, 20);
629268
630252
  return join135(this.telegramConversationDir, `${safe}.events.jsonl`);
629269
630253
  }
629270
630254
  telegramDb() {
@@ -629492,7 +630476,7 @@ ${mediaContext}` : ""
629492
630476
  users,
629493
630477
  relationships: Array.isArray(raw.relationships) ? raw.relationships.slice(0, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT).map((fact) => this.normalizeTelegramAssociativeFact(fact)) : [],
629494
630478
  actions: Array.isArray(raw.actions) ? raw.actions.slice(-TELEGRAM_ASSOCIATIVE_ACTION_LIMIT).map((action) => ({
629495
- id: String(action.id || createHash30("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)),
630479
+ id: String(action.id || createHash31("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)),
629496
630480
  ts: typeof action.ts === "number" ? action.ts : Date.now(),
629497
630481
  role: action.role === "assistant" ? "assistant" : "user",
629498
630482
  speaker: String(action.speaker || "unknown"),
@@ -629509,7 +630493,7 @@ ${mediaContext}` : ""
629509
630493
  const text = String(raw.text || "").trim();
629510
630494
  const now = Date.now();
629511
630495
  return {
629512
- id: String(raw.id || createHash30("sha1").update(text || String(now)).digest("hex").slice(0, 12)),
630496
+ id: String(raw.id || createHash31("sha1").update(text || String(now)).digest("hex").slice(0, 12)),
629513
630497
  text,
629514
630498
  tags: Array.isArray(raw.tags) ? raw.tags.map(String).slice(0, 16) : [],
629515
630499
  speakers: Array.isArray(raw.speakers) ? raw.speakers.map(String).slice(0, 16) : [],
@@ -629747,6 +630731,41 @@ ${mediaContext}` : ""
629747
630731
  scenarioStateLoop: void 0
629748
630732
  };
629749
630733
  }
630734
+ synthesizeTelegramPostReplyDecision(decision2, msg, visibleReplyText) {
630735
+ const base3 = this.stripTelegramDecisionNotes(decision2);
630736
+ const replySummary = visibleReplyText ? sanitizeTelegramProgressText(cleanTelegramVisibleReply(visibleReplyText), 180) : "visible reply attempt completed";
630737
+ return {
630738
+ ...base3,
630739
+ silentDisposition: "visible reply completed before internal note commit",
630740
+ mentalNote: `post-reply: @${msg.username || "unknown"} was answered via ${decision2.route}; ${replySummary}`,
630741
+ memoryNote: "message and visible reply were retained in scoped Telegram conversation memory"
630742
+ };
630743
+ }
630744
+ notesThenReplyDecision(decision2, msg) {
630745
+ if (decision2.silentDisposition || decision2.mentalNote || decision2.memoryNote || decision2.relationshipNote || decision2.procedureNote || decision2.voiceNote || decision2.scenarioNote || decision2.scenarioId) {
630746
+ return decision2;
630747
+ }
630748
+ return {
630749
+ ...decision2,
630750
+ silentDisposition: "internal notes committed before visible reply by reply mode",
630751
+ mentalNote: `pre-reply: @${msg.username || "unknown"} routed to ${decision2.route}; ${decision2.reason}`,
630752
+ memoryNote: "message retained in scoped Telegram conversation memory before reply"
630753
+ };
630754
+ }
630755
+ deliverTelegramPostReplyNotes(sessionKey, msg, viewId, decision2, salienceSignals, daydreamOpportunities, visibleReplyText) {
630756
+ const postReplyDecision = this.synthesizeTelegramPostReplyDecision(decision2, msg, visibleReplyText);
630757
+ if (viewId && this.subAgentViewCallbacks) {
630758
+ this.subAgentViewCallbacks.onWrite(viewId, "post-reply/internal notes:");
630759
+ }
630760
+ this.deliverTelegramAttentionDecision(
630761
+ sessionKey,
630762
+ msg,
630763
+ viewId,
630764
+ postReplyDecision,
630765
+ salienceSignals,
630766
+ daydreamOpportunities
630767
+ );
630768
+ }
629750
630769
  telegramTextDeliveryCapability(sessionKey, chatId, messageThreadId) {
629751
630770
  try {
629752
630771
  return telegramTextDeliveryCapabilityFor(this.telegramSocialStateForSession(sessionKey), {
@@ -629863,7 +630882,7 @@ ${mediaContext}` : ""
629863
630882
  }
629864
630883
  telegramHistoryBackfillMessageId(sessionKey, entry, index) {
629865
630884
  if (typeof entry.messageId === "number" && Number.isFinite(entry.messageId)) return entry.messageId;
629866
- const digest3 = createHash30("sha1").update(`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`).digest("hex").slice(0, 8);
630885
+ const digest3 = createHash31("sha1").update(`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`).digest("hex").slice(0, 8);
629867
630886
  return -Number.parseInt(digest3, 16);
629868
630887
  }
629869
630888
  backfillTelegramLoadedHistory(sessionKey, history) {
@@ -630780,7 +631799,7 @@ ${mediaContext}` : ""
630780
631799
  const now = entry.ts ?? Date.now();
630781
631800
  memory.updatedAt = now;
630782
631801
  const speaker = telegramHistorySpeaker(entry);
630783
- const actionId = createHash30("sha1").update(`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now}:${entry.text}`).digest("hex").slice(0, 16);
631802
+ const actionId = createHash31("sha1").update(`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now}:${entry.text}`).digest("hex").slice(0, 16);
630784
631803
  if (!memory.actions.some((action) => action.id === actionId)) {
630785
631804
  memory.actions.push({
630786
631805
  id: actionId,
@@ -630902,7 +631921,7 @@ ${mediaContext}` : ""
630902
631921
  let fact = facts.find((item) => item.text.toLowerCase() === key);
630903
631922
  if (!fact) {
630904
631923
  fact = {
630905
- id: createHash30("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
631924
+ id: createHash31("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
630906
631925
  text: clean5,
630907
631926
  tags: telegramMemoryTags(clean5, entry.mediaSummary),
630908
631927
  speakers: [],
@@ -630957,7 +631976,7 @@ ${mediaContext}` : ""
630957
631976
  const titleTags = tags.slice(0, 4);
630958
631977
  const title = titleTags.length > 0 ? `${speaker} / ${titleTags.join(" ")}` : `${speaker} / conversation`;
630959
631978
  const card = {
630960
- id: createHash30("sha1").update(`${sessionKey}:${now}:${speaker}:${text}`).digest("hex").slice(0, 12),
631979
+ id: createHash31("sha1").update(`${sessionKey}:${now}:${speaker}:${text}`).digest("hex").slice(0, 12),
630961
631980
  title,
630962
631981
  notes: [],
630963
631982
  tags: [],
@@ -632278,7 +633297,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
632278
633297
  routeInstruction,
632279
633298
  ``,
632280
633299
  `Return JSON only with this schema:`,
632281
- `{"recoverable":true|false,"route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","attention_state":"idle"|"observing"|"engaged"|"cooldown","attention_delta":-1.0..1.0,"next_check_after_messages":1..12,"silent_disposition":"short outcome-level disposition","mental_note":"short outcome-level observation","memory_note":"short memory/summary update","relationship_note":"short relationship/thread note","procedure_note":"short tree/procedure note","voice_note":"short final-voice note","scenario_note":"short scenario/transition note","scenario_id":"dynamic inferred scenario id","scenario_label":"human readable dynamic scenario label","scenario_confidence":0.0-1.0,"scenario_objective":"current scenario objective","scenario_state_loop":"state loop to maintain until transition","reply_mode_preference":null|{"scope":"current_user_in_chat"|"current_user_global"|"current_group","reply_mode":"reply_then_notes"|"notes_then_reply"|"reply_only","confidence":0.0-1.0,"note":"why this durable preference was explicitly expressed"}}`,
633300
+ TELEGRAM_INTERACTION_DECISION_REPAIR_SCHEMA,
632282
633301
  ``,
632283
633302
  `Original router output:`,
632284
633303
  rawPreview,
@@ -632296,7 +633315,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
632296
633315
  ],
632297
633316
  tools: [],
632298
633317
  temperature: 0,
632299
- maxTokens: 1500,
633318
+ maxTokens: 800,
632300
633319
  timeoutMs: telegramRouterTimeoutMs(timeoutMs, 8e3, 2e4),
632301
633320
  think: false
632302
633321
  }, diagnostics, "router-repair", sessionKey);
@@ -632342,7 +633361,7 @@ ${userPrompt.slice(-4e3)}` : userPrompt;
632342
633361
  `Return exactly one JSON object and no prose. No <think> tags. No commentary.`,
632343
633362
  routeInstruction,
632344
633363
  ``,
632345
- `Required schema: {"route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","attention_state":"idle"|"observing"|"engaged"|"cooldown","attention_delta":-1.0..1.0,"next_check_after_messages":1..12,"silent_disposition":"short outcome-level disposition","mental_note":"short outcome-level observation","memory_note":"short memory/summary update","relationship_note":"short relationship/thread note","procedure_note":"short tree/procedure note","voice_note":"short final-voice note","scenario_note":"short scenario/transition note","scenario_id":"dynamic inferred scenario id","scenario_label":"human readable dynamic scenario label","scenario_confidence":0.0-1.0,"scenario_objective":"current scenario objective","scenario_state_loop":"state loop to maintain until transition","reply_mode_preference":null|{"scope":"current_user_in_chat"|"current_user_global"|"current_group","reply_mode":"reply_then_notes"|"notes_then_reply"|"reply_only","confidence":0.0-1.0,"note":"why this durable preference was explicitly expressed"}}`,
633364
+ `Required schema: ${TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA}`,
632346
633365
  ``,
632347
633366
  `Invalid previous output, for diagnostics only:`,
632348
633367
  invalidPreview,
@@ -632363,7 +633382,7 @@ ${userPrompt.slice(-4e3)}` : userPrompt;
632363
633382
  ],
632364
633383
  tools: [],
632365
633384
  temperature: 0,
632366
- maxTokens: 2400,
633385
+ maxTokens: 1e3,
632367
633386
  timeoutMs: telegramRouterTimeoutMs(timeoutMs, 1e4, 3e4),
632368
633387
  think: false
632369
633388
  }, diagnostics, "router-strict-retry", sessionKey);
@@ -632666,19 +633685,12 @@ ${stimulationProbe.context}`,
632666
633685
  let reflectionNotes;
632667
633686
  let reflectionContext;
632668
633687
  if (consolidatedMode) {
632669
- reflectionNotes = this.fallbackTelegramSilentReflectionNotes(msg, "consolidated mode: reflection computed inline by router");
633688
+ reflectionNotes = {};
632670
633689
  reflectionContext = [
632671
- "## Consolidated Reflection (you produce these fields as part of the same JSON)",
632672
- "Before emitting your final decision, internally reflect on:",
632673
- " silent_disposition: what happens silently with this message",
632674
- " mental_note: concise observation of the turn",
632675
- " memory_note: what scoped memory should retain or connect",
632676
- " relationship_note: relationship/thread implication",
632677
- " procedure_note: active tree/branch/abort implication",
632678
- " voice_note: final voice implication if a reply happens",
632679
- " scenario_note: identified scenario and transition state",
632680
- " scenario_id / scenario_label / scenario_confidence / scenario_objective / scenario_state_loop",
632681
- "Use these as your attention substrate, then decide route/should_reply/confidence. Return all fields in ONE JSON."
633690
+ "## Router fast-path note policy",
633691
+ "Do not generate silent_disposition, mental_note, memory_note, relationship_note, procedure_note, voice_note, scenario fields, or other internal notes in this router response.",
633692
+ "Only decide route, should_reply, confidence, reason, optional stimulation cadence, and optional explicit reply_mode_preference.",
633693
+ "If notes are needed, the bridge will synthesize or commit them after the visible reply according to the resolved reply mode."
632682
633694
  ].join("\n");
632683
633695
  } else {
632684
633696
  reflectionNotes = await this.inferTelegramSilentReflectionNotes(
@@ -632708,22 +633720,22 @@ ${stimulationProbe.context}`,
632708
633720
  }
632709
633721
  const userPrompt = [
632710
633722
  `You are the Telegram live routing and reply-discretion model.`,
632711
- `The attention decision must happen after reading the silent reflection deliverables below. The notes are not decorations: they are the decision substrate.`,
633723
+ `Make the smallest sufficient live attention decision. Do not include internal notes unless explicitly supplied by deliberative mode context.`,
632712
633724
  `Use the persona docs below as binding behavioral guidance for whether speaking is appropriate and how to avoid over-eager or adversarially bad interventions.`,
632713
633725
  `Return JSON only, with no markdown and no explanation outside JSON.`,
632714
633726
  ``,
632715
- `Schema: {"route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","attention_state":"idle"|"observing"|"engaged"|"cooldown","attention_delta":-1.0..1.0,"next_check_after_messages":1..12,"silent_disposition":"short outcome-level disposition","mental_note":"short outcome-level observation","memory_note":"short memory/summary update","relationship_note":"short relationship/thread note","procedure_note":"short tree/procedure note","voice_note":"short final-voice note","scenario_note":"short scenario/transition note","scenario_id":"dynamic inferred scenario id","scenario_label":"human readable dynamic scenario label","scenario_confidence":0.0-1.0,"scenario_objective":"current scenario objective","scenario_state_loop":"state loop to maintain until transition","reply_mode_preference":null|{"scope":"current_user_in_chat"|"current_user_global"|"current_group","reply_mode":"reply_then_notes"|"notes_then_reply"|"reply_only","confidence":0.0-1.0,"note":"why this durable preference was explicitly expressed"}}`,
633727
+ `Schema: ${TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA}`,
632716
633728
  ``,
632717
633729
  `Route meanings:`,
632718
633730
  `- chat: a short conversational answer can be produced without tools.`,
632719
633731
  `- action: tools, workspace context, media processing, web lookup, delegation, or a multi-step agent loop may be needed.`,
632720
- `Route discipline: infer whether the selected dynamic scenario can be completed as immediate conversation or needs an external capability. Do not route from keyword categories.`,
633732
+ `Route discipline: infer whether the current request can be completed as immediate conversation or needs an external capability. Do not route from keyword categories.`,
632721
633733
  ``,
632722
633734
  `Reply discretion: make a human-like attention decision from the full social context. Observe the message, relationship stream, reply graph, conversation momentum, prior bot involvement, speaker intent, and notification-like signals, then decide whether a visible reply would be natural.`,
632723
633735
  `No hard triggers: direct address, @mentions, name/identity references, private-chat delivery, replies, active threads, and stimulation score are evidence only. They may raise or lower salience, but none guarantees should_reply=true or should_reply=false.`,
632724
633736
  `High-salience evidence: private DMs, exact @username matches, display-name self references, and replies to this bot are notification-like signals. They should usually move attention toward deeper processing and a likely response unless the surrounding context makes silence more natural.`,
632725
633737
  `No keyword routing: do not use static keyword rules. Infer whether identity references are actually aimed at this bot from syntax, tone, recent turns, and relationships.`,
632726
- `Observation notes: always fill silent_disposition, mental_note, memory_note, relationship_note, procedure_note, voice_note, scenario_note, scenario_id, scenario_label, scenario_confidence, scenario_objective, and scenario_state_loop with concise outcome-level notes for the TUI. Do not expose hidden chain-of-thought; summarize what the bot did with the heard message.`,
633738
+ `Observation notes: omit note fields on the fast path. Do not expose hidden chain-of-thought or produce scratch notes in this router JSON.`,
632727
633739
  `Reply-mode preference capture: if and only if the current sender explicitly expresses a durable preference for reply cadence/order, populate reply_mode_preference as a typed update. Do not infer this from style, keywords, tone, or one-off task shape. Use null otherwise.`,
632728
633740
  `Reply-mode meanings: reply_then_notes means visible reply first and internal notes afterward; notes_then_reply means internal notes before visible reply; reply_only means one user-facing reply with tools/context and no extra internal notes stage.`,
632729
633741
  `Bot-to-bot discipline: sender labels include [bot] or [human]. Treat peer bots as autonomous actors, not human users. Avoid bot loops by replying only when the exchange context makes a response socially useful.`,
@@ -632790,11 +633802,9 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
632790
633802
  ],
632791
633803
  tools: [],
632792
633804
  temperature: 0,
632793
- // Router JSON schema has ~18 string-valued fields when reflection is
632794
- // embedded (consolidated mode). 1000 tokens was the documented cause
632795
- // of truncated JSON → repair → strict-retry cascade. 2400 is enough
632796
- // for normal verbose values without slowing the call appreciably.
632797
- maxTokens: 2400,
633805
+ // Minimal route JSON should fit comfortably; keeping this small avoids
633806
+ // reintroducing truncated-note repair cascades.
633807
+ maxTokens: 900,
632798
633808
  timeoutMs: telegramRouterTimeoutMs(config.timeoutMs),
632799
633809
  think: false
632800
633810
  }, diagnostics, "router", sessionKey);
@@ -632833,7 +633843,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
632833
633843
  ],
632834
633844
  tools: [],
632835
633845
  temperature: 0,
632836
- maxTokens: 4096,
633846
+ maxTokens: 1400,
632837
633847
  timeoutMs: telegramRouterTimeoutMs(config.timeoutMs),
632838
633848
  think: false
632839
633849
  }, diagnostics, "router", sessionKey);
@@ -633107,7 +634117,7 @@ ${list}` : "No shared group target is currently known for this sender. Ask in th
633107
634117
  }
633108
634118
  telegramRunnerStateDir(sessionKey) {
633109
634119
  if (!this.repoRoot) return void 0;
633110
- const safe = createHash30("sha1").update(sessionKey).digest("hex").slice(0, 20);
634120
+ const safe = createHash31("sha1").update(sessionKey).digest("hex").slice(0, 20);
633111
634121
  return join135(this.repoRoot, ".omnius", "telegram-runner-state", safe);
633112
634122
  }
633113
634123
  buildTelegramAdminOverviewContext(currentSessionKey) {
@@ -633815,7 +634825,7 @@ Join: ${newUrl}`);
633815
634825
  );
633816
634826
  if (storedPreference) this.subAgentViewCallbacks?.onWrite(attentionViewId || this.viewIdForMessage(msg), `preference: ${storedPreference}`);
633817
634827
  const replyMode = this.resolvedTelegramReplyMode(sessionKey, msg);
633818
- const deliveredDecision = replyMode === "reply_only" ? this.stripTelegramDecisionNotes(decision2) : decision2;
634828
+ const deliveredDecision = replyMode === "notes_then_reply" ? this.notesThenReplyDecision(decision2, msg) : this.stripTelegramDecisionNotes(decision2);
633819
634829
  const daydreamOpportunities = this.markLatestTelegramDaydreamOpportunitiesConsidered(sessionKey, msg);
633820
634830
  const shouldDeferNotes = replyMode === "reply_then_notes" && decision2.shouldReply;
633821
634831
  if (!shouldDeferNotes) {
@@ -633849,26 +634859,22 @@ Join: ${newUrl}`);
633849
634859
  this.enqueueTelegramSubAgentContext(sessionKey, existingAfterDecision, decisionContext, msg.username);
633850
634860
  await this.enqueueTelegramQueuedSessionWorkForExistingSubAgent(work, existingAfterDecision);
633851
634861
  if (shouldDeferNotes) {
633852
- this.deliverTelegramAttentionDecision(
633853
- sessionKey,
633854
- msg,
633855
- attentionViewId,
633856
- deliveredDecision,
633857
- this.telegramMessageIdentitySalienceSignals(msg),
633858
- daydreamOpportunities
634862
+ this.subAgentViewCallbacks?.onWrite(
634863
+ attentionViewId || existingAfterDecision.viewId,
634864
+ "post-reply/internal notes deferred to active reply completion"
633859
634865
  );
633860
634866
  }
633861
634867
  return;
633862
634868
  }
633863
634869
  const subAgentProfile = decision2.route === "chat" ? "chat" : "action";
633864
634870
  if (decision2.route === "chat" && msg.chatType === "private") {
633865
- await this.handleTelegramChatCompletion(msg, toolContext, [decisionContext, rapidContext].filter(Boolean).join("\n\n"));
633866
- if (shouldDeferNotes) {
633867
- this.deliverTelegramAttentionDecision(
634871
+ const visibleReplyAttempted = await this.handleTelegramChatCompletion(msg, toolContext, [decisionContext, rapidContext].filter(Boolean).join("\n\n"));
634872
+ if (shouldDeferNotes && visibleReplyAttempted) {
634873
+ this.deliverTelegramPostReplyNotes(
633868
634874
  sessionKey,
633869
634875
  msg,
633870
634876
  attentionViewId,
633871
- deliveredDecision,
634877
+ decision2,
633872
634878
  this.telegramMessageIdentitySalienceSignals(msg),
633873
634879
  daydreamOpportunities
633874
634880
  );
@@ -633957,16 +634963,6 @@ Join: ${newUrl}`);
633957
634963
  await this.deleteLiveMessage(msg.chatId, subAgent.liveMessageId).catch(() => {
633958
634964
  });
633959
634965
  }
633960
- if (shouldDeferNotes) {
633961
- this.deliverTelegramAttentionDecision(
633962
- sessionKey,
633963
- msg,
633964
- attentionViewId,
633965
- deliveredDecision,
633966
- this.telegramMessageIdentitySalienceSignals(msg),
633967
- daydreamOpportunities
633968
- );
633969
- }
633970
634966
  return;
633971
634967
  }
633972
634968
  if (subAgent.liveMessagePromise) {
@@ -633989,19 +634985,20 @@ Join: ${newUrl}`);
633989
634985
  finalText,
633990
634986
  Boolean(subAgent.liveMessageId && !msg.guestQueryId)
633991
634987
  );
634988
+ this.tuiWrite(() => renderTelegramSubAgentComplete(msg.username, finalText));
634989
+ this.subAgentViewCallbacks?.onWrite(subAgent.viewId, `completed: ${finalText}`);
634990
+ this.subAgentViewCallbacks?.onStatus(subAgent.viewId, "completed");
633992
634991
  if (shouldDeferNotes) {
633993
- this.deliverTelegramAttentionDecision(
634992
+ this.deliverTelegramPostReplyNotes(
633994
634993
  sessionKey,
633995
634994
  msg,
633996
634995
  attentionViewId,
633997
- deliveredDecision,
634996
+ decision2,
633998
634997
  this.telegramMessageIdentitySalienceSignals(msg),
633999
- daydreamOpportunities
634998
+ daydreamOpportunities,
634999
+ finalText
634000
635000
  );
634001
635001
  }
634002
- this.tuiWrite(() => renderTelegramSubAgentComplete(msg.username, finalText));
634003
- this.subAgentViewCallbacks?.onWrite(subAgent.viewId, `completed: ${finalText}`);
634004
- this.subAgentViewCallbacks?.onStatus(subAgent.viewId, "completed");
634005
635002
  } catch (err) {
634006
635003
  if (subAgent.typingInterval) {
634007
635004
  clearInterval(subAgent.typingInterval);
@@ -634019,16 +635016,6 @@ Join: ${newUrl}`);
634019
635016
  await this.deleteLiveMessage(msg.chatId, subAgent.liveMessageId).catch(() => {
634020
635017
  });
634021
635018
  }
634022
- if (shouldDeferNotes) {
634023
- this.deliverTelegramAttentionDecision(
634024
- sessionKey,
634025
- msg,
634026
- attentionViewId,
634027
- deliveredDecision,
634028
- this.telegramMessageIdentitySalienceSignals(msg),
634029
- daydreamOpportunities
634030
- );
634031
- }
634032
635019
  } finally {
634033
635020
  this.clearTelegramSubAgentContextBuffer(sessionKey);
634034
635021
  this.subAgents.delete(sessionKey);
@@ -634156,7 +635143,7 @@ Join: ${newUrl}`);
634156
635143
  async handleTelegramChatCompletion(msg, toolContext, additionalContext = "") {
634157
635144
  if (toolContext === "telegram-admin-dm") {
634158
635145
  await this.handleTelegramAdminChatAgent(msg, toolContext, additionalContext);
634159
- return;
635146
+ return true;
634160
635147
  }
634161
635148
  const viewId = `${this.viewIdForMessage(msg)}-chat`;
634162
635149
  const sessionKey = this.sessionKeyForMessage(msg);
@@ -634241,7 +635228,7 @@ Join: ${newUrl}`);
634241
635228
  }
634242
635229
  this.subAgentViewCallbacks?.onWrite(viewId, "completed: no model reply");
634243
635230
  this.subAgentViewCallbacks?.onStatus(viewId, "completed");
634244
- return;
635231
+ return false;
634245
635232
  }
634246
635233
  const finalHtml = convertMarkdownToTelegramHTML(cleaned);
634247
635234
  const sentMessageId = await this.sendOrEditFinalTelegramHTML(msg, finalHtml, liveMessageId);
@@ -634255,6 +635242,7 @@ Join: ${newUrl}`);
634255
635242
  }
634256
635243
  this.subAgentViewCallbacks?.onWrite(viewId, `completed: ${cleaned}`);
634257
635244
  this.subAgentViewCallbacks?.onStatus(viewId, "completed");
635245
+ return true;
634258
635246
  } catch (err) {
634259
635247
  if (typingInterval) {
634260
635248
  clearInterval(typingInterval);
@@ -634273,6 +635261,7 @@ Join: ${newUrl}`);
634273
635261
  await this.deleteLiveMessage(msg.chatId, liveMessageId).catch(() => {
634274
635262
  });
634275
635263
  }
635264
+ return false;
634276
635265
  } finally {
634277
635266
  this.activeChatViews.delete(viewId);
634278
635267
  this.activeChatSessions.delete(sessionKey);
@@ -639815,14 +640804,14 @@ var init_access_policy = __esm({
639815
640804
  });
639816
640805
 
639817
640806
  // packages/cli/src/api/project-preferences.ts
639818
- import { createHash as createHash31 } from "node:crypto";
640807
+ import { createHash as createHash32 } from "node:crypto";
639819
640808
  import { existsSync as existsSync124, mkdirSync as mkdirSync72, readFileSync as readFileSync101, renameSync as renameSync8, writeFileSync as writeFileSync66, unlinkSync as unlinkSync26 } from "node:fs";
639820
640809
  import { homedir as homedir46 } from "node:os";
639821
640810
  import { join as join138, resolve as resolve50 } from "node:path";
639822
640811
  import { randomUUID as randomUUID16 } from "node:crypto";
639823
640812
  function projectKey(root) {
639824
640813
  const canonical = resolve50(root);
639825
- return createHash31("sha256").update(canonical).digest("hex").slice(0, 16);
640814
+ return createHash32("sha256").update(canonical).digest("hex").slice(0, 16);
639826
640815
  }
639827
640816
  function projectDir(root) {
639828
640817
  return join138(PROJECTS_DIR, projectKey(root));
@@ -639914,7 +640903,7 @@ __export(voicechat_exports, {
639914
640903
  VoiceChatSession: () => VoiceChatSession
639915
640904
  });
639916
640905
  import { EventEmitter as EventEmitter13 } from "node:events";
639917
- function clamp0111(x) {
640906
+ function clamp0112(x) {
639918
640907
  return x < 0 ? 0 : x > 1 ? 1 : x;
639919
640908
  }
639920
640909
  function alnumRatio(s2) {
@@ -639953,9 +640942,9 @@ function computeSignalFromText(text, confidence2) {
639953
640942
  else score = 0.15;
639954
640943
  score -= repeatingCharPenalty(t2) * 0.4;
639955
640944
  if (typeof confidence2 === "number" && !Number.isNaN(confidence2)) {
639956
- score = 0.7 * score + 0.3 * clamp0111(confidence2);
640945
+ score = 0.7 * score + 0.3 * clamp0112(confidence2);
639957
640946
  }
639958
- return clamp0111(score);
640947
+ return clamp0112(score);
639959
640948
  }
639960
640949
  function truncateForLog(s2, n2) {
639961
640950
  return s2.length <= n2 ? s2 : s2.slice(0, n2 - 1) + "…";
@@ -640225,7 +641214,7 @@ Rules:
640225
641214
  }, MAX_SEGMENT_MS);
640226
641215
  }
640227
641216
  this.captureBuffer = text;
640228
- this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp0111(snr) : computeSignalFromText(text, confidence2);
641217
+ this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp0112(snr) : computeSignalFromText(text, confidence2);
640229
641218
  this.emit("snr", { score: this.lastSignalScore });
640230
641219
  this.onPartialTranscript(text);
640231
641220
  if (this.silenceTimer) clearTimeout(this.silenceTimer);
@@ -641000,7 +641989,7 @@ var init_disk_task_output = __esm({
641000
641989
  });
641001
641990
 
641002
641991
  // packages/cli/src/api/http.ts
641003
- import { createHash as createHash32 } from "node:crypto";
641992
+ import { createHash as createHash33 } from "node:crypto";
641004
641993
  function problemDetails(opts) {
641005
641994
  const p2 = {
641006
641995
  type: opts.type ?? "about:blank",
@@ -641063,7 +642052,7 @@ function paginated(items, page2, total) {
641063
642052
  }
641064
642053
  function computeEtag(payload) {
641065
642054
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
641066
- const hash = createHash32("sha1").update(json).digest("hex").slice(0, 16);
642055
+ const hash = createHash33("sha1").update(json).digest("hex").slice(0, 16);
641067
642056
  return `W/"${hash}"`;
641068
642057
  }
641069
642058
  function checkNotModified(req2, res, etag) {
@@ -655494,7 +656483,7 @@ import { homedir as homedir53 } from "node:os";
655494
656483
  import { spawn as spawn31, execSync as execSync58 } from "node:child_process";
655495
656484
  import { mkdirSync as mkdirSync80, writeFileSync as writeFileSync72, readFileSync as readFileSync109, readdirSync as readdirSync48, existsSync as existsSync135, watch as fsWatch4, renameSync as renameSync9, unlinkSync as unlinkSync28 } from "node:fs";
655496
656485
  import { randomBytes as randomBytes27, randomUUID as randomUUID17 } from "node:crypto";
655497
- import { createHash as createHash34 } from "node:crypto";
656486
+ import { createHash as createHash35 } from "node:crypto";
655498
656487
  function memoryDbPaths3(baseDir = process.cwd()) {
655499
656488
  const dir = join149(baseDir, ".omnius");
655500
656489
  return {
@@ -661447,7 +662436,7 @@ function listScheduledTasks() {
661447
662436
  const schedule = String(t2?.schedule || t2?.cron || t2?.when || "");
661448
662437
  const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
661449
662438
  const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
661450
- const fallbackId = createHash34("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
662439
+ const fallbackId = createHash35("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
661451
662440
  const uid = realId || fallbackId;
661452
662441
  const key = `${uid}`;
661453
662442
  if (seen.has(key)) return;
@@ -661564,8 +662553,8 @@ function deleteScheduledById(id) {
661564
662553
  if (id) candidates.push(id);
661565
662554
  if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id)) candidates.push(entry.id);
661566
662555
  try {
661567
- const { createHash: createHash35 } = require4("node:crypto");
661568
- const fallback = createHash35("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
662556
+ const { createHash: createHash36 } = require4("node:crypto");
662557
+ const fallback = createHash36("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
661569
662558
  if (!candidates.includes(fallback)) candidates.push(fallback);
661570
662559
  } catch {
661571
662560
  }
@@ -671714,13 +672703,13 @@ ${taskInput}`;
671714
672703
  writeContent(() => renderError(errMsg));
671715
672704
  if (failureStore) {
671716
672705
  try {
671717
- const { createHash: createHash35 } = await import("node:crypto");
672706
+ const { createHash: createHash36 } = await import("node:crypto");
671718
672707
  failureStore.insert({
671719
672708
  taskId: "",
671720
672709
  sessionId: `${Date.now()}`,
671721
672710
  repoRoot,
671722
672711
  failureType: "runtime-error",
671723
- fingerprint: createHash35("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
672712
+ fingerprint: createHash36("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
671724
672713
  filePath: null,
671725
672714
  errorMessage: errMsg.slice(0, 500),
671726
672715
  context: null,