@junghanacs/entwurf 0.20.1 → 0.21.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 (96) hide show
  1. package/AGENTS.md +85 -190
  2. package/BASELINE.md +4 -3
  3. package/CHANGELOG.md +195 -14
  4. package/CONTRIBUTING.md +1 -1
  5. package/DELIVERY.md +202 -60
  6. package/README.md +49 -22
  7. package/VERIFY.md +37 -7
  8. package/docs/acp-backend-rail.md +0 -1
  9. package/docs/external-mcp-host.md +54 -33
  10. package/docs/setup-clean-host.md +110 -17
  11. package/mcp/entwurf-bridge/dist/mcp/entwurf-bridge/src/index.js +101 -109
  12. package/mcp/entwurf-bridge/dist/pi-extensions/lib/codex-fresh-preflight.js +326 -0
  13. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-fact-provider.js +22 -2
  14. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-peers-render.js +3 -1
  15. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-contract.js +6 -7
  16. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-native-push.js +30 -17
  17. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-production.js +7 -1
  18. package/mcp/entwurf-bridge/dist/pi-extensions/lib/entwurf-v2-surface.js +7 -4
  19. package/mcp/entwurf-bridge/dist/pi-extensions/lib/meta-mailbox-body.js +20 -11
  20. package/mcp/entwurf-bridge/dist/pi-extensions/lib/meta-sender-identity.js +227 -1
  21. package/mcp/entwurf-bridge/dist/pi-extensions/lib/mux-fresh-call.js +50 -15
  22. package/mcp/entwurf-bridge/dist/pi-extensions/lib/native-push/adapter.js +10 -7
  23. package/mcp/entwurf-bridge/dist/pi-extensions/lib/native-push/codex-ws-client.js +403 -0
  24. package/mcp/entwurf-bridge/dist/pi-extensions/lib/native-push/register.js +4 -4
  25. package/mcp/entwurf-bridge/dist/pi-extensions/meta-bridge-hook-codex.js +325 -0
  26. package/mcp/entwurf-bridge/dist/scripts/meta-bridge-fresh-cut.js +6 -1
  27. package/mcp/entwurf-bridge/src/index.ts +115 -111
  28. package/mcp/entwurf-bridge/tsconfig.build.json +1 -0
  29. package/package.json +13 -4
  30. package/pi-extensions/entwurf-control.ts +71 -19
  31. package/pi-extensions/lib/codex-fresh-preflight.ts +363 -0
  32. package/pi-extensions/lib/compaction-send-guard.ts +80 -0
  33. package/pi-extensions/lib/entwurf-fact-provider.ts +29 -3
  34. package/pi-extensions/lib/entwurf-peers-render.ts +4 -1
  35. package/pi-extensions/lib/entwurf-v2-contract.ts +6 -7
  36. package/pi-extensions/lib/entwurf-v2-native-push.ts +35 -18
  37. package/pi-extensions/lib/entwurf-v2-production.ts +10 -3
  38. package/pi-extensions/lib/entwurf-v2-surface.ts +7 -4
  39. package/pi-extensions/lib/meta-mailbox-body.ts +22 -13
  40. package/pi-extensions/lib/meta-sender-identity.ts +305 -0
  41. package/pi-extensions/lib/mux-fresh-call.ts +64 -19
  42. package/pi-extensions/lib/native-push/adapter.ts +21 -24
  43. package/pi-extensions/lib/native-push/codex-ws-client.ts +506 -0
  44. package/pi-extensions/lib/native-push/register.ts +7 -9
  45. package/pi-extensions/meta-bridge-hook-codex.ts +371 -0
  46. package/run.sh +218 -28
  47. package/scripts/check-agy-sender-identity.ts +1 -1
  48. package/scripts/check-codex-birth-hook.ts +264 -0
  49. package/scripts/check-codex-bridge-identity.ts +179 -0
  50. package/scripts/check-codex-native-push.ts +386 -0
  51. package/scripts/check-codex-sender-identity.ts +495 -0
  52. package/scripts/check-compaction-send-guard.ts +130 -0
  53. package/scripts/check-copilot-receive-arm.ts +4 -1
  54. package/scripts/check-entwurf-fact-provider.ts +38 -0
  55. package/scripts/check-entwurf-peers-surface.ts +13 -1
  56. package/scripts/check-entwurf-self-address.ts +15 -16
  57. package/scripts/check-entwurf-v2-contract.ts +4 -3
  58. package/scripts/check-entwurf-v2-decider.ts +7 -5
  59. package/scripts/check-entwurf-v2-native-push.ts +35 -7
  60. package/scripts/check-entwurf-v2-production.ts +203 -11
  61. package/scripts/check-entwurf-v2-runner.ts +1 -1
  62. package/scripts/check-entwurf-v2-surface.ts +1 -1
  63. package/scripts/check-gate-qualification.ts +6 -3
  64. package/scripts/check-harness-admission-parity.ts +0 -1
  65. package/scripts/check-mux-launch-tmux.ts +47 -2
  66. package/scripts/check-native-push-adapter.ts +20 -16
  67. package/scripts/check-native-push-register.ts +5 -1
  68. package/scripts/check-release-gate-outcomes.ts +47 -1
  69. package/scripts/check-setup-qualification.sh +3 -1
  70. package/scripts/codex-birth-doctor.sh +276 -0
  71. package/scripts/codex-birth-install.sh +414 -0
  72. package/scripts/codex-birth-uninstall.sh +170 -0
  73. package/scripts/codex-mcp-config.py +435 -0
  74. package/scripts/codex-statusline-config.py +434 -0
  75. package/scripts/codex_toml_io.py +532 -0
  76. package/scripts/lib/codex-fresh-live-protocol.ts +113 -0
  77. package/scripts/lib/codex-fresh-source-receipts.ts +399 -0
  78. package/scripts/lib/launch-receipt-windows.ts +46 -0
  79. package/scripts/lib/tmux-coordinate-row.ts +58 -0
  80. package/scripts/meta-bridge-fresh-cut.ts +6 -1
  81. package/scripts/mutants/codex-native.json +838 -0
  82. package/scripts/mutants/compaction-send-guard.json +103 -0
  83. package/scripts/mutants/entwurf-peers.json +19 -0
  84. package/scripts/mutants/mux-fresh-call.json +19 -8
  85. package/scripts/mutants/omp-fresh.json +6 -4
  86. package/scripts/mutants/release-gate.json +13 -0
  87. package/scripts/mutants/v2-surface.json +53 -1
  88. package/scripts/raw-async-delivery/README.md +2 -1
  89. package/scripts/raw-codex-measure/README.md +114 -46
  90. package/scripts/smoke-agy-native-push-live.ts +3 -1
  91. package/scripts/smoke-codex-birth.sh +347 -0
  92. package/scripts/smoke-codex-config-state.sh +511 -0
  93. package/scripts/smoke-codex-fresh-live.ts +1186 -0
  94. package/scripts/smoke-codex-native-push-live.ts +75 -0
  95. package/scripts/smoke-setup-verdict.sh +123 -10
  96. package/scripts/tsconfig.json +1 -0
