mixdog 0.9.47 → 0.9.50

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 (88) hide show
  1. package/README.md +6 -6
  2. package/package.json +19 -9
  3. package/scripts/agent-parallel-smoke.mjs +4 -1
  4. package/scripts/agent-route-batch-test.mjs +40 -0
  5. package/scripts/code-graph-aggregate-cwd-test.mjs +154 -0
  6. package/scripts/code-graph-description-contract.mjs +185 -0
  7. package/scripts/code-graph-disk-hit-test.mjs +55 -0
  8. package/scripts/code-graph-dispatch-test.mjs +96 -0
  9. package/scripts/compact-pressure-test.mjs +40 -0
  10. package/scripts/deferred-tool-loading-test.mjs +233 -0
  11. package/scripts/embedding-worker-exit-test.mjs +76 -0
  12. package/scripts/execution-completion-dedup-test.mjs +48 -0
  13. package/scripts/explore-prompt-policy-test.mjs +88 -3
  14. package/scripts/live-worker-smoke.mjs +68 -16
  15. package/scripts/memory-core-input-test.mjs +33 -13
  16. package/scripts/native-edit-wire-test.mjs +152 -0
  17. package/scripts/openai-oauth-ws-1006-retry-test.mjs +294 -16
  18. package/scripts/patch-binary-cache-test.mjs +181 -0
  19. package/scripts/prompt-immediate-render-test.mjs +89 -0
  20. package/scripts/provider-toolcall-test.mjs +280 -15
  21. package/scripts/shell-failure-diagnostics-test.mjs +211 -0
  22. package/scripts/smoke-loop.mjs +9 -3
  23. package/scripts/smoke.mjs +5 -106
  24. package/scripts/statusline-quota-hysteresis-test.mjs +26 -1
  25. package/scripts/streaming-tail-window-test.mjs +29 -0
  26. package/scripts/tool-failures.mjs +21 -3
  27. package/scripts/tool-smoke.mjs +263 -38
  28. package/scripts/tool-tui-presentation-test.mjs +17 -1
  29. package/scripts/tui-perf-run.ps1 +26 -0
  30. package/scripts/tui-transcript-perf-test.mjs +7 -1
  31. package/scripts/verify-release-assets-test.mjs +281 -0
  32. package/scripts/verify-release-assets.mjs +293 -0
  33. package/scripts/windows-hide-spawn-options-test.mjs +19 -0
  34. package/src/cli.mjs +1 -0
  35. package/src/runtime/agent/orchestrator/agent-trace-format.mjs +16 -5
  36. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +35 -11
  37. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +35 -11
  38. package/src/runtime/agent/orchestrator/providers/custom-tool-wire.mjs +28 -0
  39. package/src/runtime/agent/orchestrator/providers/openai-compat-wire.mjs +1 -1
  40. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +34 -34
  41. package/src/runtime/agent/orchestrator/providers/openai-oauth.mjs +45 -38
  42. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +36 -11
  43. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +4 -4
  44. package/src/runtime/agent/orchestrator/session/eager-dispatch.mjs +10 -6
  45. package/src/runtime/agent/orchestrator/session/loop/deferred-call-through.mjs +4 -3
  46. package/src/runtime/agent/orchestrator/session/loop/recall-fasttrack.mjs +4 -3
  47. package/src/runtime/agent/orchestrator/session/loop/tool-helpers.mjs +16 -1
  48. package/src/runtime/agent/orchestrator/session/manager/ask-session.mjs +2 -2
  49. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +0 -1
  50. package/src/runtime/agent/orchestrator/session/tool-batch.mjs +13 -8
  51. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +30 -16
  52. package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +25 -8
  53. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +69 -4
  54. package/src/runtime/agent/orchestrator/tools/code-graph-prewarm-worker.mjs +5 -4
  55. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +1 -1
  56. package/src/runtime/agent/orchestrator/tools/graph-manifest.json +12 -12
  57. package/src/runtime/agent/orchestrator/tools/patch/native-server.mjs +12 -7
  58. package/src/runtime/agent/orchestrator/tools/patch-binary-fetcher.mjs +77 -18
  59. package/src/runtime/agent/orchestrator/tools/patch-manifest.json +11 -11
  60. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +99 -24
  61. package/src/runtime/memory/lib/embedding-provider.mjs +3 -2
  62. package/src/runtime/memory/lib/memory-action-handlers.mjs +21 -11
  63. package/src/runtime/memory/tool-defs.mjs +1 -2
  64. package/src/session-runtime/context-status.mjs +25 -16
  65. package/src/session-runtime/model-route-api.mjs +2 -0
  66. package/src/session-runtime/runtime-core.mjs +2 -2
  67. package/src/session-runtime/session-turn-api.mjs +4 -1
  68. package/src/session-runtime/tool-catalog.mjs +113 -19
  69. package/src/session-runtime/tool-defs.mjs +1 -0
  70. package/src/standalone/agent-tool/helpers.mjs +25 -6
  71. package/src/standalone/agent-tool.mjs +75 -41
  72. package/src/tui/App.jsx +4 -0
  73. package/src/tui/app/input-parsers.mjs +8 -9
  74. package/src/tui/components/Markdown.jsx +6 -1
  75. package/src/tui/components/Message.jsx +11 -2
  76. package/src/tui/components/PromptInput.jsx +19 -21
  77. package/src/tui/components/Spinner.jsx +4 -4
  78. package/src/tui/components/StatusLine.jsx +6 -6
  79. package/src/tui/components/TranscriptItem.jsx +2 -2
  80. package/src/tui/components/prompt-input/immediate-render.mjs +47 -0
  81. package/src/tui/components/tool-execution/surface-detail.mjs +14 -9
  82. package/src/tui/dist/index.mjs +130 -45
  83. package/src/tui/engine/agent-job-feed.mjs +21 -2
  84. package/src/tui/engine/turn.mjs +12 -1
  85. package/src/tui/markdown/measure-rendered-rows.mjs +1 -1
  86. package/src/tui/markdown/streaming-markdown.mjs +20 -0
  87. package/src/ui/statusline.mjs +5 -5
  88. package/src/vendor/statusline/src/gateway/session-routes.mjs +22 -10
