mixdog 0.9.95 → 0.9.96

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.
Files changed (178) hide show
  1. package/LICENSES/Apache-2.0.txt +201 -0
  2. package/LICENSES/MIT.txt +56 -0
  3. package/LICENSES/codex-NOTICE.txt +6 -0
  4. package/NOTICE.md +46 -9
  5. package/package.json +12 -9
  6. package/scripts/.tmp-coverage-report.mjs +96 -0
  7. package/scripts/build-tui.mjs +17 -1
  8. package/scripts/fixtures/patch-replay-corpus.json +98 -0
  9. package/src/defaults/mixdog-config.template.json +5 -8
  10. package/src/rules/agent/30-explorer.md +7 -4
  11. package/src/rules/shared/01-tool.md +20 -29
  12. package/src/runtime/agent/orchestrator/agent-runtime/agent-dispatch.mjs +18 -2
  13. package/src/runtime/agent/orchestrator/agent-runtime/agent-progress-watchdog.mjs +31 -1
  14. package/src/runtime/agent/orchestrator/agent-runtime/maintenance-route.mjs +6 -17
  15. package/src/runtime/agent/orchestrator/agent-trace-format.mjs +12 -1
  16. package/src/runtime/agent/orchestrator/config.mjs +246 -67
  17. package/src/runtime/agent/orchestrator/mcp/client.mjs +26 -11
  18. package/src/runtime/agent/orchestrator/mcp/reconnect-singleflight.mjs +23 -0
  19. package/src/runtime/agent/orchestrator/providers/admission-scheduler.mjs +113 -14
  20. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +5 -1
  21. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +32 -11
  22. package/src/runtime/agent/orchestrator/providers/gemini.mjs +89 -2
  23. package/src/runtime/agent/orchestrator/providers/grok-oauth.mjs +12 -1
  24. package/src/runtime/agent/orchestrator/providers/openai-compat-xai.mjs +19 -1
  25. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +144 -39
  26. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +22 -8
  27. package/src/runtime/agent/orchestrator/providers/openai-oauth.mjs +15 -1
  28. package/src/runtime/agent/orchestrator/providers/openai-transport-policy.mjs +1 -1
  29. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +3 -4
  30. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +67 -7
  31. package/src/runtime/agent/orchestrator/providers/stream-json-pool.mjs +291 -0
  32. package/src/runtime/agent/orchestrator/providers/stream-json-worker.mjs +21 -0
  33. package/src/runtime/agent/orchestrator/session/agent-loop.mjs +28 -4
  34. package/src/runtime/agent/orchestrator/session/eager-dispatch.mjs +4 -33
  35. package/src/runtime/agent/orchestrator/session/loop/pre-dispatch-deny.mjs +13 -0
  36. package/src/runtime/agent/orchestrator/session/loop/termination.mjs +2 -2
  37. package/src/runtime/agent/orchestrator/session/loop/tool-classify.mjs +0 -24
  38. package/src/runtime/agent/orchestrator/session/loop/tool-exec.mjs +1 -27
  39. package/src/runtime/agent/orchestrator/session/loop/tool-helpers.mjs +6 -10
  40. package/src/runtime/agent/orchestrator/session/manager/ask-session.mjs +5 -0
  41. package/src/runtime/agent/orchestrator/session/manager/pending-messages.mjs +142 -84
  42. package/src/runtime/agent/orchestrator/session/manager/runtime-loaders.mjs +4 -0
  43. package/src/runtime/agent/orchestrator/session/manager/session-crud.mjs +31 -1
  44. package/src/runtime/agent/orchestrator/session/manager/turn-interruption.mjs +29 -9
  45. package/src/runtime/agent/orchestrator/session/manager.mjs +2 -0
  46. package/src/runtime/agent/orchestrator/session/result-classification.mjs +65 -0
  47. package/src/runtime/agent/orchestrator/session/send-with-recovery.mjs +86 -8
  48. package/src/runtime/agent/orchestrator/session/store-summary-reader.mjs +12 -0
  49. package/src/runtime/agent/orchestrator/session/tool-batch.mjs +3 -33
  50. package/src/runtime/agent/orchestrator/session/tool-result-offload.mjs +4 -5
  51. package/src/runtime/agent/orchestrator/stall-policy.mjs +1 -1
  52. package/src/runtime/agent/orchestrator/tools/bash-session.mjs +2 -2
  53. package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +35 -1
  54. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +118 -18
  55. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +8 -9
  56. package/src/runtime/agent/orchestrator/tools/builtin/cache-layers.mjs +2 -2
  57. package/src/runtime/agent/orchestrator/tools/builtin/device-paths.mjs +2 -2
  58. package/src/runtime/agent/orchestrator/tools/builtin/lib/grep-context-expander.mjs +6 -15
  59. package/src/runtime/agent/orchestrator/tools/builtin/list-tool.mjs +10 -26
  60. package/src/runtime/agent/orchestrator/tools/builtin/read-image.mjs +1 -1
  61. package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +3 -3
  62. package/src/runtime/agent/orchestrator/tools/builtin/read-tool.mjs +1 -23
  63. package/src/runtime/agent/orchestrator/tools/builtin/rg-runner.mjs +23 -9
  64. package/src/runtime/agent/orchestrator/tools/builtin/search-path-diagnostics.mjs +7 -0
  65. package/src/runtime/agent/orchestrator/tools/builtin/search-tool.mjs +17 -39
  66. package/src/runtime/agent/orchestrator/tools/builtin/shell-analysis.mjs +73 -0
  67. package/src/runtime/agent/orchestrator/tools/builtin/shell-job-paths.mjs +1 -1
  68. package/src/runtime/agent/orchestrator/tools/builtin/shell-job-spawn.mjs +0 -2
  69. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +3 -8
  70. package/src/runtime/agent/orchestrator/tools/builtin/shell-runtime.mjs +30 -0
  71. package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +5 -5
  72. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +87 -15
  73. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +6 -15
  74. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +2 -2
  75. package/src/runtime/agent/orchestrator/tools/lib/pwsh-standby-pool.mjs +83 -13
  76. package/src/runtime/agent/orchestrator/tools/patch/matcher.mjs +39 -1
  77. package/src/runtime/agent/orchestrator/tools/patch/orchestrator.mjs +29 -1
  78. package/src/runtime/agent/orchestrator/tools/patch/parsing.mjs +16 -0
  79. package/src/runtime/agent/orchestrator/tools/patch/v4a-convert.mjs +108 -12
  80. package/src/runtime/agent/orchestrator/tools/patch-tool-defs.mjs +10 -10
  81. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +56 -8
  82. package/src/runtime/agent/orchestrator/tools/shell-exec-output.mjs +2 -2
  83. package/src/runtime/channels/lib/config.mjs +2 -2
  84. package/src/runtime/channels/lib/inbound-handler.mjs +1 -1
  85. package/src/runtime/channels/lib/scheduler.mjs +2 -2
  86. package/src/runtime/memory/index.mjs +5 -38
  87. package/src/runtime/memory/lib/agent-ipc.mjs +145 -81
  88. package/src/runtime/memory/lib/compact-vector-cache.mjs +88 -0
  89. package/src/runtime/memory/lib/core-memory-store.mjs +18 -1
  90. package/src/runtime/memory/lib/cycle-llm-adapters.mjs +12 -33
  91. package/src/runtime/memory/lib/embedding-provider.mjs +47 -26
  92. package/src/runtime/memory/lib/embedding-worker.mjs +30 -34
  93. package/src/runtime/memory/lib/http-router.mjs +8 -0
  94. package/src/runtime/memory/lib/ko-morph.mjs +3 -20
  95. package/src/runtime/memory/lib/memory-action-handlers.mjs +2 -1
  96. package/src/runtime/memory/lib/memory-cycle1.mjs +1 -0
  97. package/src/runtime/memory/lib/memory-cycle2-gate.mjs +4 -2
  98. package/src/runtime/memory/lib/memory-cycle2-mutations.mjs +1 -0
  99. package/src/runtime/memory/lib/memory-cycle3.mjs +3 -1
  100. package/src/runtime/memory/lib/pg/process.mjs +32 -9
  101. package/src/runtime/memory/tool-defs.mjs +1 -5
  102. package/src/runtime/search/tool-defs.mjs +2 -2
  103. package/src/runtime/shared/agent-route-config.mjs +119 -0
  104. package/src/runtime/shared/atomic-file.mjs +80 -4
  105. package/src/runtime/shared/channel-notification-routing.mjs +2 -2
  106. package/src/runtime/shared/child-guardian.mjs +204 -108
  107. package/src/runtime/shared/child-spawn-gate.mjs +60 -31
  108. package/src/runtime/shared/config.mjs +130 -44
  109. package/src/runtime/shared/resource-admission.mjs +146 -97
  110. package/src/runtime/shared/stream-progress.mjs +6 -0
  111. package/src/runtime/shared/tool-surface.mjs +0 -5
  112. package/src/runtime/shared/turn-snapshot.mjs +31 -5
  113. package/src/runtime/shared/turn-worktree-snapshot.mjs +14 -2
  114. package/src/session-runtime/config-helpers.mjs +39 -37
  115. package/src/session-runtime/model-route-api.mjs +7 -5
  116. package/src/session-runtime/provider-auth-api.mjs +0 -7
  117. package/src/session-runtime/runtime-core.mjs +11 -11
  118. package/src/session-runtime/runtime-tunables.mjs +4 -4
  119. package/src/session-runtime/session-lifecycle.mjs +9 -2
  120. package/src/session-runtime/session-turn-api.mjs +41 -9
  121. package/src/session-runtime/settings-api.mjs +5 -17
  122. package/src/session-runtime/tool-defs.mjs +3 -3
  123. package/src/session-runtime/workflow-agents-api.mjs +55 -81
  124. package/src/session-runtime/workflow.mjs +14 -24
  125. package/src/standalone/agent-dispatch-broker.mjs +198 -0
  126. package/src/standalone/agent-tool/helpers.mjs +2 -2
  127. package/src/standalone/agent-tool/spawn-flow.mjs +2 -0
  128. package/src/standalone/agent-tool/spawn-preset.mjs +11 -21
  129. package/src/standalone/agent-tool/tool-def.mjs +0 -14
  130. package/src/standalone/backend-daemon.mjs +97 -36
  131. package/src/standalone/channel-admin.mjs +12 -12
  132. package/src/standalone/channel-daemon-client.mjs +17 -1
  133. package/src/standalone/channel-daemon-transport.mjs +90 -8
  134. package/src/standalone/engine-daemon-client.mjs +380 -205
  135. package/src/standalone/engine-daemon-protocol.mjs +3 -4
  136. package/src/standalone/engine-daemon-service.mjs +378 -134
  137. package/src/standalone/engine-daemon-transport.mjs +268 -77
  138. package/src/standalone/explore-tool.mjs +187 -70
  139. package/src/standalone/fair-call-scheduler.mjs +264 -0
  140. package/src/standalone/session-protocol.mjs +188 -0
  141. package/src/tui/App.jsx +30 -17
  142. package/src/tui/app/app-view.jsx +5 -2
  143. package/src/tui/app/core-memory-picker.mjs +19 -19
  144. package/src/tui/app/doctor.mjs +5 -11
  145. package/src/tui/app/message-selector.mjs +103 -0
  146. package/src/tui/app/onboarding-steps.mjs +1 -2
  147. package/src/tui/app/project-picker.mjs +80 -56
  148. package/src/tui/app/prompt-submit.mjs +46 -41
  149. package/src/tui/app/resume-picker.mjs +2 -2
  150. package/src/tui/app/route-pickers.mjs +3 -1
  151. package/src/tui/app/settings-picker.mjs +6 -8
  152. package/src/tui/app/transcript-window.mjs +38 -0
  153. package/src/tui/app/use-prompt-draft-flow.mjs +5 -7
  154. package/src/tui/app/use-prompt-handlers.mjs +86 -21
  155. package/src/tui/app/use-prompt-hint.mjs +3 -2
  156. package/src/tui/app/use-prompt-queue-history.mjs +10 -3
  157. package/src/tui/app/use-transcript-scroll.mjs +9 -2
  158. package/src/tui/app/use-transcript-window.mjs +50 -17
  159. package/src/tui/components/PromptInput.jsx +71 -38
  160. package/src/tui/components/Spinner.jsx +1 -1
  161. package/src/tui/components/prompt-input/edit-helpers.mjs +9 -11
  162. package/src/tui/components/prompt-input/escape-policy.mjs +42 -0
  163. package/src/tui/components/prompt-input/immediate-render.mjs +0 -10
  164. package/src/tui/components/prompt-input/interrupt-policy.mjs +10 -0
  165. package/src/tui/components/prompt-input/restore-policy.mjs +10 -0
  166. package/src/tui/dist/index.mjs +920 -1592
  167. package/src/tui/engine/live-share.mjs +34 -0
  168. package/src/tui/engine/session-api-ext.mjs +1 -4
  169. package/src/tui/engine/session-api.mjs +103 -33
  170. package/src/tui/engine/session-flow.mjs +7 -1
  171. package/src/tui/engine/tool-card-results.mjs +4 -2
  172. package/src/tui/engine/tool-result-text.mjs +10 -0
  173. package/src/tui/engine/turn.mjs +9 -69
  174. package/src/tui/engine-local-session.mjs +47 -31
  175. package/src/tui/index.jsx +1 -2
  176. package/src/tui/spinner-meta.mjs +4 -4
  177. package/src/tui/spinner-verbs.mjs +51 -3
  178. package/src/standalone/engine-daemon-local-bridge.mjs +0 -20
