omnius 1.0.532 → 1.0.534

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
@@ -119389,7 +119389,7 @@ var require_auto = __commonJS({
119389
119389
  // ../node_modules/acme-client/src/client.js
119390
119390
  var require_client = __commonJS({
119391
119391
  "../node_modules/acme-client/src/client.js"(exports, module) {
119392
- var { createHash: createHash51 } = __require("crypto");
119392
+ var { createHash: createHash53 } = __require("crypto");
119393
119393
  var { getPemBodyAsB64u } = require_crypto();
119394
119394
  var { log: log22 } = require_logger();
119395
119395
  var HttpClient = require_http();
@@ -119700,14 +119700,14 @@ var require_client = __commonJS({
119700
119700
  */
119701
119701
  async getChallengeKeyAuthorization(challenge) {
119702
119702
  const jwk = this.http.getJwk();
119703
- const keysum = createHash51("sha256").update(JSON.stringify(jwk));
119703
+ const keysum = createHash53("sha256").update(JSON.stringify(jwk));
119704
119704
  const thumbprint = keysum.digest("base64url");
119705
119705
  const result = `${challenge.token}.${thumbprint}`;
119706
119706
  if (challenge.type === "http-01") {
119707
119707
  return result;
119708
119708
  }
119709
119709
  if (challenge.type === "dns-01") {
119710
- return createHash51("sha256").update(result).digest("base64url");
119710
+ return createHash53("sha256").update(result).digest("base64url");
119711
119711
  }
119712
119712
  if (challenge.type === "tls-alpn-01") {
119713
119713
  return result;
@@ -262387,7 +262387,7 @@ var require_websocket2 = __commonJS({
262387
262387
  var http6 = __require("http");
262388
262388
  var net5 = __require("net");
262389
262389
  var tls2 = __require("tls");
262390
- var { randomBytes: randomBytes31, createHash: createHash51 } = __require("crypto");
262390
+ var { randomBytes: randomBytes31, createHash: createHash53 } = __require("crypto");
262391
262391
  var { Duplex: Duplex3, Readable } = __require("stream");
262392
262392
  var { URL: URL3 } = __require("url");
262393
262393
  var PerMessageDeflate3 = require_permessage_deflate2();
@@ -263047,7 +263047,7 @@ var require_websocket2 = __commonJS({
263047
263047
  abortHandshake(websocket, socket, "Invalid Upgrade header");
263048
263048
  return;
263049
263049
  }
263050
- const digest3 = createHash51("sha1").update(key + GUID).digest("base64");
263050
+ const digest3 = createHash53("sha1").update(key + GUID).digest("base64");
263051
263051
  if (res.headers["sec-websocket-accept"] !== digest3) {
263052
263052
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
263053
263053
  return;
@@ -263414,7 +263414,7 @@ var require_websocket_server = __commonJS({
263414
263414
  var EventEmitter15 = __require("events");
263415
263415
  var http6 = __require("http");
263416
263416
  var { Duplex: Duplex3 } = __require("stream");
263417
- var { createHash: createHash51 } = __require("crypto");
263417
+ var { createHash: createHash53 } = __require("crypto");
263418
263418
  var extension3 = require_extension2();
263419
263419
  var PerMessageDeflate3 = require_permessage_deflate2();
263420
263420
  var subprotocol3 = require_subprotocol();
@@ -263715,7 +263715,7 @@ var require_websocket_server = __commonJS({
263715
263715
  );
263716
263716
  }
263717
263717
  if (this._state > RUNNING) return abortHandshake(socket, 503);
263718
- const digest3 = createHash51("sha1").update(key + GUID).digest("base64");
263718
+ const digest3 = createHash53("sha1").update(key + GUID).digest("base64");
263719
263719
  const headers = [
263720
263720
  "HTTP/1.1 101 Switching Protocols",
263721
263721
  "Upgrade: websocket",
@@ -276522,13 +276522,13 @@ Justification: ${justification || "(none provided)"}`,
276522
276522
  }
276523
276523
  const snapshot = JSON.stringify(this.selfState, null, 2);
276524
276524
  try {
276525
- const { createHash: createHash51 } = await import("node:crypto");
276525
+ const { createHash: createHash53 } = await import("node:crypto");
276526
276526
  const snapshotDir = join44(this.cwd, ".omnius", "identity", "snapshots");
276527
276527
  await mkdir7(snapshotDir, { recursive: true });
276528
276528
  const version5 = this.selfState.version;
276529
276529
  const snapshotPath = join44(snapshotDir, `v${version5}.json`);
276530
276530
  await writeFile12(snapshotPath, snapshot, "utf8");
276531
- const hash = createHash51("sha256").update(snapshot).digest("hex");
276531
+ const hash = createHash53("sha256").update(snapshot).digest("hex");
276532
276532
  await writeFile12(join44(this.cwd, ".omnius", "identity", "latest-hash.txt"), hash, "utf8");
276533
276533
  let ipfsCid = "";
276534
276534
  try {
@@ -276661,8 +276661,8 @@ New: ${newNarrative.slice(0, 200)}...`,
276661
276661
  }
276662
276662
  // ── Helpers ──────────────────────────────────────────────────────────────
276663
276663
  createDefaultState() {
276664
- const { createHash: createHash51 } = __require("node:crypto");
276665
- const machineId = createHash51("sha256").update(this.cwd).digest("hex").slice(0, 12);
276664
+ const { createHash: createHash53 } = __require("node:crypto");
276665
+ const machineId = createHash53("sha256").update(this.cwd).digest("hex").slice(0, 12);
276666
276666
  return {
276667
276667
  self_id: `omnius-${machineId}`,
276668
276668
  version: 1,
@@ -276744,9 +276744,9 @@ New: ${newNarrative.slice(0, 200)}...`,
276744
276744
  let cid;
276745
276745
  if (this.selfState.version > prevVersion) {
276746
276746
  try {
276747
- const { createHash: createHash51 } = await import("node:crypto");
276747
+ const { createHash: createHash53 } = await import("node:crypto");
276748
276748
  const stateJson = JSON.stringify(this.selfState);
276749
- const hash = createHash51("sha256").update(stateJson).digest("hex").slice(0, 32);
276749
+ const hash = createHash53("sha256").update(stateJson).digest("hex").slice(0, 32);
276750
276750
  const cidsPath = join44(this.cwd, ".omnius", "identity", "cids.json");
276751
276751
  const cidsData = { latest: "", hash, version: this.selfState.version };
276752
276752
  try {
@@ -297713,6 +297713,12 @@ function updateWorkboardCard(workingDir, input) {
297713
297713
  updates.lane = "blocked";
297714
297714
  if ((updates.status === "open" || updates.status === "in_progress") && card.lane === "blocked" && !updates.lane)
297715
297715
  updates.lane = "worker";
297716
+ validateSpecialCardAdmission({
297717
+ ...card,
297718
+ ...updates,
297719
+ evidenceRequirements: updates.evidenceRequirements ?? card.evidenceRequirements,
297720
+ ownedFiles: updates.ownedFiles ?? card.ownedFiles
297721
+ });
297716
297722
  const decisionReason = cleanString(input.decisionReason);
297717
297723
  const decision2 = decisionReason ? makeDecision(updates.assignee && updates.assignee !== card.assignee ? "reassigned" : updates.status === "blocked" ? "blocked" : "note", decisionReason, { cardId: card.id, actor: input.actor, createdAt: now2 }) : void 0;
297718
297724
  return appendWorkboardEvents(workingDir, runId, [{
@@ -297992,6 +297998,23 @@ function verifyCompileCardEvidence(card) {
297992
297998
  missing: ["fresh verifier output after patch"]
297993
297999
  };
297994
298000
  }
298001
+ function compactWorkboardCard(card) {
298002
+ return definedOnly({
298003
+ id: truncateForModel(card.id),
298004
+ title: truncateForModel(card.title),
298005
+ status: card.status,
298006
+ lane: card.lane,
298007
+ assignee: truncateForModel(card.assignee),
298008
+ dependencies: truncateStringArrayForModel(card.dependencies),
298009
+ evidenceCount: card.evidence.length,
298010
+ evidenceRequirements: truncateStringArrayForModel(card.evidenceRequirements),
298011
+ blocker: truncateForModel(card.blocker),
298012
+ diagnosticFingerprint: truncateForModel(card.diagnosticFingerprint),
298013
+ ownedFiles: truncateStringArrayForModel(card.ownedFiles),
298014
+ verifierCommand: truncateForModel(card.verifierCommand),
298015
+ rank: card.rank
298016
+ });
298017
+ }
297995
298018
  function compactWorkboardSnapshot(snapshot, maxCards = 24) {
297996
298019
  const counts = {
297997
298020
  open: 0,
@@ -298003,26 +298026,17 @@ function compactWorkboardSnapshot(snapshot, maxCards = 24) {
298003
298026
  };
298004
298027
  for (const card of snapshot.cards)
298005
298028
  counts[card.status]++;
298006
- const cards = snapshot.cards.slice(0, maxCards).map((card) => ({
298007
- id: card.id,
298008
- title: card.title,
298009
- status: card.status,
298010
- lane: card.lane,
298011
- assignee: card.assignee,
298012
- dependencies: card.dependencies,
298013
- evidenceCount: card.evidence.length,
298014
- evidenceRequirements: card.evidenceRequirements,
298015
- blocker: card.blocker
298016
- }));
298029
+ const cardLimit = Math.max(0, Math.min(50, Math.floor(maxCards)));
298030
+ const cards = snapshot.cards.slice(0, cardLimit).map(compactWorkboardCard);
298017
298031
  return {
298018
- runId: snapshot.runId,
298032
+ runId: truncateRequiredForModel(snapshot.runId),
298019
298033
  status: snapshot.status,
298020
- owner: snapshot.owner,
298034
+ owner: truncateRequiredForModel(snapshot.owner),
298021
298035
  updatedAt: snapshot.updatedAt,
298022
298036
  counts,
298023
298037
  cards,
298024
298038
  hiddenCardCount: Math.max(0, snapshot.cards.length - cards.length),
298025
- diagnostics: snapshot.diagnostics.slice(0, 12)
298039
+ diagnostics: snapshot.diagnostics.slice(0, WORKBOARD_MODEL_MAX_DIAGNOSTICS).map(compactWorkboardDiagnosticForModel)
298026
298040
  };
298027
298041
  }
298028
298042
  function formatWorkboardCompact(snapshot, maxCards = 24) {
@@ -298136,7 +298150,7 @@ function normalizeCardInput(input, timestamp) {
298136
298150
  assertEnum(input.role, VALID_ROLES, "role");
298137
298151
  const dependencies = normalizeStringArray(input.dependencies);
298138
298152
  const evidenceRequirements = normalizeStringArray(input.evidenceRequirements);
298139
- return {
298153
+ const card = {
298140
298154
  id: cleanString(input.id) || newCardId(),
298141
298155
  title,
298142
298156
  description: cleanString(input.description) || "",
@@ -298158,6 +298172,8 @@ function normalizeCardInput(input, timestamp) {
298158
298172
  verifierCommand: cleanString(input.verifierCommand),
298159
298173
  rank: typeof input.rank === "number" && Number.isFinite(input.rank) ? input.rank : void 0
298160
298174
  };
298175
+ validateSpecialCardAdmission(card);
298176
+ return card;
298161
298177
  }
298162
298178
  function normalizeCardUpdates(input) {
298163
298179
  const updates = {};
@@ -298199,6 +298215,26 @@ function normalizeCardUpdates(input) {
298199
298215
  throw new WorkboardError("empty_update", "at least one card field must be updated");
298200
298216
  return updates;
298201
298217
  }
298218
+ function validateSpecialCardAdmission(card) {
298219
+ const compileLike = card.id.startsWith("compile-") || Boolean(card.diagnosticFingerprint) || card.assignee?.startsWith("fixer:compile-") === true;
298220
+ if (compileLike) {
298221
+ const missing = [];
298222
+ if (!cleanString(card.diagnosticFingerprint))
298223
+ missing.push("diagnosticFingerprint");
298224
+ if (!cleanString(card.verifierCommand))
298225
+ missing.push("verifierCommand");
298226
+ if (!Array.isArray(card.ownedFiles) || card.ownedFiles.length === 0)
298227
+ missing.push("ownedFiles");
298228
+ if (missing.length > 0) {
298229
+ throw new WorkboardError("invalid_compile_card", `compile cards require ${missing.join(", ")}`, { cardId: card.id, missing });
298230
+ }
298231
+ }
298232
+ if (card.id.startsWith("failure-") && card.evidenceRequirements.length === 0) {
298233
+ throw new WorkboardError("invalid_failure_card", "failure recovery cards require explicit evidence requirements", {
298234
+ cardId: card.id
298235
+ });
298236
+ }
298237
+ }
298202
298238
  function validateDependencies(cardId, dependencies, knownCardIds) {
298203
298239
  for (const dependency of dependencies) {
298204
298240
  if (dependency === cardId) {
@@ -298398,6 +298434,75 @@ function evidenceMatchesRequirement(evidence, lowercaseRequirement) {
298398
298434
  function diagnosticKey(diagnostic) {
298399
298435
  return `${diagnostic.code}:${diagnostic.cardId ?? ""}:${diagnostic.assignee ?? ""}`;
298400
298436
  }
298437
+ function compactWorkboardDiagnosticForModel(diagnostic) {
298438
+ return definedOnly({
298439
+ ...diagnostic,
298440
+ id: truncateForModel(diagnostic.id),
298441
+ message: truncateForModel(diagnostic.message),
298442
+ cardId: truncateForModel(diagnostic.cardId),
298443
+ actor: truncateForModel(diagnostic.actor),
298444
+ assignee: truncateForModel(diagnostic.assignee),
298445
+ suggestedAction: truncateForModel(diagnostic.suggestedAction),
298446
+ details: diagnostic.details ? compactWorkboardToolPayload(diagnostic.details) : void 0
298447
+ });
298448
+ }
298449
+ function compactWorkboardToolPayload(value2, depth = 0) {
298450
+ if (depth > 5)
298451
+ return "[truncated]";
298452
+ if (typeof value2 === "string")
298453
+ return truncateForModel(value2);
298454
+ if (Array.isArray(value2)) {
298455
+ return value2.slice(0, WORKBOARD_MODEL_MAX_ARRAY_ITEMS).map((item) => compactWorkboardToolPayload(item, depth + 1));
298456
+ }
298457
+ if (!value2 || typeof value2 !== "object")
298458
+ return value2;
298459
+ if (isWorkboardSnapshot(value2))
298460
+ return compactWorkboardSnapshot(value2, WORKBOARD_MODEL_MAX_CARDS);
298461
+ if (isWorkboardCard(value2))
298462
+ return compactWorkboardCard(value2);
298463
+ const out = {};
298464
+ for (const [key, item] of Object.entries(value2)) {
298465
+ if (key === "snapshot" && isWorkboardSnapshot(item)) {
298466
+ out["board"] = compactWorkboardSnapshot(item, WORKBOARD_MODEL_MAX_CARDS);
298467
+ continue;
298468
+ }
298469
+ if (key === "card" && isWorkboardCard(item)) {
298470
+ out[key] = compactWorkboardCard(item);
298471
+ continue;
298472
+ }
298473
+ if (key === "cards" && Array.isArray(item)) {
298474
+ out[key] = item.slice(0, WORKBOARD_MODEL_MAX_CARDS).map((card) => isWorkboardCard(card) ? compactWorkboardCard(card) : compactWorkboardToolPayload(card, depth + 1));
298475
+ continue;
298476
+ }
298477
+ out[key] = compactWorkboardToolPayload(item, depth + 1);
298478
+ }
298479
+ return out;
298480
+ }
298481
+ function isWorkboardSnapshot(value2) {
298482
+ const record = value2;
298483
+ return record.schemaVersion === WORKBOARD_SCHEMA_VERSION && Array.isArray(record.cards) && typeof record.runId === "string";
298484
+ }
298485
+ function isWorkboardCard(value2) {
298486
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2))
298487
+ return false;
298488
+ const record = value2;
298489
+ return typeof record.id === "string" && typeof record.title === "string" && typeof record.status === "string" && Array.isArray(record.evidence);
298490
+ }
298491
+ function truncateForModel(value2) {
298492
+ if (!value2)
298493
+ return void 0;
298494
+ if (value2.length <= WORKBOARD_MODEL_MAX_STRING)
298495
+ return value2;
298496
+ return `${value2.slice(0, WORKBOARD_MODEL_MAX_STRING - 15)}...[truncated]`;
298497
+ }
298498
+ function truncateRequiredForModel(value2) {
298499
+ return truncateForModel(value2) ?? "";
298500
+ }
298501
+ function truncateStringArrayForModel(value2) {
298502
+ if (!Array.isArray(value2))
298503
+ return [];
298504
+ return value2.slice(0, WORKBOARD_MODEL_MAX_ARRAY_ITEMS).map((item) => truncateForModel(item)).filter((item) => Boolean(item));
298505
+ }
298401
298506
  function defaultLaneForStatus(status) {
298402
298507
  if (status === "blocked")
298403
298508
  return "blocked";
@@ -298660,11 +298765,15 @@ function enumArg(args, name10, allowed) {
298660
298765
  assertEnum(value2, allowed, name10);
298661
298766
  return value2;
298662
298767
  }
298663
- var WORKBOARD_SCHEMA_VERSION, WorkboardError, activeWorkboardWrites, VALID_LANES, VALID_STATUSES, VALID_ROLES, VALID_EVIDENCE_KINDS, REPEATED_FAILURE_THRESHOLD, WorkboardBaseTool, WorkboardCreateTool, WorkboardAddCardTool, WorkboardUpdateCardTool, WorkboardAttachEvidenceTool, WorkboardCompleteCardTool, WorkboardShowTool;
298768
+ var WORKBOARD_SCHEMA_VERSION, WORKBOARD_MODEL_MAX_CARDS, WORKBOARD_MODEL_MAX_ARRAY_ITEMS, WORKBOARD_MODEL_MAX_DIAGNOSTICS, WORKBOARD_MODEL_MAX_STRING, WorkboardError, activeWorkboardWrites, VALID_LANES, VALID_STATUSES, VALID_ROLES, VALID_EVIDENCE_KINDS, REPEATED_FAILURE_THRESHOLD, WorkboardBaseTool, WorkboardCreateTool, WorkboardAddCardTool, WorkboardUpdateCardTool, WorkboardAttachEvidenceTool, WorkboardCompleteCardTool, WorkboardShowTool;
298664
298769
  var init_workboard = __esm({
298665
298770
  "packages/execution/dist/tools/workboard.js"() {
298666
298771
  "use strict";
298667
298772
  WORKBOARD_SCHEMA_VERSION = 1;
298773
+ WORKBOARD_MODEL_MAX_CARDS = 8;
298774
+ WORKBOARD_MODEL_MAX_ARRAY_ITEMS = 8;
298775
+ WORKBOARD_MODEL_MAX_DIAGNOSTICS = 8;
298776
+ WORKBOARD_MODEL_MAX_STRING = 260;
298668
298777
  WorkboardError = class extends Error {
298669
298778
  code;
298670
298779
  details;
@@ -298691,18 +298800,22 @@ var init_workboard = __esm({
298691
298800
  }
298692
298801
  result(start2, payload, mutated, runId) {
298693
298802
  const mutatedFiles = mutated && runId ? [workboardPaths(this.workingDir, runId).eventsPath, workboardPaths(this.workingDir, runId).activePath] : void 0;
298803
+ const modelPayload = compactWorkboardToolPayload(payload);
298694
298804
  return {
298695
298805
  success: true,
298696
298806
  output: JSON.stringify(payload),
298807
+ llmContent: JSON.stringify(modelPayload),
298697
298808
  durationMs: performance.now() - start2,
298698
298809
  mutated,
298699
298810
  mutatedFiles
298700
298811
  };
298701
298812
  }
298702
298813
  failure(start2, code8, message2, details, output) {
298814
+ const payload = output ?? { ok: false, code: code8, message: message2, details };
298703
298815
  return {
298704
298816
  success: false,
298705
- output: JSON.stringify(output ?? { ok: false, code: code8, message: message2, details }),
298817
+ output: JSON.stringify(payload),
298818
+ llmContent: JSON.stringify(compactWorkboardToolPayload(payload)),
298706
298819
  error: message2,
298707
298820
  durationMs: performance.now() - start2
298708
298821
  };
@@ -298747,7 +298860,7 @@ var init_workboard = __esm({
298747
298860
  actor: stringArg(args, "actor"),
298748
298861
  cards: normalizeCardsArg(args["cards"])
298749
298862
  });
298750
- return this.result(start2, { ok: true, board: compactWorkboardSnapshot(snapshot), snapshot }, true, runId);
298863
+ return this.result(start2, { ok: true, board: compactWorkboardSnapshot(snapshot) }, true, runId);
298751
298864
  } catch (err) {
298752
298865
  return this.catchFailure(start2, err);
298753
298866
  }
@@ -298784,7 +298897,7 @@ var init_workboard = __esm({
298784
298897
  actor: stringArg(args, "actor"),
298785
298898
  decisionReason: stringArg(args, "decision_reason", "decisionReason")
298786
298899
  });
298787
- return this.result(start2, { ok: true, board: compactWorkboardSnapshot(snapshot), card: snapshot.cards.at(-1) }, true, runId);
298900
+ return this.result(start2, { ok: true, board: compactWorkboardSnapshot(snapshot), card: compactWorkboardCard(snapshot.cards.at(-1)) }, true, runId);
298788
298901
  } catch (err) {
298789
298902
  return this.catchFailure(start2, err);
298790
298903
  }
@@ -298826,7 +298939,8 @@ var init_workboard = __esm({
298826
298939
  decisionReason: stringArg(args, "decision_reason", "decisionReason"),
298827
298940
  updates
298828
298941
  });
298829
- return this.result(start2, { ok: true, board: compactWorkboardSnapshot(snapshot), card: snapshot.cards.find((card) => card.id === cardId) }, true, runId);
298942
+ const card = snapshot.cards.find((card2) => card2.id === cardId);
298943
+ return this.result(start2, { ok: true, board: compactWorkboardSnapshot(snapshot), ...card ? { card: compactWorkboardCard(card) } : {} }, true, runId);
298830
298944
  } catch (err) {
298831
298945
  return this.catchFailure(start2, err);
298832
298946
  }
@@ -298873,7 +298987,8 @@ var init_workboard = __esm({
298873
298987
  actor: stringArg(args, "actor"),
298874
298988
  evidence
298875
298989
  });
298876
- return this.result(start2, { ok: true, board: compactWorkboardSnapshot(snapshot), card: snapshot.cards.find((card) => card.id === cardId) }, true, runId);
298990
+ const card = snapshot.cards.find((card2) => card2.id === cardId);
298991
+ return this.result(start2, { ok: true, board: compactWorkboardSnapshot(snapshot), ...card ? { card: compactWorkboardCard(card) } : {} }, true, runId);
298877
298992
  } catch (err) {
298878
298993
  return this.catchFailure(start2, err);
298879
298994
  }
@@ -298925,7 +299040,12 @@ var init_workboard = __esm({
298925
299040
  board: compactWorkboardSnapshot(result.snapshot)
298926
299041
  });
298927
299042
  }
298928
- return this.result(start2, { ok: true, message: result.message, board: compactWorkboardSnapshot(result.snapshot), card: result.card }, true, runId);
299043
+ return this.result(start2, {
299044
+ ok: true,
299045
+ message: result.message,
299046
+ board: compactWorkboardSnapshot(result.snapshot),
299047
+ ...result.card ? { card: compactWorkboardCard(result.card) } : {}
299048
+ }, true, runId);
298929
299049
  } catch (err) {
298930
299050
  return this.catchFailure(start2, err);
298931
299051
  }
@@ -439258,14 +439378,14 @@ ${lanes.join("\n")}
439258
439378
  }
439259
439379
  if (diagnostic.relatedInformation) {
439260
439380
  output += host.getNewLine();
439261
- for (const { file, start: start2, length: length22, messageText } of diagnostic.relatedInformation) {
439381
+ for (const { file, start: start2, length: length22, messageText: messageText2 } of diagnostic.relatedInformation) {
439262
439382
  if (file) {
439263
439383
  output += host.getNewLine();
439264
439384
  output += halfIndent + formatLocation(file, start2, host);
439265
439385
  output += formatCodeSpan(file, start2, length22, indent2, "\x1B[96m", host);
439266
439386
  }
439267
439387
  output += host.getNewLine();
439268
- output += indent2 + flattenDiagnosticMessageText(messageText, host.getNewLine());
439388
+ output += indent2 + flattenDiagnosticMessageText(messageText2, host.getNewLine());
439269
439389
  }
439270
439390
  }
439271
439391
  output += host.getNewLine();
@@ -473931,8 +474051,8 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
473931
474051
  }
473932
474052
  }
473933
474053
  }
473934
- function tryGetConstraintFromDiagnosticMessage(messageText) {
473935
- const [, constraint] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [];
474054
+ function tryGetConstraintFromDiagnosticMessage(messageText2) {
474055
+ const [, constraint] = flattenDiagnosticMessageText(messageText2, "\n", 0).match(/`extends (.*)`/) || [];
473936
474056
  return constraint;
473937
474057
  }
473938
474058
  function tryGetConstraintType(checker, node) {
@@ -475979,8 +476099,8 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
475979
476099
  operator === 38 || operator === 36 ? factory.createPrefixUnaryExpression(54, callExpression) : callExpression
475980
476100
  );
475981
476101
  }
475982
- function getSuggestion(messageText) {
475983
- const [, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/'(.*)'/) || [];
476102
+ function getSuggestion(messageText2) {
476103
+ const [, suggestion] = flattenDiagnosticMessageText(messageText2, "\n", 0).match(/'(.*)'/) || [];
475984
476104
  return suggestion;
475985
476105
  }
475986
476106
  registerCodeFix({
@@ -541096,13 +541216,13 @@ Node text: ${this.#forgottenText}`;
541096
541216
  return file == null ? void 0 : this._context.compilerFactory.getSourceFile(file, { markInProject: false });
541097
541217
  }
541098
541218
  getMessageText() {
541099
- const messageText = this._compilerObject.messageText;
541100
- if (typeof messageText === "string")
541101
- return messageText;
541219
+ const messageText2 = this._compilerObject.messageText;
541220
+ if (typeof messageText2 === "string")
541221
+ return messageText2;
541102
541222
  if (this._context == null)
541103
- return new DiagnosticMessageChain(messageText);
541223
+ return new DiagnosticMessageChain(messageText2);
541104
541224
  else
541105
- return this._context.compilerFactory.getDiagnosticMessageChain(messageText);
541225
+ return this._context.compilerFactory.getDiagnosticMessageChain(messageText2);
541106
541226
  }
541107
541227
  getLineNumber() {
541108
541228
  const sourceFile = this.getSourceFile();
@@ -553029,7 +553149,28 @@ print(json.dumps({"ok": False, "error": "No whisper backend available"}))
553029
553149
 
553030
553150
  // packages/execution/dist/tools/full-sub-agent.js
553031
553151
  import { spawn as spawn19, ChildProcess } from "node:child_process";
553032
- import { randomBytes as randomBytes18 } from "node:crypto";
553152
+ import { createHash as createHash24, randomBytes as randomBytes18 } from "node:crypto";
553153
+ function fullSubAgentTaskHash(task) {
553154
+ return createHash24("sha256").update(task).digest("hex").slice(0, 12);
553155
+ }
553156
+ function sanitizeFullSubAgentModelText(value2, maxChars = FULL_SUB_AGENT_MODEL_MAX_CHARS) {
553157
+ const stripped = value2.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/<think>[\s\S]*?<\/think>/gi, "").replace(/<think>[\s\S]*$/gi, "");
553158
+ const lines = stripped.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).filter((line) => !/^🔊/.test(line)).filter((line) => !/SHELL TRANSCRIPT/i.test(line)).filter((line) => !/^Task:\s/i.test(line)).filter((line) => !/^E Task timeout/i.test(line)).filter((line) => !/^E Incomplete:/i.test(line)).filter((line) => !/^⚠ Task incomplete/i.test(line)).slice(-FULL_SUB_AGENT_MODEL_MAX_LINES);
553159
+ const joined = lines.join("\n");
553160
+ return joined.length > maxChars ? `${joined.slice(0, Math.max(0, maxChars - 14)).trimEnd()}...[truncated]` : joined;
553161
+ }
553162
+ function fullSubAgentModelContent(input) {
553163
+ const taskPreview = sanitizeFullSubAgentModelText(input.task, 220);
553164
+ const resultPreview = input.output ? sanitizeFullSubAgentModelText(input.output) : "";
553165
+ return [
553166
+ `[full_sub_agent] id=${input.id} status=${input.status} exit_code=${input.exitCode ?? "unknown"} task_sha256=${fullSubAgentTaskHash(input.task)} output_lines=${input.outputLines ?? 0}`,
553167
+ taskPreview ? `task_preview:
553168
+ ${taskPreview}` : null,
553169
+ resultPreview ? `result_preview:
553170
+ ${resultPreview}` : null,
553171
+ `full_output_available_via=full_sub_agent action=output id=${input.id}`
553172
+ ].filter((line) => Boolean(line)).join("\n");
553173
+ }
553033
553174
  function buildSubProcessArgs(opts) {
553034
553175
  const args = [];
553035
553176
  args.push(opts.task);
@@ -553193,7 +553334,7 @@ function killAllFullSubAgents() {
553193
553334
  function removeFullSubAgent(id2) {
553194
553335
  _activeSubProcesses.delete(id2);
553195
553336
  }
553196
- var _activeSubProcesses, FullSubAgentTool;
553337
+ var _activeSubProcesses, FULL_SUB_AGENT_MODEL_MAX_LINES, FULL_SUB_AGENT_MODEL_MAX_CHARS, FullSubAgentTool;
553197
553338
  var init_full_sub_agent = __esm({
553198
553339
  "packages/execution/dist/tools/full-sub-agent.js"() {
553199
553340
  "use strict";
@@ -553201,6 +553342,8 @@ var init_full_sub_agent = __esm({
553201
553342
  init_model_broker();
553202
553343
  init_process_lifecycle();
553203
553344
  _activeSubProcesses = /* @__PURE__ */ new Map();
553345
+ FULL_SUB_AGENT_MODEL_MAX_LINES = 6;
553346
+ FULL_SUB_AGENT_MODEL_MAX_CHARS = 900;
553204
553347
  FullSubAgentTool = class {
553205
553348
  name = "full_sub_agent";
553206
553349
  description = "Spawn a COMPLETE Omnius sub-process with ALL tools and capabilities. Unlike sub_agent (shared process, limited tools), this spawns a separate omnius instance with its own clean context window, full tool set, memory, skills, and COHERE access. Use for complex multi-file tasks that benefit from a fresh context. The sub-process runs omnius --non-interactive until task_complete, abort, or timeout. By default this tool returns immediately with a process ID for monitoring; set wait=true to block until the child exits.";
@@ -553326,6 +553469,14 @@ var init_full_sub_agent = __esm({
553326
553469
  Output lines: ${entry.outputBuffer.length}` + (tail ? `
553327
553470
 
553328
553471
  ${tail}` : ""),
553472
+ llmContent: fullSubAgentModelContent({
553473
+ id: entry.id,
553474
+ task,
553475
+ status: "completed",
553476
+ exitCode,
553477
+ output: tail || output,
553478
+ outputLines: entry.outputBuffer.length
553479
+ }),
553329
553480
  durationMs
553330
553481
  };
553331
553482
  }
@@ -553334,19 +553485,35 @@ ${tail}` : ""),
553334
553485
  output: output ? `Full Omnius sub-agent failed: ${entry.id}
553335
553486
 
553336
553487
  ${tail || output}` : "",
553488
+ llmContent: fullSubAgentModelContent({
553489
+ id: entry.id,
553490
+ task,
553491
+ status: "failed",
553492
+ exitCode,
553493
+ output: tail || output,
553494
+ outputLines: entry.outputBuffer.length
553495
+ }),
553337
553496
  error: `Full Omnius sub-agent exited before successful completion (exit code ${exitCode ?? "unknown"}).`,
553338
553497
  durationMs
553339
553498
  };
553340
553499
  }
553500
+ const taskPreview = sanitizeFullSubAgentModelText(task, 220);
553341
553501
  return {
553342
553502
  success: true,
553343
553503
  output: `Full Omnius sub-agent spawned: ${entry.id}
553344
553504
  PID: ${entry.pid}
553345
553505
  Model: ${model}
553346
- Task: ${task.slice(0, 100)}
553347
- Use full_sub_agent(action='status', id='${entry.id}') to check progress.
553506
+ task_sha256=${fullSubAgentTaskHash(task)}
553507
+ ` + (taskPreview ? ` task_preview: ${taskPreview.replace(/\n/g, " ")}
553508
+ ` : "") + ` Use full_sub_agent(action='status', id='${entry.id}') to check progress.
553348
553509
  Use full_sub_agent(action='output', id='${entry.id}') to see output.
553349
553510
  Use full_sub_agent(action='stop', id='${entry.id}') to kill it.`,
553511
+ llmContent: fullSubAgentModelContent({
553512
+ id: entry.id,
553513
+ task,
553514
+ status: "running",
553515
+ outputLines: entry.outputBuffer.length
553516
+ }),
553350
553517
  durationMs: performance.now() - start2
553351
553518
  };
553352
553519
  }
@@ -553362,6 +553529,13 @@ ${tail || output}` : "",
553362
553529
  output: `${id2} [${entry.status}] PID:${entry.pid} ${runtime}s
553363
553530
  Task: ${entry.task.slice(0, 100)}
553364
553531
  Output lines: ${entry.outputBuffer.length}`,
553532
+ llmContent: fullSubAgentModelContent({
553533
+ id: id2,
553534
+ task: entry.task,
553535
+ status: entry.status,
553536
+ exitCode: entry.exitCode,
553537
+ outputLines: entry.outputBuffer.length
553538
+ }),
553365
553539
  durationMs: performance.now() - start2
553366
553540
  };
553367
553541
  }
@@ -553372,7 +553546,18 @@ ${tail || output}` : "",
553372
553546
  const runtime = ((Date.now() - e2.startedAt) / 1e3).toFixed(0);
553373
553547
  return `${e2.id} [${e2.status}] PID:${e2.pid} ${runtime}s — ${e2.task.slice(0, 60)}`;
553374
553548
  });
553375
- return { success: true, output: lines.join("\n"), durationMs: performance.now() - start2 };
553549
+ return {
553550
+ success: true,
553551
+ output: lines.join("\n"),
553552
+ llmContent: all2.map((e2) => fullSubAgentModelContent({
553553
+ id: e2.id,
553554
+ task: e2.task,
553555
+ status: e2.status,
553556
+ exitCode: e2.exitCode,
553557
+ outputLines: e2.outputBuffer.length
553558
+ })).join("\n\n"),
553559
+ durationMs: performance.now() - start2
553560
+ };
553376
553561
  }
553377
553562
  case "list":
553378
553563
  return this.execute({ ...args, action: "status" });
@@ -553382,8 +553567,20 @@ ${tail || output}` : "",
553382
553567
  if (!entry)
553383
553568
  return { success: false, output: "", error: `Unknown sub-agent: ${id2}`, durationMs: performance.now() - start2 };
553384
553569
  const tail = entry.outputBuffer.slice(-50).join("\n");
553385
- return { success: true, output: `${id2} output (last 50 lines):
553386
- ${tail}`, durationMs: performance.now() - start2 };
553570
+ return {
553571
+ success: true,
553572
+ output: `${id2} output (last 50 lines):
553573
+ ${tail}`,
553574
+ llmContent: fullSubAgentModelContent({
553575
+ id: id2,
553576
+ task: entry.task,
553577
+ status: entry.status,
553578
+ exitCode: entry.exitCode,
553579
+ output: tail,
553580
+ outputLines: entry.outputBuffer.length
553581
+ }),
553582
+ durationMs: performance.now() - start2
553583
+ };
553387
553584
  }
553388
553585
  case "stop": {
553389
553586
  const id2 = String(args["id"] ?? "");
@@ -555507,7 +555704,7 @@ var init_client3 = __esm({
555507
555704
  import { existsSync as existsSync73, readFileSync as readFileSync52, writeFileSync as writeFileSync35, mkdirSync as mkdirSync44, chmodSync, statSync as statSync30 } from "node:fs";
555508
555705
  import { join as join85, dirname as dirname23 } from "node:path";
555509
555706
  import { homedir as homedir23 } from "node:os";
555510
- import { randomBytes as randomBytes19, createHash as createHash24 } from "node:crypto";
555707
+ import { randomBytes as randomBytes19, createHash as createHash25 } from "node:crypto";
555511
555708
  function secretsPath(scope, repoRoot) {
555512
555709
  return scope === "global" ? join85(homedir23(), ".omnius", "secrets.json") : join85(repoRoot, ".omnius", "secrets.json");
555513
555710
  }
@@ -555548,7 +555745,7 @@ function sanitizeHint(hint) {
555548
555745
  return hint.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 32) || "GENERIC";
555549
555746
  }
555550
555747
  function shortDigest(value2) {
555551
- return createHash24("sha256").update(value2).digest("hex").slice(0, 6);
555748
+ return createHash25("sha256").update(value2).digest("hex").slice(0, 6);
555552
555749
  }
555553
555750
  function randomSuffix() {
555554
555751
  return randomBytes19(3).toString("hex");
@@ -557362,7 +557559,7 @@ var init_environment_snapshot = __esm({
557362
557559
  import { existsSync as existsSync77, mkdirSync as mkdirSync46, writeFileSync as writeFileSync38, readFileSync as readFileSync56, readdirSync as readdirSync26, unlinkSync as unlinkSync16, rmSync as rmSync10 } from "node:fs";
557363
557560
  import { join as join88, basename as basename18, isAbsolute as isAbsolute8, resolve as resolve46 } from "node:path";
557364
557561
  import { homedir as homedir26 } from "node:os";
557365
- import { createHash as createHash25 } from "node:crypto";
557562
+ import { createHash as createHash26 } from "node:crypto";
557366
557563
  function isYouTubeUrl2(url) {
557367
557564
  return /(?:youtube\.com\/(?:watch|shorts|live|embed|v\/)|youtu\.be\/)/i.test(url);
557368
557565
  }
@@ -557447,7 +557644,7 @@ async function extractAudioIfPresent(videoPath, audioPath, probe) {
557447
557644
  function imageHash(imagePath) {
557448
557645
  try {
557449
557646
  const data = readFileSync56(imagePath);
557450
- return createHash25("md5").update(data).digest("hex").slice(0, 12);
557647
+ return createHash26("md5").update(data).digest("hex").slice(0, 12);
557451
557648
  } catch {
557452
557649
  return "unknown";
557453
557650
  }
@@ -569598,14 +569795,14 @@ var init_artifact_inspector = __esm({
569598
569795
  // packages/orchestrator/dist/lesson-bank.js
569599
569796
  import { existsSync as existsSync91, mkdirSync as mkdirSync52, appendFileSync as appendFileSync7, readFileSync as readFileSync69 } from "node:fs";
569600
569797
  import { join as join101, dirname as dirname30 } from "node:path";
569601
- import { createHash as createHash26 } from "node:crypto";
569798
+ import { createHash as createHash27 } from "node:crypto";
569602
569799
  function tokenize4(text2) {
569603
569800
  if (!text2)
569604
569801
  return [];
569605
569802
  return text2.toLowerCase().split(TOKENIZE_RE).filter((t2) => t2.length >= 3).slice(0, 80);
569606
569803
  }
569607
569804
  function shortHash(s2) {
569608
- return createHash26("sha256").update(s2).digest("hex").slice(0, 16);
569805
+ return createHash27("sha256").update(s2).digest("hex").slice(0, 16);
569609
569806
  }
569610
569807
  function solicit(args) {
569611
569808
  const { taskGoal, stem, reflections, successOutputPreview } = args;
@@ -569701,7 +569898,7 @@ var init_lesson_bank = __esm({
569701
569898
  // packages/orchestrator/dist/intervention-replay.js
569702
569899
  import { existsSync as existsSync92, mkdirSync as mkdirSync53, readFileSync as readFileSync70, writeFileSync as writeFileSync43, readdirSync as readdirSync29 } from "node:fs";
569703
569900
  import { join as join102, dirname as dirname31 } from "node:path";
569704
- import { createHash as createHash27 } from "node:crypto";
569901
+ import { createHash as createHash28 } from "node:crypto";
569705
569902
  function checkpointDir2(workingDir) {
569706
569903
  return workingDir ? join102(workingDir, ".omnius", "checkpoints") : join102(process.env["HOME"] || ".", ".omnius", "checkpoints");
569707
569904
  }
@@ -569735,7 +569932,7 @@ function sanitizeMessagesForCheckpoint(messages2) {
569735
569932
  deduped.push(m2);
569736
569933
  continue;
569737
569934
  }
569738
- const digest3 = createHash27("sha1").update(content).digest("hex");
569935
+ const digest3 = createHash28("sha1").update(content).digest("hex");
569739
569936
  if (seenSystemDigests.has(digest3))
569740
569937
  continue;
569741
569938
  seenSystemDigests.add(digest3);
@@ -573691,12 +573888,12 @@ var init_codeGraphLink = __esm({
573691
573888
  });
573692
573889
 
573693
573890
  // packages/orchestrator/dist/artifactContract.js
573694
- import { createHash as createHash28 } from "node:crypto";
573891
+ import { createHash as createHash29 } from "node:crypto";
573695
573892
  function shortHash2(content) {
573696
573893
  if (!content)
573697
573894
  return "empty";
573698
573895
  try {
573699
- return createHash28("sha256").update(content.slice(0, 4096)).digest("hex").slice(0, 8);
573896
+ return createHash29("sha256").update(content.slice(0, 4096)).digest("hex").slice(0, 8);
573700
573897
  } catch {
573701
573898
  let h = 2166136261;
573702
573899
  for (let i2 = 0; i2 < Math.min(content.length, 4096); i2++) {
@@ -576749,6 +576946,50 @@ function collectMetadataReports(signals) {
576749
576946
  forgettingReports: forgettingReports.length > 0 ? forgettingReports : void 0
576750
576947
  };
576751
576948
  }
576949
+ function signalIdentityKeys(signal) {
576950
+ return [
576951
+ signal.dedupeKey,
576952
+ signal.semanticKey,
576953
+ `${signal.kind}:${signal.id}`,
576954
+ signal.id,
576955
+ ...signal.tags ?? []
576956
+ ].flatMap((key) => {
576957
+ const clean5 = typeof key === "string" ? key.trim() : "";
576958
+ return clean5 ? [clean5] : [];
576959
+ });
576960
+ }
576961
+ function choosePreferredSignal(a2, b) {
576962
+ const pa = a2.priority ?? 0;
576963
+ const pb = b.priority ?? 0;
576964
+ if (pa !== pb)
576965
+ return pa > pb ? a2 : b;
576966
+ const ta = a2.createdTurn ?? 0;
576967
+ const tb = b.createdTurn ?? 0;
576968
+ if (ta !== tb)
576969
+ return ta > tb ? a2 : b;
576970
+ return a2.sequence > b.sequence ? a2 : b;
576971
+ }
576972
+ function sortSignals(a2, b) {
576973
+ const pa = a2.priority ?? 0;
576974
+ const pb = b.priority ?? 0;
576975
+ if (pa !== pb)
576976
+ return pb - pa;
576977
+ const ta = a2.createdTurn ?? 0;
576978
+ const tb = b.createdTurn ?? 0;
576979
+ if (ta !== tb)
576980
+ return tb - ta;
576981
+ return a2.source.localeCompare(b.source) || a2.id.localeCompare(b.id);
576982
+ }
576983
+ function semanticKeyFor(signal) {
576984
+ const key = signal.semanticKey ?? signal.dedupeKey;
576985
+ return typeof key === "string" && key.trim() ? key.trim() : null;
576986
+ }
576987
+ function isControlSignal(signal) {
576988
+ return signal.kind === "runtime_guidance" || signal.kind === "action_contract" || signal.kind === "recent_failure";
576989
+ }
576990
+ function isEvidenceSignal(signal) {
576991
+ return signal.kind === "goal" || signal.kind === "user_steering" || signal.kind === "task_state" || signal.kind === "known_files" || signal.kind === "tool_cache" || signal.kind === "git_state" || signal.kind === "memory" || signal.kind === "semantic_chunk" || signal.kind === "session_history" || signal.kind === "anchor" || signal.kind === "handoff" || signal.kind === "environment" || signal.kind === "compaction_summary";
576992
+ }
576752
576993
  function signalFromBlock(kind, source, content, options2 = {}) {
576753
576994
  const normalized = normalizeSignalContent(content ?? "");
576754
576995
  if (!normalized)
@@ -576762,6 +577003,10 @@ function signalFromBlock(kind, source, content, options2 = {}) {
576762
577003
  createdTurn: options2.createdTurn,
576763
577004
  ttlTurns: options2.ttlTurns,
576764
577005
  dedupeKey: options2.dedupeKey,
577006
+ semanticKey: options2.semanticKey,
577007
+ conflictGroup: options2.conflictGroup,
577008
+ invalidates: options2.invalidates,
577009
+ modelVisible: options2.modelVisible,
576765
577010
  tags: options2.tags,
576766
577011
  metadata: options2.metadata
576767
577012
  };
@@ -576830,12 +577075,12 @@ var init_context_fabric = __esm({
576830
577075
  DEFAULT_KIND_CHAR_BUDGET = {
576831
577076
  goal: 900,
576832
577077
  user_steering: 1400,
576833
- runtime_guidance: 1800,
576834
- action_contract: 1800,
577078
+ runtime_guidance: 900,
577079
+ action_contract: 1400,
576835
577080
  git_state: 1400,
576836
577081
  task_state: 1800,
576837
577082
  known_files: 2400,
576838
- recent_failure: 2600,
577083
+ recent_failure: 1400,
576839
577084
  tool_cache: 2200,
576840
577085
  skill_manifest: 900,
576841
577086
  memory: 1500,
@@ -576851,11 +577096,16 @@ var init_context_fabric = __esm({
576851
577096
  ContextLedger = class {
576852
577097
  signals = /* @__PURE__ */ new Map();
576853
577098
  sequence = 0;
577099
+ invalidatedSinceLastBuild = 0;
576854
577100
  upsert(signal) {
576855
577101
  const content = normalizeSignalContent(signal.content);
576856
577102
  if (!content)
576857
577103
  return;
576858
- const key = signal.dedupeKey || `${signal.kind}:${signal.id}`;
577104
+ if (Array.isArray(signal.invalidates) && signal.invalidates.length > 0) {
577105
+ const invalidates = new Set(signal.invalidates.map((key2) => String(key2 ?? "").trim()).filter(Boolean));
577106
+ this.invalidatedSinceLastBuild += this.removeWhere((existing2) => signalIdentityKeys(existing2).some((key2) => invalidates.has(key2)));
577107
+ }
577108
+ const key = signal.dedupeKey || signal.semanticKey || `${signal.kind}:${signal.id}`;
576859
577109
  const incoming = {
576860
577110
  ...signal,
576861
577111
  content,
@@ -576869,12 +577119,15 @@ var init_context_fabric = __esm({
576869
577119
  this.signals.set(key, incoming);
576870
577120
  return;
576871
577121
  }
576872
- const shouldReplace = incoming.createdTurn > existing.createdTurn || incoming.createdTurn === existing.createdTurn && incoming.priority >= existing.priority || incoming.priority > existing.priority;
576873
- if (shouldReplace) {
577122
+ const preferred = choosePreferredSignal(incoming, existing);
577123
+ if (preferred === incoming) {
576874
577124
  this.signals.set(key, {
576875
577125
  ...existing,
576876
577126
  ...incoming,
576877
577127
  tags: [.../* @__PURE__ */ new Set([...existing.tags ?? [], ...incoming.tags ?? []])],
577128
+ invalidates: [
577129
+ .../* @__PURE__ */ new Set([...existing.invalidates ?? [], ...incoming.invalidates ?? []])
577130
+ ],
576878
577131
  metadata: { ...existing.metadata ?? {}, ...incoming.metadata ?? {} }
576879
577132
  });
576880
577133
  }
@@ -576915,12 +577168,64 @@ var init_context_fabric = __esm({
576915
577168
  size() {
576916
577169
  return this.signals.size;
576917
577170
  }
577171
+ consumeInvalidatedCount() {
577172
+ const count = this.invalidatedSinceLastBuild;
577173
+ this.invalidatedSinceLastBuild = 0;
577174
+ return count;
577175
+ }
576918
577176
  };
576919
577177
  ContextFrameBuilder = class {
576920
577178
  build(signals, options2 = {}) {
576921
577179
  const maxChars = Math.max(1200, options2.maxChars ?? 1e4);
576922
577180
  const budgets = { ...DEFAULT_KIND_CHAR_BUDGET, ...options2.kindCharBudget ?? {} };
576923
- const sanitized = signals.map((signal) => ({ ...signal, content: normalizeSignalContent(signal.content) })).filter((signal) => signal.content.length > 0);
577181
+ const normalized = signals.map((signal) => ({ ...signal, content: normalizeSignalContent(signal.content) })).filter((signal) => signal.content.length > 0);
577182
+ const hidden = normalized.filter((signal) => signal.modelVisible === false);
577183
+ const visible = normalized.filter((signal) => signal.modelVisible !== false);
577184
+ const droppedByAdmission = [];
577185
+ let semanticDedupedSignals = 0;
577186
+ let conflictDroppedSignals = 0;
577187
+ const semanticBest = /* @__PURE__ */ new Map();
577188
+ for (const signal of visible) {
577189
+ const key = semanticKeyFor(signal);
577190
+ if (!key)
577191
+ continue;
577192
+ const prior = semanticBest.get(key);
577193
+ if (!prior || sortSignals(signal, prior) < 0) {
577194
+ if (prior) {
577195
+ droppedByAdmission.push(prior);
577196
+ semanticDedupedSignals++;
577197
+ }
577198
+ semanticBest.set(key, signal);
577199
+ } else {
577200
+ droppedByAdmission.push(signal);
577201
+ semanticDedupedSignals++;
577202
+ }
577203
+ }
577204
+ const afterSemantic = visible.filter((signal) => {
577205
+ const key = semanticKeyFor(signal);
577206
+ return !key || semanticBest.get(key) === signal;
577207
+ });
577208
+ const conflictBest = /* @__PURE__ */ new Map();
577209
+ for (const signal of afterSemantic) {
577210
+ const key = typeof signal.conflictGroup === "string" ? signal.conflictGroup.trim() : "";
577211
+ if (!key)
577212
+ continue;
577213
+ const prior = conflictBest.get(key);
577214
+ if (!prior || sortSignals(signal, prior) < 0) {
577215
+ if (prior) {
577216
+ droppedByAdmission.push(prior);
577217
+ conflictDroppedSignals++;
577218
+ }
577219
+ conflictBest.set(key, signal);
577220
+ } else {
577221
+ droppedByAdmission.push(signal);
577222
+ conflictDroppedSignals++;
577223
+ }
577224
+ }
577225
+ const sanitized = afterSemantic.filter((signal) => {
577226
+ const key = typeof signal.conflictGroup === "string" ? signal.conflictGroup.trim() : "";
577227
+ return !key || conflictBest.get(key) === signal;
577228
+ });
576924
577229
  const byKind = /* @__PURE__ */ new Map();
576925
577230
  for (const signal of sanitized) {
576926
577231
  const bucket = byKind.get(signal.kind) ?? [];
@@ -576937,17 +577242,7 @@ var init_context_fabric = __esm({
576937
577242
  const bucket = byKind.get(kind);
576938
577243
  if (!bucket || bucket.length === 0)
576939
577244
  continue;
576940
- const sorted = [...bucket].sort((a2, b) => {
576941
- const pa = a2.priority ?? 0;
576942
- const pb = b.priority ?? 0;
576943
- if (pa !== pb)
576944
- return pb - pa;
576945
- const ta = a2.createdTurn ?? 0;
576946
- const tb = b.createdTurn ?? 0;
576947
- if (ta !== tb)
576948
- return tb - ta;
576949
- return a2.source.localeCompare(b.source) || a2.id.localeCompare(b.id);
576950
- });
577245
+ const sorted = [...bucket].sort(sortSignals);
576951
577246
  const budget = Math.max(200, budgets[kind]);
576952
577247
  const body = [];
576953
577248
  let chars = 0;
@@ -576985,21 +577280,40 @@ var init_context_fabric = __esm({
576985
577280
  "Scope: runtime state for the next action. Treat this as the single merged context intake; do not re-read or re-emit it unless state changes."
576986
577281
  ].filter(Boolean);
576987
577282
  let content = [...header, "", ...sectionLines].join("\n").trim();
577283
+ const controlChars = included.filter(isControlSignal).reduce((sum2, signal) => sum2 + signal.content.length, 0);
577284
+ const evidenceChars = included.filter(isEvidenceSignal).reduce((sum2, signal) => sum2 + signal.content.length, 0);
577285
+ const controlToEvidenceRatio = Number((controlChars / Math.max(1, evidenceChars)).toFixed(3));
577286
+ const qualityWarnings = [];
577287
+ const maxControlRatio = options2.maxControlToEvidenceRatio ?? 0.45;
577288
+ if (controlToEvidenceRatio > maxControlRatio) {
577289
+ qualityWarnings.push(`control_context_ratio_high:${controlToEvidenceRatio}`);
577290
+ }
577291
+ const activeFrameCount = (content.match(/\[ACTIVE CONTEXT FRAME\]/g) ?? []).length;
577292
+ if (activeFrameCount > 1)
577293
+ qualityWarnings.push(`active_frame_count:${activeFrameCount}`);
576988
577294
  if (sectionLines.length === 0) {
576989
577295
  return {
576990
577296
  content: null,
576991
577297
  diagnostics: {
576992
577298
  includedSignals: 0,
576993
- droppedSignals: sanitized.length,
577299
+ droppedSignals: sanitized.length + droppedByAdmission.length,
577300
+ hiddenSignals: hidden.length,
577301
+ semanticDedupedSignals,
577302
+ conflictDroppedSignals,
577303
+ invalidatedSignals: options2.invalidatedSignals ?? 0,
576994
577304
  truncatedSignals: 0,
576995
577305
  estimatedTokens: 0,
576996
577306
  totalChars: 0,
576997
577307
  semanticChunkCount: 0,
577308
+ controlChars: 0,
577309
+ evidenceChars: 0,
577310
+ controlToEvidenceRatio: 0,
577311
+ qualityWarnings,
576998
577312
  ...metadataReports,
576999
577313
  sections: []
577000
577314
  },
577001
577315
  included: [],
577002
- dropped: sanitized
577316
+ dropped: [...sanitized, ...droppedByAdmission, ...hidden]
577003
577317
  };
577004
577318
  }
577005
577319
  if (content.length > maxChars) {
@@ -577021,22 +577335,293 @@ context_fabric: included=${included.length} dropped=${dropped.length} truncated=
577021
577335
  content,
577022
577336
  diagnostics: {
577023
577337
  includedSignals: included.length,
577024
- droppedSignals: dropped.length,
577338
+ droppedSignals: dropped.length + droppedByAdmission.length,
577339
+ hiddenSignals: hidden.length,
577340
+ semanticDedupedSignals,
577341
+ conflictDroppedSignals,
577342
+ invalidatedSignals: options2.invalidatedSignals ?? 0,
577025
577343
  truncatedSignals,
577026
577344
  estimatedTokens: estimateTokens2(content),
577027
577345
  totalChars: content.length,
577028
577346
  semanticChunkCount: included.filter((signal) => signal.kind === "semantic_chunk").length,
577347
+ controlChars,
577348
+ evidenceChars,
577349
+ controlToEvidenceRatio,
577350
+ qualityWarnings,
577029
577351
  ...metadataReports,
577030
577352
  sections: sectionDiagnostics
577031
577353
  },
577032
577354
  included,
577033
- dropped
577355
+ dropped: [...dropped, ...droppedByAdmission, ...hidden]
577034
577356
  };
577035
577357
  }
577036
577358
  };
577037
577359
  }
577038
577360
  });
577039
577361
 
577362
+ // packages/orchestrator/dist/context-compiler.js
577363
+ function collapseWhitespace(text2) {
577364
+ return text2.replace(/\r\n/g, "\n").split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
577365
+ }
577366
+ function sanitizeModelVisibleContextText(text2) {
577367
+ let out = String(text2 ?? "");
577368
+ out = out.replace(RUNTIME_GUIDANCE_RE, (_match, inner) => {
577369
+ return `[runtime_guidance]
577370
+ ${String(inner ?? "").trim()}`;
577371
+ });
577372
+ out = out.split("\n").filter((line) => !RESTORE_NOISE_LINE_RE.test(line)).join("\n");
577373
+ const frameMatches = [...out.matchAll(ACTIVE_CONTEXT_RE)];
577374
+ if (frameMatches.length > 1) {
577375
+ const last2 = frameMatches[frameMatches.length - 1]?.[0] ?? "";
577376
+ out = out.replace(ACTIVE_CONTEXT_RE, "").trim();
577377
+ out = `${last2}
577378
+ ${out}`.trim();
577379
+ }
577380
+ return collapseWhitespace(out);
577381
+ }
577382
+ function messageText(content) {
577383
+ if (typeof content === "string")
577384
+ return content;
577385
+ if (!Array.isArray(content))
577386
+ return "";
577387
+ return content.map((part) => {
577388
+ if (part && typeof part === "object") {
577389
+ const rec = part;
577390
+ return rec["type"] === "text" && typeof rec["text"] === "string" ? rec["text"] : "";
577391
+ }
577392
+ return "";
577393
+ }).filter(Boolean).join("\n");
577394
+ }
577395
+ function runtimeControlSemanticKey(content) {
577396
+ const normalized = content.replace(/\s+/g, " ").trim().toLowerCase();
577397
+ if (!normalized)
577398
+ return null;
577399
+ if (content.includes("[ACTIVE CONTEXT FRAME]"))
577400
+ return "context.active-frame";
577401
+ if (content.includes("[NEXT ACTION CONTRACT]"))
577402
+ return "context.next-action";
577403
+ if (content.includes("[RUNTIME DIRECTIVE]")) {
577404
+ if (/compile|verifier|verification|build|fix loop/.test(normalized))
577405
+ return "runtime.guidance.verification";
577406
+ if (/action_reason|tool action reason|schema|argument/.test(normalized))
577407
+ return "runtime.guidance.tool-args";
577408
+ if (/doom-loop|loop|repeat|identical|stuck|stale|cached/.test(normalized))
577409
+ return "runtime.guidance.loop-control";
577410
+ if (/todo|workboard|card|task state/.test(normalized))
577411
+ return "runtime.guidance.task-state";
577412
+ if (/scope|owned file|forbidden|mutation/.test(normalized))
577413
+ return "runtime.guidance.mutation-scope";
577414
+ return "runtime.guidance.general";
577415
+ }
577416
+ if (/\[TOOL ACTION REASON CONTRACT\]|action_reason/i.test(content))
577417
+ return "runtime.guidance.tool-args";
577418
+ if (/\[LOCAL ERROR-INFORMED NUDGE\]/.test(content))
577419
+ return "runtime.guidance.local-error";
577420
+ if (/\[STOP — RETRY LOOP DETECTED\]|\[RECENT TOOL FAILURES/i.test(content))
577421
+ return "runtime.guidance.recent-failures";
577422
+ if (/REG-\d+|FIRST-EDIT|STUCK DETECTOR|LOOP CIRCUIT|doom-loop/i.test(content))
577423
+ return "runtime.guidance.loop-control";
577424
+ if (/\[Associative Memory/i.test(content))
577425
+ return "context.associative-memory";
577426
+ if (/\[TOOL MODE — PROMPT INJECTION\]/.test(content))
577427
+ return "context.tool-mode-prompt";
577428
+ return null;
577429
+ }
577430
+ function hasConcreteGoalMessage(messages2) {
577431
+ return messages2.some((message2) => {
577432
+ const text2 = messageText(message2.content);
577433
+ return /\[CURRENT USER GOAL\]/.test(text2) && !/No concrete current user goal/i.test(text2);
577434
+ });
577435
+ }
577436
+ function hasUserMessage(messages2) {
577437
+ return messages2.some((message2) => message2.role === "user" && messageText(message2.content).trim().length > 0);
577438
+ }
577439
+ function hasAssistantPayload(message2) {
577440
+ const text2 = messageText(message2.content).trim();
577441
+ if (text2 && !/^(null|undefined)$/i.test(text2))
577442
+ return true;
577443
+ const record = message2;
577444
+ if (Array.isArray(record["tool_calls"]) && record["tool_calls"].length > 0)
577445
+ return true;
577446
+ return Boolean(record["function_call"]);
577447
+ }
577448
+ function staleToolFailureKey(content) {
577449
+ const text2 = content.replace(/\s+/g, " ").trim();
577450
+ if (!/(FAILED:|failed again|doom-loop|result compacted|Earlier read of .* cleared)/i.test(text2)) {
577451
+ return null;
577452
+ }
577453
+ const tool = text2.match(/^\[?([a-zA-Z_][a-zA-Z0-9_]*)\(/)?.[1] ?? "tool";
577454
+ const path16 = text2.match(/"path"\s*:\s*"([^"]+)"/)?.[1] ?? text2.match(/Earlier read of ([^ ]+) cleared/)?.[1] ?? "";
577455
+ const family = text2.match(/FAILED:\s*\[([^\]\n]+)/i)?.[1] ?? text2.match(/(doom-loop[^.]+)/i)?.[1] ?? text2.match(/(Earlier read of [^ ]+ cleared)/i)?.[1] ?? "failure";
577456
+ return [tool, path16, family].join("|").toLowerCase().replace(/[a-f0-9]{16,}/g, "<hash>").replace(/\d+/g, "#");
577457
+ }
577458
+ function retireDuplicateToolFailures(messages2) {
577459
+ const seen = /* @__PURE__ */ new Set();
577460
+ const out = [...messages2];
577461
+ for (let index = out.length - 1; index >= 0; index--) {
577462
+ const message2 = out[index];
577463
+ if (message2.role !== "tool" || typeof message2.content !== "string")
577464
+ continue;
577465
+ const key = staleToolFailureKey(message2.content);
577466
+ if (!key)
577467
+ continue;
577468
+ if (!seen.has(key)) {
577469
+ seen.add(key);
577470
+ continue;
577471
+ }
577472
+ out[index] = {
577473
+ ...message2,
577474
+ content: "[retired_duplicate_tool_failure] newer matching result appears later; do not repeat the same call."
577475
+ };
577476
+ }
577477
+ return out;
577478
+ }
577479
+ function prepareModelFacingApiMessages(input) {
577480
+ const preserveFirstSystem = input.preserveFirstSystem !== false;
577481
+ const sanitized = [];
577482
+ for (let index = 0; index < input.messages.length; index++) {
577483
+ const message2 = input.messages[index];
577484
+ if (message2.role === "system" && typeof message2.content === "string") {
577485
+ if (preserveFirstSystem && sanitized.length === 0) {
577486
+ sanitized.push({ ...message2 });
577487
+ continue;
577488
+ }
577489
+ const cleaned = sanitizeModelVisibleContextText(message2.content);
577490
+ if (!cleaned)
577491
+ continue;
577492
+ sanitized.push({ ...message2, content: cleaned });
577493
+ continue;
577494
+ }
577495
+ if (message2.role === "assistant" && !hasAssistantPayload(message2)) {
577496
+ continue;
577497
+ }
577498
+ if (message2.role === "tool" && typeof message2.content === "string") {
577499
+ const cleaned = sanitizeModelVisibleContextText(message2.content);
577500
+ if (!cleaned)
577501
+ continue;
577502
+ sanitized.push({ ...message2, content: cleaned });
577503
+ continue;
577504
+ }
577505
+ sanitized.push({ ...message2 });
577506
+ }
577507
+ const keep = new Array(sanitized.length).fill(true);
577508
+ const seenSystemKeys = /* @__PURE__ */ new Set();
577509
+ for (let index = sanitized.length - 1; index >= 0; index--) {
577510
+ const message2 = sanitized[index];
577511
+ if (message2.role !== "system" || typeof message2.content !== "string")
577512
+ continue;
577513
+ if (preserveFirstSystem && index === 0)
577514
+ continue;
577515
+ const key = runtimeControlSemanticKey(message2.content);
577516
+ if (!key)
577517
+ continue;
577518
+ if (seenSystemKeys.has(key)) {
577519
+ keep[index] = false;
577520
+ continue;
577521
+ }
577522
+ seenSystemKeys.add(key);
577523
+ }
577524
+ const deduped = retireDuplicateToolFailures(sanitized.filter((_message, index) => keep[index]));
577525
+ if (!hasUserMessage(deduped) && !hasConcreteGoalMessage(deduped)) {
577526
+ const goal = deriveCurrentGoal({
577527
+ explicitGoal: input.currentGoal,
577528
+ signals: []
577529
+ });
577530
+ const goalMessage = {
577531
+ role: "system",
577532
+ content: [
577533
+ "[CURRENT USER GOAL]",
577534
+ "source=model-facing-api-view",
577535
+ goal.goal,
577536
+ goal.concrete ? null : "Required next action: recover or ask for the current user goal before mutating project files."
577537
+ ].filter(Boolean).join("\n")
577538
+ };
577539
+ const insertAt = preserveFirstSystem && deduped[0]?.role === "system" ? 1 : 0;
577540
+ deduped.splice(insertAt, 0, goalMessage);
577541
+ }
577542
+ return deduped;
577543
+ }
577544
+ function deriveCurrentGoal(input) {
577545
+ const explicit = sanitizeModelVisibleContextText(input.explicitGoal ?? "");
577546
+ if (explicit)
577547
+ return { goal: explicit.slice(0, 1200), concrete: true, source: "runtime_task_state" };
577548
+ const goalSignal = input.signals.filter((signal) => signal.kind === "goal" || signal.kind === "user_steering").sort((a2, b) => (b.createdTurn ?? 0) - (a2.createdTurn ?? 0) || (b.priority ?? 0) - (a2.priority ?? 0))[0];
577549
+ const fromSignal = sanitizeModelVisibleContextText(goalSignal?.content ?? "");
577550
+ if (fromSignal)
577551
+ return { goal: fromSignal.slice(0, 1200), concrete: true, source: goalSignal?.source ?? "context_signal" };
577552
+ return {
577553
+ goal: "No concrete current user goal was present in model-visible context. Recover the latest user request or restored active task before making project mutations.",
577554
+ concrete: false,
577555
+ source: "context_quality_gate"
577556
+ };
577557
+ }
577558
+ function normalizeContextSignalsForModel(signals) {
577559
+ const normalized = [];
577560
+ const rejected = [];
577561
+ for (const signal of signals) {
577562
+ if (signal.modelVisible === false) {
577563
+ normalized.push(signal);
577564
+ continue;
577565
+ }
577566
+ const content = sanitizeModelVisibleContextText(signal.content);
577567
+ if (!content) {
577568
+ rejected.push(signal);
577569
+ continue;
577570
+ }
577571
+ normalized.push({ ...signal, content });
577572
+ }
577573
+ return { signals: normalized, rejected };
577574
+ }
577575
+ function compileContextFrameV2(input) {
577576
+ const builder = input.builder ?? new ContextFrameBuilder();
577577
+ const normalized = normalizeContextSignalsForModel(input.signals);
577578
+ const goal = deriveCurrentGoal({
577579
+ explicitGoal: input.currentGoal,
577580
+ signals: normalized.signals
577581
+ });
577582
+ const warnings = [];
577583
+ if (!goal.concrete)
577584
+ warnings.push("missing_concrete_user_goal");
577585
+ const goalSignal = signalFromBlock("goal", "context-compiler.current-goal", [
577586
+ "[CURRENT USER GOAL]",
577587
+ `source=${goal.source}`,
577588
+ goal.goal,
577589
+ goal.concrete ? null : "Required next action: recover or ask for the current user goal before mutating project files."
577590
+ ].filter(Boolean).join("\n"), {
577591
+ id: "current-user-goal",
577592
+ dedupeKey: "context.current_user_goal",
577593
+ semanticKey: "context.current_user_goal",
577594
+ conflictGroup: "context.goal",
577595
+ priority: PRIORITY.GOAL + 20,
577596
+ createdTurn: input.turn,
577597
+ ttlTurns: 1
577598
+ });
577599
+ const frame = builder.build(goalSignal ? [goalSignal, ...normalized.signals] : normalized.signals, {
577600
+ turn: input.turn,
577601
+ ...input.frameOptions
577602
+ });
577603
+ warnings.push(...frame.diagnostics.qualityWarnings);
577604
+ return {
577605
+ ...frame,
577606
+ compilerDiagnostics: {
577607
+ warnings: [...new Set(warnings)],
577608
+ admittedSignals: frame.included.length,
577609
+ rejectedSignals: normalized.rejected.length,
577610
+ hadConcreteGoal: goal.concrete
577611
+ }
577612
+ };
577613
+ }
577614
+ var RESTORE_NOISE_LINE_RE, RUNTIME_GUIDANCE_RE, ACTIVE_CONTEXT_RE;
577615
+ var init_context_compiler = __esm({
577616
+ "packages/orchestrator/dist/context-compiler.js"() {
577617
+ "use strict";
577618
+ init_context_fabric();
577619
+ RESTORE_NOISE_LINE_RE = /^\s*(?:🔊|E Task timeout reached|E Incomplete:|⚠ Task incomplete|Tokens:\s*[\d,]+|▹\s*continue\b|·\s*(?:Starting fresh|Context (?:auto-)?restored|Nexus P2P network connected|REST API:|Voice feedback enabled|Memory maintenance:)|.*\bSHELL TRANSCRIPT\b.*|.*speaker emoji.*).*$/i;
577620
+ RUNTIME_GUIDANCE_RE = /\[RUNTIME_GUIDANCE_INTAKE v\d+\][\s\S]*?<<<RUNTIME_GUIDANCE>>>\s*([\s\S]*?)\s*<<<END_RUNTIME_GUIDANCE>>>[\s\S]*?\[\/RUNTIME_GUIDANCE_INTAKE\]/g;
577621
+ ACTIVE_CONTEXT_RE = /\[ACTIVE CONTEXT FRAME\][\s\S]*?(?=\n\[ACTIVE CONTEXT FRAME\]|$)/g;
577622
+ }
577623
+ });
577624
+
577040
577625
  // packages/orchestrator/dist/evidenceLedger.js
577041
577626
  import { statSync as statSync38 } from "node:fs";
577042
577627
  function buildExtract(content) {
@@ -577236,7 +577821,7 @@ var init_evidenceLedger = __esm({
577236
577821
  import { existsSync as existsSync102, mkdirSync as mkdirSync58, readdirSync as readdirSync32, readFileSync as readFileSync78, statSync as statSync39, unlinkSync as unlinkSync17, writeFileSync as writeFileSync48, appendFileSync as appendFileSync9 } from "node:fs";
577237
577822
  import { homedir as homedir35 } from "node:os";
577238
577823
  import { join as join111, resolve as resolve54 } from "node:path";
577239
- import { createHash as createHash29 } from "node:crypto";
577824
+ import { createHash as createHash30 } from "node:crypto";
577240
577825
  function contextWindowDumpDir(cwd4 = process.cwd()) {
577241
577826
  const envDir = process.env["OMNIUS_CONTEXT_WINDOW_DUMP_DIR"]?.trim();
577242
577827
  if (envDir)
@@ -577260,6 +577845,7 @@ function recordContextWindowDump(input) {
577260
577845
  String(input.attempt ?? "")
577261
577846
  ].join("|");
577262
577847
  const id2 = `${timestamp.replace(/[:.]/g, "-")}-${input.agentType}-${shortHash3(stable)}`;
577848
+ const metrics2 = analyzeContextWindowDumpRequest(input.request);
577263
577849
  const record = {
577264
577850
  schemaVersion: 1,
577265
577851
  id: id2,
@@ -577275,7 +577861,8 @@ function recordContextWindowDump(input) {
577275
577861
  cwd: cwd4,
577276
577862
  ...input.note ? { note: input.note } : {},
577277
577863
  ...input.focusSupervisor ? { focusSupervisor: compactFocusSupervisor(input.focusSupervisor) } : {},
577278
- metrics: analyzeContextWindowDumpRequest(input.request),
577864
+ metrics: metrics2,
577865
+ apiView: summarizeApiView(input.request, metrics2),
577279
577866
  request: input.request
577280
577867
  };
577281
577868
  const dir = contextWindowDumpDir(cwd4);
@@ -577285,9 +577872,7 @@ function recordContextWindowDump(input) {
577285
577872
  const payload = JSON.stringify(record, null, 2);
577286
577873
  writeFileSync48(filePath, payload, "utf-8");
577287
577874
  writeFileSync48(join111(dir, `latest-${record.agentType}.json`), payload, "utf-8");
577288
- if (record.agentType === "main" || record.agentType === "sub-agent" || record.agentType === "adversary") {
577289
- writeFileSync48(join111(dir, "latest.json"), payload, "utf-8");
577290
- }
577875
+ writeFileSync48(join111(dir, "latest.json"), payload, "utf-8");
577291
577876
  appendFileSync9(join111(dir, "index.jsonl"), JSON.stringify(toSummary(record, filePath)) + "\n", "utf-8");
577292
577877
  maybePruneOldDumpFiles(dir);
577293
577878
  } catch {
@@ -577338,12 +577923,17 @@ function analyzeContextWindowDumpRequest(request) {
577338
577923
  let imageCount = 0;
577339
577924
  let activeEvidenceChars = 0;
577340
577925
  let activeContextFrameChars = 0;
577926
+ let activeContextFrameCount = 0;
577341
577927
  let compactedDiscoveryChars = 0;
577342
577928
  let rawDiscoveryToolChars = 0;
577343
577929
  let toolResultChars = 0;
577344
577930
  let systemChars = 0;
577345
577931
  let userChars = 0;
577932
+ let userMessageCount = 0;
577346
577933
  let assistantChars = 0;
577934
+ let runtimeControlChars = 0;
577935
+ let modelVisibleNoiseChars = 0;
577936
+ let hasConcreteUserGoal = false;
577347
577937
  const allMessageParts = [];
577348
577938
  for (const message2 of messages2) {
577349
577939
  const rec = message2 && typeof message2 === "object" ? message2 : {};
@@ -577358,8 +577948,10 @@ function analyzeContextWindowDumpRequest(request) {
577358
577948
  allMessageParts.push(extracted.textWithoutImages);
577359
577949
  if (role === "system")
577360
577950
  systemChars += chars;
577361
- if (role === "user")
577951
+ if (role === "user") {
577362
577952
  userChars += chars;
577953
+ userMessageCount++;
577954
+ }
577363
577955
  if (role === "assistant")
577364
577956
  assistantChars += chars;
577365
577957
  if (role === "tool") {
@@ -577372,6 +577964,17 @@ function analyzeContextWindowDumpRequest(request) {
577372
577964
  }
577373
577965
  if (extracted.textWithoutImages.includes("[ACTIVE CONTEXT FRAME]")) {
577374
577966
  activeContextFrameChars += chars;
577967
+ activeContextFrameCount += (extracted.textWithoutImages.match(/\[ACTIVE CONTEXT FRAME\]/g) ?? []).length;
577968
+ }
577969
+ if (/\[CURRENT USER GOAL\]/.test(extracted.textWithoutImages) && !/No concrete current user goal/i.test(extracted.textWithoutImages)) {
577970
+ hasConcreteUserGoal = true;
577971
+ }
577972
+ if (isRuntimeControlText(extracted.textWithoutImages)) {
577973
+ runtimeControlChars += chars;
577974
+ }
577975
+ modelVisibleNoiseChars += estimateModelVisibleNoiseChars(extracted.textWithoutImages);
577976
+ if (role === "user" && extracted.textWithoutImages.trim()) {
577977
+ hasConcreteUserGoal = true;
577375
577978
  }
577376
577979
  if (extracted.textWithoutImages.includes("[DISCOVERY COMPACTED") || extracted.textWithoutImages.includes("[DISCOVERY BOUNDED")) {
577377
577980
  compactedDiscoveryChars += chars;
@@ -577384,6 +577987,20 @@ function analyzeContextWindowDumpRequest(request) {
577384
577987
  const lineNoiseChars = lineNoise.noiseChars;
577385
577988
  const rawDiscoveryPenalty = rawDiscoveryToolChars * 0.5;
577386
577989
  const structuralNoiseCandidateChars = lineNoiseChars + rawDiscoveryPenalty;
577990
+ const controlToEvidenceRatio = Number((runtimeControlChars / Math.max(1, activeEvidenceChars + activeContextFrameChars + userChars)).toFixed(3));
577991
+ const userlessTaskTurn = userMessageCount === 0 && !hasConcreteUserGoal;
577992
+ const qualityWarnings = [];
577993
+ if (activeContextFrameCount > 1) {
577994
+ qualityWarnings.push(`active_context_frame_count:${activeContextFrameCount}`);
577995
+ }
577996
+ if (userlessTaskTurn)
577997
+ qualityWarnings.push("missing_user_message_or_goal");
577998
+ if (controlToEvidenceRatio > 0.45) {
577999
+ qualityWarnings.push(`control_context_ratio_high:${controlToEvidenceRatio}`);
578000
+ }
578001
+ if (modelVisibleNoiseChars > 0) {
578002
+ qualityWarnings.push(`model_visible_restore_noise:${modelVisibleNoiseChars}`);
578003
+ }
577387
578004
  const ratio = Number((structuralSignalChars / Math.max(1, structuralNoiseCandidateChars)).toFixed(3));
577388
578005
  const snrDb = ratio > 0 ? Number((10 * Math.log10(ratio)).toFixed(2)) : -Infinity;
577389
578006
  return {
@@ -577397,12 +578014,20 @@ function analyzeContextWindowDumpRequest(request) {
577397
578014
  roleChars,
577398
578015
  activeEvidenceChars,
577399
578016
  activeContextFrameChars,
578017
+ activeContextFrameCount,
577400
578018
  compactedDiscoveryChars,
577401
578019
  rawDiscoveryToolChars,
577402
578020
  toolResultChars,
577403
578021
  systemChars,
577404
578022
  userChars,
578023
+ userMessageCount,
577405
578024
  assistantChars,
578025
+ runtimeControlChars,
578026
+ controlToEvidenceRatio,
578027
+ hasConcreteUserGoal,
578028
+ userlessTaskTurn,
578029
+ modelVisibleNoiseChars,
578030
+ qualityWarnings,
577406
578031
  signalToNoise: {
577407
578032
  structuralSignalChars,
577408
578033
  structuralNoiseCandidateChars,
@@ -577412,6 +578037,53 @@ function analyzeContextWindowDumpRequest(request) {
577412
578037
  }
577413
578038
  };
577414
578039
  }
578040
+ function summarizeApiView(request, metrics2) {
578041
+ const messages2 = Array.isArray(request["messages"]) ? request["messages"] : [];
578042
+ const previews = [];
578043
+ let currentGoalPreview;
578044
+ for (let index = 0; index < messages2.length && previews.length < 16; index++) {
578045
+ const rec = messages2[index] && typeof messages2[index] === "object" ? messages2[index] : {};
578046
+ const role = typeof rec["role"] === "string" ? rec["role"] : "unknown";
578047
+ const text2 = textAndImagesFromContent(rec["content"]).textWithoutImages;
578048
+ const preview = text2.replace(/\s+/g, " ").trim().slice(0, 180);
578049
+ const goalMatch = text2.match(/\[CURRENT USER GOAL\][\s\S]{0,500}/);
578050
+ if (goalMatch && !currentGoalPreview) {
578051
+ currentGoalPreview = goalMatch[0].replace(/\s+/g, " ").trim().slice(0, 220);
578052
+ }
578053
+ previews.push({
578054
+ index,
578055
+ role,
578056
+ chars: text2.length,
578057
+ preview
578058
+ });
578059
+ }
578060
+ return {
578061
+ kind: "model-facing-api-view",
578062
+ exactRequestStored: true,
578063
+ messageCount: metrics2.messageCount,
578064
+ toolSchemaCount: metrics2.toolSchemaCount,
578065
+ roleCounts: metrics2.roleCounts,
578066
+ estimatedTokens: metrics2.estimatedTokens,
578067
+ activeContextFrameCount: metrics2.activeContextFrameCount,
578068
+ hasConcreteUserGoal: metrics2.hasConcreteUserGoal,
578069
+ userlessTaskTurn: metrics2.userlessTaskTurn,
578070
+ qualityWarnings: metrics2.qualityWarnings,
578071
+ ...currentGoalPreview ? { currentGoalPreview } : {},
578072
+ messagePreviews: previews
578073
+ };
578074
+ }
578075
+ function isRuntimeControlText(text2) {
578076
+ return /\[(?:RUNTIME DIRECTIVE|RUNTIME_GUIDANCE_INTAKE|NEXT ACTION CONTRACT|TOOL ACTION REASON CONTRACT)\]|(?:^|\n)\s*REG-\d+\b|focus_required_next_action=|workboard_current_card=/i.test(text2);
578077
+ }
578078
+ function estimateModelVisibleNoiseChars(text2) {
578079
+ let chars = 0;
578080
+ for (const line of text2.split("\n")) {
578081
+ if (/^\s*(?:🔊|E Task timeout reached|E Incomplete:|⚠ Task incomplete|Tokens:\s*[\d,]+|▹\s*continue\b|·\s*(?:Starting fresh|Context (?:auto-)?restored|Nexus P2P network connected|REST API:|Voice feedback enabled|Memory maintenance:)|.*\bSHELL TRANSCRIPT\b.*)/i.test(line)) {
578082
+ chars += line.length;
578083
+ }
578084
+ }
578085
+ return chars;
578086
+ }
577415
578087
  function textAndImagesFromContent(content) {
577416
578088
  if (typeof content === "string") {
577417
578089
  const matches = content.match(IMAGE_BASE64_RE);
@@ -577494,7 +578166,7 @@ function safeId(value2) {
577494
578166
  return String(value2 || "unknown").replace(/[^a-zA-Z0-9_.:-]/g, "_").slice(0, 160);
577495
578167
  }
577496
578168
  function shortHash3(value2) {
577497
- return createHash29("sha256").update(value2).digest("hex").slice(0, 10);
578169
+ return createHash30("sha256").update(value2).digest("hex").slice(0, 10);
577498
578170
  }
577499
578171
  function pruneOldDumpFiles(dir) {
577500
578172
  const raw = Number(process.env["OMNIUS_CONTEXT_WINDOW_DUMP_MAX_FILES"]);
@@ -577907,7 +578579,7 @@ var init_adversaryStream = __esm({
577907
578579
 
577908
578580
  // packages/orchestrator/dist/debugArtifactLibrary.js
577909
578581
  import { appendFileSync as appendFileSync10, existsSync as existsSync103, mkdirSync as mkdirSync59, readFileSync as readFileSync79, statSync as statSync40, writeFileSync as writeFileSync49 } from "node:fs";
577910
- import { createHash as createHash30 } from "node:crypto";
578582
+ import { createHash as createHash31 } from "node:crypto";
577911
578583
  import { basename as basename24, join as join112, relative as relative12, resolve as resolve55 } from "node:path";
577912
578584
  function debugArtifactRoot(cwd4 = process.cwd(), stateDir) {
577913
578585
  const envDir = process.env["OMNIUS_DEBUG_ARTIFACT_DIR"]?.trim();
@@ -578703,7 +579375,7 @@ function safeId2(value2) {
578703
579375
  return String(value2 || "unknown").replace(/[^a-zA-Z0-9_.:-]/g, "_").slice(0, 160);
578704
579376
  }
578705
579377
  function shortHash4(value2) {
578706
- return createHash30("sha256").update(value2).digest("hex").slice(0, 10);
579378
+ return createHash31("sha256").update(value2).digest("hex").slice(0, 10);
578707
579379
  }
578708
579380
  var DEBUG_LIBRARY_DIR, RUN_EVENTS_LIMIT, PREVIEW_LIMIT;
578709
579381
  var init_debugArtifactLibrary = __esm({
@@ -580784,7 +581456,7 @@ var init_domainDetector = __esm({
580784
581456
  });
580785
581457
 
580786
581458
  // packages/orchestrator/dist/compile-error-fix-loop.js
580787
- import { createHash as createHash31 } from "node:crypto";
581459
+ import { createHash as createHash32 } from "node:crypto";
580788
581460
  import path7 from "node:path";
580789
581461
  function rankCompilerDiagnostics(diags) {
580790
581462
  const normalized = diags.map((diag, index) => ({
@@ -581065,7 +581737,7 @@ function isCompileFixDiagnostic(value2) {
581065
581737
  return Boolean(value2 && typeof value2.fingerprint === "string" && typeof value2.rank === "number");
581066
581738
  }
581067
581739
  function shortHash5(value2) {
581068
- return createHash31("sha256").update(value2).digest("hex").slice(0, 10);
581740
+ return createHash32("sha256").update(value2).digest("hex").slice(0, 10);
581069
581741
  }
581070
581742
  function fence(value2) {
581071
581743
  return ["```", value2.trim(), "```"].join("\n");
@@ -582634,7 +583306,7 @@ var init_prompt_cache = __esm({
582634
583306
 
582635
583307
  // packages/orchestrator/dist/git-progress.js
582636
583308
  import { existsSync as existsSync104, readFileSync as readFileSync80, statSync as statSync41 } from "node:fs";
582637
- import { createHash as createHash32 } from "node:crypto";
583309
+ import { createHash as createHash33 } from "node:crypto";
582638
583310
  import { relative as relative13, resolve as resolve56, sep as sep4 } from "node:path";
582639
583311
  function isRunnerOwnedGitPath(path16) {
582640
583312
  const normalized = normalizeGitPath(path16);
@@ -582661,7 +583333,7 @@ function pathHash(repoRoot, relPath) {
582661
583333
  const st = statSync41(absolute);
582662
583334
  if (!st.isFile())
582663
583335
  return `non-file:${st.size}:${Math.floor(st.mtimeMs)}`;
582664
- return createHash32("sha256").update(readFileSync80(absolute)).digest("hex");
583336
+ return createHash33("sha256").update(readFileSync80(absolute)).digest("hex");
582665
583337
  } catch {
582666
583338
  return void 0;
582667
583339
  }
@@ -583498,7 +584170,7 @@ __export(preflightSnapshot_exports, {
583498
584170
  import { existsSync as existsSync105, readFileSync as readFileSync81, statSync as statSync42, statfsSync as statfsSync6 } from "node:fs";
583499
584171
  import { homedir as homedir36, platform as platform4, arch as arch2, totalmem as totalmem4, freemem as freemem3, hostname as hostname3 } from "node:os";
583500
584172
  import { join as join113 } from "node:path";
583501
- import { createHash as createHash33 } from "node:crypto";
584173
+ import { createHash as createHash34 } from "node:crypto";
583502
584174
  function capturePreflightSnapshot(workingDir) {
583503
584175
  const warnings = [];
583504
584176
  const configFingerprints = {};
@@ -583667,7 +584339,7 @@ function expandPath(p2) {
583667
584339
  return p2;
583668
584340
  }
583669
584341
  function sha2564(s2) {
583670
- return createHash33("sha256").update(s2).digest("hex").slice(0, 16);
584342
+ return createHash34("sha256").update(s2).digest("hex").slice(0, 16);
583671
584343
  }
583672
584344
  function freeDiskBytes(path16 = "/tmp") {
583673
584345
  try {
@@ -585367,6 +586039,7 @@ var init_agenticRunner = __esm({
585367
586039
  init_failureHandoff();
585368
586040
  init_failure_taxonomy();
585369
586041
  init_context_fabric();
586042
+ init_context_compiler();
585370
586043
  init_evidenceLedger();
585371
586044
  init_adversaryStream();
585372
586045
  init_contextWindowDump();
@@ -586501,9 +587174,34 @@ var init_agenticRunner = __esm({
586501
587174
  parts.push(`Active: ${activeCards.length}`);
586502
587175
  }
586503
587176
  if (snapshot.cards.length > 0) {
586504
- const compact4 = compactWorkboardSnapshot(snapshot, 12);
586505
- parts.push(`
586506
- ${formatWorkboardCompact(snapshot, 12)}`);
587177
+ const statusCounts = snapshot.cards.reduce((acc, card) => {
587178
+ acc[card.status] = (acc[card.status] ?? 0) + 1;
587179
+ return acc;
587180
+ }, {});
587181
+ parts.push(`Card counts: ${Object.entries(statusCounts).sort(([a2], [b]) => a2.localeCompare(b)).map(([status, count]) => `${status}:${count}`).join(" ")}`);
587182
+ const action = this._deriveWorkboardActionContract(snapshot);
587183
+ const current = action ? snapshot.cards.find((card) => card.id === action.cardId) : activeCards[0] ?? null;
587184
+ if (current) {
587185
+ const currentLines = [
587186
+ `Current card: ${current.id} status=${current.status} lane=${current.lane}`,
587187
+ `title=${current.title.slice(0, 160)}`
587188
+ ];
587189
+ if (current.assignee)
587190
+ currentLines.push(`assignee=${current.assignee.slice(0, 120)}`);
587191
+ if (current.ownedFiles && current.ownedFiles.length > 0) {
587192
+ currentLines.push(`owned_files=${current.ownedFiles.slice(0, 6).join(",")}`);
587193
+ }
587194
+ if (current.verifierCommand) {
587195
+ currentLines.push(`verifier=${current.verifierCommand.slice(0, 180)}`);
587196
+ }
587197
+ if (current.diagnosticFingerprint) {
587198
+ currentLines.push(`diagnostic=${current.diagnosticFingerprint.slice(0, 160)}`);
587199
+ }
587200
+ if (current.evidenceRequirements.length > 0) {
587201
+ currentLines.push(`evidence_required=${current.evidenceRequirements.slice(0, 3).map((item) => item.slice(0, 100)).join(" | ")}`);
587202
+ }
587203
+ parts.push(currentLines.join("\n"));
587204
+ }
586507
587205
  }
586508
587206
  return parts.length > 0 ? `<workboard-status>
586509
587207
  ${parts.join("\n")}
@@ -587794,6 +588492,18 @@ Your hypotheses MUST address this specific error, not generic causes.
587794
588492
  * system prompt. Mutates `messages` in place.
587795
588493
  */
587796
588494
  gcSystemMessages(messages2) {
588495
+ for (let i2 = 1; i2 < messages2.length; i2++) {
588496
+ const msg = messages2[i2];
588497
+ if (msg?.role !== "system" || typeof msg.content !== "string")
588498
+ continue;
588499
+ const cleaned = sanitizeModelVisibleContextText(msg.content);
588500
+ if (cleaned) {
588501
+ msg.content = cleaned;
588502
+ } else {
588503
+ messages2.splice(i2, 1);
588504
+ i2--;
588505
+ }
588506
+ }
587797
588507
  const ctxTokens = this.effectiveContextWindow();
587798
588508
  const systemMaxChars = ctxTokens > 0 ? Math.max(24e3, Math.floor(ctxTokens * 4 * 0.45)) : 0;
587799
588509
  const beforeChars = messages2.reduce((sum2, m2) => sum2 + (m2.role === "system" && typeof m2.content === "string" ? m2.content.length : 0), 0);
@@ -587817,6 +588527,13 @@ Your hypotheses MUST address this specific error, not generic causes.
587817
588527
  });
587818
588528
  }
587819
588529
  }
588530
+ _prepareModelFacingMessages(messages2, _turn) {
588531
+ const prepared = prepareModelFacingApiMessages({
588532
+ messages: messages2,
588533
+ currentGoal: this._taskState.originalGoal || this._taskState.goal || this._taskState.currentStep || this._taskState.nextAction || ""
588534
+ });
588535
+ return sanitizeHistoryThink(prepared);
588536
+ }
587820
588537
  // ── Failing-approach detector (the "stop retrying variants" reflex) ───────
587821
588538
  // Encodes the behavior an effective agent uses and the dropbear 27× loop
587822
588539
  // lacked: when the SAME error recurs ~3× — especially while the same target
@@ -592381,9 +593098,11 @@ ${chunk.content}`, {
592381
593098
  async _buildTurnContextFrame(turn, messages2, recentToolResults, environmentBlock) {
592382
593099
  this._contextLedger.clearSources("turn.");
592383
593100
  this._contextLedger.prune(turn);
593101
+ const concreteGoal = this._taskState.originalGoal || this._taskState.goal || this._taskState.currentStep || this._taskState.nextAction || "";
592384
593102
  const goalBlock = [
592385
593103
  this._renderRuntimeRootBlock(),
592386
- this._taskState.goal ? `Active task: (see user message above — the goal block defers to the user message as the authoritative source)` : null
593104
+ concreteGoal ? `[CURRENT USER GOAL]
593105
+ ${String(concreteGoal).replace(/\s+/g, " ").trim().slice(0, 1200)}` : null
592387
593106
  ].filter(Boolean).join("\n\n");
592388
593107
  const workspaceTreeBlock = this._renderWorkspaceTreeBlock(turn);
592389
593108
  const filesystemBlock = this._renderFilesystemStateBlock(turn);
@@ -592422,6 +593141,8 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592422
593141
  signalFromBlock("goal", "run.goal", goalBlock, {
592423
593142
  id: "active-task",
592424
593143
  dedupeKey: "run.goal",
593144
+ semanticKey: "run.goal",
593145
+ conflictGroup: "context.runtime-root",
592425
593146
  priority: 100,
592426
593147
  createdTurn: turn
592427
593148
  }),
@@ -592449,6 +593170,8 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592449
593170
  signalFromBlock("action_contract", "turn.next-action-contract", actionContractBlock, {
592450
593171
  id: "next-action-contract",
592451
593172
  dedupeKey: "turn.next-action-contract",
593173
+ semanticKey: "context.next-action-contract",
593174
+ conflictGroup: "context.next-action",
592452
593175
  priority: PRIORITY.ACTION_CONTRACT,
592453
593176
  createdTurn: turn,
592454
593177
  ttlTurns: 1
@@ -592456,6 +593179,7 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592456
593179
  signalFromBlock("task_state", "turn.todos", todoBlock, {
592457
593180
  id: "todo-state",
592458
593181
  dedupeKey: "turn.todos",
593182
+ semanticKey: "context.todos",
592459
593183
  priority: 80,
592460
593184
  createdTurn: turn,
592461
593185
  ttlTurns: 1
@@ -592470,6 +593194,8 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592470
593194
  signalFromBlock("task_state", "turn.focus-supervisor", focusBlock, {
592471
593195
  id: "focus-supervisor",
592472
593196
  dedupeKey: "turn.focus-supervisor",
593197
+ semanticKey: "context.focus-supervisor",
593198
+ conflictGroup: "context.focus-supervisor",
592473
593199
  priority: 98,
592474
593200
  createdTurn: turn,
592475
593201
  ttlTurns: 1
@@ -592477,6 +593203,8 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592477
593203
  signalFromBlock("recent_failure", "turn.failures", failureBlock, {
592478
593204
  id: "recent-failures",
592479
593205
  dedupeKey: "turn.failures",
593206
+ semanticKey: "context.recent-failures",
593207
+ conflictGroup: "context.recent-failures",
592480
593208
  priority: 95,
592481
593209
  createdTurn: turn,
592482
593210
  ttlTurns: 1
@@ -592491,6 +593219,7 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592491
593219
  signalFromBlock("tool_cache", "turn.tool-cache", toolCacheBlock, {
592492
593220
  id: "tool-cache",
592493
593221
  dedupeKey: "turn.tool-cache",
593222
+ semanticKey: "context.tool-cache",
592494
593223
  priority: 92,
592495
593224
  createdTurn: turn,
592496
593225
  ttlTurns: 1
@@ -592529,15 +593258,49 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592529
593258
  })
592530
593259
  ];
592531
593260
  this._contextLedger.upsertMany(signals.filter(Boolean));
592532
- const frame = this._contextFrameBuilder.build(this._contextLedger.values(), {
592533
- turn,
593261
+ const invalidatedSignals = this._contextLedger.consumeInvalidatedCount();
593262
+ const frameBuildOptions = {
592534
593263
  // Raised from 10k to fit the durable read-evidence content (known_files)
592535
593264
  // that replaces the re-read loop; the per-kind budget below caps it.
592536
593265
  maxChars: 13e3,
592537
- kindCharBudget: { known_files: 8500 },
593266
+ kindCharBudget: {
593267
+ known_files: 8500,
593268
+ runtime_guidance: 900,
593269
+ recent_failure: 1400,
593270
+ action_contract: 1400
593271
+ },
593272
+ invalidatedSignals,
593273
+ maxControlToEvidenceRatio: 0.45,
592538
593274
  includeDiagnostics: process.env["OMNIUS_CONTEXT_FABRIC_DIAGNOSTICS"] === "1"
592539
- });
593275
+ };
593276
+ const compilerEnabled = process.env["OMNIUS_CONTEXT_COMPILER_V2"] !== "0";
593277
+ const frame = compilerEnabled ? compileContextFrameV2({
593278
+ turn,
593279
+ currentGoal: concreteGoal,
593280
+ signals: this._contextLedger.values(),
593281
+ builder: this._contextFrameBuilder,
593282
+ frameOptions: frameBuildOptions
593283
+ }) : {
593284
+ ...this._contextFrameBuilder.build(this._contextLedger.values(), {
593285
+ turn,
593286
+ ...frameBuildOptions
593287
+ }),
593288
+ compilerDiagnostics: {
593289
+ warnings: [],
593290
+ admittedSignals: 0,
593291
+ rejectedSignals: 0,
593292
+ hadConcreteGoal: Boolean(concreteGoal)
593293
+ }
593294
+ };
592540
593295
  this._lastContextFrameDiagnostics = frame.diagnostics;
593296
+ if (frame.compilerDiagnostics.warnings.length > 0 && process.env["OMNIUS_CONTEXT_COMPILER_STATUS"] === "1") {
593297
+ this.emit({
593298
+ type: "status",
593299
+ content: `Context compiler warnings: ${frame.compilerDiagnostics.warnings.join(", ")}`,
593300
+ turn,
593301
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
593302
+ });
593303
+ }
592541
593304
  semantic.snapshot.frameTokens = frame.diagnostics.estimatedTokens;
592542
593305
  semantic.snapshot.droppedSignals = frame.diagnostics.droppedSignals;
592543
593306
  semantic.snapshot.truncatedSignals = frame.diagnostics.truncatedSignals;
@@ -593634,6 +594397,10 @@ ${notice}`;
593634
594397
  injectUserMessage(content) {
593635
594398
  this.pendingUserMessages.push(this.scrubUserInput(content, "injected-user-message"));
593636
594399
  }
594400
+ /** Inject bounded runtime guidance without treating it as user steering. */
594401
+ injectRuntimeGuidance(content) {
594402
+ this.enqueueRuntimeGuidance(content);
594403
+ }
593637
594404
  enqueueRuntimeGuidance(content) {
593638
594405
  const cleaned = this.scrubUserInput(content, "runtime-guidance").trim();
593639
594406
  if (cleaned)
@@ -596363,8 +597130,8 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
596363
597130
  if (process.env["OMNIUS_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
596364
597131
  const goalForSig = (this._taskState.goal || "").slice(0, 200);
596365
597132
  const recentTools = this._toolSequence.slice(-5).join("|");
596366
- const { createHash: createHash51 } = await import("node:crypto");
596367
- const sig = createHash51("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
597133
+ const { createHash: createHash53 } = await import("node:crypto");
597134
+ const sig = createHash53("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
596368
597135
  if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
596369
597136
  compacted.push({
596370
597137
  role: "system",
@@ -596501,7 +597268,7 @@ ${memoryLines.join("\n")}`
596501
597268
  }
596502
597269
  const { maxOutputTokens: effectiveMaxTokens } = this.contextLimits();
596503
597270
  this.gcSystemMessages(requestMessages);
596504
- requestMessages = sanitizeHistoryThink(requestMessages);
597271
+ requestMessages = this._prepareModelFacingMessages(requestMessages, turn);
596505
597272
  const chatRequest = {
596506
597273
  messages: requestMessages,
596507
597274
  tools: toolDefs,
@@ -596685,10 +597452,10 @@ ${memoryLines.join("\n")}`
596685
597452
  'When done, output: {"tool": "task_complete", "args": {"summary": "what you did"}}'
596686
597453
  ].join("\n");
596687
597454
  messages2.push({ role: "system", content: toolInjectMsg });
596688
- chatRequest.messages = [
597455
+ chatRequest.messages = this._prepareModelFacingMessages([
596689
597456
  ...requestMessages,
596690
597457
  { role: "system", content: toolInjectMsg }
596691
- ];
597458
+ ], turn);
596692
597459
  chatRequest.tools = [];
596693
597460
  try {
596694
597461
  this._recordContextWindowDump("agent_turn_prompt_tool_retry", chatRequest, turn, 1);
@@ -600690,7 +601457,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
600690
601457
  }
600691
601458
  this._insertContextFrame(compactedMsgs, await this._buildTurnContextFrame(turn, compactedMsgs, void 0, bfEnvironmentBlock));
600692
601459
  this.gcSystemMessages(compactedMsgs);
600693
- const modelFacingMessages = sanitizeHistoryThink(compactedMsgs);
601460
+ const modelFacingMessages = this._prepareModelFacingMessages(compactedMsgs, turn);
600694
601461
  const chatRequest = {
600695
601462
  messages: modelFacingMessages,
600696
601463
  tools: toolDefs,
@@ -603738,12 +604505,15 @@ ${tail}`;
603738
604505
  appendRuntimeGuidance(guidance, turn) {
603739
604506
  const packet = this.formatRuntimeGuidance(guidance);
603740
604507
  const guidanceHash = _createHash("sha256").update(packet).digest("hex").slice(0, 16);
604508
+ const semanticKey = this.runtimeGuidanceSemanticKey(guidance);
603741
604509
  const signal = signalFromBlock("runtime_guidance", "runtime.guidance", packet, {
603742
604510
  id: `runtime-guidance-${turn}-${guidanceHash}`,
603743
604511
  dedupeKey: `runtime.guidance:${guidanceHash}`,
604512
+ semanticKey,
604513
+ conflictGroup: "context.runtime-guidance",
603744
604514
  priority: 94,
603745
604515
  createdTurn: turn,
603746
- ttlTurns: 8
604516
+ ttlTurns: 3
603747
604517
  });
603748
604518
  if (signal)
603749
604519
  this._contextLedger.upsert(signal);
@@ -603759,20 +604529,31 @@ ${tail}`;
603759
604529
  return guidance;
603760
604530
  }
603761
604531
  return [
603762
- "[RUNTIME_GUIDANCE_INTAKE v1]",
603763
- "Source: Omnius runtime control/advisory signal, not an external user message.",
603764
- "",
603765
- "<<<RUNTIME_GUIDANCE>>>",
603766
- guidance,
603767
- "<<<END_RUNTIME_GUIDANCE>>>",
603768
- "",
603769
- "Contract:",
603770
- "- Treat this as diagnostic/control-plane guidance for the next action.",
603771
- "- Reconcile it with the user goal and fresh tool evidence.",
603772
- "- Do not quote or summarize this wrapper to the user.",
603773
- "[/RUNTIME_GUIDANCE_INTAKE]"
604532
+ "[RUNTIME DIRECTIVE]",
604533
+ "source=omnius_runtime",
604534
+ guidance
603774
604535
  ].join("\n");
603775
604536
  }
604537
+ runtimeGuidanceSemanticKey(guidance) {
604538
+ const normalized = guidance.replace(/\s+/g, " ").trim().toLowerCase();
604539
+ if (/compile|verifier|verification|build|fix loop/.test(normalized)) {
604540
+ return "runtime.guidance.verification";
604541
+ }
604542
+ if (/action_reason|tool action reason|schema|argument/.test(normalized)) {
604543
+ return "runtime.guidance.tool-args";
604544
+ }
604545
+ if (/doom-loop|loop|repeat|identical|stuck|stale|cached/.test(normalized)) {
604546
+ return "runtime.guidance.loop-control";
604547
+ }
604548
+ if (/todo|workboard|card|task state/.test(normalized)) {
604549
+ return "runtime.guidance.task-state";
604550
+ }
604551
+ if (/scope|owned file|forbidden|mutation/.test(normalized)) {
604552
+ return "runtime.guidance.mutation-scope";
604553
+ }
604554
+ const digest3 = _createHash("sha256").update(normalized.slice(0, 400)).digest("hex").slice(0, 10);
604555
+ return `runtime.guidance.${digest3}`;
604556
+ }
603776
604557
  formatInjectedUserMessage(userMsg) {
603777
604558
  if (userMsg.trim().startsWith("[MID_TASK_STEERING_INTAKE")) {
603778
604559
  return userMsg;
@@ -609566,7 +610347,7 @@ var init_composite_scorer = __esm({
609566
610347
  });
609567
610348
 
609568
610349
  // packages/orchestrator/dist/memory/materialization-policy.js
609569
- import { createHash as createHash34 } from "node:crypto";
610350
+ import { createHash as createHash35 } from "node:crypto";
609570
610351
  function materializeMemoryItems(items, options2 = {}) {
609571
610352
  const config = options2.config ?? DEFAULT_WEIGHTING_CONFIG;
609572
610353
  const sorted = [...items].sort((a2, b) => b.weight - a2.weight || a2.id.localeCompare(b.id));
@@ -609804,7 +610585,7 @@ function estimateTokens4(text2) {
609804
610585
  return Math.max(1, Math.ceil(text2.length / 4));
609805
610586
  }
609806
610587
  function hashText(text2) {
609807
- return createHash34("sha256").update(text2).digest("hex");
610588
+ return createHash35("sha256").update(text2).digest("hex");
609808
610589
  }
609809
610590
  var init_materialization_policy = __esm({
609810
610591
  "packages/orchestrator/dist/memory/materialization-policy.js"() {
@@ -609968,7 +610749,7 @@ var init_config_loader = __esm({
609968
610749
  });
609969
610750
 
609970
610751
  // packages/orchestrator/dist/memory/stability-tracker.js
609971
- import { createHash as createHash35 } from "node:crypto";
610752
+ import { createHash as createHash36 } from "node:crypto";
609972
610753
  import { existsSync as existsSync109, mkdirSync as mkdirSync60, readFileSync as readFileSync84, writeFileSync as writeFileSync51 } from "node:fs";
609973
610754
  import { dirname as dirname36, join as join117 } from "node:path";
609974
610755
  function stabilityFilePath(repoRoot) {
@@ -610032,7 +610813,7 @@ function computeStabilityHash(item) {
610032
610813
  item.scope.name,
610033
610814
  item.topicKey
610034
610815
  ].join("|");
610035
- return createHash35("sha256").update(normalized).digest("hex");
610816
+ return createHash36("sha256").update(normalized).digest("hex");
610036
610817
  }
610037
610818
  function normalizeContent2(content) {
610038
610819
  return content.replace(/\s+/g, " ").trim();
@@ -614033,10 +614814,10 @@ var init_project_arc = __esm({
614033
614814
  });
614034
614815
 
614035
614816
  // packages/orchestrator/dist/dedup-gate.js
614036
- import { createHash as createHash36 } from "node:crypto";
614817
+ import { createHash as createHash37 } from "node:crypto";
614037
614818
  function fingerprintCall(name10, args) {
614038
614819
  const canon = canonicalize(args);
614039
- return createHash36("sha1").update(`${name10}\0${canon}`).digest("hex").slice(0, 16);
614820
+ return createHash37("sha1").update(`${name10}\0${canon}`).digest("hex").slice(0, 16);
614040
614821
  }
614041
614822
  function canonicalize(value2) {
614042
614823
  if (value2 === null || typeof value2 !== "object")
@@ -624950,7 +625731,7 @@ var require_websocket3 = __commonJS({
624950
625731
  var http6 = __require("http");
624951
625732
  var net5 = __require("net");
624952
625733
  var tls2 = __require("tls");
624953
- var { randomBytes: randomBytes31, createHash: createHash51 } = __require("crypto");
625734
+ var { randomBytes: randomBytes31, createHash: createHash53 } = __require("crypto");
624954
625735
  var { Duplex: Duplex3, Readable } = __require("stream");
624955
625736
  var { URL: URL3 } = __require("url");
624956
625737
  var PerMessageDeflate3 = require_permessage_deflate3();
@@ -625610,7 +626391,7 @@ var require_websocket3 = __commonJS({
625610
626391
  abortHandshake(websocket, socket, "Invalid Upgrade header");
625611
626392
  return;
625612
626393
  }
625613
- const digest3 = createHash51("sha1").update(key + GUID).digest("base64");
626394
+ const digest3 = createHash53("sha1").update(key + GUID).digest("base64");
625614
626395
  if (res.headers["sec-websocket-accept"] !== digest3) {
625615
626396
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
625616
626397
  return;
@@ -625977,7 +626758,7 @@ var require_websocket_server2 = __commonJS({
625977
626758
  var EventEmitter15 = __require("events");
625978
626759
  var http6 = __require("http");
625979
626760
  var { Duplex: Duplex3 } = __require("stream");
625980
- var { createHash: createHash51 } = __require("crypto");
626761
+ var { createHash: createHash53 } = __require("crypto");
625981
626762
  var extension3 = require_extension3();
625982
626763
  var PerMessageDeflate3 = require_permessage_deflate3();
625983
626764
  var subprotocol3 = require_subprotocol2();
@@ -626278,7 +627059,7 @@ var require_websocket_server2 = __commonJS({
626278
627059
  );
626279
627060
  }
626280
627061
  if (this._state > RUNNING) return abortHandshake(socket, 503);
626281
- const digest3 = createHash51("sha1").update(key + GUID).digest("base64");
627062
+ const digest3 = createHash53("sha1").update(key + GUID).digest("base64");
626282
627063
  const headers = [
626283
627064
  "HTTP/1.1 101 Switching Protocols",
626284
627065
  "Upgrade: websocket",
@@ -633059,14 +633840,14 @@ var init_voice_session = __esm({
633059
633840
  });
633060
633841
 
633061
633842
  // packages/cli/src/tui/scoped-personality.ts
633062
- import { createHash as createHash37 } from "node:crypto";
633843
+ import { createHash as createHash38 } from "node:crypto";
633063
633844
  import { appendFileSync as appendFileSync13, existsSync as existsSync120, mkdirSync as mkdirSync72, readFileSync as readFileSync97, writeFileSync as writeFileSync60 } from "node:fs";
633064
633845
  import { join as join131, resolve as resolve60 } from "node:path";
633065
633846
  function safeName(input) {
633066
633847
  return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
633067
633848
  }
633068
633849
  function scopeHash(scope) {
633069
- return createHash37("sha1").update(`${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
633850
+ return createHash38("sha1").update(`${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
633070
633851
  }
633071
633852
  function scopedPersonalityDir(repoRoot, kind) {
633072
633853
  return resolve60(repoRoot, ".omnius", "scoped-personality", kind);
@@ -633437,7 +634218,7 @@ var init_scoped_personality = __esm({
633437
634218
  });
633438
634219
 
633439
634220
  // packages/cli/src/tui/voice-soul.ts
633440
- import { createHash as createHash38 } from "node:crypto";
634221
+ import { createHash as createHash39 } from "node:crypto";
633441
634222
  import { existsSync as existsSync121, readdirSync as readdirSync38, readFileSync as readFileSync98 } from "node:fs";
633442
634223
  import { basename as basename26, join as join132, resolve as resolve61 } from "node:path";
633443
634224
  function compactText(text2, limit) {
@@ -633452,7 +634233,7 @@ function blockText(text2, limit) {
633452
634233
  ... [truncated]`;
633453
634234
  }
633454
634235
  function scopeStateKey(scope, surface) {
633455
- return createHash38("sha1").update(`${surface}:${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
634236
+ return createHash39("sha1").update(`${surface}:${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
633456
634237
  }
633457
634238
  function safeName2(input) {
633458
634239
  return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
@@ -636092,7 +636873,7 @@ var init_types3 = __esm({
636092
636873
  });
636093
636874
 
636094
636875
  // packages/cli/src/tui/p2p/secret-vault.ts
636095
- import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes23, scryptSync as scryptSync2, createHash as createHash39 } from "node:crypto";
636876
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes23, scryptSync as scryptSync2, createHash as createHash40 } from "node:crypto";
636096
636877
  import { readFileSync as readFileSync100, writeFileSync as writeFileSync62, existsSync as existsSync123, mkdirSync as mkdirSync74 } from "node:fs";
636097
636878
  import { dirname as dirname39 } from "node:path";
636098
636879
  var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
@@ -636336,7 +637117,7 @@ var init_secret_vault = __esm({
636336
637117
  /** Generate a deterministic fingerprint of vault contents (for sync verification) */
636337
637118
  fingerprint() {
636338
637119
  const names = Array.from(this.secrets.keys()).sort();
636339
- const hash = createHash39("sha256");
637120
+ const hash = createHash40("sha256");
636340
637121
  for (const name10 of names) {
636341
637122
  hash.update(name10 + ":");
636342
637123
  hash.update(this.secrets.get(name10).value);
@@ -636351,7 +637132,7 @@ var init_secret_vault = __esm({
636351
637132
  // packages/cli/src/tui/p2p/peer-mesh.ts
636352
637133
  import { EventEmitter as EventEmitter9 } from "node:events";
636353
637134
  import { createServer as createServer6 } from "node:http";
636354
- import { randomBytes as randomBytes24, createHash as createHash40, generateKeyPairSync } from "node:crypto";
637135
+ import { randomBytes as randomBytes24, createHash as createHash41, generateKeyPairSync } from "node:crypto";
636355
637136
  var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
636356
637137
  var init_peer_mesh = __esm({
636357
637138
  "packages/cli/src/tui/p2p/peer-mesh.ts"() {
@@ -636367,7 +637148,7 @@ var init_peer_mesh = __esm({
636367
637148
  const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
636368
637149
  this.publicKey = publicKey2.export({ type: "spki", format: "der" });
636369
637150
  this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
636370
- this.peerId = createHash40("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
637151
+ this.peerId = createHash41("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
636371
637152
  this.capabilities = options2.capabilities;
636372
637153
  this.displayName = options2.displayName;
636373
637154
  this._authKey = options2.authKey ?? randomBytes24(24).toString("base64url");
@@ -637714,6 +638495,7 @@ __export(omnius_directory_exports, {
637714
638495
  recordUsage: () => recordUsage,
637715
638496
  renderSessionDiary: () => renderSessionDiary,
637716
638497
  resolveSettings: () => resolveSettings,
638498
+ sanitizeRestorePromptForModel: () => sanitizeRestorePromptForModel,
637717
638499
  sanitizeRestoredSessionLines: () => sanitizeRestoredSessionLines,
637718
638500
  saveGlobalSettings: () => saveGlobalSettings,
637719
638501
  savePendingTask: () => savePendingTask,
@@ -637732,7 +638514,7 @@ __export(omnius_directory_exports, {
637732
638514
  import { appendFileSync as appendFileSync14, cpSync as cpSync2, existsSync as existsSync125, mkdirSync as mkdirSync76, readFileSync as readFileSync102, writeFileSync as writeFileSync64, readdirSync as readdirSync41, statSync as statSync51, unlinkSync as unlinkSync23, openSync as openSync2, closeSync as closeSync2, renameSync as renameSync11, watch as fsWatch2 } from "node:fs";
637733
638515
  import { join as join136, relative as relative17, basename as basename27, dirname as dirname40, resolve as resolve62 } from "node:path";
637734
638516
  import { homedir as homedir42 } from "node:os";
637735
- import { createHash as createHash42 } from "node:crypto";
638517
+ import { createHash as createHash43 } from "node:crypto";
637736
638518
  function isGitRoot(dir) {
637737
638519
  const gitPath = join136(dir, ".git");
637738
638520
  if (!existsSync125(gitPath)) return false;
@@ -638214,7 +638996,7 @@ function buildHandoffPrompt(repoRoot) {
638214
638996
  return lines.join("\n");
638215
638997
  }
638216
638998
  function computeDedupeHash(task, savedAt) {
638217
- return createHash42("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
638999
+ return createHash43("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
638218
639000
  }
638219
639001
  function generateSessionId() {
638220
639002
  const timestamp = Date.now().toString(36);
@@ -638269,9 +639051,16 @@ function releaseLock(lockPath) {
638269
639051
  } catch {
638270
639052
  }
638271
639053
  }
639054
+ function stripModelContextNoise(raw) {
639055
+ if (!raw) return "";
639056
+ return String(raw).replace(/\r\n/g, "\n").split("\n").filter((line) => !MODEL_CONTEXT_NOISE_LINE_RE.test(line)).join("\n").replace(/\n{3,}/g, "\n\n").trim();
639057
+ }
639058
+ function sanitizeRestorePromptForModel(raw) {
639059
+ return stripModelContextNoise(raw);
639060
+ }
638272
639061
  function normalizeSessionText(raw, maxLen = 500) {
638273
639062
  if (!raw) return "";
638274
- return String(raw).replace(/\s+/g, " ").trim().slice(0, maxLen);
639063
+ return stripModelContextNoise(raw).replace(/\s+/g, " ").trim().slice(0, maxLen);
638275
639064
  }
638276
639065
  function normalizeList(items, maxItems) {
638277
639066
  if (!items || items.length === 0) return void 0;
@@ -638469,7 +639258,7 @@ function saveSessionContext(repoRoot, entry) {
638469
639258
  }
638470
639259
  function cleanPromptForDiary(raw) {
638471
639260
  if (!raw) return "";
638472
- let text2 = String(raw);
639261
+ let text2 = stripModelContextNoise(raw);
638473
639262
  text2 = text2.replace(/^\[Previous sessions exist[^\]]*\]\s*\n*/m, "");
638474
639263
  text2 = text2.replace(/^[\s\S]*?\n---\s*\n\s*NEW TASK:\s*/m, "");
638475
639264
  text2 = text2.replace(/^NEW TASK:\s*/m, "");
@@ -638829,6 +639618,7 @@ function buildContextRestoreSnapshot(repoRoot) {
638829
639618
  const restoredTodos = findRestoredTodoState(restoreSessionIds);
638830
639619
  const sourceSessionId = restoredTodos?.sessionId ?? restoreSessionIds[0];
638831
639620
  if (handoffPrompt) {
639621
+ const safeHandoffPrompt = stripModelContextNoise(handoffPrompt);
638832
639622
  const usefulEntries2 = (ctx3?.entries ?? []).filter((entry) => !isManualSessionEntry(entry));
638833
639623
  const baseCtx = ctx3 && ctx3.entries.length > 0 ? `
638834
639624
 
@@ -638838,7 +639628,7 @@ Recent tasks: ${(usefulEntries2.length > 0 ? usefulEntries2 : ctx3.entries).slic
638838
639628
  ).join(", ")}
638839
639629
  </session-recap>` : "";
638840
639630
  const prompt2 = appendRestoreBlocks(
638841
- handoffPrompt + (activeTaskAnchor ? `
639631
+ safeHandoffPrompt + (activeTaskAnchor ? `
638842
639632
 
638843
639633
  ${activeTaskAnchor}` : "") + baseCtx,
638844
639634
  [restoredTodos?.block, historyAnchor?.block]
@@ -638878,12 +639668,12 @@ ${activeTaskAnchor}` : "") + baseCtx,
638878
639668
  const last2 = recent[recent.length - 1] ?? ctx3.entries[ctx3.entries.length - 1];
638879
639669
  const lastCompleted = [...usefulEntries].reverse().find((entry) => entry.completed);
638880
639670
  const latestCompleted = lastCompleted ? `Latest completed task: ${normalizeSessionText(lastCompleted.assistantResponse || lastCompleted.summary || lastCompleted.task, 180)}` : "";
638881
- const recentDialogue = recent.slice(-8).map((entry) => {
638882
- const assistant = normalizeSessionText(entry.assistantResponse || entry.summary, 320) || "(no assistant reply captured)";
639671
+ const recentTaskState = recent.slice(-8).map((entry) => {
638883
639672
  const user = cleanPromptForDiary(entry.task).slice(0, 220);
638884
- return `User: ${user}
638885
- Assistant: ${assistant}`;
638886
- }).join("\n\n");
639673
+ const outcome = normalizeSessionText(entry.assistantResponse || entry.summary, 240);
639674
+ const status = entry.completed ? "done" : "partial";
639675
+ return `- [${status}] user_intent="${user}"${outcome ? ` outcome="${outcome}"` : ""}`;
639676
+ }).join("\n");
638887
639677
  const prov = last2.provenance ? `
638888
639678
  Provenance: ${last2.provenance} (file_read to expand)` : "";
638889
639679
  const kg = `
@@ -638898,8 +639688,8 @@ ${chronology.join("\n")}
638898
639688
  ` + (latestCompleted ? `
638899
639689
  ${latestCompleted}
638900
639690
  ` : "\n") + `
638901
- Most recent exchanges (older to newer):
638902
- ${recentDialogue}
639691
+ Recent structured task state (older to newer; transcript omitted from model context):
639692
+ ${recentTaskState}
638903
639693
  ` + (activeTaskAnchor ? `For continuation prompts, resume the active task anchor above; use chronology only to avoid repeating completed work.${prov}${kg}
638904
639694
  ` : `Continue from the latest exchange and do not repeat completed work.${prov}${kg}
638905
639695
  `) + `</session-recap>`,
@@ -639310,7 +640100,7 @@ function deleteUsageRecord(kind, value2, repoRoot) {
639310
640100
  remove(join136(repoRoot, OMNIUS_DIR, USAGE_HISTORY_FILE));
639311
640101
  }
639312
640102
  }
639313
- var OMNIUS_DIR, LEGACY_DIRS, SUBDIRS, gitignoreWatchers, gitignoreRetryTimers, CONTEXT_FILES, PENDING_TASK_FILE, HANDOFF_FILE, CONTEXT_SAVE_FILE, CONTEXT_LEDGER_FILE, MAX_CONTEXT_ENTRIES, MAX_SESSION_DIARY_ENTRIES, MAX_SESSION_DIARY_DETAILED_ENTRIES, MAX_CONTEXT_LEDGER_LINES, MAX_CONTEXT_LEDGER_BYTES, SAME_TASK_REPLACE_WINDOW_MS, LOCK_TIMEOUT_MS, LOCK_RETRY_MS, LOCK_RETRY_MAX, DEFAULT_RESTORED_SESSION_HISTORY_MAX_LINES, DEICTIC_CONTINUATION_TERMS, SESSIONS_DIR, SESSIONS_INDEX, TUI_STATE_SUFFIX, AUTHORED_SESSION_LINE, VISUAL_CHROME_LINE, SKIP_DIRS3, HOME_SKIP_DIRS, USAGE_HISTORY_FILE, MAX_HISTORY_RECORDS;
640103
+ var OMNIUS_DIR, LEGACY_DIRS, SUBDIRS, gitignoreWatchers, gitignoreRetryTimers, CONTEXT_FILES, PENDING_TASK_FILE, HANDOFF_FILE, CONTEXT_SAVE_FILE, CONTEXT_LEDGER_FILE, MAX_CONTEXT_ENTRIES, MAX_SESSION_DIARY_ENTRIES, MAX_SESSION_DIARY_DETAILED_ENTRIES, MAX_CONTEXT_LEDGER_LINES, MAX_CONTEXT_LEDGER_BYTES, SAME_TASK_REPLACE_WINDOW_MS, LOCK_TIMEOUT_MS, LOCK_RETRY_MS, LOCK_RETRY_MAX, MODEL_CONTEXT_NOISE_LINE_RE, DEFAULT_RESTORED_SESSION_HISTORY_MAX_LINES, DEICTIC_CONTINUATION_TERMS, SESSIONS_DIR, SESSIONS_INDEX, TUI_STATE_SUFFIX, AUTHORED_SESSION_LINE, VISUAL_CHROME_LINE, SKIP_DIRS3, HOME_SKIP_DIRS, USAGE_HISTORY_FILE, MAX_HISTORY_RECORDS;
639314
640104
  var init_omnius_directory = __esm({
639315
640105
  "packages/cli/src/tui/omnius-directory.ts"() {
639316
640106
  init_dist5();
@@ -639343,6 +640133,7 @@ var init_omnius_directory = __esm({
639343
640133
  LOCK_TIMEOUT_MS = 5e3;
639344
640134
  LOCK_RETRY_MS = 50;
639345
640135
  LOCK_RETRY_MAX = 100;
640136
+ MODEL_CONTEXT_NOISE_LINE_RE = /^\s*(?:🔊|E Task timeout reached|E Incomplete:|⚠ Task incomplete|Tokens:\s*[\d,]+|▹\s*continue\b|·\s*(?:Starting fresh|Context (?:auto-)?restored|Nexus P2P network connected|REST API:|Voice feedback enabled|Memory maintenance:)|.*\bSHELL TRANSCRIPT\b.*).*$/i;
639346
640137
  DEFAULT_RESTORED_SESSION_HISTORY_MAX_LINES = 600;
639347
640138
  DEICTIC_CONTINUATION_TERMS = /* @__PURE__ */ new Set([
639348
640139
  "again",
@@ -641822,13 +642613,18 @@ function loadSessionHistory2(repoRoot) {
641822
642613
  const exchanges = sessionCtx?.entries.slice(-2) ?? [];
641823
642614
  if (exchanges.length > 0) {
641824
642615
  if (lines.length > 1) lines.push("");
641825
- lines.push("Most recent user/assistant chronology:");
642616
+ lines.push("Recent structured task outcomes:");
641826
642617
  for (const entry of exchanges) {
641827
642618
  const user = cleanForStorage(entry.task) || entry.task;
641828
642619
  const assistant = cleanForStorage(entry.assistantResponse || entry.summary) || entry.assistantResponse || entry.summary;
641829
642620
  if (!assistant) continue;
641830
- lines.push(`- User: ${truncateProjectContextText(user, 120, "")}`);
641831
- lines.push(` Assistant: ${truncateProjectContextText(assistant, 160, "")}`);
642621
+ const status = entry.completed ? "done" : "partial";
642622
+ lines.push(
642623
+ `- [${status}] intent=${truncateProjectContextText(user, 120, "")}`
642624
+ );
642625
+ lines.push(
642626
+ ` outcome=${truncateProjectContextText(assistant, 160, "")}`
642627
+ );
641832
642628
  }
641833
642629
  }
641834
642630
  return lines.length > 1 ? lines.join("\n") : "";
@@ -665242,7 +666038,7 @@ __export(commands_exports, {
665242
666038
  });
665243
666039
  import * as nodeOs from "node:os";
665244
666040
  import { spawn as nodeSpawn2 } from "node:child_process";
665245
- import { createHash as createHash43 } from "node:crypto";
666041
+ import { createHash as createHash44 } from "node:crypto";
665246
666042
  import {
665247
666043
  existsSync as existsSync147,
665248
666044
  readFileSync as readFileSync119,
@@ -678602,7 +679398,7 @@ async function collectSponsorMediaStream(args) {
678602
679398
  };
678603
679399
  }
678604
679400
  if (artifact.sha256) {
678605
- const sha = createHash43("sha256").update(bytes).digest("hex");
679401
+ const sha = createHash44("sha256").update(bytes).digest("hex");
678606
679402
  if (sha !== artifact.sha256)
678607
679403
  return { ok: false, error: `Artifact hash mismatch for ${artifactId}` };
678608
679404
  }
@@ -693070,7 +693866,7 @@ import {
693070
693866
  unlinkSync as unlinkSync34
693071
693867
  } from "node:fs";
693072
693868
  import { join as join168 } from "node:path";
693073
- import { createHash as createHash44 } from "node:crypto";
693869
+ import { createHash as createHash45 } from "node:crypto";
693074
693870
  function safeFilePart(value2) {
693075
693871
  return value2.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 80) || "telegram";
693076
693872
  }
@@ -693078,7 +693874,7 @@ function daydreamRoot(repoRoot) {
693078
693874
  return join168(repoRoot, ".omnius", "telegram-daydreams");
693079
693875
  }
693080
693876
  function sessionDir(repoRoot, sessionKey) {
693081
- const hash = createHash44("sha1").update(sessionKey).digest("hex").slice(0, 20);
693877
+ const hash = createHash45("sha1").update(sessionKey).digest("hex").slice(0, 20);
693082
693878
  return join168(daydreamRoot(repoRoot), safeFilePart(hash));
693083
693879
  }
693084
693880
  function compactLine2(value2, max = 220) {
@@ -693189,7 +693985,7 @@ function buildReplyOpportunities(input, openQuestions) {
693189
693985
  return opportunities;
693190
693986
  }
693191
693987
  function daydreamOpportunityId(input, trigger) {
693192
- return createHash44("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
693988
+ return createHash45("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
693193
693989
  }
693194
693990
  function clamp0115(value2) {
693195
693991
  if (!Number.isFinite(value2)) return 0;
@@ -693594,7 +694390,7 @@ function buildTelegramChannelDaydream(input, corpus, extraction, extractionCommi
693594
694390
  const seed = `${input.sessionKey}:${input.generatedAtMs}:${input.history.length}`;
693595
694391
  return {
693596
694392
  version: 3,
693597
- id: createHash44("sha1").update(seed).digest("hex").slice(0, 16),
694393
+ id: createHash45("sha1").update(seed).digest("hex").slice(0, 16),
693598
694394
  sessionKey: input.sessionKey,
693599
694395
  chatId: input.chatId,
693600
694396
  chatTitle: input.chatTitle,
@@ -693906,12 +694702,12 @@ var init_telegram_channel_dmn = __esm({
693906
694702
  });
693907
694703
 
693908
694704
  // packages/cli/src/tui/telegram-reflection-corpus.ts
693909
- import { createHash as createHash45 } from "node:crypto";
694705
+ import { createHash as createHash46 } from "node:crypto";
693910
694706
  function telegramReflectionMemoryDbPaths(repoRoot) {
693911
694707
  return omniusMemoryDbPaths(repoRoot);
693912
694708
  }
693913
694709
  function stableHash2(value2, length4 = 16) {
693914
- return createHash45("sha1").update(value2).digest("hex").slice(0, length4);
694710
+ return createHash46("sha1").update(value2).digest("hex").slice(0, length4);
693915
694711
  }
693916
694712
  function clean3(value2) {
693917
694713
  return String(value2 ?? "").replace(/\s+/g, " ").trim();
@@ -694724,7 +695520,7 @@ var init_telegram_reflection_extraction = __esm({
694724
695520
  });
694725
695521
 
694726
695522
  // packages/cli/src/tui/telegram-social-state-types.ts
694727
- import { createHash as createHash46 } from "node:crypto";
695523
+ import { createHash as createHash47 } from "node:crypto";
694728
695524
  function telegramSocialActorKey(actor) {
694729
695525
  if (!actor) return "unknown";
694730
695526
  if (typeof actor.userId === "number") return `user:${actor.userId}`;
@@ -694757,7 +695553,7 @@ function appendUnique(items, value2, max) {
694757
695553
  return next.slice(-max);
694758
695554
  }
694759
695555
  function hashTelegramSocialId(parts) {
694760
- return createHash46("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
695556
+ return createHash47("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
694761
695557
  }
694762
695558
  function cleanUsername(value2) {
694763
695559
  if (typeof value2 !== "string") return void 0;
@@ -695817,7 +696613,7 @@ import {
695817
696613
  } from "node:path";
695818
696614
  import { homedir as homedir56 } from "node:os";
695819
696615
  import { writeFile as writeFileAsync } from "node:fs/promises";
695820
- import { createHash as createHash47, randomBytes as randomBytes28, randomInt } from "node:crypto";
696616
+ import { createHash as createHash48, randomBytes as randomBytes28, randomInt } from "node:crypto";
695821
696617
  function formatModelBytes(bytes) {
695822
696618
  if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
695823
696619
  const units = ["B", "KB", "MB", "GB", "TB"];
@@ -697062,7 +697858,7 @@ function buildTelegramRuntimeContext(now2 = /* @__PURE__ */ new Date(), repoRoot
697062
697858
  return buildConversationRuntimeContext(now2, repoRoot);
697063
697859
  }
697064
697860
  function telegramSessionIdFromKey(sessionKey) {
697065
- return `telegram-${createHash47("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
697861
+ return `telegram-${createHash48("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
697066
697862
  }
697067
697863
  function normalizeTelegramSubAgentLimit(value2) {
697068
697864
  const parsed = typeof value2 === "number" ? value2 : typeof value2 === "string" && value2.trim() ? Number(value2.trim()) : TELEGRAM_SUB_AGENT_DEFAULT_LIMIT;
@@ -699226,7 +700022,7 @@ Telegram link integrity contract:
699226
700022
  return !!this.adminAuthChallenge && this.adminAuthChallenge.expiresAtMs > Date.now();
699227
700023
  }
699228
700024
  hashAdminAuthCode(code8) {
699229
- return createHash47("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
700025
+ return createHash48("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
699230
700026
  }
699231
700027
  viewIdForMessage(msg) {
699232
700028
  return `telegram-${this.sessionKeyForMessage(msg).replace(/[^A-Za-z0-9_-]/g, "-")}`;
@@ -701239,7 +702035,7 @@ ${mediaContext}` : ""
701239
702035
  telegramMemoryIngestPayload(msg, media, localPath, source, extractedContent) {
701240
702036
  const isReplyMedia = source === "reply";
701241
702037
  const messageId = isReplyMedia ? msg.replyToMessageId : msg.messageId;
701242
- const messageText = isReplyMedia ? msg.replyContext?.text || msg.replyContext?.caption || msg.replyToText || media.caption : msg.text || media.caption;
702038
+ const messageText2 = isReplyMedia ? msg.replyContext?.text || msg.replyContext?.caption || msg.replyToText || media.caption : msg.text || media.caption;
701243
702039
  const sender = isReplyMedia ? this.telegramMemorySenderFromReply(msg) : this.telegramMemorySenderFromMessage(msg);
701244
702040
  const modality = media.type === "audio" || media.type === "voice" ? "audio" : telegramMediaIsImage(media) ? "visual" : "text";
701245
702041
  const objectLabels = extractExplicitVisualObjectLabels({
@@ -701259,7 +702055,7 @@ ${mediaContext}` : ""
701259
702055
  id: messageId,
701260
702056
  threadId: msg.messageThreadId,
701261
702057
  timestamp: Date.now(),
701262
- text: messageText
702058
+ text: messageText2
701263
702059
  },
701264
702060
  replyTo: !isReplyMedia ? this.telegramMemoryReplyRef(msg) : void 0,
701265
702061
  modality,
@@ -701298,11 +702094,11 @@ ${mediaContext}` : ""
701298
702094
  return payload;
701299
702095
  }
701300
702096
  telegramConversationPath(sessionKey) {
701301
- const safe = createHash47("sha1").update(sessionKey).digest("hex").slice(0, 20);
702097
+ const safe = createHash48("sha1").update(sessionKey).digest("hex").slice(0, 20);
701302
702098
  return join170(this.telegramConversationDir, `${safe}.json`);
701303
702099
  }
701304
702100
  telegramConversationLedgerPath(sessionKey) {
701305
- const safe = createHash47("sha1").update(sessionKey).digest("hex").slice(0, 20);
702101
+ const safe = createHash48("sha1").update(sessionKey).digest("hex").slice(0, 20);
701306
702102
  return join170(this.telegramConversationDir, `${safe}.events.jsonl`);
701307
702103
  }
701308
702104
  telegramDb() {
@@ -701535,7 +702331,7 @@ ${mediaContext}` : ""
701535
702331
  relationships: Array.isArray(raw.relationships) ? raw.relationships.slice(0, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT).map((fact) => this.normalizeTelegramAssociativeFact(fact)) : [],
701536
702332
  actions: Array.isArray(raw.actions) ? raw.actions.slice(-TELEGRAM_ASSOCIATIVE_ACTION_LIMIT).map((action) => ({
701537
702333
  id: String(
701538
- action.id || createHash47("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)
702334
+ action.id || createHash48("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)
701539
702335
  ),
701540
702336
  ts: typeof action.ts === "number" ? action.ts : Date.now(),
701541
702337
  role: action.role === "assistant" ? "assistant" : "user",
@@ -701554,7 +702350,7 @@ ${mediaContext}` : ""
701554
702350
  const now2 = Date.now();
701555
702351
  return {
701556
702352
  id: String(
701557
- raw.id || createHash47("sha1").update(text2 || String(now2)).digest("hex").slice(0, 12)
702353
+ raw.id || createHash48("sha1").update(text2 || String(now2)).digest("hex").slice(0, 12)
701558
702354
  ),
701559
702355
  text: text2,
701560
702356
  tags: Array.isArray(raw.tags) ? raw.tags.map(String).slice(0, 16) : [],
@@ -702011,7 +702807,7 @@ ${mediaContext}` : ""
702011
702807
  telegramHistoryBackfillMessageId(sessionKey, entry, index) {
702012
702808
  if (typeof entry.messageId === "number" && Number.isFinite(entry.messageId))
702013
702809
  return entry.messageId;
702014
- const digest3 = createHash47("sha1").update(
702810
+ const digest3 = createHash48("sha1").update(
702015
702811
  `${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`
702016
702812
  ).digest("hex").slice(0, 8);
702017
702813
  return -Number.parseInt(digest3, 16);
@@ -703201,7 +703997,7 @@ ${mediaContext}` : ""
703201
703997
  const now2 = entry.ts ?? Date.now();
703202
703998
  memory.updatedAt = now2;
703203
703999
  const speaker = telegramHistorySpeaker(entry);
703204
- const actionId = createHash47("sha1").update(
704000
+ const actionId = createHash48("sha1").update(
703205
704001
  `${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now2}:${entry.text}`
703206
704002
  ).digest("hex").slice(0, 16);
703207
704003
  if (!memory.actions.some((action) => action.id === actionId)) {
@@ -703364,7 +704160,7 @@ ${mediaContext}` : ""
703364
704160
  let fact = facts.find((item) => item.text.toLowerCase() === key);
703365
704161
  if (!fact) {
703366
704162
  fact = {
703367
- id: createHash47("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
704163
+ id: createHash48("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
703368
704164
  text: clean5,
703369
704165
  tags: telegramMemoryTags(clean5, entry.mediaSummary),
703370
704166
  speakers: [],
@@ -703449,7 +704245,7 @@ ${mediaContext}` : ""
703449
704245
  const titleTags = tags.slice(0, 4);
703450
704246
  const title = titleTags.length > 0 ? `${speaker} / ${titleTags.join(" ")}` : `${speaker} / conversation`;
703451
704247
  const card = {
703452
- id: createHash47("sha1").update(`${sessionKey}:${now2}:${speaker}:${text2}`).digest("hex").slice(0, 12),
704248
+ id: createHash48("sha1").update(`${sessionKey}:${now2}:${speaker}:${text2}`).digest("hex").slice(0, 12),
703453
704249
  title,
703454
704250
  notes: [],
703455
704251
  tags: [],
@@ -706213,7 +707009,7 @@ ${list}` : "No shared group target is currently known for this sender. Ask in th
706213
707009
  }
706214
707010
  telegramRunnerStateDir(sessionKey) {
706215
707011
  if (!this.repoRoot) return void 0;
706216
- const safe = createHash47("sha1").update(sessionKey).digest("hex").slice(0, 20);
707012
+ const safe = createHash48("sha1").update(sessionKey).digest("hex").slice(0, 20);
706217
707013
  return join170(this.repoRoot, ".omnius", "telegram-runner-state", safe);
706218
707014
  }
706219
707015
  buildTelegramAdminOverviewContext(currentSessionKey) {
@@ -716908,14 +717704,14 @@ var init_access_policy = __esm({
716908
717704
  });
716909
717705
 
716910
717706
  // packages/cli/src/api/project-preferences.ts
716911
- import { createHash as createHash48 } from "node:crypto";
717707
+ import { createHash as createHash49 } from "node:crypto";
716912
717708
  import { existsSync as existsSync162, mkdirSync as mkdirSync100, readFileSync as readFileSync133, renameSync as renameSync16, writeFileSync as writeFileSync87, unlinkSync as unlinkSync37 } from "node:fs";
716913
717709
  import { homedir as homedir58 } from "node:os";
716914
717710
  import { join as join172, resolve as resolve75 } from "node:path";
716915
717711
  import { randomUUID as randomUUID20 } from "node:crypto";
716916
717712
  function projectKey(root) {
716917
717713
  const canonical = resolve75(root);
716918
- return createHash48("sha256").update(canonical).digest("hex").slice(0, 16);
717714
+ return createHash49("sha256").update(canonical).digest("hex").slice(0, 16);
716919
717715
  }
716920
717716
  function projectDir(root) {
716921
717717
  return join172(PROJECTS_DIR, projectKey(root));
@@ -717206,7 +718002,7 @@ var init_disk_task_output = __esm({
717206
718002
  });
717207
718003
 
717208
718004
  // packages/cli/src/api/http.ts
717209
- import { createHash as createHash49 } from "node:crypto";
718005
+ import { createHash as createHash50 } from "node:crypto";
717210
718006
  function problemDetails(opts) {
717211
718007
  const p2 = {
717212
718008
  type: opts.type ?? "about:blank",
@@ -717269,7 +718065,7 @@ function paginated(items, page2, total) {
717269
718065
  }
717270
718066
  function computeEtag(payload) {
717271
718067
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
717272
- const hash = createHash49("sha1").update(json).digest("hex").slice(0, 16);
718068
+ const hash = createHash50("sha1").update(json).digest("hex").slice(0, 16);
717273
718069
  return `W/"${hash}"`;
717274
718070
  }
717275
718071
  function checkNotModified(req3, res, etag) {
@@ -735432,7 +736228,8 @@ function getOpenApiSpec() {
735432
736228
  tags: ["Context"],
735433
736229
  parameters: [
735434
736230
  { name: "id", in: "path", required: true, schema: { type: "string" }, description: "Dump id, or latest" },
735435
- { name: "repo", in: "query", required: false, schema: { type: "string" } }
736231
+ { name: "repo", in: "query", required: false, schema: { type: "string" } },
736232
+ { name: "agent_type", in: "query", required: false, schema: { type: "string", enum: ["main", "sub-agent", "internal", "adversary", "auxiliary"] }, description: "When id is latest, fetch the latest dump for this agent type" }
735436
736233
  ],
735437
736234
  responses: { 200: { description: "Full context-window dump" }, 404: { description: "Dump not found" } }
735438
736235
  }
@@ -736679,7 +737476,7 @@ import {
736679
737476
  closeSync as closeSync6
736680
737477
  } from "node:fs";
736681
737478
  import { randomBytes as randomBytes29, randomUUID as randomUUID21, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
736682
- import { createHash as createHash50 } from "node:crypto";
737479
+ import { createHash as createHash51 } from "node:crypto";
736683
737480
  function memoryDbPaths3(baseDir = process.cwd()) {
736684
737481
  const dir = join183(baseDir, ".omnius");
736685
737482
  return {
@@ -744848,7 +745645,7 @@ function listScheduledTasks() {
744848
745645
  );
744849
745646
  const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
744850
745647
  const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
744851
- const fallbackId = createHash50("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
745648
+ const fallbackId = createHash51("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
744852
745649
  const uid = realId || fallbackId;
744853
745650
  const key = `${uid}`;
744854
745651
  if (seen.has(key)) return;
@@ -744986,8 +745783,8 @@ function deleteScheduledById(id2) {
744986
745783
  if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id))
744987
745784
  candidates.push(entry.id);
744988
745785
  try {
744989
- const { createHash: createHash51 } = require4("node:crypto");
744990
- const fallback = createHash51("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
745786
+ const { createHash: createHash53 } = require4("node:crypto");
745787
+ const fallback = createHash53("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
744991
745788
  if (!candidates.includes(fallback)) candidates.push(fallback);
744992
745789
  } catch {
744993
745790
  }
@@ -747224,6 +748021,7 @@ import { cwd } from "node:process";
747224
748021
  import { resolve as resolve78, join as join185, dirname as dirname56, extname as extname22, relative as relative22, sep as sep7 } from "node:path";
747225
748022
  import { createRequire as createRequire9 } from "node:module";
747226
748023
  import { fileURLToPath as fileURLToPath24 } from "node:url";
748024
+ import { createHash as createHash52 } from "node:crypto";
747227
748025
  import {
747228
748026
  readFileSync as readFileSync142,
747229
748027
  writeFileSync as writeFileSync94,
@@ -748150,6 +748948,37 @@ function getRuntimeToolProfilePolicy(repoRoot) {
748150
748948
  function truncateSubAgentViewText(s2, n2) {
748151
748949
  return s2.length > n2 ? `${s2.slice(0, n2)}…` : s2;
748152
748950
  }
748951
+ function childAgentTaskHash(task) {
748952
+ return createHash52("sha256").update(task).digest("hex").slice(0, 12);
748953
+ }
748954
+ function stripAnsiForParentContext(value2) {
748955
+ return value2.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");
748956
+ }
748957
+ function sanitizeChildAgentParentContextText(value2, options2 = {}) {
748958
+ const maxLines = options2.maxLines ?? CHILD_AGENT_PARENT_CONTEXT_MAX_LINES;
748959
+ const maxChars = options2.maxChars ?? CHILD_AGENT_PARENT_CONTEXT_MAX_CHARS;
748960
+ const noAnsi = stripAnsiForParentContext(value2).replace(/<think>[\s\S]*?<\/think>/gi, "").replace(/<think>[\s\S]*$/gi, "");
748961
+ const sanitized = sanitizeRestorePromptForModel(noAnsi);
748962
+ const lines = sanitized.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).filter((line) => !/SHELL TRANSCRIPT/i.test(line)).filter((line) => !/^Task:\s/i.test(line)).filter((line) => !/^Last output:\s*$/i.test(line)).slice(-maxLines);
748963
+ const joined = lines.join("\n");
748964
+ return joined.length > maxChars ? `${joined.slice(0, Math.max(0, maxChars - 14)).trimEnd()}...[truncated]` : joined;
748965
+ }
748966
+ function formatChildAgentParentGuidance(input) {
748967
+ const status = input.exitCode === 0 ? "completed" : "failed";
748968
+ const summary = sanitizeChildAgentParentContextText(input.output);
748969
+ const taskPreview = sanitizeChildAgentParentContextText(input.task, {
748970
+ maxLines: 2,
748971
+ maxChars: 220
748972
+ });
748973
+ return [
748974
+ `[child_agent_result] kind=${input.kind} id=${input.id} status=${status} exit_code=${input.exitCode ?? "unknown"} task_sha256=${childAgentTaskHash(input.task)}`,
748975
+ taskPreview ? `task_preview:
748976
+ ${taskPreview}` : null,
748977
+ summary ? `result_preview:
748978
+ ${summary}` : "result_preview: unavailable",
748979
+ `full_output_available_via=${input.kind === "full sub-agent" ? "full_sub_agent" : "sub_agent"} id=${input.id}`
748980
+ ].filter((line) => Boolean(line)).join("\n");
748981
+ }
748153
748982
  function subAgentDynamicBlockId(agentId, event, kind) {
748154
748983
  const safeAgent = agentId.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 48);
748155
748984
  const safeTs = String(event.timestamp || Date.now()).replace(
@@ -748525,11 +749354,17 @@ ${task}` : task;
748525
749354
  `sub_agent: ${cleanedLabelTask.slice(0, 80)}`,
748526
749355
  promise
748527
749356
  );
749357
+ const taskPreview = sanitizeChildAgentParentContextText(task, {
749358
+ maxLines: 2,
749359
+ maxChars: 220
749360
+ });
748528
749361
  return {
748529
749362
  success: true,
748530
749363
  output: `${compatibilityPrefix}Sub-agent started in background: ${taskId}
748531
- Task: ${task}
748532
- Use task_status(task_id="${taskId}") or task_output(task_id="${taskId}") to check progress.`
749364
+ task_sha256=${childAgentTaskHash(task)}
749365
+ ` + (taskPreview ? `task_preview:
749366
+ ${taskPreview}
749367
+ ` : "") + `Use task_status(task_id="${taskId}") or task_output(task_id="${taskId}") to check progress.`
748533
749368
  };
748534
749369
  }
748535
749370
  if (onViewStatus) onViewStatus(agentId, "running");
@@ -749901,16 +750736,18 @@ ${content}
749901
750736
  onComplete: (id2, task2, exitCode, output) => {
749902
750737
  registry2.unregisterAgent(id2);
749903
750738
  statusBar.unregisterAgentView(id2);
749904
- const summary = output.split("\n").filter((l2) => l2.trim()).slice(-5).join("\n");
749905
- const status = exitCode === 0 ? "COMPLETED" : "FAILED";
749906
- _activeRunnerRef?.injectUserMessage(
749907
- `[Sub-agent ${id2} ${status}]
749908
- Task: ${task2.slice(0, 100)}
749909
- Exit code: ${exitCode}
749910
- Last output:
749911
- ${summary}
749912
- Review its full output via sub_agent(action='output', id='${id2}')`
749913
- );
750739
+ const guidance = formatChildAgentParentGuidance({
750740
+ kind: "sub-agent",
750741
+ id: id2,
750742
+ task: task2,
750743
+ exitCode,
750744
+ output
750745
+ });
750746
+ if (_activeRunnerRef?.injectRuntimeGuidance) {
750747
+ _activeRunnerRef.injectRuntimeGuidance(guidance);
750748
+ } else {
750749
+ _activeRunnerRef?.injectUserMessage(guidance);
750750
+ }
749914
750751
  }
749915
750752
  });
749916
750753
  }
@@ -751930,16 +752767,18 @@ async function startInteractive(config, repoPath2) {
751930
752767
  onComplete: (id2, task, exitCode, output) => {
751931
752768
  registry2.unregisterAgent(id2);
751932
752769
  statusBar.unregisterAgentView(id2);
751933
- const summary = output.split("\n").filter((l2) => l2.trim()).slice(-5).join("\n");
751934
- const status = exitCode === 0 ? "COMPLETED" : "FAILED";
751935
- _activeRunnerRef?.injectUserMessage(
751936
- `[Full sub-agent ${id2} ${status}]
751937
- Task: ${task.slice(0, 100)}
751938
- Exit code: ${exitCode}
751939
- Last output:
751940
- ${summary}
751941
- Review its full output via full_sub_agent(action='output', id='${id2}')`
751942
- );
752770
+ const guidance = formatChildAgentParentGuidance({
752771
+ kind: "full sub-agent",
752772
+ id: id2,
752773
+ task,
752774
+ exitCode,
752775
+ output
752776
+ });
752777
+ if (_activeRunnerRef?.injectRuntimeGuidance) {
752778
+ _activeRunnerRef.injectRuntimeGuidance(guidance);
752779
+ } else {
752780
+ _activeRunnerRef?.injectUserMessage(guidance);
752781
+ }
751943
752782
  }
751944
752783
  });
751945
752784
  };
@@ -751970,16 +752809,18 @@ Review its full output via full_sub_agent(action='output', id='${id2}')`
751970
752809
  onComplete: (id2, task, exitCode, output) => {
751971
752810
  registry2.unregisterAgent(id2);
751972
752811
  statusBar.unregisterAgentView(id2);
751973
- const summary = output.split("\n").filter((l2) => l2.trim()).slice(-5).join("\n");
751974
- const status = exitCode === 0 ? "COMPLETED" : "FAILED";
751975
- _activeRunnerRef?.injectUserMessage(
751976
- `[Sub-agent ${id2} ${status}]
751977
- Task: ${task.slice(0, 100)}
751978
- Exit code: ${exitCode}
751979
- Last output:
751980
- ${summary}
751981
- Review its full output via sub_agent(action='output', id='${id2}')`
751982
- );
752812
+ const guidance = formatChildAgentParentGuidance({
752813
+ kind: "sub-agent",
752814
+ id: id2,
752815
+ task,
752816
+ exitCode,
752817
+ output
752818
+ });
752819
+ if (_activeRunnerRef?.injectRuntimeGuidance) {
752820
+ _activeRunnerRef.injectRuntimeGuidance(guidance);
752821
+ } else {
752822
+ _activeRunnerRef?.injectUserMessage(guidance);
752823
+ }
751983
752824
  }
751984
752825
  });
751985
752826
  };
@@ -756351,7 +757192,7 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
756351
757192
  },
756352
757193
  setRestoredContext(ctx3) {
756353
757194
  if (typeof ctx3 === "string") {
756354
- restoredSessionContext = ctx3;
757195
+ restoredSessionContext = sanitizeRestorePromptForModel(ctx3);
756355
757196
  } else {
756356
757197
  applyRestoreSnapshot(ctx3, { replayVisual: false });
756357
757198
  }
@@ -757342,7 +758183,8 @@ ${formatTaskCompletionMeta(previousMetaForIntake)}`
757342
758183
  let taskInput = fullInput;
757343
758184
  let taskSessionId = restoredTaskSessionId;
757344
758185
  if (restoredSessionContext) {
757345
- taskInput = `${restoredSessionContext}
758186
+ const safeRestoredContext = sanitizeRestorePromptForModel(restoredSessionContext);
758187
+ taskInput = `${safeRestoredContext}
757346
758188
 
757347
758189
  ---
757348
758190
 
@@ -757418,13 +758260,13 @@ ${taskInput}`;
757418
758260
  writeContent(() => renderError(errMsg));
757419
758261
  if (failureStore) {
757420
758262
  try {
757421
- const { createHash: createHash51 } = await import("node:crypto");
758263
+ const { createHash: createHash53 } = await import("node:crypto");
757422
758264
  failureStore.insert({
757423
758265
  taskId: "",
757424
758266
  sessionId: `${Date.now()}`,
757425
758267
  repoRoot,
757426
758268
  failureType: "runtime-error",
757427
- fingerprint: createHash51("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
758269
+ fingerprint: createHash53("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
757428
758270
  filePath: null,
757429
758271
  errorMessage: errMsg.slice(0, 500),
757430
758272
  context: null,
@@ -758183,7 +759025,7 @@ Rules:
758183
759025
  process.exit(1);
758184
759026
  }
758185
759027
  }
758186
- var NEXUS_DIRECTORY_ORIGIN3, NEXUS_AGENT_DIRECTORY_URL, localOllamaModelCache, localOllamaProbeInFlight, NEXUS_SPONSORS_URL3, ADVERSARY_COLOR, _generativeProgressSink, _liveMediaStatusSink, _liveMediaAudioCount, _liveMediaVideoCount, _interactiveSessionActive, _interactiveSessionReason, _voiceChatSession2, taskManager, _apiCallbacks, _shellToolRef, _replToolRef, _fullSubAgentToolRef, _agentToolRef, _sendMessageToolRef, _agentLifecycleMgr, _activeRunnerRef, _parentRunnerForArchive, _wireSubAgentCallbacks, _wireAgentToolCallbacks, _wireSubAgentToolCallbacks, _autoUpdatedThisSession, _mcpManager, _pluginManager, _mcpTools, subAgentPendingToolCalls, subAgentViewBlockSeq, SELF_IMPROVE_INTERVAL, _tasksSinceImprove;
759028
+ var NEXUS_DIRECTORY_ORIGIN3, NEXUS_AGENT_DIRECTORY_URL, localOllamaModelCache, localOllamaProbeInFlight, NEXUS_SPONSORS_URL3, ADVERSARY_COLOR, _generativeProgressSink, _liveMediaStatusSink, _liveMediaAudioCount, _liveMediaVideoCount, _interactiveSessionActive, _interactiveSessionReason, _voiceChatSession2, taskManager, _apiCallbacks, _shellToolRef, _replToolRef, _fullSubAgentToolRef, _agentToolRef, _sendMessageToolRef, _agentLifecycleMgr, _activeRunnerRef, _parentRunnerForArchive, _wireSubAgentCallbacks, _wireAgentToolCallbacks, _wireSubAgentToolCallbacks, _autoUpdatedThisSession, _mcpManager, _pluginManager, _mcpTools, subAgentPendingToolCalls, subAgentViewBlockSeq, CHILD_AGENT_PARENT_CONTEXT_MAX_LINES, CHILD_AGENT_PARENT_CONTEXT_MAX_CHARS, SELF_IMPROVE_INTERVAL, _tasksSinceImprove;
758187
759029
  var init_interactive = __esm({
758188
759030
  "packages/cli/src/tui/interactive.ts"() {
758189
759031
  init_memory_maintenance();
@@ -758287,6 +759129,8 @@ var init_interactive = __esm({
758287
759129
  _mcpTools = [];
758288
759130
  subAgentPendingToolCalls = /* @__PURE__ */ new Map();
758289
759131
  subAgentViewBlockSeq = 0;
759132
+ CHILD_AGENT_PARENT_CONTEXT_MAX_LINES = 5;
759133
+ CHILD_AGENT_PARENT_CONTEXT_MAX_CHARS = 900;
758290
759134
  SELF_IMPROVE_INTERVAL = 5;
758291
759135
  _tasksSinceImprove = 0;
758292
759136
  }