omnius 1.0.471 → 1.0.472

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
@@ -6288,8 +6288,8 @@ Hotspot: ${Math.round(decayHotspot(entry) * 100)}% | Accesses: ${entry.accessCou
6288
6288
  };
6289
6289
  }
6290
6290
  const entries = Object.values(map2.files);
6291
- const totalNotes = entries.reduce((sum, e2) => sum + e2.agentNotes.filter((n2) => decayConfidence(n2) > 0.1).length, 0);
6292
- const totalRelations = entries.reduce((sum, e2) => sum + e2.relationships.length, 0);
6291
+ const totalNotes = entries.reduce((sum2, e2) => sum2 + e2.agentNotes.filter((n2) => decayConfidence(n2) > 0.1).length, 0);
6292
+ const totalRelations = entries.reduce((sum2, e2) => sum2 + e2.relationships.length, 0);
6293
6293
  const hotspots = entries.map((e2) => ({ path: e2.path, score: decayHotspot(e2), notes: e2.agentNotes.filter((n2) => decayConfidence(n2) > 0.1).length })).filter((e2) => e2.score > 0.05).sort((a2, b) => b.score - a2.score).slice(0, 5);
6294
6294
  const lines = [
6295
6295
  `Codebase Semantic Map:`,
@@ -11053,7 +11053,7 @@ async function prepareHuggingFaceVisionCandidate(candidate, diagnostics) {
11053
11053
  safetyMarginBytes: gigabytesToBytes(2)
11054
11054
  });
11055
11055
  if (space.evicted.length > 0) {
11056
- diagnostics.push(`Hugging Face vision evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum, entry) => sum + entry.sizeBytes, 0))}) for ${candidate.modelId}`);
11056
+ diagnostics.push(`Hugging Face vision evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum2, entry) => sum2 + entry.sizeBytes, 0))}) for ${candidate.modelId}`);
11057
11057
  }
11058
11058
  }
11059
11059
  } catch (err) {
@@ -14546,12 +14546,12 @@ var init_file_edit = __esm({
14546
14546
  const snippet = findClosestSnippet(content, oldString, 5);
14547
14547
  let errorMsg = `old_string not found in ${filePath}.`;
14548
14548
  if (snippet) {
14549
- const pct = Math.round(snippet.similarity * 100);
14549
+ const pct2 = Math.round(snippet.similarity * 100);
14550
14550
  errorMsg += `
14551
14551
 
14552
14552
  Attempted old_string spans ${attemptedOldStringLines} line(s), ${attemptedOldStringChars} chars. The diagnostic below is the closest anchor-line match, not proof that the whole old_string exists.
14553
14553
 
14554
- Current file content (closest anchor-line match, ${pct}% line similarity, lines ${snippet.startLine}–${snippet.endLine} of ${snippet.totalLines}):
14554
+ Current file content (closest anchor-line match, ${pct2}% line similarity, lines ${snippet.startLine}–${snippet.endLine} of ${snippet.totalLines}):
14555
14555
  ${snippet.content}
14556
14556
 
14557
14557
  Use the EXACT current content above to construct a working old_string. If the intended change is a contiguous line range, use file_patch with start_line/end_line from a fresh file_read. Do not retry with a different guess — the file on disk has changed since you last read it.`;
@@ -20043,9 +20043,9 @@ function selectInnerGraphCandidates(graph, candidates, options2 = {}) {
20043
20043
  const sourceEpisodeIds = [...new Set(allEdges.map((edge) => edge.sourceEpisodeId).filter((id2) => Boolean(id2)))];
20044
20044
  const selectedEpisodeIds = [...entry.candidateEpisodeIds];
20045
20045
  const sourceStrength = sourceEpisodeIds.length;
20046
- const candidateStrength = selectedEpisodeIds.reduce((sum, id2) => sum + (candidateScore.get(id2) ?? 0), 0);
20047
- const recency = selectedEpisodeIds.reduce((sum, id2) => sum + recencyScore(candidateTimestamp.get(id2), now2), 0);
20048
- const confidence2 = allEdges.reduce((sum, edge) => sum + (Number.isFinite(edge.confidence) ? edge.confidence : 0), 0) / Math.max(1, allEdges.length);
20046
+ const candidateStrength = selectedEpisodeIds.reduce((sum2, id2) => sum2 + (candidateScore.get(id2) ?? 0), 0);
20047
+ const recency = selectedEpisodeIds.reduce((sum2, id2) => sum2 + recencyScore(candidateTimestamp.get(id2), now2), 0);
20048
+ const confidence2 = allEdges.reduce((sum2, edge) => sum2 + (Number.isFinite(edge.confidence) ? edge.confidence : 0), 0) / Math.max(1, allEdges.length);
20049
20049
  const score = degree * 1.5 + relationDiversity * 1.2 + sourceStrength * 1.4 + selectedEpisodeIds.length * 1.6 + candidateStrength + recency + confidence2 + Math.log1p(entry.node.mentionCount);
20050
20050
  results.push({
20051
20051
  node: entry.node,
@@ -20674,19 +20674,19 @@ function invertSPD(A, n2) {
20674
20674
  const L = new Float64Array(n2 * n2);
20675
20675
  for (let i2 = 0; i2 < n2; i2++) {
20676
20676
  for (let j = 0; j <= i2; j++) {
20677
- let sum = A[i2 * n2 + j];
20677
+ let sum2 = A[i2 * n2 + j];
20678
20678
  for (let k = 0; k < j; k++)
20679
- sum -= L[i2 * n2 + k] * L[j * n2 + k];
20679
+ sum2 -= L[i2 * n2 + k] * L[j * n2 + k];
20680
20680
  if (i2 === j) {
20681
- if (sum <= 0) {
20681
+ if (sum2 <= 0) {
20682
20682
  const Areg = new Float64Array(A);
20683
20683
  for (let ii = 0; ii < n2; ii++)
20684
20684
  Areg[ii * n2 + ii] += 1e-6;
20685
20685
  return invertSPD(Areg, n2);
20686
20686
  }
20687
- L[i2 * n2 + j] = Math.sqrt(sum);
20687
+ L[i2 * n2 + j] = Math.sqrt(sum2);
20688
20688
  } else {
20689
- L[i2 * n2 + j] = sum / L[j * n2 + j];
20689
+ L[i2 * n2 + j] = sum2 / L[j * n2 + j];
20690
20690
  }
20691
20691
  }
20692
20692
  }
@@ -20695,16 +20695,16 @@ function invertSPD(A, n2) {
20695
20695
  for (let c9 = 0; c9 < n2; c9++) {
20696
20696
  col.fill(0);
20697
20697
  for (let i2 = 0; i2 < n2; i2++) {
20698
- let sum = i2 === c9 ? 1 : 0;
20698
+ let sum2 = i2 === c9 ? 1 : 0;
20699
20699
  for (let k = 0; k < i2; k++)
20700
- sum -= L[i2 * n2 + k] * col[k];
20701
- col[i2] = sum / L[i2 * n2 + i2];
20700
+ sum2 -= L[i2 * n2 + k] * col[k];
20701
+ col[i2] = sum2 / L[i2 * n2 + i2];
20702
20702
  }
20703
20703
  for (let i2 = n2 - 1; i2 >= 0; i2--) {
20704
- let sum = col[i2];
20704
+ let sum2 = col[i2];
20705
20705
  for (let k = i2 + 1; k < n2; k++)
20706
- sum -= L[k * n2 + i2] * col[k];
20707
- col[i2] = sum / L[i2 * n2 + i2];
20706
+ sum2 -= L[k * n2 + i2] * col[k];
20707
+ col[i2] = sum2 / L[i2 * n2 + i2];
20708
20708
  }
20709
20709
  for (let i2 = 0; i2 < n2; i2++)
20710
20710
  Ainv[i2 * n2 + c9] = col[i2];
@@ -25591,7 +25591,7 @@ function hashEmbedding(text2, dimensions = 256) {
25591
25591
  const sign2 = (h & 2147483648) === 0 ? 1 : -1;
25592
25592
  vector[idx] += sign2;
25593
25593
  }
25594
- const norm = Math.sqrt(vector.reduce((sum, value2) => sum + value2 * value2, 0));
25594
+ const norm = Math.sqrt(vector.reduce((sum2, value2) => sum2 + value2 * value2, 0));
25595
25595
  return norm ? vector.map((value2) => value2 / norm) : vector;
25596
25596
  }
25597
25597
  function fnv1a(value2) {
@@ -25853,7 +25853,7 @@ function entityOverlap(a2, b) {
25853
25853
  function groupUtility(items, now2) {
25854
25854
  if (items.length === 0)
25855
25855
  return 0;
25856
- const raw = items.reduce((sum, item) => sum + itemUtility(item, now2), 0) / items.length;
25856
+ const raw = items.reduce((sum2, item) => sum2 + itemUtility(item, now2), 0) / items.length;
25857
25857
  const evidenceBoost = Math.min(0.2, Math.log1p(items.length) / 15);
25858
25858
  return clamp019(raw + evidenceBoost);
25859
25859
  }
@@ -26152,7 +26152,7 @@ var init_semanticContext = __esm({
26152
26152
  return groups.map((g) => this.buildChunk(g.label, g.items, g.entities, now2, maxSummaryChars)).sort((a2, b) => b.utilityScore - a2.utilityScore || a2.label.localeCompare(b.label));
26153
26153
  }
26154
26154
  buildChunk(label, items, entities, now2, maxSummaryChars) {
26155
- const rawTokenEstimate = items.reduce((sum, item) => sum + tokenCount(item), 0);
26155
+ const rawTokenEstimate = items.reduce((sum2, item) => sum2 + tokenCount(item), 0);
26156
26156
  const summary = summarize(items, maxSummaryChars);
26157
26157
  const tokenEstimate = Math.max(1, estimateTokens(summary));
26158
26158
  const utilityScore = groupUtility(items, now2);
@@ -26215,6 +26215,184 @@ var init_attention_select = __esm({
26215
26215
  }
26216
26216
  });
26217
26217
 
26218
+ // packages/memory/dist/context-folding.js
26219
+ function sum(ns) {
26220
+ let t2 = 0;
26221
+ for (const n2 of ns)
26222
+ t2 += n2;
26223
+ return t2;
26224
+ }
26225
+ var DEFAULT_SUMMARY_TOKENS, ContextFolder;
26226
+ var init_context_folding = __esm({
26227
+ "packages/memory/dist/context-folding.js"() {
26228
+ "use strict";
26229
+ DEFAULT_SUMMARY_TOKENS = 40;
26230
+ ContextFolder = class {
26231
+ open = /* @__PURE__ */ new Map();
26232
+ folded = [];
26233
+ counter = 0;
26234
+ /** Begin a subtask sub-trajectory; returns its segment id. */
26235
+ openSegment(subtask, openedAtTurn) {
26236
+ const id2 = `fold_${++this.counter}`;
26237
+ this.open.set(id2, { id: id2, subtask, openedAtTurn });
26238
+ return id2;
26239
+ }
26240
+ isOpen(id2) {
26241
+ return this.open.has(id2);
26242
+ }
26243
+ /** Fold a completed subtask into a one-line outcome. */
26244
+ closeSegment(id2, input) {
26245
+ const seg = this.open.get(id2);
26246
+ if (!seg)
26247
+ throw new Error(`closeSegment: unknown segment ${id2}`);
26248
+ this.open.delete(id2);
26249
+ const folded = {
26250
+ id: id2,
26251
+ subtask: seg.subtask,
26252
+ openedAtTurn: seg.openedAtTurn,
26253
+ closedAtTurn: input.closedAtTurn,
26254
+ outcome: input.outcome,
26255
+ artifacts: input.artifacts ?? [],
26256
+ verifierPassed: input.verifierPassed ?? false,
26257
+ foldedTurns: [],
26258
+ summaryTokens: Math.max(1, input.summaryTokens ?? DEFAULT_SUMMARY_TOKENS)
26259
+ };
26260
+ this.folded.push(folded);
26261
+ return folded;
26262
+ }
26263
+ /** One-line summaries of every folded segment (for the active frame). */
26264
+ summaries() {
26265
+ return this.folded.map((f2) => `[folded ${f2.subtask}] ${f2.outcome}` + (f2.verifierPassed ? " (verified)" : "") + (f2.artifacts.length ? ` — ${f2.artifacts.join(", ")}` : ""));
26266
+ }
26267
+ /** Folded segments (persist these to disk for audit / re-expansion). */
26268
+ foldedSegments() {
26269
+ return [...this.folded];
26270
+ }
26271
+ /**
26272
+ * Rewrite the active window: drop entries whose turn falls inside a folded
26273
+ * segment's [openedAtTurn, closedAtTurn] range and replace each folded
26274
+ * segment with a single summary entry. Entries outside any folded range
26275
+ * (including the currently-open subtask's turns) stay in the active window.
26276
+ */
26277
+ fold(entries) {
26278
+ const originalTokens = sum(entries.map((e2) => e2.tokens));
26279
+ const active = [];
26280
+ for (const entry of entries) {
26281
+ const owning = this.folded.find((f2) => entry.turn >= f2.openedAtTurn && entry.turn <= f2.closedAtTurn);
26282
+ if (owning) {
26283
+ if (!owning.foldedTurns.includes(entry.turn)) {
26284
+ owning.foldedTurns.push(entry.turn);
26285
+ }
26286
+ continue;
26287
+ }
26288
+ active.push(entry);
26289
+ }
26290
+ for (const f2 of this.folded) {
26291
+ if (f2.foldedTurns.length > 0) {
26292
+ active.push({ turn: f2.closedAtTurn, tokens: f2.summaryTokens, role: "folded" });
26293
+ }
26294
+ }
26295
+ const activeTokens = sum(active.map((e2) => e2.tokens));
26296
+ return {
26297
+ activeEntries: active.sort((a2, b) => a2.turn - b.turn),
26298
+ activeTokens,
26299
+ originalTokens,
26300
+ reductionFactor: activeTokens > 0 ? originalTokens / activeTokens : Infinity,
26301
+ foldedSegments: this.foldedSegments()
26302
+ };
26303
+ }
26304
+ };
26305
+ }
26306
+ });
26307
+
26308
+ // packages/memory/dist/compaction-policy.js
26309
+ function decideCompaction(input) {
26310
+ const fireAt = input.fireAtPressure ?? 0.85;
26311
+ const ceiling = Math.max(fireAt, input.hardCeiling ?? 0.95);
26312
+ if (input.pressureRatio >= ceiling) {
26313
+ return {
26314
+ compact: true,
26315
+ reason: `pressure ${pct(input.pressureRatio)} >= hard ceiling ${pct(ceiling)} — compact to avoid overflow`
26316
+ };
26317
+ }
26318
+ if (input.pressureRatio < fireAt) {
26319
+ return {
26320
+ compact: false,
26321
+ reason: `pressure ${pct(input.pressureRatio)} < ${pct(fireAt)} — below threshold, hold`
26322
+ };
26323
+ }
26324
+ if (input.midDerivation) {
26325
+ return {
26326
+ compact: false,
26327
+ reason: "mid-derivation: hold compaction until the current chain resolves"
26328
+ };
26329
+ }
26330
+ if (input.convergenceStalled) {
26331
+ return {
26332
+ compact: false,
26333
+ reason: "convergence stalled: hold the failure evidence for the breaker to act on"
26334
+ };
26335
+ }
26336
+ return {
26337
+ compact: true,
26338
+ reason: input.lastSubtaskResolved ? "subtask resolved and over threshold — good moment to compact" : "over threshold and trajectory not mid-derivation/stuck — compact"
26339
+ };
26340
+ }
26341
+ function validateCompaction(compactedText, pinned) {
26342
+ const text2 = compactedText ?? "";
26343
+ const dropped = [];
26344
+ for (const s2 of pinned.symbols ?? [])
26345
+ if (!text2.includes(s2))
26346
+ dropped.push(`symbol:${s2}`);
26347
+ for (const b of pinned.openBugs ?? [])
26348
+ if (!text2.includes(b))
26349
+ dropped.push(`bug:${b}`);
26350
+ if (pinned.nextAction && !text2.includes(pinned.nextAction)) {
26351
+ dropped.push(`nextAction:${pinned.nextAction}`);
26352
+ }
26353
+ const valid = dropped.length === 0;
26354
+ return {
26355
+ valid,
26356
+ dropped,
26357
+ reason: valid ? "compaction preserved all pinned invariants" : `compaction dropped ${dropped.length} pinned invariant(s): ${dropped.join(", ")} — roll back`
26358
+ };
26359
+ }
26360
+ function computeSignalToNoise(frameText, noiseMarkers = DEFAULT_NOISE_MARKERS) {
26361
+ let signalChars = 0;
26362
+ let noiseChars = 0;
26363
+ for (const line of (frameText ?? "").split(/\r?\n/)) {
26364
+ const isNoise = noiseMarkers.some((m2) => line.includes(m2));
26365
+ if (isNoise)
26366
+ noiseChars += line.length;
26367
+ else
26368
+ signalChars += line.length;
26369
+ }
26370
+ return {
26371
+ signalChars,
26372
+ noiseChars,
26373
+ ratio: signalChars / Math.max(1, noiseChars)
26374
+ };
26375
+ }
26376
+ function pct(n2) {
26377
+ return `${Math.round(n2 * 100)}%`;
26378
+ }
26379
+ var DEFAULT_NOISE_MARKERS;
26380
+ var init_compaction_policy = __esm({
26381
+ "packages/memory/dist/compaction-policy.js"() {
26382
+ "use strict";
26383
+ DEFAULT_NOISE_MARKERS = [
26384
+ "deduped",
26385
+ "duplicate shell",
26386
+ "duplicate tool",
26387
+ "Do not retry ide",
26388
+ "[FAILED] Took",
26389
+ "[TOOL ACTION REASON CONTRACT]",
26390
+ "RUNTIME TOOL ARGUMENT REPAIR",
26391
+ "trust_tier:tool_output_untrusted"
26392
+ ];
26393
+ }
26394
+ });
26395
+
26218
26396
  // packages/memory/dist/index.js
26219
26397
  var dist_exports = {};
26220
26398
  __export(dist_exports, {
@@ -26230,6 +26408,7 @@ __export(dist_exports, {
26230
26408
  CRL_SYMBOLS: () => CRL_SYMBOLS,
26231
26409
  CodebaseMap: () => CodebaseMap,
26232
26410
  ConfidenceTracker: () => ConfidenceTracker,
26411
+ ContextFolder: () => ContextFolder,
26233
26412
  ContextWindow: () => ContextWindow,
26234
26413
  DECAY_TAU: () => DECAY_TAU,
26235
26414
  DEFAULT_CRL_CONFIG: () => DEFAULT_CRL_CONFIG,
@@ -26288,6 +26467,7 @@ __export(dist_exports, {
26288
26467
  closeDb: () => closeDb,
26289
26468
  compressAndStore: () => compressAndStore,
26290
26469
  compressToGist: () => compressToGist,
26470
+ computeSignalToNoise: () => computeSignalToNoise,
26291
26471
  conformityBias: () => conformityBias,
26292
26472
  congruenceMultiplier: () => congruenceMultiplier,
26293
26473
  contextItemsFromMessages: () => contextItemsFromMessages,
@@ -26296,6 +26476,7 @@ __export(dist_exports, {
26296
26476
  createCRLMemoryStore: () => createCRLMemoryStore,
26297
26477
  createHomeostaticState: () => createHomeostaticState,
26298
26478
  crystallize: () => crystallize,
26479
+ decideCompaction: () => decideCompaction,
26299
26480
  decodeMemoryVector: () => decodeMemoryVector,
26300
26481
  detectStage: () => detectStage,
26301
26482
  developmentalReport: () => report,
@@ -26370,6 +26551,7 @@ __export(dist_exports, {
26370
26551
  suggestRegulationActions: () => suggestRegulationActions,
26371
26552
  thresholdsForStage: () => thresholdsForStage,
26372
26553
  tokenSimilarity: () => tokenSimilarity,
26554
+ validateCompaction: () => validateCompaction,
26373
26555
  walkGraphFromSeed: () => walkGraphFromSeed,
26374
26556
  wasHesitant: () => wasHesitant
26375
26557
  });
@@ -26425,6 +26607,8 @@ var init_dist = __esm({
26425
26607
  init_maintenance();
26426
26608
  init_semanticContext();
26427
26609
  init_attention_select();
26610
+ init_context_folding();
26611
+ init_compaction_policy();
26428
26612
  }
26429
26613
  });
26430
26614
 
@@ -28840,9 +29024,9 @@ var init_batch_edit = __esm({
28840
29024
  }
28841
29025
  const snippet = findClosestSnippet(content, edit.old_string, 5);
28842
29026
  if (snippet) {
28843
- const pct = Math.round(snippet.similarity * 100);
29027
+ const pct2 = Math.round(snippet.similarity * 100);
28844
29028
  results.push(`SKIP: old_string not found in ${edit.relPath}.
28845
- Closest match in current file (${pct}% similar, lines ${snippet.startLine}–${snippet.endLine} of ${snippet.totalLines}):
29029
+ Closest match in current file (${pct2}% similar, lines ${snippet.startLine}–${snippet.endLine} of ${snippet.totalLines}):
28846
29030
  ${snippet.content}
28847
29031
  Use this exact content for old_string in your next attempt.`);
28848
29032
  } else {
@@ -28922,7 +29106,7 @@ ${s2.content}`;
28922
29106
  ].join("\n") : dryRun ? [
28923
29107
  `BATCH_VALIDATED_ONLY: ${appliedCount} edit(s) validated, 0 failed across ${byFile.size} file(s).`,
28924
29108
  `NO FILES WERE MODIFIED. Call again with dry_run=false to apply this atomic batch.`
28925
- ].join("\n") : pendingWrites.length === 0 && alreadyAppliedCount > 0 ? `BATCH_NOOP_ALREADY_APPLIED: ${alreadyAppliedCount} edit(s) already satisfied, 0 failed across ${byFile.size} file(s).` : `BATCH_COMMITTED: ${appliedCount} edit(s) satisfied (${pendingWrites.reduce((sum, write2) => sum + write2.editCount, 0)} applied, ${alreadyAppliedCount} already applied), 0 failed across ${byFile.size} file(s).`;
29109
+ ].join("\n") : pendingWrites.length === 0 && alreadyAppliedCount > 0 ? `BATCH_NOOP_ALREADY_APPLIED: ${alreadyAppliedCount} edit(s) already satisfied, 0 failed across ${byFile.size} file(s).` : `BATCH_COMMITTED: ${appliedCount} edit(s) satisfied (${pendingWrites.reduce((sum2, write2) => sum2 + write2.editCount, 0)} applied, ${alreadyAppliedCount} already applied), 0 failed across ${byFile.size} file(s).`;
28926
29110
  const detailOutput = failCount === 0 ? dryRun ? results.join("\n") : results.map((line) => line.replace(/^VALIDATED_ONLY:/, "APPLIED:").replace(/ pending atomic commit/g, "")).join("\n") : results.join("\n");
28927
29111
  return {
28928
29112
  success: failCount === 0,
@@ -44161,7 +44345,7 @@ var init_structured_file = __esm({
44161
44345
  parts.push(jsonToMarkdownTable(data));
44162
44346
  }
44163
44347
  content = parts.join("\n");
44164
- byteInfo = sheets ? `${sheets.length} sections, ${sheets.reduce((s2, sh) => s2 + sh.data.length, 0)} total rows` : `${data.length} rows`;
44348
+ byteInfo = sheets ? `${sheets.length} sections, ${sheets.reduce((s2, sh2) => s2 + sh2.data.length, 0)} total rows` : `${data.length} rows`;
44165
44349
  break;
44166
44350
  }
44167
44351
  default:
@@ -50462,13 +50646,13 @@ function kdfInputToBytes(data, errorTitle = "") {
50462
50646
  return abytes(data, void 0, errorTitle);
50463
50647
  }
50464
50648
  function concatBytes(...arrays) {
50465
- let sum = 0;
50649
+ let sum2 = 0;
50466
50650
  for (let i2 = 0; i2 < arrays.length; i2++) {
50467
50651
  const a2 = arrays[i2];
50468
50652
  abytes(a2);
50469
- sum += a2.length;
50653
+ sum2 += a2.length;
50470
50654
  }
50471
- const res = new Uint8Array(sum);
50655
+ const res = new Uint8Array(sum2);
50472
50656
  for (let i2 = 0, pad = 0; i2 < arrays.length; i2++) {
50473
50657
  const a2 = arrays[i2];
50474
50658
  res.set(a2, pad);
@@ -124725,7 +124909,7 @@ var require_jsbn = __commonJS({
124725
124909
  }
124726
124910
  this.t = 0;
124727
124911
  this.s = 0;
124728
- var i2 = s2.length, mi = false, sh = 0;
124912
+ var i2 = s2.length, mi = false, sh2 = 0;
124729
124913
  while (--i2 >= 0) {
124730
124914
  var x = k == 8 ? s2[i2] & 255 : intAt(s2, i2);
124731
124915
  if (x < 0) {
@@ -124733,19 +124917,19 @@ var require_jsbn = __commonJS({
124733
124917
  continue;
124734
124918
  }
124735
124919
  mi = false;
124736
- if (sh == 0)
124920
+ if (sh2 == 0)
124737
124921
  this.data[this.t++] = x;
124738
- else if (sh + k > this.DB) {
124739
- this.data[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh;
124740
- this.data[this.t++] = x >> this.DB - sh;
124922
+ else if (sh2 + k > this.DB) {
124923
+ this.data[this.t - 1] |= (x & (1 << this.DB - sh2) - 1) << sh2;
124924
+ this.data[this.t++] = x >> this.DB - sh2;
124741
124925
  } else
124742
- this.data[this.t - 1] |= x << sh;
124743
- sh += k;
124744
- if (sh >= this.DB) sh -= this.DB;
124926
+ this.data[this.t - 1] |= x << sh2;
124927
+ sh2 += k;
124928
+ if (sh2 >= this.DB) sh2 -= this.DB;
124745
124929
  }
124746
124930
  if (k == 8 && (s2[0] & 128) != 0) {
124747
124931
  this.s = -1;
124748
- if (sh > 0) this.data[this.t - 1] |= (1 << this.DB - sh) - 1 << sh;
124932
+ if (sh2 > 0) this.data[this.t - 1] |= (1 << this.DB - sh2) - 1 << sh2;
124749
124933
  }
124750
124934
  this.clamp();
124751
124935
  if (mi) BigInteger.ZERO.subTo(this, this);
@@ -264287,14 +264471,14 @@ var init_src100 = __esm({
264287
264471
  if (this.isDirectory()) {
264288
264472
  return 0n;
264289
264473
  }
264290
- let sum = 0n;
264474
+ let sum2 = 0n;
264291
264475
  this.blockSizes.forEach((size) => {
264292
- sum += size;
264476
+ sum2 += size;
264293
264477
  });
264294
264478
  if (this.data != null) {
264295
- sum += BigInt(this.data.length);
264479
+ sum2 += BigInt(this.data.length);
264296
264480
  }
264297
- return sum;
264481
+ return sum2;
264298
264482
  }
264299
264483
  /**
264300
264484
  * encode to protobuf Uint8Array
@@ -279788,7 +279972,7 @@ ${errText.slice(0, 1200)}`,
279788
279972
  if (space.evicted.length > 0) {
279789
279973
  this.emitProgress({
279790
279974
  stage: "download",
279791
- message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum, e2) => sum + e2.sizeBytes, 0))}) to make room for ${args.model}`
279975
+ message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum2, e2) => sum2 + e2.sizeBytes, 0))}) to make room for ${args.model}`
279792
279976
  });
279793
279977
  }
279794
279978
  } catch (err) {
@@ -280018,7 +280202,7 @@ ${errText.slice(0, 800)}`,
280018
280202
  if (space.evicted.length > 0) {
280019
280203
  this.emitProgress({
280020
280204
  stage: "download",
280021
- message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum, e2) => sum + e2.sizeBytes, 0))}) to make room for ${args.model}`
280205
+ message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum2, e2) => sum2 + e2.sizeBytes, 0))}) to make room for ${args.model}`
280022
280206
  });
280023
280207
  }
280024
280208
  } catch (err) {
@@ -282073,7 +282257,7 @@ if __name__ == "__main__":
282073
282257
  if (space.evicted.length > 0) {
282074
282258
  this.emitProgress({
282075
282259
  stage: "download",
282076
- message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum, e2) => sum + e2.sizeBytes, 0))}) to make room for ${args.model}`
282260
+ message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum2, e2) => sum2 + e2.sizeBytes, 0))}) to make room for ${args.model}`
282077
282261
  });
282078
282262
  }
282079
282263
  } catch (err) {
@@ -282398,7 +282582,7 @@ if __name__ == "__main__":
282398
282582
  if (space.evicted.length > 0) {
282399
282583
  this.emitProgress({
282400
282584
  stage: "download",
282401
- message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum, e2) => sum + e2.sizeBytes, 0))}) to make room for ${args.model}`
282585
+ message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum2, e2) => sum2 + e2.sizeBytes, 0))}) to make room for ${args.model}`
282402
282586
  });
282403
282587
  }
282404
282588
  } catch (err) {
@@ -282562,7 +282746,7 @@ function discoverLegacyMediaRepos(roots, opts = {}) {
282562
282746
  out.push({
282563
282747
  repoRoot,
282564
282748
  legacyDirs,
282565
- approxBytes: measure ? legacyDirs.reduce((sum, d2) => sum + approxDirBytes(d2), 0) : 0
282749
+ approxBytes: measure ? legacyDirs.reduce((sum2, d2) => sum2 + approxDirBytes(d2), 0) : 0
282566
282750
  });
282567
282751
  }
282568
282752
  out.sort((a2, b) => b.approxBytes - a2.approxBytes);
@@ -283768,8 +283952,8 @@ function normalizedEntropy(scores) {
283768
283952
  const positive2 = scores.filter((s2) => s2 > 0);
283769
283953
  if (positive2.length <= 1)
283770
283954
  return 0;
283771
- const sum = positive2.reduce((a2, b) => a2 + b, 0) || 1;
283772
- const probs = positive2.map((s2) => s2 / sum);
283955
+ const sum2 = positive2.reduce((a2, b) => a2 + b, 0) || 1;
283956
+ const probs = positive2.map((s2) => s2 / sum2);
283773
283957
  const h = -probs.reduce((a2, p2) => a2 + (p2 > 0 ? p2 * Math.log2(p2) : 0), 0);
283774
283958
  return h / Math.log2(positive2.length);
283775
283959
  }
@@ -286857,7 +287041,7 @@ ${llmAnnotation}` : result.llmContent;
286857
287041
  if (space.evicted.length > 0) {
286858
287042
  this.emitProgress({
286859
287043
  stage: "download",
286860
- message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum, e2) => sum + e2.sizeBytes, 0))}) to make room for ${args.candidate.model}`
287044
+ message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum2, e2) => sum2 + e2.sizeBytes, 0))}) to make room for ${args.candidate.model}`
286861
287045
  });
