@miadi/tide 0.2.3 → 0.4.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Miadi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -79,6 +79,66 @@ reads herdr scrollback through the stable peek verb. Pane-id segments are alphan
79
79
  > wait output (hit + timeout exit codes), agent-status, and label→id resolution — in
80
80
  > addition to the injected-runner tests in `test/herdr.test.ts`.
81
81
 
82
+ #### Observer inventory + capability advertisement (EP152, live-verified)
83
+
84
+ ```ts
85
+ import { getHerdrSnapshot, describeHerdrCapabilities } from "@miadi/tide"
86
+
87
+ const snap = await getHerdrSnapshot()
88
+ // `herdr api snapshot` — the whole observer inventory in ONE socket round-trip
89
+ // (socket method session.snapshot): workspaces, tabs, panes, detected agents,
90
+ // the focus triple, and the server's version/protocol. Read-only, consistent
91
+ // (no tearing across a workspace/tab/pane list stitch).
92
+
93
+ const caps = await describeHerdrCapabilities()
94
+ // `herdr api schema --json` — capability advertisement DERIVED from the live
95
+ // schema document: { available, protocol, schema_version, methods[] } plus
96
+ // deterministic boolean views (inventory, snapshot, labels, agents,
97
+ // wait_output, wait_events, lifecycle_advertised). `lifecycle_authorized` is
98
+ // constant false: the server ADVERTISING workspace.close does not authorize
99
+ // this client to drive it — that flips only when the closure-receipts ladder
100
+ // lands as code. Never throws: a failed probe returns { available: false,
101
+ // reason } — safe for /api/tide/health.
102
+ ```
103
+
104
+ Live receipts (herdr 0.7.4, protocol 16, EP152 2026-07-18): 85 advertised socket
105
+ methods, all seven derived flags true, snapshot of 7 workspaces / 22 tabs / 44
106
+ panes / 21 agents. That smoke also showed pane ids go **alphanumeric** past `p9`
107
+ (`w2:pE`, `w7:pA`) — herdr's own schema types `pane_id` as a plain string — so the
108
+ client id pattern accepts the family agreed with `@miadi/tide-contract` 0.2.3:
109
+ `w[0-9A-Za-z]+:p[0-9A-Za-z]+` (the dashed legacy form stays digits-only).
110
+
111
+ #### Steer gate — ACTIVE_CONTROLLER + TTY + live target (EP152 wave-2)
112
+
113
+ Every steer **execution** (`sendKeys` tmux + herdr, `sendKeysViaHerdr`,
114
+ `runInHerdrPane`) passes the 3-part gate ported from the Python runtime's
115
+ `tide operator send --run` boundary (`src/steer-gate.ts`):
116
+
117
+ 1. **live-resolved target** — the pane must appear in the CURRENT multiplexer
118
+ inventory (`tmux list-panes -a` / `herdr pane list`; label resolution counts
119
+ as live proof);
120
+ 2. **ACTIVE_CONTROLLER posture** — `mode: controller` in
121
+ `${MIADI_HOME|~/.miadi/navigator}/config.yml`, with the controller TTL lease
122
+ applied on every read (an expired lease reads as observer, fail-closed);
123
+ 3. **interactive local TTY** — or `TIDE_ALLOW_NON_INTERACTIVE_RUN=1` set by an
124
+ approval-queue-fronted service after its own review.
125
+
126
+ A refused steer throws `TideError` naming **every** failed check and never
127
+ touches the multiplexer. Plan builders (`buildSendKeysPlan`,
128
+ `buildHerdrSendKeysPlan`) stay ungated — dry-run is the covenant's default
129
+ posture. `evaluateSteerGate`/`requireSteerGate`/`readNavigatorPosture` are
130
+ exported for `/api/tide/health`-style surfaces. The `gate` option injects
131
+ probes (tests, first-party wiring); it cannot disable the gate, and overrides
132
+ are only accepted when branded by `trustSteerGateProbes()` — which is NOT on
133
+ the package surface (direct module import only; the brand is a module-private
134
+ non-enumerable Symbol, so JSON/request-derived gate options are structurally
135
+ refused).
136
+
137
+ Label hardening (same wave): resolution is NFC-normalized, label-only (the
138
+ `title` fallback is gone), **duplicate labels are a hard refusal**, and
139
+ `{ workspace: "w7" }` scopes resolution. Wrong-multiplexer dispatch fails
140
+ loudly in both directions (a herdr-shaped id on the tmux path and vice versa).
141
+
82
142
  `getTerminals` and `detect` are the read-only surface behind `GET /api/tide/terminals`
83
143
  and `GET /api/tide/detect` — the typed half of operator-terminal triage and manual
84
144
  domain assignment (jgwill/Miadi#382). The write-back half (assign a pane to a domain)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/tide",
3
- "version": "0.2.3",
3
+ "version": "0.4.0",
4
4
  "description": "Typed client boundary for the ironsilk `tide` runtime. Daemon Unix-socket transport with CLI fallback.",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -15,15 +15,15 @@
15
15
  "src"
16
16
  ],
17
17
  "dependencies": {
18
- "@miadi/tide-contract": "0.2.3"
19
- },
20
- "scripts": {
21
- "test": "d=$(mktemp -d \"${TMPDIR:-/tmp}/miadi-tide-test.XXXXXX\") && trap 'rm -rf \"$d\"' EXIT && ../../node_modules/.bin/tsc -p tsconfig.test.json --outDir \"$d\" && node --test \"$d\"/packages/tide/test/*.test.js"
18
+ "@miadi/tide-contract": "0.3.0"
22
19
  },
23
20
  "keywords": [
24
21
  "miadi",
25
22
  "tide",
26
23
  "ironsilk",
27
24
  "operator-cockpit"
28
- ]
29
- }
25
+ ],
26
+ "scripts": {
27
+ "test": "d=$(mktemp -d \"${TMPDIR:-/tmp}/miadi-tide-test.XXXXXX\") && trap 'rm -rf \"$d\"' EXIT && ../../node_modules/.bin/tsc -p tsconfig.test.json --outDir \"$d\" && node --test \"$d\"/packages/tide/test/*.test.js"
28
+ }
29
+ }
package/src/client.ts CHANGED
@@ -49,6 +49,8 @@ import {
49
49
  sendKeysViaHerdr,
50
50
  } from "./herdr"
51
51
  import type { HerdrCommandRunner } from "./herdr"
52
+ import { requireSteerGate, acceptGateOverrides } from "./steer-gate"
53
+ import type { SteerGateOverrides } from "./steer-gate"
52
54
 
53
55
  const pExecFile = promisify(execFile)
54
56
 
