@junghanacs/entwurf 0.13.0 → 0.14.0

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 (193) hide show
  1. package/AGENTS.md +52 -17
  2. package/BASELINE.md +60 -206
  3. package/CHANGELOG.md +64 -0
  4. package/CONTRIBUTING.md +14 -10
  5. package/DELIVERY.md +118 -261
  6. package/README.md +91 -431
  7. package/VERIFY.md +74 -95
  8. package/demo/README.md +1 -1
  9. package/demo/demo-baseline.sh +1 -3
  10. package/demo/demo.sh +2 -5
  11. package/docs/acp-backend-rail.md +236 -0
  12. package/docs/external-mcp-host.md +131 -0
  13. package/docs/fresh-cut-policy.md +99 -0
  14. package/docs/setup-clean-host.md +124 -328
  15. package/mcp/entwurf-bridge/dist/mcp/entwurf-bridge/src/index.js +160 -67
  16. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/acp-client.js +12 -0
  17. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/backend-adapter.js +11 -10
  18. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/config.js +1 -1
  19. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/engraving.js +42 -1
  20. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/models.js +4 -4
  21. package/mcp/entwurf-bridge/dist/pi-extensions/lib/acp/overlay.js +11 -9
  22. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-control-rpc.js +7 -5
  23. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-core.js +13 -14
  24. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-resume-args.js +45 -40
  25. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-contract.js +117 -95
  26. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-decider.js +23 -57
  27. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-lock.js +16 -7
  28. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-production.js +5 -53
  29. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-release.js +21 -36
  30. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-runner.js +3 -15
  31. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-send-fallback.js +12 -11
  32. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-send.js +2 -7
  33. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-surface.js +30 -67
  34. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-visible-resume.js +256 -0
  35. package/mcp/entwurf-bridge/dist/pi-extensions/lib/meta-session.js +91 -5
  36. package/mcp/entwurf-bridge/dist/pi-extensions/lib/mux-fresh-call.js +258 -0
  37. package/mcp/entwurf-bridge/dist/pi-extensions/lib/mux-launch.js +202 -0
  38. package/mcp/entwurf-bridge/dist/pi-extensions/lib/mux-placement.js +289 -0
  39. package/mcp/entwurf-bridge/dist/pi-extensions/lib/mux-resume-call.js +170 -0
  40. package/mcp/entwurf-bridge/dist/pi-extensions/lib/resume-launch-identity.js +136 -0
  41. package/mcp/entwurf-bridge/dist/pi-extensions/lib/session-id.js +8 -5
  42. package/mcp/entwurf-bridge/dist/pi-extensions/lib/socket-discovery.js +3 -3
  43. package/mcp/entwurf-bridge/dist/scripts/meta-facts.js +51 -0
  44. package/mcp/entwurf-bridge/dist/scripts/new-session-id.js +9 -4
  45. package/mcp/entwurf-bridge/src/index.ts +176 -67
  46. package/mcp/entwurf-bridge/start.sh +2 -2
  47. package/mcp/entwurf-bridge/test.sh +23 -9
  48. package/mcp/entwurf-bridge/tsconfig.build.json +11 -2
  49. package/package.json +25 -11
  50. package/pi-extensions/entwurf-control.ts +220 -71
  51. package/pi-extensions/lib/acp/acp-client.ts +22 -0
  52. package/pi-extensions/lib/acp/augment.ts +42 -3
  53. package/pi-extensions/lib/acp/backend-adapter.ts +12 -11
  54. package/pi-extensions/lib/acp/backend.ts +366 -38
  55. package/pi-extensions/lib/acp/config.ts +1 -1
  56. package/pi-extensions/lib/acp/engraving.ts +43 -1
  57. package/pi-extensions/lib/acp/event-mapper.ts +16 -13
  58. package/pi-extensions/lib/acp/models.ts +4 -4
  59. package/pi-extensions/lib/acp/overlay.ts +11 -9
  60. package/pi-extensions/lib/entwurf-control-rpc.ts +7 -5
  61. package/pi-extensions/lib/entwurf-core.ts +15 -15
  62. package/pi-extensions/lib/entwurf-resume-args.ts +41 -52
  63. package/pi-extensions/lib/entwurf-v2-contract-schema.ts +1 -1
  64. package/pi-extensions/lib/entwurf-v2-contract.ts +120 -99
  65. package/pi-extensions/lib/entwurf-v2-decider.ts +30 -91
  66. package/pi-extensions/lib/entwurf-v2-lock.ts +16 -7
  67. package/pi-extensions/lib/entwurf-v2-production.ts +4 -78
  68. package/pi-extensions/lib/entwurf-v2-release.ts +25 -49
  69. package/pi-extensions/lib/entwurf-v2-runner.ts +6 -21
  70. package/pi-extensions/lib/entwurf-v2-send-fallback.ts +12 -11
  71. package/pi-extensions/lib/entwurf-v2-send.ts +2 -7
  72. package/pi-extensions/lib/entwurf-v2-surface.ts +36 -76
  73. package/pi-extensions/lib/entwurf-v2-visible-resume.ts +370 -0
  74. package/pi-extensions/lib/meta-session.ts +93 -5
  75. package/pi-extensions/lib/mux-fresh-call.ts +328 -0
  76. package/pi-extensions/lib/mux-launch.ts +267 -0
  77. package/pi-extensions/lib/mux-placement.ts +387 -0
  78. package/pi-extensions/lib/mux-resume-call.ts +221 -0
  79. package/pi-extensions/lib/resume-launch-identity.ts +162 -0
  80. package/pi-extensions/lib/session-id.js +8 -5
  81. package/pi-extensions/lib/socket-discovery.ts +3 -3
  82. package/prompts/engraving.md +13 -5
  83. package/run.sh +688 -282
  84. package/scripts/agy-bridge-config.py +5 -1
  85. package/scripts/check-acp-backend-preflight.ts +1 -1
  86. package/scripts/check-acp-carrier-augment.ts +246 -10
  87. package/scripts/check-acp-cortex.ts +5 -5
  88. package/scripts/check-acp-overlay.ts +13 -3
  89. package/scripts/check-acp-prompt-lifecycle.ts +565 -0
  90. package/scripts/check-acp-stop-reason.ts +342 -0
  91. package/scripts/check-acp-stream-hooks.ts +504 -0
  92. package/scripts/check-elapsed.sh +25 -0
  93. package/scripts/check-entwurf-bridge-boot.ts +51 -4
  94. package/scripts/check-entwurf-bridge-pi-free.ts +6 -5
  95. package/scripts/check-entwurf-control-rpc.ts +4 -3
  96. package/scripts/check-entwurf-resume-args.ts +72 -70
  97. package/scripts/check-entwurf-session-identity.ts +14 -10
  98. package/scripts/check-entwurf-v2-contract.ts +34 -59
  99. package/scripts/check-entwurf-v2-decider.ts +17 -177
  100. package/scripts/check-entwurf-v2-lock.ts +5 -2
  101. package/scripts/check-entwurf-v2-matrix.ts +3 -53
  102. package/scripts/check-entwurf-v2-production.ts +2 -91
  103. package/scripts/check-entwurf-v2-release.ts +10 -105
  104. package/scripts/check-entwurf-v2-runner.ts +4 -85
  105. package/scripts/check-entwurf-v2-send-fallback.ts +5 -6
  106. package/scripts/check-entwurf-v2-send.ts +0 -28
  107. package/scripts/check-entwurf-v2-surface.ts +198 -128
  108. package/scripts/check-entwurf-v2-visible-resume.ts +445 -0
  109. package/scripts/check-fresh-cut-gate.sh +1 -1
  110. package/scripts/check-gate-qualification.ts +101 -7
  111. package/scripts/check-install-container.sh +10 -2
  112. package/scripts/check-install-surface.ts +1 -1
  113. package/scripts/check-keyset-overlap.py +1 -1
  114. package/scripts/check-meta-facts.ts +249 -0
  115. package/scripts/check-meta-identity-consumers.ts +1 -1
  116. package/scripts/check-meta-session.ts +169 -0
  117. package/scripts/check-mux-launch-tmux.ts +316 -0
  118. package/scripts/check-mux-launch.ts +288 -0
  119. package/scripts/check-mux-launcher-fence.ts +264 -0
  120. package/scripts/check-mux-parent-artifact.ts +195 -0
  121. package/scripts/check-mux-placement-tmux.ts +322 -0
  122. package/scripts/check-mux-placement.ts +323 -0
  123. package/scripts/check-mux-resume-call.ts +282 -0
  124. package/scripts/check-probe-cli-shim.ts +25 -22
  125. package/scripts/check-probe-ordering.ts +121 -81
  126. package/scripts/check-release-gate-outcomes.ts +452 -0
  127. package/scripts/check-resume-launch-identity.ts +244 -0
  128. package/scripts/check-socket-discovery.ts +1 -1
  129. package/scripts/fixtures/mux-parent-transcript.scrubbed.jsonl +3 -0
  130. package/scripts/inventory-verification-surface.ts +349 -0
  131. package/scripts/lib/claude-launcher-fence.ts +322 -0
  132. package/scripts/lib/live-skip.ts +33 -0
  133. package/scripts/lib/mutation-qualify.ts +109 -3
  134. package/scripts/lib/probe-acp-turn.ts +33 -12
  135. package/scripts/lib/step-outcome.sh +88 -0
  136. package/scripts/meta-bridge-doctor.sh +6 -8
  137. package/scripts/meta-facts.ts +60 -0
  138. package/scripts/mutants/acp-augment.json +106 -0
  139. package/scripts/mutants/acp-cortex.json +2 -2
  140. package/scripts/mutants/acp-overlay.json +17 -0
  141. package/scripts/mutants/acp-prompt-lifecycle.json +100 -0
  142. package/scripts/mutants/acp-stop-reason.json +80 -0
  143. package/scripts/mutants/acp-stream-hooks.json +158 -0
  144. package/scripts/mutants/bridge-boot-resume.json +45 -0
  145. package/scripts/mutants/meta-facts.json +50 -0
  146. package/scripts/mutants/meta-identity.json +36 -0
  147. package/scripts/mutants/mux-boundary.json +196 -0
  148. package/scripts/mutants/mux-fresh-call.json +185 -0
  149. package/scripts/mutants/mux-launcher-fence.json +123 -0
  150. package/scripts/mutants/mux-parent-artifact.json +39 -0
  151. package/scripts/mutants/mux-resume-call.json +148 -0
  152. package/scripts/mutants/probe-ordering.json +6 -1021
  153. package/scripts/mutants/release-gate.json +140 -0
  154. package/scripts/mutants/resume-args.json +76 -0
  155. package/scripts/mutants/resume-launch-identity.json +96 -0
  156. package/scripts/mutants/v2-surface.json +74 -23
  157. package/scripts/mutants/v2-visible-resume.json +215 -0
  158. package/scripts/new-session-id.ts +9 -4
  159. package/scripts/smoke-acp-bundled-mcp-live.ts +4 -3
  160. package/scripts/smoke-acp-carrier-augment-live.ts +2 -2
  161. package/scripts/smoke-acp-cortex-live.ts +8 -14
  162. package/scripts/smoke-acp-long-turn-live.ts +185 -0
  163. package/scripts/smoke-acp-mcp-live.ts +2 -2
  164. package/scripts/smoke-acp-memory-containment-live.ts +2 -2
  165. package/scripts/smoke-acp-ordering-probe-live.ts +2 -2
  166. package/scripts/smoke-acp-overlay-live.ts +2 -2
  167. package/scripts/smoke-acp-provider-live.ts +2 -2
  168. package/scripts/smoke-acp-raw-turn-live.ts +3 -3
  169. package/scripts/smoke-acp-session-reuse-live.ts +2 -2
  170. package/scripts/smoke-acp-skill-live.ts +2 -2
  171. package/scripts/smoke-acp-socket-citizen-live.ts +4 -3
  172. package/scripts/smoke-acp-v2-send-live.ts +4 -3
  173. package/scripts/smoke-agy-native-push-live.ts +10 -20
  174. package/scripts/smoke-claude-native-resume-live.sh +13 -3
  175. package/scripts/smoke-entwurf-chain-live.ts +352 -0
  176. package/scripts/smoke-entwurf-v2-matrix-live.ts +3 -3
  177. package/scripts/smoke-meta-honesty.sh +1 -1
  178. package/scripts/smoke-meta-install-state.sh +4 -0
  179. package/scripts/smoke-mux-fresh-call-live.ts +365 -0
  180. package/scripts/smoke-mux-lifecycle-live.ts +1136 -0
  181. package/scripts/smoke-pi-attach.ts +1 -1
  182. package/scripts/smoke-user-scope-citizen.sh +1 -1
  183. package/scripts/tsconfig.json +1 -0
  184. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-preflight.js +0 -160
  185. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-spawn-production.js +0 -273
  186. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-spawn.js +0 -216
  187. package/pi-extensions/lib/entwurf-v2-spawn-production.ts +0 -373
  188. package/pi-extensions/lib/entwurf-v2-spawn.ts +0 -323
  189. package/scripts/check-acp-sdk-surface.ts +0 -236
  190. package/scripts/check-entwurf-v2-spawn-production.ts +0 -551
  191. package/scripts/check-entwurf-v2-spawn.ts +0 -399
  192. package/scripts/smoke-entwurf-v2-spawn-live.ts +0 -188
  193. package/scripts/smoke-entwurf-v2-spawn-resume-live.ts +0 -469
