@junghanacs/entwurf 0.20.1 → 0.22.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 (111) hide show
  1. package/AGENTS.md +85 -190
  2. package/BASELINE.md +6 -3
  3. package/CHANGELOG.md +473 -14
  4. package/CONTRIBUTING.md +1 -1
  5. package/DELIVERY.md +332 -60
  6. package/README.md +100 -22
  7. package/VERIFY.md +93 -7
  8. package/docs/acp-backend-rail.md +0 -1
  9. package/docs/external-mcp-host.md +64 -33
  10. package/docs/setup-clean-host.md +151 -17
  11. package/mcp/entwurf-bridge/dist/mcp/entwurf-bridge/src/index.js +130 -114
  12. package/mcp/entwurf-bridge/dist/pi-extensions/lib/codex-caller-seat.js +174 -0
  13. package/mcp/entwurf-bridge/dist/pi-extensions/lib/codex-fresh-preflight.js +519 -0
  14. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-fact-provider.js +22 -2
  15. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-peers-render.js +3 -1
  16. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-contract.js +6 -7
  17. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-native-push.js +30 -17
  18. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-production.js +7 -1
  19. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-runner.js +3 -2
  20. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-send.js +8 -4
  21. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-surface.js +7 -4
  22. package/mcp/entwurf-bridge/dist/pi-extensions/lib/meta-mailbox-body.js +20 -11
  23. package/mcp/entwurf-bridge/dist/pi-extensions/lib/meta-sender-identity.js +227 -1
  24. package/mcp/entwurf-bridge/dist/pi-extensions/lib/mux-fresh-call.js +189 -19
  25. package/mcp/entwurf-bridge/dist/pi-extensions/lib/native-push/adapter.js +10 -7
  26. package/mcp/entwurf-bridge/dist/pi-extensions/lib/native-push/codex-ws-client.js +403 -0
  27. package/mcp/entwurf-bridge/dist/pi-extensions/lib/native-push/register.js +4 -4
  28. package/mcp/entwurf-bridge/dist/pi-extensions/meta-bridge-hook-codex.js +325 -0
  29. package/mcp/entwurf-bridge/dist/scripts/codex-socket-path.js +30 -0
  30. package/mcp/entwurf-bridge/dist/scripts/meta-bridge-fresh-cut.js +6 -1
  31. package/mcp/entwurf-bridge/src/index.ts +154 -116
  32. package/mcp/entwurf-bridge/tsconfig.build.json +10 -0
  33. package/package.json +13 -4
  34. package/pi-extensions/entwurf-control.ts +71 -19
  35. package/pi-extensions/lib/codex-caller-seat.ts +204 -0
  36. package/pi-extensions/lib/codex-fresh-preflight.ts +580 -0
  37. package/pi-extensions/lib/compaction-send-guard.ts +80 -0
  38. package/pi-extensions/lib/entwurf-fact-provider.ts +29 -3
  39. package/pi-extensions/lib/entwurf-peers-render.ts +4 -1
  40. package/pi-extensions/lib/entwurf-v2-contract.ts +6 -7
  41. package/pi-extensions/lib/entwurf-v2-native-push.ts +35 -18
  42. package/pi-extensions/lib/entwurf-v2-production.ts +10 -3
  43. package/pi-extensions/lib/entwurf-v2-runner.ts +3 -2
  44. package/pi-extensions/lib/entwurf-v2-send.ts +16 -11
  45. package/pi-extensions/lib/entwurf-v2-surface.ts +7 -4
  46. package/pi-extensions/lib/meta-mailbox-body.ts +22 -13
  47. package/pi-extensions/lib/meta-sender-identity.ts +305 -0
  48. package/pi-extensions/lib/mux-fresh-call.ts +233 -29
  49. package/pi-extensions/lib/native-push/adapter.ts +21 -24
  50. package/pi-extensions/lib/native-push/codex-ws-client.ts +506 -0
  51. package/pi-extensions/lib/native-push/register.ts +7 -9
  52. package/pi-extensions/meta-bridge-hook-codex.ts +371 -0
  53. package/run.sh +342 -28
  54. package/scripts/check-agy-sender-identity.ts +1 -1
  55. package/scripts/check-codex-app-server-launch.ts +445 -0
  56. package/scripts/check-codex-birth-hook.ts +264 -0
  57. package/scripts/check-codex-bridge-identity.ts +179 -0
  58. package/scripts/check-codex-native-push.ts +386 -0
  59. package/scripts/check-codex-sender-identity.ts +495 -0
  60. package/scripts/check-compaction-send-guard.ts +130 -0
  61. package/scripts/check-copilot-receive-arm.ts +4 -1
  62. package/scripts/check-entwurf-fact-provider.ts +38 -0
  63. package/scripts/check-entwurf-peers-surface.ts +13 -1
  64. package/scripts/check-entwurf-self-address.ts +15 -16
  65. package/scripts/check-entwurf-v2-contract.ts +4 -3
  66. package/scripts/check-entwurf-v2-decider.ts +7 -5
  67. package/scripts/check-entwurf-v2-native-push.ts +35 -7
  68. package/scripts/check-entwurf-v2-production.ts +245 -12
  69. package/scripts/check-entwurf-v2-runner.ts +1 -1
  70. package/scripts/check-entwurf-v2-send.ts +26 -7
  71. package/scripts/check-entwurf-v2-surface.ts +1 -1
  72. package/scripts/check-gate-qualification.ts +8 -3
  73. package/scripts/check-harness-admission-parity.ts +0 -1
  74. package/scripts/check-mux-launch-tmux.ts +345 -4
  75. package/scripts/check-native-push-adapter.ts +20 -16
  76. package/scripts/check-native-push-register.ts +5 -1
  77. package/scripts/check-release-gate-outcomes.ts +47 -1
  78. package/scripts/check-setup-qualification.sh +3 -1
  79. package/scripts/codex-app-server-launch.sh +275 -0
  80. package/scripts/codex-birth-doctor.sh +276 -0
  81. package/scripts/codex-birth-install.sh +414 -0
  82. package/scripts/codex-birth-uninstall.sh +170 -0
  83. package/scripts/codex-mcp-config.py +435 -0
  84. package/scripts/codex-socket-path.ts +33 -0
  85. package/scripts/codex-statusline-config.py +434 -0
  86. package/scripts/codex-terminal-title-config.py +500 -0
  87. package/scripts/codex_toml_io.py +653 -0
  88. package/scripts/lib/codex-fresh-live-protocol.ts +121 -0
  89. package/scripts/lib/codex-fresh-source-receipts.ts +426 -0
  90. package/scripts/lib/launch-receipt-windows.ts +46 -0
  91. package/scripts/lib/tmux-coordinate-row.ts +58 -0
  92. package/scripts/meta-bridge-fresh-cut.ts +6 -1
  93. package/scripts/mutants/codex-app-server-launch.json +157 -0
  94. package/scripts/mutants/codex-caller-seat.json +336 -0
  95. package/scripts/mutants/codex-native.json +838 -0
  96. package/scripts/mutants/compaction-send-guard.json +103 -0
  97. package/scripts/mutants/entwurf-peers.json +19 -0
  98. package/scripts/mutants/mux-fresh-call.json +93 -10
  99. package/scripts/mutants/omp-fresh.json +6 -4
  100. package/scripts/mutants/release-gate.json +13 -0
  101. package/scripts/mutants/v2-surface.json +75 -1
  102. package/scripts/raw-async-delivery/README.md +2 -1
  103. package/scripts/raw-codex-measure/README.md +114 -46
  104. package/scripts/smoke-agy-native-push-live.ts +3 -1
  105. package/scripts/smoke-codex-birth.sh +347 -0
  106. package/scripts/smoke-codex-config-state.sh +700 -0
  107. package/scripts/smoke-codex-fresh-live.ts +1426 -0
  108. package/scripts/smoke-codex-native-push-live.ts +75 -0
  109. package/scripts/smoke-entwurf-chain-live.ts +50 -0
  110. package/scripts/smoke-setup-verdict.sh +125 -10
  111. package/scripts/tsconfig.json +1 -0
