@zieglar/pi-chat-exchange 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -2
  3. package/dist/bin/ce-native.js +119 -0
  4. package/dist/bin/mcp-stdio.js +196 -0
  5. package/dist/control/debug-log.js +67 -0
  6. package/dist/control/mcp/debug-transport.js +48 -0
  7. package/dist/control/mcp/messaging-tools.js +278 -0
  8. package/dist/control/mcp/ping.js +43 -0
  9. package/dist/control/mcp/server.js +153 -0
  10. package/dist/core/authorization.js +32 -0
  11. package/dist/core/reference.js +32 -0
  12. package/dist/core/rules.js +468 -0
  13. package/dist/endpoints/pi/contract.js +2 -0
  14. package/dist/endpoints/pi/session-host.js +39 -0
  15. package/dist/host/bound-endpoint.js +176 -0
  16. package/dist/host/endpoint-host.js +839 -0
  17. package/dist/host/mcp-binding-config.js +209 -0
  18. package/dist/host/ownership-recovery.js +257 -0
  19. package/dist/index.js +11 -0
  20. package/dist/protocol/capabilities.js +46 -0
  21. package/dist/protocol/endpoint-capabilities.js +15 -0
  22. package/dist/protocol/entities.js +185 -0
  23. package/dist/protocol/formats.js +13 -0
  24. package/dist/protocol/idempotency.js +93 -0
  25. package/dist/protocol/identity.js +130 -0
  26. package/dist/protocol/index.js +8 -0
  27. package/dist/protocol/lifecycle.js +125 -0
  28. package/dist/protocol/outcomes.js +55 -0
  29. package/dist/runtime/desktop-manifest.js +65 -0
  30. package/dist/runtime/diagnostics.js +34 -0
  31. package/dist/runtime/executables.js +217 -0
  32. package/dist/runtime/native-readiness.js +131 -0
  33. package/dist/storage/capability.js +221 -0
  34. package/dist/storage/connection.js +95 -0
  35. package/dist/storage/creation-request.js +176 -0
  36. package/dist/storage/creation.js +553 -0
  37. package/dist/storage/current-schema.js +397 -0
  38. package/dist/storage/delivery-ack.js +177 -0
  39. package/dist/storage/errors.js +9 -0
  40. package/dist/storage/filesystem.js +171 -0
  41. package/dist/storage/inbox-discovery.js +135 -0
  42. package/dist/storage/messaging.js +156 -0
  43. package/dist/storage/migration.js +258 -0
  44. package/dist/storage/native-artifact.js +234 -0
  45. package/dist/storage/native-compat.js +65 -0
  46. package/dist/storage/ownership.js +789 -0
  47. package/dist/storage/participant-identity.js +127 -0
  48. package/dist/storage/participant.js +700 -0
  49. package/dist/storage/recovery.js +99 -0
  50. package/dist/storage/runtime.js +256 -0
  51. package/dist/storage/schema.js +556 -0
  52. package/dist/storage/session-state.js +75 -0
  53. package/dist/storage/sqlite-driver-node.js +66 -0
  54. package/dist/storage/sqlite-driver-rust.js +121 -0
  55. package/dist/storage/sqlite-driver-selection.js +86 -0
  56. package/dist/storage/sqlite-driver.js +4 -0
  57. package/dist/storage/store.js +450 -0
  58. package/dist/storage/transaction.js +196 -0
  59. package/dist/storage/trust-root.js +164 -0
  60. package/dist/tunnel/background-manager.js +1727 -0
  61. package/dist/tunnel/codes.js +79 -0
  62. package/dist/tunnel/health.js +75 -0
  63. package/dist/tunnel/keychain.js +526 -0
  64. package/dist/tunnel/managed-binding.js +454 -0
  65. package/dist/tunnel/manager-panel.js +249 -0
  66. package/dist/tunnel/manager-ui.js +341 -0
  67. package/dist/tunnel/manager.js +372 -0
  68. package/dist/tunnel/messaging-activation-ui.js +85 -0
  69. package/dist/tunnel/messaging-config.js +246 -0
  70. package/dist/tunnel/multi-session-admission.js +31 -0
  71. package/dist/tunnel/multi-session-policy.js +314 -0
  72. package/dist/tunnel/offline-client.js +104 -0
  73. package/dist/tunnel/profile.js +319 -0
  74. package/dist/tunnel/redact.js +9 -0
  75. package/dist/tunnel/secure-input.js +318 -0
  76. package/dist/tunnel/session-process-mutex.js +338 -0
  77. package/dist/tunnel/setup-ui.js +443 -0
  78. package/dist/tunnel/setup.js +734 -0
  79. package/dist/tunnel/state.js +127 -0
  80. package/native/tunnel-keychain.swift +432 -0
  81. package/package.json +65 -4
  82. package/pi-extension/allowlist.example.json +11 -0
  83. package/pi-extension/index.ts +2346 -0
  84. package/pi-extension/multi-session-commands.ts +93 -0
  85. package/pi-extension/multi-session-runtime.ts +75 -0
  86. package/pi-extension/tui-keys.ts +40 -0
  87. package/scripts/reconcile-session-process-mutex.mjs +262 -0
  88. package/scripts/recover-stale-ownership.mjs +91 -0