@@ -32,6 +32,7 @@ import {
32
32
  isOutOfSocketDomainGardenIdConflict,
33
33
  type PeerObserver,
34
34
  resolveFactList,
35
+ UNOBSERVED_PEER,
35
36
  } from "./entwurf-facts.ts";
36
37
  import { observePeerFacts } from "./entwurf-peer-observe.ts";
37
38
  import { isLivenessSupported } from "./entwurf-v2-contract.ts";
@@ -102,9 +103,12 @@ export interface EntwurfFactsDeps {
102
103
  /** Observation axis (#101): per-citizen receiver + transcript facts. Defaults to the
103
104
  * REAL measurement — the same seam shape `makeProductionEntwurfV2Deps` uses, so the two
104
105
  * wiring sites (MCP + pi-native) cannot drift by each passing their own observer, and a
105
- * gate still drives the assembly with a fake and no filesystem. A caller that injects
106
- * nothing gets facts; a caller that injects `() => UNOBSERVED_PEER` says so on every row. */
106
+ * gate still drives the assembly with a fake and no filesystem. */
107
107
  observe?: PeerObserver;
108
+ /** Optional presentation budget. Undefined preserves the generic fact provider's full
109
+ * observation contract; peers surfaces pass their shared render limit. Older machine
110
+ * payload rows then say `unobserved` rather than fabricating `active` / `exists`. */
111
+ observationLimit?: number;
108
112
  }
109
113
 