@@ -215,6 +217,9 @@ export interface PeekOptions extends TideRunOptions {
215
217
  multiplexer?: Multiplexer
216
218
  /** herdr only: durable pane label, re-resolved to the current pane id at action time. */
217
219
  paneLabel?: string
220
+ /** herdr only: the session the pane lives in. Reads are session-scoped for the
221
+ * same reason writes are — see SendKeysOptions.session. */
222
+ session?: string
218
223
  /** herdr only: injected command runner (tests). */
219
224
  runner?: HerdrCommandRunner
220
225
  }
@@ -302,8 +307,39 @@ export interface SendKeysOptions extends TideRunOptions {
302
307
  * action time (herdr ids are session-scoped and reset on herdr restart).
303
308
  */
304
309
  paneLabel?: string
310
+ /**
311
+ * herdr only: the session the pane lives in (`herdr --session <name> …`).
312
+ * herdr pane ids are session-scoped and the CLI reaches `default` without
313
+ * this, so omitting it for a pane in another session addresses whatever wears
314
+ * that id in `default` — or nothing, which is how a live pane reported itself
315
+ * gone on 2026-08-05. tmux pane ids (`%127`) are server-global and need no
316
+ * session, which is why the tmux path refuses this option rather than
317
+ * ignoring it.
318
+ */
319
+ session?: string
305
320
  /** herdr only: injected command runner (tests). */
306
321
  runner?: HerdrCommandRunner
322
+ /**
323
+ * Steer-gate probe overrides (test seam / cockpit injection). The gate
324
+ * itself cannot be disabled — these only answer its three questions
325
+ * (live target, ACTIVE_CONTROLLER posture, interactive TTY). See
326
+ * steer-gate.ts (EP152 wave-2 W1).
327
+ */
328
+ gate?: SteerGateOverrides
329
+ }
330
+
331
+ /**
332
+ * Steer-gate liveness probe for the tmux path: the `%N` target must appear in
333
+ * the CURRENT `tmux list-panes -a` inventory (the direct-transport analog of
334
+ * the Python gate's `resolution_status == "resolved"`). Read-only.
335
+ */
336
+ async function tmuxTargetResolved(
337
+ target: string,
338
+ bin: string,
339
+ runOpts: { timeout: number; cwd?: string },
340
+ ): Promise<boolean> {
341
+ const { stdout } = await pExecFile(bin, ["list-panes", "-a", "-F", "#{pane_id}"], runOpts)
342
+ return stdout.split("\n").some((line) => line.trim() === target)
307
343
  }
308
344
 
309
345
  /**
@@ -336,6 +372,11 @@ export function buildSendKeysPlan(
336
372
  * separate `C-m` submits it. If the literal step succeeds but the submit step
337
373
  * fails, the text is already on the pane's prompt (unsubmitted) — the thrown
338
374
  * `TideError` names which step failed so the caller can surface that partial state.
375
+ *
376
+ * Execution is steer-gated (EP152 wave-2 W1, both multiplexers): live-resolved
377
+ * target + ACTIVE_CONTROLLER posture + interactive TTY (or approval-fronted
378
+ * `TIDE_ALLOW_NON_INTERACTIVE_RUN=1`) — the same 3-part boundary as
379
+ * `tide operator send --run`. `buildSendKeysPlan` stays ungated (dry-run).
339
380
  */
