omnius 1.0.531 → 1.0.533

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
@@ -439258,14 +439258,14 @@ ${lanes.join("\n")}
439258
439258
  }
439259
439259
  if (diagnostic.relatedInformation) {
439260
439260
  output += host.getNewLine();
439261
- for (const { file, start: start2, length: length22, messageText } of diagnostic.relatedInformation) {
439261
+ for (const { file, start: start2, length: length22, messageText: messageText2 } of diagnostic.relatedInformation) {
439262
439262
  if (file) {
439263
439263
  output += host.getNewLine();
439264
439264
  output += halfIndent + formatLocation(file, start2, host);
439265
439265
  output += formatCodeSpan(file, start2, length22, indent2, "\x1B[96m", host);
439266
439266
  }
439267
439267
  output += host.getNewLine();
439268
- output += indent2 + flattenDiagnosticMessageText(messageText, host.getNewLine());
439268
+ output += indent2 + flattenDiagnosticMessageText(messageText2, host.getNewLine());
439269
439269
  }
439270
439270
  }
439271
439271
  output += host.getNewLine();
@@ -473931,8 +473931,8 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
473931
473931
  }
473932
473932
  }
473933
473933
  }
473934
- function tryGetConstraintFromDiagnosticMessage(messageText) {
473935
- const [, constraint] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/`extends (.*)`/) || [];
473934
+ function tryGetConstraintFromDiagnosticMessage(messageText2) {
473935
+ const [, constraint] = flattenDiagnosticMessageText(messageText2, "\n", 0).match(/`extends (.*)`/) || [];
473936
473936
  return constraint;
473937
473937
  }
473938
473938
  function tryGetConstraintType(checker, node) {
@@ -475979,8 +475979,8 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
475979
475979
  operator === 38 || operator === 36 ? factory.createPrefixUnaryExpression(54, callExpression) : callExpression
475980
475980
  );
475981
475981
  }