286862
287046
  }
286863
287047
  } catch (err) {
@@ -287022,7 +287206,7 @@ ${llmAnnotation}` : result.llmContent;
287022
287206
  if (space.evicted.length > 0) {
287023
287207
  this.emitProgress({
287024
287208
  stage: "download",
287025
- message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum, e2) => sum + e2.sizeBytes, 0))}) to make room for ${args.model}`
287209
+ message: `Evicted ${space.evicted.length} cached model(s) (${formatBytes(space.evicted.reduce((sum2, e2) => sum2 + e2.sizeBytes, 0))}) to make room for ${args.model}`
287026
287210
  });
287027
287211
  }
287028
287212
  } catch (err) {
@@ -372879,7 +373063,7 @@ ${lanes.join("\n")}
372879
373063
  if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) {
372880
373064
  return namedUnions[0];
372881
373065
  }
372882
- const namedTypesCount = reduceLeft(namedUnions, (sum, union) => sum + union.types.length, 0);
373066
+ const namedTypesCount = reduceLeft(namedUnions, (sum2, union) => sum2 + union.types.length, 0);
372883
373067
  if (namedTypesCount + reducedTypes.length === typeSet.length) {
372884
373068
  for (const t2 of namedUnions) {
372885
373069
  insertType(reducedTypes, t2);
@@ -449374,7 +449558,7 @@ ${lanes.join("\n")}
449374
449558
  reportCountStatistic("Lines of " + key, value2);
449375
449559
  }
449376
449560
  } else {
449377
- reportCountStatistic("Lines", reduceLeftIterator(lineCounts.values(), (sum, count) => sum + count, 0));
449561
+ reportCountStatistic("Lines", reduceLeftIterator(lineCounts.values(), (sum2, count) => sum2 + count, 0));
449378
449562
  }
449379
449563
  reportCountStatistic("Identifiers", program.getIdentifierCount());
449380
449564
  reportCountStatistic("Symbols", program.getSymbolCount());
@@ -466566,7 +466750,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
466566
466750
  }
466567
466751
  }
466568
466752
  return result;
