mixdog 0.9.147 → 0.9.148

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 (255) hide show
  1. package/package.json +23 -3
  2. package/scripts/build-voice-runtime-unix.sh +101 -0
  3. package/scripts/embedding-quality-probe.mjs +96 -0
  4. package/scripts/generate-voice-runtime-manifest.mjs +300 -0
  5. package/scripts/generate-voice-runtime-manifest.test.mjs +135 -0
  6. package/scripts/native-binary-arch.mjs +30 -13
  7. package/scripts/native-binary-arch.test.mjs +40 -4
  8. package/scripts/plan-voice-runtime-release.mjs +73 -0
  9. package/scripts/prepare-native-assets.mjs +50 -9
  10. package/scripts/prune-embedding-runtime.mjs +3 -3
  11. package/scripts/sync-voice-runtime-manifest.mjs +46 -0
  12. package/scripts/verify-release-assets.mjs +106 -6
  13. package/scripts/verify-voice-runtime-release.mjs +89 -0
  14. package/scripts/voice-runtime-config.json +52 -0
  15. package/src/app.mjs +42 -5
  16. package/src/headless-exec.mjs +58 -32
  17. package/src/headless-exec.test.mjs +74 -13
  18. package/src/rules/lead/01-general.md +2 -0
  19. package/src/rules/shared/10-tool-workflow.md +7 -4
  20. package/src/rules/shared/30-exploration.md +2 -1
  21. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +28 -9
  22. package/src/runtime/agent/orchestrator/agent-trace-format.mjs +6 -1
  23. package/src/runtime/agent/orchestrator/config.mjs +53 -18
  24. package/src/runtime/agent/orchestrator/mcp/cancellation.test.mjs +139 -0
  25. package/src/runtime/agent/orchestrator/mcp/child-tree.mjs +34 -5
  26. package/src/runtime/agent/orchestrator/mcp/client.mjs +94 -10
  27. package/src/runtime/agent/orchestrator/providers/anthropic-betas.mjs +5 -0
  28. package/src/runtime/agent/orchestrator/providers/anthropic-fast-mode.mjs +98 -0
  29. package/src/runtime/agent/orchestrator/providers/anthropic-fast-mode.test.mjs +90 -0
  30. package/src/runtime/agent/orchestrator/providers/anthropic-leaked-toolcall.mjs +67 -16
  31. package/src/runtime/agent/orchestrator/providers/anthropic-messages.mjs +4 -82
  32. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-credentials.mjs +0 -5
  33. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +62 -121
  34. package/src/runtime/agent/orchestrator/providers/anthropic-server-fallback.mjs +48 -0
  35. package/src/runtime/agent/orchestrator/providers/anthropic-server-fallback.test.mjs +215 -0
  36. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +44 -48
  37. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +54 -31
  38. package/src/runtime/agent/orchestrator/providers/antigravity-oauth.mjs +56 -2
  39. package/src/runtime/agent/orchestrator/providers/cursor-auth.mjs +34 -2
  40. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +61 -1
  41. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +6 -1
  42. package/src/runtime/agent/orchestrator/providers/gemini.mjs +61 -15
  43. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +120 -1
  44. package/src/runtime/agent/orchestrator/providers/lib/env-utils.mjs +9 -0
  45. package/src/runtime/agent/orchestrator/providers/lib/stream-outcome.mjs +0 -3
  46. package/src/runtime/agent/orchestrator/providers/oauth-credential-probes.mjs +187 -84
  47. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +36 -36
  48. package/src/runtime/agent/orchestrator/providers/openai-compat-wire.mjs +16 -6
  49. package/src/runtime/agent/orchestrator/providers/openai-compat-xai.mjs +50 -213
  50. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +135 -126
  51. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +17 -11
  52. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +20 -7
  53. package/src/runtime/agent/orchestrator/providers/openai-ws-delta.mjs +11 -0
  54. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +132 -42
  55. package/src/runtime/agent/orchestrator/providers/openai-ws-stream.mjs +2 -2
  56. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +28 -10
  57. package/src/runtime/agent/orchestrator/providers/registry.mjs +122 -95
  58. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +58 -3
  59. package/src/runtime/agent/orchestrator/providers/tool-stream-state.mjs +4 -22
  60. package/src/runtime/agent/orchestrator/session/agent-loop.mjs +7 -14
  61. package/src/runtime/agent/orchestrator/session/compact-policy.test.mjs +128 -0
  62. package/src/runtime/agent/orchestrator/session/context-compaction-policy.mjs +5 -0
  63. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +27 -48
  64. package/src/runtime/agent/orchestrator/session/loop/steering.mjs +19 -14
  65. package/src/runtime/agent/orchestrator/session/loop/stored-tool-args.mjs +9 -43
  66. package/src/runtime/agent/orchestrator/session/loop/tool-exec.mjs +5 -1
  67. package/src/runtime/agent/orchestrator/session/manager/compaction-runner.mjs +15 -2
  68. package/src/runtime/agent/orchestrator/session/manager/pending-messages-persistence.test.mjs +325 -0
  69. package/src/runtime/agent/orchestrator/session/manager/pending-messages.mjs +599 -195
  70. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +22 -0
  71. package/src/runtime/agent/orchestrator/session/manager/session-crud.mjs +9 -2
  72. package/src/runtime/agent/orchestrator/session/manager.mjs +3 -0
  73. package/src/runtime/agent/orchestrator/session/pre-send-compact.mjs +26 -16
  74. package/src/runtime/agent/orchestrator/session/send-with-recovery.mjs +23 -11
  75. package/src/runtime/agent/orchestrator/session/store-summary-reader.mjs +118 -3
  76. package/src/runtime/agent/orchestrator/session/store-summary-reader.test.mjs +332 -0
  77. package/src/runtime/agent/orchestrator/session/store.mjs +38 -1
  78. package/src/runtime/agent/orchestrator/tools/builtin/advisory-lock.mjs +27 -6
  79. package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +12 -20
  80. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +291 -128
  81. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +45 -8
  82. package/src/runtime/agent/orchestrator/tools/builtin/edit-encoding-eol.test.mjs +224 -0
  83. package/src/runtime/agent/orchestrator/tools/builtin/edit-sequential-occupation.test.mjs +53 -3
  84. package/src/runtime/agent/orchestrator/tools/builtin/external-tool-adapters.mjs +255 -25
  85. package/src/runtime/agent/orchestrator/tools/builtin/find-search-budget.test.mjs +87 -0
  86. package/src/runtime/agent/orchestrator/tools/builtin/git-command-policy.mjs +1 -1
  87. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.mjs +132 -9
  88. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.test.mjs +10 -0
  89. package/src/runtime/agent/orchestrator/tools/builtin/lib/grep-pattern-fanout.mjs +29 -3
  90. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-job-records.mjs +1 -1
  91. package/src/runtime/agent/orchestrator/tools/builtin/list-tool.mjs +178 -29
  92. package/src/runtime/agent/orchestrator/tools/builtin/local-search-telemetry.mjs +4 -1
  93. package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +32 -5
  94. package/src/runtime/agent/orchestrator/tools/builtin/native-search-health.test.mjs +5 -2
  95. package/src/runtime/agent/orchestrator/tools/builtin/native-search-runner.mjs +10 -1
  96. package/src/runtime/agent/orchestrator/tools/builtin/read-batch.mjs +38 -10
  97. package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +12 -0
  98. package/src/runtime/agent/orchestrator/tools/builtin/read-snapshot-runtime.mjs +31 -1
  99. package/src/runtime/agent/orchestrator/tools/builtin/read-tool.mjs +11 -1
  100. package/src/runtime/agent/orchestrator/tools/builtin/read-windows.mjs +22 -4
  101. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +6 -8
  102. package/src/runtime/agent/orchestrator/tools/builtin/shell-analysis.mjs +25 -24
  103. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +152 -133
  104. package/src/runtime/agent/orchestrator/tools/builtin/task-tool.mjs +114 -42
  105. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +129 -15
  106. package/src/runtime/agent/orchestrator/tools/code-graph/loose-file-target.test.mjs +72 -0
  107. package/src/runtime/agent/orchestrator/tools/code-graph/project-root.mjs +7 -8
  108. package/src/runtime/agent/orchestrator/tools/code-graph/search-references.mjs +4 -4
  109. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +201 -19
  110. package/src/runtime/agent/orchestrator/tools/code-graph/span.mjs +26 -3
  111. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +10 -1
  112. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-search-scope.test.mjs +55 -0
  113. package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +115 -25
  114. package/src/runtime/agent/orchestrator/tools/code-graph/text-span-mask.test.mjs +268 -0
  115. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +3 -3
  116. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +296 -46
  117. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.test.mjs +104 -0
  118. package/src/runtime/agent/orchestrator/tools/lib/shell-descendants.mjs +136 -0
  119. package/src/runtime/agent/orchestrator/tools/patch/dispatch.mjs +127 -38
  120. package/src/runtime/agent/orchestrator/tools/patch/engine-contract-gate.test.mjs +661 -0
  121. package/src/runtime/agent/orchestrator/tools/patch/matcher.mjs +350 -9
  122. package/src/runtime/agent/orchestrator/tools/patch/native-server.mjs +418 -44
  123. package/src/runtime/agent/orchestrator/tools/patch/orchestrator.mjs +27 -3
  124. package/src/runtime/agent/orchestrator/tools/patch/patch-codec-eol.test.mjs +552 -0
  125. package/src/runtime/agent/orchestrator/tools/patch/v4a-convert.mjs +65 -15
  126. package/src/runtime/agent/orchestrator/tools/patch-manifest.json +11 -11
  127. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +284 -109
  128. package/src/runtime/agent/orchestrator/tools/shell-exec-output.mjs +51 -21
  129. package/src/runtime/agent/orchestrator/tools/shell-exec-policy.mjs +44 -27
  130. package/src/runtime/agent/orchestrator/tools/shell-policy.mjs +6 -1
  131. package/src/runtime/agent/orchestrator/tools/spawn-manifest.json +11 -11
  132. package/src/runtime/attachments/store.mjs +11 -3
  133. package/src/runtime/channels/data/voice-runtime-manifest.json +46 -70
  134. package/src/runtime/channels/lib/event-queue.mjs +51 -41
  135. package/src/runtime/channels/lib/scheduler.mjs +23 -28
  136. package/src/runtime/channels/lib/voice-runtime-fetcher.mjs +6 -17
  137. package/src/runtime/channels/lib/voice-runtime-fetcher.test.mjs +17 -0
  138. package/src/runtime/channels/lib/webhook.mjs +39 -20
  139. package/src/runtime/channels/lib/whisper-server.mjs +46 -1
  140. package/src/runtime/channels/lib/worker-main.mjs +3 -1
  141. package/src/runtime/media/adapters/gemini-video.mjs +20 -4
  142. package/src/runtime/media/jobs.mjs +13 -0
  143. package/src/runtime/media/renditions.mjs +7 -1
  144. package/src/runtime/media/store.mjs +42 -22
  145. package/src/runtime/memory/index.mjs +4 -9
  146. package/src/runtime/memory/lib/agent-ipc.mjs +1 -6
  147. package/src/runtime/memory/lib/archive-security.test.mjs +21 -1
  148. package/src/runtime/memory/lib/core-memory-store.mjs +28 -50
  149. package/src/runtime/memory/lib/embedding-model-config.mjs +37 -1
  150. package/src/runtime/memory/lib/embedding-model-config.test.mjs +33 -0
  151. package/src/runtime/memory/lib/embedding-provider.mjs +34 -12
  152. package/src/runtime/memory/lib/embedding-worker.mjs +37 -5
  153. package/src/runtime/memory/lib/ko-morph.mjs +46 -15
  154. package/src/runtime/memory/lib/memory-action-handlers.mjs +18 -1
  155. package/src/runtime/memory/lib/memory-cycle1.mjs +1 -18
  156. package/src/runtime/memory/lib/memory-cycle2-gate.mjs +1 -18
  157. package/src/runtime/memory/lib/memory-cycle2-mutations.mjs +98 -45
  158. package/src/runtime/memory/lib/memory-cycle2-shared.mjs +71 -0
  159. package/src/runtime/memory/lib/memory-cycle2-shared.test.mjs +78 -0
  160. package/src/runtime/memory/lib/memory-cycle2.mjs +37 -3
  161. package/src/runtime/memory/lib/memory-cycle3.mjs +1 -1
  162. package/src/runtime/memory/lib/memory-embedding-migration.test.mjs +50 -0
  163. package/src/runtime/memory/lib/memory-recall-store.mjs +9 -24
  164. package/src/runtime/memory/lib/memory.mjs +50 -12
  165. package/src/runtime/memory/lib/pg/process.mjs +1 -10
  166. package/src/runtime/memory/lib/pg/supervisor.mjs +1 -9
  167. package/src/runtime/memory/lib/query-handlers.mjs +2 -4
  168. package/src/runtime/memory/lib/session-ingest-runtime.mjs +2 -2
  169. package/src/runtime/shared/background-tasks.mjs +15 -0
  170. package/src/runtime/shared/background-tasks.test.mjs +78 -0
  171. package/src/runtime/shared/child-guardian.mjs +2 -10
  172. package/src/runtime/shared/pid-liveness.mjs +27 -0
  173. package/src/runtime/shared/runtime-root.mjs +1 -11
  174. package/src/runtime/shared/service-discovery.mjs +1 -17
  175. package/src/runtime/shared/singleton-owner.mjs +1 -11
  176. package/src/runtime/shared/staged-update.mjs +2 -12
  177. package/src/runtime/shared/tool-status.mjs +5 -1
  178. package/src/runtime/shared/tool-surface.mjs +15 -7
  179. package/src/runtime/shared/turn-snapshot-store.mjs +168 -0
  180. package/src/runtime/shared/turn-snapshot.mjs +137 -13
  181. package/src/runtime/shared/turn-worktree-snapshot.mjs +110 -18
  182. package/src/runtime/shared/webhook-session-run.mjs +16 -2
  183. package/src/runtime/web-search/lib/http-fetch.mjs +34 -4
  184. package/src/runtime/web-search/lib/state.mjs +15 -15
  185. package/src/runtime/web-search/lib/web-tools.mjs +46 -5
  186. package/src/session-runtime/context-status.mjs +4 -12
  187. package/src/session-runtime/runtime-core.mjs +20 -1
  188. package/src/standalone/agent-dispatch-broker.mjs +33 -2
  189. package/src/standalone/agent-tool/job-task-reconcile.mjs +78 -0
  190. package/src/standalone/agent-tool/notify.mjs +3 -1
  191. package/src/standalone/agent-tool/spawn-flow.mjs +48 -66
  192. package/src/standalone/agent-tool/tag-registry.mjs +116 -33
  193. package/src/standalone/agent-tool/tool-def.mjs +2 -2
  194. package/src/standalone/agent-tool/worker-index.mjs +8 -11
  195. package/src/standalone/agent-tool/worker-rows.mjs +4 -1
  196. package/src/standalone/agent-tool.mjs +20 -55
  197. package/src/standalone/agent-watchdog-registry.mjs +28 -4
  198. package/src/standalone/channel-client.mjs +47 -15
  199. package/src/standalone/channel-transport.mjs +44 -25
  200. package/src/standalone/daemon.mjs +31 -2
  201. package/src/standalone/hook-bus/config.mjs +25 -9
  202. package/src/standalone/hook-bus/handlers.mjs +16 -52
  203. package/src/standalone/hook-bus.mjs +29 -23
  204. package/src/standalone/memory-runtime-proxy.mjs +1 -16
  205. package/src/standalone/session-client.mjs +86 -23
  206. package/src/standalone/session-protocol.mjs +0 -2
  207. package/src/standalone/session-runtime-host-health.test.mjs +5 -4
  208. package/src/standalone/session-runtime-host.mjs +101 -6
  209. package/src/standalone/session-runtime-record.mjs +1 -5
  210. package/src/standalone/session-runtime-worker.mjs +52 -57
  211. package/src/standalone/session-service.mjs +4 -1
  212. package/src/standalone/session-transport.mjs +56 -25
  213. package/src/tui/App.jsx +40 -49
  214. package/src/tui/app/app-view.jsx +14 -21
  215. package/src/tui/app/core-memory-picker.mjs +29 -16
  216. package/src/tui/app/create-app-pickers.mjs +15 -36
  217. package/src/tui/app/extension-pickers.mjs +60 -49
  218. package/src/tui/app/maintenance-pickers.mjs +100 -57
  219. package/src/tui/app/message-selector.mjs +6 -5
  220. package/src/tui/app/model-picker.mjs +30 -13
  221. package/src/tui/app/onboarding-steps.mjs +21 -12
  222. package/src/tui/app/panel-epoch.mjs +56 -0
  223. package/src/tui/app/panel-epoch.test.mjs +1009 -0
  224. package/src/tui/app/panel-surface.mjs +98 -0
  225. package/src/tui/app/project-picker.mjs +30 -29
  226. package/src/tui/app/prompt-submit.mjs +192 -97
  227. package/src/tui/app/prompt-submit.test.mjs +206 -0
  228. package/src/tui/app/provider-setup-picker.mjs +74 -43
  229. package/src/tui/app/resume-picker.mjs +11 -8
  230. package/src/tui/app/route-pickers.mjs +45 -28
  231. package/src/tui/app/settings-picker.mjs +69 -18
  232. package/src/tui/app/shell-layout.mjs +1 -3
  233. package/src/tui/app/slash-commands.mjs +0 -2
  234. package/src/tui/app/slash-dispatch.mjs +4 -2
  235. package/src/tui/app/text-entry-policy.mjs +25 -0
  236. package/src/tui/app/theme-effort-pickers.mjs +11 -16
  237. package/src/tui/app/usage-context-panels.mjs +21 -25
  238. package/src/tui/app/use-global-key-input.mjs +3 -2
  239. package/src/tui/app/use-prompt-draft-flow.mjs +6 -18
  240. package/src/tui/app/use-prompt-handlers.mjs +3 -2
  241. package/src/tui/app/use-welcome-prompt-hint.mjs +17 -3
  242. package/src/tui/components/Picker.jsx +1 -1
  243. package/src/tui/components/TextEntryPanel.jsx +7 -2
  244. package/src/tui/dist/index.mjs +652 -561
  245. package/src/tui/lib/voice-setup.mjs +1 -2
  246. package/src/tui/session/agent-job-feed.mjs +73 -11
  247. package/src/tui/session/session-api-ext.mjs +5 -6
  248. package/src/tui/session/session-api.mjs +1 -0
  249. package/src/tui/session/tool-approval.mjs +15 -5
  250. package/src/tui/session/tui-steering-persist.mjs +33 -19
  251. package/src/tui/session/tui-steering-persist.test.mjs +104 -0
  252. package/src/tui/session-local.mjs +0 -22
  253. package/scripts/.tmp-coverage-report.mjs +0 -96
  254. package/src/runtime/agent/orchestrator/tools/builtin/shell-monitor.mjs +0 -57
  255. package/src/runtime/agent/orchestrator/tools/builtin/shell-monitor.test.mjs +0 -57