340
381
  export async function sendKeys(
341
382
  pane: string,
@@ -349,15 +390,31 @@ export async function sendKeys(
349
390
  }
350
391
  // herdr-only options on the tmux path would silently steer the raw tmux
351
392
  // pane — the wrong-pane hazard labels exist to prevent. Fail loudly instead.
352
- if (opts.paneLabel !== undefined || opts.runner !== undefined) {
393
+ if (opts.paneLabel !== undefined || opts.runner !== undefined || opts.session !== undefined) {
353
394
  throw new TideError(
354
- `sendKeys: "paneLabel"/"runner" are herdr-only options — pass multiplexer: "herdr"`,
395
+ `sendKeys: "paneLabel"/"runner"/"session" are herdr-only options — pass multiplexer: "herdr". ` +
396
+ `tmux pane ids (%127) are server-global, so a tmux target needs no session; accepting one ` +
397
+ `here would mean honouring it nowhere.`,
398
+ )
399
+ }
400
+ // Wrong-multiplexer dispatch assertion (EP152 wave-2 W2): a herdr-shaped id
401
+ // on the tmux path would be blindly %-prefixed into a bogus tmux target
402
+ // ("%w1:p2") — or worse, parse as tmux session:window syntax. Fail loudly.
403
+ if (HERDR_PANE_ID_PATTERN.test(pane.trim())) {
404
+ throw new TideError(
405
+ `"${pane.trim()}" is a herdr pane id but the tmux path was selected — pass multiplexer:"herdr" to steer herdr panes`,
355
406
  )
356
407
  }
357
408
  const submit = opts.submit ?? true
358
409
  const plan = buildSendKeysPlan(pane, message, submit)
359
410
  const bin = resolveTmuxBin()
360
411
  const runOpts = { timeout: opts.timeoutMs ?? 10_000, cwd: opts.cwd }
412
+ const gate = acceptGateOverrides(opts.gate)
413
+ await requireSteerGate({
414
+ ...gate,
415
+ target: plan.target,
416
+ resolveTarget: gate.resolveTarget ?? (() => tmuxTargetResolved(plan.target, bin, runOpts)),
417
+ })
361
418
  try {
362
419
  await pExecFile(bin, plan.literal_command, runOpts)
363
420
  } catch (err) {
@@ -365,6 +422,11 @@ export async function sendKeys(
365
422
  throw new TideError(`tmux send-keys to ${plan.target} failed (typing literal text): ${msg}`, err)
366
423
  }
367
424
  if (plan.submit_command) {
425
+ // A TUI (claude, ptpython) brackets a fast literal burst as a paste, and the
426
+ // first Enter only closes the paste — the message stays staged on the prompt.
427
+ // Let the pane settle, submit, then submit once more: the repeat is a no-op
428
+ // for a shell and the difference between staged and sent for a TUI.
429
+ await new Promise((resolve) => setTimeout(resolve, 200))
368
430
  try {
369
431
  await pExecFile(bin, plan.submit_command, runOpts)
370
432
  } catch (err) {
@@ -374,6 +436,13 @@ export async function sendKeys(
374
436
  err,
375
437
  )
376
438
  }
439
+ await new Promise((resolve) => setTimeout(resolve, 150))
440
+ try {
441
+ await pExecFile(bin, plan.submit_command, runOpts)
442
+ } catch {
443
+ // Best-effort repeat: the first Enter landed, so a failure here must not
444
+ // report as an unsubmitted message.
445
+ }
377
446
  }
378
447
  return { ...plan, sent_at: new Date().toISOString() }
379
448
  }
package/src/herdr.ts CHANGED
@@ -13,6 +13,8 @@
13
13
  // wait output <id> --match … [--regex] --timeout ms (JSON)
14
14
  // wait agent-status <id> --status … --timeout ms (JSON)
15
15
  // workspace list | tab list --workspace <id> | pane list (JSON)
16
+ // api snapshot one-call observer inventory (JSON)
17
+ // api schema --json capability advertisement source (JSON)
16
18
  //
17
19
  // herdr pane ids are "w<N>:p<M>" (e.g. "w1:p2") as of herdr 0.7; the legacy
18
20
  // dashed "1-2" form is still accepted for older releases. Live smoke against
@@ -41,6 +43,8 @@ import type {
41
43
  TideHerdrWorkspaceInfo,
42
44
  } from "@miadi/tide-contract"
43
45
  import { TideError } from "./errors"
46
+ import { requireSteerGate, acceptGateOverrides } from "./steer-gate"
47
+ import type { SteerGateOverrides } from "./steer-gate"
44
48
  import type { TideRunOptions } from "./client"
45
49
 
46
50
  const pExecFile = promisify(execFile)
@@ -59,6 +63,28 @@ export type HerdrCommandRunner = (
59
63
  export interface HerdrRunOptions extends TideRunOptions {
60
64
  /** Injected command runner; defaults to `execFile` against the herdr binary. */
61
65
  runner?: HerdrCommandRunner
66
+ /**
67
+ * The herdr session to address, as `herdr --session <name> …`.
68
+ *
69
+ * WHY THIS EXISTS. Every verb in this module invoked `herdr` bare, which
70
+ * reaches the `default` session and only that one. Pane ids are session-scoped
71
+ * (see the header note), so a caller holding `w1T:p1` from a session named
72
+ * `stcbot` was asking `default` about an id that means something else there —
73
+ * or nothing at all. On 2026-08-05 a voice card published from a non-default
74
+ * session refused its own reply with "that pane is gone": the address was
75
+ * right, the session was dropped between the card and the CLI.
76
+ *
77
+ * Omitted keeps the historical behaviour byte-for-byte (`default`).
78
+ */
79
+ session?: string
80
+ }
81
+
82
+ /** Prefix `--session <name>` when the caller named one. Applied in exactly two
83
+ * places — `runHerdr` for the read verbs, and the send-keys plan for the write
84
+ * ones — so a previewed argv and an executed argv cannot disagree. */
85
+ function withSession(args: readonly string[], session?: string): string[] {
86
+ const named = typeof session === "string" ? session.trim() : ""
87
+ return named ? ["--session", named, ...args] : [...args]
62
88
  }
63
89
 
64
90
  /** Resolve the herdr binary: `TIDE_HERDR_BIN` env → `herdr` (on PATH). */
@@ -108,10 +134,13 @@ function describeRunnerError(err: unknown): string {
108
134
  async function runHerdr(args: string[], opts: HerdrRunOptions): Promise<HerdrCommandResult> {
109
135
  const runner = makeRunner(opts)
110
136
  try {
111
- return await runner(resolveHerdrBin(), args)
137
+ return await runner(resolveHerdrBin(), withSession(args, opts.session))
112
138
  } catch (err) {
139
+ // The verb is read off the ORIGINAL args, not the session-prefixed ones —
140
+ // otherwise every failure would report itself as "herdr --session <name>".
113
141
  const verb = args.length >= 2 ? `${args[0]} ${args[1]}` : "operation"
114
- throw new TideError(`herdr ${verb} failed: ${describeRunnerError(err)}`, err)
142
+ const where = opts.session ? ` in session "${opts.session}"` : ""
143
+ throw new TideError(`herdr ${verb}${where} failed: ${describeRunnerError(err)}`, err)
115
144
  }
116
145
  }
117
146
 
@@ -126,17 +155,24 @@ function parseHerdrJson<T>(stdout: string, what: string): T {
126
155
  // ── Pane targets and label→id resolution ────────────────────────────────────
127
156
 
128
157
  // "w1:p2" is the live herdr 0.7 format; the dashed "1-2" form is legacy.
129
- // Segments are ALPHANUMERIC, not just digits — live 0.7.4 allocates pane
130
- // suffixes past p9 as letters (w2:pE, w2:pJ observed in the EP137 follow-up
131
- // inventory), so a digits-only pattern strands every pane beyond the ninth.
158
+ // BOTH segments are ALPHANUMERIC, not digits-only: live herdr 0.7.4 (EP152,
159
+ // 2026-07-18) lists ids like "w2:pE" and "w2:pQ" once a workspace has grown
160
+ // past p9, and herdr's own API schema (`herdr api schema --json`, protocol 16)
161
+ // types pane_id as a plain string with no pattern. This is the ONE pattern
162
+ // family agreed with the tide-contract lineage (npm 0.2.3, EP152 wave-2
163
+ // reconciliation): w[0-9A-Za-z]+:p[0-9A-Za-z]+. The legacy dashed form stays
164
+ // digits-only as observed on older releases.
132
165
  export const HERDR_PANE_ID_PATTERN = /^(w[0-9A-Za-z]+:p[0-9A-Za-z]+|[0-9]+-[0-9]+)$/
133
166
 
134
167
  /** Validate a herdr pane id (e.g. "w1:p2"). Unlike tmux there is no `%` prefix to add. */
135
168
  export function normalizeHerdrPaneTarget(pane: string): string {
136
169
  const trimmed = pane.trim()
137
170
  if (!HERDR_PANE_ID_PATTERN.test(trimmed)) {
171
+ const tmuxHint = /^%?[0-9]+$/.test(trimmed)
172
+ ? `; "${trimmed}" looks like a tmux pane id — pass multiplexer:"tmux" (or omit multiplexer) for tmux panes`
173
+ : ""
138
174
  throw new TideError(
139
- `invalid herdr pane id "${pane}" (expected "w<workspace>:p<pane>", e.g. "w1:p2"); herdr ids are session-scoped — pass paneLabel to resolve by label instead`,
175
+ `invalid herdr pane id "${pane}" (expected "w<workspace>:p<pane>", e.g. "w1:p2"); herdr ids are session-scoped — pass paneLabel to resolve by label instead${tmuxHint}`,
140
176
  )
141
177
  }
142
178
  return trimmed
@@ -145,7 +181,8 @@ export function normalizeHerdrPaneTarget(pane: string): string {
145
181
  /**
146
182
  * One row from `herdr pane list` — the covenant shape (tide-contract 0.2.2's
147
183
  * `TideHerdrPaneInfo`) plus a `title` field tolerated for other herdr builds
148
- * (live 0.7.4 rows never carry it; resolution matches it only as a fallback).
184
+ * (live 0.7.4 rows never carry it; label→id resolution is label-ONLY — the
185
+ * title fallback was removed by the EP152 wave-2 W2 hardening).
149
186
  */
150
187
  export interface HerdrPaneInfo extends TideHerdrPaneInfo {
151
188
  title?: string
@@ -222,34 +259,227 @@ export async function getHerdrInventory(opts: HerdrInventoryOptions = {}): Promi
222
259
  return inventory
223
260
  }
224
261
 
262
+ // ── Daemon-facing observer inventory + capability advertisement (EP152) ─────
263
+
264
+ /**
265
+ * The `result.snapshot` payload of `herdr api snapshot` — the whole observer
266
+ * inventory in ONE round-trip over the herdr unix socket (socket method
267
+ * `session.snapshot`): every workspace, tab, pane, and detected agent, plus
268
+ * the focus triple and the server's version/protocol. Loosely typed like
269
+ * HerdrPaneInfo: the named fields are the ones observed live on herdr 0.7.4
270
+ * (EP152, 2026-07-18); unknown fields pass through.
271
+ */
272
+ export interface HerdrSnapshot {
273
+ version?: string
274
+ protocol?: number
275
+ focused_workspace_id?: string | null
276
+ focused_tab_id?: string | null
277
+ focused_pane_id?: string | null
278
+ workspaces?: HerdrWorkspaceInfo[]
279
+ tabs?: HerdrTabInfo[]
280
+ panes?: HerdrPaneInfo[]
281
+ /** Panes with a detected agent — same row shape as `panes`, minus `scroll`. */
282
+ agents?: HerdrPaneInfo[]
283
+ layouts?: unknown[]
284
+ [key: string]: unknown
285
+ }
286
+
287
+ /**
288
+ * `herdr api snapshot` — the smallest daemon-facing observer inventory:
289
+ * read-only, one CLI call, one socket round-trip underneath. Prefer this over
290
+ * stitching `workspace list` + `tab list` + `pane list` when a whole-instance
291
+ * view is needed (the three-call stitch can tear across concurrent changes;
292
+ * the snapshot is one consistent read).
293
+ */
294
+ export async function getHerdrSnapshot(opts: HerdrRunOptions = {}): Promise<HerdrSnapshot> {
295
+ const { stdout } = await runHerdr(["api", "snapshot"], opts)
296
+ const payload = parseHerdrJson<unknown>(stdout, "api snapshot")
297
+ const env = payload as { result?: { snapshot?: unknown }; snapshot?: unknown } | null
298
+ const snap = env?.result?.snapshot ?? env?.snapshot
299
+ if (!snap || typeof snap !== "object" || Array.isArray(snap)) {
300
+ throw new TideError("herdr api snapshot returned an unexpected JSON shape")
301
+ }
302
+ return snap as HerdrSnapshot
303
+ }
304
+
305
+ /**
306
+ * Capability advertisement for the herdr backend, DERIVED live from
307
+ * `herdr api schema --json` (a bare JSON-schema document: protocol,
308
+ * schema_version, and `schemas.request.oneOf[*].properties.method.const` —
309
+ * 85 socket methods on herdr 0.7.4 / protocol 16). Nothing here is
310
+ * hard-coded per herdr version: a herdr that gains or loses a method
311
+ * advertises differently. The boolean views are deterministic reads over
312
+ * `methods` in the MISSION vocabulary (inventory / snapshot / labels /
313
+ * agents / wait / lifecycle).
314
+ */
315
+ export interface HerdrCapabilities {
316
+ multiplexer: "herdr"
317
+ /** False when the schema probe failed (binary missing, server down, bad JSON). */
318
+ available: boolean
319
+ /** Binary the probe used (TIDE_HERDR_BIN → "herdr" on PATH). */
320
+ binary: string
321
+ /** Socket protocol number from the schema document (16 on herdr 0.7.4). */
322
+ protocol: number | null
323
+ schema_version: number | null
324
+ /** Sorted socket method ids, e.g. "pane.list", "session.snapshot". */
325
+ methods: string[]
326
+ /** Why the probe failed, when `available` is false. */
327
+ reason?: string
328
+ /** workspace.list + tab.list + pane.list */
329
+ inventory: boolean
330
+ /** session.snapshot (the one-call observer inventory above) */
331
+ snapshot: boolean
332
+ /** pane.rename — durable labels for session-scoped pane ids */
333
+ labels: boolean
334
+ /** agent.list — detected-agent inventory with agent_status */
335
+ agents: boolean
336
+ /** pane.wait_for_output */
337
+ wait_output: boolean
338
+ /** events.wait — event subscription (agent-status waits ride on it) */
339
+ wait_events: boolean
340
+ /**
341
+ * workspace.create + tab.create + pane.split + pane.close are ADVERTISED by
342
+ * the server schema. Advertised is not authorized (W10b): the server
343
+ * answering a method exists says nothing about whether this client may
344
+ * drive it.
345
+ */
346
+ lifecycle_advertised: boolean
347
+ /**
348
+ * Whether THIS CLIENT is authorized to drive lifecycle mutation
349
+ * (create/split/close). Constant `false`: the EP152 safety ladder
350
+ * (G0 observe → … → G4 close) and William's per-unit gate exist as mission
351
+ * law, not yet as code — no lifecycle verb ships in @miadi/tide until the
352
+ * closure-receipts contract does. Flips only with that implementation.
353
+ */
354
+ lifecycle_authorized: false
355
+ }
356
+
357
+ function extractSchemaMethods(doc: unknown): {
358
+ protocol: number | null
359
+ schema_version: number | null
360
+ methods: string[]
361
+ } {
362
+ const d = doc as {
363
+ protocol?: unknown
364
+ schema_version?: unknown
365
+ schemas?: { request?: { oneOf?: unknown } }
366
+ } | null
367
+ const variants = d?.schemas?.request?.oneOf
368
+ if (!Array.isArray(variants)) {
369
+ throw new TideError("herdr api schema returned an unexpected JSON shape (no schemas.request.oneOf)")
370
+ }
371
+ const methods = new Set<string>()
372
+ for (const v of variants) {
373
+ const m = (v as { properties?: { method?: { const?: unknown } } } | null)?.properties?.method?.const
374
+ if (typeof m === "string") methods.add(m)
375
+ }
376
+ return {
377
+ protocol: typeof d?.protocol === "number" ? d.protocol : null,
378
+ schema_version: typeof d?.schema_version === "number" ? d.schema_version : null,
379
+ methods: [...methods].sort(),
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Probe the live herdr for its advertised capabilities. NEVER throws — a
385
+ * failed probe returns `available: false` with a `reason`, so cockpit health
386
+ * endpoints can call this unconditionally next to describeTransport().
387
+ */
388
+ export async function describeHerdrCapabilities(opts: HerdrRunOptions = {}): Promise<HerdrCapabilities> {
389
+ const binary = resolveHerdrBin()
390
+ const unavailable = (reason: string): HerdrCapabilities => ({
391
+ multiplexer: "herdr",
392
+ available: false,
393
+ binary,
394
+ protocol: null,
395
+ schema_version: null,
396
+ methods: [],
397
+ reason,
398
+ inventory: false,
399
+ snapshot: false,
400
+ labels: false,
401
+ agents: false,
402
+ wait_output: false,
403
+ wait_events: false,
404
+ lifecycle_advertised: false,
405
+ lifecycle_authorized: false,
406
+ })
407
+ try {
408
+ const { stdout } = await runHerdr(["api", "schema", "--json"], opts)
409
+ const { protocol, schema_version, methods } = extractSchemaMethods(
410
+ parseHerdrJson<unknown>(stdout, "api schema"),
411
+ )
412
+ const has = (m: string) => methods.includes(m)
413
+ return {
414
+ multiplexer: "herdr",
415
+ available: true,
416
+ binary,
417
+ protocol,
418
+ schema_version,
419
+ methods,
420
+ inventory: has("workspace.list") && has("tab.list") && has("pane.list"),
421
+ snapshot: has("session.snapshot"),
422
+ labels: has("pane.rename"),
423
+ agents: has("agent.list"),
424
+ wait_output: has("pane.wait_for_output"),
425
+ wait_events: has("events.wait"),
426
+ lifecycle_advertised:
427
+ has("workspace.create") && has("tab.create") && has("pane.split") && has("pane.close"),
428
+ lifecycle_authorized: false,
429
+ }
430
+ } catch (err) {
431
+ return unavailable(err instanceof Error ? err.message : String(err))
432
+ }
433
+ }
434
+
435
+ export interface HerdrResolveOptions extends HerdrRunOptions {
436
+ /**
437
+ * Scope label resolution to one workspace (`workspace_id`, e.g. "w7").
438
+ * Labels are only unique per operator discipline, not by herdr — scoping
439
+ * shrinks the collision surface (EP152 wave-2 W2 hardening).
440
+ */
441
+ workspace?: string
442
+ }
443
+
444
+ /** Labels compare NFC-normalized: "é" typed composed and decomposed must be the same pane. */
445
+ const nfc = (s: string) => s.normalize("NFC")
446
+
225
447
  /**
226
448
  * Resolve a durable pane label to the CURRENT herdr pane id via `pane list`.
227
449
  * Runs before every action when a label is given — herdr ids are
228
450
  * session-scoped (a herdr restart resets them), so a cached id can go stale.
229
451
  * Live 0.7.4: a stale id fails loudly with pane_not_found (ids are never
230
- * reused within a session); `pane rename` sets the `label` field matched here.
452
+ * reused within a session); `pane rename` sets the `label` field matched here
453
+ * (matching is label-only — live 0.7.4 rows carry no `title` field, and the
454
+ * old title fallback could silently hit an unrelated pane on other builds).
455
+ *
456
+ * Hardening (EP152 wave-2 W2, adversarial findings): matching is
457
+ * NFC-normalized, and a DUPLICATE label is a hard refusal — first-match on an
458
+ * order-unstable inventory could steer the wrong agent. Rename the panes or
459
+ * scope with `{ workspace }`.
231
460
  */
232
- export async function resolveHerdrPaneId(paneLabel: string, opts: HerdrRunOptions = {}): Promise<string> {
233
- const label = paneLabel.trim()
461
+ export async function resolveHerdrPaneId(paneLabel: string, opts: HerdrResolveOptions = {}): Promise<string> {
462
+ const label = nfc(paneLabel.trim())
234
463
  const panes = await listHerdrPanes(opts)
235
- // Two passes: an explicit `pane rename` label always beats a title
236
- // coincidence, regardless of pane order.
237
- let matches = panes.filter((p) => p.label === label)
238
- if (matches.length === 0) matches = panes.filter((p) => p.title === label)
464
+ const scoped = opts.workspace ? panes.filter((p) => p.workspace_id === opts.workspace) : panes
465
+ const matches = scoped.filter((p) => typeof p.label === "string" && nfc(p.label) === label)
466
+ const where = opts.workspace ? ` in workspace ${opts.workspace}` : ""
467
+ if (matches.length === 0 || !matches[0]?.pane_id) {
468
+ throw new TideError(`no herdr pane labeled "${paneLabel.trim()}"${where} in \`herdr pane list\``)
469
+ }
239
470
  if (matches.length > 1) {
240
- const ids = matches.map((p) => p.pane_id ?? "?").join(", ")
471
+ const seen = matches
472
+ .map((p) => `${p.pane_id ?? "?"} (workspace ${p.workspace_id ?? "?"})`)
473
+ .join(", ")
241
474
  throw new TideError(
242
- `ambiguous herdr pane label "${label}" — matches panes ${ids}; rename panes to unique labels`,
475
+ `duplicate herdr pane label "${paneLabel.trim()}"${where}: ${seen} — refusing first-match steering; ` +
476
+ "rename the panes (`herdr pane rename`) or scope the resolution with { workspace }",
243
477
  )
244
478
  }
245
- const match = matches[0]
246
- if (!match?.pane_id) {
247
- throw new TideError(`no herdr pane labeled "${label}" in \`herdr pane list\``)
248
- }
249
- return match.pane_id
479
+ return matches[0].pane_id
250
480
  }
251
481
 
252
- export interface HerdrTargetOptions extends HerdrRunOptions {
482
+ export interface HerdrTargetOptions extends HerdrResolveOptions {
253
483
  /**
254
484
  * Durable pane label; when set it wins over the pane id argument and is
255
485
  * re-resolved to the current id at action time.
@@ -268,6 +498,12 @@ function resolveTarget(pane: string, opts: HerdrTargetOptions): Promise<string>
268
498
  export interface HerdrSendKeysOptions extends HerdrTargetOptions {
269
499
  /** Send a real Enter key after the literal text. Default true (mirrors the tmux path). */
270
500
  submit?: boolean
501
+ /**
502
+ * Steer-gate probe overrides (test seam / cockpit injection). The gate
503
+ * itself cannot be disabled — these only answer its questions. See
504
+ * steer-gate.ts (EP152 wave-2 W1).
505
+ */
506
+ gate?: SteerGateOverrides
271
507
  }
272
508
 
273
509
  /**
@@ -281,16 +517,21 @@ function makeHerdrSendKeysPlan(
281
517
  message: string,
282
518
  submit: boolean,
283
519
  paneLabel?: string,
520
+ session?: string,
284
521
  ): TideHerdrSendKeysResult {
285
522
  const plan: TideHerdrSendKeysResult = {
286
523
  multiplexer: "herdr",
287
524
  target,
288
525
  message,
526
+ // The session is prefixed INTO the argv, not carried beside it, so there is
527
+ // no way to execute the plan and reach a different session than the one the
528
+ // plan says it is addressing.
289
529
  submitted: submit,
290
- literal_command: ["pane", "send-text", target, message],
291
- submit_command: submit ? ["pane", "send-keys", target, "Enter"] : null,
530
+ literal_command: withSession(["pane", "send-text", target, message], session),
531
+ submit_command: submit ? withSession(["pane", "send-keys", target, "Enter"], session) : null,
292
532
  }
293
533
  if (paneLabel !== undefined) plan.pane_label = paneLabel
534
+ if (session !== undefined && session.trim()) plan.session = session.trim()
294
535
  return plan
295
536
  }
296
537
 
@@ -304,8 +545,21 @@ export function buildHerdrSendKeysPlan(
304
545
  message: string,
305
546
  submit = true,
306
547
  paneLabel?: string,
548
+ session?: string,
307
549
  ): TideHerdrSendKeysResult {
308
- return makeHerdrSendKeysPlan(normalizeHerdrPaneTarget(pane), message, submit, paneLabel)
550
+ return makeHerdrSendKeysPlan(normalizeHerdrPaneTarget(pane), message, submit, paneLabel, session)
551
+ }
552
+
553
+ /**
554
+ * Liveness probe for the steer gate: label resolution IS live proof (herdr
555
+ * just returned the id); a raw id must appear in the current `pane list`.
556
+ */
557
+ function herdrTargetResolved(target: string, viaLabel: boolean, opts: HerdrRunOptions): () => Promise<boolean> {
558
+ if (viaLabel) return async () => true
559
+ return async () => {
560
+ const panes = await listHerdrPanes(opts)
561
+ return panes.some((p) => p.pane_id === target)
562
+ }
309
563
  }
310
564
 
311
565
  /**
@@ -314,6 +568,11 @@ export function buildHerdrSendKeysPlan(
314
568
  * two-step semantics as the tmux path: if the literal step succeeds but the
315
569
  * submit step fails, the text is left on the pane unsubmitted and the thrown
316
570
  * TideError names which step failed.
571
+ *
572
+ * Execution is steer-gated (EP152 wave-2 W1): live-resolved target +
573
+ * ACTIVE_CONTROLLER posture + interactive TTY (or approval-fronted override)
574
+ * — the same 3-part boundary as `tide operator send --run`. Plan builders
575
+ * stay ungated (dry-run is the default posture of the covenant).
317
576
  */
318
577
  export async function sendKeysViaHerdr(
319
578
  pane: string,
@@ -322,7 +581,13 @@ export async function sendKeysViaHerdr(
322
581
  ): Promise<TideHerdrSendKeysResult> {
323
582
  // resolveTarget validates caller-supplied ids and trusts label-resolved ones.
324
583
  const target = await resolveTarget(pane, opts)
325
- const plan = makeHerdrSendKeysPlan(target, message, opts.submit ?? true, opts.paneLabel)
584
+ const gate = acceptGateOverrides(opts.gate)
585
+ await requireSteerGate({
586
+ ...gate,
587
+ target,
588
+ resolveTarget: gate.resolveTarget ?? herdrTargetResolved(target, opts.paneLabel !== undefined, opts),
589
+ })
590
+ const plan = makeHerdrSendKeysPlan(target, message, opts.submit ?? true, opts.paneLabel, opts.session)
326
591
  const runner = makeRunner(opts)
327
592
  const bin = resolveHerdrBin()
328
593
  try {
@@ -334,6 +599,10 @@ export async function sendKeysViaHerdr(
334
599
  )
335
600
  }
336
601
  if (plan.submit_command) {
602
+ // Same paste-staging contract as the tmux path: a TUI holds the text as
603
+ // "[Pasted text]" after the first Enter. Settle, submit, submit again —
604
+ // the repeat is a no-op everywhere else.
605
+ await new Promise((resolve) => setTimeout(resolve, 200))
337
606
  try {
338
607
  await runner(bin, plan.submit_command)
339
608
  } catch (err) {
@@ -342,6 +611,12 @@ export async function sendKeysViaHerdr(
342
611
  err,
343
612
  )
344
613
  }
614
+ await new Promise((resolve) => setTimeout(resolve, 150))
615
+ try {
616
+ await runner(bin, plan.submit_command)
617
+ } catch {
618
+ // Best-effort repeat: the first Enter landed.
619
+ }
345
620
  }
346
621
  return { ...plan, sent_at: new Date().toISOString() }
347
622
  }
@@ -362,13 +637,28 @@ export async function renameHerdrPane(
362
637
  await runHerdr(["pane", "rename", target, label], opts)
363
638
  }
364
639
 
365
- /** `herdr pane run <id> <command>` — send the text and a real Enter in one request. */
640
+ export interface HerdrRunInPaneOptions extends HerdrTargetOptions {
641
+ /** Steer-gate probe overrides — see HerdrSendKeysOptions.gate. */
642
+ gate?: SteerGateOverrides
643
+ }
644
+
645
+ /**
646
+ * `herdr pane run <id> <command>` — send the text and a real Enter in one
647
+ * request. Steer-gated like sendKeysViaHerdr (W1-adjacent: same mutation
648
+ * power, same boundary — an ungated `pane run` would make the gate decorative).
649
+ */
366
650
  export async function runInHerdrPane(
367
651
  pane: string,
368
652
  command: string,
369
- opts: HerdrTargetOptions = {},
653
+ opts: HerdrRunInPaneOptions = {},
370
654
  ): Promise<void> {
371
655
  const target = await resolveTarget(pane, opts)
656
+ const gate = acceptGateOverrides(opts.gate)
657
+ await requireSteerGate({
658
+ ...gate,
659
+ target,
660
+ resolveTarget: gate.resolveTarget ?? herdrTargetResolved(target, opts.paneLabel !== undefined, opts),
661
+ })
372
662
  await runHerdr(["pane", "run", target, command], opts)
373
663
  }
374
664
 
package/src/index.ts CHANGED
@@ -2,6 +2,27 @@ export * from "./types"
2
2
  export * from "./socket"
3
3
  export * from "./client"
4
4
  export * from "./herdr"
5
+ // steer-gate: explicit exports — trustSteerGateProbes/acceptGateOverrides are
6
+ // deliberately NOT on the package surface (W10a: the test seam must be a
7
+ // direct-module import, never a consumer API).
8
+ export {
9
+ STEER_BOUNDARY,
10
+ resolveNavigatorDir,
11
+ readNavigatorPosture,
12
+ evaluateSteerGate,
13
+ requireSteerGate,
14
+ // The narrow, named exception to the line above: an authenticated human's
15
+ // presence answering the gate (William's ruling 2026-08-02). The raw
16
+ // brander stays unexported.
17
+ humanConsentSteerGate,
18
+ } from "./steer-gate"
19
+ export type {
20
+ SteerPostureMode,
21
+ SteerPosture,
22
+ SteerGateOverrides,
23
+ SteerGateInputs,
24
+ SteerGateDecision,
25
+ } from "./steer-gate"
5
26
  export type {
6
27
  EpisodeLaneTopology,
7
28
  TideLaneCheckpoint,
@@ -0,0 +1,263 @@
1
+ // Steer-layer approval gate for @miadi/tide — the TypeScript port of the
2
+ // Python runtime's 3-part guarded-send gate (EP152 wave-2 W1; adversarial
3
+ // finding: sendKeys/sendKeysViaHerdr executed with no posture, no TTY, no
4
+ // approval artifact while `tide operator send --run` enforced all three).
5
+ //
6
+ // Python source of record (runtime/tide-runtime):
7
+ // terminal_send.py SEND_BOUNDARY — the covenant string, reproduced below
8
+ // cli.py operator_send / _require_controller_execution — enforcement order:
9
+ // 1. resolution_status == "resolved" (target visible in LIVE inventory)
10
+ // 2. cfg.mode == NavigatorMode.ACTIVE_CONTROLLER (wire value "controller"
11
+ // in ${MIADI_HOME|~/.miadi/navigator}/config.yml; observer default)
12
+ // 3. stdin.isatty() OR TIDE_ALLOW_NON_INTERACTIVE_RUN=1 (Tide Studio /
13
+ // approval-queue-fronted services set the env after their own review)
14
+ // config.py _controller_ttl_expired — a controller lease older than
15
+ // controller.ttl_minutes (default 30, 0 = no expiry) counts as observer.
16
+ // Python persists that downgrade when IT loads config; this reader cannot
17
+ // write, so it applies the same expiry arithmetic on every read.
18
+ //
19
+ // The gate is multiplexer-agnostic: callers (tmux client.ts, herdr herdr.ts)
20
+ // compute target liveness their own way and pass the probes in. Every probe
21
+ // is injectable (the test seam); none of the injection points can DISABLE the
22
+ // gate — they only answer its three questions.
23
+
24
+ import { readFileSync } from "node:fs"
25
+ import { homedir } from "node:os"
26
+ import { join } from "node:path"
27
+
28
+ import { TideError } from "./errors"
29
+
30
+ /** Verbatim covenant string from terminal_send.py (SEND_BOUNDARY). */
31
+ export const STEER_BOUNDARY =
32
+ "explicit target, reviewed message source, dry-run by default, " +
33
+ "ACTIVE_CONTROLLER + interactive local TTY required for send"
34
+
35
+ /** Wire values from tide_runtime.models.NavigatorMode ("controller", not "active_controller"). */
36
+ export type SteerPostureMode = "observer" | "controller" | "unknown"
37
+
38
+ export interface SteerPosture {
39
+ /** Effective mode after TTL arithmetic — an expired controller lease reads as "observer". */
40
+ mode: SteerPostureMode
41
+ /** Where the posture came from (config path, or "default: observer" when absent). */
42
+ source: string
43
+ enabled_at?: string
44
+ ttl_minutes?: number
45
+ /** True when config said "controller" but the lease exceeded ttl_minutes. */
46
+ expired?: boolean
47
+ }
48
+
49
+ /**
50
+ * Injectable probes answering the gate's three questions. Absent probes fall
51
+ * back to the real host: config.yml posture, process.stdin TTY, process.env.
52
+ * `resolveTarget` has NO default — liveness is multiplexer-specific and the
53
+ * calling transport must supply it.
54
+ */
55
+ export interface SteerGateOverrides {
56
+ readPosture?: () => SteerPosture | Promise<SteerPosture>
57
+ isInteractive?: () => boolean
58
+ env?: Record<string, string | undefined>
59
+ /** Override the transport's liveness probe (tests / pre-verified callers). */
60
+ resolveTarget?: () => boolean | Promise<boolean>
61
+ }
62
+
63
+ export interface SteerGateInputs extends SteerGateOverrides {
64
+ /** Human-readable target, only used in refusal reasons. */
65
+ target: string
66
+ /** Is the target visible in the LIVE multiplexer inventory right now? */
67
+ resolveTarget: () => boolean | Promise<boolean>
68
+ }
69
+
70
+ export interface SteerGateDecision {
71
+ allowed: boolean
72
+ /** Every failed check, in Python enforcement order; empty when allowed. */
73
+ reasons: string[]
74
+ posture: SteerPosture
75
+ target_resolved: boolean
76
+ interactive_tty: boolean
77
+ non_interactive_override: boolean
78
+ boundary: string
79
+ }
80
+
81
+ function expandHome(p: string): string {
82
+ if (p === "~") return homedir()
83
+ if (p.startsWith("~/")) return join(homedir(), p.slice(2))
84
+ return p
85
+ }
86
+
87
+ /** `${MIADI_HOME || ~/.miadi/navigator}` — mirrors tide_runtime.paths.get_config_dir(). */
88
+ export function resolveNavigatorDir(env: Record<string, string | undefined> = process.env): string {
89
+ const override = env.MIADI_HOME?.trim()
90
+ return override ? expandHome(override) : join(homedir(), ".miadi", "navigator")
91
+ }
92
+
93
+ const QUOTE = /^['"]|['"]$/g
94
+
95
+ /**
96
+ * Read `mode:` and the `controller:` lease block from config.yml. NOT a YAML
97
+ * parser — a line reader for exactly the two keys tide writes via
98
+ * yaml.safe_dump(default_flow_style=False): a top-level scalar and one
99
+ * two-key nested block. Anything unreadable degrades to the Python default
100
+ * (observer), never to controller.
101
+ */
102
+ export function readNavigatorPosture(env: Record<string, string | undefined> = process.env): SteerPosture {
103
+ const dir = resolveNavigatorDir(env)
104
+ const path = join(dir, "config.yml")
105
+ let text: string
106
+ try {
107
+ text = readFileSync(path, "utf8")
108
+ } catch {
109
+ return { mode: "observer", source: `default: observer (no readable ${path})` }
110
+ }
111
+ let rawMode: string | undefined
112
+ let ttl: number | undefined
113
+ let enabledAt: string | undefined
114
+ let inController = false
115
+ for (const line of text.split("\n")) {
116
+ const topLevel = /^[^\s#]/.test(line)
117
+ if (topLevel) inController = /^controller:\s*$/.test(line)
118
+ const mode = line.match(/^mode:\s*(.+?)\s*$/)
119
+ if (mode) rawMode = mode[1].replace(QUOTE, "")
120
+ if (inController && !topLevel) {
121
+ const t = line.match(/^\s+ttl_minutes:\s*(.+?)\s*$/)
122
+ if (t) ttl = Number(t[1].replace(QUOTE, ""))
123
+ const e = line.match(/^\s+enabled_at:\s*(.+?)\s*$/)
124
+ if (e) enabledAt = e[1].replace(QUOTE, "")
125
+ }
126
+ }
127
+ const mode: SteerPostureMode =
128
+ rawMode === "controller" ? "controller" : rawMode === "observer" || rawMode === undefined ? "observer" : "unknown"
129
+ const posture: SteerPosture = { mode, source: path }
130
+ if (enabledAt !== undefined) posture.enabled_at = enabledAt
131
+ if (ttl !== undefined && Number.isFinite(ttl)) posture.ttl_minutes = ttl
132
+ // config.py _controller_ttl_expired: controller + ttl>0 + parseable stamp
133
+ // older than the lease ⇒ effective observer. An unparseable stamp with a
134
+ // positive TTL also expires (fail closed), matching Python's None-parse path.
135
+ if (mode === "controller") {
136
+ const ttlMin = posture.ttl_minutes ?? 30
137
+ if (ttlMin > 0) {
138
+ const enabled = Date.parse(posture.enabled_at ?? "")
139
+ if (Number.isNaN(enabled) || Date.now() - enabled > ttlMin * 60_000) {
140
+ posture.mode = "observer"
141
+ posture.expired = true
142
+ }
143
+ }
144
+ }
145
+ return posture
146
+ }
147
+
148
+ /**
149
+ * Answer the three gate questions. Never throws — the decision carries every
150
+ * failed check so cockpits can show the whole story at once (the Python CLI
151
+ * exits on the first failure; a JSON boundary wants all of them).
152
+ */
153
+ export async function evaluateSteerGate(inputs: SteerGateInputs): Promise<SteerGateDecision> {
154
+ const env = inputs.env ?? process.env
155
+ const posture = await (inputs.readPosture ? inputs.readPosture() : readNavigatorPosture(env))
156
+ const interactive = inputs.isInteractive ? inputs.isInteractive() : process.stdin.isTTY === true
157
+ const override = env.TIDE_ALLOW_NON_INTERACTIVE_RUN === "1"
158
+ let resolved = false
159
+ try {
160
+ resolved = await inputs.resolveTarget()
161
+ } catch {
162
+ resolved = false // an unreachable inventory cannot prove a live target
163
+ }
164
+
165
+ const reasons: string[] = []
166
+ if (!resolved) {
167
+ reasons.push(
168
+ `steer target ${inputs.target} is not currently resolved in the live multiplexer inventory — ` +
169
+ "list panes/terminals and retry with a visible target",
170
+ )
171
+ }
172
+ if (posture.mode !== "controller") {
173
+ reasons.push(
174
+ `steer execution requires ACTIVE_CONTROLLER posture (mode: controller); current posture is ` +
175
+ `"${posture.mode}"${posture.expired ? " (controller lease expired)" : ""} — ` +
176
+ "run `tide mode controller` from a local interactive terminal first",
177
+ )
178
+ }
179
+ if (!interactive && !override) {
180
+ reasons.push(
181
+ "steer execution requires an interactive local terminal (TTY), or TIDE_ALLOW_NON_INTERACTIVE_RUN=1 " +
182
+ "set by an approval-queue-fronted service after its own review",
183
+ )
184
+ }
185
+ return {
186
+ allowed: reasons.length === 0,
187
+ reasons,
188
+ posture,
189
+ target_resolved: resolved,
190
+ interactive_tty: interactive,
191
+ non_interactive_override: override,
192
+ boundary: STEER_BOUNDARY,
193
+ }
194
+ }
195
+
196
+ /** Evaluate and THROW a TideError naming every failed check when refused. */
197
+ export async function requireSteerGate(inputs: SteerGateInputs): Promise<SteerGateDecision> {
198
+ const decision = await evaluateSteerGate(inputs)
199
+ if (!decision.allowed) {
200
+ throw new TideError(`steer gate refused (${STEER_BOUNDARY}): ${decision.reasons.join("; ")}`)
201
+ }
202
+ return decision
203
+ }
204
+
205
+ // ── Trusted-override brand (EP152 wave-2 W10a) ──────────────────────────────
206
+ //
207
+ // The injectable probes are a test seam, and a seam is a channel: any caller
208
+ // that answers all three questions affirmatively — or merely smuggles
209
+ // `env: {TIDE_ALLOW_NON_INTERACTIVE_RUN:"1"}` in JSON-derived options — walks
210
+ // through the gate (W8 adversarial finding, verified live). Overrides are
211
+ // therefore only ACCEPTED when branded by trustSteerGateProbes(), which is
212
+ // deliberately NOT re-exported from the package surface (src/index.ts): tests
213
+ // and first-party wiring reach it via a direct module import; JSON cannot
214
+ // carry the brand (a module-private Symbol on a non-enumerable property), so
215
+ // request-derived gate options are structurally refused.
216
+
217
+ const TRUSTED_PROBES = Symbol("miadi.tide.steer-gate.trusted-probes")
218
+
219
+ /** Brand probe overrides as trusted. NOT exported from the package surface — import from the module directly (test seam / first-party wiring only). */
220
+ export function trustSteerGateProbes(overrides: SteerGateOverrides): SteerGateOverrides {
221
+ const branded: SteerGateOverrides = { ...overrides }
222
+ Object.defineProperty(branded, TRUSTED_PROBES, { value: true, enumerable: false })
223
+ return branded
224
+ }
225
+
226
+ /**
227
+ * William's ruling, 2026-08-02: the controller lease gates AGENTS, never the
228
+ * authenticated human. A server route that has ALREADY authenticated a person
229
+ * (writer token, or a named tailnet identity) may declare that presence here —
230
+ * the person's authentication is the consent, so posture and TTY answer as
231
+ * satisfied while target liveness still applies. This is the one sanctioned
232
+ * way for HTTP-derived code to answer those questions (W10a stands: the raw
233
+ * brander is not a consumer API), and it exists so the voice portal's reply
234
+ * button is not a dead end by default. `source` must name the route and the
235
+ * gate that authenticated the person — it is what a refused-audit reads later.
236
+ */
237
+ export function humanConsentSteerGate(source: string): SteerGateOverrides {
238
+ return trustSteerGateProbes({
239
+ readPosture: () => ({ mode: "controller", source: `authenticated-human: ${source}` }),
240
+ isInteractive: () => true,
241
+ })
242
+ }
243
+
244
+ function isTrustedSteerGateProbes(gate: SteerGateOverrides): boolean {
245
+ return (gate as Record<PropertyKey, unknown>)[TRUSTED_PROBES] === true
246
+ }
247
+
248
+ /**
249
+ * Admission check for `opts.gate` at the transport boundary: absent → real
250
+ * host probes; branded → accepted; anything else → loud refusal (a gate
251
+ * override that reaches a steer verb without the brand is either a bug or an
252
+ * injection — both deserve a named failure, not a silent bypass or ignore).
253
+ */
254
+ export function acceptGateOverrides(gate: SteerGateOverrides | undefined): SteerGateOverrides {
255
+ if (gate === undefined) return {}
256
+ if (!isTrustedSteerGateProbes(gate)) {
257
+ throw new TideError(
258
+ "steer gate overrides refused: not branded by trustSteerGateProbes() — " +
259
+ "request-derived or untrusted gate options cannot answer the gate's questions",
260
+ )
261
+ }
262
+ return gate
263
+ }