466569
- function escapeRegExp2(str) {
466753
+ function escapeRegExp3(str) {
466570
466754
  return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&");
466571
466755
  }
466572
466756
  function getTodoCommentsRegExp() {
@@ -466574,7 +466758,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
466574
466758
  const multiLineCommentStart = /(?:\/\*+\s*)/.source;
466575
466759
  const anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source;
466576
466760
  const preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")";
466577
- const literals = "(?:" + map2(descriptors, (d2) => "(" + escapeRegExp2(d2.text) + ")").join("|") + ")";
466761
+ const literals = "(?:" + map2(descriptors, (d2) => "(" + escapeRegExp3(d2.text) + ")").join("|") + ")";
466578
466762
  const endOfLineOrEndOfComment = /(?:$|\*\/)/.source;
466579
466763
  const messageRemainder = /(?:.*?)/.source;
466580
466764
  const messagePortion = "(" + literals + messageRemainder + ")";
@@ -549124,7 +549308,7 @@ Context saved to: ${contextFile}`,
549124
549308
  }
549125
549309
  }
549126
549310
  profile.silenceSegments = silences;
549127
- const silenceTotal = silences.reduce((sum, item) => sum + item.durationSec, 0);
549311
+ const silenceTotal = silences.reduce((sum2, item) => sum2 + item.durationSec, 0);
549128
549312
  if (durationSec > 0) {
549129
549313
  profile.silencePercentage = Math.max(0, Math.min(100, silenceTotal / durationSec * 100));
549130
549314
  profile.activeSegments = this.complementSegments(silences, durationSec);
@@ -558719,12 +558903,349 @@ var init_validationPipeline = __esm({
558719
558903
  }
558720
558904
  });
558721
558905
 
558906
+ // packages/execution/dist/adaptive-edit-strategy.js
558907
+ function classifyEditFailure(error) {
558908
+ const e2 = (error ?? "").toLowerCase();
558909
+ if (!e2)
558910
+ return "other";
558911
+ if (e2.includes("hash") && (e2.includes("mismatch") || e2.includes("expected")))
558912
+ return "hash_mismatch";
558913
+ if (e2.includes("not found") || e2.includes("no such file"))
558914
+ return "not_found";
558915
+ if (e2.includes("must be unique") || e2.includes("ambiguous") || e2.includes("multiple matches") || e2.includes("appears"))
558916
+ return "ambiguous_match";
558917
+ if (e2.includes("old_string") && (e2.includes("not present") || e2.includes("no match") || e2.includes("could not find") || e2.includes("does not match")))
558918
+ return "no_match";
558919
+ return "other";
558920
+ }
558921
+ var DEFAULT_SWITCH_THRESHOLD, AdaptiveEditStrategy;
558922
+ var init_adaptive_edit_strategy = __esm({
558923
+ "packages/execution/dist/adaptive-edit-strategy.js"() {
558924
+ "use strict";
558925
+ DEFAULT_SWITCH_THRESHOLD = 2;
558926
+ AdaptiveEditStrategy = class {
558927
+ switchThreshold;
558928
+ files = /* @__PURE__ */ new Map();
558929
+ constructor(options2 = {}) {
558930
+ this.switchThreshold = Math.max(1, options2.switchThreshold ?? DEFAULT_SWITCH_THRESHOLD);
558931
+ }
558932
+ /** Record an edit outcome and return the recommendation for that file. */
558933
+ record(outcome) {
558934
+ const state = this.files.get(outcome.path) ?? {
558935
+ consecutiveFailures: 0,
558936
+ recommendedRewrite: false
558937
+ };
558938
+ if (outcome.mutated) {
558939
+ this.files.set(outcome.path, {
558940
+ consecutiveFailures: 0,
558941
+ recommendedRewrite: false
558942
+ });
558943
+ return { path: outcome.path, mode: "edit", consecutiveFailures: 0 };
558944
+ }
558945
+ state.consecutiveFailures += 1;
558946
+ state.lastFailureClass = classifyEditFailure(outcome.error);
558947
+ if (state.consecutiveFailures >= this.switchThreshold) {
558948
+ state.recommendedRewrite = true;
558949
+ }
558950
+ this.files.set(outcome.path, state);
558951
+ return this.recommendation(outcome.path, state);
558952
+ }
558953
+ /** Current recommendation for a file without recording a new outcome. */
558954
+ peek(path12) {
558955
+ const state = this.files.get(path12);
558956
+ if (!state)
558957
+ return { path: path12, mode: "edit", consecutiveFailures: 0 };
558958
+ return this.recommendation(path12, state);
558959
+ }
558960
+ /** Explicitly clear a file (e.g. after a successful full-file rewrite). */
558961
+ reset(path12) {
558962
+ this.files.delete(path12);
558963
+ }
558964
+ recommendation(path12, state) {
558965
+ if (state.recommendedRewrite) {
558966
+ return {
558967
+ path: path12,
558968
+ mode: "rewrite",
558969
+ consecutiveFailures: state.consecutiveFailures,
558970
+ lastFailureClass: state.lastFailureClass,
558971
+ guidance: `file_edit failed ${state.consecutiveFailures}× on ${path12} (${state.lastFailureClass}). Stop retrying the same edit. Read the current file, then replace it wholesale with file_write seeded from the current contents — do not re-issue file_edit on this file.`
558972
+ };
558973
+ }
558974
+ return {
558975
+ path: path12,
558976
+ mode: "edit",
558977
+ consecutiveFailures: state.consecutiveFailures,
558978
+ lastFailureClass: state.lastFailureClass
558979
+ };
558980
+ }
558981
+ };
558982
+ }
558983
+ });
558984
+
558985
+ // packages/execution/dist/boundary-verifier.js
558986
+ function isStructuralBoundary(path12) {
558987
+ if (HEADER_EXT.test(path12))
558988
+ return true;
558989
+ const base3 = path12.replace(/\\/g, "/");
558990
+ return CONTRACT_HINT.test(base3);
558991
+ }
558992
+ function detectLanguage2(path12) {
558993
+ const p2 = path12.toLowerCase();
558994
+ if (/\.(c|cc|cpp|cxx|h|hh|hpp|hxx|ino)$/.test(p2))
558995
+ return "cpp";
558996
+ if (/\.(ts|tsx|mts|cts)$/.test(p2))
558997
+ return "typescript";
558998
+ if (/\.py$/.test(p2))
558999
+ return "python";
559000
+ if (/\.rs$/.test(p2))
559001
+ return "rust";
559002
+ if (/\.go$/.test(p2))
559003
+ return "go";
559004
+ return "unknown";
559005
+ }
559006
+ function parseCompilerDiagnostics(text2, language = "unknown") {
559007
+ const out = [];
559008
+ if (!text2)
559009
+ return out;
559010
+ for (const raw of text2.split(/\r?\n/)) {
559011
+ const line = raw.trim();
559012
+ if (!line || !/error/i.test(line))
559013
+ continue;
559014
+ const loc = line.match(/^(.+?):(\d+):(?:\d+:)?\s*(?:fatal\s+)?error:\s*(.*)$/i);
559015
+ const file = loc?.[1];
559016
+ const lineNo = loc ? Number(loc[2]) : void 0;
559017
+ const msg = loc?.[3] ?? line;
559018
+ let kind = "other";
559019
+ let symbol3;
559020
+ if (/no declaration matches/i.test(msg)) {
559021
+ kind = "signature_mismatch";
559022
+ symbol3 = firstQuoted(msg) ?? extractCppQualified(msg);
559023
+ } else if (/conflicting declaration|redefinition of|redeclared/i.test(msg)) {
559024
+ kind = "duplicate_definition";
559025
+ symbol3 = firstQuoted(msg);
559026
+ } else if (/has no member named/i.test(msg)) {
559027
+ kind = "unknown_member";
559028
+ symbol3 = msg.match(/has no member named\s+'([^']+)'/i)?.[1] ?? firstQuoted(msg);
559029
+ } else if (/was not declared in this scope|has not been declared|undeclared/i.test(msg)) {
559030
+ kind = "unknown_symbol";
559031
+ symbol3 = firstQuoted(msg);
559032
+ } else if (/no matching function for call to/i.test(msg)) {
559033
+ kind = "signature_mismatch";
559034
+ symbol3 = firstQuoted(msg);
559035
+ } else if (/^ts\d+:/i.test(msg) || /property '.*' does not exist/i.test(msg)) {
559036
+ kind = /does not exist/i.test(msg) ? "unknown_member" : "type_error";
559037
+ symbol3 = firstQuoted(msg);
559038
+ } else {
559039
+ kind = "type_error";
559040
+ }
559041
+ out.push({ file, line: lineNo, symbol: symbol3, kind, message: msg });
559042
+ }
559043
+ return out;
559044
+ }
559045
+ function firstQuoted(s2) {
559046
+ const m2 = s2.match(/'([^']+)'/);
559047
+ return m2?.[1];
559048
+ }
559049
+ function extractCppQualified(s2) {
559050
+ const m2 = s2.match(/([A-Za-z_]\w*::[A-Za-z_]\w*)/);
559051
+ return m2?.[1];
559052
+ }
559053
+ function summarizeDiagnostics(diags) {
559054
+ if (diags.length === 0)
559055
+ return "boundary verified: no diagnostics";
559056
+ const byKind = /* @__PURE__ */ new Map();
559057
+ const symbols = /* @__PURE__ */ new Set();
559058
+ for (const d2 of diags) {
559059
+ byKind.set(d2.kind, (byKind.get(d2.kind) ?? 0) + 1);
559060
+ if (d2.symbol)
559061
+ symbols.add(d2.symbol);
559062
+ }
559063
+ const kinds = [...byKind.entries()].map(([k, n2]) => `${k}×${n2}`).join(", ");
559064
+ const syms = [...symbols].slice(0, 6).join(", ");
559065
+ return `boundary FAILED: ${diags.length} diagnostic(s) [${kinds}]${syms ? ` — symbols: ${syms}` : ""}. Fix the contract before editing unrelated files.`;
559066
+ }
559067
+ async function verifyBoundary(input) {
559068
+ const language = input.language ?? detectLanguage2(input.path);
559069
+ if (!input.force && !isStructuralBoundary(input.path)) {
559070
+ return {
559071
+ ok: true,
559072
+ tool: "none",
559073
+ scope: input.path,
559074
+ skipped: true,
559075
+ diagnostics: [],
559076
+ summary: "not a structural boundary — verification skipped"
559077
+ };
559078
+ }
559079
+ const result = await input.runner({
559080
+ projectRoot: input.projectRoot,
559081
+ scope: input.path
559082
+ });
559083
+ if (result.skipped) {
559084
+ return {
559085
+ ok: true,
559086
+ tool: result.tool,
559087
+ scope: input.path,
559088
+ skipped: true,
559089
+ diagnostics: [],
559090
+ summary: `no verifier configured for ${input.path} — skipped`
559091
+ };
559092
+ }
559093
+ const diagnostics = parseCompilerDiagnostics(`${result.stdout}
559094
+ ${result.stderr}`, language);
559095
+ const ok3 = result.success && diagnostics.length === 0;
559096
+ return {
559097
+ ok: ok3,
559098
+ tool: result.tool,
559099
+ scope: input.path,
559100
+ skipped: false,
559101
+ diagnostics,
559102
+ summary: ok3 ? "boundary verified: no diagnostics" : summarizeDiagnostics(diagnostics)
559103
+ };
559104
+ }
559105
+ var HEADER_EXT, CONTRACT_HINT;
559106
+ var init_boundary_verifier = __esm({
559107
+ "packages/execution/dist/boundary-verifier.js"() {
559108
+ "use strict";
559109
+ HEADER_EXT = /\.(h|hh|hpp|hxx|d\.ts)$/i;
559110
+ CONTRACT_HINT = /(^|\/)(types|interfaces?|contract|schema|protocol|api|pal)\b/i;
559111
+ }
559112
+ });
559113
+
559114
+ // packages/execution/dist/harness-plan.js
559115
+ function pathEscapesRoot(p2) {
559116
+ if (!p2)
559117
+ return true;
559118
+ if (p2.startsWith("/") || p2.startsWith("~"))
559119
+ return true;
559120
+ const parts = [];
559121
+ for (const seg of p2.split("/")) {
559122
+ if (seg === "" || seg === ".")
559123
+ continue;
559124
+ if (seg === "..") {
559125
+ if (parts.length === 0)
559126
+ return true;
559127
+ parts.pop();
559128
+ continue;
559129
+ }
559130
+ parts.push(seg);
559131
+ }
559132
+ return false;
559133
+ }
559134
+ function guardShell(command) {
559135
+ for (const re of FORBIDDEN_SHELL) {
559136
+ if (re.test(command))
559137
+ return `forbidden shell pattern: ${re}`;
559138
+ }
559139
+ return null;
559140
+ }
559141
+ function sh(s2) {
559142
+ return `'${s2.replace(/'/g, `'\\''`)}'`;
559143
+ }
559144
+ function planHarnessBatch(ops, opts) {
559145
+ const accepted = [];
559146
+ const rejected = [];
559147
+ for (const op of ops) {
559148
+ const reject = (reason) => rejected.push({ op, reason });
559149
+ if (op.kind === "shell") {
559150
+ if (!op.command) {
559151
+ reject("shell op missing command");
559152
+ continue;
559153
+ }
559154
+ const bad = guardShell(op.command);
559155
+ if (bad) {
559156
+ reject(bad);
559157
+ continue;
559158
+ }
559159
+ accepted.push(op);
559160
+ continue;
559161
+ }
559162
+ if (op.kind === "remove" && !opts.allowRemove) {
559163
+ reject("remove not permitted (set allowRemove to enable)");
559164
+ continue;
559165
+ }
559166
+ const targets = [op.path, op.to].filter((p2) => Boolean(p2));
559167
+ if (targets.length === 0) {
559168
+ reject(`${op.kind} op missing path`);
559169
+ continue;
559170
+ }
559171
+ const escaping = targets.find((t2) => pathEscapesRoot(t2));
559172
+ if (escaping) {
559173
+ reject(`path escapes project root: ${escaping}`);
559174
+ continue;
559175
+ }
559176
+ if (op.kind === "write" && op.content === void 0) {
559177
+ reject("write op missing content");
559178
+ continue;
559179
+ }
559180
+ accepted.push(op);
559181
+ }
559182
+ const script = accepted.length ? buildScript(accepted, opts) : "";
559183
+ const ok3 = rejected.length === 0 && accepted.length === ops.length;
559184
+ return {
559185
+ ok: ok3,
559186
+ script,
559187
+ accepted,
559188
+ rejected,
559189
+ summary: ok3 ? `harness cell: ${accepted.length} op(s), all validated` : `harness plan: ${accepted.length} accepted, ${rejected.length} rejected — ${rejected.map((r2) => r2.reason).join("; ")}`
559190
+ };
559191
+ }
559192
+ function buildScript(ops, opts) {
559193
+ const lines = [
559194
+ "set -euo pipefail",
559195
+ `cd ${sh(opts.projectRoot)}`
559196
+ ];
559197
+ for (const op of ops) {
559198
+ switch (op.kind) {
559199
+ case "read":
559200
+ lines.push(`cat ${sh(op.path)}`);
559201
+ break;
559202
+ case "mkdir":
559203
+ lines.push(`mkdir -p ${sh(op.path)}`);
559204
+ break;
559205
+ case "move":
559206
+ lines.push(`mkdir -p "$(dirname ${sh(op.to)})" && mv ${sh(op.path)} ${sh(op.to)}`);
559207
+ break;
559208
+ case "remove":
559209
+ lines.push(`rm -f ${sh(op.path)}`);
559210
+ break;
559211
+ case "write": {
559212
+ const b64 = Buffer.from(op.content ?? "", "utf8").toString("base64");
559213
+ lines.push(`mkdir -p "$(dirname ${sh(op.path)})"`);
559214
+ lines.push(`printf %s ${sh(b64)} | base64 -d > ${sh(op.path)}`);
559215
+ break;
559216
+ }
559217
+ case "shell":
559218
+ lines.push(op.command);
559219
+ break;
559220
+ }
559221
+ }
559222
+ return lines.join("\n") + "\n";
559223
+ }
559224
+ var FORBIDDEN_SHELL;
559225
+ var init_harness_plan = __esm({
559226
+ "packages/execution/dist/harness-plan.js"() {
559227
+ "use strict";
559228
+ FORBIDDEN_SHELL = [
559229
+ /\bsudo\b/,
559230
+ /\b(curl|wget|nc|ncat|telnet|ssh|scp|sftp|rsync)\b/,
559231
+ /\b(ftp|git\s+push|git\s+clone|npm\s+publish|pip\s+install)\b/,
559232
+ /rm\s+-rf\s+\/(?:\s|$)/,
559233
+ /[:{]\s*\|\s*[:{]\s*&/,
559234
+ // fork bomb-ish
559235
+ />\s*\/dev\/(sd|nvme|mmcblk|disk)/,
559236
+ /\bmkfs\b|\bdd\s+if=/,
559237
+ /\bchmod\s+777\b/
559238
+ ];
559239
+ }
559240
+ });
559241
+
558722
559242
  // packages/execution/dist/index.js
558723
559243
  var dist_exports2 = {};
558724
559244
  __export(dist_exports2, {
558725
559245
  AUDIO_GENERATION_MODEL_PRESETS: () => AUDIO_GENERATION_MODEL_PRESETS,
558726
559246
  AVAdapterRegistry: () => AVAdapterRegistry,
558727
559247
  AVComprehendTool: () => AVComprehendTool,
559248
+ AdaptiveEditStrategy: () => AdaptiveEditStrategy,
558728
559249
  AgendaTool: () => AgendaTool,
558729
559250
  AgentTool: () => AgentTool,
558730
559251
  AiwgHealthTool: () => AiwgHealthTool,
@@ -558925,6 +559446,7 @@ __export(dist_exports2, {
558925
559446
  canInvokeTool: () => canInvokeTool,
558926
559447
  checkConstraints: () => checkConstraints,
558927
559448
  checkDesktopDeps: () => checkDesktopDeps,
559449
+ classifyEditFailure: () => classifyEditFailure,
558928
559450
  classifyTool: () => classifyTool,
558929
559451
  clearExploreNotes: () => clearExploreNotes,
558930
559452
  clearImportGraphCache: () => clearImportGraphCache,
@@ -558959,6 +559481,7 @@ __export(dist_exports2, {
558959
559481
  deleteTodos: () => deleteTodos,
558960
559482
  detectCudaDevices: () => detectCudaDevices,
558961
559483
  detectElevationMethod: () => detectElevationMethod,
559484
+ detectLanguage: () => detectLanguage2,
558962
559485
  detectLegacyCaches: () => detectLegacyCaches,
558963
559486
  detectSceneCuts: () => detectSceneCuts,
558964
559487
  detectSearchProvider: () => detectSearchProvider,
@@ -559062,6 +559585,7 @@ __export(dist_exports2, {
559062
559585
  isMcpMarkdown: () => isMcpMarkdown,
559063
559586
  isProcessAlive: () => isProcessAlive,
559064
559587
  isProcessIdentityVerified: () => isProcessIdentityVerified,
559588
+ isStructuralBoundary: () => isStructuralBoundary,
559065
559589
  isVideoPresetGated: () => isVideoPresetGated,
559066
559590
  killAllFullSubAgents: () => killAllFullSubAgents,
559067
559591
  killProcess: () => killProcess,
@@ -559112,11 +559636,13 @@ __export(dist_exports2, {
559112
559636
  normalizedEntropy: () => normalizedEntropy,
559113
559637
  omniusHomeDir: () => omniusHomeDir,
559114
559638
  packetPath: () => packetPath,
559639
+ parseCompilerDiagnostics: () => parseCompilerDiagnostics,
559115
559640
  parseCudaComputeCapability: () => parseCudaComputeCapability,
559116
559641
  parseCudaDeviceInfo: () => parseCudaDeviceInfo,
559117
559642
  parseMcpMarkdown: () => parseMcpMarkdown,
559118
559643
  parseMcpToolName: () => parseMcpToolName,
559119
559644
  parseSponsorMediaCapability: () => parseSponsorMediaCapability,
559645
+ planHarnessBatch: () => planHarnessBatch,
559120
559646
  planInspections: () => planInspections,
559121
559647
  playSoundFile: () => playSoundFile,
559122
559648
  predictNextBbox: () => predictNextBbox,
@@ -559202,6 +559728,7 @@ __export(dist_exports2, {
559202
559728
  startProcessLeaseSweeper: () => startProcessLeaseSweeper,
559203
559729
  stopFullSubAgent: () => stopFullSubAgent,
559204
559730
  stopProcessLease: () => stopProcessLease,
559731
+ summarizeDiagnostics: () => summarizeDiagnostics,
559205
559732
  summarizeLog: () => summarizeLog,
559206
559733
  summarizeProvenance: () => summarizeProvenance,
559207
559734
  sweepProcessLeases: () => sweepProcessLeases,
@@ -559221,6 +559748,7 @@ __export(dist_exports2, {
559221
559748
  venvExe: () => venvExe,
559222
559749
  venvPip: () => venvPip,
559223
559750
  venvPython: () => venvPython,
559751
+ verifyBoundary: () => verifyBoundary,
559224
559752
  verifyStorePermissions: () => verifyStorePermissions,
559225
559753
  videoDiffusersVenvDir: () => videoDiffusersVenvDir,
559226
559754
  videoGenerationDir: () => videoGenerationDir,
@@ -559399,6 +559927,9 @@ var init_dist5 = __esm({
559399
559927
  init_process_kill();
559400
559928
  init_constraints();
559401
559929
  init_validationPipeline();
559930
+ init_adaptive_edit_strategy();
559931
+ init_boundary_verifier();
559932
+ init_harness_plan();
559402
559933
  }
559403
559934
  });
559404
559935
 
@@ -567962,7 +568493,7 @@ function regenerate(opts) {
567962
568493
  } else if (files.length === 0) {
567963
568494
  lines.push(` No files found in workspace (excluding ignored paths).`);
567964
568495
  } else {
567965
- const totalBytes = files.reduce((sum, f2) => sum + f2.bytes, 0);
568496
+ const totalBytes = files.reduce((sum2, f2) => sum2 + f2.bytes, 0);
567966
568497
  lines.push(` ${files.length} file(s)${truncated ? " (truncated — more exist)" : ""}, total ${humanBytes2(totalBytes)}.`);
567967
568498
  if (lastWriteFile) {
567968
568499
  lines.push(` Most recently modified: ${lastWriteFile.rel} (${humanBytes2(lastWriteFile.bytes)}, ${ago(nowMs - lastWriteFile.mtimeMs)}).`);
@@ -571616,7 +572147,7 @@ function textToHashEmbedding(text2, dimensions = DEFAULT_HASH_DIMS) {
571616
572147
  const sign2 = (h & 2147483648) === 0 ? 1 : -1;
571617
572148
  vec[idx] += sign2;
571618
572149
  }
571619
- const norm = Math.sqrt(vec.reduce((sum, v) => sum + v * v, 0));
572150
+ const norm = Math.sqrt(vec.reduce((sum2, v) => sum2 + v * v, 0));
571620
572151
  if (!norm)
571621
572152
  return vec;
571622
572153
  return vec.map((v) => Math.round(v / norm * 1e6) / 1e6);
@@ -574107,7 +574638,7 @@ function analyzeContextWindowDumpRequest(request) {
574107
574638
  compactedDiscoveryChars += chars;
574108
574639
  }
574109
574640
  }
574110
- const toolSchemaChars = tools.reduce((sum, tool) => sum + JSON.stringify(tool).length, 0);
574641
+ const toolSchemaChars = tools.reduce((sum2, tool) => sum2 + JSON.stringify(tool).length, 0);
574111
574642
  const structuralSignalChars = userChars + activeEvidenceChars + activeContextFrameChars + compactedDiscoveryChars + assistantChars;
574112
574643
  const structuralNoiseCandidateChars = rawDiscoveryToolChars;
574113
574644
  const ratio = structuralNoiseCandidateChars > 0 ? Number((structuralSignalChars / structuralNoiseCandidateChars).toFixed(3)) : null;
@@ -575711,6 +576242,9 @@ var init_focusSupervisor = __esm({
575711
576242
  lastReason = "";
575712
576243
  lastContext = null;
575713
576244
  failureFamilies = /* @__PURE__ */ new Map();
576245
+ convergenceBreaker = null;
576246
+ /** WO-3: set when a mutation lands, consumed by the next observed failure. */
576247
+ sawMutationSinceFailure = false;
575714
576248
  ignoredDirectiveStreak = 0;
575715
576249
  lastIgnoredDirectiveTurn = null;
575716
576250
  availableTools = null;
@@ -575719,6 +576253,7 @@ var init_focusSupervisor = __esm({
575719
576253
  this.modelTier = options2.modelTier ?? "large";
575720
576254
  this.repeatGateMax = Math.max(0, Math.floor(options2.repeatGateMax ?? 3));
575721
576255
  this.availableTools = options2.availableTools ? new Set(Array.from(options2.availableTools)) : null;
576256
+ this.convergenceBreaker = options2.convergenceBreaker ?? null;
575722
576257
  }
575723
576258
  get enabled() {
575724
576259
  return this.mode !== "off";
@@ -575907,6 +576442,7 @@ var init_focusSupervisor = __esm({
575907
576442
  if (!this.enabled)
575908
576443
  return;
575909
576444
  if (input.mutated) {
576445
+ this.sawMutationSinceFailure = true;
575910
576446
  this.clearSatisfiedDirective("mutation landed", input.turn);
575911
576447
  return;
575912
576448
  }
@@ -575996,6 +576532,28 @@ var init_focusSupervisor = __esm({
575996
576532
  forbiddenActionFamilies: shellFailure ? [actionFamily(input.toolName, input.args)] : [actionFamily(input.toolName, input.args)]
575997
576533
  });
575998
576534
  }
576535
+ if (this.convergenceBreaker) {
576536
+ const verdict = this.convergenceBreaker.observe({
576537
+ family,
576538
+ sessionCount: next.count,
576539
+ turn: input.turn,
576540
+ sample: next.sample,
576541
+ errorClass: next.errorClass,
576542
+ mutatedSinceLast: this.sawMutationSinceFailure
576543
+ });
576544
+ this.sawMutationSinceFailure = false;
576545
+ if (verdict.tier === "abandon") {
576546
+ this.markTerminalIncomplete(verdict.reason, input.turn);
576547
+ } else if (verdict.tier === "stalled") {
576548
+ this.setDirective({
576549
+ turn: input.turn,
576550
+ state: "forced_replan",
576551
+ reason: verdict.reason,
576552
+ requiredNextAction: this.resolveRequiredNextAction("run_verification"),
576553
+ forbiddenActionFamilies: [actionFamily(input.toolName, input.args)]
576554
+ });
576555
+ }
576556
+ }
575999
576557
  }
576000
576558
  markCompletionBlocked(input) {
576001
576559
  if (!this.enabled)
@@ -576844,7 +577402,7 @@ var init_resolution_memory = __esm({
576844
577402
 
576845
577403
  // packages/orchestrator/dist/contextEngine.js
576846
577404
  function estimateTokens3(messages2) {
576847
- const chars = messages2.reduce((sum, message2) => sum + message2.content.length + message2.role.length + (message2.name?.length ?? 0), 0);
577405
+ const chars = messages2.reduce((sum2, message2) => sum2 + message2.content.length + message2.role.length + (message2.name?.length ?? 0), 0);
576848
577406
  return Math.ceil(chars / 4);
576849
577407
  }
576850
577408
  function evidenceMessage(folded) {
@@ -578262,7 +578820,7 @@ function buildFallbackSemanticChunks(items, maxChunks = 7) {
578262
578820
  const bucketItems = normalized.filter((item) => bucket.kinds.includes(item.kind)).sort((a2, b) => (b.priority ?? 0) - (a2.priority ?? 0));
578263
578821
  if (bucketItems.length === 0)
578264
578822
  continue;
578265
- const rawChars = bucketItems.reduce((sum, item) => sum + item.content.length, 0);
578823
+ const rawChars = bucketItems.reduce((sum2, item) => sum2 + item.content.length, 0);
578266
578824
  const lines = bucketItems.slice(0, 5).map((item) => {
578267
578825
  const oneLine = item.content.replace(/\s+/g, " ").trim();
578268
578826
  return `- ${item.label}: ${oneLine.slice(0, 360)}`;
@@ -580881,7 +581439,7 @@ ${wbCtx}`,
580881
581439
  } catch {
580882
581440
  }
580883
581441
  const assembled = sections.map((s2) => s2.content).join("");
580884
- const totalTokenEstimate = sections.reduce((sum, s2) => sum + s2.tokenEstimate, 0);
581442
+ const totalTokenEstimate = sections.reduce((sum2, s2) => sum2 + s2.tokenEstimate, 0);
580885
581443
  return {
580886
581444
  assembled,
580887
581445
  sections: sections.map((s2) => ({
@@ -580991,7 +581549,7 @@ Your hypotheses MUST address this specific error, not generic causes.
580991
581549
  gcSystemMessages(messages2) {
580992
581550
  const ctxTokens = this.options.contextWindowSize ?? 0;
580993
581551
  const systemMaxChars = ctxTokens > 0 ? Math.max(24e3, Math.floor(ctxTokens * 4 * 0.45)) : 0;
580994
- const beforeChars = messages2.reduce((sum, m2) => sum + (m2.role === "system" && typeof m2.content === "string" ? m2.content.length : 0), 0);
581552
+ const beforeChars = messages2.reduce((sum2, m2) => sum2 + (m2.role === "system" && typeof m2.content === "string" ? m2.content.length : 0), 0);
580995
581553
  const result = this._signalExtractor.distillSystemMessages(messages2, {
580996
581554
  maxSystemChars: systemMaxChars || void 0,
580997
581555
  preserveFirstSystem: true,
@@ -581004,7 +581562,7 @@ Your hypotheses MUST address this specific error, not generic causes.
581004
581562
  messages2.push(...result.messages);
581005
581563
  const dropped = result.stats.droppedNoise + result.stats.droppedDuplicate + result.stats.droppedBudget;
581006
581564
  if (dropped > 0) {
581007
- const afterChars = messages2.reduce((sum, m2) => sum + (m2.role === "system" && typeof m2.content === "string" ? m2.content.length : 0), 0);
581565
+ const afterChars = messages2.reduce((sum2, m2) => sum2 + (m2.role === "system" && typeof m2.content === "string" ? m2.content.length : 0), 0);
581008
581566
  this.emit({
581009
581567
  type: "status",
581010
581568
  content: `Signal distillation dropped ${dropped} system message(s) (noise=${result.stats.droppedNoise}, dup=${result.stats.droppedDuplicate}, budget=${result.stats.droppedBudget}; ${beforeChars} -> ${afterChars} chars)`,
@@ -584107,7 +584665,7 @@ ${latest.output || ""}`.trim();
584107
584665
  maxLines: artifactLines,
584108
584666
  sortBy: "recent"
584109
584667
  });
584110
- const totalBytes = scan.files.reduce((sum, file) => sum + file.bytes, 0);
584668
+ const totalBytes = scan.files.reduce((sum2, file) => sum2 + file.bytes, 0);
584111
584669
  const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
584112
584670
  const focusSnapshot = this._focusSupervisor?.snapshot();
584113
584671
  const recentActions = this._recentToolActionsForWorldState().slice(-12).map((item) => ({
@@ -588876,7 +589434,7 @@ ${memoryLines.join("\n")}`
588876
589434
  estimatedTokens += Math.ceil((choiceContent.length + choiceArgs.length) / 4);
588877
589435
  const IMAGE_TOKEN_ESTIMATE = 1500;
588878
589436
  const imageBase64Pattern = /\[IMAGE_BASE64:[^\]]+\]/g;
588879
- const estimatedContextTokens = Math.ceil(compacted.reduce((sum, m2) => {
589437
+ const estimatedContextTokens = Math.ceil(compacted.reduce((sum2, m2) => {
588880
589438
  let chars = 0;
588881
589439
  let imageCount = 0;
588882
589440
  if (typeof m2.content === "string") {
@@ -588898,7 +589456,7 @@ ${memoryLines.join("\n")}`
588898
589456
  for (const tc of m2.tool_calls)
588899
589457
  chars += tc.function.arguments?.length ?? 0;
588900
589458
  }
588901
- return sum + chars + imageCount * IMAGE_TOKEN_ESTIMATE * 4;
589459
+ return sum2 + chars + imageCount * IMAGE_TOKEN_ESTIMATE * 4;
588902
589460
  }, 0) / 4);
588903
589461
  this.emit({
588904
589462
  type: "token_usage",
@@ -592632,7 +593190,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
592632
593190
  const choiceArgs2 = response.choices[0]?.message?.toolCalls?.map((tc) => JSON.stringify(tc.arguments)).join("") ?? "";
592633
593191
  estimatedTokens += Math.ceil((choiceContent2.length + choiceArgs2.length) / 4);
592634
593192
  const _bfImgPat = /\[IMAGE_BASE64:[^\]]+\]/g;
592635
- const bfEstCtx = Math.ceil(compactedMsgs.reduce((sum, m2) => {
593193
+ const bfEstCtx = Math.ceil(compactedMsgs.reduce((sum2, m2) => {
592636
593194
  let chars = 0;
592637
593195
  let imgCount = 0;
592638
593196
  if (typeof m2.content === "string") {
@@ -592653,7 +593211,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
592653
593211
  for (const tc of m2.tool_calls)
592654
593212
  chars += tc.function.arguments?.length ?? 0;
592655
593213
  }
592656
- return sum + chars + imgCount * 1500 * 4;
593214
+ return sum2 + chars + imgCount * 1500 * 4;
592657
593215
  }, 0) / 4);
592658
593216
  this.emit({
592659
593217
  type: "token_usage",
@@ -595658,7 +596216,7 @@ Describe what you see and integrate this into your current approach.` : "[User s
595658
596216
  if (messages2.length < 3)
595659
596217
  return messages2;
595660
596218
  const _compImgPat = /\[IMAGE_BASE64:[^\]]+\]/g;
595661
- const totalChars = messages2.reduce((sum, m2) => {
596219
+ const totalChars = messages2.reduce((sum2, m2) => {
595662
596220
  let chars = 0;
595663
596221
  if (typeof m2.content === "string") {
595664
596222
  const imgMatches = m2.content.match(_compImgPat);
@@ -595680,7 +596238,7 @@ Describe what you see and integrate this into your current approach.` : "[User s
595680
596238
  chars += tc.function.name?.length ?? 0;
595681
596239
  }
595682
596240
  }
595683
- return sum + chars;
596241
+ return sum2 + chars;
595684
596242
  }, 0);
595685
596243
  const estimatedTokens = totalChars / 4;
595686
596244
  const limits = this.contextLimits();
@@ -596151,7 +596709,7 @@ ${content.slice(0, 8e3)}
596151
596709
  const ctxWindow = this.options.contextWindowSize;
596152
596710
  if (ctxWindow > 0) {
596153
596711
  const _safetyImgPat = /\[IMAGE_BASE64:[^\]]+\]/g;
596154
- const estimateResult = (msgs) => msgs.reduce((sum, m2) => {
596712
+ const estimateResult = (msgs) => msgs.reduce((sum2, m2) => {
596155
596713
  let chars = 0;
596156
596714
  let imgCount = 0;
596157
596715
  if (typeof m2.content === "string") {
@@ -596172,7 +596730,7 @@ ${content.slice(0, 8e3)}
596172
596730
  for (const tc of m2.tool_calls)
596173
596731
  chars += tc.function.arguments?.length ?? 0;
596174
596732
  }
596175
- return sum + chars + imgCount * 1500 * 4;
596733
+ return sum2 + chars + imgCount * 1500 * 4;
596176
596734
  }, 0) / 4;
596177
596735
  const safetyTarget = Math.floor(ctxWindow * 0.65);
596178
596736
  let trimmedRecent = [...filteredRecent];
@@ -600787,7 +601345,7 @@ var init_workEvaluator = __esm({
600787
601345
  feedback: pd?.feedback ?? ""
600788
601346
  };
600789
601347
  });
600790
- const overallScore = dimensions.reduce((sum, d2) => sum + d2.score / 10 * d2.weight, 0);
601348
+ const overallScore = dimensions.reduce((sum2, d2) => sum2 + d2.score / 10 * d2.weight, 0);
600791
601349
  return {
600792
601350
  overallScore,
600793
601351
  dimensions,
@@ -601233,7 +601791,7 @@ function cascadeBudget(decisions, config) {
601233
601791
  for (const tier of ["A", "B", "C", "D"]) {
601234
601792
  const budget = config.budgetsTokens[tier];
601235
601793
  const inTier = decisions.filter((decision2) => decision2.tier === tier).sort((a2, b) => a2.item.weight - b.item.weight || b.item.id.localeCompare(a2.item.id));
601236
- let tokens = inTier.reduce((sum, decision2) => sum + decision2.estimatedTokens, 0);
601794
+ let tokens = inTier.reduce((sum2, decision2) => sum2 + decision2.estimatedTokens, 0);
601237
601795
  while (tokens > budget && inTier.length > 0) {
601238
601796
  const demoted = inTier.shift();
601239
601797
  const oldTokens = demoted.estimatedTokens;
@@ -601308,7 +601866,7 @@ function renderPlan(decisions, includeHeader) {
601308
601866
  const memoryPrefix = stable.filter((decision2) => decision2.cacheEligible).map((decision2) => decision2.renderedText).join("\n\n");
601309
601867
  const renderedText = renderedParts.join("\n\n");
601310
601868
  const tokensEmitted = renderedTokenTotal(decisions);
601311
- const tokensBaselineNoWeighting = decisions.reduce((sum, decision2) => sum + decision2.item.contentTokens, 0);
601869
+ const tokensBaselineNoWeighting = decisions.reduce((sum2, decision2) => sum2 + decision2.item.contentTokens, 0);
601312
601870
  const tierDistribution = tierDistributionFor(decisions);
601313
601871
  return {
601314
601872
  decisions,
@@ -601394,7 +601952,7 @@ function stabilityFor(id2, options2) {
601394
601952
  return options2.defaultStability ?? "new";
601395
601953
  }
601396
601954
  function renderedTokenTotal(decisions) {
601397
- return decisions.filter((decision2) => decision2.tier !== "E").reduce((sum, decision2) => sum + decision2.estimatedTokens, 0);
601955
+ return decisions.filter((decision2) => decision2.tier !== "E").reduce((sum2, decision2) => sum2 + decision2.estimatedTokens, 0);
601398
601956
  }
601399
601957
  function tierDistributionFor(decisions) {
601400
601958
  const distribution = { A: 0, B: 0, C: 0, D: 0, E: 0 };
@@ -605672,6 +606230,146 @@ var init_dedup_gate = __esm({
605672
606230
  }
605673
606231
  });
605674
606232
 
606233
+ // packages/orchestrator/dist/convergence-breaker.js
606234
+ var InMemoryConvergenceStore, DEFAULTS2, ConvergenceBreaker;
606235
+ var init_convergence_breaker = __esm({
606236
+ "packages/orchestrator/dist/convergence-breaker.js"() {
606237
+ "use strict";
606238
+ InMemoryConvergenceStore = class {
606239
+ map = /* @__PURE__ */ new Map();
606240
+ load(family) {
606241
+ return this.map.get(family) ?? null;
606242
+ }
606243
+ save(entry) {
606244
+ this.map.set(entry.family, { ...entry });
606245
+ }
606246
+ /** Test/telemetry helper. */
606247
+ entries() {
606248
+ return [...this.map.values()];
606249
+ }
606250
+ };
606251
+ DEFAULTS2 = { warnRound: 2, stallRound: 3, abandonRound: 5 };
606252
+ ConvergenceBreaker = class {
606253
+ warnRound;
606254
+ stallRound;
606255
+ abandonRound;
606256
+ store;
606257
+ /** Live per-family total (session + carry) for snapshotting. */
606258
+ live = /* @__PURE__ */ new Map();
606259
+ /**
606260
+ * Prior-session rounds, captured from the store exactly once per family the
606261
+ * first time it is seen this session. Never re-read mid-session, so the
606262
+ * breaker's own persisted writes are not double-counted back into the total.
606263
+ */
606264
+ baseline = /* @__PURE__ */ new Map();
606265
+ /** Progress decay accumulated this session (one per productive mutation). */
606266
+ decay = /* @__PURE__ */ new Map();
606267
+ constructor(options2 = {}) {
606268
+ this.warnRound = Math.max(1, options2.warnRound ?? DEFAULTS2.warnRound);
606269
+ this.stallRound = Math.max(this.warnRound + 1, options2.stallRound ?? DEFAULTS2.stallRound);
606270
+ this.abandonRound = Math.max(this.stallRound + 1, options2.abandonRound ?? DEFAULTS2.abandonRound);
606271
+ this.store = options2.store ?? new InMemoryConvergenceStore();
606272
+ }
606273
+ /**
606274
+ * Observe a failure and return the convergence verdict. Idempotent per
606275
+ * (family, sessionCount): callers pass the focusSupervisor's monotonically
606276
+ * increasing session count, so re-observing the same count does not
606277
+ * double-advance the cliff.
606278
+ */
606279
+ observe(obs) {
606280
+ if (!this.baseline.has(obs.family)) {
606281
+ const carry2 = this.store.load(obs.family);
606282
+ this.baseline.set(obs.family, carry2?.rounds ?? 0);
606283
+ }
606284
+ const base3 = this.baseline.get(obs.family) ?? 0;
606285
+ let dec = this.decay.get(obs.family) ?? 0;
606286
+ if (obs.mutatedSinceLast) {
606287
+ dec += 1;
606288
+ this.decay.set(obs.family, dec);
606289
+ }
606290
+ const sessionCount = Math.max(1, obs.sessionCount);
606291
+ const totalRounds = Math.max(1, base3 + sessionCount - dec);
606292
+ const tier = this.tierFor(totalRounds);
606293
+ this.live.set(obs.family, { totalRounds, tier });
606294
+ const carry = this.store.load(obs.family);
606295
+ this.store.save({
606296
+ family: obs.family,
606297
+ rounds: Math.max(carry?.rounds ?? 0, totalRounds),
606298
+ lastSample: obs.sample ?? carry?.lastSample,
606299
+ updatedAtMs: Date.now()
606300
+ });
606301
+ return this.verdict(obs.family, totalRounds, tier, obs.sample);
606302
+ }
606303
+ /** Clear a family's carry when its underlying work is verified/complete. */
606304
+ resolve(family) {
606305
+ this.live.delete(family);
606306
+ this.baseline.delete(family);
606307
+ this.decay.delete(family);
606308
+ this.store.save({ family, rounds: 0, updatedAtMs: Date.now() });
606309
+ }
606310
+ snapshot() {
606311
+ return {
606312
+ families: [...this.live.entries()].map(([family, v]) => ({
606313
+ family,
606314
+ totalRounds: v.totalRounds,
606315
+ tier: v.tier
606316
+ }))
606317
+ };
606318
+ }
606319
+ tierFor(totalRounds) {
606320
+ if (totalRounds >= this.abandonRound)
606321
+ return "abandon";
606322
+ if (totalRounds >= this.stallRound)
606323
+ return "stalled";
606324
+ if (totalRounds >= this.warnRound)
606325
+ return "converging_warn";
606326
+ return "healthy";
606327
+ }
606328
+ verdict(family, totalRounds, tier, sample) {
606329
+ const suffix = sample ? `: ${sample}` : "";
606330
+ switch (tier) {
606331
+ case "abandon":
606332
+ return {
606333
+ tier,
606334
+ tripped: true,
606335
+ totalRounds,
606336
+ family,
606337
+ reason: `failure family "${family}" has not converged after ${totalRounds} rounds (>= ${this.abandonRound}); this trajectory is dead — stop iterating and report incomplete or regenerate from the locked contract${suffix}`,
606338
+ recommendedAction: "report_incomplete"
606339
+ };
606340
+ case "stalled":
606341
+ return {
606342
+ tier,
606343
+ tripped: true,
606344
+ totalRounds,
606345
+ family,
606346
+ reason: `failure family "${family}" stalled after ${totalRounds} rounds (>= ${this.stallRound}); stop patching and regenerate the incoherent layer from the locked contract instead of editing again${suffix}`,
606347
+ recommendedAction: "regenerate_incoherent_layer"
606348
+ };
606349
+ case "converging_warn":
606350
+ return {
606351
+ tier,
606352
+ tripped: false,
606353
+ totalRounds,
606354
+ family,
606355
+ reason: `failure family "${family}" repeated ${totalRounds} rounds; ~75% of reachable improvement is already spent — change approach on the next attempt${suffix}`,
606356
+ recommendedAction: "replan"
606357
+ };
606358
+ default:
606359
+ return {
606360
+ tier,
606361
+ tripped: false,
606362
+ totalRounds,
606363
+ family,
606364
+ reason: `failure family "${family}" at ${totalRounds} round(s)`,
606365
+ recommendedAction: "continue"
606366
+ };
606367
+ }
606368
+ }
606369
+ };
606370
+ }
606371
+ });
606372
+
605675
606373
  // packages/orchestrator/dist/conversational-scrutiny.js
605676
606374
  function auditPerceptionClaims(text2, evidence) {
605677
606375
  if (!text2 || !text2.trim())
@@ -605744,6 +606442,189 @@ var init_conversational_scrutiny = __esm({
605744
606442
  }
605745
606443
  });
605746
606444
 
606445
+ // packages/orchestrator/dist/coherence-gate.js
606446
+ function scanDuplicateDefinitions(source, language = "unknown") {
606447
+ if (!source)
606448
+ return [];
606449
+ const counts = /* @__PURE__ */ new Map();
606450
+ const bump = (name10) => {
606451
+ if (!name10)
606452
+ return;
606453
+ counts.set(name10, (counts.get(name10) ?? 0) + 1);
606454
+ };
606455
+ if (language === "cpp" || language === "unknown") {
606456
+ for (const m2 of source.matchAll(/}\s*([A-Za-z_]\w*)\s*;/g))
606457
+ bump(m2[1]);
606458
+ for (const m2 of source.matchAll(/^\s*typedef\s+[^;{]+\s([A-Za-z_]\w*)\s*;/gm))
606459
+ bump(m2[1]);
606460
+ for (const m2 of source.matchAll(/\b(?:struct|class|enum|union)\s+([A-Za-z_]\w*)\s*[:{]/g))
606461
+ bump(m2[1]);
606462
+ for (const m2 of source.matchAll(/^\s*#define\s+([A-Za-z_]\w*)/gm))
606463
+ bump(m2[1]);
606464
+ }
606465
+ if (language === "typescript" || language === "unknown") {
606466
+ for (const m2 of source.matchAll(/\b(?:interface|type|class|enum)\s+([A-Za-z_]\w*)\b/g))
606467
+ bump(m2[1]);
606468
+ }
606469
+ return [...counts.entries()].filter(([, n2]) => n2 > 1).map(([name10]) => name10);
606470
+ }
606471
+ function clamp0110(n2) {
606472
+ if (Number.isNaN(n2))
606473
+ return 0;
606474
+ return Math.max(0, Math.min(1, n2));
606475
+ }
606476
+ var DEFAULT_WEIGHTS2, CoherenceGate;
606477
+ var init_coherence_gate = __esm({
606478
+ "packages/orchestrator/dist/coherence-gate.js"() {
606479
+ "use strict";
606480
+ DEFAULT_WEIGHTS2 = {
606481
+ duplicateDefinition: 0.34,
606482
+ // 2 duplicate defs -> score ~0.32, below floor
606483
+ signatureMismatch: 0.15,
606484
+ unknownSymbol: 0.1,
606485
+ typeError: 0.05
606486
+ };
606487
+ CoherenceGate = class {
606488
+ regenThreshold;
606489
+ weights;
606490
+ constructor(options2 = {}) {
606491
+ this.regenThreshold = clamp0110(options2.regenThreshold ?? 0.6);
606492
+ this.weights = { ...DEFAULT_WEIGHTS2, ...options2.weights ?? {} };
606493
+ }
606494
+ evaluate(input) {
606495
+ const diags = input.diagnostics ?? [];
606496
+ const duplicateSymbols = input.source ? scanDuplicateDefinitions(input.source, input.language ?? "unknown") : [];
606497
+ const signals = {
606498
+ duplicateDefinitions: diags.filter((d2) => d2.kind === "duplicate_definition").length + duplicateSymbols.length,
606499
+ signatureMismatches: diags.filter((d2) => d2.kind === "signature_mismatch").length,
606500
+ unknownSymbols: diags.filter((d2) => d2.kind === "unknown_symbol" || d2.kind === "unknown_member").length,
606501
+ otherTypeErrors: diags.filter((d2) => d2.kind === "type_error").length,
606502
+ duplicateSymbols
606503
+ };
606504
+ let score = 1;
606505
+ score -= signals.duplicateDefinitions * this.weights.duplicateDefinition;
606506
+ score -= signals.signatureMismatches * this.weights.signatureMismatch;
606507
+ score -= signals.unknownSymbols * this.weights.unknownSymbol;
606508
+ score -= signals.otherTypeErrors * this.weights.typeError;
606509
+ score = clamp0110(score);
606510
+ const regime = score < this.regenThreshold ? "regenerate" : "patch";
606511
+ return { score, regime, reason: this.reason(score, regime, signals), signals };
606512
+ }
606513
+ reason(score, regime, s2) {
606514
+ if (regime === "regenerate") {
606515
+ const dup = s2.duplicateSymbols.length ? ` Duplicate definitions: ${s2.duplicateSymbols.slice(0, 6).join(", ")}.` : "";
606516
+ return `coherence ${score.toFixed(2)} < ${this.regenThreshold} — the contract is self-contradictory; regenerate this unit wholesale from the locked contract instead of patching.${dup}`;
606517
+ }
606518
+ return `coherence ${score.toFixed(2)} >= ${this.regenThreshold} — invariants hold; patch mode.`;
606519
+ }
606520
+ };
606521
+ }
606522
+ });
606523
+
606524
+ // packages/orchestrator/dist/spec-gate.js
606525
+ function definitionCount(source, name10) {
606526
+ const n2 = escapeRegExp2(name10);
606527
+ const patterns = [
606528
+ new RegExp(`}\\s*${n2}\\s*;`, "g"),
606529
+ // } Name; (typedef struct/enum)
606530
+ new RegExp(`\\b(?:struct|class|enum|union)\\s+${n2}\\s*[:{]`, "g"),
606531
+ new RegExp(`\\b(?:interface|type|class|enum)\\s+${n2}\\b`, "g"),
606532
+ new RegExp(`\\btypedef\\s+[^;{]+\\b${n2}\\s*;`, "g")
606533
+ ];
606534
+ let total = 0;
606535
+ for (const re of patterns)
606536
+ total += (source.match(re) ?? []).length;
606537
+ return total;
606538
+ }
606539
+ function hasField(source, symbol3, field) {
606540
+ const n2 = escapeRegExp2(symbol3);
606541
+ const block = source.match(new RegExp(`(?:struct|class|enum|union|interface)\\s+${n2}[^{]*{([\\s\\S]*?)}|{([\\s\\S]*?)}\\s*${n2}\\s*;`));
606542
+ const body = block?.[1] ?? block?.[2] ?? "";
606543
+ if (!body)
606544
+ return false;
606545
+ return new RegExp(`\\b${escapeRegExp2(field)}\\b`).test(body);
606546
+ }
606547
+ function hasSignature(source, fragment) {
606548
+ const norm = (s2) => s2.replace(/\s+/g, " ").trim();
606549
+ return norm(source).includes(norm(fragment));
606550
+ }
606551
+ function evaluateSpecGate(unit, contract, opts = {}) {
606552
+ const violations = [];
606553
+ const expected = new Set(opts.expectedSymbols ?? []);
606554
+ for (const spec of contract.symbols) {
606555
+ const count = definitionCount(unit.source, spec.name);
606556
+ const mustDefine = expected.has(spec.name);
606557
+ if (count === 0) {
606558
+ if (mustDefine) {
606559
+ violations.push({
606560
+ symbol: spec.name,
606561
+ kind: "missing_symbol",
606562
+ detail: `unit ${unit.path} must declare ${spec.kind} ${spec.name} but it is absent`
606563
+ });
606564
+ }
606565
+ continue;
606566
+ }
606567
+ if (count > 1) {
606568
+ violations.push({
606569
+ symbol: spec.name,
606570
+ kind: "duplicate_symbol",
606571
+ detail: `${spec.name} is defined ${count}× in ${unit.path}; the contract permits exactly one`
606572
+ });
606573
+ }
606574
+ for (const field of spec.fields ?? []) {
606575
+ if (!hasField(unit.source, spec.name, field)) {
606576
+ violations.push({
606577
+ symbol: spec.name,
606578
+ kind: "missing_field",
606579
+ detail: `${spec.name} is missing required member "${field}"`
606580
+ });
606581
+ }
606582
+ }
606583
+ if (spec.signature && !hasSignature(unit.source, spec.signature)) {
606584
+ violations.push({
606585
+ symbol: spec.name,
606586
+ kind: "signature_divergence",
606587
+ detail: `${spec.name} does not match the contract signature "${spec.signature}"`
606588
+ });
606589
+ }
606590
+ }
606591
+ const pass = violations.length === 0;
606592
+ return {
606593
+ pass,
606594
+ violations,
606595
+ summary: pass ? `spec gate PASS for ${unit.path}` : `spec gate FAIL for ${unit.path}: ${violations.length} violation(s) — ${violations.map((v) => `${v.symbol}:${v.kind}`).join(", ")}`
606596
+ };
606597
+ }
606598
+ function evaluateExecutorStep(input) {
606599
+ const spec = evaluateSpecGate(input.unit, input.contract, {
606600
+ expectedSymbols: input.expectedSymbols
606601
+ });
606602
+ if (input.convergenceTier === "abandon" || input.convergenceTier === "stalled") {
606603
+ return {
606604
+ decision: "replan",
606605
+ spec,
606606
+ reason: `convergence ${input.convergenceTier}: stop patching ${input.unit.path}; re-plan / regenerate from the locked contract`
606607
+ };
606608
+ }
606609
+ const boundaryOk = input.boundaryOk ?? true;
606610
+ if (spec.pass && boundaryOk) {
606611
+ return { decision: "accept", spec, reason: `${input.unit.path} accepted` };
606612
+ }
606613
+ return {
606614
+ decision: "reject_regenerate",
606615
+ spec,
606616
+ reason: spec.pass ? `${input.unit.path} passed the spec gate but failed to compile — regenerate` : spec.summary
606617
+ };
606618
+ }
606619
+ function escapeRegExp2(s2) {
606620
+ return s2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
606621
+ }
606622
+ var init_spec_gate = __esm({
606623
+ "packages/orchestrator/dist/spec-gate.js"() {
606624
+ "use strict";
606625
+ }
606626
+ });
606627
+
605747
606628
  // packages/orchestrator/dist/index.js
605748
606629
  var dist_exports3 = {};
605749
606630
  __export(dist_exports3, {
@@ -605762,6 +606643,8 @@ __export(dist_exports3, {
605762
606643
  CRITIQUE_PRINCIPLES: () => CRITIQUE_PRINCIPLES,
605763
606644
  CallHistory: () => CallHistory,
605764
606645
  CascadeBackend: () => CascadeBackend,
606646
+ CoherenceGate: () => CoherenceGate,
606647
+ ConvergenceBreaker: () => ConvergenceBreaker,
605765
606648
  CoordinatorManager: () => CoordinatorManager,
605766
606649
  CostTracker: () => CostTracker,
605767
606650
  DEFAULT_COORDINATOR_CONFIG: () => DEFAULT_COORDINATOR_CONFIG,
@@ -605777,6 +606660,7 @@ __export(dist_exports3, {
605777
606660
  HookManager: () => HookManager,
605778
606661
  INFRA_WORKER_SKILL: () => INFRA_WORKER_SKILL,
605779
606662
  ImportanceBudget: () => ImportanceBudget,
606663
+ InMemoryConvergenceStore: () => InMemoryConvergenceStore,
605780
606664
  MergeRunner: () => MergeRunner,
605781
606665
  NexusAgenticBackend: () => NexusAgenticBackend,
605782
606666
  OllamaAgenticBackend: () => OllamaAgenticBackend,
@@ -605864,6 +606748,8 @@ __export(dist_exports3, {
605864
606748
  detectTaskType: () => detectTaskType,
605865
606749
  discoverPlugins: () => discoverPlugins3,
605866
606750
  discoverSystemOllamaModelStore: () => discoverSystemOllamaModelStore,
606751
+ evaluateExecutorStep: () => evaluateExecutorStep,
606752
+ evaluateSpecGate: () => evaluateSpecGate,
605867
606753
  executeBatch: () => executeBatch,
605868
606754
  executeHook: () => executeHook,
605869
606755
  expandContextReference: () => expandContextReference,
@@ -605988,6 +606874,7 @@ __export(dist_exports3, {
605988
606874
  saveCompletionLedger: () => saveCompletionLedger,
605989
606875
  saveStabilityIndex: () => saveStabilityIndex,
605990
606876
  scanContextContent: () => scanContextContent,
606877
+ scanDuplicateDefinitions: () => scanDuplicateDefinitions,
605991
606878
  scanOllamaProcesses: () => scanOllamaProcesses,
605992
606879
  scoreHandoff: () => scoreHandoff,
605993
606880
  scoreMemoryItem: () => scoreMemoryItem,
@@ -606085,11 +606972,14 @@ var init_dist8 = __esm({
606085
606972
  init_plugins();
606086
606973
  init_project_arc();
606087
606974
  init_dedup_gate();
606975
+ init_convergence_breaker();
606088
606976
  init_memory_consolidation();
606089
606977
  init_exploration_fanout();
606090
606978
  init_consolidation_runtime();
606091
606979
  init_completion_evidence_gate();
606092
606980
  init_conversational_scrutiny();
606981
+ init_coherence_gate();
606982
+ init_spec_gate();
606093
606983
  }
606094
606984
  });
606095
606985
 
@@ -607595,28 +608485,28 @@ function updateListenLiveState(patch) {
607595
608485
  function getListenLiveState() {
607596
608486
  return listenLiveState;
607597
608487
  }
607598
- function clamp0110(value2) {
608488
+ function clamp0111(value2) {
607599
608489
  if (!Number.isFinite(value2)) return 0;
607600
608490
  return Math.max(0, Math.min(1, value2));
607601
608491
  }
607602
608492
  function micColor(text2, level) {
607603
- const idx = Math.round(clamp0110(level) * (MIC_GRADIENT_256.length - 1));
608493
+ const idx = Math.round(clamp0111(level) * (MIC_GRADIENT_256.length - 1));
607604
608494
  const code8 = MIC_GRADIENT_256[idx] ?? 21;
607605
608495
  return `\x1B[38;5;${code8}m${text2}\x1B[0m`;
607606
608496
  }
607607
608497
  function micLevelChar(level) {
607608
- const idx = Math.round(clamp0110(level) * (MIC_LEVEL_CHARS.length - 1));
608498
+ const idx = Math.round(clamp0111(level) * (MIC_LEVEL_CHARS.length - 1));
607609
608499
  return MIC_LEVEL_CHARS[idx] ?? "▁";
607610
608500
  }
607611
608501
  function micSpectrumChar(level) {
607612
- const idx = Math.round(clamp0110(level) * (MIC_SPECTRUM_CHARS.length - 1));
608502
+ const idx = Math.round(clamp0111(level) * (MIC_SPECTRUM_CHARS.length - 1));
607613
608503
  return MIC_SPECTRUM_CHARS[idx] ?? " ";
607614
608504
  }
607615
608505
  function renderMicWaveform(bucketSquares, bucketCounts, peak) {
607616
- return bucketSquares.map((sum, idx) => {
608506
+ return bucketSquares.map((sum2, idx) => {
607617
608507
  const count = Math.max(1, bucketCounts[idx] ?? 1);
607618
- const level = Math.sqrt(sum / count);
607619
- const normalized = clamp0110(level / Math.max(0.02, peak || 0.02));
608508
+ const level = Math.sqrt(sum2 / count);
608509
+ const normalized = clamp0111(level / Math.max(0.02, peak || 0.02));
607620
608510
  return micColor(micLevelChar(normalized), normalized);
607621
608511
  }).join("");
607622
608512
  }
@@ -607640,7 +608530,7 @@ function renderMicSpectrum(samples) {
607640
608530
  }
607641
608531
  const mag = Math.sqrt(re * re + im * im) / n2;
607642
608532
  const db = 20 * Math.log10(Math.max(1e-7, mag));
607643
- const normalized = clamp0110((db + 75) / 75);
608533
+ const normalized = clamp0111((db + 75) / 75);
607644
608534
  bands.push(micColor(micSpectrumChar(normalized), normalized));
607645
608535
  }
607646
608536
  return bands.join("");
@@ -608535,7 +609425,7 @@ var init_listen = __esm({
608535
609425
  const speech = hardwareFresh ? listenLiveState.speechActive : this.micLevelDb > Math.max(-58, floor + 6);
608536
609426
  const changed = speech !== this.micSpeechActive;
608537
609427
  this.micSpeechActive = speech;
608538
- const peak = Math.sqrt(Math.max(...bucketSquares.map((sum, idx) => sum / Math.max(1, bucketCounts[idx] ?? 1)), 0));
609428
+ const peak = Math.sqrt(Math.max(...bucketSquares.map((sum2, idx) => sum2 / Math.max(1, bucketCounts[idx] ?? 1)), 0));
608539
609429
  const waveform = renderMicWaveform(bucketSquares, bucketCounts, peak);
608540
609430
  const spectrum = renderMicSpectrum(spectrumSamples);
608541
609431
  if (spectrum) {
@@ -609597,8 +610487,8 @@ function formatGpuRuntimeLine(broker) {
609597
610487
  }
609598
610488
  const parts = devices.map((device) => {
609599
610489
  const label = device.uuid === "jetson-uma" ? "jetson-uma" : `gpu${device.index}`;
609600
- const pct = device.total > 0 ? device.used / device.total : 0;
609601
- return `${label} ${pressureColor(pct, 0.78)(`${mbToGb(device.used)}/${mbToGb(device.total)}GB`)}`;
610490
+ const pct2 = device.total > 0 ? device.used / device.total : 0;
610491
+ return `${label} ${pressureColor(pct2, 0.78)(`${mbToGb(device.used)}/${mbToGb(device.total)}GB`)}`;
609602
610492
  });
609603
610493
  return `├─ accelerator: ${colorText("CUDA on", 82)} ${parts.join(" ")}`;
609604
610494
  }
@@ -609623,8 +610513,8 @@ function formatSubsystemMemoryLine(loaded, width) {
609623
610513
  }
609624
610514
  function formatUnattributedMemoryLine(loaded, broker) {
609625
610515
  const resource = getLiveResourceArbiter().snapshot();
609626
- const trackedRam = loaded.reduce((sum, model) => sum + Math.max(0, Number(model.ramMB ?? 0)), 0);
609627
- const trackedVram = loaded.reduce((sum, model) => sum + Math.max(0, Number(model.vramMB ?? 0)), 0);
610516
+ const trackedRam = loaded.reduce((sum2, model) => sum2 + Math.max(0, Number(model.ramMB ?? 0)), 0);
610517
+ const trackedVram = loaded.reduce((sum2, model) => sum2 + Math.max(0, Number(model.vramMB ?? 0)), 0);
609628
610518
  const ramGap = Math.max(0, resource.usedMemMB - trackedRam);
609629
610519
  const vramGap = broker.vramMB ? Math.max(0, broker.vramMB.used - trackedVram) : null;
609630
610520
  return `├─ unattributed/system: ram=${mbToGb(ramGap)}G${vramGap !== null ? ` vram/uma=${mbToGb(vramGap)}G` : ""} ${colorText("(OS, camera ffmpeg, CV libs, CUDA overhead, untracked subprocesses)", 244)}`;
@@ -610076,7 +610966,7 @@ function chooseCameraOrientationFromScores(scores) {
610076
610966
  if (!best || best.score <= 0 || best.faces <= 0) return null;
610077
610967
  const second3 = sorted[1];
610078
610968
  const gap = best.score - (second3?.score ?? 0);
610079
- const total = sorted.reduce((sum, score) => sum + Math.max(0, score.score), 0);
610969
+ const total = sorted.reduce((sum2, score) => sum2 + Math.max(0, score.score), 0);
610080
610970
  const share = total > 0 ? best.score / total : 1;
610081
610971
  const confidence2 = Math.max(0.55, Math.min(0.98, share * 0.75 + Math.min(0.23, gap / Math.max(1, best.score))));
610082
610972
  if (confidence2 < 0.58 && gap < 0.4) return null;
@@ -610343,9 +611233,9 @@ function readPcm16WavActivity(filePath, bins = 36) {
610343
611233
  }
610344
611234
  const rms = Math.sqrt(sumSquares / frames);
610345
611235
  const chars = "▁▂▃▄▅▆▇█";
610346
- const waveform = bucketSquares.map((sum, idx) => {
611236
+ const waveform = bucketSquares.map((sum2, idx) => {
610347
611237
  const count = Math.max(1, bucketCounts[idx] ?? 1);
610348
- const level = Math.sqrt(sum / count);
611238
+ const level = Math.sqrt(sum2 / count);
610349
611239
  const normalized = Math.max(0, Math.min(1, level / Math.max(0.02, peak || 0.02)));
610350
611240
  return chars[Math.min(chars.length - 1, Math.round(normalized * (chars.length - 1)))] ?? "▁";
610351
611241
  }).join("");
@@ -610780,11 +611670,11 @@ function formatCameraRotationDashboard(camera) {
610780
611670
  }
610781
611671
  function cameraPaneBadge(camera) {
610782
611672
  const classifications = camera.classifications ?? [];
610783
- const faceCount = classifications.filter((item) => item.kind === "face" || item.kind === "identity").reduce((sum, item) => sum + Math.max(1, item.count), 0);
610784
- const objectCount = classifications.filter((item) => item.kind === "object").reduce((sum, item) => sum + Math.max(1, item.count), 0);
610785
- const segmentCount = classifications.filter((item) => item.kind === "segment").reduce((sum, item) => sum + Math.max(1, item.count), 0);
610786
- const trackCount = classifications.filter((item) => item.kind === "track").reduce((sum, item) => sum + Math.max(1, item.count), 0);
610787
- const triggerCount = classifications.filter((item) => item.kind === "trigger").reduce((sum, item) => sum + Math.max(1, item.count), 0);
611673
+ const faceCount = classifications.filter((item) => item.kind === "face" || item.kind === "identity").reduce((sum2, item) => sum2 + Math.max(1, item.count), 0);
611674
+ const objectCount = classifications.filter((item) => item.kind === "object").reduce((sum2, item) => sum2 + Math.max(1, item.count), 0);
611675
+ const segmentCount = classifications.filter((item) => item.kind === "segment").reduce((sum2, item) => sum2 + Math.max(1, item.count), 0);
611676
+ const trackCount = classifications.filter((item) => item.kind === "track").reduce((sum2, item) => sum2 + Math.max(1, item.count), 0);
611677
+ const triggerCount = classifications.filter((item) => item.kind === "trigger").reduce((sum2, item) => sum2 + Math.max(1, item.count), 0);
610788
611678
  const parts = [
610789
611679
  faceCount > 0 ? `F${faceCount}` : "",
610790
611680
  segmentCount > 0 ? `S${segmentCount}` : "",
@@ -613438,14 +614328,14 @@ function formatGenerativeProgress(kind, event, options2 = {}) {
613438
614328
  const width = Math.max(8, Math.min(32, options2.width ?? (options2.surface === "telegram" ? 12 : 20)));
613439
614329
  const label = kindLabel2(kind);
613440
614330
  const stage2 = stageLabel(event.stage);
613441
- const pct = finitePercent(event.percent);
614331
+ const pct2 = finitePercent(event.percent);
613442
614332
  const bytes = formatProgressBytes(event);
613443
614333
  const elapsed = formatElapsed(event.elapsedMs);
613444
614334
  const message2 = compactProgressMessage(event.message);
613445
- if (typeof pct === "number") {
613446
- const filled = Math.max(0, Math.min(width, Math.round(pct / 100 * width)));
614335
+ if (typeof pct2 === "number") {
614336
+ const filled = Math.max(0, Math.min(width, Math.round(pct2 / 100 * width)));
613447
614337
  const bar = `${"#".repeat(filled)}${"-".repeat(width - filled)}`;
613448
- return `${label} ${stage2}: [${bar}] ${pct}% ${message2}${bytes}${elapsed}`;
614338
+ return `${label} ${stage2}: [${bar}] ${pct2}% ${message2}${bytes}${elapsed}`;
613449
614339
  }
613450
614340
  return `${label} ${stage2}: ${message2}${bytes}${elapsed}`;
613451
614341
  }
@@ -619706,7 +620596,7 @@ var init_task_complete_box = __esm({
619706
620596
  // packages/cli/src/tui/syntax-highlight.ts
619707
620597
  var syntax_highlight_exports = {};
619708
620598
  __export(syntax_highlight_exports, {
619709
- detectLanguage: () => detectLanguage2,
620599
+ detectLanguage: () => detectLanguage3,
619710
620600
  getHighlightStatus: () => getHighlightStatus,
619711
620601
  highlightBlock: () => highlightBlock,
619712
620602
  highlightCode: () => highlightCode,
@@ -619776,7 +620666,7 @@ function highlightCode(code8, language) {
619776
620666
  if (!code8) return code8;
619777
620667
  const fn = loadHighlighterSync();
619778
620668
  if (!fn) return code8;
619779
- const lang = (language ?? detectLanguage2(code8) ?? "").trim();
620669
+ const lang = (language ?? detectLanguage3(code8) ?? "").trim();
619780
620670
  try {
619781
620671
  if (lang) {
619782
620672
  return fn(code8, { language: lang, ignoreIllegals: true });
@@ -619786,7 +620676,7 @@ function highlightCode(code8, language) {
619786
620676
  return code8;
619787
620677
  }
619788
620678
  }
619789
- function detectLanguage2(text2) {
620679
+ function detectLanguage3(text2) {
619790
620680
  if (!text2) return null;
619791
620681
  const trimmed = text2.trimStart();
619792
620682
  const shebang = trimmed.match(/^#!\s*\/[^\n]+/);
@@ -619841,7 +620731,7 @@ function highlightBlock(code8, language) {
619841
620731
  if (!code8) return [""];
619842
620732
  const fn = loadHighlighterSync();
619843
620733
  if (!fn) return code8.split("\n");
619844
- const lang = (language ?? detectLanguage2(code8) ?? "").trim();
620734
+ const lang = (language ?? detectLanguage3(code8) ?? "").trim();
619845
620735
  try {
619846
620736
  const out = lang ? fn(code8, { language: lang, ignoreIllegals: true }) : fn(code8, { ignoreIllegals: true });
619847
620737
  const lines = out.split("\n");
@@ -624706,15 +625596,15 @@ function formatUsageBar(options2) {
624706
625596
  const used = total > 0 ? Math.min(total, rawUsed) : 0;
624707
625597
  const width = Math.max(4, options2.width ?? 18);
624708
625598
  const labelWidth = Math.max(options2.label.length, options2.labelWidth ?? 16);
624709
- const pct = total > 0 ? Math.round(used / total * 100) : 0;
624710
- const filled = total > 0 ? Math.min(width, Math.round(pct / 100 * width)) : 0;
624711
- const color = pct >= 90 ? c3.red : pct >= 70 ? c3.yellow : c3.green;
625599
+ const pct2 = total > 0 ? Math.round(used / total * 100) : 0;
625600
+ const filled = total > 0 ? Math.min(width, Math.round(pct2 / 100 * width)) : 0;
625601
+ const color = pct2 >= 90 ? c3.red : pct2 >= 70 ? c3.yellow : c3.green;
624712
625602
  const bar = color("█".repeat(filled)) + c3.dim("░".repeat(width - filled));
624713
625603
  const reset = options2.resetAt ? c3.dim(formatResetDelta(options2.resetAt)) : "";
624714
625604
  return [
624715
625605
  c3.cyan(options2.label.padEnd(labelWidth)),
624716
625606
  bar,
624717
- color(`${pct}%`.padStart(4)),
625607
+ color(`${pct2}%`.padStart(4)),
624718
625608
  c3.dim(`${formatCompactCount(rawUsed)}/${formatCompactCount(total)}`),
624719
625609
  reset
624720
625610
  ].join(" ").trimEnd();
@@ -624779,7 +625669,7 @@ function safeNonNegativeInt(value2) {
624779
625669
  function currentTokenRate(samples, now2 = Date.now()) {
624780
625670
  while (samples.length > 0 && samples[0].at < now2 - 1e4) samples.shift();
624781
625671
  if (samples.length === 0) return 0;
624782
- const tokens = samples.reduce((sum, sample) => sum + sample.tokens, 0);
625672
+ const tokens = samples.reduce((sum2, sample) => sum2 + sample.tokens, 0);
624783
625673
  const spanMs = Math.max(1e3, now2 - samples[0].at);
624784
625674
  return Math.round(tokens / (spanMs / 1e3) * 10) / 10;
624785
625675
  }
@@ -626140,9 +627030,9 @@ ${this.formatConnectionInfo()}`);
626140
627030
  lines.push(` ${c3.cyan("Tokens out".padEnd(18))} ${fmtTokens(s2.totalTokensOut)}`);
626141
627031
  lines.push(` ${c3.cyan("Tokens/sec".padEnd(18))} ${s2.tokensPerSecond.toFixed(s2.tokensPerSecond >= 10 ? 0 : 1)} t/s`);
626142
627032
  if (s2.budgetTokensTotal > 0) {
626143
- const pct = Math.round(s2.budgetTokensRemaining / s2.budgetTokensTotal * 100);
626144
- const budgetColor = pct > 50 ? c3.green : pct > 20 ? c3.yellow : c3.red;
626145
- lines.push(` ${c3.cyan("Budget".padEnd(18))} ${budgetColor(fmtTokens(s2.budgetTokensRemaining))}${c3.dim("/")}${fmtTokens(s2.budgetTokensTotal)} ${c3.dim(`(${pct}% left)`)}`);
627033
+ const pct2 = Math.round(s2.budgetTokensRemaining / s2.budgetTokensTotal * 100);
627034
+ const budgetColor = pct2 > 50 ? c3.green : pct2 > 20 ? c3.yellow : c3.red;
627035
+ lines.push(` ${c3.cyan("Budget".padEnd(18))} ${budgetColor(fmtTokens(s2.budgetTokensRemaining))}${c3.dim("/")}${fmtTokens(s2.budgetTokensTotal)} ${c3.dim(`(${pct2}% left)`)}`);
626146
627036
  }
626147
627037
  if (s2.sponsorUsage) {
626148
627038
  lines.push("");
@@ -626870,9 +627760,9 @@ ${this.formatConnectionInfo()}`);
626870
627760
  lines.push(` ${c3.cyan("Tokens out".padEnd(18))} ${fmtTokens(s2.totalTokensOut)}`);
626871
627761
  lines.push(` ${c3.cyan("Tokens/sec".padEnd(18))} ${s2.tokensPerSecond.toFixed(s2.tokensPerSecond >= 10 ? 0 : 1)} t/s`);
626872
627762
  if (s2.budgetTokensTotal > 0) {
626873
- const pct = Math.round(s2.budgetTokensRemaining / s2.budgetTokensTotal * 100);
626874
- const budgetColor = pct > 50 ? c3.green : pct > 20 ? c3.yellow : c3.red;
626875
- lines.push(` ${c3.cyan("Budget".padEnd(18))} ${budgetColor(fmtTokens(s2.budgetTokensRemaining))}${c3.dim("/")}${fmtTokens(s2.budgetTokensTotal)} ${c3.dim(`(${pct}% left)`)}`);
627763
+ const pct2 = Math.round(s2.budgetTokensRemaining / s2.budgetTokensTotal * 100);
627764
+ const budgetColor = pct2 > 50 ? c3.green : pct2 > 20 ? c3.yellow : c3.red;
627765
+ lines.push(` ${c3.cyan("Budget".padEnd(18))} ${budgetColor(fmtTokens(s2.budgetTokensRemaining))}${c3.dim("/")}${fmtTokens(s2.budgetTokensTotal)} ${c3.dim(`(${pct2}% left)`)}`);
626876
627766
  }
626877
627767
  if (s2.sponsorUsage) {
626878
627768
  lines.push("");
@@ -631510,9 +632400,9 @@ async function collectGpuMetrics() {
631510
632400
  });
631511
632401
  }
631512
632402
  if (devices.length === 0) return noGpu;
631513
- const vramUsed = devices.reduce((sum, gpu) => sum + gpu.vramUsedMB, 0);
631514
- const vramTotal = devices.reduce((sum, gpu) => sum + gpu.vramTotalMB, 0);
631515
- const avgUtil = Math.round(devices.reduce((sum, gpu) => sum + gpu.utilization, 0) / devices.length);
632403
+ const vramUsed = devices.reduce((sum2, gpu) => sum2 + gpu.vramUsedMB, 0);
632404
+ const vramTotal = devices.reduce((sum2, gpu) => sum2 + gpu.vramTotalMB, 0);
632405
+ const avgUtil = Math.round(devices.reduce((sum2, gpu) => sum2 + gpu.utilization, 0) / devices.length);
631516
632406
  const firstName = devices[0]?.name ?? "";
631517
632407
  const allSameName = devices.every((gpu) => gpu.name === firstName);
631518
632408
  return {
@@ -633535,7 +634425,7 @@ var init_status_bar = __esm({
633535
634425
  w: NO_SUB_AGENTS_HEADER_LABEL.length
633536
634426
  });
633537
634427
  }
633538
- const sysSeparatorOffset = sysItems.reduce((sum, item) => sum + item.w, 0);
634428
+ const sysSeparatorOffset = sysItems.reduce((sum2, item) => sum2 + item.w, 0);
633539
634429
  this._sysSeparatorOffset = sysSeparatorOffset;
633540
634430
  sysItems.push({
633541
634431
  render: () => `${BOX_FG}│${RESET4}${PANEL_BG_SEQ} `,
@@ -633672,7 +634562,7 @@ var init_status_bar = __esm({
633672
634562
  const buttons = panel.meta.buttons ?? [];
633673
634563
  const versionWidth = panel.meta.versionWidth ?? 0;
633674
634564
  const usedW = panel.meta.isFirstPage ? versionWidth : 0;
633675
- const btnTotalW = buttons.reduce((sum, btn) => sum + btn.w + 1, 0);
634565
+ const btnTotalW = buttons.reduce((sum2, btn) => sum2 + btn.w + 1, 0);
633676
634566
  const gap = Math.max(1, innerW - usedW - btnTotalW);
633677
634567
  let col = chromeLayout.contentStartCol + usedW + gap;
633678
634568
  if (panel.meta.isFirstPage && this._updateLatest) {
@@ -636204,8 +637094,8 @@ ${CONTENT_BG_SEQ}`);
636204
637094
  }
636205
637095
  if (this._contentScrollOffset > 0) {
636206
637096
  const linesAbove = win.startIdx;
636207
- const pct = win.totalRows > 0 ? Math.round((win.startIdx + h) / win.totalRows * 100) : 100;
636208
- const indicator = ` ↑ ${linesAbove} lines above · ${pct}% · PgDn/End to return `;
637097
+ const pct2 = win.totalRows > 0 ? Math.round((win.startIdx + h) / win.totalRows * 100) : 100;
637098
+ const indicator = ` ↑ ${linesAbove} lines above · ${pct2}% · PgDn/End to return `;
636209
637099
  const pad = Math.max(0, w - indicator.length);
636210
637100
  buf += `\x1B[${this.scrollRegionTop};1H\x1B[7m${indicator}${" ".repeat(pad)}\x1B[0m`;
636211
637101
  }
@@ -636460,7 +637350,7 @@ ${CONTENT_BG_SEQ}`);
636460
637350
  return pm ? pm[1] : mdl.split(":")[0]?.split("/").pop() ?? mdl;
636461
637351
  });
636462
637352
  const modelStr = modelParams.join(",");
636463
- const visibleReqs = Array.from(this._expose.modelUsage.entries()).filter(([m3]) => !INTERNAL_CAPS.has(m3)).reduce((sum, [, n2]) => sum + n2, 0);
637353
+ const visibleReqs = Array.from(this._expose.modelUsage.entries()).filter(([m3]) => !INTERNAL_CAPS.has(m3)).reduce((sum2, [, n2]) => sum2 + n2, 0);
636464
637354
  const reqStr = visibleReqs > 0 ? ` ${_StatusBar.digitBar(visibleReqs)}req` : "";
636465
637355
  const connStr = this._expose.activeConnections > 0 ? ` ${_StatusBar.digitBar(this._expose.activeConnections)}conn` : "";
636466
637356
  const exposeExpanded = statusEmoji + pastel2(183, (modelStr ? " " + modelStr : "") + reqStr + connStr);
@@ -642259,8 +643149,8 @@ var init_registry3 = __esm({
642259
643149
  degraded: statuses.filter((s2) => s2.state === "degraded").length,
642260
643150
  failed: statuses.filter((s2) => s2.state === "failed").length,
642261
643151
  unconfigured: statuses.filter((s2) => s2.state === "unconfigured").length,
642262
- queued: statuses.reduce((sum, s2) => sum + s2.health.queueDepth, 0),
642263
- activeSessions: statuses.reduce((sum, s2) => sum + s2.health.activeSessions, 0)
643152
+ queued: statuses.reduce((sum2, s2) => sum2 + s2.health.queueDepth, 0),
643153
+ activeSessions: statuses.reduce((sum2, s2) => sum2 + s2.health.activeSessions, 0)
642264
643154
  };
642265
643155
  }
642266
643156
  require(id2) {
@@ -646053,11 +646943,11 @@ function readSample(buffer2, offset, format3, bitsPerSample) {
646053
646943
  function frameAmplitude(buffer2, info, frame) {
646054
646944
  const bytesPerSample = info.bitsPerSample / 8;
646055
646945
  const offset = info.dataOffset + frame * info.frameSize;
646056
- let sum = 0;
646946
+ let sum2 = 0;
646057
646947
  for (let channel = 0; channel < info.channels; channel++) {
646058
- sum += readSample(buffer2, offset + channel * bytesPerSample, info.format, info.bitsPerSample);
646948
+ sum2 += readSample(buffer2, offset + channel * bytesPerSample, info.format, info.bitsPerSample);
646059
646949
  }
646060
- return Math.max(-1, Math.min(1, sum / info.channels));
646950
+ return Math.max(-1, Math.min(1, sum2 / info.channels));
646061
646951
  }
646062
646952
  function renderAudioWaveform(file, options2 = {}) {
646063
646953
  let Canvas;
@@ -648531,7 +649421,7 @@ function endpointModelCountLabel(ep) {
648531
649421
  }
648532
649422
  async function stepModelSelection(config, rl, availableRows) {
648533
649423
  const enabled2 = config.endpoints.filter((ep) => ep.enabled);
648534
- const totalKnownModels = enabled2.reduce((sum, ep) => sum + ep.models.length, 0);
649424
+ const totalKnownModels = enabled2.reduce((sum2, ep) => sum2 + ep.models.length, 0);
648535
649425
  if (totalKnownModels === 0) {
648536
649426
  renderWarning("No model lists were returned; sponsorship will expose each enabled endpoint's full model set.");
648537
649427
  return true;
@@ -654098,10 +654988,10 @@ Error: ${err instanceof Error ? err.message : String(err)}`
654098
654988
  chunks.push(value2);
654099
654989
  received += value2.length;
654100
654990
  if (contentLength > 0) {
654101
- const pct = Math.round(received / contentLength * 100);
654102
- if (pct === 25 || pct === 50 || pct === 75 || pct === 100) {
654991
+ const pct2 = Math.round(received / contentLength * 100);
654992
+ if (pct2 === 25 || pct2 === 50 || pct2 === 75 || pct2 === 100) {
654103
654993
  renderInfo(
654104
- ` ${pct}% (${formatBytes11(received)} / ${formatBytes11(contentLength)})`
654994
+ ` ${pct2}% (${formatBytes11(received)} / ${formatBytes11(contentLength)})`
654105
654995
  );
654106
654996
  }
654107
654997
  }
@@ -654880,8 +655770,8 @@ async function destroyOrphanProcesses(ctx3, global2) {
654880
655770
  myPpid
654881
655771
  );
654882
655772
  if (diagnostics.length > 0) {
654883
- const totalMb = diagnostics.reduce((sum, c9) => sum + c9.rssMb, 0);
654884
- const totalCpu = diagnostics.reduce((sum, c9) => sum + c9.cpuPct, 0);
655773
+ const totalMb = diagnostics.reduce((sum2, c9) => sum2 + c9.rssMb, 0);
655774
+ const totalCpu = diagnostics.reduce((sum2, c9) => sum2 + c9.cpuPct, 0);
654885
655775
  renderWarning(
654886
655776
  `untracked_omnius_like: ${diagnostics.length} process(es) matched legacy diagnostics only — not killed automatically (${totalMb}MB RAM, ${totalCpu.toFixed(1)}% CPU):`
654887
655777
  );
@@ -655106,7 +655996,7 @@ async function handleSlashCommand(input, ctx3) {
655106
655996
  const cached = listCachedModels();
655107
655997
  const legacyPaths = detectLegacyCaches(ctx3.repoRoot);
655108
655998
  const totalCachedBytes = cached.reduce(
655109
- (sum, e2) => sum + e2.sizeBytes,
655999
+ (sum2, e2) => sum2 + e2.sizeBytes,
655110
656000
  0
655111
656001
  );
655112
656002
  renderInfo(`Model store: ${unifiedModelStoreDir()}`);
@@ -655316,10 +656206,10 @@ async function handleSlashCommand(input, ctx3) {
655316
656206
  newRoot: target,
655317
656207
  onProgress: (p2) => {
655318
656208
  if (p2.stage === "copy" && p2.bytesTotal > 0) {
655319
- const pct = Math.floor(p2.bytesDone / p2.bytesTotal * 100);
655320
- if (pct !== lastPct && pct % 5 === 0) {
655321
- lastPct = pct;
655322
- renderContentBlock(` ${c3.dim(`copy ${pct}%`)} ${c3.dim(formatBytes(p2.bytesDone) + " / " + formatBytes(p2.bytesTotal))}`);
656209
+ const pct2 = Math.floor(p2.bytesDone / p2.bytesTotal * 100);
656210
+ if (pct2 !== lastPct && pct2 % 5 === 0) {
656211
+ lastPct = pct2;
656212
+ renderContentBlock(` ${c3.dim(`copy ${pct2}%`)} ${c3.dim(formatBytes(p2.bytesDone) + " / " + formatBytes(p2.bytesTotal))}`);
655323
656213
  }
655324
656214
  } else if (p2.stage !== "copy") {
655325
656215
  renderContentBlock(` ${c3.dim("∙")} ${c3.dim(p2.message || p2.stage)}`);
@@ -655754,13 +656644,13 @@ async function handleSlashCommand(input, ctx3) {
655754
656644
  );
655755
656645
  if (evalResult.success) {
655756
656646
  const lines = [];
655757
- const pct = Math.round(evalResult.overallScore * 100);
655758
- const scoreColor = pct >= 80 ? c3.green : pct >= 60 ? c3.yellow : c3.red;
656647
+ const pct2 = Math.round(evalResult.overallScore * 100);
656648
+ const scoreColor = pct2 >= 80 ? c3.green : pct2 >= 60 ? c3.yellow : c3.red;
655759
656649
  lines.push(
655760
656650
  `
655761
656651
  ${c3.bold("Task Evaluation")} (${evalResult.taskType})`
655762
656652
  );
655763
- lines.push(` Overall: ${scoreColor(c3.bold(`${pct}%`))}`);
656653
+ lines.push(` Overall: ${scoreColor(c3.bold(`${pct2}%`))}`);
655764
656654
  lines.push("");
655765
656655
  for (const d2 of evalResult.dimensions) {
655766
656656
  const bar = "█".repeat(d2.score) + "░".repeat(10 - d2.score);
@@ -657304,10 +658194,10 @@ async function handleSlashCommand(input, ctx3) {
657304
658194
  );
657305
658195
  for (const [cat2, info] of sorted) {
657306
658196
  const name10 = cat2 || "root";
657307
- const pct = totalBytes > 0 ? Math.round(info.bytes / totalBytes * 100) : 0;
657308
- const bar = "█".repeat(Math.max(1, Math.round(pct / 5))) + "░".repeat(Math.max(0, 20 - Math.round(pct / 5)));
658197
+ const pct2 = totalBytes > 0 ? Math.round(info.bytes / totalBytes * 100) : 0;
658198
+ const bar = "█".repeat(Math.max(1, Math.round(pct2 / 5))) + "░".repeat(Math.max(0, 20 - Math.round(pct2 / 5)));
657309
658199
  lines.push(
657310
- ` ${c3.bold(name10.padEnd(20))} ${bar} ${formatFileSize(info.bytes).padStart(8)} ${String(info.files).padStart(4)} files ${String(pct).padStart(2)}%`
658200
+ ` ${c3.bold(name10.padEnd(20))} ${bar} ${formatFileSize(info.bytes).padStart(8)} ${String(info.files).padStart(4)} files ${String(pct2).padStart(2)}%`
657311
658201
  );
657312
658202
  }
657313
658203
  lines.push(
@@ -662854,7 +663744,7 @@ function cachedModelDiskStats(root, model) {
662854
663744
  const paths = cacheCandidatePaths(root, model).filter(
662855
663745
  (path12) => existsSync142(path12)
662856
663746
  );
662857
- const bytes = paths.reduce((sum, path12) => sum + directorySizeBytes2(path12), 0);
663747
+ const bytes = paths.reduce((sum2, path12) => sum2 + directorySizeBytes2(path12), 0);
662858
663748
  return { downloaded: paths.length > 0, bytes, paths };
662859
663749
  }
662860
663750
  function downloadedModelSuffix(stats) {
@@ -662903,7 +663793,7 @@ function imageModelDiskStats(ctx3, preset, ollamaSizes) {
662903
663793
  (model) => cachedModelDiskStats(root, model)
662904
663794
  );
662905
663795
  const paths = [...new Set(parts.flatMap((part) => part.paths))];
662906
- const bytes = parts.reduce((sum, part) => sum + part.bytes, 0);
663796
+ const bytes = parts.reduce((sum2, part) => sum2 + part.bytes, 0);
662907
663797
  return { downloaded: paths.length > 0, bytes, paths };
662908
663798
  }
662909
663799
  return { downloaded: false, bytes: 0, paths: [] };
@@ -670566,14 +671456,14 @@ async function showExposeDashboard(gateway, rl, ctx3) {
670566
671456
  ` ${c3.dim("Req")} ${c3.bold(String(totalReqs))} ${c3.dim("Active")} ${activeDot} ${c3.dim("Err")} ${errors > 0 ? c3.magenta(String(errors)) : c3.dim("0")} ${c3.dim("Tok")} ↑${c3.cyan(fmtDashTokens(tokIn))} ↓${c3.cyan(fmtDashTokens(tokOut))}`
670567
671457
  );
670568
671458
  if (s2.budgetTokensTotal > 0) {
670569
- const pct = Math.round(
671459
+ const pct2 = Math.round(
670570
671460
  s2.budgetTokensRemaining / s2.budgetTokensTotal * 100
670571
671461
  );
670572
- const budgetColor = pct > 50 ? c3.green : pct > 20 ? c3.yellow : c3.red;
671462
+ const budgetColor = pct2 > 50 ? c3.green : pct2 > 20 ? c3.yellow : c3.red;
670573
671463
  const barLen = 20;
670574
- const filledLen = Math.round(pct / 100 * barLen);
671464
+ const filledLen = Math.round(pct2 / 100 * barLen);
670575
671465
  const bar = budgetColor("█".repeat(filledLen)) + c3.dim("░".repeat(barLen - filledLen));
670576
- lines.push(` ${c3.dim("Budget")} ${bar} ${budgetColor(`${pct}%`)}`);
671466
+ lines.push(` ${c3.dim("Budget")} ${bar} ${budgetColor(`${pct2}%`)}`);
670577
671467
  }
670578
671468
  }
670579
671469
  const modelEntries = s2?.modelUsage ? Array.from(s2.modelUsage.entries()).filter(
@@ -673026,7 +673916,7 @@ function normalizePersonName(name10) {
673026
673916
  function personKey(name10) {
673027
673917
  return `person:${normalizePersonName(name10)}`;
673028
673918
  }
673029
- function clamp0111(value2, fallback = 0) {
673919
+ function clamp0112(value2, fallback = 0) {
673030
673920
  if (typeof value2 !== "number" || !Number.isFinite(value2)) return fallback;
673031
673921
  return Math.max(0, Math.min(1, value2));
673032
673922
  }
@@ -673043,7 +673933,7 @@ function parseStructuredIdentifyResult(result) {
673043
673933
  const matches = faces.filter((face) => face["identified"] === true && typeof face["name"] === "string" && String(face["name"]).trim()).map((face) => ({
673044
673934
  name: String(face["name"]).trim(),
673045
673935
  personId: typeof face["person_id"] === "string" ? face["person_id"] : void 0,
673046
- confidence: clamp0111(face["confidence"], 0),
673936
+ confidence: clamp0112(face["confidence"], 0),
673047
673937
  margin: typeof face["margin"] === "number" ? face["margin"] : void 0,
673048
673938
  bbox: Array.isArray(face["bbox"]) ? face["bbox"].map((n2) => Number(n2)).filter(Number.isFinite) : void 0
673049
673939
  }));
@@ -673126,7 +674016,7 @@ function activePendingVisualIdentities(store2, scope, sessionId, limit = 3) {
673126
674016
  pendingId,
673127
674017
  name: name10,
673128
674018
  relation: String(meta["relation"] || "depicts"),
673129
- confidence: clamp0111(meta["confidence"], 0.92),
674019
+ confidence: clamp0112(meta["confidence"], 0.92),
673130
674020
  note: typeof meta["note"] === "string" ? meta["note"] : void 0,
673131
674021
  episodeId: ep.id,
673132
674022
  createdAt: ep.timestamp,
@@ -673235,7 +674125,7 @@ function stageVisualIdentityAssertion(options2) {
673235
674125
  target: "next_visual_media",
673236
674126
  name: name10,
673237
674127
  relation: options2.relation || "depicts",
673238
- confidence: clamp0111(options2.confidence, 0.92),
674128
+ confidence: clamp0112(options2.confidence, 0.92),
673239
674129
  note: options2.note,
673240
674130
  createdAt: Date.now(),
673241
674131
  expiresAt
@@ -673243,7 +674133,7 @@ function stageVisualIdentityAssertion(options2) {
673243
674133
  identityAssertions: [{
673244
674134
  name: name10,
673245
674135
  relation: options2.relation || "named_as",
673246
- confidence: clamp0111(options2.confidence, 0.92),
674136
+ confidence: clamp0112(options2.confidence, 0.92),
673247
674137
  assertedBy: options2.sender,
673248
674138
  note: options2.note || "Explicit user-provided identity staged for the next visual media."
673249
674139
  }],
@@ -673274,7 +674164,7 @@ function stageVisualIdentityAssertion(options2) {
673274
674164
  target: "next_visual_media",
673275
674165
  name: name10,
673276
674166
  relation: options2.relation || "depicts",
673277
- confidence: clamp0111(options2.confidence, 0.92),
674167
+ confidence: clamp0112(options2.confidence, 0.92),
673278
674168
  note: options2.note,
673279
674169
  createdAt: Date.now(),
673280
674170
  expiresAt
@@ -673283,7 +674173,7 @@ function stageVisualIdentityAssertion(options2) {
673283
674173
  identityAssertions: [{
673284
674174
  name: name10,
673285
674175
  relation: options2.relation || "named_as",
673286
- confidence: clamp0111(options2.confidence, 0.92),
674176
+ confidence: clamp0112(options2.confidence, 0.92),
673287
674177
  assertedBy: options2.sender,
673288
674178
  note: options2.note || "Explicit user-provided identity staged for the next visual media."
673289
674179
  }]
@@ -682593,7 +683483,7 @@ ${result.output}`,
682593
683483
  });
682594
683484
 
682595
683485
  // packages/cli/src/tui/stimulation.ts
682596
- function clamp0112(value2) {
683486
+ function clamp0113(value2) {
682597
683487
  return Math.max(0, Math.min(1, value2));
682598
683488
  }
682599
683489
  function cloneState(state) {
@@ -682649,7 +683539,7 @@ var init_stimulation = __esm({
682649
683539
  ...DEFAULT_STATE,
682650
683540
  ...state,
682651
683541
  phase: normalizePhase(state.phase) ?? DEFAULT_STATE.phase,
682652
- attention: clamp0112(Number.isFinite(state.attention) ? Number(state.attention) : DEFAULT_STATE.attention),
683542
+ attention: clamp0113(Number.isFinite(state.attention) ? Number(state.attention) : DEFAULT_STATE.attention),
682653
683543
  updatedAtMs: Number.isFinite(state.updatedAtMs) ? Number(state.updatedAtMs) : now2,
682654
683544
  lastStimulusAtMs: Number.isFinite(state.lastStimulusAtMs) ? Number(state.lastStimulusAtMs) : now2,
682655
683545
  messagesSinceAnalysis: Math.max(0, Math.floor(Number(state.messagesSinceAnalysis ?? 0))),
@@ -682690,11 +683580,11 @@ var init_stimulation = __esm({
682690
683580
  applyAgentDecision(channelId, decision2, nowMs = Date.now()) {
682691
683581
  const state = this.stateFor(channelId, nowMs);
682692
683582
  if (Number.isFinite(decision2.attentionScore)) {
682693
- state.attention = clamp0112(Number(decision2.attentionScore));
683583
+ state.attention = clamp0113(Number(decision2.attentionScore));
682694
683584
  } else if (Number.isFinite(decision2.attentionDelta)) {
682695
- state.attention = clamp0112(state.attention + Number(decision2.attentionDelta));
683585
+ state.attention = clamp0113(state.attention + Number(decision2.attentionDelta));
682696
683586
  } else {
682697
- state.attention = clamp0112(state.attention + (decision2.shouldReply ? 0.22 : -0.1));
683587
+ state.attention = clamp0113(state.attention + (decision2.shouldReply ? 0.22 : -0.1));
682698
683588
  }
682699
683589
  if (decision2.phase) {
682700
683590
  state.attention = Math.max(state.attention, PHASE_FLOORS[decision2.phase]);
@@ -682750,7 +683640,7 @@ var init_stimulation = __esm({
682750
683640
  });
682751
683641
 
682752
683642
  // packages/cli/src/tui/pid-controller.ts
682753
- function clamp0113(x) {
683643
+ function clamp0114(x) {
682754
683644
  if (!Number.isFinite(x)) return 0;
682755
683645
  if (x < 0) return 0;
682756
683646
  if (x > 1) return 1;
@@ -682814,7 +683704,7 @@ var init_pid_controller = __esm({
682814
683704
  const dt = st.lastSampleAt > 0 ? now2 - st.lastSampleAt : 1e3;
682815
683705
  const derivative = dt > 0 ? (error - st.lastError) / dt : 0;
682816
683706
  const u = st.config.kp * error + st.config.ki * st.integral + st.config.kd * derivative;
682817
- st.output = clamp0113(st.output + u);
683707
+ st.output = clamp0114(st.output + u);
682818
683708
  st.lastError = error;
682819
683709
  st.lastSampleAt = now2;
682820
683710
  st.samples += 1;
@@ -683343,7 +684233,7 @@ function buildReplyOpportunities(input, openQuestions) {
683343
684233
  function daydreamOpportunityId(input, trigger) {
683344
684234
  return createHash42("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
683345
684235
  }
683346
- function clamp0114(value2) {
684236
+ function clamp0115(value2) {
683347
684237
  if (!Number.isFinite(value2)) return 0;
683348
684238
  return Math.max(0, Math.min(1, value2));
683349
684239
  }
@@ -683360,7 +684250,7 @@ function pushStimulationSignal(signals, signal, source, weight) {
683360
684250
  signals.push({
683361
684251
  signal: cleanSignal,
683362
684252
  source: cleanSource,
683363
- weight: clamp0114(weight)
684253
+ weight: clamp0115(weight)
683364
684254
  });
683365
684255
  }
683366
684256
  function buildMetaAnalysisSignals(input) {
@@ -683490,7 +684380,7 @@ function buildCuriosityThreads(input, openQuestions, stimulationSignals) {
683490
684380
  question: text2.endsWith("?") || text2.endsWith("?") ? text2 : `What should be learned or clarified from: ${text2 || entry.mediaSummary || "recent media"}?`,
683491
684381
  rationale: "Human curiosity, uncertainty, or multimodal content makes this a useful idle exploration target.",
683492
684382
  sourceMessages: messageId,
683493
- intensity: clamp0114(0.5 + replyBoost + mediaBoost + questionBoost)
684383
+ intensity: clamp0115(0.5 + replyBoost + mediaBoost + questionBoost)
683494
684384
  });
683495
684385
  }
683496
684386
  for (const question of openQuestions.slice(-4)) {
@@ -683513,7 +684403,7 @@ function buildCuriosityThreads(input, openQuestions, stimulationSignals) {
683513
684403
  question: `Is there a useful clarification or memory consolidation around ${strongest.source}?`,
683514
684404
  rationale: "Strongest stimulation signal can seed a low-intrusion reflection target.",
683515
684405
  sourceMessages: [],
683516
- intensity: clamp0114(strongest.weight * 0.72)
684406
+ intensity: clamp0115(strongest.weight * 0.72)
683517
684407
  });
683518
684408
  }
683519
684409
  return threads.sort((a2, b) => b.intensity - a2.intensity).slice(0, 8);
@@ -683593,7 +684483,7 @@ function buildOutreachPlans(input, curiosityThreads) {
683593
684483
  purpose: "Continue the public thread only when the live model judges that the group would benefit from a concise follow-up.",
683594
684484
  draftIntent: "Ask one concrete clarification, offer one useful synthesis, or stay silent if the room has moved on.",
683595
684485
  gate: "model_decision",
683596
- confidence: clamp0114(thread.intensity * 0.86)
684486
+ confidence: clamp0115(thread.intensity * 0.86)
683597
684487
  });
683598
684488
  const participant = participantForThread(input, thread);
683599
684489
  if (!participant) continue;
@@ -683605,7 +684495,7 @@ function buildOutreachPlans(input, curiosityThreads) {
683605
684495
  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.",
683606
684496
  draftIntent: "Reference the public thread briefly, ask permission to continue privately, and do not reveal hidden meta-analysis.",
683607
684497
  gate: "admin_review",
683608
- confidence: clamp0114(thread.intensity * 0.58)
684498
+ confidence: clamp0115(thread.intensity * 0.58)
683609
684499
  });
683610
684500
  }
683611
684501
  return plans.slice(0, 8);
@@ -684937,7 +685827,7 @@ function numberOr(value2, fallback) {
684937
685827
  function isNumber(value2) {
684938
685828
  return typeof value2 === "number" && Number.isFinite(value2);
684939
685829
  }
684940
- function clamp0115(value2) {
685830
+ function clamp0116(value2) {
684941
685831
  return Math.max(0, Math.min(1, Number.isFinite(value2) ? value2 : 0));
684942
685832
  }
684943
685833
  function iso(ts) {
@@ -685121,8 +686011,8 @@ function normalizeRelationship(raw) {
685121
686011
  kind: value2.kind,
685122
686012
  fromKey: String(value2.fromKey),
685123
686013
  toKey: String(value2.toKey),
685124
- confidence: clamp0115(numberOr(value2.confidence, 0)),
685125
- weight: clamp0115(numberOr(value2.weight, 0)),
686014
+ confidence: clamp0116(numberOr(value2.confidence, 0)),
686015
+ weight: clamp0116(numberOr(value2.weight, 0)),
685126
686016
  firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
685127
686017
  lastSeenAt: numberOr(value2.lastSeenAt, Date.now()),
685128
686018
  evidenceMessageIds: Array.isArray(value2.evidenceMessageIds) ? value2.evidenceMessageIds.filter(isNumber).slice(-40) : [],
@@ -685141,7 +686031,7 @@ function normalizePreferences(raw) {
685141
686031
  if (!evidence || typeof evidence !== "object") continue;
685142
686032
  out[actorKey][key] = {
685143
686033
  value: Math.max(-1, Math.min(1, numberOr(evidence.value, 0))),
685144
- confidence: clamp0115(numberOr(evidence.confidence, 0)),
686034
+ confidence: clamp0116(numberOr(evidence.confidence, 0)),
685145
686035
  updatedAt: numberOr(evidence.updatedAt, Date.now()),
685146
686036
  evidenceMessageIds: Array.isArray(evidence.evidenceMessageIds) ? evidence.evidenceMessageIds.filter(isNumber).slice(-12) : [],
685147
686037
  note: compactOptional(evidence.note, 220)
@@ -685155,7 +686045,7 @@ function normalizePreferences(raw) {
685155
686045
  out[actorKey].replyMode = {
685156
686046
  mode,
685157
686047
  scope: normalizeReplyPreferenceScope(record["scope"]),
685158
- confidence: clamp0115(numberOr(record["confidence"], 0.8)),
686048
+ confidence: clamp0116(numberOr(record["confidence"], 0.8)),
685159
686049
  updatedAt: numberOr(record["updatedAt"], Date.now()),
685160
686050
  evidenceMessageIds: Array.isArray(record["evidenceMessageIds"]) ? record["evidenceMessageIds"].filter(isNumber).slice(-12) : [],
685161
686051
  note: compactOptional(record["note"], 220),
@@ -685245,7 +686135,7 @@ function normalizeOutcome2(raw) {
685245
686135
  replyToMessageId: typeof value2.replyToMessageId === "number" ? value2.replyToMessageId : void 0,
685246
686136
  route: value2.route === "action" ? "action" : "chat",
685247
686137
  shouldReply: value2.shouldReply === true,
685248
- confidence: clamp0115(numberOr(value2.confidence, 0)),
686138
+ confidence: clamp0116(numberOr(value2.confidence, 0)),
685249
686139
  reason: compact3(value2.reason || "", 280),
685250
686140
  source: compact3(value2.source || "unknown", 80),
685251
686141
  silentDisposition: compactOptional(value2.silentDisposition, 280),
@@ -685257,7 +686147,7 @@ function normalizeOutcome2(raw) {
685257
686147
  scenarioNote: compactOptional(value2.scenarioNote, 360),
685258
686148
  scenarioId: compactOptional(value2.scenarioId, 160),
685259
686149
  scenarioLabel: compactOptional(value2.scenarioLabel, 160),
685260
- scenarioConfidence: typeof value2.scenarioConfidence === "number" && Number.isFinite(value2.scenarioConfidence) ? clamp0115(value2.scenarioConfidence) : void 0,
686150
+ scenarioConfidence: typeof value2.scenarioConfidence === "number" && Number.isFinite(value2.scenarioConfidence) ? clamp0116(value2.scenarioConfidence) : void 0,
685261
686151
  scenarioObjective: compactOptional(value2.scenarioObjective, 360),
685262
686152
  scenarioStateLoop: compactOptional(value2.scenarioStateLoop, 360),
685263
686153
  salienceSignals: Array.isArray(value2.salienceSignals) ? value2.salienceSignals.map(String).slice(0, 16) : [],
@@ -685275,7 +686165,7 @@ function normalizeDaydreamOpportunity(raw) {
685275
686165
  artifactId: String(value2.artifactId || "unknown"),
685276
686166
  generatedAt: String(value2.generatedAt || (/* @__PURE__ */ new Date()).toISOString()),
685277
686167
  trigger: compact3(value2.trigger || "", 240),
685278
- confidence: clamp0115(numberOr(value2.confidence, 0)),
686168
+ confidence: clamp0116(numberOr(value2.confidence, 0)),
685279
686169
  lifecycle,
685280
686170
  firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
685281
686171
  updatedAt: numberOr(value2.updatedAt, Date.now()),
@@ -685332,7 +686222,7 @@ function commitTelegramSocialDecision(state, input) {
685332
686222
  replyToMessageId: input.replyToMessageId,
685333
686223
  route: input.route,
685334
686224
  shouldReply: input.shouldReply,
685335
- confidence: clamp0115(input.confidence),
686225
+ confidence: clamp0116(input.confidence),
685336
686226
  reason: compact3(input.reason, 280),
685337
686227
  source: compact3(input.source, 80),
685338
686228
  silentDisposition: compactOptional(input.silentDisposition, 280),
@@ -685344,7 +686234,7 @@ function commitTelegramSocialDecision(state, input) {
685344
686234
  scenarioNote: compactOptional(input.scenarioNote, 360),
685345
686235
  scenarioId: compactOptional(input.scenarioId, 160),
685346
686236
  scenarioLabel: compactOptional(input.scenarioLabel, 160),
685347
- scenarioConfidence: input.scenarioConfidence === void 0 ? void 0 : clamp0115(input.scenarioConfidence),
686237
+ scenarioConfidence: input.scenarioConfidence === void 0 ? void 0 : clamp0116(input.scenarioConfidence),
685348
686238
  scenarioObjective: compactOptional(input.scenarioObjective, 360),
685349
686239
  scenarioStateLoop: compactOptional(input.scenarioStateLoop, 360),
685350
686240
  salienceSignals: [...new Set((input.salienceSignals ?? []).map(String))].slice(0, 16),
@@ -685368,7 +686258,7 @@ function registerDaydreamOpportunities(state, opportunities, now2 = Date.now())
685368
686258
  artifactId: opportunity.artifactId || "unknown",
685369
686259
  generatedAt: opportunity.generatedAt || new Date(now2).toISOString(),
685370
686260
  trigger: compact3(opportunity.trigger, 240),
685371
- confidence: clamp0115(opportunity.confidence),
686261
+ confidence: clamp0116(opportunity.confidence),
685372
686262
  lifecycle: "proposed",
685373
686263
  firstSeenAt: now2,
685374
686264
  updatedAt: now2,
@@ -685378,7 +686268,7 @@ function registerDaydreamOpportunities(state, opportunities, now2 = Date.now())
685378
686268
  };
685379
686269
  if (existing) {
685380
686270
  item.trigger = compact3(opportunity.trigger, 240) || item.trigger;
685381
- item.confidence = clamp0115(opportunity.confidence);
686271
+ item.confidence = clamp0116(opportunity.confidence);
685382
686272
  item.updatedAt = now2;
685383
686273
  }
685384
686274
  state.daydreamOpportunities[id2] = item;
@@ -685405,7 +686295,7 @@ function setTelegramReplyModePreference(state, input) {
685405
686295
  const next = {
685406
686296
  mode: input.mode,
685407
686297
  scope: input.scope,
685408
- confidence: Math.max(existing?.confidence ?? 0, clamp0115(input.confidence ?? 0.84)),
686298
+ confidence: Math.max(existing?.confidence ?? 0, clamp0116(input.confidence ?? 0.84)),
685409
686299
  updatedAt: now2,
685410
686300
  evidenceMessageIds: appendUnique(existing?.evidenceMessageIds ?? [], input.messageId, 12),
685411
686301
  note: compactOptional(input.note, 220),
@@ -685585,8 +686475,8 @@ function upsertRelationship(state, kind, fromKey, toKey, messageId, confidence2,
685585
686475
  evidenceMessageIds: [],
685586
686476
  source
685587
686477
  };
685588
- edge.confidence = Math.max(edge.confidence, clamp0115(confidence2));
685589
- edge.weight = Math.min(1, edge.weight + 0.12 + clamp0115(confidence2) * 0.2);
686478
+ edge.confidence = Math.max(edge.confidence, clamp0116(confidence2));
686479
+ edge.weight = Math.min(1, edge.weight + 0.12 + clamp0116(confidence2) * 0.2);
685590
686480
  edge.lastSeenAt = now2;
685591
686481
  edge.evidenceMessageIds = appendUnique(edge.evidenceMessageIds, messageId, 40);
685592
686482
  edge.note = compactOptional(note, 260) || edge.note;
@@ -685628,7 +686518,7 @@ function setPreference(vector, key, value2, confidence2, messageId, now2, note)
685628
686518
  const existing = vector[key];
685629
686519
  vector[key] = {
685630
686520
  value: existing ? existing.value * 0.7 + value2 * 0.3 : value2,
685631
- confidence: Math.max(existing?.confidence ?? 0, clamp0115(confidence2)),
686521
+ confidence: Math.max(existing?.confidence ?? 0, clamp0116(confidence2)),
685632
686522
  updatedAt: now2,
685633
686523
  evidenceMessageIds: appendUnique(existing?.evidenceMessageIds ?? [], messageId, 12),
685634
686524
  note
@@ -685810,7 +686700,7 @@ async function queryVisionModel(modelName, imagePath, prompt = "Describe what yo
685810
686700
  return "";
685811
686701
  }
685812
686702
  }
685813
- function clamp0116(value2, fallback = 0) {
686703
+ function clamp0117(value2, fallback = 0) {
685814
686704
  if (typeof value2 !== "number" || !Number.isFinite(value2)) return fallback;
685815
686705
  return Math.max(0, Math.min(1, value2));
685816
686706
  }
@@ -685827,9 +686717,9 @@ function parseVisualMemoryRecognize(raw) {
685827
686717
  label: String(match.label).trim(),
685828
686718
  objectId: typeof match.object_id === "string" ? match.object_id : void 0,
685829
686719
  matchedAlias: typeof match.matched_alias === "string" ? match.matched_alias : void 0,
685830
- blendedScore: clamp0116(match.blended_score, 0),
685831
- imageSimilarity: typeof match.image_similarity === "number" ? clamp0116(match.image_similarity, 0) : void 0,
685832
- textSimilarity: typeof match.text_similarity === "number" ? clamp0116(match.text_similarity, 0) : void 0
686720
+ blendedScore: clamp0117(match.blended_score, 0),
686721
+ imageSimilarity: typeof match.image_similarity === "number" ? clamp0117(match.image_similarity, 0) : void 0,
686722
+ textSimilarity: typeof match.text_similarity === "number" ? clamp0117(match.text_similarity, 0) : void 0
685833
686723
  })).sort((a2, b) => b.blendedScore - a2.blendedScore).slice(0, 5);
685834
686724
  }
685835
686725
  function formatVisualFamiliarityContext(result) {
@@ -690301,7 +691191,7 @@ ${message2}`)
690301
691191
  }
690302
691192
  telegramModelCachedBytes(dependencies) {
690303
691193
  return dependencies.reduce(
690304
- (sum, dep) => sum + measureRepoCacheBytes(dep),
691194
+ (sum2, dep) => sum2 + measureRepoCacheBytes(dep),
690305
691195
  0
690306
691196
  );
690307
691197
  }
@@ -690740,7 +691630,7 @@ install/prewarm: ${model.install}` : ""
690740
691630
  return `Deleted Ollama weights for ${model.id}.`;
690741
691631
  }
690742
691632
  const results = model.dependencies.map((repo) => deleteCachedModel(repo));
690743
- const freed = results.reduce((sum, item) => sum + item.bytesFreed, 0);
691633
+ const freed = results.reduce((sum2, item) => sum2 + item.bytesFreed, 0);
690744
691634
  const lines = results.map(
690745
691635
  (item) => `- ${item.repo}: ${item.bytesFreed > 0 ? formatModelBytes(item.bytesFreed) : "not cached"}`
690746
691636
  );
@@ -704590,7 +705480,7 @@ __export(voicechat_exports, {
704590
705480
  isLikelyAgentSpeechEcho: () => isLikelyAgentSpeechEcho
704591
705481
  });
704592
705482
  import { EventEmitter as EventEmitter12 } from "node:events";
704593
- function clamp0117(x) {
705483
+ function clamp0118(x) {
704594
705484
  return x < 0 ? 0 : x > 1 ? 1 : x;
704595
705485
  }
704596
705486
  function alnumRatio(s2) {
@@ -704643,9 +705533,9 @@ function computeSignalFromText(text2, confidence2) {
704643
705533
  score -= repeatingCharPenalty(t2) * 0.4;
704644
705534
  score -= gibberishTokenPenalty(t2) * 0.8;
704645
705535
  if (typeof confidence2 === "number" && !Number.isNaN(confidence2)) {
704646
- score = 0.7 * score + 0.3 * clamp0117(confidence2);
705536
+ score = 0.7 * score + 0.3 * clamp0118(confidence2);
704647
705537
  }
704648
- return clamp0117(score);
705538
+ return clamp0118(score);
704649
705539
  }
704650
705540
  function truncateForLog(s2, n2) {
704651
705541
  return s2.length <= n2 ? s2 : s2.slice(0, n2 - 1) + "…";
@@ -705139,7 +706029,7 @@ Rules:
705139
706029
  }
705140
706030
  }, MAX_SEGMENT_MS);
705141
706031
  }
705142
- const signalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp0117(snr) : computeSignalFromText(text2, confidence2);
706032
+ const signalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp0118(snr) : computeSignalFromText(text2, confidence2);
705143
706033
  this.lastSignalScore = signalScore;
705144
706034
  if (consensus !== void 0) {
705145
706035
  this.consensusMetadataSeen = true;
@@ -732226,10 +733116,10 @@ async function handleRequest(req3, res, ollamaUrl, verbose, runtimeDefaults = {}
732226
733116
  { encoding: "utf8", timeout: 3e3, stdio: "pipe" }
732227
733117
  );
732228
733118
  for (const line of util2.trim().split("\n")) {
732229
- const [pct, used, total] = line.split(",").map((s2) => parseInt(s2.trim(), 10));
732230
- if (!isNaN(pct) && !isNaN(used) && !isNaN(total)) {
733119
+ const [pct2, used, total] = line.split(",").map((s2) => parseInt(s2.trim(), 10));
733120
+ if (!isNaN(pct2) && !isNaN(used) && !isNaN(total)) {
732231
733121
  gpuUtil.push({
732232
- gpu_pct: pct,
733122
+ gpu_pct: pct2,
732233
733123
  vram_used_gb: Math.round(used / 1024 * 10) / 10,
732234
733124
  vram_total_gb: Math.round(total / 1024)
732235
733125
  });
@@ -735358,12 +736248,12 @@ function sampleGpuUtil() {
735358
736248
  const arr = [];
735359
736249
  for (const line of out.trim().split("\n")) {
735360
736250
  const [pctS, usedS, totalS] = line.split(",").map((s2) => s2.trim());
735361
- const pct = parseInt(pctS, 10);
736251
+ const pct2 = parseInt(pctS, 10);
735362
736252
  const usedGb = Math.round(parseInt(usedS, 10) / 1024 * 10) / 10;
735363
736253
  const totalGb = Math.round(parseInt(totalS, 10) / 1024);
735364
- if (!isNaN(pct) && !isNaN(usedGb) && !isNaN(totalGb))
736254
+ if (!isNaN(pct2) && !isNaN(usedGb) && !isNaN(totalGb))
735365
736255
  arr.push({
735366
- gpu_pct: pct,
736256
+ gpu_pct: pct2,
735367
736257
  vram_used_gb: usedGb,
735368
736258
  vram_total_gb: totalGb
735369
736259
  });