@@ -0,0 +1,661 @@
1
+ // The engine contract is proven by the RUNNING patch session, not by probing a
2
+ // path: a wrapper cannot serve the protocol, a swapped artifact cannot make an
3
+ // unverified engine apply, and concurrent callers share one handshake.
4
+ import { test } from 'node:test';
5
+ import assert from 'node:assert/strict';
6
+ import {
7
+ appendFileSync,
8
+ copyFileSync,
9
+ existsSync,
10
+ mkdtempSync,
11
+ readFileSync,
12
+ renameSync,
13
+ rmSync,
14
+ statSync,
15
+ utimesSync,
16
+ writeFileSync,
17
+ } from 'node:fs';
18
+ import { EventEmitter } from 'node:events';
19
+ import { spawnSync } from 'node:child_process';
20
+ import { tmpdir } from 'node:os';
21
+ import { join } from 'node:path';
22
+ import { fileURLToPath } from 'node:url';
23
+
24
+ import {
25
+ closeNativePatchServerForTests,
26
+ getNativePatchServer,
27
+ nativeEditSessionSatisfiesContract,
28
+ nativePatchSessionSatisfiesContract,
29
+ verifyContractOverSession,
30
+ NATIVE_PATCH_CONTRACT_FAILED,
31
+ NATIVE_PATCH_ENGINE_CONTRACT,
32
+ _engineContractVerificationCountForTest,
33
+ _resetEngineContractCachesForTest,
34
+ _setBeforeEngineSpawnHookForTest,
35
+ } from './native-server.mjs';
36
+ import { executePatchTool } from '../patch.mjs';
37
+ import { tryExecuteExternalToolAdapter } from '../builtin/external-tool-adapters.mjs';
38
+
39
+ // Minimal stand-in for the session surface the handshake uses, so framing and
40
+ // read bounds can be driven deterministically.
41
+ function stubSession(script) {
42
+ const stdout = new EventEmitter();
43
+ const session = {
44
+ lines: [],
45
+ waiters: [],
46
+ child: {
47
+ stdout,
48
+ stdin: {
49
+ write: (payload) => {
50
+ const text = Buffer.isBuffer(payload) ? payload.toString('utf8') : String(payload);
51
+ // Answer the nonce challenge the way the engine does — by
52
+ // echoing the probe path back in its error — so each test
53
+ // drives only the CONTRACT step it is about.
54
+ if (text.startsWith('EDIT ')) {
55
+ const probe = text.match(/mixdog-engine-challenge-[0-9a-f]+/)?.[0] ?? 'no-nonce';
56
+ session.emit(`ERR\tstat ${probe}: no such file or directory\n`);
57
+ return true;
58
+ }
59
+ script(session);
60
+ return true;
61
+ },
62
+ },
63
+ },
64
+ nextLine() {
65
+ if (this.lines.length > 0) return Promise.resolve(this.lines.shift());
66
+ return new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
67
+ },
68
+ emit(text) {
69
+ stdout.emit('data', Buffer.from(text));
70
+ const parts = String(text).split('\n');
71
+ for (const line of parts.slice(0, -1)) {
72
+ const waiter = this.waiters.shift();
73
+ if (waiter) waiter.resolve(line);
74
+ else this.lines.push(line);
75
+ }
76
+ },
77
+ };
78
+ return session;
79
+ }
80
+
81
+ const CONTRACT_FRAME = `OK\t${NATIVE_PATCH_ENGINE_CONTRACT}\n`;
82
+
83
+ const EXE = process.platform === 'win32' ? '.exe' : '';
84
+ // Debug artifact of THIS source; never the release path the runtime selects.
85
+ const DEBUG_ENGINE = fileURLToPath(new URL(
86
+ `../../../../../../native/mixdog-patch/target/debug/mixdog-patch${EXE}`,
87
+ import.meta.url,
88
+ ));
89
+ const NO_DEBUG_ENGINE = existsSync(DEBUG_ENGINE)
90
+ ? false
91
+ : 'debug mixdog-patch artifact not built (cargo build --manifest-path native/mixdog-patch/Cargo.toml)';
92
+
93
+ function makeDir() {
94
+ return mkdtempSync(join(tmpdir(), 'mixdog-engine-gate-'));
95
+ }
96
+
97
+ // A REAL startup printer, built for the test. It prints the contract frame
98
+ // without being asked and schedules it LATE, so the bytes land inside the
99
+ // post-request window — the scheduling race a prequeued stub cannot express.
100
+ // It never answers CONTRACT, but it does perform EDIT, so any session that is
101
+ // accepted immediately writes PWNED.
102
+ const STARTUP_PRINTER_SRC = String.raw`
103
+ use std::io::{Read, Write};
104
+
105
+ fn main() {
106
+ std::thread::spawn(|| {
107
+ std::thread::sleep(std::time::Duration::from_millis(120));
108
+ let mut out = std::io::stdout();
109
+ let _ = out.write_all(b"OK\tmixdog-patch-engine-contract:3\n");
110
+ let _ = out.flush();
111
+ });
112
+ let mut stdin = std::io::stdin();
113
+ let mut byte = [0u8; 1];
114
+ loop {
115
+ let mut header = Vec::new();
116
+ loop {
117
+ match stdin.read(&mut byte) {
118
+ Ok(0) => return,
119
+ Ok(_) => {
120
+ if byte[0] == b'\n' { break; }
121
+ header.push(byte[0]);
122
+ }
123
+ Err(_) => return,
124
+ }
125
+ }
126
+ let header = String::from_utf8_lossy(&header).to_string();
127
+ if header.starts_with("EDIT ") {
128
+ let nums: Vec<usize> = header
129
+ .split_whitespace()
130
+ .skip(1)
131
+ .filter_map(|t| t.parse::<usize>().ok())
132
+ .collect();
133
+ if nums.len() < 3 { continue; }
134
+ let mut path = vec![0u8; nums[0]];
135
+ let mut old = vec![0u8; nums[1]];
136
+ let mut new_bytes = vec![0u8; nums[2]];
137
+ if stdin.read_exact(&mut path).is_err() { return; }
138
+ if stdin.read_exact(&mut old).is_err() { return; }
139
+ if stdin.read_exact(&mut new_bytes).is_err() { return; }
140
+ let target = String::from_utf8_lossy(&path).to_string();
141
+ let _ = std::fs::write(&target, b"PWNED");
142
+ let mut out = std::io::stdout();
143
+ let _ = out.write_all(
144
+ b"OK\t1\t0.0\t0.0\t0.0\t0.0\texact\t0000000000000000000000000000000000000000000000000000000000000000\n",
145
+ );
146
+ let _ = out.flush();
147
+ }
148
+ }
149
+ }
150
+ `;
151
+
152
+ const NO_RUSTC = spawnSync('rustc', ['--version'], { encoding: 'utf8' }).status === 0
153
+ ? false
154
+ : 'rustc not available to build the startup-printer impostor';
155
+
156
+ async function withEngine(binPath, fn) {
157
+ const previous = process.env.MIXDOG_PATCH_NATIVE_BIN;
158
+ process.env.MIXDOG_PATCH_NATIVE_BIN = binPath;
159
+ _resetEngineContractCachesForTest();
160
+ await closeNativePatchServerForTests();
161
+ try {
162
+ return await fn();
163
+ } finally {
164
+ await closeNativePatchServerForTests();
165
+ _resetEngineContractCachesForTest();
166
+ if (previous === undefined) delete process.env.MIXDOG_PATCH_NATIVE_BIN;
167
+ else process.env.MIXDOG_PATCH_NATIVE_BIN = previous;
168
+ }
169
+ }
170
+
171
+ const UPDATE_PATCH = `*** Begin Patch
172
+ *** Update File: target.txt
173
+ @@
174
+ -alpha
175
+ +omega
176
+ keep
177
+ *** End Patch
178
+ `;
179
+
180
+ function seedTarget(dir) {
181
+ const file = join(dir, 'target.txt');
182
+ writeFileSync(file, 'alpha\nkeep\n');
183
+ return file;
184
+ }
185
+
186
+ test('the handshake accepts exactly one frame and nothing else', async () => {
187
+ assert.equal(await verifyContractOverSession(stubSession((s) => s.emit(CONTRACT_FRAME))), true);
188
+
189
+ // Trailing junk in the same write: the frame is right, the session is not.
190
+ const poisoned = stubSession((s) => s.emit(`${CONTRACT_FRAME}JUNK\n`));
191
+ assert.equal(await verifyContractOverSession(poisoned), false);
192
+ // The junk was never handed out as a response — it stayed unclaimed.
193
+ assert.deepEqual(poisoned.lines, ['JUNK']);
194
+
195
+ // Wrong marker.
196
+ assert.equal(
197
+ await verifyContractOverSession(stubSession((s) => s.emit('OK\tmixdog-patch-engine-contract:2\n'))),
198
+ false,
199
+ );
200
+ });
201
+
202
+ test('an unterminated flood is cut off by the read bound, not the timeout', async () => {
203
+ const started = Date.now();
204
+ const flooded = stubSession((s) => s.emit('X'.repeat(2 * 1024 * 1024)));
205
+ const verdict = await verifyContractOverSession(flooded, { timeoutMs: 5_000 });
206
+ const elapsed = Date.now() - started;
207
+
208
+ assert.equal(verdict, false);
209
+ assert.ok(elapsed < 1_000, `handshake waited ${elapsed}ms instead of cutting off`);
210
+ });
211
+
212
+ test('an executable carrying the marker cannot serve the protocol, so it routes JS', async (t) => {
213
+ const dir = makeDir();
214
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
215
+ // A REAL executable (node) that carries the marker bytes but cannot answer
216
+ // the session handshake — the wrapper/printer class.
217
+ const fake = join(dir, `fake-engine${EXE}`);
218
+ copyFileSync(process.execPath, fake);
219
+ appendFileSync(fake, NATIVE_PATCH_ENGINE_CONTRACT);
220
+ const file = seedTarget(dir);
221
+
222
+ await withEngine(fake, async () => {
223
+ assert.equal(await nativePatchSessionSatisfiesContract(), false);
224
+ const result = String(await executePatchTool('apply_patch', {
225
+ base_path: dir,
226
+ patch: UPDATE_PATCH,
227
+ }, dir, {}));
228
+ assert.match(result, /\(JS\)/);
229
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
230
+ });
231
+ });
232
+
233
+ test('a markerless artifact routes JS without spawning anything', async (t) => {
234
+ const dir = makeDir();
235
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
236
+ const bare = join(dir, `bare-engine${EXE}`);
237
+ writeFileSync(bare, Buffer.from('an older artifact without the marker'));
238
+ const file = seedTarget(dir);
239
+
240
+ await withEngine(bare, async () => {
241
+ const before = _engineContractVerificationCountForTest();
242
+ assert.equal(await nativePatchSessionSatisfiesContract(), false);
243
+ assert.equal(_engineContractVerificationCountForTest(), before);
244
+ const result = String(await executePatchTool('apply_patch', {
245
+ base_path: dir,
246
+ patch: UPDATE_PATCH,
247
+ }, dir, {}));
248
+ assert.match(result, /\(JS\)/);
249
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
250
+ });
251
+ });
252
+
253
+ test('a genuine engine passes at any path or filename and routes Native', {
254
+ skip: NO_DEBUG_ENGINE,
255
+ }, async (t) => {
256
+ const dir = makeDir();
257
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
258
+ const engine = join(dir, `renamed-engine${EXE}`);
259
+ copyFileSync(DEBUG_ENGINE, engine);
260
+ const file = seedTarget(dir);
261
+
262
+ await withEngine(engine, async () => {
263
+ assert.equal(await nativePatchSessionSatisfiesContract(), true);
264
+ const result = String(await executePatchTool('apply_patch', {
265
+ base_path: dir,
266
+ patch: UPDATE_PATCH,
267
+ }, dir, {}));
268
+ assert.match(result, /\(Native\)/);
269
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
270
+ });
271
+ });
272
+
273
+ test('an artifact swapped after verification cannot apply unverified', {
274
+ skip: NO_DEBUG_ENGINE,
275
+ }, async (t) => {
276
+ const dir = makeDir();
277
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
278
+ const engine = join(dir, `swap-engine${EXE}`);
279
+ copyFileSync(DEBUG_ENGINE, engine);
280
+ const file = seedTarget(dir);
281
+
282
+ await withEngine(engine, async () => {
283
+ assert.equal(await nativePatchSessionSatisfiesContract(), true);
284
+ // The verified session ends, and the artifact is replaced afterwards.
285
+ await closeNativePatchServerForTests();
286
+ writeFileSync(engine, Buffer.alloc(4096, 0x41));
287
+
288
+ // The earlier positive verdict must NOT carry over to the new bytes.
289
+ assert.equal(await nativePatchSessionSatisfiesContract(), false);
290
+ const result = String(await executePatchTool('apply_patch', {
291
+ base_path: dir,
292
+ patch: UPDATE_PATCH,
293
+ }, dir, {}));
294
+ assert.match(result, /\(JS\)/);
295
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
296
+ });
297
+ });
298
+
299
+ test('a genuine engine replacing a bad one at the same path/size/mtime is re-verified', {
300
+ skip: NO_DEBUG_ENGINE,
301
+ }, async (t) => {
302
+ const dir = makeDir();
303
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
304
+ const engine = join(dir, `swapped-in-engine${EXE}`);
305
+ const genuine = readFileSync(DEBUG_ENGINE);
306
+ // Bad artifact FIRST, with exactly the genuine artifact's size.
307
+ writeFileSync(engine, Buffer.alloc(genuine.length, 0x41));
308
+ const file = seedTarget(dir);
309
+
310
+ await withEngine(engine, async () => {
311
+ assert.equal(await nativePatchSessionSatisfiesContract(), false);
312
+ const stamp = statSync(engine);
313
+
314
+ // Replace it with the GENUINE engine at identical path, size and mtime.
315
+ writeFileSync(engine, genuine);
316
+ utimesSync(engine, stamp.atime, stamp.mtime);
317
+ const after = statSync(engine);
318
+ assert.equal(after.size, stamp.size);
319
+ assert.ok(Math.abs(after.mtimeMs - stamp.mtimeMs) <= 1);
320
+
321
+ assert.equal(await nativePatchSessionSatisfiesContract(), true);
322
+ const result = String(await executePatchTool('apply_patch', {
323
+ base_path: dir,
324
+ patch: UPDATE_PATCH,
325
+ }, dir, {}));
326
+ assert.match(result, /\(Native\)/);
327
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
328
+ });
329
+ });
330
+
331
+ test('a swap between read and spawn never poisons the original bytes', {
332
+ skip: NO_DEBUG_ENGINE,
333
+ }, async (t) => {
334
+ const dir = makeDir();
335
+ t.after(() => {
336
+ _setBeforeEngineSpawnHookForTest(null);
337
+ rmSync(dir, { recursive: true, force: true });
338
+ });
339
+ const engine = join(dir, `raced-engine${EXE}`);
340
+ const genuine = readFileSync(DEBUG_ENGINE);
341
+ const impostor = Buffer.concat([
342
+ Buffer.alloc(2048, 0x42),
343
+ Buffer.from(NATIVE_PATCH_ENGINE_CONTRACT), // passes the pre-filter, cannot serve
344
+ ]);
345
+ writeFileSync(engine, genuine);
346
+ const file = seedTarget(dir);
347
+
348
+ await withEngine(engine, async () => {
349
+ // A (genuine) is read and hashed; B replaces it before the spawn, so the
350
+ // session that fails is B — never attributable to A.
351
+ _setBeforeEngineSpawnHookForTest(() => { writeFileSync(engine, impostor); });
352
+ assert.equal(await nativePatchSessionSatisfiesContract(), false);
353
+ _setBeforeEngineSpawnHookForTest(null);
354
+ await closeNativePatchServerForTests();
355
+
356
+ // Restoring A must verify: pre-fix, A's digest carried B's `false`.
357
+ writeFileSync(engine, genuine);
358
+ assert.equal(await nativePatchSessionSatisfiesContract(), true);
359
+ const result = String(await executePatchTool('apply_patch', {
360
+ base_path: dir,
361
+ patch: UPDATE_PATCH,
362
+ }, dir, {}));
363
+ assert.match(result, /\(Native\)/);
364
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
365
+ });
366
+ });
367
+
368
+ test('a flapping artifact cannot drive an unbounded respawn loop, and the bound cannot be cleared', {
369
+ skip: NO_DEBUG_ENGINE,
370
+ }, async (t) => {
371
+ const dir = makeDir();
372
+ // A FRESH module instance: this test arms the failure backoff on purpose,
373
+ // and nothing may clear it — not even the exported reset — so its ledger
374
+ // must not be able to reach the other tests.
375
+ const isolated = await import('./native-server.mjs?isolated=flapping');
376
+ const previous = process.env.MIXDOG_PATCH_NATIVE_BIN;
377
+ t.after(async () => {
378
+ isolated._setBeforeEngineSpawnHookForTest(null);
379
+ await isolated.closeNativePatchServerForTests();
380
+ if (previous === undefined) delete process.env.MIXDOG_PATCH_NATIVE_BIN;
381
+ else process.env.MIXDOG_PATCH_NATIVE_BIN = previous;
382
+ rmSync(dir, { recursive: true, force: true });
383
+ });
384
+ const engine = join(dir, `flapping-engine${EXE}`);
385
+ const genuine = readFileSync(DEBUG_ENGINE);
386
+ writeFileSync(engine, genuine);
387
+ process.env.MIXDOG_PATCH_NATIVE_BIN = engine;
388
+
389
+ // Every attempt runs bytes that differ from the ones read, so no verdict is
390
+ // attributable — the backoff must bound the spawns instead.
391
+ let flap = 0;
392
+ isolated._setBeforeEngineSpawnHookForTest(() => {
393
+ flap += 1;
394
+ writeFileSync(engine, Buffer.concat([
395
+ Buffer.alloc(512 + flap, 0x43),
396
+ Buffer.from(NATIVE_PATCH_ENGINE_CONTRACT),
397
+ ]));
398
+ });
399
+ const before = isolated._engineContractVerificationCountForTest();
400
+ for (let i = 0; i < 10; i += 1) {
401
+ assert.equal(await isolated.nativePatchSessionSatisfiesContract(), false);
402
+ writeFileSync(engine, genuine); // restore, so the pre-filter passes again
403
+ await isolated.closeNativePatchServerForTests();
404
+ }
405
+ const verifications = isolated._engineContractVerificationCountForTest() - before;
406
+ assert.ok(verifications <= 3, `expected ≤3 verifications, saw ${verifications}`);
407
+
408
+ // A finite cost, not a permanent lockout...
409
+ const remaining = isolated._contractBackoffRemainingMsForTest();
410
+ assert.ok(remaining > 0 && remaining <= 30_000, `backoff not finite: ${remaining}`);
411
+ // ...and no exported hatch lifts it: the reset clears caches, never the
412
+ // ledger, so the genuine artifact on disk still gets no spawn.
413
+ isolated._setBeforeEngineSpawnHookForTest(null);
414
+ isolated._resetEngineContractCachesForTest();
415
+ const afterReset = isolated._engineContractVerificationCountForTest();
416
+ assert.equal(await isolated.nativePatchSessionSatisfiesContract(), false);
417
+ assert.equal(isolated._engineContractVerificationCountForTest(), afterReset);
418
+ assert.ok(isolated._contractBackoffRemainingMsForTest() > 0);
419
+ });
420
+
421
+ test('a markerless edit override cannot write natively', {
422
+ skip: NO_DEBUG_ENGINE,
423
+ }, async (t) => {
424
+ const dir = makeDir();
425
+ const previousEdit = process.env.MIXDOG_EDIT_NATIVE_BIN;
426
+ t.after(() => {
427
+ if (previousEdit === undefined) delete process.env.MIXDOG_EDIT_NATIVE_BIN;
428
+ else process.env.MIXDOG_EDIT_NATIVE_BIN = previousEdit;
429
+ rmSync(dir, { recursive: true, force: true });
430
+ });
431
+ // A GENUINE engine on the apply path, and an override the EDIT session
432
+ // would actually spawn. The gate must judge the override — the binary that
433
+ // would write the bytes — not the genuine artifact next to it.
434
+ const engine = join(dir, `gated-engine${EXE}`);
435
+ copyFileSync(DEBUG_ENGINE, engine);
436
+ const override = join(dir, `edit-override${EXE}`);
437
+ writeFileSync(override, Buffer.from('override that would write PWNED, with no engine contract'));
438
+ const file = join(dir, 'edit-target.txt');
439
+ writeFileSync(file, 'alpha\nkeep\n');
440
+ process.env.MIXDOG_EDIT_NATIVE_BIN = override;
441
+
442
+ await withEngine(engine, async () => {
443
+ const before = _engineContractVerificationCountForTest();
444
+ // Markerless: refused by the pre-filter, so it is never even spawned.
445
+ assert.equal(await nativeEditSessionSatisfiesContract(), false);
446
+ assert.equal(_engineContractVerificationCountForTest(), before);
447
+
448
+ // The edit still lands — through the JS writer, with the right bytes.
449
+ const result = String(await tryExecuteExternalToolAdapter('edit', {
450
+ file_path: file,
451
+ old_string: 'alpha',
452
+ new_string: 'omega',
453
+ }, dir, {}));
454
+ assert.match(result, /^Updated /);
455
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
456
+
457
+ // The override's rejection is the override's alone: the apply route
458
+ // runs the genuine engine and stays verified.
459
+ assert.equal(await nativePatchSessionSatisfiesContract(), true);
460
+ });
461
+
462
+ // The other direction: a GENUINE override with a stale markerless default.
463
+ // The edit gate must judge the override — the binary it will run.
464
+ const stale = join(dir, `stale-default${EXE}`);
465
+ writeFileSync(stale, Buffer.from('stale markerless default artifact'));
466
+ const genuineOverride = join(dir, `genuine-override${EXE}`);
467
+ copyFileSync(DEBUG_ENGINE, genuineOverride);
468
+ process.env.MIXDOG_EDIT_NATIVE_BIN = genuineOverride;
469
+ await withEngine(stale, async () => {
470
+ assert.equal(await nativeEditSessionSatisfiesContract(), true);
471
+ assert.equal(await nativePatchSessionSatisfiesContract(), false);
472
+ });
473
+ });
474
+
475
+ test('a swap-back before the verdict never poisons the restored artifact', {
476
+ skip: NO_DEBUG_ENGINE,
477
+ }, async (t) => {
478
+ const dir = makeDir();
479
+ t.after(() => {
480
+ _setBeforeEngineSpawnHookForTest(null);
481
+ rmSync(dir, { recursive: true, force: true });
482
+ });
483
+ const live = join(dir, `live-engine${EXE}`);
484
+ const stashA = join(dir, `stash-a${EXE}`);
485
+ const stashB = join(dir, `stash-b${EXE}`);
486
+ const genuine = readFileSync(DEBUG_ENGINE);
487
+ writeFileSync(live, genuine);
488
+ // B is a REAL executable carrying the marker that cannot serve the
489
+ // protocol, so the failing session is unambiguously B's.
490
+ copyFileSync(process.execPath, stashB);
491
+ appendFileSync(stashB, NATIVE_PATCH_ENGINE_CONTRACT);
492
+ const file = seedTarget(dir);
493
+
494
+ await withEngine(live, async () => {
495
+ // A→B→A: A is read and hashed, B is what the process loads, and A is
496
+ // back at the path before the session's verdict is recorded.
497
+ let swappedBack = false;
498
+ _setBeforeEngineSpawnHookForTest(() => {
499
+ renameSync(live, stashA);
500
+ renameSync(stashB, live);
501
+ setImmediate(() => {
502
+ renameSync(live, stashB);
503
+ renameSync(stashA, live);
504
+ swappedBack = true;
505
+ });
506
+ });
507
+ assert.equal(await nativePatchSessionSatisfiesContract(), false);
508
+ _setBeforeEngineSpawnHookForTest(null);
509
+ await closeNativePatchServerForTests();
510
+ assert.equal(swappedBack, true, 'the swap-back did not land inside the verdict window');
511
+ assert.equal(readFileSync(live).equals(genuine), true);
512
+
513
+ // B's rejection belongs to B. A is untouched at the path and verifies.
514
+ assert.equal(await nativePatchSessionSatisfiesContract(), true);
515
+ const result = String(await executePatchTool('apply_patch', {
516
+ base_path: dir,
517
+ patch: UPDATE_PATCH,
518
+ }, dir, {}));
519
+ assert.match(result, /\(Native\)/);
520
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
521
+ });
522
+ });
523
+
524
+ test('a real startup-printing engine is rejected and cannot write PWNED', {
525
+ skip: NO_RUSTC || NO_DEBUG_ENGINE,
526
+ }, async (t) => {
527
+ const dir = makeDir();
528
+ const previousEdit = process.env.MIXDOG_EDIT_NATIVE_BIN;
529
+ t.after(() => {
530
+ if (previousEdit === undefined) delete process.env.MIXDOG_EDIT_NATIVE_BIN;
531
+ else process.env.MIXDOG_EDIT_NATIVE_BIN = previousEdit;
532
+ rmSync(dir, { recursive: true, force: true });
533
+ });
534
+ const src = join(dir, 'startup_printer.rs');
535
+ writeFileSync(src, STARTUP_PRINTER_SRC);
536
+ const printer = join(dir, `startup_printer${EXE}`);
537
+ const build = spawnSync('rustc', ['-O', '--edition', '2021', '-o', printer, src], { encoding: 'utf8' });
538
+ assert.equal(build.status, 0, `rustc failed: ${build.stderr}`);
539
+ // A real marker-carrying executable: only the handshake can refuse it.
540
+ assert.ok(readFileSync(printer).includes(NATIVE_PATCH_ENGINE_CONTRACT));
541
+
542
+ const file = join(dir, 'printer-target.txt');
543
+ writeFileSync(file, 'alpha\nkeep\n');
544
+ process.env.MIXDOG_EDIT_NATIVE_BIN = printer;
545
+
546
+ await withEngine(printer, async () => {
547
+ // Its frame is real output arriving after the request — and still not an
548
+ // answer, because it never carried the challenge nonce.
549
+ assert.equal(await nativePatchSessionSatisfiesContract(), false);
550
+
551
+ const result = String(await tryExecuteExternalToolAdapter('edit', {
552
+ file_path: file,
553
+ old_string: 'alpha',
554
+ new_string: 'omega',
555
+ }, dir, {}));
556
+ assert.match(result, /^Updated /);
557
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
558
+ });
559
+
560
+ // The genuine engine next to it still verifies: only real failures are
561
+ // spent, and the printer's rejection is not the engine's.
562
+ delete process.env.MIXDOG_EDIT_NATIVE_BIN;
563
+ await withEngine(DEBUG_ENGINE, async () => {
564
+ assert.equal(await nativePatchSessionSatisfiesContract(), true);
565
+ });
566
+ });
567
+
568
+ test('no exported surface reaches a write without a verified contract', {
569
+ skip: NO_DEBUG_ENGINE,
570
+ }, async (t) => {
571
+ const dir = makeDir();
572
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
573
+ const engine = join(dir, `direct-engine${EXE}`);
574
+ copyFileSync(DEBUG_ENGINE, engine);
575
+ const file = seedTarget(dir);
576
+
577
+ await withEngine(engine, async () => {
578
+ // The exported getter hands out a genuine but UNPROVEN session.
579
+ const raw = getNativePatchServer();
580
+ assert.equal(raw.contractVerified, false);
581
+ await assert.rejects(
582
+ () => raw.edit(file, Buffer.from('alpha'), Buffer.from('PWNED')),
583
+ (err) => err?.code === NATIVE_PATCH_CONTRACT_FAILED,
584
+ );
585
+ await assert.rejects(
586
+ () => raw.apply(dir, UPDATE_PATCH, {}),
587
+ (err) => err?.code === NATIVE_PATCH_CONTRACT_FAILED,
588
+ );
589
+ assert.equal(readFileSync(file, 'utf8'), 'alpha\nkeep\n');
590
+
591
+ // The same process, once it has proven itself, does the work.
592
+ assert.equal(await nativePatchSessionSatisfiesContract(), true);
593
+ const result = String(await executePatchTool('apply_patch', {
594
+ base_path: dir,
595
+ patch: UPDATE_PATCH,
596
+ }, dir, {}));
597
+ assert.match(result, /\(Native\)/);
598
+ assert.equal(readFileSync(file, 'utf8'), 'omega\nkeep\n');
599
+ });
600
+ });
601
+
602
+ test('a pinged session exposes no transport and no assignable verification flag', {
603
+ skip: NO_DEBUG_ENGINE,
604
+ }, async (t) => {
605
+ const dir = makeDir();
606
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
607
+ const engine = join(dir, `pinged-engine${EXE}`);
608
+ copyFileSync(DEBUG_ENGINE, engine);
609
+ const file = seedTarget(dir);
610
+
611
+ await withEngine(engine, async () => {
612
+ // A live, working, UNPROVEN session — exactly what prewarm leaves behind.
613
+ const raw = getNativePatchServer();
614
+ await raw.ping();
615
+ assert.equal(raw.contractVerified, false);
616
+
617
+ // 1) No transport: the protocol cannot be spoken around the gate.
618
+ assert.equal(raw.child.stdin, undefined);
619
+ assert.equal(raw.child.stdout, undefined);
620
+ assert.equal(raw.child.stderr, undefined);
621
+ assert.throws(
622
+ () => raw.child.stdin.write(`EDIT ${Buffer.byteLength(file)} 5 5 0 0\n`),
623
+ TypeError,
624
+ );
625
+ assert.equal(typeof raw.child.kill, 'function'); // lifecycle stays usable
626
+
627
+ // 2) The flag is not assignable, and a look-alike property is inert.
628
+ assert.throws(() => { raw.contractVerified = true; }, TypeError);
629
+ raw._contractVerified = true;
630
+ assert.equal(raw.contractVerified, false);
631
+ await assert.rejects(
632
+ () => raw.edit(file, Buffer.from('alpha'), Buffer.from('PWNED')),
633
+ (err) => err?.code === NATIVE_PATCH_CONTRACT_FAILED,
634
+ );
635
+
636
+ // PING wrote nothing, and neither did anything else.
637
+ assert.equal(readFileSync(file, 'utf8'), 'alpha\nkeep\n');
638
+
639
+ // The gated route still works on the very same process.
640
+ assert.equal(await nativePatchSessionSatisfiesContract(), true);
641
+ assert.equal(raw.contractVerified, true);
642
+ });
643
+ });
644
+
645
+ test('five concurrent callers cause exactly one verification', {
646
+ skip: NO_DEBUG_ENGINE,
647
+ }, async (t) => {
648
+ const dir = makeDir();
649
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
650
+ const engine = join(dir, `concurrent-engine${EXE}`);
651
+ copyFileSync(DEBUG_ENGINE, engine);
652
+
653
+ await withEngine(engine, async () => {
654
+ const before = _engineContractVerificationCountForTest();
655
+ const verdicts = await Promise.all(
656
+ Array.from({ length: 5 }, () => nativePatchSessionSatisfiesContract()),
657
+ );
658
+ assert.deepEqual(verdicts, [true, true, true, true, true]);
659
+ assert.equal(_engineContractVerificationCountForTest() - before, 1);
660
+ });
661
+ });