@@ -0,0 +1,365 @@
1
+ /**
2
+ * smoke-mux-fresh-call-live — the ONE axis a deterministic gate cannot reach: a real window, a
3
+ * real runtime, a real first turn, and a real callback arriving on a real inbound surface.
4
+ *
5
+ * OUT of `pnpm check`. Needs `LIVE=1`. Costs two model turns (one pi, one Claude Code).
6
+ *
7
+ * ── Isolate the WRITES, keep the runtimes real ──
8
+ *
9
+ * The obvious fence — redirect HOME and everything under it — is wrong here, and wrongly GREEN
10
+ * is worse than red: a pi with no `PI_CODING_AGENT_DIR` and a Claude with no config dir are
11
+ * unauthenticated runtimes that fail for a reason this smoke is not testing. So the split is:
12
+ *
13
+ * REAL (runtime-owned) the authenticated runtime config — the real pi agent dir
14
+ * for Pi, and canonical HOME/optional CLAUDE_CONFIG_DIR for
15
+ * Claude. Native session transcripts remain there as evidence.
16
+ * FIXTURE (entwurf-owned writes) XDG roots, the four meta roots, the v2 lock dir, and the
17
+ * working directory. Pi also receives fixture HOME so its
18
+ * control socket cannot touch the operator's directory.
19
+ *
20
+ * Be honest about what that means: this smoke READS the operator's real runtime config, and the
21
+ * two siblings it opens will write their own session transcripts into the real pi agent dir the
22
+ * same way any pi session does. What it must never do is mint a garden record, a control socket,
23
+ * a mailbox or a lock outside the fixture — that is what the proof at the end checks.
24
+ *
25
+ * The siblings inherit the fixture through the private tmux server we start inside it, so their
26
+ * records land in the fixture store too: born, observed, discarded, and the garden never sees
27
+ * them.
28
+ */
29
+
30
+ import { spawnSync } from "node:child_process";
31
+ import fs from "node:fs";
32
+ import os from "node:os";
33
+ import path from "node:path";
34
+ import {
35
+ assessLauncherCleanup,
36
+ restoreOriginalXdg,
37
+ snapshotClaudeLauncher,
38
+ snapshotOriginalXdg,
39
+ verifyClaudeLauncher,
40
+ } from "./lib/claude-launcher-fence.ts";
41
+ import { skipLive } from "./lib/live-skip.ts";
42
+
43
+ const LABEL = "smoke-mux-fresh-call-live";
44
+ const CALLBACK_WAIT_MS = 180_000;
45
+ const LIVE_MODEL = {
46
+ pi: "openai-codex/gpt-5.6-terra",
47
+ "claude-code": "claude-sonnet-5",
48
+ } as const;
49
+
50
+ // Captured BEFORE any redirect: these name the operator's world and must stay untouched.
51
+ const REAL_HOME = os.homedir();
52
+ const REAL_PI_AGENT_DIR = process.env.PI_CODING_AGENT_DIR?.trim() || path.join(REAL_HOME, ".pi", "agent");
53
+ const ORIGINAL_CLAUDE_CONFIG_DIR = process.env.CLAUDE_CONFIG_DIR?.trim() || null;
54
+ const REAL_CLAUDE_CONFIG_DIR = ORIGINAL_CLAUDE_CONFIG_DIR || path.join(REAL_HOME, ".claude");
55
+ const REAL_META_SESSIONS =
56
+ process.env.ENTWURF_META_SESSIONS_DIR?.trim() || path.join(REAL_PI_AGENT_DIR, "meta-sessions");
57
+ const REAL_CONTROL_DIR = path.join(REAL_HOME, ".pi", "entwurf-control");
58
+ // The four XDG roots as the OPERATOR has them — presence and value, captured before any redirect,
59
+ // so the real-HOME Claude cell can be given exact operator-env parity (issue #67).
60
+ const ORIGINAL_XDG = snapshotOriginalXdg(process.env);
61
+
62
+ let passed = 0;
63
+ function ok(label: string, cond: boolean): void {
64
+ if (!cond) throw new Error(`${LABEL}: FAILED — ${label}`);
65
+ console.log(` ok ${label}`);
66
+ passed++;
67
+ }
68
+
69
+ /**
70
+ * The entry SET of a directory we must not write to. A missing directory is a valid answer
71
+ * (ENOENT); anything else — EACCES above all — is a real failure and must not be laundered into
72
+ * "absent", which would turn an unreadable store into a passing proof.
73
+ *
74
+ * This is an ENTRY-SET comparison, not a byte comparison: it detects a record/socket/lock that
75
+ * appeared or vanished, which is exactly the residue class this smoke can create. It does not
76
+ * claim file contents are unchanged.
77
+ */
78
+ function entrySet(dir: string): string {
79
+ try {
80
+ return fs.readdirSync(dir).sort().join("\n");
81
+ } catch (err) {
82
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return "<absent>";
83
+ throw err;
84
+ }
85
+ }
86
+
87
+ function tmux(socket: string, args: string[], env: NodeJS.ProcessEnv): { status: number | null; stdout: string } {
88
+ const r = spawnSync("tmux", ["-S", socket, ...args], { env, encoding: "utf8" });
89
+ return { status: r.status, stdout: (r.stdout ?? "").trim() };
90
+ }
91
+
92
+ function pidIsAlive(pid: number): boolean {
93
+ try {
94
+ process.kill(pid, 0);
95
+ return true;
96
+ } catch (err) {
97
+ if ((err as NodeJS.ErrnoException).code === "ESRCH") return false;
98
+ throw err;
99
+ }
100
+ }
101
+
102
+ function waitForPidsGone(pids: ReadonlySet<number>, timeoutMs = 10_000): boolean {
103
+ const deadline = Date.now() + timeoutMs;
104
+ while (Date.now() < deadline) {
105
+ if ([...pids].every((pid) => !pidIsAlive(pid))) return true;
106
+ spawnSync("sleep", ["0.1"]);
107
+ }
108
+ return [...pids].every((pid) => !pidIsAlive(pid));
109
+ }
110
+
111
+ async function main(): Promise<void> {
112
+ if (process.env.LIVE !== "1")
113
+ skipLive(LABEL, "LIVE=1 not set — this smoke opens real windows and spends model turns");
114
+ if (spawnSync("tmux", ["-V"], { encoding: "utf8" }).status !== 0) skipLive(LABEL, "tmux is not installed on PATH");
115
+ if (spawnSync("sh", ["-c", "command -v claude"], { encoding: "utf8" }).status !== 0)
116
+ skipLive(LABEL, "the claude runtime is not on PATH — the fixed claude-code backend cannot be opened");
117
+ if (!fs.existsSync(REAL_PI_AGENT_DIR))
118
+ skipLive(LABEL, `no pi agent dir at ${REAL_PI_AGENT_DIR} — an unauthenticated pi would fail for the wrong reason`);
119
+ if (!fs.existsSync(REAL_CLAUDE_CONFIG_DIR))
120
+ skipLive(
121
+ LABEL,
122
+ `no Claude config dir at ${REAL_CLAUDE_CONFIG_DIR} — an unauthenticated claude would fail likewise`,
123
+ );
124
+
125
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mux-fresh-call-live-"));
126
+ const scratch = path.join(root, "cwd");
127
+ const beforeRealStore = entrySet(REAL_META_SESSIONS);
128
+ const beforeRealSockets = entrySet(REAL_CONTROL_DIR);
129
+ const originalCwd = process.cwd();
130
+ // FAIL-CLOSED launcher preflight (issue #67): pin the real claude launcher — path, kind, link,
131
+ // resolved target and content — before ANY Claude-capable child starts. Throws if it cannot.
132
+ const launcherSnapshot = snapshotClaudeLauncher({ env: process.env, fixtureRoot: root });
133
+
134
+ // ── Every WRITE axis into the fixture; the two auth roots stay real ──────
135
+ const fenced: Record<string, string> = {
136
+ HOME: path.join(root, "home"),
137
+ XDG_CONFIG_HOME: path.join(root, "xdg-config"),
138
+ XDG_DATA_HOME: path.join(root, "xdg-data"),
139
+ XDG_STATE_HOME: path.join(root, "xdg-state"),
140
+ XDG_CACHE_HOME: path.join(root, "xdg-cache"),
141
+ XDG_RUNTIME_DIR: path.join(root, "xdg-runtime"),
142
+ ENTWURF_META_SESSIONS_DIR: path.join(root, "meta-sessions"),
143
+ ENTWURF_META_RECEIVERS_DIR: path.join(root, "meta-receivers"),
144
+ ENTWURF_META_SENDERS_DIR: path.join(root, "meta-senders"),
145
+ ENTWURF_META_MAILBOX_DIR: path.join(root, "meta-mailbox"),
146
+ ENTWURF_V2_LOCK_DIR: path.join(root, "v2-locks"),
147
+ };
148
+ const referenced: Record<string, string> = {
149
+ PI_CODING_AGENT_DIR: REAL_PI_AGENT_DIR,
150
+ };
151
+ for (const dir of Object.values(fenced)) fs.mkdirSync(dir, { recursive: true });
152
+ fs.mkdirSync(scratch, { recursive: true });
153
+ // A runtime dir is a private surface by convention and tmux checks it.
154
+ fs.chmodSync(fenced.XDG_RUNTIME_DIR, 0o700);
155
+ for (const [k, v] of Object.entries(fenced)) process.env[k] = v;
156
+ for (const [k, v] of Object.entries(referenced)) process.env[k] = v;
157
+ delete process.env.CLAUDE_CONFIG_DIR;
158
+ process.chdir(scratch);
159
+
160
+ // Import the meta layer only AFTER the redirects — a module that resolved its roots at import
161
+ // time would have captured the operator's.
162
+ const meta = await import("../pi-extensions/lib/meta-session.ts");
163
+ const { freshCall } = await import("../pi-extensions/lib/mux-fresh-call.ts");
164
+
165
+ const siblingGids = new Set<string>();
166
+ const siblingPids = new Set<number>();
167
+ const privateSockets = new Set<string>();
168
+ let cleanupError: Error | null = null;
169
+ let runError: unknown = null;
170
+ try {
171
+ ok(
172
+ "fence: every entwurf-owned WRITE root is inside the fixture and none is the operator's home",
173
+ Object.values(fenced).every((d) => d.startsWith(root)) && !Object.values(fenced).includes(REAL_HOME),
174
+ );
175
+ ok(
176
+ "fence: runtime auth roots are real — this smoke tests configured runtimes, not empty ones",
177
+ referenced.PI_CODING_AGENT_DIR === REAL_PI_AGENT_DIR &&
178
+ !referenced.PI_CODING_AGENT_DIR.startsWith(root) &&
179
+ !REAL_CLAUDE_CONFIG_DIR.startsWith(root),
180
+ );
181
+ ok(
182
+ "fence: the meta layer resolved its roots to the fixture, and cwd is the scratch dir",
183
+ meta.defaultMetaSessionsDir().startsWith(root) &&
184
+ meta.defaultMetaMailboxDir().startsWith(root) &&
185
+ process.cwd().startsWith(root),
186
+ );
187
+ ok("fence: XDG_RUNTIME_DIR is 0700", (fs.statSync(fenced.XDG_RUNTIME_DIR).mode & 0o777) === 0o700);
188
+
189
+ // ── The caller: a self-fetch citizen whose mailbox we can drain ──────────
190
+ const nativeSessionId = `mux-fresh-call-live-${process.pid}`;
191
+ const caller = meta.upsertMetaSession({
192
+ input: { backend: "claude-code", nativeSessionId, cwd: scratch },
193
+ });
194
+ const callerGid = caller.record.gardenId;
195
+ // A record proves identity; only an ARMED receiver marker makes the mailbox deliverable —
196
+ // without it the callbacks would be refused as mailbox-undeliverable and this smoke would
197
+ // measure nothing.
198
+ meta.writeMetaReceiverMarker({
199
+ gardenId: callerGid,
200
+ backend: "claude-code",
201
+ nativeSessionId,
202
+ ownerPid: process.pid,
203
+ armProvenance: "session-start",
204
+ });
205
+ ok(
206
+ "fixture: the caller citizen was minted INSIDE the fixture store and its mailbox is armed",
207
+ Boolean(callerGid) && caller.path.startsWith(root),
208
+ );
209
+
210
+ // ── One private tmux server per backend ──────────────────────────────────
211
+ // Pi needs fixture HOME so its control socket is isolated. Claude needs canonical
212
+ // operator HOME (and the operator's optional CLAUDE_CONFIG_DIR) or it enters first-run
213
+ // onboarding instead of exercising the configured runtime. Separate servers preserve
214
+ // those backend-native environments without adding an env carrier to the product.
215
+ const nonces = new Map<string, string>();
216
+ for (const backend of ["pi", "claude-code"] as const) {
217
+ const socket = path.join(root, `${backend}.sock`);
218
+ privateSockets.add(socket);
219
+ const env = { ...process.env } as NodeJS.ProcessEnv;
220
+ delete env.TMUX;
221
+ delete env.TMUX_PANE;
222
+ if (backend === "claude-code") {
223
+ env.HOME = REAL_HOME;
224
+ // EXACT operator-env parity on the four XDG roots (issue #67): real HOME plus a
225
+ // fixture XDG_DATA_HOME is the measured state in which Claude's self-update rewrote
226
+ // the operator's real launcher into the fixture tree and teardown dangled it. Each
227
+ // variable is restored to its original value; an originally absent one is DELETED,
228
+ // never filled with a canonical default.
229
+ restoreOriginalXdg(env, ORIGINAL_XDG);
230
+ if (ORIGINAL_CLAUDE_CONFIG_DIR) env.CLAUDE_CONFIG_DIR = ORIGINAL_CLAUDE_CONFIG_DIR;
231
+ else delete env.CLAUDE_CONFIG_DIR;
232
+ }
233
+ if (tmux(socket, ["new-session", "-d", "-s", "fixture", "-c", scratch, "-n", "anchor"], env).status !== 0) {
234
+ throw new Error(`${LABEL}: could not start the private ${backend} tmux server at ${socket}`);
235
+ }
236
+ const anchorPane = tmux(socket, ["display-message", "-p", "-t", "fixture:anchor", "#{pane_id}"], env).stdout;
237
+ const inherited: NodeJS.ProcessEnv = { ...env, TMUX: `${socket},0,0`, TMUX_PANE: anchorPane };
238
+ ok(`${backend}: tmux server is a private socket, never the operator's`, String(inherited.TMUX).startsWith(root));
239
+
240
+ const result = freshCall(
241
+ {
242
+ backend,
243
+ model: LIVE_MODEL[backend],
244
+ task: "Reply with the single word ACK and then stop. Do not read files.",
245
+ callerGardenId: callerGid,
246
+ },
247
+ inherited,
248
+ );
249
+ ok(`${backend}: launch receipt is ok`, result.ok);
250
+ if (!result.ok) return;
251
+ nonces.set(backend, result.receipt.nonce);
252
+ siblingPids.add(Number(result.receipt.panePid));
253
+ ok(
254
+ `${backend}: the receipt carries tmux coordinates, requested model and nonce, and nothing about delivery`,
255
+ Boolean(
256
+ result.receipt.windowId &&
257
+ result.receipt.paneId &&
258
+ result.receipt.model === LIVE_MODEL[backend] &&
259
+ result.receipt.nonce,
260
+ ) && !("gardenId" in result.receipt),
261
+ );
262
+ }
263
+
264
+ // The sender envelope rides INSIDE the mailbox body (` session: <gid> (…)`) — that line
265
+ // is the whole point of this smoke, so it is parsed rather than assumed. `readMetaInbox`
266
+ // drains, so every arrival must be recorded on the pass that saw it.
267
+ const deadline = Date.now() + CALLBACK_WAIT_MS;
268
+ const arrived = new Map<string, string>();
269
+ while (Date.now() < deadline && arrived.size < nonces.size) {
270
+ for (const msg of meta.readMetaInbox({ gardenId: callerGid }).messages) {
271
+ const sender = /^\s*session:\s+(\S+)/m.exec(msg.body)?.[1] ?? "";
272
+ for (const [backend, nonce] of nonces) if (msg.body.includes(nonce) && sender) arrived.set(backend, sender);
273
+ }
274
+ if (arrived.size < nonces.size) spawnSync("sleep", ["3"]);
275
+ }
276
+
277
+ for (const backend of nonces.keys()) {
278
+ const sender = arrived.get(backend);
279
+ ok(
280
+ `${backend}: the nonce came back and its SENDER ENVELOPE carries a garden id — correlation without asking the sibling`,
281
+ Boolean(sender) && /^\d{8}T\d{6}-[0-9a-f]{6}$/.test(String(sender)),
282
+ );
283
+ if (sender) siblingGids.add(sender);
284
+ }
285
+ ok(
286
+ "correlation: the two siblings reported DIFFERENT garden ids — the envelope identifies each one, not the launcher",
287
+ siblingGids.size === arrived.size && !siblingGids.has(callerGid),
288
+ );
289
+ ok(
290
+ "fence: those sibling records live in the FIXTURE store",
291
+ [...siblingGids].every(
292
+ (gid) => fs.existsSync(meta.defaultMetaSessionsDir()) && entrySet(meta.defaultMetaSessionsDir()).includes(gid),
293
+ ),
294
+ );
295
+ } catch (err) {
296
+ // Captured, not rethrown here: the teardown below must run and its findings must AGGREGATE
297
+ // with the run error — neither may hide the other.
298
+ runError = err;
299
+ } finally {
300
+ for (const socket of privateSockets) tmux(socket, ["kill-server"], process.env);
301
+ const panesGone = waitForPidsGone(siblingPids);
302
+ process.chdir(originalCwd);
303
+ const problems: string[] = [];
304
+ // Launcher integrity BEFORE fixture removal, on success and failure alike (issue #67).
305
+ // Removal happens only when it is PROVEN non-destructive: the launcher demonstrably does
306
+ // not reference the fixture tree AND every TRACKED launched pane process is proven gone —
307
+ // a live pane could still rewrite the launcher after the check. (Tracked-pane quiescence
308
+ // only; this claims nothing about untracked detached descendants.) An unproven state
309
+ // blocks removal loudly rather than guessing.
310
+ const launcherProblems = verifyClaudeLauncher(launcherSnapshot);
311
+ const cleanup = assessLauncherCleanup(launcherSnapshot);
312
+ for (const p of cleanup.problems) problems.push(`launcher cleanup: ${p}`);
313
+ if (!panesGone) {
314
+ problems.push(
315
+ `tracked sibling pane processes were not proven gone after private tmux teardown: ${[...siblingPids].join(", ")}`,
316
+ );
317
+ }
318
+ if (!cleanup.safeToRemove || !panesGone) {
319
+ problems.push(
320
+ `fixture removal of ${root} is BLOCKED — ${
321
+ cleanup.safeToRemove
322
+ ? "tracked pane processes are not proven gone"
323
+ : "the real claude launcher references the fixture tree or could not be proven safe"
324
+ }; resolve the named problems above, then remove the tree by hand`,
325
+ );
326
+ } else {
327
+ fs.rmSync(root, { recursive: true, force: true });
328
+ }
329
+ for (const p of launcherProblems) problems.push(`launcher integrity: ${p}`);
330
+ if (problems.length > 0) cleanupError = new Error(problems.join("\n "));
331
+ }
332
+ if (runError || cleanupError) {
333
+ const parts: string[] = [];
334
+ if (runError) parts.push(`RUN: ${runError instanceof Error ? runError.message : String(runError)}`);
335
+ if (cleanupError) parts.push(`CLEANUP:\n ${cleanupError.message}`);
336
+ throw new Error(`${LABEL}: run did not complete cleanly —\n\n${parts.join("\n\n")}`);
337
+ }
338
+
339
+ // ── Prove the fence held, by name and by entry set ───────────────────────
340
+ ok(
341
+ "self-fence: the operator's meta-session store has the same entry set as before",
342
+ entrySet(REAL_META_SESSIONS) === beforeRealStore,
343
+ );
344
+ ok(
345
+ "self-fence: the operator's control-socket dir has the same entry set as before",
346
+ entrySet(REAL_CONTROL_DIR) === beforeRealSockets,
347
+ );
348
+ const realStoreNow = entrySet(REAL_META_SESSIONS);
349
+ const realSocketsNow = entrySet(REAL_CONTROL_DIR);
350
+ ok(
351
+ "self-fence: not one fixture sibling garden id appears in the operator's store or leaves a control-socket residue",
352
+ [...siblingGids].every((gid) => !realStoreNow.includes(gid) && !realSocketsNow.includes(gid)),
353
+ );
354
+ ok(
355
+ "self-fence: the real claude launcher, its link and its resolved target are exactly as pinned before launch",
356
+ verifyClaudeLauncher(launcherSnapshot).length === 0,
357
+ );
358
+
359
+ console.log(`\n${LABEL}: ${passed} checks passed`);
360
+ }
361
+
362
+ main().catch((err) => {
363
+ console.error(`${LABEL}: ${err instanceof Error ? err.message : String(err)}`);
364
+ process.exit(1);
365
+ });