@@ -0,0 +1,1727 @@
1
+ /**
2
+ * HANDOFF-CE-LOCAL-BACKGROUND-01 v3 — real background tunnel lifecycle.
3
+ *
4
+ * v10 amendments (Lane S v9 S9-1, Lane C v9 C9-1…3):
5
+ * - The signal-phase "return unknown" contract is now pinned by a pending-run
6
+ * regression that actually reaches the signal branch (S9-1/C9-1).
7
+ * - Identity resolution's ledger-preserving merge and stopped-not-resurrected
8
+ * behaviour each have a deterministic concurrency regression (C9-2).
9
+ * - The write-ahead window (a record-backed run whose termination intent
10
+ * persisted but whose signal was never delivered) is disclosed: at-most-once
11
+ * guarantees zero EXTRA signals, never non-zero delivery.
12
+ *
13
+ * v9 amendments (Lane S v8 S8-1, S8-2):
14
+ * - Identity resolution in refresh merges the identity upgrade onto the record
15
+ * re-read INSIDE the lock, preserving a concurrent stop's termRequestedAt
16
+ * and state; a run another session already stopped is never resurrected.
17
+ *
18
+ * v8 amendments (Lane C v7 F1–F4):
19
+ * - The in-memory once-set is burned ONLY immediately before the signal, under
20
+ * the held lock — a lost lock can no longer permanently immunize a run.
21
+ * Note the write-ahead window: if a record-backed run's termRequestedAt
22
+ * persisted but the signal was never delivered (lock lost after the ledger
23
+ * write), that run is NOT re-signalled — at-most-once forbids the retry and
24
+ * permits zero deliveries here; a later stop only reports unconfirmed.
25
+ * - A lost lock during the signal phase returns "unknown" (ownership
26
+ * retained), preserving the three-state termination contract instead of
27
+ * throwing MANAGER_BUSY out of terminateOwned.
28
+ *
29
+ * v7 amendments (Lane S v6 S6-1…5):
30
+ * - The signal path is symmetric with persist: a SIGTERM (including the
31
+ * pending-run in-memory once-set branch) is only ever issued under a held
32
+ * lock token — the discipline is machine-enforced on both writes.
33
+ *
34
+ * v6 amendments (Lane S v5 S5-1…8, Lane C v5 C-v5-1…5):
35
+ * - judgeLock: a leaked holder is reclaimed when EITHER the pid/startedKey
36
+ * judgement is stale OR the age threshold passed (leaked is an additional
37
+ * reclaim reason, never a replacement).
38
+ * - persist() refuses a CORRUPT on-disk record too, and requires a held lock
39
+ * token outright (the lock discipline is machine-enforced, not advisory).
40
+ * - stop() also terminates a pending unpersisted daemon that is NOT the disk
41
+ * record's run (in-memory once-set protected); a successful stop that left
42
+ * a live pending run says so in its note.
43
+ * - A reclaimProbe seam (test-only) sits between the reclaim judgement and
44
+ * the rename, letting tests inject the exact interleavings F2 targets.
45
+ *
46
+ * v5 amendments (Lane S v4 F1–F7, Lane C v4 C-v4-1…7):
47
+ * - persist() itself enforces the lock (assertLockIntact at entry) and refuses
48
+ * to overwrite a DIFFERENT run's non-stopped disk record — no code path can
49
+ * roll back another session's live ownership or termination ledger.
50
+ * - Pending priority is narrowed to DISK-STOPPED records only (a live foreign
51
+ * run's record always wins the in-memory view).
52
+ * - Lock reclaim compares inode+mtime of the judged directory against the
53
+ * grave after rename — a successor created during the judgement window is
54
+ * detected and rolled back even while it is still holderless.
55
+ * - A stop/refresh that proves exit strips identityPending before the final
56
+ * persist, so an identity-pending run terminates cleanly.
57
+ * - refresh's identity re-acquisition persists under the lock; holder-write
58
+ * self-clean only removes a lock that is still ours; leaked holders keep
59
+ * their startedKey and remain age-reclaimable; grave sweeping is prefixed
60
+ * to this lock and aged.
61
+ *
62
+ * v4 amendments (Lane S v3 S3-1…7, Lane C v3 C-v3-1…7):
63
+ * - Lock reclaim verifies AFTER the rename that the grave holds the SAME lock
64
+ * that was judged stale (token match, or still holderless for the aged
65
+ * branch); a mismatch rolls the rename back and refuses BUSY, so a live
66
+ * successor's lock is never deleted. Critical sections additionally assert
67
+ * the lock is still ours before persist/signal.
68
+ * - Pending ownership outranks a stale disk record of a DIFFERENT run
69
+ * (reloadRecord), so a stopped-record file can never hide a live pending
70
+ * daemon from stop/refresh.
71
+ * - identityPending re-acquisition requires the command line to be EXACTLY
72
+ * `<client> run --profile-file <this profile>` — substring matching refused.
73
+ * - Leaked-lock tokens are process-wide (module scope); a failed release
74
+ * rewrites the holder best-effort to preserve the token evidence.
75
+ * - Quoted profile scalars are printable-ASCII only (no C0/C1/line
76
+ * separators), keeping gate values byte-identical to YAML decoding.
77
+ * - refresh persists absence using the record re-read INSIDE the lock.
78
+ *
79
+ * v3 amendments (Lane S v2 S2-R1…R8, Lane C v2 C-v2-1…6):
80
+ * - Lock is a mkdir DIRECTORY lock: creation is atomic cross-process; stale
81
+ * reclaim first renames the old dir to a unique grave (reclaimers are
82
+ * mutually exclusive) and then VERIFIES the grave is the judged-stale lock
83
+ * before deleting (v4). Holder-write failure self-cleans; an unparseable
84
+ * holder is reclaimable only after LOCK_STALE_MS (crash-safe by age).
85
+ * - The termination ledger is authoritative: a record-backed run is signalled
86
+ * only AFTER termRequestedAt persists; an unpersisted (pending) run is
87
+ * guarded by an in-memory once-set so a crash loses the record AND the
88
+ * ability to re-signal together.
89
+ * - Unpersisted ownership (persist failed after spawn, or identity capture
90
+ * incomplete) is a first-class pendingRecord: disk ENOENT never discards it,
91
+ * and stop/refresh keep managing it until exit is proven.
92
+ * - refresh persists ONLY under the lock, re-reading and re-checking runId
93
+ * inside it, so a stale observation cannot overwrite a newer run's record.
94
+ * - start captures the lifecycle generation AT CALL TIME and re-checks it
95
+ * before executing, after the lock, and before spawn; stop awaits the
96
+ * settlement of any start it invalidated before taking the lock.
97
+ * - loadRecord maps only ENOENT to "no record"; every other error is corrupt
98
+ * (fail closed).
99
+ * - The profile reader is EXHAUSTIVE over the canonical grammar documented in
100
+ * docs/tunnel.example.yaml (single mcp command, canonical indentation):
101
+ * every non-blank, non-comment line must match a known key at its exact
102
+ * indent; unknown keys, nesting, quoting styles, or sections refuse.
103
+ * - Adopted runs (not spawned by this session) are supervised with an
104
+ * unbounded startup window — an observation lapse is DEGRADED, never a
105
+ * permanent terminal Error; the baseline is captured BEFORE the async probe
106
+ * so a completed health measurement can never predate it.
107
+ *
108
+ * Review amendments applied (Lane S S1–S10, Lane C C1–C8 over v1):
109
+ * - S1 Real start is GATED: it requires the exact opt-in
110
+ * `CE_TUNNEL_BACKGROUND_ALLOW === "1"` (defense in depth at the manager,
111
+ * not just the command). status/stop remain gate-free: they cannot create
112
+ * cost, and stop only ever reduces it.
113
+ * - S2 Profile parsing is a STRICT SUBSET reader, not regex-over-YAML: exact
114
+ * section tracking, double-quoted values without backslashes, unique keys,
115
+ * no block scalars, no tabs. Anything outside the canonical subset that
116
+ * `profile.ts buildTunnelProfile` emits refuses CE_TUNNEL_PROFILE_INVALID,
117
+ * so the value we gate on is byte-identical to what a YAML parser decodes.
118
+ * - S3/C5 Process inspection is THREE-STATE: present / proven-absent /
119
+ * unknown. `ps` is invoked as /bin/ps with a fixed minimal environment and
120
+ * LC_ALL=C (S9); only exit 0 + parseable row is present, only exit 1 + empty
121
+ * stdout is absent, everything else is unknown. Unknown RETAINS ownership,
122
+ * blocks start, and makes stop unconfirmed — never a false exit proof.
123
+ * - S4/C2 Cross-process mutual exclusion: an O_EXCL lock file whose holder is
124
+ * itself identity-verified (pid + start key). Every start/stop re-reads the
125
+ * record INSIDE the lock; refresh re-reads the record from disk each call.
126
+ * A contended or unverifiable lock refuses CE_TUNNEL_MANAGER_BUSY.
127
+ * - S5/C8 ONE termination path: identity is re-verified immediately before
128
+ * any signal, and the persisted termRequestedAt is honored by every path
129
+ * (including startup-timeout cleanup), so a run is signalled at most once
130
+ * across all sessions.
131
+ * - S6/C4 Start is a transaction: directory writability is proven BEFORE
132
+ * spawn; a post-spawn failure performs identity-verified single-signal
133
+ * cleanup with a bounded wait, and an unpersistable run stays owned
134
+ * in-memory (runId visible, stop() can retry) instead of being orphaned.
135
+ * - S7 File hygiene: state directory must be an owned, non-symlink 0700 dir;
136
+ * record temp files are random-named O_EXCL creations; the log is opened
137
+ * O_NOFOLLOW and tightened to 0600; existing symlinks refuse.
138
+ * - S8 Record loading distinguishes none / ok / corrupt: only ENOENT means
139
+ * "no record"; anything else is CE_TUNNEL_STATE_CORRUPT and blocks mutation.
140
+ * Size is checked via lstat BEFORE reading; every used field is validated.
141
+ * - S10 A timed-out or killed health probe DISCARDS its stdout and becomes
142
+ * "unverifiable"; only cleanly exited probes feed the frozen parser.
143
+ * - C1 A record adopted from a previous session is re-baselined: its state
144
+ * machine run starts at this manager's first observation, so the original
145
+ * startup deadline cannot fence a long-lived daemon. The recorded startedAt
146
+ * is still the one displayed.
147
+ * - C3 start/stop are serialized per manager through one lifecycle queue and
148
+ * fenced after every await: a stop during a pending start aborts the start
149
+ * into the standard cleanup path, and a superseded start never reports
150
+ * success.
151
+ * - C6 Start success requires the shared state machine to ACCEPT Connected;
152
+ * a healthy probe completing after the startup deadline takes the timeout
153
+ * path instead of being announced.
154
+ *
155
+ * Persistent invariants (unchanged from v1): no credential is ever read,
156
+ * printed, copied, or forwarded — the client reads the operator's own key via
157
+ * the profile's file: reference; the daemon environment is the profile.ts
158
+ * allowlist; no autostart/reconnect/respawn; the MCP child is never signalled
159
+ * by this manager; transport state is never delivery/ACK/completion evidence.
160
+ */
161
+ import { execFile as nodeExecFile, spawn as nodeSpawn } from "node:child_process";
162
+ import { randomUUID, createHash } from "node:crypto";
163
+ import { constants as fsConstants } from "node:fs";
164
+ import { chmodSync, closeSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
165
+ import { homedir } from "node:os";
166
+ import { dirname, isAbsolute, join, normalize } from "node:path";
167
+ import { TunnelRefusal } from "./codes.js";
168
+ import { resolveTunnelClient } from "../runtime/executables.js";
169
+ import { createHealthCompletionRecorder } from "./health.js";
170
+ import { checkKeyFileRequirements, childEnvironment } from "./profile.js";
171
+ import { DEFAULT_TUNNEL_TIMING, initialTunnelState, nextTunnelState, } from "./state.js";
172
+ // Background-only budget for the external 0.0.16 client's defaults: initial
173
+ // long-poll 30s + deadline guardrail 5s + 10s startup/probe/scheduling margin.
174
+ // No authoritative client timing config is available here. Keep the shared
175
+ // offline timing and explicit caller overrides unchanged; retain required poll.
176
+ const DEFAULT_BACKGROUND_TUNNEL_TIMING = Object.freeze({
177
+ ...DEFAULT_TUNNEL_TIMING, startupTimeoutMs: 45_000,
178
+ });
179
+ /** Derived from the invoking account rather than a hardcoded operator home. */
180
+ const defaultProfilePath = () => join(homedir(), ".config", "pi-chat-exchange", "tunnel", "tunnel.yaml");
181
+ const PS_PATH = "/bin/ps";
182
+ const PROBE_TIMEOUT_MS = 10_000;
183
+ const IDENTITY_APPEAR_MS = 2_000;
184
+ const EXIT_POLL_MS = 200;
185
+ const MAX_RECORD_BYTES = 16_384;
186
+ const BACKGROUND_OPT_IN = "CE_TUNNEL_BACKGROUND_ALLOW";
187
+ const LOCK_STALE_MS = 60_000;
188
+ /** Tokens of locks THIS PROCESS failed to release (e.g. the state dir went
189
+ * unwritable mid-operation). Process-wide so a rebuilt manager in the same
190
+ * host can still reclaim them; never consulted for foreign holders. */
191
+ const leakedLockTokens = new Set();
192
+ const maskTunnelId = (id) => `${id.slice(0, 13)}…`;
193
+ // ---------------------------------------------------------------------------
194
+ // Strict-subset profile reader (S2). Accepts EXACTLY the canonical shape that
195
+ // profile.ts buildTunnelProfile emits: section-tracked, double-quoted values
196
+ // without backslashes, unique keys, no block scalars, no tabs. In this subset
197
+ // the line text and the YAML-decoded value are byte-identical, so the gate
198
+ // checks the same value the client will read. Anything else refuses.
199
+ // ---------------------------------------------------------------------------
200
+ export function parseTunnelProfile(text) {
201
+ // Exhaustive grammar over the canonical profile shape (R8). Every non-blank,
202
+ // non-comment line MUST match one production below; anything else refuses.
203
+ if (/[\t\u0000\r\u0085\u2028\u2029]/.test(text)) {
204
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
205
+ }
206
+ const SECTION_KEYS = {
207
+ control_plane: new Set(["base_url", "tunnel_id", "api_key", "organization_id"]),
208
+ health: new Set(["listen_addr", "url_file"]),
209
+ admin_ui: new Set(["open_browser"]),
210
+ harpoon: new Set(["capture_payloads"]),
211
+ log: new Set(["level", "format", "http_raw_unsafe"]),
212
+ mcp: new Set(["commands"]),
213
+ };
214
+ /** Gate-relevant values must be double-quoted, escape-free scalars so the
215
+ * line text and the YAML-decoded value are byte-identical. */
216
+ const quoted = (raw, tag) => {
217
+ // S3-5: printable ASCII only — no C0/C1 controls or Unicode line
218
+ // separators that a YAML reader could fold into a DIFFERENT scalar.
219
+ if (!/^"[\x20\x21\x23-\x5B\x5D-\x7E]*"$/.test(raw))
220
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", tag);
221
+ return raw.slice(1, -1);
222
+ };
223
+ const bare = (raw, tag, pattern) => {
224
+ if (!pattern.test(raw))
225
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", tag);
226
+ return raw;
227
+ };
228
+ let section;
229
+ let inCommands = false;
230
+ let itemOpen = false;
231
+ const seen = new Set();
232
+ const found = {};
233
+ for (const rawLine of text.split("\n")) {
234
+ if (rawLine.trim() === "" || rawLine.trimStart().startsWith("#"))
235
+ continue;
236
+ const indent = rawLine.length - rawLine.trimStart().length;
237
+ const line = rawLine.trim();
238
+ if (indent === 0) {
239
+ itemOpen = false;
240
+ inCommands = false;
241
+ if (line === "config_version: 1") {
242
+ section = undefined;
243
+ continue;
244
+ }
245
+ const m = /^(\w+):$/.exec(line);
246
+ if (m === null || !(m[1] in SECTION_KEYS))
247
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
248
+ section = m[1];
249
+ if (seen.has(section))
250
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", section);
251
+ seen.add(section);
252
+ continue;
253
+ }
254
+ if (section === undefined)
255
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
256
+ if (section === "mcp") {
257
+ if (!inCommands) {
258
+ if (indent !== 2 || line !== "commands:")
259
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp");
260
+ inCommands = true;
261
+ continue;
262
+ }
263
+ if (line.startsWith("- ")) {
264
+ if (indent !== 4)
265
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.commands");
266
+ itemOpen = true;
267
+ const first = line.slice(2);
268
+ const kv = /^(\w+):\s*(\S+)$/.exec(first);
269
+ if (kv === null || kv[1] !== "channel")
270
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.commands");
271
+ bare(kv[2], "mcp.commands.channel", /^[A-Za-z0-9_-]{1,32}$/);
272
+ continue;
273
+ }
274
+ if (!itemOpen || indent !== 6)
275
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.commands");
276
+ const kv = /^(\w+):\s*(.+)$/.exec(line);
277
+ if (kv === null || kv[1] !== "command")
278
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.commands");
279
+ if (found.mcpCommand !== undefined)
280
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.commands.command");
281
+ found.mcpCommand = quoted(kv[2], "mcp.commands.command");
282
+ continue;
283
+ }
284
+ if (indent !== 2)
285
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", section);
286
+ const kv = /^(\w+):\s*(\S.*)$/.exec(line);
287
+ if (kv === null)
288
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", section);
289
+ const [, key, rawValue] = kv;
290
+ if (!SECTION_KEYS[section].has(key))
291
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", `${section}.${key}`);
292
+ const tag = `${section}.${key}`;
293
+ if (seen.has(tag))
294
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", tag);
295
+ seen.add(tag);
296
+ switch (tag) {
297
+ case "control_plane.base_url":
298
+ bare(quoted(rawValue, tag), tag, /^https:\/\/[A-Za-z0-9._:-]+(\/[A-Za-z0-9._~/-]*)?$/);
299
+ break;
300
+ case "control_plane.tunnel_id":
301
+ found.tunnelId = quoted(rawValue, tag);
302
+ break;
303
+ case "control_plane.api_key":
304
+ found.apiKey = quoted(rawValue, tag);
305
+ break;
306
+ case "control_plane.organization_id":
307
+ // BG05: optional, profile-only organization context. The client reads
308
+ // this same file; no argv/header injection or parent-env override.
309
+ // This is a bounded local grammar, not remote binding validation.
310
+ found.organizationId = bare(quoted(rawValue, tag), tag, /^org-[A-Za-z0-9]{1,128}$/);
311
+ break;
312
+ case "health.listen_addr":
313
+ bare(quoted(rawValue, tag), tag, /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}$/);
314
+ break;
315
+ case "health.url_file":
316
+ found.urlFile = quoted(rawValue, tag);
317
+ break;
318
+ case "admin_ui.open_browser":
319
+ case "harpoon.capture_payloads":
320
+ case "log.http_raw_unsafe":
321
+ bare(rawValue, tag, /^(true|false)$/);
322
+ break;
323
+ case "log.level":
324
+ bare(rawValue, tag, /^(debug|info|warn|error)$/);
325
+ break;
326
+ case "log.format":
327
+ bare(rawValue, tag, /^(json|text)$/);
328
+ break;
329
+ default: throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", tag);
330
+ }
331
+ }
332
+ if (found.tunnelId === undefined || !/^tunnel_[A-Za-z0-9]{8,}$/.test(found.tunnelId)) {
333
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "control_plane.tunnel_id");
334
+ }
335
+ if (found.apiKey === undefined) {
336
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "control_plane.api_key");
337
+ }
338
+ if (!found.apiKey.startsWith("file:")) {
339
+ // env: references and inline values are both refused: this manager only
340
+ // ever allows the pre-existing operator key FILE reference.
341
+ throw new TunnelRefusal("CE_TUNNEL_CREDENTIAL_HANDOFF_BLOCKED", "control_plane.api_key");
342
+ }
343
+ const keyFile = found.apiKey.slice("file:".length);
344
+ if (!isAbsolute(keyFile) || normalize(keyFile) !== keyFile) {
345
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "control_plane.api_key");
346
+ }
347
+ if (found.urlFile === undefined || !isAbsolute(found.urlFile) || normalize(found.urlFile) !== found.urlFile) {
348
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "health.url_file");
349
+ }
350
+ return { tunnelId: found.tunnelId, organizationId: found.organizationId, keyFile, urlFile: found.urlFile, mcpCommand: found.mcpCommand };
351
+ }
352
+ export function checkKeyFileMetadata(path) {
353
+ let stat;
354
+ try {
355
+ stat = lstatSync(path);
356
+ }
357
+ catch {
358
+ throw new TunnelRefusal("CE_TUNNEL_KEY_MISSING", "control_plane.api_key");
359
+ }
360
+ const euid = process.geteuid?.();
361
+ if (euid === undefined)
362
+ throw new TunnelRefusal("CE_TUNNEL_KEY_PERMS_INVALID", "control_plane.api_key");
363
+ const verdict = checkKeyFileRequirements({
364
+ mode: stat.mode, uid: stat.uid, ownerUid: euid,
365
+ isSymbolicLink: stat.isSymbolicLink(), size: stat.size,
366
+ });
367
+ if (!verdict.ok)
368
+ throw new TunnelRefusal("CE_TUNNEL_KEY_PERMS_INVALID", "control_plane.api_key");
369
+ }
370
+ // ---------------------------------------------------------------------------
371
+ // Production process adapters (S3/C5/S9): /bin/ps, fixed minimal env, LC_ALL=C.
372
+ // ---------------------------------------------------------------------------
373
+ const PS_ENV = Object.freeze({ PATH: "/usr/bin:/bin", LC_ALL: "C" });
374
+ function parsePsIdentity(pid, stdout) {
375
+ const trimmed = stdout.trim();
376
+ if (trimmed === "")
377
+ return { kind: "unknown" }; // exit 0 without a row is NOT absence proof
378
+ const match = /^(\w{3}\s+\w{3}\s+\d+\s+\d\d:\d\d:\d\d\s+\d{4})\s+(.+)$/.exec(trimmed);
379
+ if (match === null)
380
+ return { kind: "unknown" };
381
+ return { kind: "present", identity: { pid, startedKey: match[1], command: match[2] } };
382
+ }
383
+ const defaultInspectProcess = (pid) => new Promise((resolve) => {
384
+ nodeExecFile(PS_PATH, ["-p", String(pid), "-o", "lstart=,command="], { timeout: 5_000, env: { ...PS_ENV } }, (error, stdout) => {
385
+ if (error === null) {
386
+ resolve(parsePsIdentity(pid, stdout));
387
+ return;
388
+ }
389
+ // SAFETY: execFile errors carry the numeric exit `code` when the child ran
390
+ // and exited; ps exits 1 with empty stdout exactly when the pid is gone.
391
+ const code = error.code;
392
+ if (code === 1 && (stdout ?? "").trim() === "") {
393
+ resolve({ kind: "absent" });
394
+ return;
395
+ }
396
+ resolve({ kind: "unknown" });
397
+ });
398
+ });
399
+ const defaultListProcesses = () => new Promise((resolve) => {
400
+ nodeExecFile(PS_PATH, ["-ax", "-o", "pid=,lstart=,command="], { timeout: 5_000, maxBuffer: 4 * 1024 * 1024, env: { ...PS_ENV } }, (error, stdout) => {
401
+ if (error !== null) {
402
+ resolve({ kind: "unknown" });
403
+ return;
404
+ }
405
+ const out = [];
406
+ for (const line of stdout.split("\n")) {
407
+ const pidMatch = /^\s*(\d+)\s+(.*)$/.exec(line);
408
+ if (pidMatch === null)
409
+ continue;
410
+ const pidText = pidMatch[1];
411
+ if (pidText === undefined)
412
+ continue;
413
+ const row = parsePsIdentity(Number.parseInt(pidText, 10), pidMatch[2] ?? "");
414
+ if (row.kind !== "present")
415
+ continue;
416
+ // Refusal-only discovery must not depend on a configurable client's basename.
417
+ if (!row.identity.command.includes("--profile-file ") && !row.identity.command.includes("mcp-stdio.js"))
418
+ continue;
419
+ out.push(row.identity);
420
+ }
421
+ resolve({ kind: "ok", processes: out });
422
+ });
423
+ });
424
+ function defaultProbeHealth(clientPath) {
425
+ return (urlFile, pid) => new Promise((resolve) => {
426
+ if (clientPath === undefined) {
427
+ resolve({ stdout: "", exitCode: 2 });
428
+ return;
429
+ }
430
+ nodeExecFile(clientPath, ["health", "--url-file", urlFile, "--pid", String(pid), "--require-control-plane-poll", "--json"], { timeout: PROBE_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: { ...PS_ENV, HOME: process.env.HOME ?? "" } }, (error, stdout) => {
431
+ if (error === null) {
432
+ resolve({ stdout: stdout ?? "", exitCode: 0 });
433
+ return;
434
+ }
435
+ // SAFETY: same execFile error shape as above.
436
+ const err = error;
437
+ if (typeof err.code === "number") {
438
+ // A cleanly exited probe keeps its stdout for the frozen parser
439
+ // (measured fail shapes); exit code itself never decides health.
440
+ resolve({ stdout: stdout ?? "", exitCode: err.code });
441
+ return;
442
+ }
443
+ // S10: timeout/kill/spawn failure — stdout is untrusted partial output.
444
+ resolve({ stdout: "", exitCode: 2 });
445
+ });
446
+ });
447
+ }
448
+ function defaultSpawnDaemon(logPath) {
449
+ return (executable, args, options) => {
450
+ const fd = openSync(logPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND | fsConstants.O_NOFOLLOW, 0o600);
451
+ try {
452
+ // An inherited log with loose permissions is tightened, never trusted.
453
+ const stat = fstatSync(fd);
454
+ if ((stat.mode & 0o777) !== 0o600)
455
+ chmodSync(logPath, 0o600);
456
+ return nodeSpawn(executable, [...args], {
457
+ env: { ...options.env },
458
+ detached: true,
459
+ stdio: ["ignore", fd, fd],
460
+ });
461
+ }
462
+ finally {
463
+ closeSync(fd);
464
+ }
465
+ };
466
+ }
467
+ const MAX_WRAPPER_BYTES = 4096;
468
+ const SHEBANG_RE = /^#!(\/[^\s\u0000]+)$/;
469
+ const WRAPPER_EXEC_RE = /^exec "(\/[^"\\\r\n\u0000]+)" "\$@"$/;
470
+ export function resolveWrapperIdentityEvidence(clientPath) {
471
+ let text;
472
+ try {
473
+ const stat = statSync(clientPath); // follows the brew bin symlink
474
+ if (!stat.isFile() || stat.size === 0 || stat.size > MAX_WRAPPER_BYTES)
475
+ return undefined;
476
+ text = readFileSync(clientPath, "utf8");
477
+ }
478
+ catch {
479
+ return undefined;
480
+ }
481
+ if (!text.startsWith("#!"))
482
+ return {}; // direct binary: no wrapper forms
483
+ const lines = text.split("\n");
484
+ const shebang = SHEBANG_RE.exec((lines[0] ?? "").replace(/\r$/, ""));
485
+ const shellPrefix = shebang !== null && /^[ -~]+$/.test(shebang[1]) && normalize(shebang[1]) === shebang[1]
486
+ ? shebang[1]
487
+ : undefined;
488
+ const evidence = shellPrefix === undefined ? {} : { shellPrefix };
489
+ // C-1 (Lane C): the exec form is accepted only when the ENTIRE file is the
490
+ // canonical shim shape — shebang, then exactly ONE strict exec line, with
491
+ // every other line blank or a comment. Anything else (heredocs, indented or
492
+ // argument-carrying exec, conditionals, extra statements) means the file's
493
+ // execution semantics are not fully understood here, so NO exec evidence is
494
+ // produced (fail closed). The shell-prefix form rests on the shebang alone,
495
+ // which the kernel honors regardless of the script body.
496
+ const meaningful = lines.slice(1).filter((line) => {
497
+ const trimmed = line.trim();
498
+ return trimmed !== "" && !trimmed.startsWith("#");
499
+ });
500
+ if (meaningful.length !== 1)
501
+ return evidence;
502
+ const execMatch = WRAPPER_EXEC_RE.exec(meaningful[0]); // column-0, strict
503
+ if (execMatch === null)
504
+ return evidence;
505
+ const target = execMatch[1];
506
+ if (!/^[ -~]+$/.test(target) || normalize(target) !== target)
507
+ return evidence;
508
+ try {
509
+ if (!statSync(target).isFile())
510
+ return evidence;
511
+ }
512
+ catch {
513
+ return evidence;
514
+ }
515
+ evidence.execTarget = target;
516
+ return evidence;
517
+ }
518
+ // ---------------------------------------------------------------------------
519
+ // Ownership record (S7/S8): strict load, random-name O_EXCL temp, 0700 dir.
520
+ // ---------------------------------------------------------------------------
521
+ function ensureStateDir(dir) {
522
+ const euid = process.geteuid?.();
523
+ try {
524
+ const stat = lstatSync(dir);
525
+ if (!stat.isDirectory() || stat.isSymbolicLink())
526
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "state-dir");
527
+ if (euid !== undefined && stat.uid !== euid)
528
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "state-dir");
529
+ // An existing directory is verified, never re-permissioned (S7).
530
+ if ((stat.mode & 0o777) !== 0o700)
531
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "state-dir");
532
+ }
533
+ catch (error) {
534
+ if (error instanceof TunnelRefusal)
535
+ throw error;
536
+ try {
537
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
538
+ chmodSync(dir, 0o700);
539
+ }
540
+ catch {
541
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "state-dir");
542
+ }
543
+ }
544
+ }
545
+ function loadRecord(file) {
546
+ let stat;
547
+ try {
548
+ stat = lstatSync(file);
549
+ }
550
+ catch (error) {
551
+ // R6/C-v2-6: ONLY ENOENT means "no record"; EACCES/EIO/… fail closed.
552
+ if (error.code === "ENOENT")
553
+ return { kind: "none" };
554
+ return { kind: "corrupt" };
555
+ }
556
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_RECORD_BYTES)
557
+ return { kind: "corrupt" };
558
+ let parsed;
559
+ try {
560
+ parsed = JSON.parse(readFileSync(file, "utf8"));
561
+ }
562
+ catch {
563
+ return { kind: "corrupt" };
564
+ }
565
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
566
+ return { kind: "corrupt" };
567
+ const r = parsed;
568
+ const valid = r.version === 1 &&
569
+ typeof r.runId === "string" && r.runId.length > 0 &&
570
+ typeof r.pid === "number" && Number.isSafeInteger(r.pid) && r.pid > 0 &&
571
+ typeof r.commandIdentity === "string" && typeof r.processStartedKey === "string" &&
572
+ (r.commandIdentityExec === undefined || r.commandIdentityExec === null ||
573
+ (typeof r.commandIdentityExec === "string" && r.commandIdentityExec.length > 0 && r.commandIdentityExec.length <= 4096)) &&
574
+ typeof r.profilePath === "string" && typeof r.tunnelId === "string" &&
575
+ typeof r.urlFile === "string" && typeof r.keyFile === "string" &&
576
+ typeof r.logPath === "string" &&
577
+ typeof r.startedAt === "number" && Number.isFinite(r.startedAt) && r.startedAt > 0 && r.startedAt < 4.1e12 &&
578
+ (r.termRequestedAt === undefined || r.termRequestedAt === null || (typeof r.termRequestedAt === "number" && Number.isFinite(r.termRequestedAt))) &&
579
+ (r.state === "running" || r.state === "stop-unconfirmed" || r.state === "stopped") &&
580
+ r.identityPending === undefined; // an identity-pending record must never come from disk
581
+ if (!valid)
582
+ return { kind: "corrupt" };
583
+ // C-v2-3: a serialized null normalizes to absent, so a loaded record always
584
+ // matches the declared `string | undefined` (JSON.stringify drops undefined,
585
+ // so a first-party writer never emits null; a foreign null is inert anyway
586
+ // because exact command equality against null is impossible).
587
+ if (r.commandIdentityExec === null)
588
+ delete parsed.commandIdentityExec;
589
+ // F2 (Lane C v3): same normalization for the ledger field — a foreign null
590
+ // must not read as "SIGTERM already requested" (every consumer uses
591
+ // !== undefined), which would suppress termination and lie in stop notes.
592
+ if (r.termRequestedAt === null)
593
+ delete parsed.termRequestedAt;
594
+ // SAFETY: every consumed field is individually validated above; the
595
+ // assertion only restores the readonly narrowings TypeScript cannot infer.
596
+ return { kind: "ok", record: parsed };
597
+ }
598
+ function mapStateName(name) {
599
+ switch (name) {
600
+ case "Connected": return "CONNECTED";
601
+ case "Starting":
602
+ case "Connecting": return "STARTING";
603
+ case "Disconnected":
604
+ case "Stopping":
605
+ case "Error": return "DEGRADED";
606
+ case "Unknown": return "UNKNOWN";
607
+ case "Stopped":
608
+ default: return "STOPPED";
609
+ }
610
+ }
611
+ /** Single path-selection authority for manager, setup and configuration status.
612
+ * Reject control bytes before a path can reach any visible TUI/status surface. */
613
+ export function resolveTunnelProfilePath(options) {
614
+ const path = options.profilePath ??
615
+ (typeof options.env.CE_TUNNEL_PROFILE === "string" && options.env.CE_TUNNEL_PROFILE.length > 0
616
+ ? options.env.CE_TUNNEL_PROFILE : defaultProfilePath());
617
+ if (!isAbsolute(path) || normalize(path) !== path || !/^[\x20\x21\x23-\x5B\x5D-\x7E]+$/.test(path)) {
618
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile.path");
619
+ }
620
+ return path;
621
+ }
622
+ export function createBackgroundTunnelManager(options) {
623
+ const env = options.env ?? {};
624
+ const now = options.now ?? Date.now;
625
+ const timing = options.timing ?? DEFAULT_BACKGROUND_TUNNEL_TIMING;
626
+ // Constructor overrides remain domain-test dependencies. Operator settings
627
+ // and discovered production executables always cross the trust boundary.
628
+ const clientPath = options.clientPath ?? (() => {
629
+ try {
630
+ return resolveTunnelClient({ env });
631
+ }
632
+ catch {
633
+ return undefined;
634
+ }
635
+ })();
636
+ const profilePath = resolveTunnelProfilePath(options);
637
+ const stateFilePath = options.stateFilePath ?? `${dirname(profilePath)}/background-state.json`;
638
+ const logPath = `${dirname(stateFilePath)}/background-tunnel.log`;
639
+ const spawnSeam = options.spawn ?? defaultSpawnDaemon(logPath);
640
+ /** Exact command lines this manager's own spawn may show in ps (F2): the
641
+ * direct argv, plus wrapper-evidence forms (shell prefix / exec target).
642
+ * Recomputed at every start; used only for the never-persisted pending
643
+ * re-acquisition path, which belongs to this process's own spawn. */
644
+ let pendingSpawnIdentities = [`${clientPath} run --profile-file ${profilePath}`];
645
+ /** S-1 (Lane S) + F1 (Lane C v3): spawn-linked exit proof, archived PER RUN.
646
+ * A child handle's exit event is FIRST-CLASS evidence that OUR spawn is
647
+ * dead; once fired, any process at that pid is foreign (PID reuse) and the
648
+ * run must never adopt or signal it. Evidence is keyed by runId (UUIDs,
649
+ * never reused), so a later start can never sever or inherit another run's
650
+ * binding — single-slot state provably cannot serve the dual-run stop path
651
+ * (S5-7). The listener is armed BEFORE the identity-capture loop (the
652
+ * dominant pending path is a child dying INSIDE that window). Handles are
653
+ * strongly held defensively (S-2/F4: a listener does not retain its
654
+ * emitter; no runtime-observable behavior depends on this in tests).
655
+ * Entries are deleted when their run closes; consulted only for
656
+ * identityPending records (same session). */
657
+ const exitedPendingRuns = new Set();
658
+ const pendingChildren = new Map();
659
+ const inspect = options.inspectProcess ?? defaultInspectProcess;
660
+ const listProcesses = options.listProcesses ?? defaultListProcesses;
661
+ const probeHealth = options.probeHealth ?? defaultProbeHealth(clientPath);
662
+ const signal = options.signal ?? ((pid, sig) => process.kill(pid, sig));
663
+ let state = initialTunnelState(now());
664
+ /** In-memory view; refresh/stop/start always re-read the record from disk. */
665
+ let record;
666
+ let recordCorrupt = false;
667
+ {
668
+ const loaded = loadRecord(stateFilePath);
669
+ if (loaded.kind === "ok")
670
+ record = loaded.record;
671
+ if (loaded.kind === "corrupt")
672
+ recordCorrupt = true;
673
+ }
674
+ let recorder;
675
+ /** State-machine start baseline per run: spawn time for own runs, first
676
+ * observation time for adopted ones (C1). */
677
+ const machineStart = new Map();
678
+ /** PID reuse/foreign identity observed: status is UNKNOWN until re-verified. */
679
+ let identityMismatch = false;
680
+ let note = record?.state === "stop-unconfirmed" ? "previous stop unconfirmed; ownership retained" : undefined;
681
+ let disposed = false;
682
+ /** C3: one serialized lifecycle queue per manager (cross-process exclusion is
683
+ * the lock; this queue fences THIS manager's async interleavings). */
684
+ let lifecycle = Promise.resolve();
685
+ /** A stop (here or in another session) invalidates a pending start. */
686
+ let startFence = 0;
687
+ let stopping;
688
+ /** A start submitted but not settled; stop awaits it before taking the lock. */
689
+ let activeStart;
690
+ /** R3/C-v2-1: spawned but UNPERSISTED ownership. Disk ENOENT never discards
691
+ * it; stop/refresh keep managing it until exit is proven. */
692
+ let pendingRecord;
693
+ /** R2: in-memory single-signal guard for runs that could not be persisted.
694
+ * A crash loses this set AND the record together, so the global at-most-once
695
+ * signal invariant still holds. */
696
+ const termIntentSent = new Set();
697
+ /** Runs spawned by THIS session: their startup deadline is real. Adopted
698
+ * runs are supervised with an unbounded startup window instead (C-v2-5). */
699
+ const spawnedRuns = new Set();
700
+ const recorderFor = (runId, pid) => {
701
+ if (recorder === undefined || recorder.runId !== runId) {
702
+ recorder = { runId, record: createHealthCompletionRecorder(runId, pid, now) };
703
+ }
704
+ return recorder.record;
705
+ };
706
+ const sleep = (ms) => new Promise((resolve) => {
707
+ const timer = setTimeout(resolve, ms);
708
+ timer.unref?.();
709
+ });
710
+ const enqueue = (op) => {
711
+ const run = lifecycle.then(op, op);
712
+ lifecycle = run.then(() => undefined, () => undefined);
713
+ return run;
714
+ };
715
+ // --- cross-process lock (S4/C2, v3 R1/R7/C-v2-4) -----------------------------
716
+ // A mkdir DIRECTORY lock: creation is atomic; stale reclaim claims the right
717
+ // to delete by renaming the old dir to a unique grave first (exactly one
718
+ // reclaimer wins), so no contender can ever delete a live successor's lock.
719
+ const lockDir = `${stateFilePath}.lock.d`;
720
+ const holderPath = `${lockDir}/holder.json`;
721
+ const LOCK_RETRIES = 3;
722
+ /** The lock token this manager currently holds (critical-section guard). */
723
+ let heldLockToken;
724
+ /** Judge the existing lock; the caller re-verifies identity after rename. */
725
+ const judgeLock = async () => {
726
+ let stat;
727
+ try {
728
+ stat = lstatSync(lockDir);
729
+ }
730
+ catch {
731
+ return undefined; // vanished or unreadable: retry mkdir, never delete blind
732
+ }
733
+ if (!stat.isDirectory())
734
+ return { stale: false, ino: stat.ino, mtimeMs: stat.mtimeMs };
735
+ const base = { ino: stat.ino, mtimeMs: stat.mtimeMs };
736
+ let holder;
737
+ try {
738
+ holder = JSON.parse(readFileSync(holderPath, "utf8"));
739
+ }
740
+ catch {
741
+ holder = undefined;
742
+ }
743
+ if (holder !== undefined && typeof holder.pid === "number" && holder.pid > 0) {
744
+ const presence = await inspect(holder.pid);
745
+ const pidStale = presence.kind === "absent" ||
746
+ (presence.kind === "present" && typeof holder.startedKey === "string" &&
747
+ presence.identity.startedKey !== holder.startedKey);
748
+ // S5-4: `leaked` is an ADDITIONAL age-based reclaim reason; the pid
749
+ // judgement still applies to every holder.
750
+ const ageStale = holder.leaked === true && Date.now() - stat.mtimeMs > LOCK_STALE_MS;
751
+ return { ...base, stale: pidStale || ageStale };
752
+ }
753
+ // Crash between mkdir and holder write (or partial write/removal), or a
754
+ // leaked holder (F5): recoverable by age only. A live creator writes its
755
+ // holder immediately, refreshing the dir mtime; an old holderless dir
756
+ // belongs to a crashed or failed acquirer (R7). Wall-clock age is a REAL
757
+ // cross-process fact, so it deliberately uses Date.now, not the
758
+ // injectable clock.
759
+ return { ...base, stale: Date.now() - stat.mtimeMs > LOCK_STALE_MS };
760
+ };
761
+ const acquireLock = async () => {
762
+ ensureStateDir(dirname(stateFilePath));
763
+ const token = randomUUID();
764
+ for (let attempt = 0;; attempt++) {
765
+ try {
766
+ mkdirSync(lockDir); // atomic: exactly one acquirer wins
767
+ }
768
+ catch {
769
+ // A lock WE leaked (release failed while we still live) is reclaimable
770
+ // by us alone; a live foreign holder is always respected.
771
+ let existingToken;
772
+ try {
773
+ existingToken = JSON.parse(readFileSync(holderPath, "utf8")).token;
774
+ }
775
+ catch {
776
+ existingToken = undefined;
777
+ }
778
+ const leaked = typeof existingToken === "string" && leakedLockTokens.has(existingToken);
779
+ const judgement = leaked ? undefined : await judgeLock();
780
+ if (leaked || judgement?.stale === true) {
781
+ options.reclaimProbe?.(); // test seam: inject the judge→rename window
782
+ // Claim the sole right to remove by renaming FIRST (R1/C-v2-4).
783
+ const grave = `${lockDir}.reclaim-${token}`;
784
+ let renamed = false;
785
+ try {
786
+ renameSync(lockDir, grave);
787
+ renamed = true;
788
+ }
789
+ catch { /* another reclaimer won; loop and retry mkdir */ }
790
+ if (renamed) {
791
+ // C-v3-2/S3-1/F2: judgement and rename are NOT atomic (a real ps
792
+ // call sits between them). Verify the grave IS the directory we
793
+ // judged — same inode+mtime AND same holder token (holderless
794
+ // branch: still holderless). A live successor created meanwhile
795
+ // fails this check: roll back and refuse, never delete it.
796
+ let graveToken;
797
+ let graveStat;
798
+ try {
799
+ graveStat = lstatSync(grave);
800
+ graveToken = JSON.parse(readFileSync(`${grave}/holder.json`, "utf8")).token;
801
+ }
802
+ catch {
803
+ graveToken = undefined;
804
+ }
805
+ const sameLock = graveStat !== undefined &&
806
+ (judgement === undefined ||
807
+ (graveStat.ino === judgement.ino && graveStat.mtimeMs === judgement.mtimeMs)) &&
808
+ (existingToken === undefined ? graveToken === undefined : graveToken === existingToken);
809
+ if (!sameLock) {
810
+ try {
811
+ renameSync(grave, lockDir);
812
+ }
813
+ catch { /* best effort rollback */ }
814
+ throw new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
815
+ }
816
+ try {
817
+ rmSync(grave, { recursive: true, force: true });
818
+ }
819
+ catch { /* harmless residue; swept on a later acquire */ }
820
+ if (typeof existingToken === "string")
821
+ leakedLockTokens.delete(existingToken);
822
+ }
823
+ continue;
824
+ }
825
+ if (attempt + 1 >= LOCK_RETRIES)
826
+ throw new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
827
+ await sleep(100);
828
+ continue;
829
+ }
830
+ // C-v3-7/C-v4-6: best-effort sweep of AGED reclaim graves belonging to
831
+ // THIS lock only — a concurrent reclaimer's fresh grave is untouched.
832
+ try {
833
+ const dir = dirname(stateFilePath);
834
+ const prefix = `${lockDir.slice(dir.length + 1)}.reclaim-`;
835
+ for (const entry of readdirSync(dir)) {
836
+ if (!entry.startsWith(prefix))
837
+ continue;
838
+ try {
839
+ if (Date.now() - lstatSync(`${dir}/${entry}`).mtimeMs <= LOCK_STALE_MS)
840
+ continue;
841
+ rmSync(`${dir}/${entry}`, { recursive: true, force: true });
842
+ }
843
+ catch { /* ignore */ }
844
+ }
845
+ }
846
+ catch { /* sweep is best effort */ }
847
+ let selfStartedKey;
848
+ try {
849
+ const self = await inspect(process.pid);
850
+ selfStartedKey = self.kind === "present" ? self.identity.startedKey : undefined;
851
+ writeFileSync(holderPath, JSON.stringify({
852
+ token, pid: process.pid, acquiredAt: now(), startedKey: selfStartedKey,
853
+ }), { mode: 0o600 });
854
+ }
855
+ catch (error) {
856
+ // R7+F4: never leave a holderless lock behind on our own failure, and
857
+ // never delete a directory that is no longer OURS (a successor may
858
+ // already hold the path).
859
+ let foreign = false;
860
+ try {
861
+ const current = JSON.parse(readFileSync(holderPath, "utf8"));
862
+ foreign = current.token !== undefined && current.token !== token;
863
+ }
864
+ catch { /* holder missing/unparseable: still our fresh dir */ }
865
+ if (!foreign) {
866
+ try {
867
+ rmSync(lockDir, { recursive: true, force: true });
868
+ }
869
+ catch { /* best effort */ }
870
+ }
871
+ throw error instanceof TunnelRefusal ? error : new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
872
+ }
873
+ heldLockToken = token;
874
+ let released = false;
875
+ return () => {
876
+ if (released)
877
+ return;
878
+ released = true;
879
+ if (heldLockToken === token)
880
+ heldLockToken = undefined;
881
+ try {
882
+ const current = JSON.parse(readFileSync(holderPath, "utf8"));
883
+ if (current.token === token) {
884
+ rmSync(lockDir, { recursive: true, force: true });
885
+ }
886
+ return; // success, or the lock is no longer ours — never delete
887
+ }
888
+ catch { /* fall through to leaked tracking */ }
889
+ // S3-4/F5/S5-4: keep the token evidence readable (with startedKey, so
890
+ // the pid/startedKey stale judgement still applies, and `leaked: true`
891
+ // additionally allows age reclaim) so THIS process can reclaim its own
892
+ // leaked lock deterministically.
893
+ try {
894
+ writeFileSync(holderPath, JSON.stringify({
895
+ token, pid: process.pid, leaked: true,
896
+ startedKey: selfStartedKey,
897
+ }), { mode: 0o600 });
898
+ }
899
+ catch { /* dir unwritable; the age protocol remains */ }
900
+ leakedLockTokens.add(token);
901
+ };
902
+ }
903
+ };
904
+ /** S3-1(b): inside a critical section, prove the lock is still ours before
905
+ * any persist/signal. If a reclaim ever stole it, fail closed. */
906
+ const assertLockIntact = () => {
907
+ const mine = heldLockToken;
908
+ if (mine === undefined)
909
+ return; // not inside a critical section
910
+ try {
911
+ const current = JSON.parse(readFileSync(holderPath, "utf8"));
912
+ if (current.token === mine)
913
+ return;
914
+ }
915
+ catch { /* unreadable holder while we hold it: fail closed */ }
916
+ throw new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
917
+ };
918
+ const reloadRecord = () => {
919
+ const loaded = loadRecord(stateFilePath);
920
+ recordCorrupt = loaded.kind === "corrupt";
921
+ if (loaded.kind === "ok") {
922
+ // C-v3-1 + C-v4-2: pending (unpersisted) ownership outranks only a
923
+ // STOPPED disk record of a different run — a stopped record must never
924
+ // hide a live pending daemon, but another session's LIVE record always
925
+ // wins the in-memory view (persist() independently refuses to overwrite
926
+ // it).
927
+ record = pendingRecord !== undefined && loaded.record.runId !== pendingRecord.runId &&
928
+ loaded.record.state === "stopped"
929
+ ? pendingRecord
930
+ : loaded.record;
931
+ }
932
+ else if (loaded.kind === "none") {
933
+ record = pendingRecord; // R3: ENOENT never discards pending ownership
934
+ }
935
+ // corrupt: keep the previous in-memory view; mutations refuse elsewhere
936
+ };
937
+ const persist = (next) => {
938
+ // An identity-pending record is memory-only by design: persisting it would
939
+ // both corrupt the on-disk schema and invent an unverified identity.
940
+ if (next.identityPending === true)
941
+ throw new TunnelRefusal("CE_TUNNEL_STATE_CORRUPT");
942
+ // F3/C-v5-4: EVERY ledger write happens under this manager's held lock —
943
+ // machine-enforced, not advisory.
944
+ if (heldLockToken === undefined)
945
+ throw new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
946
+ assertLockIntact();
947
+ // F1/C-v4-2/S5-5: never overwrite a DIFFERENT run's live record — that
948
+ // would roll back another session's ownership and termination ledger —
949
+ // and never overwrite a CORRUPT record we cannot even read (S8).
950
+ const onDisk = loadRecord(stateFilePath);
951
+ if (onDisk.kind === "corrupt")
952
+ throw new TunnelRefusal("CE_TUNNEL_STATE_CORRUPT");
953
+ if (onDisk.kind === "ok" && onDisk.record.runId !== next.runId && onDisk.record.state !== "stopped") {
954
+ throw new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
955
+ }
956
+ ensureStateDir(dirname(stateFilePath));
957
+ const tmp = `${stateFilePath}.${randomUUID()}.tmp`;
958
+ const fd = openSync(tmp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL, 0o600);
959
+ try {
960
+ writeFileSync(fd, `${JSON.stringify(next, null, 2)}\n`);
961
+ }
962
+ finally {
963
+ closeSync(fd);
964
+ }
965
+ renameSync(tmp, stateFilePath);
966
+ chmodSync(stateFilePath, 0o600);
967
+ record = next;
968
+ if (pendingRecord?.runId === next.runId) {
969
+ exitedPendingRuns.delete(next.runId);
970
+ pendingChildren.delete(next.runId);
971
+ pendingRecord = undefined;
972
+ }
973
+ };
974
+ // F2: the startedKey anchor is unchanged; the command must equal EITHER the
975
+ // identity captured at start OR the spawn-time wrapper exec evidence. Both
976
+ // are exact full-string matches — substring/basename matches never pass.
977
+ const identityMatches = (current, actual) => actual.startedKey === current.processStartedKey &&
978
+ (actual.command === current.commandIdentity ||
979
+ (current.commandIdentityExec !== undefined && actual.command === current.commandIdentityExec));
980
+ const machineStartedAt = (current) => {
981
+ let baseline = machineStart.get(current.runId);
982
+ if (baseline === undefined) {
983
+ // C1: an adopted run's supervision window starts at first observation.
984
+ // Callers capture this BEFORE any async probe so a health completion can
985
+ // never predate the baseline (C-v2-5).
986
+ baseline = now();
987
+ machineStart.set(current.runId, baseline);
988
+ }
989
+ return baseline;
990
+ };
991
+ /** Own spawns keep the real startup deadline; adopted runs get an unbounded
992
+ * startup window so an observation lapse is DEGRADED, never terminal. */
993
+ const timingFor = (runId) => spawnedRuns.has(runId) ? timing : { ...timing, startupTimeoutMs: Number.MAX_SAFE_INTEGER / 4 };
994
+ const observeAbsence = (current, runTiming, baseline) => {
995
+ state = nextTunnelState(state, {
996
+ now: now(), runId: current.runId, managedPid: current.pid, processAlive: false,
997
+ userStopped: current.termRequestedAt !== undefined, startedAt: baseline ?? machineStartedAt(current),
998
+ exit: { code: null, signal: current.termRequestedAt !== undefined ? "SIGTERM" : null },
999
+ probe: undefined, startupLogSeen: false, externalInstance: false,
1000
+ }, runTiming ?? timingFor(current.runId));
1001
+ };
1002
+ const markStopped = (current, stopNote) => ({
1003
+ ...current, state: "stopped", stoppedAt: now(), note: stopNote,
1004
+ });
1005
+ /** The ONE termination path (S5/C8, v3 R2/R3): identity re-verified, signal
1006
+ * at most once. The ledger is authoritative: a record-backed run is
1007
+ * signalled only after termRequestedAt PERSISTS; an unpersisted pending run
1008
+ * falls back to the in-memory once-set (a crash loses both together). */
1009
+ const terminateOwned = async (input, graceMs) => {
1010
+ let current = input;
1011
+ const presence = await inspect(current.pid);
1012
+ if (presence.kind === "absent")
1013
+ return "stopped";
1014
+ if (presence.kind === "unknown")
1015
+ return "unknown";
1016
+ if (current.identityPending === true) {
1017
+ // Spawned child whose identity was never confirmed: re-acquire now.
1018
+ // S-1 FIRST: if the spawn-linked child already exited, OUR process is
1019
+ // provably dead and any process at this pid is a foreign reuser — never
1020
+ // adopt its startedKey, never signal it. The run's exit is proven.
1021
+ if (exitedPendingRuns.has(current.runId))
1022
+ return "stopped";
1023
+ // S3-2 + F2: we spawned it, so the argv is KNOWN — require membership in
1024
+ // the exact, evidence-derived spawn-identity set (direct argv plus any
1025
+ // wrapper shell/exec forms). Substring matching is refused (forged argv
1026
+ // must never match). A live child link (no exit event) pins the pid to
1027
+ // our spawn, so the observed startedKey IS our child's start time.
1028
+ if (!pendingSpawnIdentities.includes(presence.identity.command)) {
1029
+ identityMismatch = true;
1030
+ note = "spawned child identity unconfirmed; retained ownership, no signal sent";
1031
+ return "unknown";
1032
+ }
1033
+ current = {
1034
+ ...current, commandIdentity: presence.identity.command,
1035
+ processStartedKey: presence.identity.startedKey, identityPending: undefined,
1036
+ };
1037
+ try {
1038
+ persist(current);
1039
+ }
1040
+ catch { /* stays pending; in-memory guard below still applies */ }
1041
+ }
1042
+ else if (!identityMatches(current, presence.identity)) {
1043
+ identityMismatch = true;
1044
+ note = "process identity mismatch; retained record, no signal sent";
1045
+ return "unknown";
1046
+ }
1047
+ identityMismatch = false;
1048
+ if (current.termRequestedAt === undefined) {
1049
+ const requested = { ...current, termRequestedAt: now() };
1050
+ // Snapshot BEFORE any bookkeeping: at-most-once spans the persisted
1051
+ // ledger and the in-memory guard across BOTH mechanisms.
1052
+ const alreadySent = termIntentSent.has(current.runId);
1053
+ let maySignal = false;
1054
+ try {
1055
+ assertLockIntact(); // S3-1(b): ledger writes happen under OUR lock
1056
+ persist(requested);
1057
+ current = requested;
1058
+ maySignal = !alreadySent;
1059
+ }
1060
+ catch {
1061
+ // R2: a record-backed run may NOT be signalled without its ledger.
1062
+ // A pending (never persisted) run uses the in-memory once-set instead.
1063
+ // The once-set is NOT burned here: it is burned below, only once the
1064
+ // lock is proven held, so a lost lock never burns the guard (F1).
1065
+ if (pendingRecord?.runId === current.runId && !alreadySent)
1066
+ maySignal = true;
1067
+ }
1068
+ if (maySignal) {
1069
+ // S6-4/F1: symmetric with persist — a signal (including the pending-run
1070
+ // in-memory once-set branch) is machine-enforced to a held lock. A
1071
+ // lost lock returns "unknown" (ownership retained) rather than
1072
+ // throwing, preserving the three-state termination contract.
1073
+ if (heldLockToken === undefined) {
1074
+ note = "lock lost before signal; ownership retained, no signal sent";
1075
+ return "unknown";
1076
+ }
1077
+ try {
1078
+ assertLockIntact(); // S3-1(b): never signal after losing the lock
1079
+ }
1080
+ catch {
1081
+ note = "lock lost before signal; ownership retained, no signal sent";
1082
+ return "unknown";
1083
+ }
1084
+ if (!alreadySent)
1085
+ termIntentSent.add(current.runId);
1086
+ try {
1087
+ signal(current.pid, "SIGTERM");
1088
+ }
1089
+ catch { /* delivery failure is not exit proof; record retains ownership */ }
1090
+ }
1091
+ else if (!alreadySent) {
1092
+ note = "termination intent could not be persisted; ownership retained, no signal sent";
1093
+ return "unknown";
1094
+ }
1095
+ // alreadySent && !maySignal: the single signal went out earlier; wait.
1096
+ }
1097
+ const deadline = now() + graceMs;
1098
+ for (;;) {
1099
+ const probe = await inspect(current.pid);
1100
+ if (probe.kind === "absent")
1101
+ return "stopped";
1102
+ if (probe.kind === "unknown")
1103
+ return "unknown";
1104
+ if (now() >= deadline)
1105
+ return "unconfirmed";
1106
+ await sleep(EXIT_POLL_MS);
1107
+ }
1108
+ };
1109
+ const refresh = async () => {
1110
+ reloadRecord();
1111
+ if (recordCorrupt) {
1112
+ note = "ownership record unreadable; refusing to guess";
1113
+ return status();
1114
+ }
1115
+ let current = record;
1116
+ if (current === undefined || current.state === "stopped")
1117
+ return status();
1118
+ // C-v2-5: establish the run baseline BEFORE any async measurement so a
1119
+ // health completion can never predate it.
1120
+ const baseline = machineStartedAt(current);
1121
+ const runTiming = timingFor(current.runId);
1122
+ const presence = await inspect(current.pid);
1123
+ // Exit proof: verified ps absence (the only cross-session proof), OR — for
1124
+ // a never-persisted identity-pending run, same-session only — the spawn
1125
+ // link's exit event (S-1: after it, the pid may be a foreign reuser and
1126
+ // must never be adopted or signalled).
1127
+ if (presence.kind === "absent" || (current.identityPending === true && exitedPendingRuns.has(current.runId))) {
1128
+ observeAbsence(current, runTiming, baseline);
1129
+ // R4/C-v2-3: persist ONLY under the lock, re-checking the run inside.
1130
+ let release;
1131
+ try {
1132
+ release = await acquireLock();
1133
+ }
1134
+ catch {
1135
+ note = "exit observed but not persisted (lock busy); ownership view retained";
1136
+ return status();
1137
+ }
1138
+ try {
1139
+ reloadRecord();
1140
+ if (recordCorrupt)
1141
+ return status();
1142
+ if (record?.runId !== current.runId || record.state === "stopped")
1143
+ return status();
1144
+ // S3-7: persist the record re-read INSIDE the lock, so a concurrent
1145
+ // session's ledger fields (termRequestedAt, note) are not rolled back.
1146
+ const fresh = { ...record, identityPending: undefined };
1147
+ try {
1148
+ persist(markStopped(fresh, fresh.termRequestedAt !== undefined ? "exit observed after SIGTERM"
1149
+ : current.identityPending === true && exitedPendingRuns.has(current.runId) ? "spawn exit observed via child link; no respawn"
1150
+ : "process absent (unexpected; no respawn)"));
1151
+ }
1152
+ catch { /* a persistence failure never fabricates a stop either */ }
1153
+ }
1154
+ finally {
1155
+ release();
1156
+ }
1157
+ return status();
1158
+ }
1159
+ if (presence.kind === "unknown") {
1160
+ note = "process inspection unavailable; ownership retained";
1161
+ return status();
1162
+ }
1163
+ if (current.identityPending === true) {
1164
+ // Same re-acquisition rule as terminateOwned (S3-2 + F2: exact membership
1165
+ // in the evidence-derived spawn-identity set, never substring).
1166
+ if (pendingSpawnIdentities.includes(presence.identity.command)) {
1167
+ const upgraded = {
1168
+ commandIdentity: presence.identity.command,
1169
+ processStartedKey: presence.identity.startedKey,
1170
+ commandIdentityExec: current.commandIdentityExec,
1171
+ };
1172
+ // F1/S8-1: the upgrade persist happens under the lock, MERGED onto the
1173
+ // record re-read INSIDE the lock — a concurrent stop may have persisted
1174
+ // a newer termRequestedAt/state that must NOT be rolled back, and a run
1175
+ // another session already stopped is never resurrected.
1176
+ let release;
1177
+ try {
1178
+ release = await acquireLock();
1179
+ reloadRecord();
1180
+ if (recordCorrupt)
1181
+ return status();
1182
+ const fresh = record;
1183
+ if (fresh !== undefined && fresh.runId === current.runId && fresh.state !== "stopped") {
1184
+ const merged = { ...fresh, ...upgraded, identityPending: undefined };
1185
+ persist(merged);
1186
+ current = merged;
1187
+ }
1188
+ else if (fresh !== undefined && fresh.runId === current.runId && fresh.state === "stopped") {
1189
+ // Already terminated by a concurrent session: do not resurrect.
1190
+ current = { ...fresh, identityPending: undefined };
1191
+ return status();
1192
+ }
1193
+ else {
1194
+ // Still purely pending (no on-disk record): memory-only upgrade.
1195
+ current = { ...current, ...upgraded, identityPending: undefined };
1196
+ }
1197
+ }
1198
+ catch { /* remains pending; the in-memory identity still applies below */ }
1199
+ finally {
1200
+ release?.();
1201
+ }
1202
+ }
1203
+ else {
1204
+ identityMismatch = true;
1205
+ note = "spawned child identity unconfirmed; retained ownership";
1206
+ return status();
1207
+ }
1208
+ }
1209
+ else if (!identityMatches(current, presence.identity)) {
1210
+ identityMismatch = true;
1211
+ note = "process identity mismatch; retained record, no signal sent";
1212
+ return status();
1213
+ }
1214
+ identityMismatch = false;
1215
+ const probe = recorderFor(current.runId, current.pid)(await probeHealth(current.urlFile, current.pid));
1216
+ // C3 fencing: discard the measurement if the run stopped meanwhile.
1217
+ const latest = loadRecord(stateFilePath);
1218
+ if (latest.kind !== "ok" || latest.record.runId !== current.runId || latest.record.state === "stopped") {
1219
+ return status();
1220
+ }
1221
+ state = nextTunnelState(state, {
1222
+ now: now(), runId: current.runId, managedPid: current.pid, processAlive: true,
1223
+ userStopped: current.termRequestedAt !== undefined, startedAt: baseline,
1224
+ exit: undefined, probe, startupLogSeen: false, externalInstance: false,
1225
+ }, runTiming);
1226
+ return status();
1227
+ };
1228
+ const start = () => {
1229
+ // R5/C-v2-2: the lifecycle generation is captured AT CALL TIME, so a stop
1230
+ // submitted before this start executes still invalidates it.
1231
+ const fenceAtCall = startFence;
1232
+ const op = enqueue(() => startImpl(fenceAtCall));
1233
+ activeStart = op;
1234
+ const settled = op.then((result) => { if (activeStart === op)
1235
+ activeStart = undefined; return result; }, (error) => { if (activeStart === op)
1236
+ activeStart = undefined; throw error; });
1237
+ return settled;
1238
+ };
1239
+ /** REAL-START-FIX-01: spawn + persist (ack) separately from readiness
1240
+ * (settled). Both stay joined by activeStart so stop/dispose settle the
1241
+ * full start before proceeding; nothing becomes an unsupervised promise. */
1242
+ const startDeferred = () => {
1243
+ const fenceAtCall = startFence;
1244
+ let resolveAck;
1245
+ let rejectAck;
1246
+ const ack = new Promise((resolve, reject) => { resolveAck = resolve; rejectAck = reject; });
1247
+ const op = enqueue(() => startImpl(fenceAtCall, (spawned) => resolveAck?.(spawned)));
1248
+ activeStart = op;
1249
+ const settled = op.then((result) => { if (activeStart === op)
1250
+ activeStart = undefined; return result; }, (error) => { if (activeStart === op)
1251
+ activeStart = undefined; rejectAck?.(error); throw error; });
1252
+ return { ack, settled };
1253
+ };
1254
+ const startImpl = async (fenceAtCall, onSpawned) => {
1255
+ if (fenceAtCall !== startFence)
1256
+ throw new TunnelRefusal("CE_TUNNEL_READY_TIMEOUT");
1257
+ if (disposed)
1258
+ throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
1259
+ // S1: the real start gate is exact and independent of the offline flag.
1260
+ if (env[BACKGROUND_OPT_IN] !== "1")
1261
+ throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED");
1262
+ if (!isAbsolute(profilePath) || normalize(profilePath) !== profilePath) {
1263
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
1264
+ }
1265
+ let profileText;
1266
+ try {
1267
+ profileText = readFileSync(profilePath, "utf8");
1268
+ }
1269
+ catch {
1270
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
1271
+ }
1272
+ const facts = parseTunnelProfile(profileText);
1273
+ checkKeyFileMetadata(facts.keyFile);
1274
+ const profileSha256 = createHash("sha256").update(profileText, "utf8").digest("hex");
1275
+ // S6/C4: prove the record location is writable BEFORE spawning.
1276
+ ensureStateDir(dirname(stateFilePath));
1277
+ const writabilityProbe = `${stateFilePath}.${randomUUID()}.probe`;
1278
+ try {
1279
+ writeFileSync(writabilityProbe, "", { mode: 0o600, flag: "wx" });
1280
+ unlinkSync(writabilityProbe);
1281
+ }
1282
+ catch {
1283
+ throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
1284
+ }
1285
+ const release = await acquireLock();
1286
+ if (fenceAtCall !== startFence) {
1287
+ release();
1288
+ throw new TunnelRefusal("CE_TUNNEL_READY_TIMEOUT");
1289
+ }
1290
+ let child;
1291
+ try {
1292
+ reloadRecord();
1293
+ if (recordCorrupt)
1294
+ throw new TunnelRefusal("CE_TUNNEL_STATE_CORRUPT");
1295
+ const existing = record;
1296
+ if (existing !== undefined && existing.state !== "stopped") {
1297
+ const presence = await inspect(existing.pid);
1298
+ if (presence.kind === "present" && identityMatches(existing, presence.identity)) {
1299
+ // Identity verified but health NOT re-measured here: report unknown.
1300
+ onSpawned?.({ runId: existing.runId, pid: existing.pid, tunnelId: maskTunnelId(existing.tunnelId), startedAt: new Date(existing.startedAt).toISOString() });
1301
+ return {
1302
+ runId: existing.runId, pid: existing.pid, tunnelId: maskTunnelId(existing.tunnelId),
1303
+ health: "unknown", startedAt: new Date(existing.startedAt).toISOString(), alreadyRunning: true,
1304
+ };
1305
+ }
1306
+ if (presence.kind === "present")
1307
+ throw new TunnelRefusal("CE_TUNNEL_EXTERNAL_INSTANCE");
1308
+ if (presence.kind === "unknown")
1309
+ throw new TunnelRefusal("CE_TUNNEL_STOP_UNCONFIRMED");
1310
+ observeAbsence(existing);
1311
+ // C-v4-1: strip identityPending before persisting — a never-confirmed
1312
+ // run whose process is gone IS superseded (its exit is proven by ps
1313
+ // absence), so persist must not reject it as STATE_CORRUPT.
1314
+ persist(markStopped({ ...existing, identityPending: undefined }, "superseded: previous process absent"));
1315
+ }
1316
+ const listed = await listProcesses();
1317
+ if (listed.kind !== "ok")
1318
+ throw new TunnelRefusal("CE_TUNNEL_HEALTH_UNAVAILABLE");
1319
+ for (const proc of listed.processes) {
1320
+ if (proc.command.includes(`--profile-file ${profilePath}`)) {
1321
+ throw new TunnelRefusal("CE_TUNNEL_EXTERNAL_INSTANCE");
1322
+ }
1323
+ }
1324
+ if (fenceAtCall !== startFence)
1325
+ throw new TunnelRefusal("CE_TUNNEL_READY_TIMEOUT");
1326
+ assertLockIntact(); // S3-1(b): the lock must still be ours before spawn
1327
+ // Setup commits under this same lock. Recheck after ALL asynchronous
1328
+ // identity/list operations: never spawn against a different generation
1329
+ // than the facts and credential metadata validated above.
1330
+ let currentProfileText;
1331
+ try {
1332
+ currentProfileText = readFileSync(profilePath, "utf8");
1333
+ }
1334
+ catch {
1335
+ throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
1336
+ }
1337
+ if (currentProfileText !== profileText)
1338
+ throw new TunnelRefusal("CE_TUNNEL_CONFIG_CONFLICT", "profile");
1339
+ checkKeyFileMetadata(facts.keyFile);
1340
+ if (clientPath === undefined)
1341
+ throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED", "client");
1342
+ const runId = `bg-${randomUUID()}`;
1343
+ const startedAt = now();
1344
+ state = initialTunnelState(startedAt);
1345
+ machineStart.set(runId, startedAt);
1346
+ spawnedRuns.add(runId);
1347
+ identityMismatch = false;
1348
+ // S-1/F1: exit evidence is per-run and runIds are fresh UUIDs, so a new
1349
+ // start must NOT reset it — doing so would sever a surviving pending
1350
+ // run's binding (dual-run stop path, S5-7).
1351
+ note = undefined;
1352
+ // F2: establish the spawn's stable identity set BEFORE spawning. The
1353
+ // direct argv is always acceptable (it is what we pass); the wrapper
1354
+ // shell/exec forms are added only when the client file provides strict
1355
+ // evidence (resolveWrapperIdentityEvidence). The exec form is also
1356
+ // persisted on the record so LATER sessions recognize the post-exec argv.
1357
+ const wrapperEvidence = resolveWrapperIdentityEvidence(clientPath);
1358
+ const spawnArgs = ["run", "--profile-file", profilePath];
1359
+ const commandIdentityExec = wrapperEvidence?.execTarget !== undefined
1360
+ ? [wrapperEvidence.execTarget, ...spawnArgs].join(" ")
1361
+ : undefined;
1362
+ pendingSpawnIdentities = [
1363
+ [clientPath, ...spawnArgs].join(" "),
1364
+ ...(wrapperEvidence?.shellPrefix !== undefined
1365
+ ? [`${wrapperEvidence.shellPrefix} ${[clientPath, ...spawnArgs].join(" ")}`]
1366
+ : []),
1367
+ ...(commandIdentityExec !== undefined ? [commandIdentityExec] : []),
1368
+ ];
1369
+ try {
1370
+ child = spawnSeam(clientPath, spawnArgs, {
1371
+ env: childEnvironment(env), detached: true, logPath,
1372
+ });
1373
+ }
1374
+ catch {
1375
+ throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
1376
+ }
1377
+ child.on("error", () => undefined);
1378
+ const pid = child.pid;
1379
+ if (pid === undefined || !Number.isSafeInteger(pid) || pid <= 0) {
1380
+ child = undefined;
1381
+ throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
1382
+ }
1383
+ child.unref();
1384
+ // S-1: arm the spawn-linked exit proof BEFORE the capture loop. The
1385
+ // dominant pending path is a child dying INSIDE the capture window — its
1386
+ // exit event fires there, once, before any pending record exists. The
1387
+ // entry is keyed by THIS run's id, so neither an early exit nor a later
1388
+ // start can lose or misattribute it.
1389
+ child.on("exit", () => {
1390
+ exitedPendingRuns.add(runId);
1391
+ });
1392
+ // Capture the process identity BEFORE persisting ownership.
1393
+ let identity;
1394
+ const appearDeadline = now() + IDENTITY_APPEAR_MS;
1395
+ while (now() <= appearDeadline) {
1396
+ const presence = await inspect(pid);
1397
+ if (presence.kind === "present") {
1398
+ identity = presence.identity;
1399
+ break;
1400
+ }
1401
+ if (presence.kind === "absent")
1402
+ break;
1403
+ await sleep(50);
1404
+ }
1405
+ // S3-2 + F2: capture accepts ONLY the exact evidence-derived spawn
1406
+ // identities (direct argv / wrapper shell prefix / wrapper exec target);
1407
+ // a merely substring-similar command is never attributed to this spawn.
1408
+ if (identity === undefined || !pendingSpawnIdentities.includes(identity.command)) {
1409
+ // Never signal a process we cannot attribute to THIS spawn — but do
1410
+ // NOT abandon it either: keep a pending, never-persisted record so
1411
+ // stop/refresh can re-acquire identity and terminate it later (R3).
1412
+ pendingRecord = {
1413
+ version: 1, runId, pid, profilePath, profileSha256,
1414
+ tunnelId: facts.tunnelId, keyFile: facts.keyFile, urlFile: facts.urlFile,
1415
+ mcpCommand: facts.mcpCommand, logPath,
1416
+ commandIdentity: "", processStartedKey: "", commandIdentityExec,
1417
+ startedAt, termRequestedAt: undefined, state: "running",
1418
+ stoppedAt: undefined, note: "spawned child identity unconfirmed",
1419
+ identityPending: true,
1420
+ };
1421
+ record = pendingRecord;
1422
+ note = "spawned child identity unconfirmed; ownership retained in memory";
1423
+ // S-1/S-2: the exit listener is already armed (above) and archives by
1424
+ // runId; keep the handle strongly (defensive — a listener does not
1425
+ // retain its emitter) until this pending run closes or dispose().
1426
+ pendingChildren.set(runId, child);
1427
+ child = undefined;
1428
+ throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
1429
+ }
1430
+ const base = {
1431
+ version: 1, runId, pid, profilePath, profileSha256,
1432
+ tunnelId: facts.tunnelId, keyFile: facts.keyFile, urlFile: facts.urlFile,
1433
+ mcpCommand: facts.mcpCommand, logPath,
1434
+ commandIdentity: identity.command, processStartedKey: identity.startedKey, commandIdentityExec,
1435
+ startedAt, termRequestedAt: undefined, state: "running",
1436
+ stoppedAt: undefined, note: undefined,
1437
+ };
1438
+ try {
1439
+ persist(base);
1440
+ onSpawned?.({ runId, pid, tunnelId: maskTunnelId(facts.tunnelId), startedAt: new Date(startedAt).toISOString() });
1441
+ }
1442
+ catch (error) {
1443
+ // S6/C4 + R3: the daemon exists but the record does not. Ownership
1444
+ // becomes PENDING: disk ENOENT must never discard it, and a later
1445
+ // stop() retries the ledger + termination through the same path.
1446
+ pendingRecord = base;
1447
+ record = base;
1448
+ note = "ownership record persistence failed; in-memory ownership retained";
1449
+ const outcome = await terminateOwned(base, timing.stopGraceMs);
1450
+ if (outcome === "stopped") {
1451
+ pendingRecord = undefined;
1452
+ record = undefined;
1453
+ note = "startup aborted; record persistence failed and the child was stopped";
1454
+ }
1455
+ throw error instanceof TunnelRefusal ? error : new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED");
1456
+ }
1457
+ }
1458
+ finally {
1459
+ release();
1460
+ }
1461
+ const current = record;
1462
+ // Wait for REAL transport readiness, never mere PID liveness. Success
1463
+ // requires the shared state machine to ACCEPT Connected (C6).
1464
+ const recordCompletion = recorderFor(current.runId, current.pid);
1465
+ const deadline = current.startedAt + timing.startupTimeoutMs;
1466
+ let accepted = false;
1467
+ for (;;) {
1468
+ const probe = recordCompletion(await probeHealth(facts.urlFile, current.pid));
1469
+ // C3 fencing: a stop here or in another session aborts this start.
1470
+ const latest = loadRecord(stateFilePath);
1471
+ const fenced = fenceAtCall !== startFence || latest.kind !== "ok" ||
1472
+ latest.record.runId !== current.runId || latest.record.state !== "running" ||
1473
+ latest.record.termRequestedAt !== undefined;
1474
+ state = nextTunnelState(state, {
1475
+ now: now(), runId: current.runId, managedPid: current.pid, processAlive: true,
1476
+ userStopped: false, startedAt: current.startedAt,
1477
+ exit: undefined, probe, startupLogSeen: false, externalInstance: false,
1478
+ }, timing);
1479
+ if (!fenced && state.name === "Connected") {
1480
+ accepted = true;
1481
+ break;
1482
+ }
1483
+ if (fenced || now() >= deadline)
1484
+ break;
1485
+ await sleep(250);
1486
+ }
1487
+ if (accepted) {
1488
+ return {
1489
+ runId: current.runId, pid: current.pid, tunnelId: maskTunnelId(facts.tunnelId),
1490
+ health: "connected", startedAt: new Date(current.startedAt).toISOString(), alreadyRunning: false,
1491
+ };
1492
+ }
1493
+ // Startup failure/timeout/superseded: unified verified cleanup (S5/C8).
1494
+ // A concurrent stop may hold the lock; its termination already applies to
1495
+ // this run, so a busy lock here is not a second failure path.
1496
+ let cleanupRelease;
1497
+ try {
1498
+ cleanupRelease = await acquireLock();
1499
+ }
1500
+ catch {
1501
+ note = "startup not confirmed; cleanup lock busy (a concurrent stop owns this run)";
1502
+ throw new TunnelRefusal("CE_TUNNEL_READY_TIMEOUT");
1503
+ }
1504
+ try {
1505
+ reloadRecord();
1506
+ if (recordCorrupt)
1507
+ throw new TunnelRefusal("CE_TUNNEL_STATE_CORRUPT");
1508
+ if (record?.runId === current.runId && record.state !== "stopped") {
1509
+ const outcome = await terminateOwned(record, timing.stopGraceMs);
1510
+ if (outcome === "stopped") {
1511
+ observeAbsence(record);
1512
+ persist(markStopped({ ...record, identityPending: undefined }, "startup not confirmed; verified stop"));
1513
+ }
1514
+ else {
1515
+ try {
1516
+ persist({ ...record, state: "stop-unconfirmed", note: `startup not confirmed; cleanup ${outcome}` });
1517
+ }
1518
+ catch { /* ownership retained in memory */ }
1519
+ note = "startup not confirmed; cleanup unconfirmed; ownership retained";
1520
+ }
1521
+ }
1522
+ }
1523
+ finally {
1524
+ cleanupRelease();
1525
+ }
1526
+ throw new TunnelRefusal("CE_TUNNEL_READY_TIMEOUT");
1527
+ };
1528
+ // Stop is deliberately NOT queued behind a pending start: it preempts via
1529
+ // startFence + the lock (C3). v3: it first AWAITS the settlement of any
1530
+ // start it invalidated — bounded by one probe timeout + identity capture +
1531
+ // stopGraceMs — so it never returns while a cancelled start still owns work.
1532
+ const stop = (stopOptions = {}) => {
1533
+ if (stopping !== undefined)
1534
+ return stopping;
1535
+ const attempt = stopOnce(stopOptions);
1536
+ stopping = attempt;
1537
+ return attempt.then(() => { stopping = undefined; }, (error) => { stopping = undefined; throw error; });
1538
+ };
1539
+ const stopOnce = async (stopOptions) => {
1540
+ startFence += 1; // invalidate any pending start in THIS manager (C3)
1541
+ // R5/C-v2-2: an invalidated start must SETTLE (cleanup included) before we
1542
+ // proceed, so stop never returns while a start it cancelled still owns work.
1543
+ const inflight = activeStart;
1544
+ if (inflight !== undefined)
1545
+ await inflight.catch(() => undefined);
1546
+ const graceMs = stopOptions.graceMs ?? timing.stopGraceMs;
1547
+ // Fast path without taking the lock or touching the filesystem: nothing
1548
+ // owned on disk AND no pending in-memory ownership means nothing to stop.
1549
+ {
1550
+ const pre = loadRecord(stateFilePath);
1551
+ if (pre.kind === "corrupt") {
1552
+ recordCorrupt = true;
1553
+ throw new TunnelRefusal("CE_TUNNEL_STATE_CORRUPT");
1554
+ }
1555
+ if (pre.kind === "none" || pre.record.state === "stopped") {
1556
+ if (pendingRecord === undefined) {
1557
+ record = pre.kind === "ok" ? pre.record : undefined;
1558
+ return;
1559
+ }
1560
+ record = pendingRecord; // R3: pending ownership must still be stoppable
1561
+ }
1562
+ }
1563
+ const release = await acquireLock();
1564
+ try {
1565
+ reloadRecord();
1566
+ if (recordCorrupt)
1567
+ throw new TunnelRefusal("CE_TUNNEL_STATE_CORRUPT");
1568
+ const current = record;
1569
+ // S5-7: an unpersisted pending daemon that is NOT the disk record's run
1570
+ // still belongs to this session — terminate it alongside (the in-memory
1571
+ // once-set keeps this at-most-once). Exit proof clears the pending view.
1572
+ let pendingUnresolved = false;
1573
+ if (pendingRecord !== undefined && pendingRecord.runId !== current?.runId) {
1574
+ const pOutcome = await terminateOwned(pendingRecord, graceMs);
1575
+ if (pOutcome === "stopped") {
1576
+ try {
1577
+ persist(markStopped({ ...pendingRecord, identityPending: undefined }, "pending run exit confirmed"));
1578
+ }
1579
+ catch { /* exit is proven; the record is informational only */ }
1580
+ exitedPendingRuns.delete(pendingRecord.runId);
1581
+ pendingChildren.delete(pendingRecord.runId);
1582
+ pendingRecord = undefined;
1583
+ if (record?.runId !== current?.runId)
1584
+ record = current;
1585
+ }
1586
+ else {
1587
+ pendingUnresolved = true;
1588
+ note = "pending run stop unconfirmed; ownership retained";
1589
+ }
1590
+ }
1591
+ if (current === undefined || current.state === "stopped") {
1592
+ if (pendingUnresolved)
1593
+ throw new TunnelRefusal("CE_TUNNEL_STOP_UNCONFIRMED");
1594
+ return;
1595
+ }
1596
+ const outcome = await terminateOwned(current, graceMs);
1597
+ if (outcome === "stopped") {
1598
+ // Verify the profile-declared MCP child is gone too; the child belongs
1599
+ // to the client, so we NEVER signal it — only report. The note must be
1600
+ // honest about whether THIS run was ever signalled (S-1 child-link and
1601
+ // ps-absence exits deliver no signal): the ledger or the once-set tells.
1602
+ const signalled = current.termRequestedAt !== undefined || termIntentSent.has(current.runId);
1603
+ let stopNote = signalled
1604
+ ? "exit observed after SIGTERM"
1605
+ : "exit observed (process already gone); no signal sent";
1606
+ if (current.mcpCommand !== undefined) {
1607
+ const listed = await listProcesses();
1608
+ if (listed.kind === "ok" && listed.processes.some((proc) => proc.command === current.mcpCommand)) {
1609
+ stopNote = `${signalled ? "exit observed after SIGTERM" : "exit observed (process already gone); no signal sent"}; MCP child still running (not signalled by this manager)`;
1610
+ note = stopNote;
1611
+ }
1612
+ }
1613
+ observeAbsence(record);
1614
+ persist(markStopped({ ...record, identityPending: undefined }, stopNote));
1615
+ if (pendingUnresolved || pendingRecord !== undefined) {
1616
+ note = "stopped the recorded run; ANOTHER unpersisted pending run is still alive — run stop again";
1617
+ }
1618
+ if (pendingUnresolved)
1619
+ throw new TunnelRefusal("CE_TUNNEL_STOP_UNCONFIRMED");
1620
+ return;
1621
+ }
1622
+ try {
1623
+ persist({ ...record, state: "stop-unconfirmed", note: `stop ${outcome}; ownership retained` });
1624
+ }
1625
+ catch { /* ownership retained in memory; the refusal below still applies */ }
1626
+ note = "stop unconfirmed; ownership retained";
1627
+ throw new TunnelRefusal("CE_TUNNEL_STOP_UNCONFIRMED");
1628
+ }
1629
+ finally {
1630
+ release();
1631
+ }
1632
+ };
1633
+ const status = () => {
1634
+ const current = record;
1635
+ // Pure projection: this observation is never committed, but lets a stale
1636
+ // Connected lapse to Unknown exactly like the offline manager's reads.
1637
+ const view = current === undefined || current.state === "stopped" || identityMismatch
1638
+ ? state
1639
+ : nextTunnelState(state, {
1640
+ now: now(), runId: current.runId, managedPid: current.pid, processAlive: true,
1641
+ userStopped: current.termRequestedAt !== undefined, startedAt: machineStartedAt(current),
1642
+ exit: undefined, probe: undefined, startupLogSeen: false, externalInstance: false,
1643
+ }, timingFor(current.runId));
1644
+ const mapped = recordCorrupt || identityMismatch
1645
+ ? "UNKNOWN"
1646
+ : mapStateName(current === undefined || current.state === "stopped" ? "Stopped" : view.name);
1647
+ const evidence = current === undefined
1648
+ ? "none"
1649
+ : current.state === "stopped"
1650
+ ? "process-absent"
1651
+ : !identityMismatch && view.lastHealthyAt !== undefined && now() - view.lastHealthyAt <= timing.freshnessMs
1652
+ ? "health-probe"
1653
+ : "none";
1654
+ return Object.freeze({
1655
+ mode: "real-background",
1656
+ state: mapped,
1657
+ label: `Tunnel ${mapped} (real background)`,
1658
+ evidence,
1659
+ running: current !== undefined && current.state !== "stopped" && !identityMismatch && !recordCorrupt && mapped !== "STOPPED",
1660
+ runId: current?.runId,
1661
+ pid: current !== undefined && current.state !== "stopped" ? current.pid : undefined,
1662
+ startedAt: current !== undefined && current.state !== "stopped" ? new Date(current.startedAt).toISOString() : undefined,
1663
+ tunnelId: current !== undefined ? maskTunnelId(current.tunnelId) : undefined,
1664
+ note: note ?? (current?.note),
1665
+ });
1666
+ };
1667
+ return {
1668
+ kind: "real-background",
1669
+ start,
1670
+ startDeferred,
1671
+ withProfileConfigurationLock: (operation) => enqueue(async () => {
1672
+ if (disposed)
1673
+ throw new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
1674
+ const release = await acquireLock();
1675
+ try {
1676
+ reloadRecord();
1677
+ if (recordCorrupt)
1678
+ throw new TunnelRefusal("CE_TUNNEL_STATE_CORRUPT");
1679
+ // Do not turn a setup action into recovery, a stop or an adoption.
1680
+ // Even a stale running ledger requires explicit lifecycle resolution.
1681
+ if (record !== undefined && record.state !== "stopped")
1682
+ throw new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
1683
+ const listed = await listProcesses();
1684
+ if (listed.kind !== "ok")
1685
+ throw new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
1686
+ if (listed.processes.some((proc) => proc.command.includes(`--profile-file ${profilePath}`))) {
1687
+ throw new TunnelRefusal("CE_TUNNEL_EXTERNAL_INSTANCE");
1688
+ }
1689
+ assertLockIntact();
1690
+ const token = heldLockToken;
1691
+ return operation({ profilePath, assertIntact: () => {
1692
+ if (token === undefined || heldLockToken !== token)
1693
+ throw new TunnelRefusal("CE_TUNNEL_MANAGER_BUSY");
1694
+ assertLockIntact();
1695
+ } });
1696
+ }
1697
+ finally {
1698
+ release();
1699
+ }
1700
+ }),
1701
+ stop,
1702
+ refresh,
1703
+ status,
1704
+ runId: () => (record !== undefined && record.state !== "stopped" ? record.runId : undefined),
1705
+ async dispose() {
1706
+ // The daemon is deliberately NOT stopped: it is owned by the record and
1707
+ // survives this Pi session. Session-locals are released only.
1708
+ // C-v5-1: settle an in-flight start first — its pending record and exit
1709
+ // proof must be materialized before we decide whether to release the
1710
+ // archives, so a start racing with dispose cannot lose its exit proof.
1711
+ const inflight = activeStart;
1712
+ if (inflight !== undefined)
1713
+ await inflight.catch(() => undefined);
1714
+ // S-1/F1 (S4-1): dispose must NOT sever a surviving pending run's exit
1715
+ // proof — stop/refresh remain callable after dispose and must still be
1716
+ // able to distinguish our dead child from a pid reuser. Only release the
1717
+ // archives when no pending ownership survives; otherwise the handle is
1718
+ // kept strongly so its exit event can still be archived.
1719
+ if (pendingRecord === undefined) {
1720
+ exitedPendingRuns.clear();
1721
+ pendingChildren.clear();
1722
+ }
1723
+ disposed = true;
1724
+ },
1725
+ };
1726
+ }
1727
+ //# sourceMappingURL=background-manager.js.map