mixdog 0.9.25 → 0.9.26

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 (68) hide show
  1. package/package.json +1 -1
  2. package/scripts/steering-fold-provenance-test.mjs +71 -0
  3. package/scripts/webhook-smoke.mjs +46 -53
  4. package/src/defaults/skills/setup/SKILL.md +6 -1
  5. package/src/rules/shared/01-tool.md +8 -4
  6. package/src/runtime/agent/orchestrator/agent-trace-io.mjs +17 -0
  7. package/src/runtime/agent/orchestrator/mcp/child-tree.mjs +2 -2
  8. package/src/runtime/agent/orchestrator/mcp/client.mjs +28 -10
  9. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +8 -1
  10. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +14 -1
  11. package/src/runtime/agent/orchestrator/providers/oauth-usage.mjs +51 -15
  12. package/src/runtime/agent/orchestrator/session/agent-loop.mjs +5 -1
  13. package/src/runtime/agent/orchestrator/session/loop/steering-ladder.mjs +164 -9
  14. package/src/runtime/agent/orchestrator/session/loop/stored-tool-args.mjs +45 -0
  15. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +4 -0
  16. package/src/runtime/agent/orchestrator/session/tool-batch.mjs +12 -1
  17. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +2 -2
  18. package/src/runtime/agent/orchestrator/tools/shell-state.mjs +7 -3
  19. package/src/runtime/channels/lib/config.mjs +13 -11
  20. package/src/runtime/channels/lib/memory-client.mjs +22 -2
  21. package/src/runtime/channels/lib/owned-runtime.mjs +1 -1
  22. package/src/runtime/channels/lib/scheduler.mjs +226 -208
  23. package/src/runtime/channels/lib/status-snapshot.mjs +16 -0
  24. package/src/runtime/channels/lib/webhook/deliveries.mjs +7 -318
  25. package/src/runtime/channels/lib/webhook.mjs +98 -150
  26. package/src/runtime/channels/lib/worker-main.mjs +1 -1
  27. package/src/runtime/memory/index.mjs +50 -25
  28. package/src/runtime/memory/lib/cycle-scheduler.mjs +3 -1
  29. package/src/runtime/memory/lib/memory-config-flags.mjs +13 -1
  30. package/src/runtime/memory/lib/pg/adapter.mjs +6 -1
  31. package/src/runtime/memory/lib/pg/process.mjs +19 -1
  32. package/src/runtime/memory/lib/pg/supervisor.mjs +125 -14
  33. package/src/runtime/memory/lib/query-handlers.mjs +102 -0
  34. package/src/runtime/memory/lib/recall-format.mjs +60 -22
  35. package/src/runtime/memory/lib/session-ingest-runtime.mjs +20 -6
  36. package/src/runtime/memory/tool-defs.mjs +1 -1
  37. package/src/runtime/shared/child-guardian.mjs +2 -2
  38. package/src/runtime/shared/open-url.mjs +2 -1
  39. package/src/runtime/shared/schedules-db.mjs +350 -0
  40. package/src/runtime/shared/service-discovery.mjs +169 -0
  41. package/src/runtime/shared/spawn-flags.mjs +27 -0
  42. package/src/runtime/shared/tool-primitives.mjs +3 -1
  43. package/src/runtime/shared/tool-surface.mjs +19 -3
  44. package/src/runtime/shared/update-checker.mjs +54 -10
  45. package/src/runtime/shared/webhooks-db.mjs +405 -0
  46. package/src/session-runtime/channel-config-api.mjs +13 -13
  47. package/src/session-runtime/lifecycle-api.mjs +14 -0
  48. package/src/session-runtime/runtime-core.mjs +39 -20
  49. package/src/standalone/agent-tool.mjs +42 -11
  50. package/src/standalone/channel-admin.mjs +173 -121
  51. package/src/standalone/channel-worker.mjs +2 -2
  52. package/src/standalone/memory-runtime-proxy.mjs +10 -5
  53. package/src/tui/App.jsx +32 -10
  54. package/src/tui/app/channel-pickers.mjs +9 -9
  55. package/src/tui/app/clipboard.mjs +14 -0
  56. package/src/tui/app/doctor.mjs +1 -1
  57. package/src/tui/app/maintenance-pickers.mjs +17 -7
  58. package/src/tui/app/settings-picker.mjs +2 -2
  59. package/src/tui/app/transcript-window.mjs +37 -1
  60. package/src/tui/app/use-mouse-input.mjs +19 -6
  61. package/src/tui/components/ToolExecution.jsx +12 -4
  62. package/src/tui/display-width.mjs +10 -4
  63. package/src/tui/dist/index.mjs +129 -55
  64. package/src/tui/engine/session-api-ext.mjs +12 -12
  65. package/src/tui/index.jsx +12 -2
  66. package/src/ui/statusline-segments.mjs +12 -1
  67. package/vendor/ink/build/display-width.js +5 -4
  68. package/src/runtime/shared/schedules-store.mjs +0 -82
