ADR-0003: Process IPC and session authentication
Status: Accepted — 2026-09-21. The project owner approved the process IPC design, baseline limits and recorded validation scope, with the known Python startup regression retained. Acceptance establishes the architecture, not a released protocol or completed product implementation.
Clarification — 2026-09-22: the exit mapping covers all process invocations, including process-only commands; this does not require those commands to implement IPC. Cancellation reasons and the single shutdown deadline are explicit below. Historical measurements and validation remain unchanged; the clarified cases require additional conformance checks.
Refinement — 2026-09-24: shared CLI/MCP and agent-use additions are accepted under ADR-0013 and ADR-0014–0016. The original acceptance date and historical evidence remain unchanged; the new requirements are not claimed implemented or verified.
Context and problem
Section titled “Context and problem”ADR-0001 establishes separate processes as the baseline executor. ADR-0002 defines invocation, core operations, terminal ownership and completion independently of transport. A managed process needs a concrete channel that preserves those rules across implementation languages.
This decision concerns processes launched and supervised by the core for one invocation. Ordinary process-only commands do not need this protocol. Remote extensions, persistent workers, registry trust, the KCL schema and runtime installation are outside its scope. Future executors, including WASM, may map ADR-0002 without using process IPC.
Decision drivers
Section titled “Decision drivers”- Separate control messages from command input and output.
- Bind the channel to the process the core launched, without trusting a claimed name or invocation ID.
- Support different languages through small, explicit platform adapters.
- Bound memory, waiting and cleanup; keep cancellation possible under load.
- Preserve permissions, one final outcome and the absence of automatic action retries.
Considered options
Section titled “Considered options”| Option | Benefit | Limitation |
|---|---|---|
| Messages mixed into stdin/stdout | Familiar stream APIs | Conflicts with pipelines, redirected bytes and independent control |
| An already connected, privately inherited channel | No public connection address or application authentication handshake | Requires verified descriptor/handle transfer for each runtime |
| A local listener with a fresh launch credential | Familiar socket connection APIs | Adds connection races, credential delivery, mutual authentication and channel-integrity rules |
| Local TCP with an established authenticated protocol | Broad library support | Adds network configuration and credential management to a local child-process problem |
Decision
Section titled “Decision”Use one private, already connected byte channel per invocation, carrying a restricted JSON-RPC 2.0 profile. The core creates both ends before launching the extension and transfers only the extension end to that process. Possession of this OS handle establishes the session boundary; confirmation messages establish compatibility. There is no reconnect, session reuse or automatic fallback to a listener.
Channel and ownership
Section titled “Channel and ownership”The channels separate command data, control and presentation. None gives the extension ownership of the terminal.
| Platform | Channel setup |
|---|---|
| Unix-like systems | A connected AF_UNIX / SOCK_STREAM socket pair, with no pathname or listening socket |
| Windows | A local named pipe pair in byte mode, connected by the core before launch; a fresh name, explicit DACL, remote clients rejected, first-instance creation and nMaxInstances=1 required |
On Windows, the temporary name is a setup detail: the child receives a connected handle, not an address to dial. The core verifies that both connected endpoints belong to its own setup before transferring an end; an unexpected connection aborts setup. It keeps no instance available for another client and never disconnects/reuses the pipe for a new session. The connected server handle remains open as the core end; there is no pending accept after setup. Byte mode avoids an additional OS message boundary. Windows pipe creation, pipe access control.
The launcher explicitly allows only the required standard streams and extension control end to cross the process boundary. It closes its duplicate extension end immediately after a successful launch and all ends on failure. The extension adapter prevents further inheritance before it starts extension handlers. On Unix this requires deliberate close-on-exec handling; on Windows it requires an explicit inherited-handle list, including safe handling of concurrent launches in an embedding application. These are launcher responsibilities, not instructions left to each command author. Windows handle inheritance.
Native code, Node.js, Python and Lua need a tested adapter for the selected runtime and platform. A numeric Windows handle is not a portable file descriptor; do not promise that fd 3 works everywhere. An adapter may need a small native binding. Unsupported transfer or asynchronous I/O is a known compatibility failure before launch, not a reason to switch to stdout or TCP. The runtime provider supplies an environment; the approved launcher and adapter establish this channel.
Windows requires overlapped I/O on both endpoints. Reads and writes have separate operation state and completion events; a pending read cannot block the writer. The supervisor can cancel pending I/O and still enforce the shutdown deadline. The reference experiment found that synchronous operations on the shared handle prevented progress; separate reader and writer threads alone were insufficient. Windows overlapped pipe I/O.
Establish process supervision before allowing extension code to run. The Windows launcher creates the process suspended, assigns it to a Job Object with kill-on-close and no breakaway, then resumes its initial thread. Failure at any step stops the suspended process and closes the channel; it does not dispatch invoke. The job handle is not inherited. Cleanup covers processes in that job, not work delegated to external services. Windows Job Objects.
The validation scope is explicit; it is not an implied runtime support list for a released product:
| Platform and adapter | Recorded evidence |
|---|---|
| Windows 11 x64, native Go 1.27.1 | Real inherited channel, framing, invocation and cleanup checks |
Windows 11 x64, Python 3.14.7 with a ctypes Win32 adapter | Real inherited channel plus service, policy and lifecycle fault scenarios |
| Node.js, Lua and adapters on additional platforms | Require their own implementation and the same conformance checks before being declared supported |
Session identity and confirmation
Section titled “Session identity and confirmation”The core pins the invocation kind, canonical command, extension release, contract and access context before launch. A fresh session ID identifies the channel within that invocation. Both IDs are correlation data, not secrets or permissions. The extension identifies the core as the peer of its inherited endpoint; the core identifies the launched extension as the peer of the endpoint it retained. Neither accepts a replacement channel advertised in a message.
This authenticates possession of the launched session, not the publisher, safety of the extension or the logged-in user. The selected artifact and entry point still require the existing trust checks. Code able to inspect or modify the processes, steal handles or deliberately share its endpoint is outside this protection. A child process is not a sandbox. OS peer credentials can provide diagnostics or setup checks, but the creator’s PID on a preconnected pair is not proof of the child’s identity.
The exchange confirms an already selected contract. It does not negotiate a downgrade. The diagram shows the Windows launch sequence; another platform must establish equivalent supervision before handlers run.
The binding version and framing are selected from verified declarations before launch, then confirmed alongside the interaction version and required features. The core sends only the context needed by the extension; authoritative identity and access scope stay in the core. Before confirmation, only initialize and its response are valid. Cancellation at this stage closes the channel and starts process stopping without a cancel request. An extension handler, service request or UI request must not run during initialization. A trusted adapter enforces that rule for conforming extensions; IPC is not an OS barrier against malicious startup code.
After confirmation, the channel itself selects the fixed session and invocation context. An optional repeated session or invocation field must match it exactly; it cannot select another context. A mismatch is a protocol error.
A known incompatibility causes rejected before any extension code starts. An actual channel-creation, transfer or launch failure causes execution_failed. A mismatch, malformed response or initialization-budget timeout after process launch causes execution_failed, with no invoke, unless invocation cancellation has been accepted. Expiry of the invocation deadline instead accepts deadline_exceeded, even during initialization. There is one invocation per session; execute cannot turn into describe, or the reverse.
Framing and value representation
Section titled “Framing and value representation”Each frame is a four-byte unsigned big-endian payload length followed by exactly that many UTF-8 bytes containing one JSON object. Reads and writes may split or combine frames. There is no delimiter, compression, batch array or out-of-band binary attachment in this binding. Command bytes stay on their separate data streams.
The receiver checks the length before allocating the payload, reads within a fixed frame deadline, and validates the complete object before dispatch. Reject invalid UTF-8, duplicate keys, invalid Unicode scalar values, a BOM, excess nesting and non-finite numbers. Field schemas reject unknown authority-bearing fields. JSON interoperability requires explicit number limits: integers must be within -(2^53 - 1) through 2^53 - 1; decimal values follow the declared binary64 representation. Larger exact integers or exact decimal values need an explicitly declared string encoding, never a silent conversion. Values that the selected schema cannot represent are refused before dispatch. JSON standard.
For managed execute, the payload carries the already parsed typed inputs and IDs of explicitly supplied parameters, without a second argv representation. describe carries its separate help request, not mandatory execution arguments; stdin is closed, UI is forbidden and only separately authorized read operations are available. Its structured supplement is part of the completion report. Captured process output does not become help content.
Negotiated command results and outer adapters — 2026-09-24
Section titled “Negotiated command results and outer adapters — 2026-09-24”ADR-0013 defines the optional command-result/1 feature. A compatible interaction/binding version must explicitly support it in static capabilities and initialization confirmation. When selected for execute, the existing rukh.invoke result contains the declared commandResult alongside its completion report; no new unsolicited result message is introduced. The feature defines this additional member’s schema, requiredness and limits. Without negotiated support this member is invalid, not an ignorable unknown field. Older accepted mappings and recorded fixtures remain unchanged. An implementation must advertise a compatible feature-bearing binding/interaction version before using it; acceptance does not assign an unimplemented wire version or imply that old adapters accept new members.
The payload, metadata and envelope together obey the smaller of ADR-0003 and ADR-0013 limits. Invalid result data prevents normal success and follows the same cancellation precedence, exit agreement and bounded cleanup. describe retains its separate help payload. Sensitive authoritative task/effect context stays in the core; an extension cannot replace it through a repeated field or core call.
The host’s MCP channel is an outer client interface, not this process session. It cannot inherit the private extension endpoint or route raw MCP messages to rukh.call. The core translates an admitted call into one existing foreground invocation. MCP cancellation/loss reaches the lifecycle owner; completion delivery to that client never repeats invoke or a protected effect. Diagnostics and process streams remain separate from both control protocols.
Requests, responses and events
Section titled “Requests, responses and events”Use JSON-RPC 2.0 objects with named parameters and string request IDs. A response contains exactly one of result or error. This profile excludes batches and does not use the reserved rpc. namespace. JSON-RPC supplies correlation and error envelopes; lifecycle, authorization and delivery rules remain Rukh’s responsibility. JSON-RPC specification.
| Message | Direction and form | Meaning |
|---|---|---|
rukh.initialize | Core → extension, request | Confirm the pinned session, versions, features and limits |
rukh.invoke | Core → extension, one request | Dispatch execute or describe; its response is the sole completion report |
rukh.call | Extension → core, request | Call a registered operation with its version and validated input |
rukh.ui.event | Core → extension, acknowledged request | Deliver an allowed interface event with view, revision and event order |
rukh.log | Extension → core, notification | Submit a bounded diagnostic record; delivery is not guaranteed |
rukh.cancel | Core → extension, request | Notify cancellation; acknowledgement does not delay or prove stopping |
rukh.close | Core → extension, request | Complete orderly control-channel shutdown after a completion report |
Both succeeded and command_failed are normal invoke results containing a completion report. A JSON-RPC error response to invoke denotes a dispatch/protocol failure, not an ordinary command failure, and leads to execution_failed unless cancellation already governs the outcome.
The reader keeps receiving while handlers wait. Waiting for invoke must not block a nested call, its response, a UI event or cancellation. A single bounded writer serializes frames in each direction; handlers cannot interleave their bytes.
Request IDs use direction prefixes and contiguous increasing counters, such as c:1 and e:1, assigned in wire order. They are never reused. A repeated, skipped or decreasing request ID is a protocol failure: do not perform the action or send a second response with that ID. Responses may arrive out of order and must match a pending request. An unknown future ID or wrong-direction ID is a protocol error. A response to a previously issued, retired request is discarded and counted as late; it cannot restore a request or repeat an action. Counters and a bounded pending map avoid retaining an unlimited history. The invoke ID remains tracked until closure: a second completion report is a protocol error, not an ordinary late response.
Operation identity, version and validated inputs select a registered core handler. The core derives the actual action and resource, then checks the core-owned context immediately before the protected action. Message fields cannot replace the subject, release or permissions. Local policy and a configured broker use the same checks; broker failure never enables a local fallback. A normal operation rejection returns a typed operation error and need not close a healthy session.
The core owns operation and UI request deadlines, capped by the invocation budget. A peer may ask for a shorter relative budget, not extend it using its clock. Cancellation and closure use the separate, fixed shutdown deadline, including after the invocation deadline has expired; they never extend execution time. Loss of a response leaves an external action potentially completed: correlation does not provide rollback or exactly-once execution. No request, command or external action is automatically retried.
Load, logs and interface events
Section titled “Load, logs and interface events”The following are the selected baseline limits of this binding. The reference checks exercise boundary rejection, overload and shortened test deadlines; they do not establish optimal production capacity. The core may tighten limits when selecting a compatible profile; the peer cannot increase them. Required sizes known in advance are checked before launch. Confirmation fixes the effective limits for that session. Higher limits require a separately declared and tested profile.
| Resource | Baseline limit |
|---|---|
| JSON payload | 1 MiB per frame; 16 KiB for initialization, cancellation, closure or an ordinary log record |
| JSON structure | Depth 32; 4,096 total members and array elements per frame |
| Pending operation/UI requests | 64 per direction, apart from the single invocation and lifecycle requests |
| Pending output queue | 128 frames or 4 MiB, whichever is reached first; includes queued logs |
| Reserved lifecycle queue | An additional 8 frames / 128 KiB for cancellation, closure and their replies |
| Ordinary log admission | 100 records and 1 MiB per second; excess records are dropped and counted |
| Initialization | 5 seconds from process launch, capped by the invocation deadline |
| Partial frame / blocked frame write | 2 seconds from the first byte received / start of write; progress does not reset the timer |
| Shutdown | One 5-second budget from entry into finalization, including at most 2 seconds of cooperative stopping, then forced termination and cleanup; no timer restarts |
An idle channel is allowed while waiting for user input or a long operation within its invocation budget. A partial frame is not idle. Reserve processing capacity for lifecycle messages and apply the frame deadline even under log load; priority cannot interrupt bytes already being written. Queue growth and parsing work must remain bounded. If control can no longer progress, fail the session and use process supervision to stop it.
The owner fixes one monotonic shutdown deadline on the first transition to finalization: completion evidence, terminal failure, rejection or accepted cancellation. For a process-only command, observed exit supplies completion evidence. Subsequent cancellation, failure, close, audit, stream draining and descendant cleanup share the time remaining; none starts another five-second window. Cooperative stopping ends no later than two seconds after that first transition, or sooner if the shared budget requires it. If finalization has already consumed that interval, cancellation may proceed directly to forced stopping. At the deadline the core closes its context and records incomplete work; it does not wait indefinitely for the OS or a trusted callback. Failure to confirm termination or required cleanup prevents success and retains protective resource references where necessary. Deadline selection cannot forcibly interrupt arbitrary trusted in-process code; adapters must supply a bounded boundary or declare that guarantee unsupported.
An invalid ordinary log payload or excess log rate causes a counted drop, not command failure. Invalid framing, session state or a broken control channel is a protocol failure. The core supplies trusted log metadata and routes diagnostics separately from stdout. Mandatory audit uses the protected operation path, not rukh.log; its failure can prevent an action or a successful outcome.
UI events are not lossy log notifications. An acknowledgement means validated admission into a bounded ordered queue, not completion of an external action. A stale revision, missing acknowledgement or a full queue closes the affected interaction with a defined error; there is no event replay after an uncertain acknowledgement. Only explicitly replaceable presentation updates may be coalesced. Secret input is delivered only to its intended operation and is never copied into logs or diagnostic payload dumps. Global cancellation remains core-owned.
Completion and transport failures
Section titled “Completion and transport failures”The state diagram concerns the transport. Reaching Closed does not, by itself, establish a successful invocation.
A valid completion report immediately closes admission of new core operations and UI. The core settles or cancels already accepted work within the remaining shutdown budget, sends close, and waits for its acknowledgement. The adapter flushes that acknowledgement, closes its endpoint and exits. EOF is expected only after a valid close acknowledgement; earlier EOF cannot replace a report or prove success. Under an already accepted cancellation, channel closure belongs to stopping and cannot change the outcome back to success or failure.
The core still checks normal process exit and its agreement with the report, drains or bounds captured output, completes required audit and releases resources. A success report requires a zero exit; a command-failure report requires a nonzero normal exit, with any explicitly reported code matching the actual code. Missing, duplicate or contradictory reports, abnormal exit and mandatory cleanup failure prevent success. Descendants holding an inherited stream cannot extend finalization indefinitely.
Cancellation accepted before the final outcome is committed wins over a late result. The first accepted ADR-0002 cause is retained: user_request, owner_shutdown or deadline_exceeded. The core closes admission immediately and enters bounded stopping without waiting for the extension’s acknowledgement or restarting the shutdown deadline. Later cancellation sources, protocol, audit or cleanup failures remain diagnostics. The invocation deadline is checked through commitment: its expiry during finalization accepts cancellation unless an earlier cause already governs the outcome. Expiry of the shutdown budget itself is an execution failure, not a new cancellation reason. A request-local timeout returns its defined operation error; a framing/control failure fails the invocation. EOF on stdin remains input exhaustion, not cancellation.
| Observation | Invocation consequence |
|---|---|
| Known incompatible binding or required capacity, before extension code | rejected |
| Initialization mismatch, damaged frame, early IPC EOF or lost control after launch | execution_failed, unless cancellation was already accepted |
| Valid report and matching normal exit, all required finalization completed | succeeded or command_failed, as reported |
| Cancellation accepted before final commit | cancelled; retain its cause and cleanup diagnostics |
| Ordinary log dropped or a retired ordinary response arrives late | Account for it; do not by itself change the outcome |
Unexpected closure never starts a new connection or dispatches the command again. The core reports a failed/uncertain operation without asserting that its external effects were undone. Preserve the first transport failure; a secondary broken-pipe error during forced cleanup must not hide it. An already accepted cancellation still takes precedence.
The CLI exit mapping is fixed by this decision for managed and process-only invocations; the typed outcomes of ADR-0002 remain authoritative. Process-only commands need no IPC report or acknowledgement: their normal process exit, stream handling and required finalization supply the evidence. Absence of an IPC session does not exempt them from the same cancellation causes and shutdown budget:
| Typed outcome | CLI exit code |
|---|---|
succeeded | 0 |
command_failed | The observed nonzero normal process exit code; a managed completion report must agree with it |
rejected, execution_failed | 125, with distinct typed outcome and diagnostic reason |
cancelled, user_request | 130 |
cancelled, owner_shutdown | 130 |
cancelled, deadline_exceeded | 124 |
Do not truncate the Windows process code to eight bits: the reference checks preserve 74565. The platform adapter records the raw process status separately; forced termination or a crash is never reclassified as command_failed merely because its numeric status matches a command code. On platforms with a smaller normal exit-code range, validate against that range; signal termination is separate. Codes 124, 125 and 130 can also be returned by a command, so the number alone never determines the typed outcome.
Consequences
Section titled “Consequences”The decision keeps authentication local to process launch and avoids a new cryptographic protocol. Commands and runtime integrations can use different languages, while one framing and lifecycle model remains shared. Terminal rendering, permissions and required audit stay under core control.
The cost is a maintained adapter per supported runtime/platform, rather than a promise that every standard library can consume an arbitrary inherited handle. No remote connection, background worker or reconnect is supported by implication. If practical adapters cannot preserve these guarantees, revisit the channel choice explicitly rather than silently enabling a less constrained mode.
Confirmation
Section titled “Confirmation”The 2026-09-24 refinement checks remain unrun. Verify the shared CLI/MCP path, unsupported result-feature rejection, current profile/task binding, bounded data, absence of replay and channel separation within this ADR’s responsibility. Historical results below do not cover these additions.
Reference checks — 2026-09-21
Section titled “Reference checks — 2026-09-21”Reproducible experiment in validation/adr-0003/ (mise run ipc-check): 126/126 checks passed on Windows 11 x64 10.0.26220, using mise-managed Go 1.27.1 and Python 3.14.7. The host uses Python and real Win32 calls; the workers are a native executable and a script. This is new evidence for the inherited channel, separate from the earlier ADR-0001/0002 experiments.
| Acceptance check | Observed result |
|---|---|
| Channel and adapters | Both adapters received the actual connected handle and disabled further inheritance. Endpoint ownership and refusal of another connection were checked. Unrelated inheritable handles were excluded; failed launch and failed Job Object assignment released resources without invoking extension code. Handle counts stayed unchanged across repeated warmed success/failure runs. |
| Frames and load | Byte-by-byte frames, split UTF-8, combined frames, number/structure limits, duplicate keys and IDs, out-of-order responses and simultaneous directions passed. Invalid payloads were rejected by both worker decoders and the host. Byte streams stayed separate; queue limits, dropped logs and cancellation under continuous log load were checked. A stuck read/write or partial frame could not wait indefinitely. |
| Session and permissions | Wrong session, contract or required features prevented invocation. Pre-confirmation calls never reached a handler. Local policy and a localhost HTTP broker stub shared the action gate; denial, malformed broker replies, context substitution and out-of-scope operations did not widen access. |
| Completion and failures | Missing, duplicate or contradictory results, early EOF, crash, user cancellation, deadline, lost response, UI admission failure and required-audit failure produced defined outcomes. A lost response after a counted effect did not repeat it. New effects were prevented after completion; an uncooperative descendant was terminated with the job. Wide Windows exit codes survived. |
| Performance and fixed rules | The complete reference lifecycle and framed operation calls were measured below. This decision specifies the resource bounds, overlapped I/O, supervision-before-resume, preservation of the first failure and the CLI exit mapping. Python startup still fails the comparison threshold. |
The detailed policy, overload, audit and UI scenarios use the Python worker; native checks cover the transport and basic lifecycle. Audit/effects and terminal events are controlled fixtures, not durable external integrations or physical terminal tests. Capacity tests combine real channels with an in-memory blocked writer. These results establish feasibility of this bounded reference, not complete production conformance or support for unlisted adapters.
Full adapter measurements
Section titled “Full adapter measurements”Three rounds reversed worker order in the middle round. Each worker has 150 fresh-invocation samples and 3,000 IPC round trips per payload size, after warmups: 300 invocations and 12,000 measured exchanges in total, without failed samples. Caches were warm; background machine load was not controlled. Go used Windows QueryPerformanceCounter; Python used its high-resolution performance counter. Low-resolution pilot timings were excluded. The runner retains raw samples locally under .generated/adr-0003/measurements.json.
Values are median / p95 in milliseconds, with nearest-rank p95. The last column retains ADR-0001’s minimal warmed-scenario comparison limits; it does not redefine them as product guarantees.
| Measurement | Native Go worker | Python worker | ADR-0001 p95 limit |
|---|---|---|---|
| Process start → validated initialization | 24.852 / 31.074 | 141.955 / 166.002 | 100 |
| Channel preparation + initialization + one operation + close + exit + cleanup | 45.697 / 47.338 | 156.766 / 185.434 | 150 |
| Established IPC, 64-byte data, validated request → response | 0.162 / 0.258 | 0.189 / 0.297 | 1 |
| Established IPC, 4,096-byte data, validated request → response | 0.211 / 0.333 | 0.233 / 0.373 | 1 |
IPC includes JSON validation, framing, local authorization and dispatch in the reference host; a full invocation includes one such operation and acknowledged closure. These are data-field sizes, not whole-frame sizes. Host startup, runtime installation, a network broker, real command work and cold-cache behavior are excluded. A p95 is not a maximum: the largest observed round trips were 2.135 ms native and 1.233 ms Python. Full-invocation maxima were 61.726 and 203.874 ms respectively.
Conclusion: the inherited channel is feasible, and the native path meets all four comparison limits. Established IPC meets its limits for both workers. The Python path is functionally valid in the tested scenarios but exceeds the startup and complete-invocation limits. This experiment does not isolate interpreter, adapter-import and OS startup costs, so it cannot attribute the excess to the transport alone. The performance thresholds have not been relaxed.
Accepted scope and remaining work
Section titled “Accepted scope and remaining work”The project owner accepted ADR-0003 on 2026-09-21 with the recorded Python startup and full-invocation regression. This known limitation does not block acceptance of the IPC architecture. ADR-0001’s performance targets remain unchanged; acceptance does not establish a higher Python budget or declare those checks passed.
The initial evidence covers the Windows Go and Python reference adapters listed above. Additional platform/runtime combinations require their own adapter and conformance run before support is claimed. Reducing Python startup cost and repeating the measurements remain implementation work. The reference checks do not certify a production SDK, external audit storage or real terminal integrations.
The 2026-09-22 clarification additionally requires process-only and managed checks for owner shutdown, first-cause races, invocation expiry during finalization, the shared non-renewable shutdown deadline and incomplete cleanup. The historical runs do not claim this additional coverage; these cases have not been run against the refined contract.