110
114
  function diagnosticSortKey(d: EntwurfDiagnostic): string {
@@ -195,9 +199,31 @@ export async function listEntwurfFacts(deps: EntwurfFactsDeps): Promise<EntwurfF
195
199
  // 4. resolveFactList over CLEAN inputs only. Its throws (duplicate identity /
196
200
  // unprobed in-domain citizen) are impossible wiring invariants — left to
197
201
  // fire as the last line of defense, never caught here.
202
+ //
203
+ // A peers surface may bound observation to its SAME newest rendered rows. Receiver
204
+ // observation can inspect process state and historical Claude markers, so doing it
205
+ // for every retained record made bounded text grow linearly with history. The generic
206
+ // provider stays unbounded when no limit is supplied. Either way the full clean
207
+ // identity/probe arrays reach the core: certification, duplicate detection,
208
+ // diagnostics, liveness, and the machine payload remain complete. Only an observation
209
+ // not performed becomes `unobserved`.
198
210
  const cleanIdentities = identities.filter((i) => !conflictGids.has(i.gardenId));
199
211
  const cleanProbes = probes.filter((p) => !conflictGids.has(p.gardenId));
200
- const facts: FactList = resolveFactList(cleanIdentities, cleanProbes, deps.observe ?? observePeerFacts);
212
+ const observe = deps.observe ?? observePeerFacts;
213
+ let selectedObserve = observe;
214
+ if (deps.observationLimit !== undefined) {
215
+ if (!Number.isSafeInteger(deps.observationLimit) || deps.observationLimit < 0) {
216
+ throw new Error("listEntwurfFacts: observationLimit must be a non-negative safe integer");
217
+ }
218
+ const observedGardenIds = new Set(
219
+ [...cleanIdentities]
220
+ .sort((a, b) => (a.gardenId < b.gardenId ? -1 : a.gardenId > b.gardenId ? 1 : 0))
221
+ .slice(Math.max(0, cleanIdentities.length - deps.observationLimit))
222
+ .map((identity) => identity.gardenId),
223
+ );
224
+ selectedObserve = (identity) => (observedGardenIds.has(identity.gardenId) ? observe(identity) : UNOBSERVED_PEER);
225
+ }
226
+ const facts: FactList = resolveFactList(cleanIdentities, cleanProbes, selectedObserve);
201
227
 
202
228
  // 5. #50 C4 demotion: a record-less socket is a diagnostic, not a listing
203
229
  // section. One diagnostic per socket (subjects aggregate at render, F8);
@@ -39,6 +39,9 @@ export interface EntwurfPeersRender {
39
39
  payload: EntwurfPeersPayload;
40
40
  }
41
41
 
42
+ /** Human rows and expensive provider observations share this one presentation budget. */
43
+ export const ENTWURF_PEERS_RENDER_LIMIT = 32;
44
+
42
45
  // `receiver` and `transcript` are OBSERVED facts, not routing (#101): they say what was
43
46
  // found on disk for this citizen, and a caller still asks entwurf_v2 what may be done
44
47
  // about it. They earn a column because for every claude-code row `liveness` reads
@@ -124,7 +127,7 @@ function renderDiagnosticLines(diagnostics: EntwurfDiagnostic[]): string[] {
124
127
  return lines;
125
128
  }
126
129
 
127
- function compactLines(lines: string[], max: number = 32): string[] {
130
+ function compactLines(lines: string[], max: number = ENTWURF_PEERS_RENDER_LIMIT): string[] {
128
131
  if (lines.length <= max) return lines;
129
132
  const omitted = lines.length - max;
130
133
  return [` … (${omitted} older entries omitted; showing latest ${max})`, ...lines.slice(-max)];
@@ -122,13 +122,12 @@ export function isLivenessSupported(backend: string): boolean {
122
122
 
123
123
  // ── Native-push backend domain (봉인 2/4) ───────────────────────────────────
124
124
  // A backend whose liveness is measured by the SEPARATE native-push adapter rail (a
125
- // live app-server conversation probe — antigravity's LS gRPC), NOT a control
126
- // socket. This domain is DISJOINT from LIVENESS_DOMAIN_BACKENDS: an agy session
127
- // is `unsupported` on the socket FACT axis (entwurf_peers) yet fully
128
- // measured + deliverable on the native-push axis. The two are separate rails on
129
- // purpose check-entwurf-facts pins both sets and asserts their intersection is
130
- // (a backend can never be in both domains).
131
- export const NATIVE_PUSH_BACKENDS = ["antigravity"] as const;
125
+ // live vendor app-server target probe), NOT a control socket. This domain is DISJOINT
126
+ // from LIVENESS_DOMAIN_BACKENDS: an Antigravity or Codex session is `unsupported` on
127
+ // the socket FACT axis (entwurf_peers) yet independently measured on the native-push
128
+ // axis. The two are separate rails on purpose — check-entwurf-facts pins both sets
129
+ // and asserts their intersection is (a backend can never be in both domains).
130
+ export const NATIVE_PUSH_BACKENDS = ["antigravity", "codex"] as const;
132
131
  export type NativePushBackend = (typeof NATIVE_PUSH_BACKENDS)[number];
133
132
 
134
133
  export function nativePushSupported(backend: string): backend is NativePushBackend {
@@ -5,11 +5,10 @@
5
5
  * ROUTING (the NATIVE_PUSH_DISPATCH_TABLE did) and carries NO release seam — a native-push
6
6
  * plan is the LOCK-FREE path (봉인 4), so a lock leak is structurally impossible here.
7
7
  *
8
- * This is where the 1-shot retry lives NOT in the adapter leaf (봉인 3). The decider
9
- * probed a fresh route and planted it in the plan; the executor sends over it, and on a
10
- * failure it re-probes ONCE (the volatile LS port may have shifted between decide and
11
- * execute) and re-sends. A second failure is fail-loud (no infinite loop). This mirrors the
12
- * control-socket send-fallback pattern: the decider stays pure, the hand owns the retry.
8
+ * Retry is an adapter capability, not a rail-wide assumption. Antigravity re-probes once
9
+ * because its volatile LS port can shift before send. Codex never retries: `codex queue`
10
+ * may have accepted the message before its receipt failed, so replay could duplicate it.
11
+ * The decider stays pure; this hand enforces the adapter's declared policy.
13
12
  *
14
13
  * A native-push send has NO in-band refuse (there is no live receiver to answer
15
14
  * success:false) — like a mailbox enqueue, it either succeeds or THROWS. The hand never
@@ -18,6 +17,7 @@
18
17
 
19
18
  import type { ExecutionPlan } from "./entwurf-v2-decider.ts";
20
19
  import type { LockClaim } from "./entwurf-v2-lock.ts";
20
+ import { formatMetaMailboxBody, type MailboxSenderEnvelope } from "./meta-mailbox-body.ts";
21
21
  import { type NativePushAdapter, type NativePushRoute, resolveNativePushAdapter } from "./native-push/adapter.ts";
22
22
 
23
23
  /** The native-push slice of the ExecutionPlan union (the decider plants it, this consumes it). */
@@ -25,16 +25,14 @@ export type NativePushPlan = Extract<ExecutionPlan, { transport: "native-push" }
25
25
 
26
26
  export interface NativePushSendResult {
27
27
  success: true;
28
- /** Whether the 1-shot re-probe→re-send fired (the first send over the planted route failed). */
28
+ /** Whether the adapter's one permitted re-probe→re-send fired. */
29
29
  retried: boolean;
30
30
  }
31
31
 
32
32
  /**
33
- * Deliver `content` into the conversation, owning the 1-shot retry (봉인 3). Send over the
34
- * planted (decider-probed) route first; on failure re-probe ONCE and re-send over the fresh
35
- * route; a second failure PROPAGATES (fail-loud). If the re-probe finds the target no longer
36
- * alive, throw — a failed send into a now-dead conversation is an honest non-delivery, never
37
- * a silent success. The re-probe is the ONLY re-derivation of the volatile route.
33
+ * Deliver `content` through the decider-probed route. A non-retriable adapter propagates
34
+ * the first failure unchanged. A retriable adapter re-probes once and sends once more only
35
+ * when the target is still alive; no adapter gets a third attempt.
38
36
  */
39
37
  export async function deliverViaNativePush(
40
38
  adapter: NativePushAdapter,
@@ -46,8 +44,8 @@ export async function deliverViaNativePush(
46
44
  await adapter.send(route, nativeSessionId, content);
47
45
  return { success: true, retried: false };
48
46
  } catch (firstErr) {
49
- // 1-shot re-probe → re-send: the volatile LS route may have shifted since the decider
50
- // probed it. Re-discover it fresh and retry exactly once.
47
+ if (!adapter.retriable) throw firstErr;
48
+ // One re-probe and one retry for adapters whose send boundary is safe to replay.
51
49
  const reprobe = await adapter.probe(nativeSessionId);
52
50
  if (reprobe.status !== "alive") {
53
51
  throw new Error(
@@ -65,22 +63,41 @@ export async function deliverViaNativePush(
65
63
  * registry). Injected so the 5d gate proves the wiring with a fake adapter. */
66
64
  export interface NativePushSendDeps {
67
65
  resolveAdapter?: (backend: string) => NativePushAdapter;
66
+ /** The SAME provider the mailbox hand receives (`makeProductionEntwurfV2Deps` passes one
67
+ * `opts.senderProvider` to both). When it yields an envelope, the injected content is the
68
+ * mailbox-serialized body — see the render note on `makeNativePushSend`. Absent/undefined
69
+ * preserves the raw `plan.message`. */
70
+ senderProvider?: () => MailboxSenderEnvelope | undefined;
68
71
  }
69
72
 
70
73
  /**
71
74
  * Build the production `sendNativePush(plan, lock)` adapter the runner consumes. It IGNORES
72
- * `lock` entirely (a native-push plan is lock-free, 봉인 4) the field exists only to match
73
- * the DispatchExecutorDeps hand signature. It resolves the adapter from the plan's backend
74
- * and delivers with the 1-shot retry. A delivery throw surfaces as a REJECTED promise (the
75
- * runner's try/catch maps it to execution-failed).
75
+ * `lock` entirely (a native-push plan is lock-free, 봉인 4), resolves the adapter, then applies
76
+ * that adapter's retry policy. A delivery throw surfaces as a REJECTED promise (the runner's
77
+ * try/catch maps it to execution-failed).
78
+ *
79
+ * SENDER ENVELOPE (measured #95). Direct injection used to hand the adapter the raw
80
+ * `plan.message`, so a native-push citizen received a body with no sender. The #95 A LIVE run
81
+ * measured what that costs: a fresh Pi's nonce-only callback landed in the Codex thread as
82
+ * bare text, and Codex could not name who called it — the callback was uncorrelatable. The
83
+ * control-socket rail carries the envelope in its RPC framing and the mailbox rail serializes
84
+ * it into the body; this rail has neither, so it renders the SAME `formatMetaMailboxBody` SSOT
85
+ * the mailbox uses. Rendered ONCE, before `deliverViaNativePush`, so an Antigravity re-probe
86
+ * retry replays byte-identical content (including its timestamp) instead of a second render.
87
+ * The adapter stays a dumb pipe — its signature is unchanged and it never learns about senders.
76
88
  */
77
89
  export function makeNativePushSend(
78
90
  deps: NativePushSendDeps = {},
79
91
  ): (plan: NativePushPlan, lock: LockClaim | null) => Promise<NativePushSendResult> {
80
92
  const resolveAdapter = deps.resolveAdapter ?? resolveNativePushAdapter;
93
+ const senderProvider = deps.senderProvider;
81
94
  // `_lock` is named for the hand contract but NEVER read — native-push owns/releases no lock.
82
95
  return async (plan: NativePushPlan, _lock: LockClaim | null): Promise<NativePushSendResult> => {
96
+ // Resolve the sender BEFORE the adapter is resolved or touched: a provider throw must
97
+ // reject this send with nothing injected, not leave a half-delivered conversation.
98
+ const sender = senderProvider?.();
99
+ const content = sender ? formatMetaMailboxBody(sender, plan.message, plan.wantsReply) : plan.message;
83
100
  const adapter = resolveAdapter(plan.backend);
84
- return deliverViaNativePush(adapter, plan.route, plan.nativeSessionId, plan.message);
101
+ return deliverViaNativePush(adapter, plan.route, plan.nativeSessionId, content);
85
102
  };
86
103
  }
@@ -137,8 +137,9 @@ export interface ProductionEntwurfV2Seams {
137
137
  export interface ProductionEntwurfV2Opts {
138
138
  /** Built at the wiring site from `buildLocalSenderEnvelope(ctx)`, decorated with its
139
139
  * HONEST pi-session replyability (SE-1 2e-a: `replyable` reflects whether the canonical
140
- * control socket actually exists, not a hardcoded true). ONE provider feeds the
141
- * control-socket RPC sender AND the meta-mailbox body sender (they share the envelope). */
140
+ * control socket actually exists, not a hardcoded true). ONE provider feeds ALL THREE
141
+ * rails — the control-socket RPC sender, the meta-mailbox body sender, and the
142
+ * native-push injected body sender — so no rail can present a different who-sent-it. */
142
143
  senderProvider: () => SenderEnvelope | undefined;
143
144
  lockDir?: string;
144
145
  sessionsDir?: string;
@@ -339,7 +340,13 @@ export function makeProductionEntwurfV2Deps(opts: ProductionEntwurfV2Opts): Entw
339
340
  sendMailbox: (plan, _lock) => sendViaMailbox(plan as MetaMailboxPlan, _lock as LockClaim),
340
341
  // native-push (봉인 4): the SAME injected adapter resolver drives the executor send,
341
342
  // so the decider's probe and the delivery use one adapter. Lock-free (lock ignored).
342
- sendNativePush: makeNativePushSend({ resolveAdapter: io.resolveNativePushAdapter }),
343
+ // It also receives the SAME `opts.senderProvider` the mailbox hand got — one envelope
344
+ // source for all three rails, so a native-push citizen can name its sender exactly as
345
+ // a mailbox citizen does (#95: an envelope-less direct injection is uncorrelatable).
346
+ sendNativePush: makeNativePushSend({
347
+ resolveAdapter: io.resolveNativePushAdapter,
348
+ senderProvider: opts.senderProvider,
349
+ }),
343
350
  };
344
351
 
345
352
  return {
@@ -100,11 +100,14 @@ export function actionableRejectHint(reason: string): string | undefined {
100
100
  "that garden id by a session that died without cleaning up."
101
101
  );
102
102
  case "native-push-target-dead":
103
- // The adapter probe found no live host process for the conversation.
104
- return "native-push conversation is not live (no host process found). Re-open the conversation, then retry there is nothing to inject into.";
103
+ // The adapter probe found no live native host serving this conversation/thread. Stays
104
+ // backend-neutral: agy speaks conversations over an LS port, Codex threads over an
105
+ // app-server socket, and this hint is read by callers of both.
106
+ return "the native-push conversation/thread is not live — no native host (harness process or app-server) answered the probe for it. Re-open that conversation/thread in its own harness, then retry; there is nothing to inject into.";
105
107
  case "native-push-probe-indeterminate":
106
- // Host up, but no LS port served the conversation — inconclusive, not a hard dead.
107
- return "native-push host is up but no port served this conversation (probe inconclusive). Retry once the conversation is loaded, or verify the conversation id.";
108
+ // Native host up, but nothing served this conversation/thread — inconclusive, not a
109
+ // hard dead. Backend-neutral for the same reason as the dead cell above.
110
+ return "the native host (harness process or app-server) is up, but nothing served this conversation/thread, so the probe is INCONCLUSIVE — not a measured death. Retry once it is loaded, or verify the conversation/thread id.";
108
111
  case "record-less-socket":
109
112
  // #50 C4: name the true cause AND the fix — a bare socket is a diagnostic
110
113
  // state, not an addressable citizen (the record is the address).
@@ -1,26 +1,33 @@
1
1
  /**
2
2
  * meta-mailbox-body — the SINGLE source for rendering an entwurf message as a
3
- * meta-bridge mailbox body. Both transports that can deliver to a garden citizen
4
- * with no live control socket use this:
3
+ * meta-bridge mailbox body. Every transport that can deliver to a garden citizen
4
+ * with no live control socket uses this:
5
5
  * - the MCP bridge entwurf_v2 (mcp/entwurf-bridge) — external/Claude-host sends
6
6
  * - the pi-native entwurf_v2 (pi-extensions/entwurf-control.ts) — pi-session sends
7
+ * - the native-push rail (pi-extensions/lib/entwurf-v2-native-push.ts) — direct
8
+ * injection into an Antigravity conversation or a loaded Codex thread. Its
9
+ * THIRD consumer, added after the #95 A LIVE run measured what an envelope-less
10
+ * injection costs: a nonce-only callback arrived in a Codex thread as bare text
11
+ * and the receiving citizen could not name who had called it.
7
12
  *
8
13
  * The control-socket path carries the sender envelope inside its RPC framing; the
9
- * mailbox path is just a file, so the envelope must be SERIALIZED INTO the body
10
- * else a receiver reading entwurf_inbox_read would not know who sent it, whether
11
- * the sender is replyable (and at which sessionId), or whether a reply was wanted.
12
- * The render mirrors the live "[entwurf received ⟵]" header so a transcript reads
13
- * the same whether the message arrived over a socket or a mailbox.
14
+ * mailbox path is just a file and direct injection is just a string, so for both the
15
+ * envelope must be SERIALIZED INTO the body
16
+ * else a receiver reading entwurf_inbox_read, or reading an injected turn in its own
17
+ * conversation would not know who sent it, whether the sender is replyable (and at
18
+ * which sessionId), or whether a reply was wanted. The render mirrors the live
19
+ * "[entwurf received ⟵]" header so a transcript reads the same whether the message
20
+ * arrived over a socket, a mailbox, or direct injection.
14
21
  *
15
22
  * No filesystem/network IO and no mutation — the only ambient read is
16
23
  * process.env.HOME for display abbreviation (so not strictly referentially pure,
17
- * but deterministic per environment). Extracted so the two senders cannot drift
18
- * in how a mailbox message presents who-sent-it — the field that round-trips
19
- * garden-id replies.
24
+ * but deterministic per environment). Extracted so the three consumers cannot
25
+ * drift in how a delivered message presents who-sent-it — the field that
26
+ * round-trips garden-id replies.
20
27
  */
21
28
 
22
- /** The fields a mailbox body needs from a sender. Structurally compatible with
23
- * the SenderEnvelope of both entwurf_v2 surfaces. */
29
+ /** The fields a sender-envelope presentation needs from a sender. Structurally
30
+ * compatible with the SenderEnvelope of both entwurf_v2 surfaces. */
24
31
  export interface MailboxSenderEnvelope {
25
32
  sessionId: string;
26
33
  agentId: string;
@@ -53,7 +60,9 @@ function formatKstTimestamp(iso: string): string {
53
60
  }
54
61
 
55
62
  /**
56
- * Render the full mailbox body: header envelope + separator + message. A
63
+ * Render the full body: header envelope + separator + message. The mailbox writes this
64
+ * into its message file and the native-push rail injects it directly into a live
65
+ * conversation; both present the sender identically. A
57
66
  * replyable sender (pi-session, or a trusted meta-session) advertises its
58
67
  * sessionId as the reply address; a non-replyable sender says so WITHOUT
59
68
  * losing its origin — a record-backed meta-session that is currently inactive
@@ -34,15 +34,31 @@
34
34
  * Every candidate is collected and validated BEFORE one is chosen. A first-match loop would make
35
35
  * the answer depend on which pid or backend happened to be read first; here lookup order carries
36
36
  * no meaning, and two live identities are a refusal rather than a race.
37
+ *
38
+ * A SECOND RAIL LIVES BELOW THE MARKER RAIL, and it does not share this one's join key.
39
+ * Codex names its caller on EVERY `tools/call` (`_meta.threadId` plus an
40
+ * `x-codex-turn-metadata.{session_id,thread_id}` block), and its parent pid cannot separate
41
+ * citizens at all: in the delivery-capable launch mode every hook and every MCP child of N
42
+ * live threads resolves to the ONE app-server pid, so a pid marker would be one marker for N
43
+ * citizens — exactly what the store's `nativeSessionId` uniqueness forbids (measured
44
+ * 2026-09-08, `scripts/raw-codex-measure/README.md` S1b-C/S1b-D). So the codex resolver is
45
+ * REQUEST-scoped, not process-scoped: see {@link resolveCodexRequestSenderIdentity}. The two
46
+ * rails never merge — `codex` is deliberately absent from {@link META_SENDER_BACKENDS}, since
47
+ * a backend listed there is one whose hook writes a pid marker, and codex birth writes none.
37
48
  */
38
49
 
39
50
  import {
51
+ defaultMetaSessionsDir,
52
+ describe,
40
53
  isPlausibleOwnerPid,
54
+ listAllMetaIdentities,
41
55
  type MetaBackend,
42
56
  type MetaIdentity,
43
57
  type MetaSenderMarker,
58
+ makeStoreRecordReader,
44
59
  metaRecordExistsByGardenId,
45
60
  parentPid,
61
+ readActiveStoreEntries,
46
62
  readMetaIdentityByGardenId,
47
63
  readMetaSenderMarker,
48
64
  } from "./meta-session.ts";
@@ -211,3 +227,292 @@ export async function probeNativeSenderAlive(
211
227
  const probe = await resolveAdapter(identity.backend).probe(identity.nativeSessionId);
212
228
  return probe.status === "alive";
213
229
  }
230
+
231
+ // ─────────────────────────────────────────────────────────────────────────────
232
+ // REQUEST-SCOPED SENDER IDENTITY — codex
233
+ // ─────────────────────────────────────────────────────────────────────────────
234
+
235
+ /**
236
+ * The provenance label the MANAGED codex MCP entry carries (`ENTWURF_BRIDGE_NATIVE_HOST=codex`
237
+ * under `[mcp_servers.entwurf-bridge]` in the codex config the entwurf config writer owns).
238
+ *
239
+ * It is an OWNERSHIP/DRIFT atom, not authentication: any process able to write that config, or
240
+ * to set that env on a child, can spell it. What it buys is the thing a codex bridge child
241
+ * genuinely cannot observe otherwise — that THIS child was launched from an entwurf-managed
242
+ * entry, so the request-scoped rail below is admitted deliberately rather than by sniffing.
243
+ * The value travels to this resolver as an EXPLICIT ARGUMENT: nothing here reads the
244
+ * environment, and in particular nothing here reads `ENTWURF_BRIDGE_EXTERNAL_AGENT_ID`, which
245
+ * is the omp root-policy label with its own policy attached (`applyOmpBridgeChildRootPolicy`)
246
+ * and must never double as a codex admission.
247
+ */
248
+ export const CODEX_BRIDGE_PROVENANCE_LABEL = "codex";
249
+
250
+ /**
251
+ * `clientInfo.name` every codex MCP client sends, and it is a FIXED VENDOR LITERAL —
252
+ * `Implementation::new("codex-mcp-client", CARGO_PKG_VERSION).with_title("Codex")`
253
+ * (`codex-mcp/src/rmcp_client.rs:1035-1039`, read at 0.153.4). `initialize` carries no
254
+ * identity at all and is byte-identical between two children of two different threads, so this
255
+ * name is a HOST-KIND gate and never an identity: it says "the peer on this stdio is a codex
256
+ * client", which is precisely as much as startup can honestly say.
257
+ */
258
+ export const CODEX_MCP_CLIENT_NAME = "codex-mcp-client";
259
+
260
+ /** The `_meta` member carrying the vendor turn-metadata block (`core/src/mcp_tool_call.rs`
261
+ * `build_mcp_tool_call_request_meta`, :1238-1263). A dash-cased key, hence the string form. */
262
+ const CODEX_TURN_METADATA_KEY = "x-codex-turn-metadata";
263
+
264
+ /**
265
+ * The codex caller's identity metadata is PRESENT but does not hold together: a `threadId` that
266
+ * is not a nonempty string, a missing/foreign turn-metadata block, or three ids that disagree.
267
+ *
268
+ * WHY THIS IS LOUD AND NOT `null`. `null` on this rail means "no identity claim reached me" —
269
+ * the bridge then refuses the send as anonymous, and the prescription is "open the session
270
+ * through the installed codex birth hook". A HALF claim is a different fact with a different
271
+ * cause (a vendor `_meta` shape that moved, or something imitating the codex client), and both
272
+ * ids exist precisely so neither has to be trusted alone: `threadId` and
273
+ * `x-codex-turn-metadata.session_id` are built by two different vendor call sites, and the
274
+ * hook's `session_id` is byte-identical to both (measured 2026-09-08, S1b-D/D3). Selecting a
275
+ * record from one field while its corroborator is absent or disagrees would address a citizen on
276
+ * an unverified id — the SE-1 shape — so the disagreement is reported instead.
277
+ */
278
+ export class EntwurfCodexIdentityMetadataError extends Error {
279
+ constructor(reason: string) {
280
+ super(
281
+ "entwurf-bridge refused: this codex tool call carries identity metadata that does not hold " +
282
+ `together — ${reason} A codex caller names itself on every call with THREE ids that must be one ` +
283
+ `string: \`_meta.threadId\`, \`_meta.${CODEX_TURN_METADATA_KEY}.session_id\` and \`.thread_id\`. ` +
284
+ "Selecting a garden citizen from a partial or self-contradicting claim would send under an " +
285
+ "identity nothing vouched for. Report it; do not work around it — if the vendor `_meta` shape " +
286
+ "moved, the measurement in scripts/raw-codex-measure/README.md (S1b-D) must be re-taken.",
287
+ );
288
+ this.name = "EntwurfCodexIdentityMetadataError";
289
+ }
290
+ }
291
+
292
+ /**
293
+ * The codex `threadId` selected exactly one V3 record — and that record is NOT a codex citizen.
294
+ *
295
+ * This is corruption of the native→garden mapping, never a miss: the store says some other
296
+ * backend's session carries this exact native id. Returning `null` would report "no record for
297
+ * this thread" and prescribe re-opening the session, which would mint a SECOND record for the
298
+ * same `nativeSessionId` and turn a readable defect into the duplicate the certification
299
+ * refuses. Sending under the foreign citizen is worse still — it would attribute a codex
300
+ * caller's message to a claude-code/agy/pi session.
301
+ */
302
+ export class EntwurfCodexIdentityBackendError extends Error {
303
+ readonly gardenId: string;
304
+ constructor(identity: MetaIdentity) {
305
+ super(
306
+ `entwurf-bridge refused: codex thread ${identity.nativeSessionId} selected meta-record ` +
307
+ `${identity.gardenId}, but that citizen's backend is "${identity.backend}", not "codex". One ` +
308
+ "native id is bound to one backend for the life of the record, so this store cannot say who the " +
309
+ "caller is — and neither re-opening the codex session nor sending under the foreign citizen is a " +
310
+ "fix. The record must be corrected (a fresh generation) before this thread can send.",
311
+ );
312
+ this.name = "EntwurfCodexIdentityBackendError";
313
+ this.gardenId = identity.gardenId;
314
+ }
315
+ }
316
+
317
+ /** A JSON OBJECT, as a narrowing guard — `typeof value === "object"` alone admits `null` and
318
+ * arrays, and every codex identity field is read through a member access that both would
319
+ * survive silently (`[]._meta` is `undefined`, not a type error). */
320
+ function isJsonObject(value: unknown): value is Record<string, unknown> {
321
+ return typeof value === "object" && value !== null && !Array.isArray(value);
322
+ }
323
+
324
+ /** What the resolver is handed. Every field is UNKNOWN on purpose: three of them come off the
325
+ * wire (an MCP peer may send any JSON) and the fourth is a config-written label, so none of
326
+ * them may be typed as trusted at the boundary. */
327
+ export interface ResolveCodexRequestSenderOptions {
328
+ /** The managed-entry provenance, supplied EXPLICITLY by the bridge (never read here). */
329
+ provenance?: unknown;
330
+ /** The peer's `initialize` `clientInfo` — a host-kind gate, never an identity. */
331
+ clientInfo?: unknown;
332
+ /** THIS request's `params._meta`. Per-call, because identity on codex is per-call. */
333
+ requestMeta?: unknown;
334
+ /** Record store override (gates isolate it; production reads the SSOT default). */
335
+ sessionsDir?: string;
336
+ }
337
+
338
+ /**
339
+ * The one codex caller a request names, as the RECORD describes it.
340
+ *
341
+ * `identity` is the whole answer: gardenId, cwd, model, transcriptPath and backend all come from
342
+ * the record, never from the wire. `_meta` carries a `workspaces` map and a `model` field, and
343
+ * both are IGNORED here — a caller that can name its own cwd/model can relabel a citizen by
344
+ * asking, which is a write disguised as a read. `threadId` is retained only because it is the
345
+ * SELECTOR that was proven equal to `identity.nativeSessionId`; it adds no new authority.
346
+ */
347
+ export interface CodexRequestSender {
348
+ identity: MetaIdentity;
349
+ /** The wire id that selected the record; `=== identity.nativeSessionId` by construction. */
350
+ threadId: string;
351
+ /** The provenance that admitted this rail — always the codex label past the gate. */
352
+ provenance: typeof CODEX_BRIDGE_PROVENANCE_LABEL;
353
+ }
354
+
355
+ /**
356
+ * Read the caller's thread id out of ONE request, or refuse.
357
+ *
358
+ * `null` — this is not an admitted codex identity claim at all: no managed provenance, a peer
359
+ * that is not the codex client, no `_meta` object, or an `_meta` with no `threadId` member
360
+ * (`tools/list`, `initialize`, a non-turn call). All four are ordinary and carry no defect.
361
+ *
362
+ * THROWS {@link EntwurfCodexIdentityMetadataError} — a claim exists and is broken. The line
363
+ * between the two is the PRESENCE of `threadId`: absent is a call that never claimed identity,
364
+ * present-but-unusable is a claim that failed, and collapsing them would report "no identity"
365
+ * for a caller that named itself.
366
+ *
367
+ * Pure: no fs, no env, no clock. The store lookup is the next function's job on purpose — this
368
+ * half is the wire contract and can be pinned without a store at all.
369
+ */
370
+ export function readCodexRequestThreadId(
371
+ opts: Pick<ResolveCodexRequestSenderOptions, "provenance" | "clientInfo" | "requestMeta">,
372
+ ): string | null {
373
+ if (opts.provenance !== CODEX_BRIDGE_PROVENANCE_LABEL) return null;
374
+ if (!isJsonObject(opts.clientInfo) || opts.clientInfo.name !== CODEX_MCP_CLIENT_NAME) return null;
375
+ const meta = opts.requestMeta;
376
+ if (!isJsonObject(meta)) return null;
377
+ if (!("threadId" in meta)) return null;
378
+
379
+ const threadId = meta.threadId;
380
+ if (typeof threadId !== "string" || threadId.length === 0) {
381
+ throw new EntwurfCodexIdentityMetadataError(
382
+ `\`_meta.threadId\` is present but is not a nonempty string (got ${describe(threadId)}).`,
383
+ );
384
+ }
385
+ const turn = meta[CODEX_TURN_METADATA_KEY];
386
+ if (!isJsonObject(turn)) {
387
+ throw new EntwurfCodexIdentityMetadataError(
388
+ `\`_meta.threadId\` names ${threadId} but \`_meta.${CODEX_TURN_METADATA_KEY}\` is ${describe(turn)}, not an ` +
389
+ "object, so the second, independently-built id that corroborates it is missing.",
390
+ );
391
+ }
392
+ const sessionId = turn.session_id;
393
+ const turnThreadId = turn.thread_id;
394
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
395
+ throw new EntwurfCodexIdentityMetadataError(
396
+ `\`_meta.${CODEX_TURN_METADATA_KEY}.session_id\` is not a nonempty string (got ${describe(sessionId)}) — ` +
397
+ "that field is the one the birth hook also sees, so without it nothing joins the wire to a record.",
398
+ );
399
+ }
400
+ if (typeof turnThreadId !== "string" || turnThreadId.length === 0) {
401
+ throw new EntwurfCodexIdentityMetadataError(
402
+ `\`_meta.${CODEX_TURN_METADATA_KEY}.thread_id\` is not a nonempty string (got ${describe(turnThreadId)}).`,
403
+ );
404
+ }
405
+ if (sessionId !== threadId || turnThreadId !== threadId) {
406
+ throw new EntwurfCodexIdentityMetadataError(
407
+ `the three ids disagree (threadId=${threadId}, session_id=${sessionId}, thread_id=${turnThreadId}); ` +
408
+ "on a healthy codex turn they are one byte-identical string.",
409
+ );
410
+ }
411
+ return threadId;
412
+ }
413
+
414
+ /**
415
+ * Resolve the ONE codex citizen a request names, or refuse.
416
+ *
417
+ * `null` — no admitted claim ({@link readCodexRequestThreadId}), or no record holds that
418
+ * `nativeSessionId`. The second case is the ordinary pre-birth window: codex birth is
419
+ * first-turn, not window-open, so a thread whose hook has not minted a record yet simply has no
420
+ * citizen, and the bridge's default anonymous refusal already names the fix.
421
+ *
422
+ * THROWS — every knowable defect, unfolded: a broken claim
423
+ * ({@link EntwurfCodexIdentityMetadataError}), a foreign-backend record
424
+ * ({@link EntwurfCodexIdentityBackendError}), or a store that cannot be certified
425
+ * (`MetaRecordError` from the strict listing — an unreadable/previous-generation record
426
+ * anywhere in the store, a duplicated `nativeSessionId`, or a store this process cannot read).
427
+ *
428
+ * THE LOOKUP IS THE STRICT STORE-WIDE LISTING, NOT A NARROW SCAN. `nativeSessionId` → garden id
429
+ * is the store's own authority (there is no index, by design), and the same reason
430
+ * `upsertMetaSession` certifies the WHOLE store before writing applies to a read that turns an
431
+ * id into an ADDRESS: a narrow "find my thread" pass would answer happily beside a duplicate,
432
+ * drifted or symlinked neighbour that the doctor refuses, so the runtime would hold the weaker
433
+ * contract exactly where a message gets attributed. `mode: "strict"` is what makes an
434
+ * unreadable record a refusal instead of an invisible one — a duplicate of THIS thread's id
435
+ * would otherwise be dropped from `identities` and read as "no record".
436
+ */
437
+ export function resolveCodexRequestSenderIdentity(
438
+ opts: ResolveCodexRequestSenderOptions = {},
439
+ ): CodexRequestSender | null {
440
+ const threadId = readCodexRequestThreadId(opts);
441
+ if (threadId === null) return null;
442
+
443
+ const dir = opts.sessionsDir ?? defaultMetaSessionsDir();
444
+ const { identities } = listAllMetaIdentities(readActiveStoreEntries(dir), makeStoreRecordReader(dir), {
445
+ mode: "strict",
446
+ });
447
+ const identity = identities.find((record) => record.nativeSessionId === threadId);
448
+ if (!identity) return null;
449
+ if (identity.backend !== "codex") throw new EntwurfCodexIdentityBackendError(identity);
450
+ return { identity, threadId, provenance: CODEX_BRIDGE_PROVENANCE_LABEL };
451
+ }
452
+
453
+ /**
454
+ * The three rails an entwurf-bridge child can learn WHO is calling from. Named as a type so a
455
+ * reconciliation can report which rails spoke without any of them being privileged by position.
456
+ */
457
+ export type SenderIdentityRail = "pi-session" | "meta-sender-marker" | "codex-request";
458
+
459
+ /** One rail's answer: the address it names (a pi session id, or a garden id). */
460
+ export interface SenderIdentityClaim {
461
+ rail: SenderIdentityRail;
462
+ id: string;
463
+ }
464
+
465
+ /** One address, plus every rail that named it. Rails are sorted and de-duplicated, so this
466
+ * answer never depends on the order the caller collected its claims in. */
467
+ export interface ReconciledSenderIdentity {
468
+ id: string;
469
+ rails: SenderIdentityRail[];
470
+ }
471
+
472
+ /**
473
+ * Two rails claim this MCP process for DIFFERENT addresses. Sibling of
474
+ * {@link EntwurfSenderIdentityAmbiguityError} and deliberately not the same error: that one is
475
+ * about two pid MARKERS on one owner pid, while this is about rails that do not even share a
476
+ * join key — a planted `PI_SESSION_ID` in a native host's environment, a pid marker inherited
477
+ * from a host whose child we are not, a codex `_meta` naming a thread while a marker names
478
+ * someone else. Which is right is unknowable here, and both are visible, so neither is used.
479
+ */
480
+ export class EntwurfSenderIdentityConflictError extends Error {
481
+ readonly claims: SenderIdentityClaim[];
482
+ constructor(claims: readonly SenderIdentityClaim[]) {
483
+ super(
484
+ "entwurf-bridge refused: conflicting sender identity. This MCP process holds authoritative " +
485
+ `identity claims from more than one rail, naming DIFFERENT addresses (${claims
486
+ .map((claim) => `${claim.rail}=${claim.id}`)
487
+ .join(", ")}), so which one is calling cannot be determined. A send under the wrong identity ` +
488
+ "is worse than no send. Report it; do not work around it.",
489
+ );
490
+ this.name = "EntwurfSenderIdentityConflictError";
491
+ this.claims = [...claims];
492
+ }
493
+ }
494
+
495
+ /**
496
+ * Fold every rail's answer into ONE address, or refuse.
497
+ *
498
+ * 0 claims → `null` (anonymous; the bridge's default refusal owns that outcome).
499
+ * 1+ claims that AGREE on the id → that address, carrying every rail that named it. Agreement is
500
+ * the normal shape of an overlap, not a conflict: a codex citizen's request-scoped claim and a
501
+ * pid marker for the same garden id are two views of one identity.
502
+ * claims that DISAGREE → throw {@link EntwurfSenderIdentityConflictError}.
503
+ *
504
+ * Every claim is collected and compared BEFORE one is chosen — the same rule the marker rail
505
+ * holds one layer up. A rail-priority order would answer even when the truth is unknown, which
506
+ * is the failure this exists to prevent, so callers must pass ALL rails they resolved rather
507
+ * than short-circuiting on the first one that answered.
508
+ */
509
+ export function reconcileSenderIdentityClaims(claims: readonly SenderIdentityClaim[]): ReconciledSenderIdentity | null {
510
+ if (claims.length === 0) return null;
511
+ const ids = new Set(claims.map((claim) => claim.id));
512
+ if (ids.size > 1) throw new EntwurfSenderIdentityConflictError(claims);
513
+ const [id] = ids;
514
+ return {
515
+ id,
516
+ rails: [...new Set(claims.map((claim) => claim.rail))].sort(),
517
+ };
518
+ }