@@ -19,6 +19,10 @@ const root = mkdtempSync(join(tmpdir(), 'mixdog-live-worker-'));
19
19
  const dataDir = join(root, '.mixdog-data');
20
20
  let activeAsks = 0;
21
21
  let maxActiveAsks = 0;
22
+ let releaseBusyGate = null;
23
+ let busySafetyTimer = null;
24
+ let agentRunner = null;
25
+ let runnerClosed = false;
22
26
 
23
27
  function assert(condition, message) {
24
28
  if (!condition) throw new Error(message);
@@ -28,6 +32,33 @@ function sleep(ms) {
28
32
  return new Promise((resolve) => setTimeout(resolve, ms));
29
33
  }
30
34
 
35
+ function waitForBusyRelease() {
36
+ return new Promise((resolve) => {
37
+ const release = () => {
38
+ if (busySafetyTimer) clearTimeout(busySafetyTimer);
39
+ busySafetyTimer = null;
40
+ if (releaseBusyGate === release) releaseBusyGate = null;
41
+ resolve();
42
+ };
43
+ releaseBusyGate = release;
44
+ busySafetyTimer = setTimeout(release, 10_000);
45
+ });
46
+ }
47
+
48
+ function releaseBusyWorker() {
49
+ const release = releaseBusyGate;
50
+ releaseBusyGate = null;
51
+ if (busySafetyTimer) clearTimeout(busySafetyTimer);
52
+ busySafetyTimer = null;
53
+ release?.();
54
+ }
55
+
56
+ function closeAgentRunner() {
57
+ if (!agentRunner || runnerClosed) return;
58
+ runnerClosed = true;
59
+ agentRunner.closeAll('live-worker-smoke-end');
60
+ }
61
+
31
62
  function taskId(text) {
32
63
  return String(text).match(/agent task: (\S+)/)?.[1] || null;
33
64
  }
@@ -45,13 +76,16 @@ async function main() {
45
76
  .split(/[.!?]\s+|;|,\s+(?=(?:but|however|yet)\b)/)
46
77
  .some((clause) => {
47
78
  const hasReview = /\b(review|reviewer|verification)\b/.test(clause);
48
- const hasSkip = /\b(skip|skipping|skipped|omit|omits|omitting|omitted)\b/.test(clause) ||
79
+ const hasSkip = /\b(skip|skipping|skipped|skippable|omit|omits|omitting|omitted)\b/.test(clause) ||
49
80
  /\bwithout\s+(?:any\s+)?(?:a\s+)?(?:review|reviewer|verification)\b/.test(clause);
50
- const negated = /\b(?:never|(?:must|shall|may)\s+not|can(?:not|'t)|do\s+not|don't|not)\b[^;]{0,40}\b(?:skip|skipping|skipped|omit|omitting|omitted)\b/.test(clause) ||
51
- /\b(?:skip|skipping|skipped|omit|omitting|omitted)\b[^;]{0,40}\b(?:not allowed|forbidden|prohibited)\b/.test(clause) ||
81
+ const weakRequirement = /\b(?:optional|unnecessary|not required|need not)\b/.test(clause);
82
+ const negated = /\b(?:never|(?:must|shall|may)\s+not|can(?:not|'t)|do\s+not|don't|not)\b[^;]{0,40}\b(?:skip|skipping|skipped|skippable|omit|omitting|omitted)\b/.test(clause) ||
83
+ /\b(?:skip|skipping|skipped|skippable|omit|omitting|omitted)\b[^;]{0,40}\b(?:not allowed|forbidden|prohibited)\b/.test(clause) ||
52
84
  /\b(?:never|(?:must|shall|may)\s+not|can(?:not|'t)|do\s+not|don't|not)\b[^;]{0,40}\bwithout\s+(?:any\s+)?(?:a\s+)?(?:review|reviewer|verification)\b/.test(clause);
85
+ const negatedWeakRequirement = /\b(?:not|never)\s+(?:optional|unnecessary)\b/.test(clause);
53
86
  const exception = /\b(?:unless|except(?:\s+when)?|only\s+if)\b/.test(clause);
54
- return hasReview && hasSkip && (!negated || exception);
87
+ return hasReview && ((hasSkip && (!negated || exception)) ||
88
+ (weakRequirement && (!negatedWeakRequirement || exception)));
55
89
  });
56
90
  for (const [phrase, expected] of [
57
91
  ['Never skip Reviewer verification', false],
@@ -63,16 +97,24 @@ async function main() {
63
97
  ['Never skip review only if low-risk', true],
64
98
  ['May omit review', true],
65
99
  ['Proceed without review', true],
100
+ ['Review is optional', true],
101
+ ['Review is unnecessary', true],
102
+ ['Review is not required', true],
103
+ ['Review is skippable for low-risk work', true],
104
+ ['Review is not optional', false],
105
+ ['Review is not unnecessary', false],
66
106
  ]) assert(reviewSkipViolation(phrase) === expected, `review-skip detector case failed: ${phrase}`);
67
107
  const skipsReview = reviewSkipViolation(workflow);
68
108
  assert(hasAll(lead, 'write-role agents self-verify', 'cross-scope verification', 'benches', 'all git', 'current project/workspace'), 'lead tool rules must preserve verification, git, and workspace ownership');
69
- assert(hasAll(workflow, 'after approval', 'delegate', 'by default'), 'default workflow must delegate after approval');
70
- assert(hasAll(workflow, 'coordinates', 'git', '1-edit', '1-check'), 'default workflow must limit Lead direct work');
71
- assert(hasAll(workflow, 'implementation/research/debugging', 'matching agent'), 'default workflow must route other work to matching agents');
72
- assert(hasAll(workflow, 'parallel', 'independent', 'every delegated implementation'), 'workflow rules must keep independent work parallel');
73
- assert(hasAll(workflow, 'every delegated implementation', 'reviewer', 'lead integration', 'fix', 're-verify'), 'default workflow must require review and the fix loop');
109
+ assert(hasAll(workflow, 'before the user explicitly approves the latest plan', 'no edits, no state mutation, no delegation'), 'default workflow must require latest-plan approval before work');
110
+ assert(hasAll(workflow, 'on approval, fan out at maximum width', 'one agent per independent scope', 'all spawned in one turn'), 'default workflow must fan out independent scopes at maximum width');
111
+ assert(hasAll(workflow, 'simple, well-understood implementation goes to worker', 'complex or investigative implementation goes to heavy worker', 'lead itself edits only a local, one-turn configuration/git change', 'debugger only on a defect needing deep root-cause analysis or a bug surviving 2+ review/fix cycles'), 'default workflow must enforce role routing and Lead/Debugger limits');
112
+ assert(hasAll(workflow, 'every implementation gets its own reviewer, attached per scope', 'only the local lead-direct edits above are exempt', 'lead itself edits only a local, one-turn configuration/git change', 'keep the same reviewer through the fix loop', 'fix -> re-verify until clean', 'lead cross-verifies'), 'default workflow must require a Reviewer for every implementation except local Lead-direct one-turn config/git edits');
113
+ assert(hasAll(workflow, 'build, deploy, commit, and push happen only on an explicit user request', 'on direction change, pause and re-consult the user'), 'default workflow must require user authorization and re-consultation');
74
114
  assert(!skipsReview, 'default workflow must not permit delegated-review skips');
75
- assert(hasAll(solo, 'never spawn', 'send', 'delegate', 'ask agents'), 'Solo workflow must forbid delegation');
115
+ assert(hasAll(solo, 'before the user explicitly approves the latest plan', 'read-only investigation and planning — no edits, no state mutation', 'a new or changed request resets planning; a scope change requires fresh approval'), 'Solo workflow must require latest-plan approval and reset it for request or scope changes');
116
+ assert(hasAll(solo, 'on approval, lead executes all work itself', 'never spawn, send, or delegate to agents', 'verify directly: check and fix until clean, or report the blocker'), 'Solo workflow must keep work with Lead, forbid delegation, and verify directly');
117
+ assert(hasAll(solo, 'build, deploy, commit, and push happen only on an explicit user request', 'on direction change, pause and re-consult the user'), 'Solo workflow must require user authorization and re-consultation');
76
118
  assert(/always start background tasks/i.test(AGENT_TOOL.description || '') && /distinct tags?/i.test(AGENT_TOOL.description || '') && /completion notification/i.test(AGENT_TOOL.description || ''), 'agent tool description must expose async parallel tags');
77
119
 
78
120
  mkdirSync(dataDir, { recursive: true });
@@ -112,7 +154,7 @@ async function main() {
112
154
  maxActiveAsks = Math.max(maxActiveAsks, activeAsks);
113
155
  try {
114
156
  if (/parallel slow/i.test(prompt)) await sleep(600);
115
- if (/long busy/i.test(prompt)) await sleep(350);
157
+ if (/long busy/i.test(prompt)) await waitForBusyRelease();
116
158
  if (/write implementation/i.test(prompt)) {
117
159
  const out = await executePatchTool('apply_patch', {
118
160
  base_path: cwdOverride,
@@ -163,7 +205,7 @@ async function main() {
163
205
  getSessionLastProgressAt,
164
206
  askSession: fakeAskSession,
165
207
  };
166
- const agentRunner = createStandaloneAgent({ cfgMod, reg, mgr, dataDir, cwd: root, defaultMode: 'async' });
208
+ agentRunner = createStandaloneAgent({ cfgMod, reg, mgr, dataDir, cwd: root, defaultMode: 'async' });
167
209
 
168
210
  async function waitJob(out, pattern, label) {
169
211
  const id = taskId(out);
@@ -180,10 +222,11 @@ async function main() {
180
222
 
181
223
  async function waitAgentTag(tag, label) {
182
224
  for (let i = 0; i < 20; i += 1) {
183
- if (listSessions().some((session) => session?.agentTag === tag && !session.closed)) return;
225
+ if (agentRunner.getStatus({ cwd: root }).workers
226
+ .some((worker) => worker?.tag === tag && worker.status === 'running')) return;
184
227
  await sleep(25);
185
228
  }
186
- throw new Error(`${label} did not register agent tag ${tag}`);
229
+ throw new Error(`${label} did not start agent tag ${tag}`);
187
230
  }
188
231
 
189
232
  const spawnOut = await agentRunner.execute({
@@ -265,17 +308,26 @@ async function main() {
265
308
  message: 'follow-up while still busy',
266
309
  }, { invocationSource: 'model-tool', cwd: root });
267
310
  assert(/agent message queued/.test(queued), `busy send should queue, got ${queued}`);
311
+ releaseBusyWorker();
268
312
  await waitJob(busyOut, /ack worker/, 'busy worker');
269
313
 
270
314
  const missing = await agentRunner.execute({ type: 'read', task_id: 'task_missing_live_smoke' }, { invocationSource: 'model-tool', cwd: root });
271
315
  assert(/^Error[\s:[]/.test(missing), 'missing agent task should be Error result');
272
316
  assert(readFileSync(join(root, 'feature.txt'), 'utf8').includes('beta from worker'), 'final file missing worker edit');
273
- agentRunner.closeAll('live-worker-smoke-end');
317
+ closeAgentRunner();
274
318
  process.stdout.write('live worker smoke passed\n');
275
319
  }
276
320
 
277
321
  try {
278
322
  await main();
279
323
  } finally {
280
- rmSync(root, { recursive: true, force: true });
324
+ try {
325
+ releaseBusyWorker();
326
+ } finally {
327
+ try {
328
+ closeAgentRunner();
329
+ } finally {
330
+ rmSync(root, { recursive: true, force: true });
331
+ }
332
+ }
281
333
  }
@@ -5,16 +5,27 @@ import { tmpdir } from 'node:os'
5
5
  import { join } from 'node:path'
6
6
  import { normalizeCoreInput } from '../src/runtime/memory/lib/core-memory-store.mjs'
7
7
  import { createMemoryActionHandlers } from '../src/runtime/memory/lib/memory-action-handlers.mjs'
8
+ import { TOOL_DEFS as MEMORY_TOOL_DEFS } from '../src/runtime/memory/tool-defs.mjs'
9
+ import { parseMemoryCandidateRows, parseMemoryCoreRows } from '../src/tui/app/input-parsers.mjs'
8
10
 
9
- test('core content aliases summary and derives a bounded element', () => {
11
+ test('memory mutation schema omits category while recall keeps its internal filter', () => {
12
+ const memoryTool = MEMORY_TOOL_DEFS.find((tool) => tool.name === 'memory')
13
+ const recallTool = MEMORY_TOOL_DEFS.find((tool) => tool.name === 'recall')
14
+ assert.equal(Object.hasOwn(memoryTool.inputSchema.properties, 'category'), false)
15
+ assert.doesNotMatch(memoryTool.description, /category/i)
16
+ assert.equal(Object.hasOwn(recallTool.inputSchema.properties, 'category'), true)
17
+ })
18
+
19
+ test('core content aliases summary, derives an element, and accepts no category', () => {
10
20
  const content = 'A durable preference that callers should receive concise answers.'
11
- const input = normalizeCoreInput({ content, category: 'preference' }, {
21
+ const input = normalizeCoreInput({ content }, {
12
22
  requireElement: true,
13
23
  requireSummary: true,
14
- requireCategory: true,
24
+ requireCategory: false,
15
25
  })
16
26
  assert.equal(input.summary, content)
17
27
  assert.equal(input.element, content.slice(0, 40))
28
+ assert.equal(input.category, 'fact')
18
29
  assert.deepEqual(input.errors, [])
19
30
  })
20
31
 
@@ -34,12 +45,11 @@ test('core add reports every invalid field and cwd project hint together', async
34
45
  cwd,
35
46
  element: 'x'.repeat(41),
36
47
  summary: 'y'.repeat(101),
37
- category: 'unknown',
38
48
  })
39
49
  assert.equal(result.isError, true)
40
50
  assert.equal(
41
51
  result.text,
42
- 'core add: project_id required — pass "common" for COMMON pool, or project slug like "owner/repo" for scoped pool (cwd suggests "owner/repo"); element too long (41/40 chars, remove 1); summary too long (101/100 chars, remove 1); invalid category "unknown". Valid: rule, constraint, decision, fact, goal, preference, task, issue',
52
+ 'core add: project_id required — pass "common" for COMMON pool, or project slug like "owner/repo" for scoped pool (cwd suggests "owner/repo"); element too long (41/40 chars, remove 1); summary too long (101/100 chars, remove 1)',
43
53
  )
44
54
  } finally {
45
55
  await rm(cwd, { recursive: true, force: true })
@@ -58,13 +68,11 @@ test('core add rejects blank project_id in the batched error', async () => {
58
68
  project_id: ' ',
59
69
  element: 'x'.repeat(41),
60
70
  summary: 'y'.repeat(101),
61
- category: 'unknown',
62
71
  })
63
72
  assert.equal(result.isError, true)
64
73
  assert.match(result.text, /^core add: project_id required —/)
65
74
  assert.match(result.text, /element too long \(41\/40 chars, remove 1\)/)
66
75
  assert.match(result.text, /summary too long \(101\/100 chars, remove 1\)/)
67
- assert.match(result.text, /invalid category "unknown"/)
68
76
  })
69
77
 
70
78
  test('core add folds project_id "*" into the batched error', async () => {
@@ -79,12 +87,10 @@ test('core add folds project_id "*" into the batched error', async () => {
79
87
  project_id: '*',
80
88
  element: 'x'.repeat(41),
81
89
  summary: 'y'.repeat(101),
82
- category: 'unknown',
83
90
  })
84
91
  assert.equal(result.isError, true)
85
92
  assert.match(result.text, /^core add: project_id "\*" only valid for op="list"; element too long/)
86
93
  assert.match(result.text, /summary too long \(101\/100 chars, remove 1\)/)
87
- assert.match(result.text, /invalid category "unknown"/)
88
94
  })
89
95
 
90
96
  test('core add suppresses malformed cwd project hints', async () => {
@@ -103,7 +109,6 @@ test('core add suppresses malformed cwd project hints', async () => {
103
109
  cwd,
104
110
  element: 'durable preference',
105
111
  summary: 'Callers prefer concise answers.',
106
- category: 'preference',
107
112
  })
108
113
  assert.equal(result.text, 'core add: project_id required — pass "common" for COMMON pool, or project slug like "owner/repo" for scoped pool')
109
114
  } finally {
@@ -119,7 +124,7 @@ test('core edit by id succeeds without project_id', async () => {
119
124
  readMainConfig: () => ({}),
120
125
  editCoreImpl: async (dataDir, id, patch) => {
121
126
  call = { dataDir, id, patch }
122
- return { id: Number(id), element: patch.element, summary: patch.summary, category: patch.category }
127
+ return { id: Number(id), element: patch.element, summary: patch.summary, category: 'preference' }
123
128
  },
124
129
  })
125
130
  const result = await handleMemoryAction({
@@ -128,10 +133,25 @@ test('core edit by id succeeds without project_id', async () => {
128
133
  id: 7,
129
134
  element: 'reply style',
130
135
  summary: 'Use concise answers.',
131
- category: 'preference',
132
136
  })
133
137
  assert.equal(result.isError, undefined)
134
- assert.equal(result.text, 'core edited (id=7): [preference] reply style — Use concise answers.')
138
+ assert.equal(result.text, 'core edited (id=7): reply style — Use concise answers.')
135
139
  assert.equal(call.id, 7)
136
140
  assert.equal(call.patch.project_id, undefined)
141
+ assert.equal(call.patch.category, undefined)
142
+ })
143
+
144
+ test('category-free core and candidate rows remain selectable in the TUI', () => {
145
+ const [core] = parseMemoryCoreRows('COMMON:\nid=7 reply style — Use concise answers.')
146
+ assert.equal(core._id, 7)
147
+ assert.equal(core._element, 'reply style')
148
+ assert.equal(core._summary, 'Use concise answers.')
149
+ assert.equal(Object.hasOwn(core, '_category'), false)
150
+
151
+ const [candidate] = parseMemoryCandidateRows(
152
+ 'id=9 project=COMMON score=1.60 coding agent refs — Use C:\\Project\\refs. (durable)',
153
+ )
154
+ assert.equal(candidate._id, 9)
155
+ assert.equal(candidate.label, '#9 coding agent refs')
156
+ assert.equal(candidate._projectId, null)
137
157
  })
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ import assert from 'node:assert/strict';
3
+ import { spawn } from 'node:child_process';
4
+ import { createHash } from 'node:crypto';
5
+ import { once } from 'node:events';
6
+ import {
7
+ existsSync,
8
+ mkdtempSync,
9
+ readFileSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from 'node:fs';
13
+ import { tmpdir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ import test from 'node:test';
16
+ import {
17
+ closeNativePatchServerForTests,
18
+ runServerEdit,
19
+ } from '../src/runtime/agent/orchestrator/tools/patch.mjs';
20
+
21
+ const binary = process.env.MIXDOG_EDIT_NATIVE_BIN;
22
+ assert.ok(binary, 'MIXDOG_EDIT_NATIVE_BIN must point to the release mixdog-patch binary');
23
+ assert.ok(existsSync(binary), `native EDIT test binary does not exist: ${binary}`);
24
+
25
+ const responseFields = [
26
+ 'replacements',
27
+ 'readMs',
28
+ 'applyMs',
29
+ 'writeMs',
30
+ 'totalMs',
31
+ 'tier',
32
+ 'contentHash',
33
+ 'roundtripMs',
34
+ ];
35
+
36
+ function digest(content) {
37
+ return createHash('sha256').update(content).digest('hex');
38
+ }
39
+
40
+ function assertCompleteResponse(response, { replacements, tier, content }) {
41
+ assert.deepEqual(Object.keys(response), responseFields, 'EDIT response must expose all eight decoded fields');
42
+ assert.equal(response.replacements, replacements);
43
+ assert.equal(response.tier, tier);
44
+ assert.match(response.contentHash, /^[a-f0-9]{64}$/);
45
+ assert.equal(response.contentHash, digest(content), 'EDIT response hash must describe the resulting bytes');
46
+ for (const field of ['readMs', 'applyMs', 'writeMs', 'totalMs', 'roundtripMs']) {
47
+ assert.ok(Number.isFinite(response[field]) && response[field] >= 0, `${field} must be a non-negative number`);
48
+ }
49
+ }
50
+
51
+ function edit(fullPath, oldString, newString, options = {}) {
52
+ return runServerEdit({
53
+ fullPath,
54
+ oldBuf: Buffer.from(oldString, 'utf8'),
55
+ newBuf: Buffer.from(newString, 'utf8'),
56
+ ...options,
57
+ });
58
+ }
59
+
60
+ async function rawEdit(fullPath, oldString, newString, { replaceAll = false, dryRun = false } = {}) {
61
+ const pathBuf = Buffer.from(fullPath, 'utf8');
62
+ const oldBuf = Buffer.from(oldString, 'utf8');
63
+ const newBuf = Buffer.from(newString, 'utf8');
64
+ const child = spawn(binary, ['--server'], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
65
+ const stdout = [];
66
+ const stderr = [];
67
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
68
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
69
+ child.stdin.end(Buffer.concat([
70
+ Buffer.from(`EDIT ${pathBuf.length} ${oldBuf.length} ${newBuf.length} ${replaceAll ? 1 : 0} ${dryRun ? 1 : 0}\n`),
71
+ pathBuf,
72
+ oldBuf,
73
+ newBuf,
74
+ Buffer.from('QUIT\n'),
75
+ ]));
76
+ const [code] = await once(child, 'exit');
77
+ assert.equal(code, 0, `raw native EDIT server failed: ${Buffer.concat(stderr).toString('utf8')}`);
78
+ return Buffer.concat(stdout).toString('utf8').trimEnd();
79
+ }
80
+
81
+ function assertRawResponse(line) {
82
+ const fields = line.split('\t');
83
+ assert.equal(fields.length, 8, 'raw EDIT response must contain exactly eight tab-delimited fields');
84
+ assert.equal(fields[0], 'OK');
85
+ for (const index of [2, 3, 4, 5]) {
86
+ assert.notEqual(fields[index], '', `raw EDIT timing field ${index} must be present`);
87
+ assert.match(fields[index], /^\d+(?:\.\d+)?$/, `raw EDIT timing field ${index} must be numeric`);
88
+ }
89
+ }
90
+
91
+ test('native EDIT production wire path preserves matching and response invariants', async (t) => {
92
+ const root = mkdtempSync(join(tmpdir(), 'mixdog-native-edit-wire-'));
93
+ try {
94
+ await t.test('rejects ambiguity, then reports the replace-all repeat count and full response', async () => {
95
+ const path = join(root, 'repeats.txt');
96
+ writeFileSync(path, 'token token token\n', 'utf8');
97
+
98
+ await assert.rejects(
99
+ edit(path, 'token', 'value'),
100
+ (error) => {
101
+ assert.equal(error.message, 'old_string found 3 times');
102
+ return true;
103
+ },
104
+ );
105
+ assert.equal(readFileSync(path, 'utf8'), 'token token token\n');
106
+
107
+ const expected = 'value value value\n';
108
+ assertRawResponse(await rawEdit(path, 'token', 'value', { replaceAll: true, dryRun: true }));
109
+ const response = await edit(path, 'token', 'value', { replaceAll: true });
110
+ assert.equal(readFileSync(path, 'utf8'), expected);
111
+ assertCompleteResponse(response, { replacements: 3, tier: 'exact', content: expected });
112
+ });
113
+
114
+ await t.test('rejects a 30-line folded match without writing', async () => {
115
+ const path = join(root, 'folded-30.txt');
116
+ const source = Array.from({ length: 30 }, (_, i) => `line ${i + 1} “value”`).join('\n');
117
+ const foldedNeedle = Array.from({ length: 30 }, (_, i) => `line ${i + 1} "value"`).join('\n');
118
+ writeFileSync(path, source, 'utf8');
119
+
120
+ await assert.rejects(
121
+ edit(path, foldedNeedle, 'unsafe replacement'),
122
+ /old_string is 30 lines \(>= 30\)\./,
123
+ );
124
+ assert.equal(readFileSync(path, 'utf8'), source);
125
+ });
126
+
127
+ await t.test('absorbs the deleted line newline', async () => {
128
+ const path = join(root, 'delete-crlf.txt');
129
+ const source = 'keep\r\ndelete me\r\nafter\r\n';
130
+ const expected = 'keep\r\nafter\r\n';
131
+ writeFileSync(path, source, 'utf8');
132
+
133
+ const response = await edit(path, 'delete me', '');
134
+ assert.equal(readFileSync(path, 'utf8'), expected);
135
+ assertCompleteResponse(response, { replacements: 1, tier: 'exact', content: expected });
136
+ });
137
+
138
+ await t.test('preserves CRLF while lowering an LF-authored replacement', async () => {
139
+ const path = join(root, 'preserve-crlf.txt');
140
+ const source = 'head\r\nold a\r\nold b\r\ntail\r\n';
141
+ const expected = 'head\r\nnew a\r\nnew b\r\ntail\r\n';
142
+ writeFileSync(path, source, 'utf8');
143
+
144
+ const response = await edit(path, 'old a\nold b', 'new a\nnew b');
145
+ assert.equal(readFileSync(path, 'utf8'), expected);
146
+ assertCompleteResponse(response, { replacements: 1, tier: 'crlf', content: expected });
147
+ });
148
+ } finally {
149
+ await closeNativePatchServerForTests();
150
+ rmSync(root, { recursive: true, force: true });
151
+ }
152
+ });