@@ -0,0 +1,580 @@
1
+ import * as crypto from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { parse } from "smol-toml";
5
+
6
+ import {
7
+ type CodexProtocolOpener,
8
+ type CodexRpcProtocol,
9
+ type CodexSocketFileCheck,
10
+ checkCodexSocketFile,
11
+ realCodexProtocolOpener,
12
+ resolveCodexDefaultSocketPath,
13
+ } from "./native-push/codex-ws-client.ts";
14
+
15
+ export type CodexPreflightRejectReason =
16
+ | "codex-birth-unit-missing"
17
+ | "codex-mcp-hand-missing"
18
+ | "codex-visible-identity-missing"
19
+ | "codex-birth-trust-missing"
20
+ | "codex-app-server-unavailable";
21
+
22
+ export const CODEX_PREFLIGHT_HINT: Record<CodexPreflightRejectReason, string> = {
23
+ "codex-birth-unit-missing":
24
+ "the Codex SessionStart birth unit is absent, drifted from its recorded digests, or unsafely owned; run `entwurf install-codex-birth`, then `entwurf doctor-codex-birth`",
25
+ "codex-birth-trust-missing":
26
+ "the vendor has recorded no trust receipt for this birth declaration, so the hook is declared and never runs; open a visible plain Codex, answer its prompt with `Trust all and continue`, send one first turn, then `entwurf doctor-codex-birth`",
27
+ "codex-mcp-hand-missing":
28
+ "the Codex user config does not expose the managed entwurf bridge; run `entwurf install-codex-mcp`, then `entwurf doctor-codex-mcp`",
29
+ "codex-visible-identity-missing":
30
+ "Codex tui.status_line does not include thread-title; run `entwurf install-codex-statusline`, then `entwurf doctor-codex-statusline`",
31
+ "codex-app-server-unavailable":
32
+ "the operator-owned Codex app-server default socket is absent or unsafe; start it with `entwurf codex-app-server` from a detached tmux session (one that is NOT where you work), then retry",
33
+ };
34
+
35
+ /**
36
+ * THE CALLER AXIS, AND IT IS NOT THE ONE ABOVE. Everything above asks "can a Codex sibling be
37
+ * OPENED on this host" — birth unit, vendor trust, MCP hand, visible identity, app-server. This
38
+ * asks the opposite question: "can the Codex citizen DOING the opening be located", which is a
39
+ * fact about the CALLER's own config and is required no matter which backend it opens (#95
40
+ * lane B). Keeping them apart is the point: a Pi caller opening a Codex sibling needs the five
41
+ * above and none of this, and a Codex caller opening a Pi sibling needs this and none of those.
42
+ * Folding either into the other would refuse one operator for the other's missing repair.
43
+ */
44
+ export type CodexCallerPreflightRejectReason = "codex-caller-title-missing";
45
+
46
+ /**
47
+ * THE LAUNCH-DIRECTORY AXIS, AND IT IS A THIRD QUESTION AGAIN. The target axis asks "can a Codex
48
+ * sibling be opened on this host", the caller axis asks "can the Codex citizen doing the opening
49
+ * be located", and this asks "will the vendor START A TURN in the directory this launch names" —
50
+ * a fact about ONE directory rather than about the host or the caller, so it is the only axis
51
+ * that needs the resolved launch cwd and the only one that can pass for one call and refuse the
52
+ * next on an unchanged host.
53
+ */
54
+ export type CodexLaunchCwdPreflightRejectReason = "codex-launch-cwd-undecided" | "codex-launch-cwd-untrusted-ancestor";
55
+
56
+ export const CODEX_LAUNCH_CWD_PREFLIGHT_HINT: Record<CodexLaunchCwdPreflightRejectReason, string> = {
57
+ "codex-launch-cwd-undecided":
58
+ "Codex has recorded NO decision for the directory this sibling would start in, so the window would open on the vendor's folder-consent screen and WAIT for a human instead of running its first turn — no rollout, no callback, and nothing to address; either launch in a directory this Codex has already been answered for, or open a plain `codex -C <dir>` there once and answer it, then retry",
59
+ "codex-launch-cwd-untrusted-ancestor":
60
+ "this directory sits inside a project the operator marked `untrusted`, and on this rail the vendor does not offer a consent screen for that — it refuses the startup outright with `pass the repository root explicitly with --cd`, so answering a prompt at this directory would only reproduce that error; launch at that untrusted project's own root instead, or change that project's recorded decision",
61
+ };
62
+
63
+ export const CODEX_CALLER_PREFLIGHT_HINT: Record<CodexCallerPreflightRejectReason, string> = {
64
+ "codex-caller-title-missing":
65
+ "this Codex caller's tui.terminal_title does not include thread-id, so the multiplexer reports no pane title naming this thread and there is no caller seat to open the sibling beside; run `entwurf install-codex-terminal-title`, then `entwurf doctor-codex-terminal-title` (an explicit placement.tmuxSession skips this check entirely, because it never needs the seat)",
66
+ };
67
+
68
+ export interface CodexUnitPaths {
69
+ hooksFile: string;
70
+ helperDir: string;
71
+ stateFile: string;
72
+ }
73
+
74
+ export interface CodexPreflightDeps {
75
+ unitPathsOverride?: CodexUnitPaths;
76
+ operatorUid?: number;
77
+ checkSocket?: (socketPath: string) => CodexSocketFileCheck;
78
+ openProtocol?: CodexProtocolOpener;
79
+ appServerTimeoutMs?: number;
80
+ }
81
+
82
+ /**
83
+ * The unit's paths are the operator's own, derived from the SAME environment the installer
84
+ * reads — never a system location and never a flag. A preflight that resolved them any other
85
+ * way could pass while the installed unit sat somewhere else.
86
+ */
87
+ function unitPaths(env: NodeJS.ProcessEnv): CodexUnitPaths {
88
+ const home = env.HOME?.trim() ?? "";
89
+ const codexHome = env.CODEX_HOME?.trim() || path.join(home, ".codex");
90
+ const dataHome = env.XDG_DATA_HOME?.trim() || path.join(home, ".local", "share");
91
+ const unitRoot = path.join(dataHome, "entwurf", "codex-birth");
92
+ return {
93
+ hooksFile: path.join(codexHome, "hooks.json"),
94
+ helperDir: path.join(unitRoot, "helper"),
95
+ stateFile: path.join(unitRoot, "install-state.json"),
96
+ };
97
+ }
98
+
99
+ const CODEX_MCP_ENV_VARS = [
100
+ "CODEX_HOME",
101
+ "ENTWURF_DIR",
102
+ "PI_CODING_AGENT_DIR",
103
+ "ENTWURF_META_SESSIONS_DIR",
104
+ "ENTWURF_META_MAILBOX_DIR",
105
+ "ENTWURF_META_SENDERS_DIR",
106
+ "ENTWURF_META_RECEIVERS_DIR",
107
+ "TMUX",
108
+ "TMUX_PANE",
109
+ ] as const;
110
+
111
+ function isSafeOwnedFile(file: string, expectedUid: number, executable = false): boolean {
112
+ try {
113
+ const stat = fs.lstatSync(file);
114
+ return (
115
+ stat.isFile() &&
116
+ !stat.isSymbolicLink() &&
117
+ stat.uid === expectedUid &&
118
+ (stat.mode & 0o022) === 0 &&
119
+ (!executable || (stat.mode & 0o111) !== 0)
120
+ );
121
+ } catch {
122
+ return false;
123
+ }
124
+ }
125
+
126
+ function isSafeOwnedDir(dir: string, expectedUid: number): boolean {
127
+ try {
128
+ const stat = fs.lstatSync(dir);
129
+ return stat.isDirectory() && !stat.isSymbolicLink() && stat.uid === expectedUid && (stat.mode & 0o022) === 0;
130
+ } catch {
131
+ return false;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * The unit's own ownership state, read as the digest inventory it is. Bytes that merely
137
+ * EXIST prove nothing: the launcher codex is about to exec must be the one this unit
138
+ * published, so every recorded member is compared to its recorded digest before a sibling
139
+ * is opened. No digest is computed for the VENDOR here — that is a different axis below.
140
+ */
141
+ function closureDriftedFromState(paths: CodexUnitPaths, expectedUid: number): boolean {
142
+ // The directory holding the state carries the state's authority: anyone who can write it
143
+ // can replace the inventory every digest below is compared against.
144
+ if (!isSafeOwnedDir(path.dirname(paths.stateFile), expectedUid)) return true;
145
+ if (!isSafeOwnedDir(path.dirname(path.dirname(paths.stateFile)), expectedUid)) return true;
146
+ if (!isSafeOwnedFile(paths.stateFile, expectedUid)) return true;
147
+ let state: Record<string, unknown>;
148
+ try {
149
+ state = JSON.parse(fs.readFileSync(paths.stateFile, "utf8")) as Record<string, unknown>;
150
+ } catch {
151
+ return true;
152
+ }
153
+ if (state.schema !== "codex-birth-install-state/v1" || state.status !== "installed") return true;
154
+ if (state.hooksFile !== paths.hooksFile || state.helperDir !== paths.helperDir) return true;
155
+ const digest = (file: string): string | null => {
156
+ try {
157
+ return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
158
+ } catch {
159
+ return null;
160
+ }
161
+ };
162
+ if (typeof state.hooksSha256 !== "string" || digest(paths.hooksFile) !== state.hooksSha256) return true;
163
+ const members = state.helperFiles;
164
+ if (!Array.isArray(members)) return true;
165
+ // Exactly the closure the installer publishes: a short inventory would leave a member
166
+ // nothing compares, which is the same hole as not checking digests at all.
167
+ const named = members.map((raw) => (raw as Record<string, unknown>)?.path);
168
+ const expected = [
169
+ "codex-birth-launch.sh",
170
+ "meta-bridge-hook-codex.ts",
171
+ "lib/meta-session.ts",
172
+ "lib/native-push/codex-ws-client.ts",
173
+ "lib/session-id.js",
174
+ "entwurf-capabilities.json",
175
+ ];
176
+ if (named.length !== expected.length) return true;
177
+ if (expected.some((name) => !named.includes(name))) return true;
178
+ if (named.some((name, index) => named.indexOf(name) !== index)) return true;
179
+ for (const raw of members) {
180
+ const member = raw as Record<string, unknown>;
181
+ const rel = member.path;
182
+ if (typeof rel !== "string" || rel.length === 0 || rel.startsWith("/") || rel.split("/").includes("..")) {
183
+ return true;
184
+ }
185
+ if (typeof member.sha256 !== "string" || digest(path.join(paths.helperDir, rel)) !== member.sha256) return true;
186
+ }
187
+ return false;
188
+ }
189
+
190
+ function birthMissing(paths: CodexUnitPaths, expectedUid: number): boolean {
191
+ const launcher = path.join(paths.helperDir, "codex-birth-launch.sh");
192
+ const directories = [
193
+ path.dirname(paths.hooksFile),
194
+ paths.helperDir,
195
+ path.join(paths.helperDir, "lib"),
196
+ path.join(paths.helperDir, "lib", "native-push"),
197
+ ];
198
+ if (directories.some((dir) => !isSafeOwnedDir(dir, expectedUid))) return true;
199
+ if (!isSafeOwnedFile(paths.hooksFile, expectedUid)) return true;
200
+ const closure = [
201
+ [launcher, true],
202
+ [path.join(paths.helperDir, "meta-bridge-hook-codex.ts"), false],
203
+ [path.join(paths.helperDir, "lib", "meta-session.ts"), false],
204
+ [path.join(paths.helperDir, "lib", "native-push", "codex-ws-client.ts"), false],
205
+ [path.join(paths.helperDir, "lib", "session-id.js"), false],
206
+ [path.join(paths.helperDir, "entwurf-capabilities.json"), false],
207
+ ] as const;
208
+ if (closure.some(([file, executable]) => !isSafeOwnedFile(file, expectedUid, executable))) return true;
209
+ try {
210
+ const parsed = JSON.parse(fs.readFileSync(paths.hooksFile, "utf8")) as Record<string, unknown>;
211
+ const events = (parsed.hooks as Record<string, unknown> | undefined)?.SessionStart;
212
+ if (!Array.isArray(events) || events.length !== 1) return true;
213
+ const group = events[0] as Record<string, unknown>;
214
+ if ("matcher" in group || !Array.isArray(group.hooks) || group.hooks.length !== 1) return true;
215
+ const hook = group.hooks[0] as Record<string, unknown>;
216
+ if (Object.keys(hook).sort().join(",") !== "command,timeout,type") return true;
217
+ if (hook.type !== "command" || hook.command !== `'${launcher}'` || hook.timeout !== 30) return true;
218
+ } catch {
219
+ return true;
220
+ }
221
+ return closureDriftedFromState(paths, expectedUid);
222
+ }
223
+
224
+ /**
225
+ * The vendor's own receipt for THIS declaration, read and never written. The key the vendor
226
+ * writes is `<declaration path>:<event>:<group>:<handler>`; the value must be a
227
+ * `trusted_hash` of the shape `sha256:<64 hex>`. What this asserts is that a receipt EXISTS
228
+ * for our declaration identity — never that the hash is correct, which only the vendor can
229
+ * say, and never by launching Codex to find out.
230
+ */
231
+ function trustReceiptMissing(config: Record<string, unknown>, hooksFile: string): boolean {
232
+ const hooks = config.hooks;
233
+ if (hooks == null || typeof hooks !== "object" || Array.isArray(hooks)) return true;
234
+ const state = (hooks as Record<string, unknown>).state;
235
+ if (state == null || typeof state !== "object" || Array.isArray(state)) return true;
236
+ const entry = (state as Record<string, unknown>)[`${hooksFile}:session_start:0:0`];
237
+ if (entry == null || typeof entry !== "object" || Array.isArray(entry)) return true;
238
+ const digest = (entry as Record<string, unknown>).trusted_hash;
239
+ return typeof digest !== "string" || !/^sha256:[0-9a-f]{64}$/.test(digest);
240
+ }
241
+
242
+ function readConfig(env: NodeJS.ProcessEnv): Record<string, unknown> | null {
243
+ try {
244
+ const text = fs.readFileSync(
245
+ path.join(env.CODEX_HOME?.trim() || path.join(env.HOME ?? "", ".codex"), "config.toml"),
246
+ "utf8",
247
+ );
248
+ const value = parse(text);
249
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
250
+ } catch {
251
+ return null;
252
+ }
253
+ }
254
+
255
+ function mcpMissing(config: Record<string, unknown>): boolean {
256
+ const servers = config.mcp_servers;
257
+ if (servers == null || typeof servers !== "object" || Array.isArray(servers)) return true;
258
+ const entry = (servers as Record<string, unknown>)["entwurf-bridge"];
259
+ if (entry == null || typeof entry !== "object" || Array.isArray(entry)) return true;
260
+ const server = entry as Record<string, unknown>;
261
+ if (Object.keys(server).sort().join(",") !== "command,env,env_vars") return true;
262
+ const envVars = server.env_vars;
263
+ if (
264
+ !Array.isArray(envVars) ||
265
+ envVars.length !== CODEX_MCP_ENV_VARS.length ||
266
+ envVars.some((name, index) => name !== CODEX_MCP_ENV_VARS[index])
267
+ )
268
+ return true;
269
+ const env = server.env;
270
+ if (env == null || typeof env !== "object" || Array.isArray(env)) return true;
271
+ const serverEnv = env as Record<string, unknown>;
272
+ return (
273
+ server.command !== "entwurf-bridge" ||
274
+ Object.keys(serverEnv).join(",") !== "ENTWURF_BRIDGE_NATIVE_HOST" ||
275
+ serverEnv.ENTWURF_BRIDGE_NATIVE_HOST !== "codex"
276
+ );
277
+ }
278
+
279
+ function visibleIdentityMissing(config: Record<string, unknown>): boolean {
280
+ const tui = config.tui;
281
+ if (tui == null || typeof tui !== "object" || Array.isArray(tui)) return true;
282
+ const statusLine = (tui as Record<string, unknown>).status_line;
283
+ return !Array.isArray(statusLine) || !statusLine.includes("thread-title");
284
+ }
285
+
286
+ /** `[tui].terminal_title` membership, the exact axis `entwurf doctor-codex-terminal-title`
287
+ * judges. Same shape as `visibleIdentityMissing` and a DIFFERENT key: `status_line` is what a
288
+ * human reads inside the TUI, `terminal_title` is what the multiplexer reports back as
289
+ * `#{pane_title}`. Neither substitutes for the other. */
290
+ function callerTitleMissing(config: Record<string, unknown>): boolean {
291
+ const tui = config.tui;
292
+ if (tui == null || typeof tui !== "object" || Array.isArray(tui)) return true;
293
+ const terminalTitle = (tui as Record<string, unknown>).terminal_title;
294
+ return !Array.isArray(terminalTitle) || !terminalTitle.includes("thread-id");
295
+ }
296
+
297
+ /**
298
+ * The CALLER-side capability, pre-mutation and synchronous.
299
+ *
300
+ * Synchronous because it reads one config file and nothing else: there is no app-server axis
301
+ * here and there must not be one — whether the operator's app-server is up says nothing about
302
+ * whether a caller's pane can be found, and asking would make a placement check fail for a
303
+ * delivery reason.
304
+ *
305
+ * Call it only when the anchor will actually be USED — a codex caller that named an explicit
306
+ * `placement` never consults the title, so refusing it for a missing `thread-id` would be a
307
+ * refusal for an unused capability.
308
+ */
309
+ export function codexCallerFreshPreflight(env: NodeJS.ProcessEnv): CodexCallerPreflightRejectReason | null {
310
+ const config = readConfig(env);
311
+ if (config === null || callerTitleMissing(config)) return "codex-caller-title-missing";
312
+ return null;
313
+ }
314
+
315
+ /**
316
+ * The launch directory's own capability, pre-mutation and synchronous — and DELIBERATELY NARROWER
317
+ * than the vendor's own decision, because the leaf that decides here reads one TOML file while the
318
+ * vendor asks its app-server. Read this whole comment as the scope statement it is: what follows
319
+ * says what this answers, and then says what it refuses to claim.
320
+ *
321
+ * WHY THE AXIS EXISTS. `[source rust-v0.153.4]` a fresh call always passes `--remote`, so the TUI
322
+ * resolves `AppServerTarget::Remote` and startup ALWAYS runs `check_directory_trust` on the `-C`
323
+ * value (`tui/src/lib.rs:1699-1725`). Nothing on that path consults the approval or sandbox policy
324
+ * (`tui/src/onboarding/directory_trust.rs:33-130`), which is why the
325
+ * `--dangerously-bypass-approvals-and-sandbox` token this argv already carries does NOT cover it:
326
+ * approvals and folder consent are two different gates. A directory with no recorded decision
327
+ * renders the consent screen and blocks, and a blocked TUI has started no turn — no rollout, no
328
+ * birth, no callback, and the caller waits out its whole timeout on a window that is merely
329
+ * waiting to be answered. `[측정 2026-09-16]` the two release-gate runs that failed launched in
330
+ * `…-2zznHl` and `…-kSsoAn`, neither of which had an entry; the two that passed launched in
331
+ * `…-db65N2` and `…-pBXxOJ`, both of which did. Unattended, the failure is silent.
332
+ *
333
+ * THE THREE VENDOR OUTCOMES THIS LEAF MODELS, in the vendor's own order
334
+ * (`tui/src/config_update.rs:290-371`, `ProjectTrustHost::Remote`):
335
+ *
336
+ * 1. A DIRECT decision on the exact cwd starts a turn, and BOTH recorded answers do. `trusted`
337
+ * returns before any screen (`:346-354`); a saved `untrusted` is explicitly skipped for a
338
+ * remote target — `if target.uses_remote_workspace() && trust_level == Some(Untrusted) {
339
+ * continue; }` (`onboarding/directory_trust.rs:94-96`), and `uses_remote_workspace()` is
340
+ * exactly `matches!(self, Self::Remote { .. })` (`tui/src/lib.rs:307-309`). Refusing a
341
+ * deliberate `untrusted` would be entwurf inventing a policy the vendor does not have.
342
+ * The key is the exact cwd — `cwd_keys = vec![cwd_key]` (`:290-296`), no root marker, no git
343
+ * root, no parent, all three of which exist only on the Local host. `[측정 2026-09-16]`
344
+ * `~/.codex/config.toml` carried a trusted `/tmp` and still recorded two separate
345
+ * `/tmp/entwurf-codex-fresh-live-*` entries, one per run a human answered.
346
+ * 2. With NO direct decision, an enabled PROJECT LAYER consents on the directory's behalf
347
+ * (`trust_level.is_none() && disabled_project.is_none() && project_layers.any(no
348
+ * disabledReason)` → `Ok(None)`, `:346-354`). Those layers come from the app-server's
349
+ * `ConfigRead { include_layers: true }` answer, which this leaf does not have. A layer that
350
+ * is present but DISABLED is a fourth outcome — the vendor preserves an unknown or untrusted
351
+ * project layer as disabled rather than dropping it, and that path falls through to the
352
+ * screen — and this leaf cannot tell the two apart either. So wherever a layer could exist at
353
+ * all it answers `null`, which folds both outcomes into "proceed".
354
+ * 3. With no direct decision and NO layers, a cwd inside an explicitly `untrusted` ancestor is
355
+ * not a consent screen at all: the remote branch returns an ERROR
356
+ * (`"remote project directory is inside an explicitly untrusted project; pass the repository
357
+ * root explicitly with --cd"`, `:357-371`). That is a different failure with a different
358
+ * repair, so it gets its own reason — answering `Trust` at the child would only reproduce the
359
+ * same vendor error. Note the vendor's own precondition there is `project_layers.is_empty()`,
360
+ * which is why this reason is only reachable after step 2 has found no layer anywhere.
361
+ *
362
+ * WHAT THIS LEAF IS FOR, AND WHAT IT IS NOT. It is NOT equivalent to the vendor's judgment and
363
+ * must not be described as asking "the same question": it reads the operator's own `config.toml`,
364
+ * while the vendor reads an EFFECTIVE config — system, managed and cloud layers merged around that
365
+ * user layer (`config/src/loader/mod.rs:258-290`, `:430-460`) — through its app-server.
366
+ *
367
+ * That gap is affordable because NOTHING HERE REFUSES A LAUNCH. `freshCall` prints what this leaf
368
+ * saw and opens the window anyway: the consent screen is self-repairing when a human is there, and
369
+ * one answer teaches the vendor the directory for good. The one caller that treats the answer as a
370
+ * precondition is `smoke-codex-fresh-live`, where nobody is at the keyboard and a named
371
+ * precondition is worth more than a callback timeout — that gate owns one directory, answered
372
+ * once.
373
+ *
374
+ * So read a non-null answer as "the vendor will probably stop here, and this is the repair", never
375
+ * as a verdict. Absence is not evidence either way, and every case this leaf cannot see resolves
376
+ * to `null`.
377
+ */
378
+ export function codexLaunchCwdFreshPreflight(
379
+ env: NodeJS.ProcessEnv,
380
+ launchCwd: string,
381
+ ): CodexLaunchCwdPreflightRejectReason | null {
382
+ // THREE NON-ANSWERS, AND EVERY ONE OF THEM PROCEEDS. Each is a case where this leaf holds no
383
+ // evidence about what the vendor will do, and a refusal without evidence is exactly the false
384
+ // refusal this axis promises not to produce:
385
+ //
386
+ // - A RELATIVE directory. It cannot match a stored key here, but the vendor does not give up
387
+ // on one — it asks its app-server for a cwd and joins (`config_update.rs:203-224`), so the
388
+ // joined path may well be answered. In production this branch is unreachable anyway: the
389
+ // shared cwd leaf already refuses a non-absolute request as `cwd-not-absolute`, which is a
390
+ // better reason than anything this axis could give.
391
+ // - NO READABLE USER CONFIG. A missing `config.toml` is not "no decisions": the vendor loads
392
+ // an empty user table and merges system, managed and cloud layers around it
393
+ // (`config/src/loader/mod.rs:258-290`, `:430-460`, `:520-610`), any of which can carry the
394
+ // decision or the layer that starts the turn.
395
+ // - NO `projects` TABLE. Same reason: it says the USER layer records nothing, not that the
396
+ // effective config does.
397
+ if (!path.isAbsolute(launchCwd)) return null;
398
+ const config = readConfig(env);
399
+ if (config === null) return null;
400
+ const projects = config.projects;
401
+ if (projects == null || typeof projects !== "object" || Array.isArray(projects)) {
402
+ return null;
403
+ }
404
+ const table = projects as Record<string, unknown>;
405
+ const levelOf = (key: string): string | null => {
406
+ const entry = table[key];
407
+ if (entry == null || typeof entry !== "object" || Array.isArray(entry)) return null;
408
+ const level = (entry as Record<string, unknown>).trust_level;
409
+ // An unrecognised value leaves `trust_level` as `None` on the vendor side too, and `None`
410
+ // with no project layer is precisely the case that renders the screen.
411
+ return level === "trusted" || level === "untrusted" ? level : null;
412
+ };
413
+ // Outcome 1: a direct decision, either answer.
414
+ if (levelOf(launchCwd) !== null) return null;
415
+ // Outcome 2: a PROJECT LAYER may consent with no entry at all, and this leaf cannot enumerate
416
+ // layers — they come from the app-server's `ConfigRead { include_layers: true }` answer. What
417
+ // it CAN decide is the negative: a `.codex` anywhere from the directory upward is the only
418
+ // place such a layer comes from, so when none exists the vendor's `project_layers` really is
419
+ // empty and the two remaining outcomes below are computable. Where one could exist, answer
420
+ // `null`.
421
+ //
422
+ // EXISTENCE, not ownership, and the weaker predicate is the load-bearing one. The vendor
423
+ // admits a layer on its own terms — an unknown or untrusted one is preserved as a DISABLED
424
+ // layer, not dropped — and none of that consults owner/mode/symlink safety. Asking for a
425
+ // safely-owned directory here would let a layer the vendor sees go unseen by this leaf, which
426
+ // would then synthesise an `untrusted-ancestor` refusal for a launch the vendor was going to
427
+ // run. That is the false refusal this axis must never produce, so the check is the widest
428
+ // thing that still means "a layer could live here".
429
+ //
430
+ // The operator's own CODEX HOME is excluded, and excluding it is what keeps this axis from
431
+ // being a no-op: `~/.codex` is an ancestor of nearly every directory anyone launches a sibling
432
+ // in, and it is the USER config root rather than a project layer — the vendor names those
433
+ // apart (`layer.name.dotCodexFolder` for a project, the home for the user layer). Counting it
434
+ // would answer `null` for every path under `$HOME` and the check would never fire in real use.
435
+ const codexHome = path.resolve(env.CODEX_HOME?.trim() || path.join(env.HOME ?? "", ".codex"));
436
+ for (let dir = launchCwd; ; ) {
437
+ const candidate = path.join(dir, ".codex");
438
+ if (candidate !== codexHome && fs.existsSync(candidate)) return null;
439
+ const parent = path.dirname(dir);
440
+ if (parent === dir) break;
441
+ dir = parent;
442
+ }
443
+ // Outcome 3: no layer anywhere and an explicitly untrusted ancestor — the vendor's own
444
+ // precondition for that branch is exactly `project_layers.is_empty()`, which the loop above
445
+ // has now established. It is reported as its own failure because its repair is to launch at
446
+ // that root, never to answer a prompt at the child.
447
+ //
448
+ // The MATCH IS NOT THE VENDOR'S and is not claimed to be. The vendor compares path URIs
449
+ // (`LegacyAppPathString` → `PathUri::starts_with`, segment-aware, fail-closed on encoded
450
+ // separators); this compares plain strings on a separator boundary. Where the two could
451
+ // disagree — a key or a cwd that is not a plain POSIX path — this answers `undecided` rather
452
+ // than `untrusted-ancestor`. Be exact about what that buys: BOTH are refusals, so this is NOT
453
+ // the launch-permissive direction. What it weakens is the SPECIFIC-ERROR claim — the ancestor
454
+ // reason names another directory as the repair, and naming the wrong one is worse than saying
455
+ // "no decision here". Neither vendor outcome on this branch starts a turn, so the guarantee
456
+ // above is untouched either way.
457
+ const plainPosixPath = (value: string): boolean =>
458
+ !value.includes("%") && !value.includes("\\") && !value.split("/").some((seg) => seg === "." || seg === "..");
459
+ if (plainPosixPath(launchCwd)) {
460
+ for (const key of Object.keys(table)) {
461
+ if (levelOf(key) !== "untrusted" || !plainPosixPath(key)) continue;
462
+ if (launchCwd === key || launchCwd.startsWith(key.endsWith("/") ? key : `${key}/`)) {
463
+ return "codex-launch-cwd-untrusted-ancestor";
464
+ }
465
+ }
466
+ }
467
+ return "codex-launch-cwd-undecided";
468
+ }
469
+
470
+ const DEFAULT_APP_SERVER_TIMEOUT_MS = 5_000;
471
+
472
+ function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
473
+ return new Promise((resolve, reject) => {
474
+ const timer = setTimeout(() => reject(new Error("codex app-server exchange timed out")), timeoutMs);
475
+ promise.then(
476
+ (value) => {
477
+ clearTimeout(timer);
478
+ resolve(value);
479
+ },
480
+ (error) => {
481
+ clearTimeout(timer);
482
+ reject(error);
483
+ },
484
+ );
485
+ });
486
+ }
487
+
488
+ /**
489
+ * A bounded real initialize/liveness exchange over the app-server's own JSON-RPC. The inode
490
+ * check above only proves a socket FILE with the right owner and mode exists — a dead
491
+ * app-server's stale socket a new process has not reclaimed yet passes that check identically
492
+ * to a live one. Only a real connection plus a real `initialize` round trip distinguishes them.
493
+ * Any failure — refused/hung connection, a response that never lands within the bound, or a
494
+ * reply the transport itself rejects — answers identically: not live. This is deliberately not
495
+ * `probeCodexThread`: preflight asks "is the app-server there to talk to", never "is a specific
496
+ * thread loaded", so it carries no thread id and no retry/backoff policy.
497
+ */
498
+ async function appServerIsLive(
499
+ socketPath: string,
500
+ openProtocol: CodexProtocolOpener,
501
+ timeoutMs: number,
502
+ ): Promise<boolean> {
503
+ let protocol: CodexRpcProtocol;
504
+ const opening = openProtocol.open(socketPath);
505
+ try {
506
+ protocol = await withTimeout(opening, timeoutMs);
507
+ } catch {
508
+ // The bound expired (or the connect failed), but a slow open can still LAND afterwards.
509
+ // Nothing else holds that handle, so a late success would leave a live connection to the
510
+ // operator's app-server open for the rest of this process. Close it when it arrives —
511
+ // the answer stays "not live" either way; this only refuses to leak.
512
+ void opening.then(
513
+ (late) => {
514
+ try {
515
+ late.close();
516
+ } catch {
517
+ // best-effort: the socket may already be gone.
518
+ }
519
+ },
520
+ () => {
521
+ // The open failed; there is nothing to close.
522
+ },
523
+ );
524
+ return false;
525
+ }
526
+ try {
527
+ await withTimeout(
528
+ protocol.request("initialize", {
529
+ clientInfo: { name: "entwurf-fresh-preflight", title: "entwurf-fresh-preflight", version: "0" },
530
+ capabilities: { experimentalApi: true, requestAttestation: false },
531
+ }),
532
+ timeoutMs,
533
+ );
534
+ return true;
535
+ } catch {
536
+ return false;
537
+ } finally {
538
+ try {
539
+ protocol.close();
540
+ } catch {
541
+ // best-effort: the socket may already be gone.
542
+ }
543
+ }
544
+ }
545
+
546
+ /**
547
+ * Async because the app-server axis now performs a real bounded protocol exchange, not just an
548
+ * inode check (see `appServerIsLive`). Every other axis stays synchronous filesystem/config
549
+ * work; only the last `await` point can suspend.
550
+ */
551
+ export async function codexFreshPreflight(
552
+ env: NodeJS.ProcessEnv,
553
+ deps: CodexPreflightDeps = {},
554
+ ): Promise<CodexPreflightRejectReason | null> {
555
+ const paths = deps.unitPathsOverride ?? unitPaths(env);
556
+ // A relative root would make the declaration's launcher path — the very string the vendor
557
+ // keys its trust receipt to — depend on this process's cwd.
558
+ if (!path.isAbsolute(paths.hooksFile) || !path.isAbsolute(paths.helperDir) || !path.isAbsolute(paths.stateFile)) {
559
+ return "codex-birth-unit-missing";
560
+ }
561
+ if (birthMissing(paths, deps.operatorUid ?? process.getuid?.() ?? -1)) {
562
+ return "codex-birth-unit-missing";
563
+ }
564
+ const config = readConfig(env);
565
+ // The vendor receipt is a SEPARATE reject from our bytes: perfect bytes the vendor will
566
+ // not run and absent bytes are two different repairs, and folding them would send the
567
+ // operator to the installer for something only they can answer in their own Codex.
568
+ if (config === null || trustReceiptMissing(config, paths.hooksFile)) return "codex-birth-trust-missing";
569
+ if (mcpMissing(config)) return "codex-mcp-hand-missing";
570
+ if (visibleIdentityMissing(config)) return "codex-visible-identity-missing";
571
+ const socketPath = resolveCodexDefaultSocketPath(env);
572
+ const socket = (deps.checkSocket ?? checkCodexSocketFile)(socketPath);
573
+ if (!socket.ok) return "codex-app-server-unavailable";
574
+ const live = await appServerIsLive(
575
+ socketPath,
576
+ deps.openProtocol ?? realCodexProtocolOpener,
577
+ deps.appServerTimeoutMs ?? DEFAULT_APP_SERVER_TIMEOUT_MS,
578
+ );
579
+ return live ? null : "codex-app-server-unavailable";
580
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * compaction-send-guard — whether a control-socket `send` may call `pi.sendMessage`.
3
+ *
4
+ * Pi 0.85.1 has no public `ExtensionContext.isCompacting()`. Compaction is non-idle
5
+ * (`AgentSession.isIdle` = no agent run AND not compacting) but `sendCustomMessage`
6
+ * does not refuse it. A non-streaming `triggerTurn:true` send starts `_runAgentPrompt`
7
+ * while `compact()` is rewriting the session tree — the field path that can make
8
+ * compaction "풀린다" and still return `delivered:true` (#111).
9
+ *
10
+ * Public facts the resident can see, without reaching into `AgentSession`:
11
+ * - `ctx.isIdle()`
12
+ * - `ctx.signal` — `agent.activeRun?.abortController.signal`, undefined when
13
+ * there is no low-level agent run. This is NOT `AgentSession.isStreaming`
14
+ * (`_isAgentRunActive`). After `agent.prompt()` returns, `_handlePostAgentRun`
15
+ * retry / auto-compaction / continuation keeps `_isAgentRunActive=true` while
16
+ * `ctx.signal` is already undefined.
17
+ * - `session_before_compact` / `session_compact` / `session_compact_failed`
18
+ *
19
+ * Terminal semantics, read from installed `agent-session.js`:
20
+ * - `session_before_compact` fires AFTER the abort controller is set (manual
21
+ * compact then awaits summarization auth — a real start-race window).
22
+ * - `session_compact` is NOT guaranteed (only if the saved compaction entry is
23
+ * found by summary-text match).
24
+ * - `session_compact_failed` fires on cancel / abort / fail.
25
+ * - `isIdle()` becoming true is the honest recovery for a missed success event.
26
+ *
27
+ * Auto-compaction can run inside `_handlePostAgentRun` while `_isAgentRunActive`
28
+ * stays true, so only the event flag can name that window `compacting`.
29
+ *
30
+ * Quiet unknown (`!idle && !hasAgentSignal && !armed`) is fail-closed as `busy`,
31
+ * not `compacting`: the public pair cannot tell manual-compact start race from
32
+ * branch summary, post-run retry, or continuation. Calling those `compacting`
33
+ * is a false claim. The start-race guarantee is still "do not call sendMessage".
34
+ *
35
+ * The predicate takes no send mode. Every mode is refused the same way.
36
+ */
37
+
38
+ export const COMPACTION_SEND_REJECT = "compacting" as const;
39
+ export const BUSY_SEND_REJECT = "busy" as const;
40
+ export type CompactionSendReject = typeof COMPACTION_SEND_REJECT | typeof BUSY_SEND_REJECT;
41
+
42
+ export type CompactionGuard = {
43
+ /** Armed by `session_before_compact`; disarmed by either terminal event or idle recovery. */
44
+ armed: boolean;
45
+ };
46
+
47
+ export type CompactionSendFacts = {
48
+ idle: boolean;
49
+ /** `ctx.signal !== undefined`. Not `AgentSession.isStreaming`. */
50
+ hasAgentSignal: boolean;
51
+ };
52
+
53
+ export function createCompactionGuard(): CompactionGuard {
54
+ return { armed: false };
55
+ }
56
+
57
+ export function noteCompactionBefore(guard: CompactionGuard): void {
58
+ guard.armed = true;
59
+ }
60
+
61
+ export function noteCompactionTerminal(guard: CompactionGuard): void {
62
+ guard.armed = false;
63
+ }
64
+
65
+ /**
66
+ * `null` = admit (caller may `pi.sendMessage`).
67
+ * `"compacting"` = event-armed compaction; `"busy"` = quiet unknown non-idle.
68
+ * Either way: do not call `pi.sendMessage`; do not emit `delivered:true`.
69
+ */
70
+ export function compactionSendReject(guard: CompactionGuard, facts: CompactionSendFacts): CompactionSendReject | null {
71
+ if (facts.idle) {
72
+ // Idle means Pi is neither in an agent run nor compacting. Also recovers a
73
+ // missed `session_compact` so a later ordinary stream is not stuck refused.
74
+ guard.armed = false;
75
+ return null;
76
+ }
77
+ if (guard.armed) return COMPACTION_SEND_REJECT;
78
+ if (!facts.hasAgentSignal) return BUSY_SEND_REJECT;
79
+ return null; // live agent run — steer/followUp unchanged
80
+ }