@@ -40,6 +40,38 @@ function _pathsOf(arg) {
40
40
  function _normPath(p) { return String(p).replace(/\\/g, '/').toLowerCase(); }
41
41
  function _baseName(p) { const s = _normPath(p); const i = s.lastIndexOf('/'); return i >= 0 ? s.slice(i + 1) : s; }
42
42
  function _dirName(p) { const s = _normPath(p); const i = s.lastIndexOf('/'); return i >= 0 ? s.slice(0, i) : ''; }
43
+ // A path targets a specific file (not a directory scope) when its basename
44
+ // carries a file extension — the signal that a grep was already file-scoped.
45
+ function _isFileScopedPath(p) { return /\.[A-Za-z0-9]{1,12}$/.test(_baseName(p)); }
46
+ // Grep context flag: -C/-A/-B count as context ONLY when > 0. An explicit
47
+ // -C:0 / -A:0 / -B:0 is NO context (bare match lines).
48
+ function _hasGrepContext(a) { return Number(a?.['-A']) > 0 || Number(a?.['-B']) > 0 || Number(a?.['-C']) > 0; }
49
+ // Canonical path segments: normalize slashes/case, drop '.' and resolve '..'
50
+ // so ./ and ../ variants collapse. Used by the abs/rel-tolerant path match.
51
+ function _canonSegs(p) {
52
+ const out = [];
53
+ for (const seg of _normPath(p).split('/')) {
54
+ if (seg === '' || seg === '.') continue;
55
+ if (seg === '..') { if (out.length && out[out.length - 1] !== '..') out.pop(); else out.push('..'); continue; }
56
+ out.push(seg);
57
+ }
58
+ return out;
59
+ }
60
+ function _canonPath(p) { return _canonSegs(p).join('/'); }
61
+ // abs/rel-tolerant same-file test: equal when one canonical path is a
62
+ // segment-aligned suffix of the other (so C:/proj/src/x.mjs, src/x.mjs and
63
+ // ./src/x.mjs all match). Basename equality is implied by the suffix compare.
64
+ function _pathsMatch(a, b) {
65
+ if (!a || !b) return false;
66
+ const A = _canonSegs(a); const B = _canonSegs(b);
67
+ if (!A.length || !B.length) return false;
68
+ const long = A.length >= B.length ? A : B;
69
+ const short = A.length >= B.length ? B : A;
70
+ for (let i = 0; i < short.length; i += 1) {
71
+ if (long[long.length - short.length + i] !== short[i]) return false;
72
+ }
73
+ return true;
74
+ }
43
75
  // Exact (normalized) same-file test — used where "related" is too loose.
44
76
  function _samePath(a, b) { return !!a && !!b && _normPath(a) === _normPath(b); }
45
77
  // Loose sibling/variant relation — cluster detector pairs this WITH token overlap.
@@ -148,6 +180,15 @@ export function createSteeringLadder(ctx) {
148
180
  // same-path regions in ONE call are the recommended batched form and are
149
181
  // never counted. Fires once per path per session.
150
182
  const _readWindowsByPath = new Map();
183
+ // Detector A state: prior turn's file-scoped grep paths that ran WITHOUT
184
+ // any -C/-B/-A context (a bare match-line grep on a specific file). Seeds
185
+ // the grep-no-context-then-read nudge for the next turn.
186
+ let _lastFileScopedGrepNoCtxPaths = null;
187
+ // Detector B state: per-path consecutive-read streak (canonical path ->
188
+ // count). Tracked as a Map so multi-file turns keep independent streaks
189
+ // ([A,B]->B->B fires on B). Files not read this turn are pruned; a path is
190
+ // dropped after it fires.
191
+ const _readStreaks = new Map();
151
192
 
152
193
  // Level-2 steering emitter shared by both ladder paths (single-call
153
194
  // level-1 streak and the independent all-read-only streak). Sets the latch
@@ -178,20 +219,37 @@ export function createSteeringLadder(ctx) {
178
219
  // Steering hint gate: at most ONE hint per turn (priority:
179
220
  // level-2 > grep/shell detectors > level-1).
180
221
  let _hintFiredThisTurn = hintAlreadyFired;
222
+ // Specific-detector predicates (A: grep-no-context then re-read; B:
223
+ // 3rd consecutive same-file read). Evaluated up front so the GENERIC
224
+ // level-1 batching nudge can defer to them (more specific wins),
225
+ // while the level-2 runaway escalation below still outranks them.
226
+ const _readCallsThisTurn = calls.filter((c) => c?.name === 'read');
227
+ const _aWouldFire = !!_lastFileScopedGrepNoCtxPaths
228
+ && _readCallsThisTurn.some((c) => _pathsOf(c?.arguments?.path)
229
+ .some((p) => [..._lastFileScopedGrepNoCtxPaths].some((g) => _pathsMatch(p, g))));
230
+ let _bWouldFire = false;
231
+ for (const c of _readCallsThisTurn) {
232
+ for (const w of _readWindows(c)) {
233
+ for (const [k, cnt] of _readStreaks) { if (cnt >= 2 && _pathsMatch(k, w.path)) { _bWouldFire = true; break; } }
234
+ if (_bWouldFire) break;
235
+ }
236
+ if (_bWouldFire) break;
237
+ }
181
238
  // Missed-parallelism steering: 2+ consecutive turns of a single
182
239
  // read-only tool call suggest the model isn't batching independent
183
240
  // lookups. Nudge once, then reset (fires again after 2 more).
184
241
  if (calls.length === 1 && isEagerDispatchable(calls[0].name, tools)) {
185
242
  _serialReadOnlyStreak += 1;
186
- if (_serialReadOnlyStreak >= 2 && !_hintFiredThisTurn) {
243
+ // Escalation ladder (Step 1). Cumulative level-1 fires are tracked
244
+ // and NEVER reset. Once level-1 has fired >=3 times with ZERO edits,
245
+ // escalate to level-2 steering (latched once per 5 turns). The
246
+ // level-2 escalation always wins; the plain batching nudge instead
247
+ // DEFERS to the specific A/B detectors when either would fire.
248
+ const _canEscalate = (_level1FireCount + 1) >= 3 && editCount === 0 && (iterations - _level2LatchAtIteration) >= 5;
249
+ if (_serialReadOnlyStreak >= 2 && !_hintFiredThisTurn && (_canEscalate || (!_aWouldFire && !_bWouldFire))) {
187
250
  _serialReadOnlyStreak = 0;
188
- // Escalation ladder (Step 1). Cumulative level-1 fires are
189
- // tracked and NEVER reset. Once level-1 has fired >=3 times with
190
- // ZERO edits, escalate to level-2 steering (blocked-report is a
191
- // valid completion) instead of the batching nudge — latched to at
192
- // most once per 5 turns.
193
251
  _level1FireCount += 1;
194
- if (_level1FireCount >= 3 && editCount === 0 && (iterations - _level2LatchAtIteration) >= 5) {
252
+ if (_canEscalate) {
195
253
  _emitLevel2Steer();
196
254
  } else {
197
255
  pushSystemReminder('Last 2 turns each ran a single read-only tool. Batch independent lookups (read/grep/glob/code_graph) into ONE turn, or start editing if you have enough context.');
@@ -303,8 +361,10 @@ export function createSteeringLadder(ctx) {
303
361
  const _next = new Set();
304
362
  for (const c of _grepCalls) {
305
363
  const a = c?.arguments || {};
306
- const _hasCtx = a['-A'] != null || a['-B'] != null || a['-C'] != null;
307
- const _isContent = a.output_mode === 'content' || a.output_mode === 'content_with_context' || _hasCtx;
364
+ // Bare output_mode:'content' WITHOUT real context is routed to
365
+ // Detector A (which gives the add-`-C` advice); this detector
366
+ // only owns greps that actually returned context.
367
+ const _isContent = _hasGrepContext(a) || a.output_mode === 'content_with_context';
308
368
  const _pathsOnly = a.output_mode === 'files_with_matches' || a.output_mode === 'count';
309
369
  const _capped = a.head_limit != null;
310
370
  if (_isContent && !_pathsOnly && !_capped) {
@@ -313,6 +373,55 @@ export function createSteeringLadder(ctx) {
313
373
  }
314
374
  _lastGrepContentPaths = _next.size ? _next : null;
315
375
  }
376
+ // Detector A (fire): a file-scoped grep WITHOUT context last turn,
377
+ // then a read of that same file this turn. Fires ahead of the read-
378
+ // fragmentation / B detectors below; the generic level-1 nudge
379
+ // already deferred to it via _aWouldFire, while the level-2
380
+ // escalation above still outranks it. On pre-emption by an
381
+ // earlier hint, the pending set is kept (not cleared) so A can fire
382
+ // next turn.
383
+ let _aPending = false;
384
+ if (_lastFileScopedGrepNoCtxPaths) {
385
+ const _rp = [];
386
+ for (const c of _readCallsThisTurn) { for (const p of _pathsOf(c?.arguments?.path)) _rp.push(p); }
387
+ const _hit = _rp.find((p) => [..._lastFileScopedGrepNoCtxPaths].some((g) => _pathsMatch(p, g)));
388
+ if (_hit) {
389
+ if (!_hintFiredThisTurn) {
390
+ pushSystemReminder(`You grepped ${_baseName(_hit)} last turn then re-opened it — request context with -C on file-scoped grep so the match window is already on screen.`);
391
+ try {
392
+ appendAgentTrace({
393
+ sessionId,
394
+ iteration: iterations,
395
+ kind: 'steer',
396
+ payload: { tag: 'grep_nocontext_reread', file: _baseName(_hit) },
397
+ agent: sessionAgent || null,
398
+ });
399
+ } catch { /* best-effort */ }
400
+ _hintFiredThisTurn = true;
401
+ _lastFileScopedGrepNoCtxPaths = null;
402
+ } else {
403
+ _aPending = true; // pre-empted this turn — keep pending for next turn
404
+ }
405
+ }
406
+ }
407
+ // Detector A (seed): record this turn's file-scoped greps that ran
408
+ // WITHOUT context so a same-file read next turn triggers the fire
409
+ // block above. When A was pre-empted this turn (_aPending) the
410
+ // existing pending set is kept rather than cleared.
411
+ if (!_aPending) {
412
+ const _next = new Set();
413
+ for (const c of _grepCalls) {
414
+ const a = c?.arguments || {};
415
+ // Exact complement of the content detector's seed: skip greps
416
+ // that carried real context (positive -A/-B/-C) OR ran in
417
+ // content_with_context mode — those belong to that detector.
418
+ if (_hasGrepContext(a) || a.output_mode === 'content_with_context') continue;
419
+ for (const p of _pathsOf(a.path)) {
420
+ if (_isFileScopedPath(p)) _next.add(p);
421
+ }
422
+ }
423
+ _lastFileScopedGrepNoCtxPaths = _next.size ? _next : null;
424
+ }
316
425
  // Detector: read fragmentation — 2nd+ single-window read into the
317
426
  // SAME file with offsets inside an 800-line span means the model is
318
427
  // paging small windows across turns instead of reading one wider
@@ -345,6 +454,50 @@ export function createSteeringLadder(ctx) {
345
454
  }
346
455
  }
347
456
  }
457
+ // Detector B: 3rd consecutive turn reading the SAME file (any
458
+ // window). Per-path streaks in a Map so multi-file turns keep
459
+ // independent counts ([A,B]->B->B fires on B). rel/abs spellings of
460
+ // one file collapse onto a single streak key; files not read this
461
+ // turn are pruned; a path is dropped after it fires.
462
+ {
463
+ // Resolve each read path to one streak key, merging rel/abs
464
+ // spellings against existing keys and keys already seen this turn.
465
+ const _touched = new Set();
466
+ for (const c of calls.filter((x) => x?.name === 'read')) {
467
+ for (const w of _readWindows(c)) {
468
+ let _key = null;
469
+ for (const k of _readStreaks.keys()) { if (_pathsMatch(k, w.path)) { _key = k; break; } }
470
+ if (!_key) { for (const k of _touched) { if (_pathsMatch(k, w.path)) { _key = k; break; } } }
471
+ _touched.add(_key || _canonPath(w.path));
472
+ }
473
+ }
474
+ // Prune streaks for files not read this turn (breaks consecutiveness).
475
+ for (const k of [..._readStreaks.keys()]) { if (!_touched.has(k)) _readStreaks.delete(k); }
476
+ // Increment each file read this turn (once per turn).
477
+ for (const k of _touched) {
478
+ _readStreaks.set(k, (_readStreaks.get(k) || 0) + 1);
479
+ if (_readStreaks.size > 32) _readStreaks.delete(_readStreaks.keys().next().value);
480
+ }
481
+ if (!_hintFiredThisTurn) {
482
+ for (const [k, cnt] of _readStreaks) {
483
+ if (cnt >= 3) {
484
+ pushSystemReminder(`3rd window into ${_baseName(k)} — take the remaining span in ONE wide read (offset+limit) instead of paging.`);
485
+ try {
486
+ appendAgentTrace({
487
+ sessionId,
488
+ iteration: iterations,
489
+ kind: 'steer',
490
+ payload: { tag: 'consecutive_same_file_read', file: _baseName(k) },
491
+ agent: sessionAgent || null,
492
+ });
493
+ } catch { /* best-effort */ }
494
+ _readStreaks.delete(k);
495
+ _hintFiredThisTurn = true;
496
+ break;
497
+ }
498
+ }
499
+ }
500
+ }
348
501
  // Detector: read-only shell (git status/log/diff --stat, ls/dir/cat/
349
502
  // type/Get-ChildItem) inspects state the dedicated tools cover.
350
503
  // Nudge toward them; never blocks execution.
@@ -366,6 +519,8 @@ export function createSteeringLadder(ctx) {
366
519
  _lastGrepContentPaths = null;
367
520
  _identGrepStreak = 0;
368
521
  _identGrepToken = null;
522
+ _lastFileScopedGrepNoCtxPaths = null;
523
+ _readStreaks.clear();
369
524
  },
370
525
  };
371
526
  }
@@ -106,3 +106,48 @@ function _restoreCompactedBodies(tcVal, origVal, key) {
106
106
  }
107
107
  return tcVal;
108
108
  }
109
+
110
+ // Marker prefix emitted by compactStoredToolArgString for every compacted
111
+ // body/long arg (`[mixdog compacted <key>: <N> chars, sha256:…]`). Both the
112
+ // body-only form (marker alone) and the long form (marker + head/tail preview)
113
+ // begin with this exact span.
114
+ const COMPACTED_MARKER_PREFIX = '[mixdog compacted ';
115
+
116
+ function _isCompactedPlaceholderString(v) {
117
+ return typeof v === 'string' && v.startsWith(COMPACTED_MARKER_PREFIX);
118
+ }
119
+
120
+ // Recursively drop every key whose stored value is a compacted-placeholder
121
+ // string, at any depth (batch shapes like edits[].old_string carry nested
122
+ // compacted bodies too). Non-placeholder values are kept verbatim.
123
+ function _dropCompactedPlaceholders(val) {
124
+ if (Array.isArray(val)) return val.map((item) => _dropCompactedPlaceholders(item));
125
+ if (val && typeof val === 'object') {
126
+ const out = {};
127
+ for (const [k, v] of Object.entries(val)) {
128
+ if (_isCompactedPlaceholderString(v)) continue; // drop the key entirely
129
+ out[k] = _dropCompactedPlaceholders(v);
130
+ }
131
+ return out;
132
+ }
133
+ return val;
134
+ }
135
+
136
+ // A SUCCESSFUL tool call's compacted body/long arg (patch / old_string /
137
+ // new_string / content / rewrite / command / script) is never needed again —
138
+ // the edit already applied. compactToolCallsForHistory (run at push time,
139
+ // before the outcome is known) leaves a `[mixdog compacted …]` placeholder in
140
+ // its place. For a success that placeholder persists in the stored assistant
141
+ // tool_use and is transmitted back as a prior apply_patch INPUT, which the
142
+ // model copies verbatim as new patch args — caught by the patch guard, but only
143
+ // after a wasted turn. Drop those placeholder keys so no resubmittable
144
+ // placeholder body survives in history. Failed calls take the opposite path
145
+ // (restoreToolCallBodyForId expands to the full original); success and failure
146
+ // are mutually exclusive per call id, so this never races the restore path.
147
+ // Cache-safe: the caller runs this before the assistant message is transmitted.
148
+ export function dropCompactedBodyArgsForId(assistantMsg, callId) {
149
+ if (!assistantMsg || !Array.isArray(assistantMsg.toolCalls) || !callId) return;
150
+ const tc = assistantMsg.toolCalls.find((t) => t && t.id === callId);
151
+ if (!tc || !tc.arguments || typeof tc.arguments !== 'object') return;
152
+ tc.arguments = _dropCompactedPlaceholders(tc.arguments);
153
+ }
@@ -157,6 +157,10 @@ async function runRecallFastTrackForSession(session, messages, opts = {}) {
157
157
  messages,
158
158
  cwd: session?.cwd,
159
159
  limit: hydrateLimit,
160
+ // Clear/manual-compact path: these rows are about to be summarized
161
+ // away, so skip the bounded 15s synchronous embedding-flush wait —
162
+ // kick the flush fire-and-forget (dense-search immediacy is moot here).
163
+ embedWait: false,
160
164
  }, callerCtx, memoryTimeoutMs);
161
165
  } catch (err) {
162
166
  // Ingest failed (dead/timed-out memory runtime). The transcript is NOT
@@ -30,7 +30,7 @@ import { preDispatchDenyForSession } from './loop/pre-dispatch-deny.mjs';
30
30
  import { executeTool } from './loop/tool-exec.mjs';
31
31
  import { crossTurnSignature, crossTurnDedupStub, isEditProgressTool } from './loop/completion-guards.mjs';
32
32
  import { getToolKind, isEagerDispatchable, parseNativeToolSearchPayload } from './loop/tool-helpers.mjs';
33
- import { restoreToolCallBodyForId } from './loop/stored-tool-args.mjs';
33
+ import { restoreToolCallBodyForId, dropCompactedBodyArgsForId } from './loop/stored-tool-args.mjs';
34
34
 
35
35
  export async function processToolBatch(ctx) {
36
36
  const {
@@ -586,6 +586,17 @@ export async function processToolBatch(ctx) {
586
586
  toolKind: 'error',
587
587
  });
588
588
  }
589
+ // Successful call: its compacted body/long args are never needed
590
+ // again. Drop any `[mixdog compacted …]` placeholder from the stored
591
+ // assistant tool_use so a prior apply_patch INPUT never surfaces a
592
+ // resubmittable placeholder patch body the model copies back verbatim
593
+ // (the patch guard catches it, but only after a wasted turn). Gated on
594
+ // full success + clean post-processing; the failed/post-fail paths run
595
+ // restoreToolCallBodyForId instead (mutually exclusive per call id).
596
+ // Cache-safe: assistantTurnMsg is not transmitted until the next send.
597
+ if (_postProcessOk && _executeOk && _resultKind === 'normal' && call?.id) {
598
+ dropCompactedBodyArgsForId(assistantTurnMsg, call.id);
599
+ }
589
600
  // Soft-cancel after each tool: if close landed during execution,
590
601
  // discard the rest of the batch and skip the next provider.send.
591
602
  throwIfAborted();
@@ -19,6 +19,7 @@ import {
19
19
  getBackgroundTask,
20
20
  } from '../../../../shared/background-tasks.mjs';
21
21
  import { startChildGuardian } from '../../../../shared/child-guardian.mjs';
22
+ import { detachedSpawnOpts } from '../../../../shared/spawn-flags.mjs';
22
23
  import {
23
24
  getShellJobsDir,
24
25
  shellJobStdoutPath,
@@ -828,9 +829,8 @@ function _startBackgroundShellJobImpl({ command, timeoutMs, workDir, mergeStderr
828
829
  const child = spawn(shell, [wrappedTempPath], {
829
830
  cwd: workDir,
830
831
  env: scrubLoaderVars(scrubProviderSecrets({ ...spawnEnv })),
831
- detached: true,
832
832
  stdio: 'ignore',
833
- windowsHide: true,
833
+ ...detachedSpawnOpts,
834
834
  });
835
835
  startChildGuardian({
836
836
  childPid: child.pid,
@@ -129,15 +129,19 @@ export function wrapPowerShellWithCwdProbe(command, stateFile) {
129
129
  // a failing native call $LASTEXITCODE holds its real code (case3 → 7).
130
130
  //
131
131
  // The `if (-not $?)` check MUST be the first statement after the command;
132
- // any intervening statement resets $?. Terminating errors (`throw`) skip to
133
- // catch → $__ec = 1. The cwd probe runs in finally regardless, and we exit
132
+ // any intervening statement resets $?. Terminating errors (`throw`,
133
+ // `-ErrorAction Stop`, .NET exceptions) skip to catch → $__ec = 1. A
134
+ // *caught* terminating error is NOT auto-written to the error stream, so
135
+ // without re-emitting it the caller only sees `[exit code: 1] (no output)`.
136
+ // Re-surface the ErrorRecord on stderr so the failure cause reaches the
137
+ // result envelope. The cwd probe runs in finally regardless, and we exit
134
138
  // with $__ec so the probe never masks the observed code.
135
139
  return '$global:LASTEXITCODE = 0\n'
136
140
  + '$__ec = 0\n'
137
141
  + 'try {\n'
138
142
  + `${command}\n`
139
143
  + ' if (-not $?) { $__ec = if ($LASTEXITCODE) { $LASTEXITCODE } else { 1 } }\n'
140
- + '} catch { $__ec = 1 }\n'
144
+ + '} catch { [Console]::Error.WriteLine(($_ | Out-String).Trim()); $__ec = 1 }\n'
141
145
  + `finally { (Get-Location).Path | Out-File -Encoding utf8 ${qFile} }\n`
142
146
  + 'exit $__ec';
143
147
  }
@@ -3,7 +3,7 @@ import { join } from "path";
3
3
  import { DiscordBackend } from "../backends/discord.mjs";
4
4
  import { TelegramBackend } from "../backends/telegram.mjs";
5
5
  import { readSection, updateSection, CONFIG_PATH as MIXDOG_CONFIG_PATH, getDiscordToken, getTelegramToken, diagnoseDiscordTokenValue } from "../../shared/config.mjs";
6
- import { listSchedules } from "../../shared/schedules-store.mjs";
6
+ import { listSchedules } from "../../shared/schedules-db.mjs";
7
7
  import { resolvePluginData } from "../../shared/plugin-paths.mjs";
8
8
  const DATA_DIR = resolvePluginData();
9
9
  const CONFIG_FILE = MIXDOG_CONFIG_PATH;
@@ -63,19 +63,21 @@ function resolveChannelId(raw = {}, backend = "discord") {
63
63
  return "";
64
64
  }
65
65
 
66
- function loadConfig() {
66
+ async function loadConfig() {
67
67
  try {
68
68
  let raw = readSection("channels");
69
69
  raw = raw && typeof raw === "object" ? raw : {};
70
- // Schedules live in the Mixdog data dir under `schedules/<name>/` (single
71
- // source of truth). The legacy `raw.schedules.items` / `raw.nonInteractive`
72
- // / `raw.interactive` arrays in mixdog-config.json are no longer read.
73
- const scheduleEntries = listSchedules().filter((s) => s.enabled !== false);
74
- // Channel-presence routing (no `type` field): an entry WITH a channel is
75
- // dispatched directly to that channel; an entry WITHOUT a channel is
76
- // injected into the current (Lead) session. Mirrors the webhook model.
77
- raw.nonInteractive = scheduleEntries.filter((i) => !!i.channel);
78
- raw.interactive = scheduleEntries.filter((i) => !i.channel);
70
+ // Schedules are the PG `scheduler.schedules` table (single source of
71
+ // truth). The legacy SCHEDULE.md store and the `raw.schedules.items` /
72
+ // `raw.nonInteractive` / `raw.interactive` arrays in mixdog-config.json
73
+ // are no longer read. Done one-shots are dropped so they never re-arm.
74
+ const scheduleEntries = (await listSchedules())
75
+ .filter((s) => s.enabled !== false && s.status !== "done");
76
+ // `target` drives routing: 'channel' non-interactive dispatch to the
77
+ // schedule's channel_id; 'session' → inject into the current (Lead)
78
+ // session. Mirrors the webhook model.
79
+ raw.nonInteractive = scheduleEntries.filter((s) => s.target === "channel");
80
+ raw.interactive = scheduleEntries.filter((s) => s.target === "session");
79
81
  const accessChannels = { ...raw.access?.channels ?? {} };
80
82
  // voice config lives at the top level of mixdog-config.json (peer of
81
83
  // channels), so readSection("channels") never sees it. Pull it explicitly.
@@ -4,6 +4,7 @@ import os from 'node:os'
4
4
  import path from 'node:path'
5
5
  import { fileURLToPath } from 'node:url'
6
6
  import { createStandaloneMemoryRuntime } from '../../../standalone/memory-runtime-proxy.mjs'
7
+ import { readServicePort, markServiceUnreachable, isConnRefuseError } from '../../shared/service-discovery.mjs'
7
8
 
8
9
  const RUNTIME_ROOT = process.env.MIXDOG_RUNTIME_ROOT
9
10
  ? path.resolve(process.env.MIXDOG_RUNTIME_ROOT)
@@ -60,9 +61,28 @@ function isConnRefusedLike(err) {
60
61
  || /ECONNREFUSED|missing memory_port|memory-service timeout/i.test(msg)
61
62
  }
62
63
 
64
+ // A discovery advert validates only the owner pid, which can be a recycled pid
65
+ // living on an unrelated process while its advertised port is dead. This client
66
+ // has no separate /health probe, so on a connect-level failure we distrust the
67
+ // port: mark it unreachable (readServicePort then skips it → legacy fallback)
68
+ // and drop the port cache so the next getMemoryPort re-resolves.
69
+ function _distrustMemoryPort(port, err) {
70
+ // Connection-level failures ONLY. A 'memory-service timeout' means the daemon
71
+ // is slow-but-alive — distrusting it would false-route to legacy/buffer.
72
+ if (port && isConnRefuseError(err)) {
73
+ markServiceUnreachable('memory', port)
74
+ _portCache = null
75
+ }
76
+ }
77
+
63
78
  async function getMemoryPort() {
64
79
  const now = Date.now()
65
80
  if (_portCache && (now - _portCache.ts) < 5_000) return _portCache.port
81
+ // Prefer the single-writer discovery advert (discovery/memory.json), which
82
+ // validates the owner pid is alive. Fall back to the legacy
83
+ // active-instance.json memory_port field for cross-version compat.
84
+ const advertPort = readServicePort('memory', { requirePid: false })
85
+ if (advertPort) { _portCache = { port: advertPort, mtime: 0, ts: now }; return advertPort }
66
86
  try {
67
87
  const stat = await fs.promises.stat(ACTIVE_INSTANCE_FILE)
68
88
  const mtime = stat.mtimeMs
@@ -115,8 +135,8 @@ async function memoryFetch(method, endpoint, body = null, timeoutMs = 10_000, {
115
135
  resolve(parsed)
116
136
  })
117
137
  })
118
- req.on('error', reject)
119
- req.on('timeout', () => { req.destroy(); reject(new Error('memory-service timeout')) })
138
+ req.on('error', err => { _distrustMemoryPort(port, err); reject(err) })
139
+ req.on('timeout', () => { req.destroy(); const err = new Error('memory-service timeout'); _distrustMemoryPort(port, err); reject(err) })
120
140
  if (payload) req.write(payload)
121
141
  req.end()
122
142
  })
@@ -407,7 +407,7 @@ async function refreshBridgeOwnership(options = {}) {
407
407
  async function reloadRuntimeConfig() {
408
408
  const previousBackend = getBackend();
409
409
  const previousBackendName = previousBackend?.name || "";
410
- setConfig(loadConfig());
410
+ setConfig(await loadConfig());
411
411
  scheduler.reloadConfig(
412
412
  getConfig().nonInteractive ?? [],
413
413
  getConfig().interactive ?? [],