@@ -28,6 +28,8 @@ import {
28
28
  findLineSequence,
29
29
  findLineSequenceEscapeEquiv,
30
30
  longestCommonSubstringLen,
31
+ boundedEditDistance,
32
+ EDIT_DISTANCE_ALLOWANCE_PER_LINE,
31
33
  splitTextLinesForPatch,
32
34
  firstMeaningfulPatchLine,
33
35
  nearestPatchLineHint,
@@ -162,6 +164,18 @@ function noteV4AHunkAmbiguity(displayPath, sourceLines, loc) {
162
164
  );
163
165
  }
164
166
 
167
+ // `*** End of File` was relaxed to locate this hunk: report where it actually
168
+ // landed so a mid-file hunk that carried the marker by mistake is visible in
169
+ // the same turn instead of silently looking like an end-of-file edit.
170
+ function noteV4AEofSignalIgnored(displayPath, loc) {
171
+ if (_v4aAmbiguityNotices.size >= V4A_AMBIGUITY_NOTICE_CAP) return;
172
+ if (!loc?.eofSignalIgnored) return;
173
+ _v4aAmbiguityNotices.add(
174
+ `${displayPath}: hunk carried *** End of File but its context is at line ${loc.oldStartIdx + 1}, `
175
+ + 'not the end of file; the marker was ignored. Drop it unless the hunk really ends the file.',
176
+ );
177
+ }
178
+
165
179
  export function drainV4AAmbiguityNotices() {
166
180
  if (_v4aAmbiguityNotices.size === 0) return [];
167
181
  const list = [..._v4aAmbiguityNotices];
@@ -299,14 +313,50 @@ function findContextTolerantWindow(sourceLines, oldLines, oldTags) {
299
313
  return windows.length === 1 ? { start: windows[0] } : null;
300
314
  }
301
315
 
302
- // Last-resort recovery for a model that accidentally copied 1-2 unrelated
303
- // unchanged context lines just outside the real edit. Trim only contiguous
304
- // outer ' ' lines — never '-' or '+' lines — and accept the shortened old
305
- // block only when it matches byte-exactly at exactly one place in the ENTIRE
306
- // file. Requiring a deletion keeps this fallback off insertion-only hunks;
307
- // exact whole-block matching proves every deletion line is current. Any
308
- // competing trim plan or duplicate occurrence is ambiguous and stays a hard
309
- // context miss.
316
+ // Bounded edit-distance tier (fuzzy, after the context-tolerance tier).
317
+ // Recovers the block a model retyped from memory with a couple of characters
318
+ // off — a dropped bracket, a mistyped short token — where the tolerance tier
319
+ // refuses because the drift sits on a deletion line. Guards keep it safe:
320
+ // - TOTAL distance across the block stays within ~0.34 characters per line
321
+ // (3 lines buy exactly 1 character), measured on trimmed text;
322
+ // - at least 2 non-blank lines must match byte-exactly as anchors;
323
+ // - the qualifying window must be UNIQUE across the ENTIRE file;
324
+ // - the caller REMAPS every old line to the file's on-disk text, so the
325
+ // emitted hunk stays byte-exact for the applier.
326
+ function findEditDistanceWindow(sourceLines, oldLines) {
327
+ const n = (oldLines || []).length;
328
+ const maxDistance = Math.floor(n * EDIT_DISTANCE_ALLOWANCE_PER_LINE);
329
+ if (n < 3 || maxDistance <= 0) return null;
330
+ const windows = [];
331
+ for (let i = 0; i + n <= sourceLines.length && windows.length < 2; i++) {
332
+ let total = 0;
333
+ let exact = 0;
334
+ let ok = true;
335
+ for (let k = 0; k < n; k++) {
336
+ const pat = String(oldLines[k] ?? '');
337
+ const src = String(sourceLines[i + k] ?? '');
338
+ if (src === pat) {
339
+ if (pat.trim()) exact++;
340
+ continue;
341
+ }
342
+ total += boundedEditDistance(src.trim(), pat.trim(), maxDistance - total);
343
+ if (total > maxDistance) { ok = false; break; }
344
+ }
345
+ if (ok && total > 0 && exact >= 2) windows.push(i);
346
+ }
347
+ return windows.length === 1 ? { start: windows[0] } : null;
348
+ }
349
+
350
+ // Recovery for outer context the model got wrong — a stray copied line, or a
351
+ // whole surrounding block retyped from memory — around an edit whose deletion
352
+ // lines are current. Trim only contiguous outer ' ' lines — never '-' or '+'
353
+ // lines — smallest trim first, and accept the shortened old block only when it
354
+ // matches byte-exactly at exactly one place in the ENTIRE file. That
355
+ // uniqueness IS the position proof, so the trim budget runs to all available
356
+ // outer context: a byte-exact, file-unique deletion core cannot land anywhere
357
+ // else, whatever the caller wrote around it. Requiring a deletion keeps this
358
+ // off insertion-only hunks (they carry no payload to anchor on), and any
359
+ // competing trim plan or duplicate occurrence stays a hard context miss.
310
360
  function findOuterContextTrimmedWindow(sourceLines, hunk, stats) {
311
361
  const body = (hunk?.lines || []).filter(
312
362
  (line) => typeof line === 'string'
@@ -325,7 +375,8 @@ function findOuterContextTrimmedWindow(sourceLines, hunk, stats) {
325
375
  ) trailingAvailable++;
326
376
  if (leadingAvailable === 0 && trailingAvailable === 0) return null;
327
377
 
328
- for (let totalTrimmed = 1; totalTrimmed <= 2; totalTrimmed++) {
378
+ const maxTrimmed = leadingAvailable + trailingAvailable;
379
+ for (let totalTrimmed = 1; totalTrimmed <= maxTrimmed; totalTrimmed++) {
329
380
  const plans = [];
330
381
  let ambiguous = false;
331
382
  for (let leading = 0; leading <= Math.min(totalTrimmed, leadingAvailable); leading++) {
@@ -424,7 +475,23 @@ function resolveV4AHunkPosition(sourceLines, hunk, nextSearchLine, options = {})
424
475
  // of the patch's real character. On match, remap old/context lines to the
425
476
  // file's on-disk form so untouched context stays byte-identical and the
426
477
  // escape representation survives the edit.
427
- if (oldStartIdx < 0 && fuzzy && !eof && oldLinesPattern.length > 0) {
478
+ // `*** End of File` is a HINT, not a hard constraint. When the EOF-anchored
479
+ // seek misses, retry the pattern as an ordinary in-file search: a mid-file
480
+ // hunk that carried the marker by mistake used to fail with a "context not
481
+ // found" that pointed at its own byte-perfect context, costing a whole retry
482
+ // turn. Once that happens the EOF signal is exhausted, so every recovery
483
+ // tier below treats the hunk as unmarked.
484
+ let eofSignalIgnored = false;
485
+ if (oldStartIdx < 0 && eof && oldLinesPattern.length > 0) {
486
+ const relaxedFrom = Math.max(0, anchorLine - 1);
487
+ const relaxed = findLineSequence(sourceLines, oldLinesPattern, relaxedFrom, relaxedFrom, { fuzzy, eof: false });
488
+ if (relaxed >= 0) {
489
+ oldStartIdx = relaxed;
490
+ eofSignalIgnored = true;
491
+ }
492
+ }
493
+ if (oldStartIdx < 0 && fuzzy && oldLinesPattern.length > 0) {
494
+ if (eof) eofSignalIgnored = true;
428
495
  const from = Math.max(0, anchorLine - 1);
429
496
  const alt = findLineSequenceEscapeEquiv(sourceLines, oldLinesPattern, from, from);
430
497
  if (alt >= 0) {
@@ -447,7 +514,7 @@ function resolveV4AHunkPosition(sourceLines, hunk, nextSearchLine, options = {})
447
514
  // lines are remapped to the file's actual lines on BOTH the old and new
448
515
  // side (same shape as the escape-equiv remap above); remapping bails on any
449
516
  // string ambiguity so an unrelated occurrence can never be rewritten.
450
- if (oldStartIdx < 0 && fuzzy && !eof && oldLinesPattern.length >= 3) {
517
+ if (oldStartIdx < 0 && fuzzy && oldLinesPattern.length >= 3) {
451
518
  const tolTags = trimmedTrailing ? stats.oldTags.slice(0, -1) : stats.oldTags;
452
519
  const tol = findContextTolerantWindow(sourceLines, oldLinesPattern, tolTags);
453
520
  if (tol) {
@@ -474,7 +541,7 @@ function resolveV4AHunkPosition(sourceLines, hunk, nextSearchLine, options = {})
474
541
  // This fallback is deliberately narrower than the context-tolerance tier:
475
542
  // fuzzy mode only, non-EOF, no newline-sentinel interaction, deletion hunks
476
543
  // only, byte-exact remaining block, and one unique whole-file location.
477
- if (oldStartIdx < 0 && fuzzy && !eof && trimmedTrailing === 0) {
544
+ if (oldStartIdx < 0 && fuzzy && trimmedTrailing === 0) {
478
545
  const trimmed = findOuterContextTrimmedWindow(sourceLines, hunk, stats);
479
546
  if (trimmed) {
480
547
  oldStartIdx = trimmed.start;
@@ -484,6 +551,31 @@ function resolveV4AHunkPosition(sourceLines, hunk, nextSearchLine, options = {})
484
551
  trimmedTrailingContext = trimmed.trailing;
485
552
  }
486
553
  }
554
+ // Edit-distance tier: same remap contract as the context-tolerance tier —
555
+ // the window's on-disk lines replace the patch's near-miss lines on BOTH
556
+ // sides, and any string ambiguity abandons the rescue.
557
+ if (oldStartIdx < 0 && fuzzy && oldLinesPattern.length >= 3) {
558
+ const near = findEditDistanceWindow(sourceLines, oldLinesPattern);
559
+ if (near) {
560
+ const remapped = new Map();
561
+ let ambiguous = false;
562
+ for (let k = 0; k < oldLinesPattern.length; k++) {
563
+ const pat = oldLinesPattern[k];
564
+ const src = sourceLines[near.start + k];
565
+ if (src === pat) continue;
566
+ if (
567
+ oldLinesPattern.filter((l) => l === pat).length > 1
568
+ || (remapped.has(pat) && remapped.get(pat) !== src)
569
+ ) { ambiguous = true; break; }
570
+ remapped.set(pat, src);
571
+ }
572
+ if (!ambiguous) {
573
+ newLinesPattern = newLinesPattern.map((l) => remapped.get(l) ?? l);
574
+ oldLinesPattern = oldLinesPattern.map((_, k) => sourceLines[near.start + k]);
575
+ oldStartIdx = near.start;
576
+ }
577
+ }
578
+ }
487
579
  if (oldStartIdx < 0) {
488
580
  const msg = `V4A hunk context not found: ${formatV4AHunkLocator(hunk)};${formatV4AContextMissHint(sourceLines, stats, anchorLine)}`;
489
581
  return { error: msg };
@@ -506,6 +598,9 @@ function resolveV4AHunkPosition(sourceLines, hunk, nextSearchLine, options = {})
506
598
  // hunk carried an @@ anchor (an anchored hunk is never ambiguous).
507
599
  pattern: oldLinesPattern,
508
600
  anchored: (hunk.anchors || []).filter(Boolean).length > 0,
601
+ // True when the hunk's `*** End of File` marker had to be relaxed to
602
+ // locate it (drives the non-fatal notice on the success output).
603
+ eofSignalIgnored,
509
604
  };
510
605
  }
511
606
 
@@ -1011,6 +1106,7 @@ export async function convertV4ASectionsToUnifiedPatch(sections, basePath, optio
1011
1106
  ],
1012
1107
  });
1013
1108
  noteV4AHunkAmbiguity(displayPath, sourceLines, loc);
1109
+ noteV4AEofSignalIgnored(displayPath, loc);
1014
1110
  nextSearchLine = loc.nextSearchLine;
1015
1111
  }
1016
1112
  sectionHunkEntries.sort((a, b) => (a.start - b.start) || (a.order - b.order));
@@ -28,7 +28,7 @@ eof_line: "*** End of File" LF
28
28
  // Batching stays a rules-level policy: every new edit goes in one patch, with
29
29
  // one file block per target.
30
30
  const APPLY_PATCH_FREEFORM_DESCRIPTION =
31
- 'Use the `apply_patch` tool to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.';
31
+ 'Edit files with `apply_patch`. FREEFORM input; do not wrap the patch in JSON.';
32
32
 
33
33
  // JSON-schema fallback providers (Anthropic and other non-grammar surfaces)
34
34
  // get the full V4A instructions inline: without a grammar the model has
@@ -41,13 +41,10 @@ const APPLY_PATCH_JSON_DESCRIPTION = [
41
41
  '*** Begin Patch',
42
42
  '[file sections]',
43
43
  '*** End Patch',
44
- 'Every section starts with exactly one header:',
45
- '- *** Add File: <path> then +content lines.',
46
- '- *** Delete File: <path> with nothing after it.',
47
- '- *** Update File: <path>, optionally followed by *** Move to: <new path>.',
48
- 'Update hunks open with @@ or @@ <enclosing class/function>; prefix every line with space (context), - (remove), or + (add); a hunk at end of file may close with *** End of File.',
49
- 'Copy 3 context lines above and below verbatim from the newest tool output of the file (after your own patch, use post-patch content; never retype from memory). Do not duplicate overlapping context; if context is not unique, add enclosing @@ headers.',
50
- 'Use project-relative paths. Every added file line needs +. Never submit a compacted-history marker; re-read and create a fresh patch.',
44
+ 'Every section starts with exactly one header: *** Add File: <path> (+content lines), *** Delete File: <path> (nothing after), *** Update File: <path> (optional *** Move to: <new path>).',
45
+ 'Hunks open with @@ or @@ <symbol>; prefix lines with space, -, or +; an end-of-file hunk may close with *** End of File.',
46
+ 'Copy 3 context lines above/below verbatim from the newest tool output — after your own patch use its post-patch body, never memory. No duplicate overlapping context; if still ambiguous, stack @@ headers: @@ class Foo then @@ def bar.',
47
+ 'Project-relative paths; every added line needs +. Never submit a compacted-history marker — re-read and send a fresh patch.',
51
48
  ].join('\n');
52
49
 
53
50
  export const PATCH_TOOL_DEFS = [
@@ -65,8 +62,11 @@ export const PATCH_TOOL_DEFS = [
65
62
  inputSchema: {
66
63
  type: 'object',
67
64
  properties: {
68
- patch: { type: 'string', description: 'The V4A patch text to apply (format and context rules in the tool description).' },
69
- post_shell: { type: 'string', description: 'Verification command run when the patch applies; skipped on patch failure.' },
65
+ patch: { type: 'string', description: 'V4A patch text to apply; rules above.' },
66
+ root: {
67
+ type: 'string',
68
+ description: 'Write root; required only for targets outside the session directory.',
69
+ },
70
70
  },
71
71
  required: ['patch'],
72
72
  additionalProperties: false,
@@ -75,8 +75,8 @@ const SHELL_ADMISSION_WAIT_MS = Number.isFinite(_envAdmissionWait) && _envAdmiss
75
75
  ? _envAdmissionWait
76
76
  : 30_000;
77
77
 
78
- // CC parity default: capture child output via file fds (TaskOutput direct
79
- // mode) instead of parent-side pipes. Opt back into pipe capture with
78
+ // Default: capture child output via file fds (direct mode) instead of
79
+ // parent-side pipes. Opt back into pipe capture with
80
80
  // MIXDOG_SHELL_PIPE_CAPTURE=1 (diagnostic escape hatch).
81
81
  // win32 EXCEPTION: fd-based stdio entries are UV_INHERIT_FD, which makes
82
82
  // libuv DROP CREATE_NO_WINDOW (libuv PR #1659) — the child shell then
@@ -145,9 +145,30 @@ function _abortableDelay(ms, signal) {
145
145
  });
146
146
  }
147
147
 
148
- export async function acquireShellLeaseBounded(admission, { abortSignal, label, dependency = 'scoped' } = {}) {
148
+ // True when an abort was raised because the user sent a NEW message while the
149
+ // command was running (session-api.mjs raises 'interrupt' when steering is
150
+ // pending, 'user-cancel' for a plain ESC). The reason travels as the
151
+ // SessionClosedError's `reason` field; a bare string / message fallback keeps
152
+ // non-session callers working. Anything unrecognized is treated as a real
153
+ // cancellation, so the kill path stays the default.
154
+ export function _abortReasonIsInterrupt(abortSignal) {
155
+ const raw = abortSignal?.reason;
156
+ if (!raw) return false;
157
+ if (typeof raw === 'string') return raw === 'interrupt';
158
+ if (typeof raw === 'object') {
159
+ if (raw.reason === 'interrupt') return true;
160
+ if (typeof raw.message === 'string' && /\breason=interrupt\b/.test(raw.message)) return true;
161
+ }
162
+ return false;
163
+ }
164
+
165
+ export async function acquireShellLeaseBounded(admission, {
166
+ abortSignal, label, dependency = 'scoped', ownerKey = null,
167
+ } = {}) {
149
168
  if (!(SHELL_ADMISSION_WAIT_MS > 0)) {
150
- return admission.acquire('shell', { signal: abortSignal || null, label, dependency });
169
+ return admission.acquire('shell', {
170
+ signal: abortSignal || null, label, dependency, ownerKey,
171
+ });
151
172
  }
152
173
  const ctl = new AbortController();
153
174
  const onAbort = () => {
@@ -165,7 +186,9 @@ export async function acquireShellLeaseBounded(admission, { abortSignal, label,
165
186
  try {
166
187
  for (;;) {
167
188
  try {
168
- const lease = await admission.acquire('shell', { signal: ctl.signal, label, dependency });
189
+ const lease = await admission.acquire('shell', {
190
+ signal: ctl.signal, label, dependency, ownerKey,
191
+ });
169
192
  // Hand governance back to the caller's signal: the internal deadline
170
193
  // controller may still fire in a lost race after grant, and a stale
171
194
  // aborted signal on the lease would poison later parent-restore paths.
@@ -363,6 +386,7 @@ export function execShellCommand({
363
386
  resourceLease = await acquireShellLeaseBounded(admission, {
364
387
  abortSignal,
365
388
  label: String(command || '').slice(0, 120),
389
+ ownerKey: ownerSessionId,
366
390
  });
367
391
  const _policyErr = await _execPolicyBlockMessage(command);
368
392
  if (_policyErr) {
@@ -443,7 +467,6 @@ export function execShellCommand({
443
467
  childPid: child.pid,
444
468
  childGroupPid: child.pid,
445
469
  label: 'shell-command',
446
- protectHostMemory: true,
447
470
  });
448
471
  // Windows has no process-group handle. Begin observing while the owned
449
472
  // root still exists so descendants can be proven before root exit.
@@ -830,7 +853,12 @@ export function execShellCommand({
830
853
  // Re-check after the awaited capture reads: cancellation can race after
831
854
  // adoption commits. Never report that cancelled process as a successful
832
855
  // still-running background task.
833
- if (abortSignal && abortSignal.aborted) {
856
+ // EXCEPTION: an interrupt-driven promotion starts FROM an aborted signal
857
+ // by design (the user typed a new message), so this guard must not undo
858
+ // the very transition it was asked to perform. A plain cancellation still
859
+ // reverts adoption and kills.
860
+ if (abortSignal && abortSignal.aborted
861
+ && !(reason === 'interrupt' && _abortReasonIsInterrupt(abortSignal))) {
834
862
  killed = true;
835
863
  killCause = 'cancellation';
836
864
  try { killShellJob(jobId); } catch {}
@@ -855,7 +883,7 @@ export function execShellCommand({
855
883
  }));
856
884
  return;
857
885
  }
858
- // CC parity (BashTool completed-during-promotion race): the child
886
+ // Completed-during-promotion race: the child
859
887
  // finished while adoption was committing. Report a clean COMPLETED
860
888
  // result instead of backgrounded — the caller then never arms the
861
889
  // completion watcher, so no redundant task notification fires. Write
@@ -1037,6 +1065,26 @@ export function execShellCommand({
1037
1065
 
1038
1066
  if (abortSignal) {
1039
1067
  abortHandler = () => {
1068
+ // Interrupt (the user typed a NEW message while this was running) is a
1069
+ // "also look at this" signal, not "stop that" — CC backgrounds instead
1070
+ // of killing there, and throwing away a long build the user never asked
1071
+ // to stop is the worse outcome. Explicit cancellation (ESC) keeps the
1072
+ // kill. The promotion reuses the timeout path's guards verbatim so a
1073
+ // detached / already-settled / already-exited child can never be
1074
+ // adopted as a job.
1075
+ if (
1076
+ _abortReasonIsInterrupt(abortSignal) &&
1077
+ backgroundOnTimeout &&
1078
+ !_isBackground &&
1079
+ !settled &&
1080
+ !autoBackgrounded &&
1081
+ !killed &&
1082
+ child?.exitCode == null &&
1083
+ child?.signalCode == null
1084
+ ) {
1085
+ fireAutoBackground({ reason: 'interrupt' });
1086
+ return;
1087
+ }
1040
1088
  _treeKillForceSettle('cancellation');
1041
1089
  };
1042
1090
  try {
@@ -209,7 +209,7 @@ export class TaskOutput {
209
209
  this.stdoutFileSize = 0;
210
210
  this.stderrFileSize = 0;
211
211
  this.writeError = null;
212
- // CC parity: direct-capture mode hands the spill files to the child as
212
+ // Direct-capture mode hands the spill files to the child as
213
213
  // stdio fds (no JS pipes). Sizes are then tracked via stat, not writes.
214
214
  this.direct = false;
215
215
  // fsync throttle: task wait/read + tail-read polling can call getStdout/
@@ -292,7 +292,7 @@ export class TaskOutput {
292
292
  this._ensureFileBacking();
293
293
  }
294
294
 
295
- // CC parity (ShellCommand file mode): open the spill files BEFORE spawn and
295
+ // File mode: open the spill files BEFORE spawn and
296
296
  // hand their fds to the child as stdio[1]/stdio[2]. The child (and any
297
297
  // grandchildren) write straight to disk with no parent-side pipes, so a
298
298
  // surviving grandchild can never wedge the caller by holding a pipe handle.
@@ -26,7 +26,7 @@ const DEFAULT_CONFIG = {
26
26
  discord: { token: "" },
27
27
  telegram: { token: "" },
28
28
  access: DEFAULT_ACCESS,
29
- channel: { channelId: "" }
29
+ channel: {}
30
30
  };
31
31
  // Shared defaults layer. Merge semantics: user values win; defaults
32
32
  // only fill missing fields. Helper is exported so the setup UI and
@@ -117,7 +117,7 @@ async function loadConfig({ freshSecrets = false } = {}) {
117
117
  updateSection("channels", () => DEFAULT_CONFIG);
118
118
  process.stderr.write(
119
119
  `mixdog: default channels config created in ${MIXDOG_CONFIG_PATH}
120
- edit discord.token and channel.channelId to connect.
120
+ edit the active backend channel id to connect.
121
121
  `
122
122
  );
123
123
  return applyDefaults(DEFAULT_CONFIG);
@@ -63,7 +63,7 @@ getBackend().onMessage = (msg) => {
63
63
  : (!getChannelBridgeActive() ? "bridge-inactive" : "");
64
64
  if (gateBlocked) {
65
65
  if (gateBlocked === "bridge-seat") refreshBridgeOwnershipSafe();
66
- // CC parity: an inbound message is never silently swallowed. The bridge
66
+ // An inbound message is never silently swallowed. The bridge
67
67
  // seat may be mid-handover or the channel bridge may still be activating
68
68
  // (app relaunch / boot); retry with backoff before giving up, and make
69
69
  // the final drop loud so a real loss stays diagnosable.
@@ -589,8 +589,8 @@ ${Scheduler.INSTANCE_UUID}`;
589
589
  logSchedule(`${schedule.name}: skipped — previous run still in progress\n`);
590
590
  return false;
591
591
  }
592
- // CC parity (reference messageQueueManager.ts): interactive schedules
593
- // enqueue into the live Lead session's command queue as system-generated
592
+ // Interactive schedules enqueue into the live Lead session's command
593
+ // queue as system-generated
594
594
  // task notifications (priority 'later'), exactly like inbound channel
595
595
  // messages — enqueue counts as the fire. The visible-session run below
596
596
  // remains the non-interactive path AND the fallback when no live Lead
@@ -27,10 +27,6 @@ const PLUGIN_VERSION = readPluginVersion(PLUGIN_ROOT)
27
27
  const BOOT_PROMOTION_CODE_FINGERPRINT = readPromotionCodeFingerprint(PLUGIN_ROOT)
28
28
 
29
29
  try { os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL) } catch {}
30
- try {
31
- const { env } = await import('@huggingface/transformers')
32
- env.backends.onnx.wasm.numThreads = 1
33
- } catch {}
34
30
 
35
31
  import { Server } from '@modelcontextprotocol/sdk/server/index.js'
36
32
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
@@ -67,9 +63,7 @@ import {
67
63
  import { configureEmbedding, embedText, embedTexts, getEmbeddingDims, getEmbeddingDtype, getEmbeddingModelId, getKnownDimsForCurrentModel, isEmbeddingModelReady, primeEmbeddingDims, shutdownEmbeddingProvider, warmupEmbeddingProvider } from './lib/embedding-provider.mjs'
68
64
  import { startLlmWorker, stopLlmWorker } from './lib/llm-worker-host.mjs'
69
65
  import { runCycle1, runCycle2, runCycle3, runUnifiedGate, parseInterval, syncRootEmbedding, flushRawEmbeddings, applySimpleStatus, applyUpdate, applyMerge, CYCLE2_ACTIVE_TARGET_CAP } from './lib/memory-cycle.mjs'
70
- import { loadConfig as loadAgentConfig } from '../agent/orchestrator/config.mjs'
71
- import { initProviders } from '../agent/orchestrator/providers/registry.mjs'
72
- import { makeAgentDispatch } from '../agent/orchestrator/agent-runtime/agent-dispatch.mjs'
66
+ import { callAgentDispatch } from './lib/agent-ipc.mjs'
73
67
  import { getInFlightCycle1 } from './lib/memory-cycle1.mjs'
74
68
  import { claimAndMarkScheduledCycle, markCycleRequest, resolveCoalesceMaxRetries, scheduleCoalescedCycleRetry } from './lib/memory-cycle-requests.mjs'
75
69
  import { searchRelevantHybrid } from './lib/memory-recall-store.mjs'
@@ -358,36 +352,9 @@ async function _initStore() {
358
352
  } else {
359
353
  __mixdogMemoryLog('[memory-service] secondary mode; skipping llm worker\n')
360
354
  }
361
- // Initialize the in-process provider registry so cycle1 can run the agent dispatch
362
- // LLM locally (makeAgentDispatch → session manager → provider.send). In
363
- // standalone the memory worker runs as a detached HTTP daemon whose parent
364
- // has disconnected IPC, so the legacy callAgentDispatch() IPC path is dead on
365
- // arrival. Mirror the channels worker boot (channels/index.mjs:
366
- // loadAgentConfig() + initProviders) so the registry is populated before any
367
- // cycle1 dispatch. The gate MUST match _startCycle1Run's makeAgentDispatch
368
- // injection condition: cycle1 may dispatch in-process whenever cycles are
369
- // enabled OR the llm worker is enabled (both exclude secondary mode), so
370
- // registering only under the llm-worker gate would leave a hole where
371
- // MIXDOG_MEMORY_DISABLE_LLM_WORKER=1 + cycles enabled hits an empty registry
372
- // and fails with "Provider not found". Non-fatal: a failure here is logged
373
- // and cycle1's own callLlm surfaces the unresolved-provider error per call.
374
- // Registry must be available whenever cycles COULD run in this process, not
375
- // just when they are currently enabled: recap can be toggled on at runtime
376
- // (memoryCyclesEnabled() now includes the recap flag), so gate registry init
377
- // on the cycle-capable conditions (not secondary, env not hard-disabled) OR
378
- // the llm worker gate — never on the runtime recap flag itself, or enabling
379
- // recap later would hit an empty registry and fail with "Provider not found".
380
- const cyclesCapable = !memorySecondaryMode() && !envFlagEnabled('MIXDOG_MEMORY_DISABLE_CYCLES')
381
- if (cyclesCapable || memoryLlmWorkerEnabled()) {
382
- try {
383
- const agentCfg = loadAgentConfig()
384
- const providersStartedAt = performance.now()
385
- await initProviders(agentCfg.providers || {})
386
- memoryProfile('providers:init:done', { ms: (performance.now() - providersStartedAt).toFixed(1) })
387
- } catch (e) {
388
- process.stderr.write(`[memory-service] initProviders failed (non-fatal): ${e instanceof Error ? e.message : String(e)}\n`)
389
- }
390
- }
355
+ // Provider/session/agent modules live once in the backend daemon. Memory
356
+ // cycles cross the authenticated loopback broker instead of initializing a
357
+ // second registry in this process.
391
358
  _bootTimestamp = Date.now()
392
359
  const offsetsStartedAt = performance.now()
393
360
  await loadTranscriptOffsets()
@@ -437,7 +404,7 @@ async function setCycleLastRun(kind, ts) {
437
404
  // getters (getDb/getConfig/setConfig) plus runners and LLM adapters.
438
405
  const CYCLE_STATE_FILE = path.join(DATA_DIR, 'memory-cycle-state.json')
439
406
 
440
- const _cycleLlmAdapters = createCycleLlmAdapters({ makeAgentDispatch })
407
+ const _cycleLlmAdapters = createCycleLlmAdapters({ callAgentDispatch })
441
408
  const { getCycle1CallLlm, getCycle2CallLlm, getCycle3CallLlm } = _cycleLlmAdapters
442
409
 
443
410
  const _cycleScheduler = createCycleScheduler({