475982
- function getSuggestion(messageText) {
475983
- const [, suggestion] = flattenDiagnosticMessageText(messageText, "\n", 0).match(/'(.*)'/) || [];
475982
+ function getSuggestion(messageText2) {
475983
+ const [, suggestion] = flattenDiagnosticMessageText(messageText2, "\n", 0).match(/'(.*)'/) || [];
475984
475984
  return suggestion;
475985
475985
  }
475986
475986
  registerCodeFix({
@@ -541096,13 +541096,13 @@ Node text: ${this.#forgottenText}`;
541096
541096
  return file == null ? void 0 : this._context.compilerFactory.getSourceFile(file, { markInProject: false });
541097
541097
  }
541098
541098
  getMessageText() {
541099
- const messageText = this._compilerObject.messageText;
541100
- if (typeof messageText === "string")
541101
- return messageText;
541099
+ const messageText2 = this._compilerObject.messageText;
541100
+ if (typeof messageText2 === "string")
541101
+ return messageText2;
541102
541102
  if (this._context == null)
541103
- return new DiagnosticMessageChain(messageText);
541103
+ return new DiagnosticMessageChain(messageText2);
541104
541104
  else
541105
- return this._context.compilerFactory.getDiagnosticMessageChain(messageText);
541105
+ return this._context.compilerFactory.getDiagnosticMessageChain(messageText2);
541106
541106
  }
541107
541107
  getLineNumber() {
541108
541108
  const sourceFile = this.getSourceFile();
@@ -560801,6 +560801,10 @@ var init_adaptive_edit_strategy = __esm({
560801
560801
  });
560802
560802
 
560803
560803
  // packages/execution/dist/boundary-verifier.js
560804
+ function normalizeCompilerOutputLine(line) {
560805
+ const trimmed = line.trim();
560806
+ return trimmed.replace(/^\d+:\s+(?=(?:.*?:\d+(?::\d+)?:\s*(?:fatal\s+)?(?:error|warning):|(?:UnknownPackageError|PackageError):))/i, "");
560807
+ }
560804
560808
  function isStructuralBoundary(path16) {
560805
560809
  if (HEADER_EXT.test(path16))
560806
560810
  return true;
@@ -560848,7 +560852,7 @@ function parseCompilerDiagnostics(text2, language = "unknown") {
560848
560852
  }
560849
560853
  }
560850
560854
  for (const raw of allLines) {
560851
- const line = raw.trim();
560855
+ const line = normalizeCompilerOutputLine(raw);
560852
560856
  if (!line)
560853
560857
  continue;
560854
560858
  const pytestMatch = line.match(/^FAILED\s+(.+?)(?:::(\w+))?(?:\s+-\s+(.+))?$/);
@@ -560863,6 +560867,15 @@ function parseCompilerDiagnostics(text2, language = "unknown") {
560863
560867
  }
560864
560868
  if (!/error|FAILED|unrecognized|Traceback|Warning|warning/i.test(line))
560865
560869
  continue;
560870
+ const packageError = line.match(/^(?:UnknownPackageError|PackageError):\s*(.*)$/i);
560871
+ if (packageError) {
560872
+ out.push({
560873
+ kind: "import_error",
560874
+ symbol: firstQuoted(packageError[1] ?? line),
560875
+ message: packageError[1] ?? line
560876
+ });
560877
+ continue;
560878
+ }
560866
560879
  if (/unrecognized\s+(element|attribute)/i.test(line) || /not\s+allowed\s+here/i.test(line)) {
560867
560880
  const fileMatch = line.match(/^(.+?):/);
560868
560881
  const lnMatch = line.match(/:(\d+):/);
@@ -560875,6 +560888,8 @@ function parseCompilerDiagnostics(text2, language = "unknown") {
560875
560888
  continue;
560876
560889
  }
560877
560890
  const loc = line.match(/^(.+?):(\d+):(?:\d+:)?\s*(?:fatal\s+)?error:\s*(.*)$/i);
560891
+ if (!loc)
560892
+ continue;
560878
560893
  const file = loc?.[1];
560879
560894
  const lineNo = loc ? Number(loc[2]) : void 0;
560880
560895
  const msg = loc?.[3] ?? line;
@@ -576734,6 +576749,50 @@ function collectMetadataReports(signals) {
576734
576749
  forgettingReports: forgettingReports.length > 0 ? forgettingReports : void 0
576735
576750
  };
576736
576751
  }
576752
+ function signalIdentityKeys(signal) {
576753
+ return [
576754
+ signal.dedupeKey,
576755
+ signal.semanticKey,
576756
+ `${signal.kind}:${signal.id}`,
576757
+ signal.id,
576758
+ ...signal.tags ?? []
576759
+ ].flatMap((key) => {
576760
+ const clean5 = typeof key === "string" ? key.trim() : "";
576761
+ return clean5 ? [clean5] : [];
576762
+ });
576763
+ }
576764
+ function choosePreferredSignal(a2, b) {
576765
+ const pa = a2.priority ?? 0;
576766
+ const pb = b.priority ?? 0;
576767
+ if (pa !== pb)
576768
+ return pa > pb ? a2 : b;
576769
+ const ta = a2.createdTurn ?? 0;
576770
+ const tb = b.createdTurn ?? 0;
576771
+ if (ta !== tb)
576772
+ return ta > tb ? a2 : b;
576773
+ return a2.sequence > b.sequence ? a2 : b;
576774
+ }
576775
+ function sortSignals(a2, b) {
576776
+ const pa = a2.priority ?? 0;
576777
+ const pb = b.priority ?? 0;
576778
+ if (pa !== pb)
576779
+ return pb - pa;
576780
+ const ta = a2.createdTurn ?? 0;
576781
+ const tb = b.createdTurn ?? 0;
576782
+ if (ta !== tb)
576783
+ return tb - ta;
576784
+ return a2.source.localeCompare(b.source) || a2.id.localeCompare(b.id);
576785
+ }
576786
+ function semanticKeyFor(signal) {
576787
+ const key = signal.semanticKey ?? signal.dedupeKey;
576788
+ return typeof key === "string" && key.trim() ? key.trim() : null;
576789
+ }
576790
+ function isControlSignal(signal) {
576791
+ return signal.kind === "runtime_guidance" || signal.kind === "action_contract" || signal.kind === "recent_failure";
576792
+ }
576793
+ function isEvidenceSignal(signal) {
576794
+ 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";
576795
+ }
576737
576796
  function signalFromBlock(kind, source, content, options2 = {}) {
576738
576797
  const normalized = normalizeSignalContent(content ?? "");
576739
576798
  if (!normalized)
@@ -576747,6 +576806,10 @@ function signalFromBlock(kind, source, content, options2 = {}) {
576747
576806
  createdTurn: options2.createdTurn,
576748
576807
  ttlTurns: options2.ttlTurns,
576749
576808
  dedupeKey: options2.dedupeKey,
576809
+ semanticKey: options2.semanticKey,
576810
+ conflictGroup: options2.conflictGroup,
576811
+ invalidates: options2.invalidates,
576812
+ modelVisible: options2.modelVisible,
576750
576813
  tags: options2.tags,
576751
576814
  metadata: options2.metadata
576752
576815
  };
@@ -576815,12 +576878,12 @@ var init_context_fabric = __esm({
576815
576878
  DEFAULT_KIND_CHAR_BUDGET = {
576816
576879
  goal: 900,
576817
576880
  user_steering: 1400,
576818
- runtime_guidance: 1800,
576819
- action_contract: 1800,
576881
+ runtime_guidance: 900,
576882
+ action_contract: 1400,
576820
576883
  git_state: 1400,
576821
576884
  task_state: 1800,
576822
576885
  known_files: 2400,
576823
- recent_failure: 2600,
576886
+ recent_failure: 1400,
576824
576887
  tool_cache: 2200,
576825
576888
  skill_manifest: 900,
576826
576889
  memory: 1500,
@@ -576836,11 +576899,16 @@ var init_context_fabric = __esm({
576836
576899
  ContextLedger = class {
576837
576900
  signals = /* @__PURE__ */ new Map();
576838
576901
  sequence = 0;
576902
+ invalidatedSinceLastBuild = 0;
576839
576903
  upsert(signal) {
576840
576904
  const content = normalizeSignalContent(signal.content);
576841
576905
  if (!content)
576842
576906
  return;
576843
- const key = signal.dedupeKey || `${signal.kind}:${signal.id}`;
576907
+ if (Array.isArray(signal.invalidates) && signal.invalidates.length > 0) {
576908
+ const invalidates = new Set(signal.invalidates.map((key2) => String(key2 ?? "").trim()).filter(Boolean));
576909
+ this.invalidatedSinceLastBuild += this.removeWhere((existing2) => signalIdentityKeys(existing2).some((key2) => invalidates.has(key2)));
576910
+ }
576911
+ const key = signal.dedupeKey || signal.semanticKey || `${signal.kind}:${signal.id}`;
576844
576912
  const incoming = {
576845
576913
  ...signal,
576846
576914
  content,
@@ -576854,12 +576922,15 @@ var init_context_fabric = __esm({
576854
576922
  this.signals.set(key, incoming);
576855
576923
  return;
576856
576924
  }
576857
- const shouldReplace = incoming.createdTurn > existing.createdTurn || incoming.createdTurn === existing.createdTurn && incoming.priority >= existing.priority || incoming.priority > existing.priority;
576858
- if (shouldReplace) {
576925
+ const preferred = choosePreferredSignal(incoming, existing);
576926
+ if (preferred === incoming) {
576859
576927
  this.signals.set(key, {
576860
576928
  ...existing,
576861
576929
  ...incoming,
576862
576930
  tags: [.../* @__PURE__ */ new Set([...existing.tags ?? [], ...incoming.tags ?? []])],
576931
+ invalidates: [
576932
+ .../* @__PURE__ */ new Set([...existing.invalidates ?? [], ...incoming.invalidates ?? []])
576933
+ ],
576863
576934
  metadata: { ...existing.metadata ?? {}, ...incoming.metadata ?? {} }
576864
576935
  });
576865
576936
  }
@@ -576900,12 +576971,64 @@ var init_context_fabric = __esm({
576900
576971
  size() {
576901
576972
  return this.signals.size;
576902
576973
  }
576974
+ consumeInvalidatedCount() {
576975
+ const count = this.invalidatedSinceLastBuild;
576976
+ this.invalidatedSinceLastBuild = 0;
576977
+ return count;
576978
+ }
576903
576979
  };
576904
576980
  ContextFrameBuilder = class {
576905
576981
  build(signals, options2 = {}) {
576906
576982
  const maxChars = Math.max(1200, options2.maxChars ?? 1e4);
576907
576983
  const budgets = { ...DEFAULT_KIND_CHAR_BUDGET, ...options2.kindCharBudget ?? {} };
576908
- const sanitized = signals.map((signal) => ({ ...signal, content: normalizeSignalContent(signal.content) })).filter((signal) => signal.content.length > 0);
576984
+ const normalized = signals.map((signal) => ({ ...signal, content: normalizeSignalContent(signal.content) })).filter((signal) => signal.content.length > 0);
576985
+ const hidden = normalized.filter((signal) => signal.modelVisible === false);
576986
+ const visible = normalized.filter((signal) => signal.modelVisible !== false);
576987
+ const droppedByAdmission = [];
576988
+ let semanticDedupedSignals = 0;
576989
+ let conflictDroppedSignals = 0;
576990
+ const semanticBest = /* @__PURE__ */ new Map();
576991
+ for (const signal of visible) {
576992
+ const key = semanticKeyFor(signal);
576993
+ if (!key)
576994
+ continue;
576995
+ const prior = semanticBest.get(key);
576996
+ if (!prior || sortSignals(signal, prior) < 0) {
576997
+ if (prior) {
576998
+ droppedByAdmission.push(prior);
576999
+ semanticDedupedSignals++;
577000
+ }
577001
+ semanticBest.set(key, signal);
577002
+ } else {
577003
+ droppedByAdmission.push(signal);
577004
+ semanticDedupedSignals++;
577005
+ }
577006
+ }
577007
+ const afterSemantic = visible.filter((signal) => {
577008
+ const key = semanticKeyFor(signal);
577009
+ return !key || semanticBest.get(key) === signal;
577010
+ });
577011
+ const conflictBest = /* @__PURE__ */ new Map();
577012
+ for (const signal of afterSemantic) {
577013
+ const key = typeof signal.conflictGroup === "string" ? signal.conflictGroup.trim() : "";
577014
+ if (!key)
577015
+ continue;
577016
+ const prior = conflictBest.get(key);
577017
+ if (!prior || sortSignals(signal, prior) < 0) {
577018
+ if (prior) {
577019
+ droppedByAdmission.push(prior);
577020
+ conflictDroppedSignals++;
577021
+ }
577022
+ conflictBest.set(key, signal);
577023
+ } else {
577024
+ droppedByAdmission.push(signal);
577025
+ conflictDroppedSignals++;
577026
+ }
577027
+ }
577028
+ const sanitized = afterSemantic.filter((signal) => {
577029
+ const key = typeof signal.conflictGroup === "string" ? signal.conflictGroup.trim() : "";
577030
+ return !key || conflictBest.get(key) === signal;
577031
+ });
576909
577032
  const byKind = /* @__PURE__ */ new Map();
576910
577033
  for (const signal of sanitized) {
576911
577034
  const bucket = byKind.get(signal.kind) ?? [];
@@ -576922,17 +577045,7 @@ var init_context_fabric = __esm({
576922
577045
  const bucket = byKind.get(kind);
576923
577046
  if (!bucket || bucket.length === 0)
576924
577047
  continue;
576925
- const sorted = [...bucket].sort((a2, b) => {
576926
- const pa = a2.priority ?? 0;
576927
- const pb = b.priority ?? 0;
576928
- if (pa !== pb)
576929
- return pb - pa;
576930
- const ta = a2.createdTurn ?? 0;
576931
- const tb = b.createdTurn ?? 0;
576932
- if (ta !== tb)
576933
- return tb - ta;
576934
- return a2.source.localeCompare(b.source) || a2.id.localeCompare(b.id);
576935
- });
577048
+ const sorted = [...bucket].sort(sortSignals);
576936
577049
  const budget = Math.max(200, budgets[kind]);
576937
577050
  const body = [];
576938
577051
  let chars = 0;
@@ -576970,21 +577083,40 @@ var init_context_fabric = __esm({
576970
577083
  "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."
576971
577084
  ].filter(Boolean);
576972
577085
  let content = [...header, "", ...sectionLines].join("\n").trim();
577086
+ const controlChars = included.filter(isControlSignal).reduce((sum2, signal) => sum2 + signal.content.length, 0);
577087
+ const evidenceChars = included.filter(isEvidenceSignal).reduce((sum2, signal) => sum2 + signal.content.length, 0);
577088
+ const controlToEvidenceRatio = Number((controlChars / Math.max(1, evidenceChars)).toFixed(3));
577089
+ const qualityWarnings = [];
577090
+ const maxControlRatio = options2.maxControlToEvidenceRatio ?? 0.45;
577091
+ if (controlToEvidenceRatio > maxControlRatio) {
577092
+ qualityWarnings.push(`control_context_ratio_high:${controlToEvidenceRatio}`);
577093
+ }
577094
+ const activeFrameCount = (content.match(/\[ACTIVE CONTEXT FRAME\]/g) ?? []).length;
577095
+ if (activeFrameCount > 1)
577096
+ qualityWarnings.push(`active_frame_count:${activeFrameCount}`);
576973
577097
  if (sectionLines.length === 0) {
576974
577098
  return {
576975
577099
  content: null,
576976
577100
  diagnostics: {
576977
577101
  includedSignals: 0,
576978
- droppedSignals: sanitized.length,
577102
+ droppedSignals: sanitized.length + droppedByAdmission.length,
577103
+ hiddenSignals: hidden.length,
577104
+ semanticDedupedSignals,
577105
+ conflictDroppedSignals,
577106
+ invalidatedSignals: options2.invalidatedSignals ?? 0,
576979
577107
  truncatedSignals: 0,
576980
577108
  estimatedTokens: 0,
576981
577109
  totalChars: 0,
576982
577110
  semanticChunkCount: 0,
577111
+ controlChars: 0,
577112
+ evidenceChars: 0,
577113
+ controlToEvidenceRatio: 0,
577114
+ qualityWarnings,
576983
577115
  ...metadataReports,
576984
577116
  sections: []
576985
577117
  },
576986
577118
  included: [],
576987
- dropped: sanitized
577119
+ dropped: [...sanitized, ...droppedByAdmission, ...hidden]
576988
577120
  };
576989
577121
  }
576990
577122
  if (content.length > maxChars) {
@@ -577006,22 +577138,243 @@ context_fabric: included=${included.length} dropped=${dropped.length} truncated=
577006
577138
  content,
577007
577139
  diagnostics: {
577008
577140
  includedSignals: included.length,
577009
- droppedSignals: dropped.length,
577141
+ droppedSignals: dropped.length + droppedByAdmission.length,
577142
+ hiddenSignals: hidden.length,
577143
+ semanticDedupedSignals,
577144
+ conflictDroppedSignals,
577145
+ invalidatedSignals: options2.invalidatedSignals ?? 0,
577010
577146
  truncatedSignals,
577011
577147
  estimatedTokens: estimateTokens2(content),
577012
577148
  totalChars: content.length,
577013
577149
  semanticChunkCount: included.filter((signal) => signal.kind === "semantic_chunk").length,
577150
+ controlChars,
577151
+ evidenceChars,
577152
+ controlToEvidenceRatio,
577153
+ qualityWarnings,
577014
577154
  ...metadataReports,
577015
577155
  sections: sectionDiagnostics
577016
577156
  },
577017
577157
  included,
577018
- dropped
577158
+ dropped: [...dropped, ...droppedByAdmission, ...hidden]
577019
577159
  };
577020
577160
  }
577021
577161
  };
577022
577162
  }
577023
577163
  });
577024
577164
 
577165
+ // packages/orchestrator/dist/context-compiler.js
577166
+ function collapseWhitespace(text2) {
577167
+ return text2.replace(/\r\n/g, "\n").split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
577168
+ }
577169
+ function sanitizeModelVisibleContextText(text2) {
577170
+ let out = String(text2 ?? "");
577171
+ out = out.replace(RUNTIME_GUIDANCE_RE, (_match, inner) => {
577172
+ return `[runtime_guidance]
577173
+ ${String(inner ?? "").trim()}`;
577174
+ });
577175
+ out = out.split("\n").filter((line) => !RESTORE_NOISE_LINE_RE.test(line)).join("\n");
577176
+ const frameMatches = [...out.matchAll(ACTIVE_CONTEXT_RE)];
577177
+ if (frameMatches.length > 1) {
577178
+ const last2 = frameMatches[frameMatches.length - 1]?.[0] ?? "";
577179
+ out = out.replace(ACTIVE_CONTEXT_RE, "").trim();
577180
+ out = `${last2}
577181
+ ${out}`.trim();
577182
+ }
577183
+ return collapseWhitespace(out);
577184
+ }
577185
+ function messageText(content) {
577186
+ if (typeof content === "string")
577187
+ return content;
577188
+ if (!Array.isArray(content))
577189
+ return "";
577190
+ return content.map((part) => {
577191
+ if (part && typeof part === "object") {
577192
+ const rec = part;
577193
+ return rec["type"] === "text" && typeof rec["text"] === "string" ? rec["text"] : "";
577194
+ }
577195
+ return "";
577196
+ }).filter(Boolean).join("\n");
577197
+ }
577198
+ function runtimeControlSemanticKey(content) {
577199
+ const normalized = content.replace(/\s+/g, " ").trim().toLowerCase();
577200
+ if (!normalized)
577201
+ return null;
577202
+ if (content.includes("[ACTIVE CONTEXT FRAME]"))
577203
+ return "context.active-frame";
577204
+ if (content.includes("[NEXT ACTION CONTRACT]"))
577205
+ return "context.next-action";
577206
+ if (content.includes("[RUNTIME DIRECTIVE]")) {
577207
+ if (/compile|verifier|verification|build|fix loop/.test(normalized))
577208
+ return "runtime.guidance.verification";
577209
+ if (/action_reason|tool action reason|schema|argument/.test(normalized))
577210
+ return "runtime.guidance.tool-args";
577211
+ if (/doom-loop|loop|repeat|identical|stuck|stale|cached/.test(normalized))
577212
+ return "runtime.guidance.loop-control";
577213
+ if (/todo|workboard|card|task state/.test(normalized))
577214
+ return "runtime.guidance.task-state";
577215
+ if (/scope|owned file|forbidden|mutation/.test(normalized))
577216
+ return "runtime.guidance.mutation-scope";
577217
+ return "runtime.guidance.general";
577218
+ }
577219
+ if (/\[TOOL ACTION REASON CONTRACT\]|action_reason/i.test(content))
577220
+ return "runtime.guidance.tool-args";
577221
+ if (/\[LOCAL ERROR-INFORMED NUDGE\]/.test(content))
577222
+ return "runtime.guidance.local-error";
577223
+ if (/\[STOP — RETRY LOOP DETECTED\]|\[RECENT TOOL FAILURES/i.test(content))
577224
+ return "runtime.guidance.recent-failures";
577225
+ if (/REG-\d+|FIRST-EDIT|STUCK DETECTOR|LOOP CIRCUIT|doom-loop/i.test(content))
577226
+ return "runtime.guidance.loop-control";
577227
+ if (/\[Associative Memory/i.test(content))
577228
+ return "context.associative-memory";
577229
+ if (/\[TOOL MODE — PROMPT INJECTION\]/.test(content))
577230
+ return "context.tool-mode-prompt";
577231
+ return null;
577232
+ }
577233
+ function hasConcreteGoalMessage(messages2) {
577234
+ return messages2.some((message2) => {
577235
+ const text2 = messageText(message2.content);
577236
+ return /\[CURRENT USER GOAL\]/.test(text2) && !/No concrete current user goal/i.test(text2);
577237
+ });
577238
+ }
577239
+ function hasUserMessage(messages2) {
577240
+ return messages2.some((message2) => message2.role === "user" && messageText(message2.content).trim().length > 0);
577241
+ }
577242
+ function prepareModelFacingApiMessages(input) {
577243
+ const preserveFirstSystem = input.preserveFirstSystem !== false;
577244
+ const sanitized = [];
577245
+ for (let index = 0; index < input.messages.length; index++) {
577246
+ const message2 = input.messages[index];
577247
+ if (message2.role === "system" && typeof message2.content === "string") {
577248
+ if (preserveFirstSystem && sanitized.length === 0) {
577249
+ sanitized.push({ ...message2 });
577250
+ continue;
577251
+ }
577252
+ const cleaned = sanitizeModelVisibleContextText(message2.content);
577253
+ if (!cleaned)
577254
+ continue;
577255
+ sanitized.push({ ...message2, content: cleaned });
577256
+ continue;
577257
+ }
577258
+ sanitized.push({ ...message2 });
577259
+ }
577260
+ const keep = new Array(sanitized.length).fill(true);
577261
+ const seenSystemKeys = /* @__PURE__ */ new Set();
577262
+ for (let index = sanitized.length - 1; index >= 0; index--) {
577263
+ const message2 = sanitized[index];
577264
+ if (message2.role !== "system" || typeof message2.content !== "string")
577265
+ continue;
577266
+ if (preserveFirstSystem && index === 0)
577267
+ continue;
577268
+ const key = runtimeControlSemanticKey(message2.content);
577269
+ if (!key)
577270
+ continue;
577271
+ if (seenSystemKeys.has(key)) {
577272
+ keep[index] = false;
577273
+ continue;
577274
+ }
577275
+ seenSystemKeys.add(key);
577276
+ }
577277
+ const deduped = sanitized.filter((_message, index) => keep[index]);
577278
+ if (!hasUserMessage(deduped) && !hasConcreteGoalMessage(deduped)) {
577279
+ const goal = deriveCurrentGoal({
577280
+ explicitGoal: input.currentGoal,
577281
+ signals: []
577282
+ });
577283
+ const goalMessage = {
577284
+ role: "system",
577285
+ content: [
577286
+ "[CURRENT USER GOAL]",
577287
+ "source=model-facing-api-view",
577288
+ goal.goal,
577289
+ goal.concrete ? null : "Required next action: recover or ask for the current user goal before mutating project files."
577290
+ ].filter(Boolean).join("\n")
577291
+ };
577292
+ const insertAt = preserveFirstSystem && deduped[0]?.role === "system" ? 1 : 0;
577293
+ deduped.splice(insertAt, 0, goalMessage);
577294
+ }
577295
+ return deduped;
577296
+ }
577297
+ function deriveCurrentGoal(input) {
577298
+ const explicit = sanitizeModelVisibleContextText(input.explicitGoal ?? "");
577299
+ if (explicit)
577300
+ return { goal: explicit.slice(0, 1200), concrete: true, source: "runtime_task_state" };
577301
+ 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];
577302
+ const fromSignal = sanitizeModelVisibleContextText(goalSignal?.content ?? "");
577303
+ if (fromSignal)
577304
+ return { goal: fromSignal.slice(0, 1200), concrete: true, source: goalSignal?.source ?? "context_signal" };
577305
+ return {
577306
+ 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.",
577307
+ concrete: false,
577308
+ source: "context_quality_gate"
577309
+ };
577310
+ }
577311
+ function normalizeContextSignalsForModel(signals) {
577312
+ const normalized = [];
577313
+ const rejected = [];
577314
+ for (const signal of signals) {
577315
+ if (signal.modelVisible === false) {
577316
+ normalized.push(signal);
577317
+ continue;
577318
+ }
577319
+ const content = sanitizeModelVisibleContextText(signal.content);
577320
+ if (!content) {
577321
+ rejected.push(signal);
577322
+ continue;
577323
+ }
577324
+ normalized.push({ ...signal, content });
577325
+ }
577326
+ return { signals: normalized, rejected };
577327
+ }
577328
+ function compileContextFrameV2(input) {
577329
+ const builder = input.builder ?? new ContextFrameBuilder();
577330
+ const normalized = normalizeContextSignalsForModel(input.signals);
577331
+ const goal = deriveCurrentGoal({
577332
+ explicitGoal: input.currentGoal,
577333
+ signals: normalized.signals
577334
+ });
577335
+ const warnings = [];
577336
+ if (!goal.concrete)
577337
+ warnings.push("missing_concrete_user_goal");
577338
+ const goalSignal = signalFromBlock("goal", "context-compiler.current-goal", [
577339
+ "[CURRENT USER GOAL]",
577340
+ `source=${goal.source}`,
577341
+ goal.goal,
577342
+ goal.concrete ? null : "Required next action: recover or ask for the current user goal before mutating project files."
577343
+ ].filter(Boolean).join("\n"), {
577344
+ id: "current-user-goal",
577345
+ dedupeKey: "context.current_user_goal",
577346
+ semanticKey: "context.current_user_goal",
577347
+ conflictGroup: "context.goal",
577348
+ priority: PRIORITY.GOAL + 20,
577349
+ createdTurn: input.turn,
577350
+ ttlTurns: 1
577351
+ });
577352
+ const frame = builder.build(goalSignal ? [goalSignal, ...normalized.signals] : normalized.signals, {
577353
+ turn: input.turn,
577354
+ ...input.frameOptions
577355
+ });
577356
+ warnings.push(...frame.diagnostics.qualityWarnings);
577357
+ return {
577358
+ ...frame,
577359
+ compilerDiagnostics: {
577360
+ warnings: [...new Set(warnings)],
577361
+ admittedSignals: frame.included.length,
577362
+ rejectedSignals: normalized.rejected.length,
577363
+ hadConcreteGoal: goal.concrete
577364
+ }
577365
+ };
577366
+ }
577367
+ var RESTORE_NOISE_LINE_RE, RUNTIME_GUIDANCE_RE, ACTIVE_CONTEXT_RE;
577368
+ var init_context_compiler = __esm({
577369
+ "packages/orchestrator/dist/context-compiler.js"() {
577370
+ "use strict";
577371
+ init_context_fabric();
577372
+ 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;
577373
+ 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;
577374
+ ACTIVE_CONTEXT_RE = /\[ACTIVE CONTEXT FRAME\][\s\S]*?(?=\n\[ACTIVE CONTEXT FRAME\]|$)/g;
577375
+ }
577376
+ });
577377
+
577025
577378
  // packages/orchestrator/dist/evidenceLedger.js
577026
577379
  import { statSync as statSync38 } from "node:fs";
577027
577380
  function buildExtract(content) {
@@ -577245,6 +577598,7 @@ function recordContextWindowDump(input) {
577245
577598
  String(input.attempt ?? "")
577246
577599
  ].join("|");
577247
577600
  const id2 = `${timestamp.replace(/[:.]/g, "-")}-${input.agentType}-${shortHash3(stable)}`;
577601
+ const metrics2 = analyzeContextWindowDumpRequest(input.request);
577248
577602
  const record = {
577249
577603
  schemaVersion: 1,
577250
577604
  id: id2,
@@ -577260,7 +577614,8 @@ function recordContextWindowDump(input) {
577260
577614
  cwd: cwd4,
577261
577615
  ...input.note ? { note: input.note } : {},
577262
577616
  ...input.focusSupervisor ? { focusSupervisor: compactFocusSupervisor(input.focusSupervisor) } : {},
577263
- metrics: analyzeContextWindowDumpRequest(input.request),
577617
+ metrics: metrics2,
577618
+ apiView: summarizeApiView(input.request, metrics2),
577264
577619
  request: input.request
577265
577620
  };
577266
577621
  const dir = contextWindowDumpDir(cwd4);
@@ -577323,12 +577678,17 @@ function analyzeContextWindowDumpRequest(request) {
577323
577678
  let imageCount = 0;
577324
577679
  let activeEvidenceChars = 0;
577325
577680
  let activeContextFrameChars = 0;
577681
+ let activeContextFrameCount = 0;
577326
577682
  let compactedDiscoveryChars = 0;
577327
577683
  let rawDiscoveryToolChars = 0;
577328
577684
  let toolResultChars = 0;
577329
577685
  let systemChars = 0;
577330
577686
  let userChars = 0;
577687
+ let userMessageCount = 0;
577331
577688
  let assistantChars = 0;
577689
+ let runtimeControlChars = 0;
577690
+ let modelVisibleNoiseChars = 0;
577691
+ let hasConcreteUserGoal = false;
577332
577692
  const allMessageParts = [];
577333
577693
  for (const message2 of messages2) {
577334
577694
  const rec = message2 && typeof message2 === "object" ? message2 : {};
@@ -577343,8 +577703,10 @@ function analyzeContextWindowDumpRequest(request) {
577343
577703
  allMessageParts.push(extracted.textWithoutImages);
577344
577704
  if (role === "system")
577345
577705
  systemChars += chars;
577346
- if (role === "user")
577706
+ if (role === "user") {
577347
577707
  userChars += chars;
577708
+ userMessageCount++;
577709
+ }
577348
577710
  if (role === "assistant")
577349
577711
  assistantChars += chars;
577350
577712
  if (role === "tool") {
@@ -577357,6 +577719,17 @@ function analyzeContextWindowDumpRequest(request) {
577357
577719
  }
577358
577720
  if (extracted.textWithoutImages.includes("[ACTIVE CONTEXT FRAME]")) {
577359
577721
  activeContextFrameChars += chars;
577722
+ activeContextFrameCount += (extracted.textWithoutImages.match(/\[ACTIVE CONTEXT FRAME\]/g) ?? []).length;
577723
+ }
577724
+ if (/\[CURRENT USER GOAL\]/.test(extracted.textWithoutImages) && !/No concrete current user goal/i.test(extracted.textWithoutImages)) {
577725
+ hasConcreteUserGoal = true;
577726
+ }
577727
+ if (isRuntimeControlText(extracted.textWithoutImages)) {
577728
+ runtimeControlChars += chars;
577729
+ }
577730
+ modelVisibleNoiseChars += estimateModelVisibleNoiseChars(extracted.textWithoutImages);
577731
+ if (role === "user" && extracted.textWithoutImages.trim()) {
577732
+ hasConcreteUserGoal = true;
577360
577733
  }
577361
577734
  if (extracted.textWithoutImages.includes("[DISCOVERY COMPACTED") || extracted.textWithoutImages.includes("[DISCOVERY BOUNDED")) {
577362
577735
  compactedDiscoveryChars += chars;
@@ -577369,6 +577742,20 @@ function analyzeContextWindowDumpRequest(request) {
577369
577742
  const lineNoiseChars = lineNoise.noiseChars;
577370
577743
  const rawDiscoveryPenalty = rawDiscoveryToolChars * 0.5;
577371
577744
  const structuralNoiseCandidateChars = lineNoiseChars + rawDiscoveryPenalty;
577745
+ const controlToEvidenceRatio = Number((runtimeControlChars / Math.max(1, activeEvidenceChars + activeContextFrameChars + userChars)).toFixed(3));
577746
+ const userlessTaskTurn = userMessageCount === 0 && !hasConcreteUserGoal;
577747
+ const qualityWarnings = [];
577748
+ if (activeContextFrameCount > 1) {
577749
+ qualityWarnings.push(`active_context_frame_count:${activeContextFrameCount}`);
577750
+ }
577751
+ if (userlessTaskTurn)
577752
+ qualityWarnings.push("missing_user_message_or_goal");
577753
+ if (controlToEvidenceRatio > 0.45) {
577754
+ qualityWarnings.push(`control_context_ratio_high:${controlToEvidenceRatio}`);
577755
+ }
577756
+ if (modelVisibleNoiseChars > 0) {
577757
+ qualityWarnings.push(`model_visible_restore_noise:${modelVisibleNoiseChars}`);
577758
+ }
577372
577759
  const ratio = Number((structuralSignalChars / Math.max(1, structuralNoiseCandidateChars)).toFixed(3));
577373
577760
  const snrDb = ratio > 0 ? Number((10 * Math.log10(ratio)).toFixed(2)) : -Infinity;
577374
577761
  return {
@@ -577382,12 +577769,20 @@ function analyzeContextWindowDumpRequest(request) {
577382
577769
  roleChars,
577383
577770
  activeEvidenceChars,
577384
577771
  activeContextFrameChars,
577772
+ activeContextFrameCount,
577385
577773
  compactedDiscoveryChars,
577386
577774
  rawDiscoveryToolChars,
577387
577775
  toolResultChars,
577388
577776
  systemChars,
577389
577777
  userChars,
577778
+ userMessageCount,
577390
577779
  assistantChars,
577780
+ runtimeControlChars,
577781
+ controlToEvidenceRatio,
577782
+ hasConcreteUserGoal,
577783
+ userlessTaskTurn,
577784
+ modelVisibleNoiseChars,
577785
+ qualityWarnings,
577391
577786
  signalToNoise: {
577392
577787
  structuralSignalChars,
577393
577788
  structuralNoiseCandidateChars,
@@ -577397,6 +577792,53 @@ function analyzeContextWindowDumpRequest(request) {
577397
577792
  }
577398
577793
  };
577399
577794
  }
577795
+ function summarizeApiView(request, metrics2) {
577796
+ const messages2 = Array.isArray(request["messages"]) ? request["messages"] : [];
577797
+ const previews = [];
577798
+ let currentGoalPreview;
577799
+ for (let index = 0; index < messages2.length && previews.length < 16; index++) {
577800
+ const rec = messages2[index] && typeof messages2[index] === "object" ? messages2[index] : {};
577801
+ const role = typeof rec["role"] === "string" ? rec["role"] : "unknown";
577802
+ const text2 = textAndImagesFromContent(rec["content"]).textWithoutImages;
577803
+ const preview = text2.replace(/\s+/g, " ").trim().slice(0, 180);
577804
+ const goalMatch = text2.match(/\[CURRENT USER GOAL\][\s\S]{0,500}/);
577805
+ if (goalMatch && !currentGoalPreview) {
577806
+ currentGoalPreview = goalMatch[0].replace(/\s+/g, " ").trim().slice(0, 220);
577807
+ }
577808
+ previews.push({
577809
+ index,
577810
+ role,
577811
+ chars: text2.length,
577812
+ preview
577813
+ });
577814
+ }
577815
+ return {
577816
+ kind: "model-facing-api-view",
577817
+ exactRequestStored: true,
577818
+ messageCount: metrics2.messageCount,
577819
+ toolSchemaCount: metrics2.toolSchemaCount,
577820
+ roleCounts: metrics2.roleCounts,
577821
+ estimatedTokens: metrics2.estimatedTokens,
577822
+ activeContextFrameCount: metrics2.activeContextFrameCount,
577823
+ hasConcreteUserGoal: metrics2.hasConcreteUserGoal,
577824
+ userlessTaskTurn: metrics2.userlessTaskTurn,
577825
+ qualityWarnings: metrics2.qualityWarnings,
577826
+ ...currentGoalPreview ? { currentGoalPreview } : {},
577827
+ messagePreviews: previews
577828
+ };
577829
+ }
577830
+ function isRuntimeControlText(text2) {
577831
+ 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);
577832
+ }
577833
+ function estimateModelVisibleNoiseChars(text2) {
577834
+ let chars = 0;
577835
+ for (const line of text2.split("\n")) {
577836
+ 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)) {
577837
+ chars += line.length;
577838
+ }
577839
+ }
577840
+ return chars;
577841
+ }
577400
577842
  function textAndImagesFromContent(content) {
577401
577843
  if (typeof content === "string") {
577402
577844
  const matches = content.match(IMAGE_BASE64_RE);
@@ -581021,7 +581463,7 @@ function isDeprioritizedDiagnostic(diag) {
581021
581463
  function normalizeFile(file) {
581022
581464
  if (!file)
581023
581465
  return void 0;
581024
- const unix = file.trim().replace(/\\/g, "/");
581466
+ const unix = file.trim().replace(/\\/g, "/").replace(/^\d+:\s+(?=.*\.[a-z0-9]+(?::|$))/i, "");
581025
581467
  if (!unix)
581026
581468
  return void 0;
581027
581469
  const normalized = path7.posix.normalize(unix).replace(/^\.\//, "");
@@ -582625,6 +583067,12 @@ function isRunnerOwnedGitPath(path16) {
582625
583067
  const normalized = normalizeGitPath(path16);
582626
583068
  return RUNNER_OWNED_PREFIXES.some((prefix) => normalized.startsWith(prefix));
582627
583069
  }
583070
+ function isGeneratedArtifactGitPath(path16) {
583071
+ return GENERATED_ARTIFACT_PATH_RE.test(normalizeGitPath(path16));
583072
+ }
583073
+ function isTrackableProjectGitPath(path16) {
583074
+ return !isRunnerOwnedGitPath(path16) && !isGeneratedArtifactGitPath(path16);
583075
+ }
582628
583076
  function normalizeGitPath(path16) {
582629
583077
  return path16.replace(/\\/g, "/").replace(/^\.\//, "");
582630
583078
  }
@@ -582703,7 +583151,7 @@ function parseGitPorcelainStatusZ(raw) {
582703
583151
  i2++;
582704
583152
  }
582705
583153
  }
582706
- if (!isRunnerOwnedGitPath(entry.path))
583154
+ if (isTrackableProjectGitPath(entry.path))
582707
583155
  entries.push(entry);
582708
583156
  }
582709
583157
  return entries;
@@ -582763,7 +583211,7 @@ function buildChangedPaths(input) {
582763
583211
  }
582764
583212
  for (const path16 of input.mutatedPaths) {
582765
583213
  const rel = normalizeMutatedPath(input.repoRoot, path16);
582766
- if (rel && !isRunnerOwnedGitPath(rel))
583214
+ if (rel && isTrackableProjectGitPath(rel))
582767
583215
  changed.add(rel);
582768
583216
  }
582769
583217
  return {
@@ -582859,7 +583307,7 @@ async function refreshGitProgressState(state, input) {
582859
583307
  const currentStatus = parseGitPorcelainStatusZ(statusRaw);
582860
583308
  const currentDirtyPaths = pathsFromStatus(currentStatus);
582861
583309
  const currentUntrackedPaths = pathsFromStatus(currentStatus.filter((entry) => entry.untracked));
582862
- const mutatedPaths = normalizePathList((input.mutatedPaths ?? []).map((path16) => normalizeMutatedPath(repoRoot, path16)).filter((path16) => path16 && !isRunnerOwnedGitPath(path16)));
583310
+ const mutatedPaths = normalizePathList((input.mutatedPaths ?? []).map((path16) => normalizeMutatedPath(repoRoot, path16)).filter((path16) => path16 && isTrackableProjectGitPath(path16)));
582863
583311
  const delta = buildChangedPaths({
582864
583312
  repoRoot,
582865
583313
  baselineEntries: state.baselineStatus,
@@ -583011,12 +583459,13 @@ function summarizeGitProgressForTrajectory(state) {
583011
583459
  error: state.error
583012
583460
  };
583013
583461
  }
583014
- var RUNNER_OWNED_PREFIXES;
583462
+ var RUNNER_OWNED_PREFIXES, GENERATED_ARTIFACT_PATH_RE;
583015
583463
  var init_git_progress = __esm({
583016
583464
  "packages/orchestrator/dist/git-progress.js"() {
583017
583465
  "use strict";
583018
583466
  init_process_async2();
583019
583467
  RUNNER_OWNED_PREFIXES = [".omnius/"];
583468
+ GENERATED_ARTIFACT_PATH_RE = /(^|\/)(?:\.pio\/build|node_modules|\.pnpm-store|\.cache|coverage|\.next|\.nuxt|target\/debug|target\/release)(\/|$)/i;
583020
583469
  }
583021
583470
  });
583022
583471
 
@@ -585345,6 +585794,7 @@ var init_agenticRunner = __esm({
585345
585794
  init_failureHandoff();
585346
585795
  init_failure_taxonomy();
585347
585796
  init_context_fabric();
585797
+ init_context_compiler();
585348
585798
  init_evidenceLedger();
585349
585799
  init_adversaryStream();
585350
585800
  init_contextWindowDump();
@@ -586479,9 +586929,34 @@ var init_agenticRunner = __esm({
586479
586929
  parts.push(`Active: ${activeCards.length}`);
586480
586930
  }
586481
586931
  if (snapshot.cards.length > 0) {
586482
- const compact4 = compactWorkboardSnapshot(snapshot, 12);
586483
- parts.push(`
586484
- ${formatWorkboardCompact(snapshot, 12)}`);
586932
+ const statusCounts = snapshot.cards.reduce((acc, card) => {
586933
+ acc[card.status] = (acc[card.status] ?? 0) + 1;
586934
+ return acc;
586935
+ }, {});
586936
+ parts.push(`Card counts: ${Object.entries(statusCounts).sort(([a2], [b]) => a2.localeCompare(b)).map(([status, count]) => `${status}:${count}`).join(" ")}`);
586937
+ const action = this._deriveWorkboardActionContract(snapshot);
586938
+ const current = action ? snapshot.cards.find((card) => card.id === action.cardId) : activeCards[0] ?? null;
586939
+ if (current) {
586940
+ const currentLines = [
586941
+ `Current card: ${current.id} status=${current.status} lane=${current.lane}`,
586942
+ `title=${current.title.slice(0, 160)}`
586943
+ ];
586944
+ if (current.assignee)
586945
+ currentLines.push(`assignee=${current.assignee.slice(0, 120)}`);
586946
+ if (current.ownedFiles && current.ownedFiles.length > 0) {
586947
+ currentLines.push(`owned_files=${current.ownedFiles.slice(0, 6).join(",")}`);
586948
+ }
586949
+ if (current.verifierCommand) {
586950
+ currentLines.push(`verifier=${current.verifierCommand.slice(0, 180)}`);
586951
+ }
586952
+ if (current.diagnosticFingerprint) {
586953
+ currentLines.push(`diagnostic=${current.diagnosticFingerprint.slice(0, 160)}`);
586954
+ }
586955
+ if (current.evidenceRequirements.length > 0) {
586956
+ currentLines.push(`evidence_required=${current.evidenceRequirements.slice(0, 3).map((item) => item.slice(0, 100)).join(" | ")}`);
586957
+ }
586958
+ parts.push(currentLines.join("\n"));
586959
+ }
586485
586960
  }
586486
586961
  return parts.length > 0 ? `<workboard-status>
586487
586962
  ${parts.join("\n")}
@@ -587772,6 +588247,18 @@ Your hypotheses MUST address this specific error, not generic causes.
587772
588247
  * system prompt. Mutates `messages` in place.
587773
588248
  */
587774
588249
  gcSystemMessages(messages2) {
588250
+ for (let i2 = 1; i2 < messages2.length; i2++) {
588251
+ const msg = messages2[i2];
588252
+ if (msg?.role !== "system" || typeof msg.content !== "string")
588253
+ continue;
588254
+ const cleaned = sanitizeModelVisibleContextText(msg.content);
588255
+ if (cleaned) {
588256
+ msg.content = cleaned;
588257
+ } else {
588258
+ messages2.splice(i2, 1);
588259
+ i2--;
588260
+ }
588261
+ }
587775
588262
  const ctxTokens = this.effectiveContextWindow();
587776
588263
  const systemMaxChars = ctxTokens > 0 ? Math.max(24e3, Math.floor(ctxTokens * 4 * 0.45)) : 0;
587777
588264
  const beforeChars = messages2.reduce((sum2, m2) => sum2 + (m2.role === "system" && typeof m2.content === "string" ? m2.content.length : 0), 0);
@@ -587795,6 +588282,13 @@ Your hypotheses MUST address this specific error, not generic causes.
587795
588282
  });
587796
588283
  }
587797
588284
  }
588285
+ _prepareModelFacingMessages(messages2, _turn) {
588286
+ const prepared = prepareModelFacingApiMessages({
588287
+ messages: messages2,
588288
+ currentGoal: this._taskState.originalGoal || this._taskState.goal || this._taskState.currentStep || this._taskState.nextAction || ""
588289
+ });
588290
+ return sanitizeHistoryThink(prepared);
588291
+ }
587798
588292
  // ── Failing-approach detector (the "stop retrying variants" reflex) ───────
587799
588293
  // Encodes the behavior an effective agent uses and the dropbear 27× loop
587800
588294
  // lacked: when the SAME error recurs ~3× — especially while the same target
@@ -592359,9 +592853,11 @@ ${chunk.content}`, {
592359
592853
  async _buildTurnContextFrame(turn, messages2, recentToolResults, environmentBlock) {
592360
592854
  this._contextLedger.clearSources("turn.");
592361
592855
  this._contextLedger.prune(turn);
592856
+ const concreteGoal = this._taskState.originalGoal || this._taskState.goal || this._taskState.currentStep || this._taskState.nextAction || "";
592362
592857
  const goalBlock = [
592363
592858
  this._renderRuntimeRootBlock(),
592364
- this._taskState.goal ? `Active task: (see user message above — the goal block defers to the user message as the authoritative source)` : null
592859
+ concreteGoal ? `[CURRENT USER GOAL]
592860
+ ${String(concreteGoal).replace(/\s+/g, " ").trim().slice(0, 1200)}` : null
592365
592861
  ].filter(Boolean).join("\n\n");
592366
592862
  const workspaceTreeBlock = this._renderWorkspaceTreeBlock(turn);
592367
592863
  const filesystemBlock = this._renderFilesystemStateBlock(turn);
@@ -592400,6 +592896,8 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592400
592896
  signalFromBlock("goal", "run.goal", goalBlock, {
592401
592897
  id: "active-task",
592402
592898
  dedupeKey: "run.goal",
592899
+ semanticKey: "run.goal",
592900
+ conflictGroup: "context.runtime-root",
592403
592901
  priority: 100,
592404
592902
  createdTurn: turn
592405
592903
  }),
@@ -592427,6 +592925,8 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592427
592925
  signalFromBlock("action_contract", "turn.next-action-contract", actionContractBlock, {
592428
592926
  id: "next-action-contract",
592429
592927
  dedupeKey: "turn.next-action-contract",
592928
+ semanticKey: "context.next-action-contract",
592929
+ conflictGroup: "context.next-action",
592430
592930
  priority: PRIORITY.ACTION_CONTRACT,
592431
592931
  createdTurn: turn,
592432
592932
  ttlTurns: 1
@@ -592434,6 +592934,7 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592434
592934
  signalFromBlock("task_state", "turn.todos", todoBlock, {
592435
592935
  id: "todo-state",
592436
592936
  dedupeKey: "turn.todos",
592937
+ semanticKey: "context.todos",
592437
592938
  priority: 80,
592438
592939
  createdTurn: turn,
592439
592940
  ttlTurns: 1
@@ -592448,6 +592949,8 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592448
592949
  signalFromBlock("task_state", "turn.focus-supervisor", focusBlock, {
592449
592950
  id: "focus-supervisor",
592450
592951
  dedupeKey: "turn.focus-supervisor",
592952
+ semanticKey: "context.focus-supervisor",
592953
+ conflictGroup: "context.focus-supervisor",
592451
592954
  priority: 98,
592452
592955
  createdTurn: turn,
592453
592956
  ttlTurns: 1
@@ -592455,6 +592958,8 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592455
592958
  signalFromBlock("recent_failure", "turn.failures", failureBlock, {
592456
592959
  id: "recent-failures",
592457
592960
  dedupeKey: "turn.failures",
592961
+ semanticKey: "context.recent-failures",
592962
+ conflictGroup: "context.recent-failures",
592458
592963
  priority: 95,
592459
592964
  createdTurn: turn,
592460
592965
  ttlTurns: 1
@@ -592469,6 +592974,7 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592469
592974
  signalFromBlock("tool_cache", "turn.tool-cache", toolCacheBlock, {
592470
592975
  id: "tool-cache",
592471
592976
  dedupeKey: "turn.tool-cache",
592977
+ semanticKey: "context.tool-cache",
592472
592978
  priority: 92,
592473
592979
  createdTurn: turn,
592474
592980
  ttlTurns: 1
@@ -592507,15 +593013,49 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
592507
593013
  })
592508
593014
  ];
592509
593015
  this._contextLedger.upsertMany(signals.filter(Boolean));
592510
- const frame = this._contextFrameBuilder.build(this._contextLedger.values(), {
592511
- turn,
593016
+ const invalidatedSignals = this._contextLedger.consumeInvalidatedCount();
593017
+ const frameBuildOptions = {
592512
593018
  // Raised from 10k to fit the durable read-evidence content (known_files)
592513
593019
  // that replaces the re-read loop; the per-kind budget below caps it.
592514
593020
  maxChars: 13e3,
592515
- kindCharBudget: { known_files: 8500 },
593021
+ kindCharBudget: {
593022
+ known_files: 8500,
593023
+ runtime_guidance: 900,
593024
+ recent_failure: 1400,
593025
+ action_contract: 1400
593026
+ },
593027
+ invalidatedSignals,
593028
+ maxControlToEvidenceRatio: 0.45,
592516
593029
  includeDiagnostics: process.env["OMNIUS_CONTEXT_FABRIC_DIAGNOSTICS"] === "1"
592517
- });
593030
+ };
593031
+ const compilerEnabled = process.env["OMNIUS_CONTEXT_COMPILER_V2"] !== "0";
593032
+ const frame = compilerEnabled ? compileContextFrameV2({
593033
+ turn,
593034
+ currentGoal: concreteGoal,
593035
+ signals: this._contextLedger.values(),
593036
+ builder: this._contextFrameBuilder,
593037
+ frameOptions: frameBuildOptions
593038
+ }) : {
593039
+ ...this._contextFrameBuilder.build(this._contextLedger.values(), {
593040
+ turn,
593041
+ ...frameBuildOptions
593042
+ }),
593043
+ compilerDiagnostics: {
593044
+ warnings: [],
593045
+ admittedSignals: 0,
593046
+ rejectedSignals: 0,
593047
+ hadConcreteGoal: Boolean(concreteGoal)
593048
+ }
593049
+ };
592518
593050
  this._lastContextFrameDiagnostics = frame.diagnostics;
593051
+ if (frame.compilerDiagnostics.warnings.length > 0 && process.env["OMNIUS_CONTEXT_COMPILER_STATUS"] === "1") {
593052
+ this.emit({
593053
+ type: "status",
593054
+ content: `Context compiler warnings: ${frame.compilerDiagnostics.warnings.join(", ")}`,
593055
+ turn,
593056
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
593057
+ });
593058
+ }
592519
593059
  semantic.snapshot.frameTokens = frame.diagnostics.estimatedTokens;
592520
593060
  semantic.snapshot.droppedSignals = frame.diagnostics.droppedSignals;
592521
593061
  semantic.snapshot.truncatedSignals = frame.diagnostics.truncatedSignals;
@@ -596479,7 +597019,7 @@ ${memoryLines.join("\n")}`
596479
597019
  }
596480
597020
  const { maxOutputTokens: effectiveMaxTokens } = this.contextLimits();
596481
597021
  this.gcSystemMessages(requestMessages);
596482
- requestMessages = sanitizeHistoryThink(requestMessages);
597022
+ requestMessages = this._prepareModelFacingMessages(requestMessages, turn);
596483
597023
  const chatRequest = {
596484
597024
  messages: requestMessages,
596485
597025
  tools: toolDefs,
@@ -596663,10 +597203,10 @@ ${memoryLines.join("\n")}`
596663
597203
  'When done, output: {"tool": "task_complete", "args": {"summary": "what you did"}}'
596664
597204
  ].join("\n");
596665
597205
  messages2.push({ role: "system", content: toolInjectMsg });
596666
- chatRequest.messages = [
597206
+ chatRequest.messages = this._prepareModelFacingMessages([
596667
597207
  ...requestMessages,
596668
597208
  { role: "system", content: toolInjectMsg }
596669
- ];
597209
+ ], turn);
596670
597210
  chatRequest.tools = [];
596671
597211
  try {
596672
597212
  this._recordContextWindowDump("agent_turn_prompt_tool_retry", chatRequest, turn, 1);
@@ -600668,7 +601208,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
600668
601208
  }
600669
601209
  this._insertContextFrame(compactedMsgs, await this._buildTurnContextFrame(turn, compactedMsgs, void 0, bfEnvironmentBlock));
600670
601210
  this.gcSystemMessages(compactedMsgs);
600671
- const modelFacingMessages = sanitizeHistoryThink(compactedMsgs);
601211
+ const modelFacingMessages = this._prepareModelFacingMessages(compactedMsgs, turn);
600672
601212
  const chatRequest = {
600673
601213
  messages: modelFacingMessages,
600674
601214
  tools: toolDefs,
@@ -603716,12 +604256,15 @@ ${tail}`;
603716
604256
  appendRuntimeGuidance(guidance, turn) {
603717
604257
  const packet = this.formatRuntimeGuidance(guidance);
603718
604258
  const guidanceHash = _createHash("sha256").update(packet).digest("hex").slice(0, 16);
604259
+ const semanticKey = this.runtimeGuidanceSemanticKey(guidance);
603719
604260
  const signal = signalFromBlock("runtime_guidance", "runtime.guidance", packet, {
603720
604261
  id: `runtime-guidance-${turn}-${guidanceHash}`,
603721
604262
  dedupeKey: `runtime.guidance:${guidanceHash}`,
604263
+ semanticKey,
604264
+ conflictGroup: "context.runtime-guidance",
603722
604265
  priority: 94,
603723
604266
  createdTurn: turn,
603724
- ttlTurns: 8
604267
+ ttlTurns: 3
603725
604268
  });
603726
604269
  if (signal)
603727
604270
  this._contextLedger.upsert(signal);
@@ -603737,20 +604280,31 @@ ${tail}`;
603737
604280
  return guidance;
603738
604281
  }
603739
604282
  return [
603740
- "[RUNTIME_GUIDANCE_INTAKE v1]",
603741
- "Source: Omnius runtime control/advisory signal, not an external user message.",
603742
- "",
603743
- "<<<RUNTIME_GUIDANCE>>>",
603744
- guidance,
603745
- "<<<END_RUNTIME_GUIDANCE>>>",
603746
- "",
603747
- "Contract:",
603748
- "- Treat this as diagnostic/control-plane guidance for the next action.",
603749
- "- Reconcile it with the user goal and fresh tool evidence.",
603750
- "- Do not quote or summarize this wrapper to the user.",
603751
- "[/RUNTIME_GUIDANCE_INTAKE]"
604283
+ "[RUNTIME DIRECTIVE]",
604284
+ "source=omnius_runtime",
604285
+ guidance
603752
604286
  ].join("\n");
603753
604287
  }
604288
+ runtimeGuidanceSemanticKey(guidance) {
604289
+ const normalized = guidance.replace(/\s+/g, " ").trim().toLowerCase();
604290
+ if (/compile|verifier|verification|build|fix loop/.test(normalized)) {
604291
+ return "runtime.guidance.verification";
604292
+ }
604293
+ if (/action_reason|tool action reason|schema|argument/.test(normalized)) {
604294
+ return "runtime.guidance.tool-args";
604295
+ }
604296
+ if (/doom-loop|loop|repeat|identical|stuck|stale|cached/.test(normalized)) {
604297
+ return "runtime.guidance.loop-control";
604298
+ }
604299
+ if (/todo|workboard|card|task state/.test(normalized)) {
604300
+ return "runtime.guidance.task-state";
604301
+ }
604302
+ if (/scope|owned file|forbidden|mutation/.test(normalized)) {
604303
+ return "runtime.guidance.mutation-scope";
604304
+ }
604305
+ const digest3 = _createHash("sha256").update(normalized.slice(0, 400)).digest("hex").slice(0, 10);
604306
+ return `runtime.guidance.${digest3}`;
604307
+ }
603754
604308
  formatInjectedUserMessage(userMsg) {
603755
604309
  if (userMsg.trim().startsWith("[MID_TASK_STEERING_INTAKE")) {
603756
604310
  return userMsg;
@@ -629895,7 +630449,12 @@ ${c3.magenta("●")} ${c3.italic(text2)}
629895
630449
  `);
629896
630450
  }
629897
630451
  function renderVoiceText(text2) {
629898
- process.stdout.write(` ${c3.dim("🔊")} ${c3.italic(c3.dim(text2))}
630452
+ if (process.env["OMNIUS_SHOW_SPOKEN_TEXT"] !== "1" && process.env["OMNIUS_RENDER_VOICE_TEXT"] !== "1") {
630453
+ return;
630454
+ }
630455
+ const clean5 = text2.replace(/\s+/g, " ").trim();
630456
+ if (!clean5) return;
630457
+ process.stdout.write(` ${c3.dim("voice")} ${c3.italic(c3.dim(clean5))}
629899
630458
  `);
629900
630459
  }
629901
630460
  function renderUserInterrupt(text2) {
@@ -637687,6 +638246,7 @@ __export(omnius_directory_exports, {
637687
638246
  recordUsage: () => recordUsage,
637688
638247
  renderSessionDiary: () => renderSessionDiary,
637689
638248
  resolveSettings: () => resolveSettings,
638249
+ sanitizeRestorePromptForModel: () => sanitizeRestorePromptForModel,
637690
638250
  sanitizeRestoredSessionLines: () => sanitizeRestoredSessionLines,
637691
638251
  saveGlobalSettings: () => saveGlobalSettings,
637692
638252
  savePendingTask: () => savePendingTask,
@@ -638242,9 +638802,16 @@ function releaseLock(lockPath) {
638242
638802
  } catch {
638243
638803
  }
638244
638804
  }
638805
+ function stripModelContextNoise(raw) {
638806
+ if (!raw) return "";
638807
+ 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();
638808
+ }
638809
+ function sanitizeRestorePromptForModel(raw) {
638810
+ return stripModelContextNoise(raw);
638811
+ }
638245
638812
  function normalizeSessionText(raw, maxLen = 500) {
638246
638813
  if (!raw) return "";
638247
- return String(raw).replace(/\s+/g, " ").trim().slice(0, maxLen);
638814
+ return stripModelContextNoise(raw).replace(/\s+/g, " ").trim().slice(0, maxLen);
638248
638815
  }
638249
638816
  function normalizeList(items, maxItems) {
638250
638817
  if (!items || items.length === 0) return void 0;
@@ -638442,7 +639009,7 @@ function saveSessionContext(repoRoot, entry) {
638442
639009
  }
638443
639010
  function cleanPromptForDiary(raw) {
638444
639011
  if (!raw) return "";
638445
- let text2 = String(raw);
639012
+ let text2 = stripModelContextNoise(raw);
638446
639013
  text2 = text2.replace(/^\[Previous sessions exist[^\]]*\]\s*\n*/m, "");
638447
639014
  text2 = text2.replace(/^[\s\S]*?\n---\s*\n\s*NEW TASK:\s*/m, "");
638448
639015
  text2 = text2.replace(/^NEW TASK:\s*/m, "");
@@ -638751,8 +639318,7 @@ function buildRestoreHistoryAnchor(repoRoot) {
638751
639318
  const [latest] = listSessions(repoRoot);
638752
639319
  if (!latest?.id) return null;
638753
639320
  const lines = loadSessionHistory(repoRoot, latest.id) ?? [];
638754
- const restoredLines = sanitizeRestoredSessionLines(lines);
638755
- const meaningfulTail = restoredLines.map((line) => cleanSessionHistoryDisplayLine(line)).filter((line) => line && !isNoisySessionHistoryLine(line)).slice(-18).map((line) => `- ${normalizeSessionText(line, 220)}`);
639321
+ const recordedLineCount = lines.filter((line) => String(line ?? "").trim()).length;
638756
639322
  const path16 = join136(OMNIUS_DIR, SESSIONS_DIR, `${latest.id}.jsonl`);
638757
639323
  const statePath = join136(OMNIUS_DIR, SESSIONS_DIR, `${latest.id}${TUI_STATE_SUFFIX}`);
638758
639324
  const hasTuiState = existsSync125(join136(repoRoot, statePath));
@@ -638760,12 +639326,10 @@ function buildRestoreHistoryAnchor(repoRoot) {
638760
639326
  latest_visual_session_id=${latest.id}
638761
639327
  ` + (hasTuiState ? `full_tui_state_path=${statePath}
638762
639328
  ` : "") + `full_transcript_path=${path16}
638763
- recorded_lines=${restoredLines.length}
638764
- ` + (meaningfulTail.length > 0 ? `Recent visible transcript tail:
638765
- ${meaningfulTail.join("\n")}
638766
- ` : "") + `Recall contract: the full transcript artifact above is restored into the TUI scrollback and is the authoritative previous interface state. Read it only when exact prior UI/tool output is needed; otherwise use this restored state to avoid rediscovery.
639329
+ available_transcript_lines=${recordedLineCount}
639330
+ Recall contract: do not replay or ingest the transcript wholesale. Use the structured session recap and todo state first. Read the transcript artifact only when exact prior UI/tool output is needed.
638767
639331
  </restored-interface-history>`;
638768
- return { sessionId: latest.id, path: path16, lineCount: restoredLines.length, block };
639332
+ return { sessionId: latest.id, path: path16, lineCount: recordedLineCount, block };
638769
639333
  }
638770
639334
  function appendRestoreBlocks(base3, blocks) {
638771
639335
  return [base3, ...blocks].filter((part) => part && part.trim()).join("\n\n");
@@ -638805,6 +639369,7 @@ function buildContextRestoreSnapshot(repoRoot) {
638805
639369
  const restoredTodos = findRestoredTodoState(restoreSessionIds);
638806
639370
  const sourceSessionId = restoredTodos?.sessionId ?? restoreSessionIds[0];
638807
639371
  if (handoffPrompt) {
639372
+ const safeHandoffPrompt = stripModelContextNoise(handoffPrompt);
638808
639373
  const usefulEntries2 = (ctx3?.entries ?? []).filter((entry) => !isManualSessionEntry(entry));
638809
639374
  const baseCtx = ctx3 && ctx3.entries.length > 0 ? `
638810
639375
 
@@ -638814,7 +639379,7 @@ Recent tasks: ${(usefulEntries2.length > 0 ? usefulEntries2 : ctx3.entries).slic
638814
639379
  ).join(", ")}
638815
639380
  </session-recap>` : "";
638816
639381
  const prompt2 = appendRestoreBlocks(
638817
- handoffPrompt + (activeTaskAnchor ? `
639382
+ safeHandoffPrompt + (activeTaskAnchor ? `
638818
639383
 
638819
639384
  ${activeTaskAnchor}` : "") + baseCtx,
638820
639385
  [restoredTodos?.block, historyAnchor?.block]
@@ -638854,12 +639419,12 @@ ${activeTaskAnchor}` : "") + baseCtx,
638854
639419
  const last2 = recent[recent.length - 1] ?? ctx3.entries[ctx3.entries.length - 1];
638855
639420
  const lastCompleted = [...usefulEntries].reverse().find((entry) => entry.completed);
638856
639421
  const latestCompleted = lastCompleted ? `Latest completed task: ${normalizeSessionText(lastCompleted.assistantResponse || lastCompleted.summary || lastCompleted.task, 180)}` : "";
638857
- const recentDialogue = recent.slice(-8).map((entry) => {
638858
- const assistant = normalizeSessionText(entry.assistantResponse || entry.summary, 320) || "(no assistant reply captured)";
639422
+ const recentTaskState = recent.slice(-8).map((entry) => {
638859
639423
  const user = cleanPromptForDiary(entry.task).slice(0, 220);
638860
- return `User: ${user}
638861
- Assistant: ${assistant}`;
638862
- }).join("\n\n");
639424
+ const outcome = normalizeSessionText(entry.assistantResponse || entry.summary, 240);
639425
+ const status = entry.completed ? "done" : "partial";
639426
+ return `- [${status}] user_intent="${user}"${outcome ? ` outcome="${outcome}"` : ""}`;
639427
+ }).join("\n");
638863
639428
  const prov = last2.provenance ? `
638864
639429
  Provenance: ${last2.provenance} (file_read to expand)` : "";
638865
639430
  const kg = `
@@ -638874,8 +639439,8 @@ ${chronology.join("\n")}
638874
639439
  ` + (latestCompleted ? `
638875
639440
  ${latestCompleted}
638876
639441
  ` : "\n") + `
638877
- Most recent exchanges (older to newer):
638878
- ${recentDialogue}
639442
+ Recent structured task state (older to newer; transcript omitted from model context):
639443
+ ${recentTaskState}
638879
639444
  ` + (activeTaskAnchor ? `For continuation prompts, resume the active task anchor above; use chronology only to avoid repeating completed work.${prov}${kg}
638880
639445
  ` : `Continue from the latest exchange and do not repeat completed work.${prov}${kg}
638881
639446
  `) + `</session-recap>`,
@@ -638917,14 +639482,20 @@ function updateSessionEntry(repoRoot, sessionId, patch) {
638917
639482
  }
638918
639483
  }
638919
639484
  function cleanSessionHistoryDisplayLine(line) {
638920
- return String(line || "").replace(/\x1B\[[0-9;]*[a-zA-Z]/g, "").replace(/^[>❯▹·∙•*+\-\s]+/, "").replace(/^\[.*?\]\s*/, "").replace(/^(?:User|Assistant|You|Open Agent|Omnius)\s*:\s*/i, "").replace(/\s+/g, " ").trim();
639485
+ return String(line || "").replace(/\x1B\[[0-9;]*[a-zA-Z]/g, "").replace(/^\s*(?:[>❯▹·∙•*+\-]\s*)+/, "").replace(/^\[.*?\]\s*/, "").replace(/^(?:User|Assistant|You|Open Agent|Omnius)\s*:\s*/i, "").replace(/\s+/g, " ").trim();
638921
639486
  }
638922
- function isNoisySessionHistoryLine(line) {
638923
- const clean5 = cleanSessionHistoryDisplayLine(line || "");
638924
- if (!clean5) return true;
638925
- const withoutEventPrefix = clean5.replace(/^(?:E|W|⚠)\s+/, "");
638926
- const noise2 = /^(?:Previous session found|REST API:|Nexus P2P network connected|No context to restore|Starting fresh|Use \/endpoint|Knowledge graph:|Zettelkasten:|Episodes captured:|Current OMNIUS_HOST:|Loaded TUI session|General session$|Chat tui:sess|TUI session\b|Using (?:expanded )?context model|Using model|Context (?:auto-)?restored|Context restored|Recovered session|Last task:|Voice feedback enabled\b|Clone ref:|clone-[^\s]+\.wav$|Memory maintenance:|reclaimed\b.*\.?$|Task timeout reached during backend retry|Incomplete: task timed out\b|Task incomplete\b|Tokens:\s*[\d,~]+|\(manual save\)|continue$|\[VRAM|VRAM |model_info|KV |arch[ -]capped|i\s+(?:starting|loaded|using|context|rest|nexus|previous)\b|\bSHELL TRANSCRIPT\b|Invoking todo write|decompositionContract|Todos have been modified successfully|continuing with python|🔊|SHELL)$/i;
638927
- return noise2.test(clean5) || noise2.test(withoutEventPrefix);
639487
+ function normalizeStoredSessionLine(line) {
639488
+ return String(line ?? "").replace(/\x1B\[[0-9;]*[a-zA-Z]/g, "").replace(/\s+$/g, "");
639489
+ }
639490
+ function isAuthoredSessionLine(line) {
639491
+ return AUTHORED_SESSION_LINE.test(line.trimStart());
639492
+ }
639493
+ function isAuthoredSessionContinuation(line, previousWasAuthored) {
639494
+ if (!previousWasAuthored) return false;
639495
+ if (!/^\s{2,}\S/.test(line)) return false;
639496
+ const trimmed = line.trimStart();
639497
+ if (!trimmed || trimmed.startsWith("🔊")) return false;
639498
+ return !VISUAL_CHROME_LINE.test(trimmed);
638928
639499
  }
638929
639500
  function sanitizeRestoredSessionLines(lines, options2 = {}) {
638930
639501
  const maxLines = Math.max(
@@ -638933,16 +639504,24 @@ function sanitizeRestoredSessionLines(lines, options2 = {}) {
638933
639504
  );
638934
639505
  const out = [];
638935
639506
  let previousBlank = false;
639507
+ let previousWasAuthored = false;
638936
639508
  for (const raw of lines) {
638937
- const line = String(raw ?? "").replace(/\x1B\[[0-9;]*[a-zA-Z]/g, "").replace(/\s+$/g, "");
638938
- if (isNoisySessionHistoryLine(line)) continue;
639509
+ const line = normalizeStoredSessionLine(String(raw ?? ""));
638939
639510
  if (!line.trim()) {
639511
+ previousWasAuthored = false;
638940
639512
  if (previousBlank) continue;
638941
639513
  previousBlank = true;
638942
639514
  out.push("");
638943
639515
  continue;
638944
639516
  }
639517
+ const keep = isAuthoredSessionLine(line) || isAuthoredSessionContinuation(line, previousWasAuthored);
639518
+ if (!keep) {
639519
+ previousWasAuthored = false;
639520
+ previousBlank = false;
639521
+ continue;
639522
+ }
638945
639523
  previousBlank = false;
639524
+ previousWasAuthored = true;
638946
639525
  out.push(line);
638947
639526
  }
638948
639527
  while (out[0] === "") out.shift();
@@ -638950,20 +639529,22 @@ function sanitizeRestoredSessionLines(lines, options2 = {}) {
638950
639529
  return out.slice(-maxLines);
638951
639530
  }
638952
639531
  function firstMeaningfulSessionHistoryLine(lines) {
638953
- for (const line of lines) {
639532
+ for (const line of sanitizeRestoredSessionLines(lines, { maxLines: 12 })) {
638954
639533
  const clean5 = cleanSessionHistoryDisplayLine(line);
638955
- if (!isNoisySessionHistoryLine(clean5)) return clean5;
639534
+ if (clean5) return clean5;
638956
639535
  }
638957
639536
  return "";
638958
639537
  }
638959
639538
  function sanitizeSessionHistoryEntry(repoRoot, entry) {
638960
- if (!isNoisySessionHistoryLine(entry.name) && !isNoisySessionHistoryLine(entry.description)) return entry;
639539
+ const nameLooksAuthored = isAuthoredSessionLine(entry.name) || cleanSessionHistoryDisplayLine(entry.name).length > 0;
639540
+ const descriptionLooksAuthored = isAuthoredSessionLine(entry.description) || cleanSessionHistoryDisplayLine(entry.description).length > 0;
639541
+ if (nameLooksAuthored && descriptionLooksAuthored) return entry;
638961
639542
  const lines = loadSessionHistory(repoRoot, entry.id) || [];
638962
639543
  const fallback = firstMeaningfulSessionHistoryLine(lines);
638963
639544
  return {
638964
639545
  ...entry,
638965
- name: isNoisySessionHistoryLine(entry.name) ? fallback ? fallback.length > 40 ? fallback.slice(0, 37) + "..." : fallback : entry.name : entry.name,
638966
- description: isNoisySessionHistoryLine(entry.description) ? fallback || entry.description : entry.description
639546
+ name: !nameLooksAuthored ? fallback ? fallback.length > 40 ? fallback.slice(0, 37) + "..." : fallback : entry.name : entry.name,
639547
+ description: !descriptionLooksAuthored ? fallback || entry.description : entry.description
638967
639548
  };
638968
639549
  }
638969
639550
  function saveSessionHistory(repoRoot, sessionId, contentLines, meta) {
@@ -639270,7 +639851,7 @@ function deleteUsageRecord(kind, value2, repoRoot) {
639270
639851
  remove(join136(repoRoot, OMNIUS_DIR, USAGE_HISTORY_FILE));
639271
639852
  }
639272
639853
  }
639273
- 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, SKIP_DIRS3, HOME_SKIP_DIRS, USAGE_HISTORY_FILE, MAX_HISTORY_RECORDS;
639854
+ 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;
639274
639855
  var init_omnius_directory = __esm({
639275
639856
  "packages/cli/src/tui/omnius-directory.ts"() {
639276
639857
  init_dist5();
@@ -639303,6 +639884,7 @@ var init_omnius_directory = __esm({
639303
639884
  LOCK_TIMEOUT_MS = 5e3;
639304
639885
  LOCK_RETRY_MS = 50;
639305
639886
  LOCK_RETRY_MAX = 100;
639887
+ 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;
639306
639888
  DEFAULT_RESTORED_SESSION_HISTORY_MAX_LINES = 600;
639307
639889
  DEICTIC_CONTINUATION_TERMS = /* @__PURE__ */ new Set([
639308
639890
  "again",
@@ -639335,6 +639917,8 @@ var init_omnius_directory = __esm({
639335
639917
  SESSIONS_DIR = "sessions";
639336
639918
  SESSIONS_INDEX = "sessions-index.json";
639337
639919
  TUI_STATE_SUFFIX = ".tui-state.json";
639920
+ AUTHORED_SESSION_LINE = /^(?:User|Assistant|You|Open Agent|Omnius)\s*:/i;
639921
+ VISUAL_CHROME_LINE = /^[╭╮╰╯│├┤┬┴┌┐└┘─━═\[\]▌▐█▒░●○◐◖▶!·∙•*+\-]|^(?:E|W|⚠)\s/;
639338
639922
  SKIP_DIRS3 = /* @__PURE__ */ new Set([
639339
639923
  "node_modules",
639340
639924
  ".git",
@@ -641780,13 +642364,18 @@ function loadSessionHistory2(repoRoot) {
641780
642364
  const exchanges = sessionCtx?.entries.slice(-2) ?? [];
641781
642365
  if (exchanges.length > 0) {
641782
642366
  if (lines.length > 1) lines.push("");
641783
- lines.push("Most recent user/assistant chronology:");
642367
+ lines.push("Recent structured task outcomes:");
641784
642368
  for (const entry of exchanges) {
641785
642369
  const user = cleanForStorage(entry.task) || entry.task;
641786
642370
  const assistant = cleanForStorage(entry.assistantResponse || entry.summary) || entry.assistantResponse || entry.summary;
641787
642371
  if (!assistant) continue;
641788
- lines.push(`- User: ${truncateProjectContextText(user, 120, "")}`);
641789
- lines.push(` Assistant: ${truncateProjectContextText(assistant, 160, "")}`);
642372
+ const status = entry.completed ? "done" : "partial";
642373
+ lines.push(
642374
+ `- [${status}] intent=${truncateProjectContextText(user, 120, "")}`
642375
+ );
642376
+ lines.push(
642377
+ ` outcome=${truncateProjectContextText(assistant, 160, "")}`
642378
+ );
641790
642379
  }
641791
642380
  }
641792
642381
  return lines.length > 1 ? lines.join("\n") : "";
@@ -671298,9 +671887,9 @@ sleep 1
671298
671887
  const snapshot = typeof prompt === "string" ? null : prompt;
671299
671888
  ctx3.setRestoredContext?.(prompt);
671300
671889
  renderInfo(
671301
- `Context restored from ${info?.entries ?? 0} saved session(s)${snapshot?.historyLineCount ? `; replayed ${snapshot.historyLineCount} transcript line(s)` : ""}${snapshot?.todoCount ? `; restored ${snapshot.todoCount} todo(s)` : ""}. Will be injected into your next task.`
671890
+ `Context restored from ${info?.entries ?? 0} saved session(s)${snapshot?.historyLineCount ? `; transcript artifact available (${snapshot.historyLineCount} line(s))` : ""}${snapshot?.todoCount ? `; restored ${snapshot.todoCount} todo(s)` : ""}. Will be injected into your next task.`
671302
671891
  );
671303
- if (!snapshot?.historyLineCount) renderContextHistory(ctx3, "Session History");
671892
+ renderContextHistory(ctx3, "Session History");
671304
671893
  } else {
671305
671894
  renderWarning(
671306
671895
  "No saved session context found. Complete a task first, or use /context save."
@@ -701197,7 +701786,7 @@ ${mediaContext}` : ""
701197
701786
  telegramMemoryIngestPayload(msg, media, localPath, source, extractedContent) {
701198
701787
  const isReplyMedia = source === "reply";
701199
701788
  const messageId = isReplyMedia ? msg.replyToMessageId : msg.messageId;
701200
- const messageText = isReplyMedia ? msg.replyContext?.text || msg.replyContext?.caption || msg.replyToText || media.caption : msg.text || media.caption;
701789
+ const messageText2 = isReplyMedia ? msg.replyContext?.text || msg.replyContext?.caption || msg.replyToText || media.caption : msg.text || media.caption;
701201
701790
  const sender = isReplyMedia ? this.telegramMemorySenderFromReply(msg) : this.telegramMemorySenderFromMessage(msg);
701202
701791
  const modality = media.type === "audio" || media.type === "voice" ? "audio" : telegramMediaIsImage(media) ? "visual" : "text";
701203
701792
  const objectLabels = extractExplicitVisualObjectLabels({
@@ -701217,7 +701806,7 @@ ${mediaContext}` : ""
701217
701806
  id: messageId,
701218
701807
  threadId: msg.messageThreadId,
701219
701808
  timestamp: Date.now(),
701220
- text: messageText
701809
+ text: messageText2
701221
701810
  },
701222
701811
  replyTo: !isReplyMedia ? this.telegramMemoryReplyRef(msg) : void 0,
701223
701812
  modality,
@@ -752209,13 +752798,15 @@ ${result.summary}`
752209
752798
  const taskSummary = hasTaskToResume ? getLastTaskSummary2(repoRoot) : null;
752210
752799
  const resumeMsg = taskSummary ? `v${version5} — picking up: ${taskSummary}` : `Updated to v${version5}.`;
752211
752800
  const restoreSnapshot = buildContextRestoreSnapshot(repoRoot);
752212
- const replayedVisual = restoreSnapshot ? applyRestoreSnapshot(restoreSnapshot, { replayVisual: true }) : false;
752801
+ if (restoreSnapshot) {
752802
+ applyRestoreSnapshot(restoreSnapshot, { replayVisual: false });
752803
+ }
752213
752804
  writeContent(() => {
752214
752805
  renderInfo(resumeMsg);
752215
752806
  if (restoreSnapshot) {
752216
752807
  const info = loadSessionContext(repoRoot);
752217
752808
  renderInfo(
752218
- `Context restored from ${info?.entries.length ?? 0} session(s)${replayedVisual ? `; replayed ${restoreSnapshot.historyLineCount ?? 0} transcript line(s).` : "."}`
752809
+ `Context restored from ${info?.entries.length ?? 0} session(s); transcript artifact available (${restoreSnapshot.historyLineCount ?? 0} line(s)).`
752219
752810
  );
752220
752811
  }
752221
752812
  });
@@ -756307,9 +756898,9 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
756307
756898
  },
756308
756899
  setRestoredContext(ctx3) {
756309
756900
  if (typeof ctx3 === "string") {
756310
- restoredSessionContext = ctx3;
756901
+ restoredSessionContext = sanitizeRestorePromptForModel(ctx3);
756311
756902
  } else {
756312
- applyRestoreSnapshot(ctx3, { replayVisual: true });
756903
+ applyRestoreSnapshot(ctx3, { replayVisual: false });
756313
756904
  }
756314
756905
  },
756315
756906
  contextShow() {
@@ -756455,30 +757046,26 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
756455
757046
  if (doRestore) {
756456
757047
  const snapshot = buildContextRestoreSnapshot(repoRoot);
756457
757048
  if (snapshot) {
756458
- const replayedVisual = applyRestoreSnapshot(snapshot, {
756459
- replayVisual: true
756460
- });
757049
+ applyRestoreSnapshot(snapshot, { replayVisual: false });
756461
757050
  const info = loadSessionContext(repoRoot);
756462
757051
  writeContent(() => {
756463
757052
  renderInfo(
756464
- auto ? `Context auto-restored from ${info?.entries.length ?? 0} session(s)${replayedVisual ? `; replayed ${snapshot.historyLineCount ?? 0} transcript line(s)` : ""}${snapshot.todoCount ? `; restored ${snapshot.todoCount} todo(s)` : ""}.` : `Context restored from ${info?.entries.length ?? 0} session(s)${replayedVisual ? `; replayed ${snapshot.historyLineCount ?? 0} transcript line(s)` : ""}${snapshot.todoCount ? `; restored ${snapshot.todoCount} todo(s)` : ""}.`
757053
+ auto ? `Context auto-restored from ${info?.entries.length ?? 0} session(s); transcript artifact available (${snapshot.historyLineCount ?? 0} line(s))${snapshot.todoCount ? `; restored ${snapshot.todoCount} todo(s)` : ""}.` : `Context restored from ${info?.entries.length ?? 0} session(s); transcript artifact available (${snapshot.historyLineCount ?? 0} line(s))${snapshot.todoCount ? `; restored ${snapshot.todoCount} todo(s)` : ""}.`
756465
757054
  );
756466
- if (!replayedVisual) {
756467
- if (statusBar.isActive && !isNeovimActive() && !isOverlayActive()) {
756468
- renderSessionHistoryBox(
756469
- {
756470
- registerDynamicBlock: (id2, render2) => statusBar.registerDynamicBlock(id2, render2),
756471
- appendDynamicBlock: (id2) => statusBar.appendDynamicBlock(id2)
756472
- },
756473
- sessionContextToHistoryBoxData(info, "Session History")
756474
- );
756475
- } else {
756476
- const historyDisplay = formatSessionHistoryDisplay(info);
756477
- process.stdout.write(
756478
- historyDisplay.endsWith("\n") ? historyDisplay : `${historyDisplay}
757055
+ if (statusBar.isActive && !isNeovimActive() && !isOverlayActive()) {
757056
+ renderSessionHistoryBox(
757057
+ {
757058
+ registerDynamicBlock: (id2, render2) => statusBar.registerDynamicBlock(id2, render2),
757059
+ appendDynamicBlock: (id2) => statusBar.appendDynamicBlock(id2)
757060
+ },
757061
+ sessionContextToHistoryBoxData(info, "Session History")
757062
+ );
757063
+ } else {
757064
+ const historyDisplay = formatSessionHistoryDisplay(info);
757065
+ process.stdout.write(
757066
+ historyDisplay.endsWith("\n") ? historyDisplay : `${historyDisplay}
756479
757067
  `
756480
- );
756481
- }
757068
+ );
756482
757069
  }
756483
757070
  });
756484
757071
  } else {
@@ -756541,7 +757128,7 @@ Respond concisely and safely. Remember: you are talking to the general public.`;
756541
757128
  const restoreSnapshot = buildContextRestoreSnapshot(repoRoot);
756542
757129
  if (restoreSnapshot) {
756543
757130
  applyRestoreSnapshot(restoreSnapshot, {
756544
- replayVisual: true,
757131
+ replayVisual: false,
756545
757132
  injectNextTask: false
756546
757133
  });
756547
757134
  }
@@ -757302,7 +757889,8 @@ ${formatTaskCompletionMeta(previousMetaForIntake)}`
757302
757889
  let taskInput = fullInput;
757303
757890
  let taskSessionId = restoredTaskSessionId;
757304
757891
  if (restoredSessionContext) {
757305
- taskInput = `${restoredSessionContext}
757892
+ const safeRestoredContext = sanitizeRestorePromptForModel(restoredSessionContext);
757893
+ taskInput = `${safeRestoredContext}
757306
757894
 
757307
757895
  ---
757308
757896