A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(daemon): add the Windows app channel's native ownership and stream core
Marcelito3e5f4d316447
diff --git a/packages/daemon/native/windows-app-channel-stream.cc b/packages/daemon/native/windows-app-channel-stream.ccnew file mode 100644index 0000000..45e39be--- /dev/null+++ b/packages/daemon/native/windows-app-channel-stream.cc@@ -0,0 +1,251 @@+#include "windows-app-channel-stream.h"+#include <atomic>+#include <cstring>+#include <new>+#include <utility>++namespace gentle_dot::app_channel {+namespace {+struct Operation {+ OVERLAPPED overlapped{};+ HANDLE event = nullptr;+ bool pending = false;+ bool cancel_requested = false;+ bool close_failed = false;+};+struct Write {+ Write* next = nullptr;+ BYTE* bytes = nullptr;+ size_t size = 0;+ size_t offset = 0;+ uint64_t ticket = 0;+ ~Write() { delete[] bytes; }+};+}+struct Stream {+ explicit Stream(Owner&& value) noexcept : owner(std::move(value)) {}+ Owner owner;+ Operation read, write;+ BYTE bytes[kStreamReadBytes];+ size_t read_size = 0, read_offset = 0;+ Write* head = nullptr;+ Write* tail = nullptr;+ size_t queued_bytes = 0, queued_items = 0;+ uint64_t accepted = 0, completed = 0;+ StreamPhase phase = StreamPhase::open;+ DWORD error = ERROR_SUCCESS;+ bool eof = false, abort = false;+ Stream* next = nullptr;+};+namespace {+// Foundation adoption has already pinned the addon before moving its owner here.+// Every quarantined record keeps buffers, OVERLAPPEDs, events and Owner together.+std::atomic<Stream*> retained{nullptr};+static_assert(std::atomic<Stream*>::is_always_lock_free);+void Retain(Stream* s) noexcept {+ Stream* head = retained.load(std::memory_order_relaxed);+ do { s->next = head; } while (!retained.compare_exchange_weak(+ head, s, std::memory_order_release, std::memory_order_relaxed));+}+void Fail(Stream& s, DWORD error) noexcept {+ if (!s.error) s.error = error ? error : ERROR_GEN_FAILURE;+ s.phase = StreamPhase::stopping;+ s.abort = true;+}+bool InitEvent(Stream& s, Operation& op) noexcept {+ SECURITY_ATTRIBUTES attributes{sizeof(attributes), nullptr, FALSE};+ op.event = CreateEventW(&attributes, TRUE, FALSE, nullptr);+ if (!op.event) { Fail(s, GetLastError()); return false; }+ DWORD flags = 0;+ if (!GetHandleInformation(op.event, &flags)) {+ Fail(s, GetLastError()); return false;+ }+ if (flags & HANDLE_FLAG_INHERIT) {+ Fail(s, ERROR_INVALID_DATA); return false;+ }+ return true;+}+bool Prepare(Stream& s, Operation& op) noexcept {+ if (!ResetEvent(op.event)) { Fail(s, GetLastError()); return false; }+ op.overlapped = {};+ // Low-bit tagging suppresses IOCP packets. This backend owns completion through+ // GetOverlappedResult only; there is no completion callback left to drain.+ op.overlapped.hEvent = reinterpret_cast<HANDLE>(+ reinterpret_cast<ULONG_PTR>(op.event) | ULONG_PTR{1});+ op.cancel_requested = false;+ return true;+}+void Cancel(Stream& s, Operation& op) noexcept {+ if (!op.pending || op.cancel_requested) return;+ op.cancel_requested = true;+ if (!CancelIoEx(s.owner.borrowed_handle(), &op.overlapped)) {+ DWORD error = GetLastError();+ if (error != ERROR_NOT_FOUND) Fail(s, error);+ }+ // Neither success nor ERROR_NOT_FOUND retires the operation.+}+bool Complete(Stream& s, Operation& op, DWORD& count, DWORD& error) noexcept {+ if (!op.pending || !HasOverlappedIoCompleted(&op.overlapped)) return false;+ if (GetOverlappedResult(s.owner.borrowed_handle(), &op.overlapped, &count, FALSE)) {+ error = ERROR_SUCCESS;+ } else {+ error = GetLastError();+ if (error == ERROR_IO_INCOMPLETE || error == ERROR_INVALID_HANDLE ||+ error == ERROR_INVALID_PARAMETER) {+ // A failed query is not definitive completion evidence. Keep exact state.+ if (error != ERROR_IO_INCOMPLETE) Fail(s, error);+ return false;+ }+ }+ op.pending = false;+ return true;+}+void ReadResult(Stream& s, DWORD count, DWORD error) noexcept {+ if (error == ERROR_OPERATION_ABORTED && s.phase != StreamPhase::open) return;+ if (error == ERROR_BROKEN_PIPE || error == ERROR_PIPE_NOT_CONNECTED ||+ (!error && !count)) {+ s.eof = true;+ s.phase = StreamPhase::stopping;+ s.abort = true;+ return;+ }+ if (error) { Fail(s, error); return; }+ if (count > kStreamReadBytes) { Fail(s, ERROR_INVALID_DATA); return; }+ if (s.phase == StreamPhase::open) { s.read_size = count; s.read_offset = 0; }+}+void Pop(Stream& s) noexcept {+ Write* item = s.head;+ s.head = item->next;+ if (!s.head) s.tail = nullptr;+ s.queued_bytes -= item->size;+ --s.queued_items;+ delete item;+}+void WriteResult(Stream& s, DWORD count, DWORD error) noexcept {+ if (error == ERROR_OPERATION_ABORTED && s.abort) return;+ if (error) { Fail(s, error); return; }+ Write& item = *s.head;+ if (!count || count > item.size - item.offset) { Fail(s, ERROR_WRITE_FAULT); return; }+ item.offset += count;+ if (item.offset == item.size) { s.completed = item.ticket; Pop(s); }+}+bool CloseEvent(Stream& s, Operation& op) noexcept {+ if (op.close_failed) return false;+ if (!op.event) return true;+ if (!CloseHandle(op.event)) {+ op.close_failed = true;+ if (!s.error) s.error = GetLastError();+ return false; // never retry an uncertain handle value+ }+ op.event = nullptr;+ return true;+}+void Finish(Stream& s) noexcept {+ if (s.read.pending || s.write.pending) return;+ if (!s.abort && s.head) return;+ while (s.head) Pop(s);+ s.read_size = s.read_offset = 0;+ // Attempt all independent closes, but never claim success on any failed close.+ bool read_closed = CloseEvent(s, s.read);+ bool write_closed = CloseEvent(s, s.write);+ bool owner_closed = s.owner.close();+ if (!owner_closed && !s.error) s.owner.close_failure(s.error);+ s.phase = read_closed && write_closed && owner_closed+ ? StreamPhase::closed : StreamPhase::retained_failure;+}+}+Stream* CreateStream(Adoption& adoption, DWORD& error) noexcept {+ error = ERROR_SUCCESS;+ if (adoption.startup_must_refuse() || !adoption.original_removed ||+ adoption.owner.borrowed_handle() == INVALID_HANDLE_VALUE) {+ error = ERROR_INVALID_DATA; return nullptr;+ }+ auto* s = new (std::nothrow) Stream(std::move(adoption.owner));+ if (!s) { error = ERROR_NOT_ENOUGH_MEMORY; return nullptr; }+ if (!InitEvent(*s, s->read) || !InitEvent(*s, s->write)) {+ error = s->error;+ Finish(*s);+ }+ return s;+}+WriteAdmission QueueStreamWrite(Stream* s, const void* bytes, size_t size,+ uint64_t& ticket) noexcept {+ ticket = 0;+ if (s->phase != StreamPhase::open) return WriteAdmission::stopped;+ if (!bytes || !size || size > kStreamQueueBytes || s->accepted == UINT64_MAX)+ return WriteAdmission::invalid;+ if (s->queued_items == kStreamQueueItems || size > kStreamQueueBytes - s->queued_bytes)+ return WriteAdmission::backpressure;+ auto* item = new (std::nothrow) Write;+ if (!item) return WriteAdmission::allocation_failed;+ item->bytes = new (std::nothrow) BYTE[size];+ if (!item->bytes) { delete item; return WriteAdmission::allocation_failed; }+ std::memcpy(item->bytes, bytes, size);+ item->size = size;+ ticket = item->ticket = ++s->accepted;+ if (s->tail) s->tail->next = item; else s->head = item;+ s->tail = item;+ s->queued_bytes += size;+ ++s->queued_items;+ return WriteAdmission::accepted;+}+void PollStream(Stream* s) noexcept {+ if (s->phase == StreamPhase::closed || s->phase == StreamPhase::retained_failure) return;+ DWORD count = 0, error = 0;+ if (Complete(*s, s->read, count, error)) ReadResult(*s, count, error);+ if (Complete(*s, s->write, count, error)) WriteResult(*s, count, error);+ if (s->phase == StreamPhase::stopping) {+ Cancel(*s, s->read);+ if (s->abort) Cancel(*s, s->write);+ Finish(*s);+ if (s->phase != StreamPhase::stopping) return;+ }+ if (s->phase == StreamPhase::open && !s->read.pending && !s->read_size &&+ Prepare(*s, s->read)) {+ BOOL success = ReadFile(s->owner.borrowed_handle(), s->bytes,+ static_cast<DWORD>(kStreamReadBytes), nullptr, &s->read.overlapped);+ DWORD result = success ? ERROR_SUCCESS : GetLastError();+ if (success || result == ERROR_IO_PENDING) s->read.pending = true;+ else ReadResult(*s, 0, result);+ }+ if (!s->abort && s->head && !s->write.pending && Prepare(*s, s->write)) {+ Write& item = *s->head;+ BOOL success = WriteFile(s->owner.borrowed_handle(), item.bytes + item.offset,+ static_cast<DWORD>(item.size - item.offset), nullptr,+ &s->write.overlapped);+ DWORD result = success ? ERROR_SUCCESS : GetLastError();+ if (success || result == ERROR_IO_PENDING) s->write.pending = true;+ else WriteResult(*s, 0, result);+ }+ // Synchronous success still goes through completion retrieval on the next poll.+ // No buffer or OVERLAPPED is recycled merely because initiation returned true.+}+size_t TakeStreamRead(Stream* s, void* destination, size_t capacity) noexcept {+ if (s->phase != StreamPhase::open || !destination || !capacity) return 0;+ size_t available = s->read_size - s->read_offset;+ size_t count = capacity < available ? capacity : available;+ std::memcpy(destination, s->bytes + s->read_offset, count);+ s->read_offset += count;+ if (s->read_offset == s->read_size) s->read_offset = s->read_size = 0;+ return count;+}+StreamStatus InspectStream(const Stream* s) noexcept {+ return {s->phase, s->error, s->eof, s->read.pending || s->write.pending,+ s->read_size - s->read_offset, s->queued_bytes, s->queued_items,+ s->accepted, s->completed};+}+void StopStream(Stream* s, StopMode mode) noexcept {+ if (s->phase == StreamPhase::closed || s->phase == StreamPhase::retained_failure) return;+ s->phase = StreamPhase::stopping;+ if (mode == StopMode::abort) s->abort = true;+ Cancel(*s, s->read);+ if (s->abort) Cancel(*s, s->write);+}+void ReleaseStream(Stream* s) noexcept {+ if (!s) return;+ StopStream(s, StopMode::abort);+ PollStream(s);+ if (s->phase == StreamPhase::closed) delete s;+ else Retain(s); // no destructor may violate Owner's fully-drained precondition+}+} // namespace gentle_dot::app_channeldiff --git a/packages/daemon/native/windows-app-channel-stream.h b/packages/daemon/native/windows-app-channel-stream.hnew file mode 100644index 0000000..6f90b1d--- /dev/null+++ b/packages/daemon/native/windows-app-channel-stream.h@@ -0,0 +1,59 @@+#pragma once+#include "windows-app-channel.h"+#include <cstddef>+#include <cstdint>++namespace gentle_dot::app_channel {+// Native-only opaque heap owner. All calls (including release) must be serialized+// on one host-loop thread; no callbacks, worker, N-API environment or CRT alias.+// A later adapter must adopt/create before ANY spawn, refuse failed startup, drive+// poll on its existing loop, and stop then await closed before resolving close.+struct Stream;+constexpr size_t kStreamReadBytes = 64 * 1024;+constexpr size_t kStreamQueueBytes = 2 * 1024 * 1024;+constexpr size_t kStreamQueueItems = 64;+enum class StreamPhase { open, stopping, closed, retained_failure };+enum class WriteAdmission { accepted, backpressure, stopped, invalid, allocation_failed };+enum class StopMode { drain_writes, abort };+struct StreamStatus {+ StreamPhase phase;+ DWORD error; // first native error; no handle or rendered secrets+ bool eof;+ bool pending_io;+ size_t readable_bytes;+ size_t queued_bytes; // includes whole partially-written head allocation+ size_t queued_items;+ uint64_t accepted_write;+ uint64_t completed_write; // highest fully delivered ordered ticket, not peer ACK+};+// Consumes adoption.owner only after successful validation and heap allocation.+// Null returns ERROR_INVALID_DATA/ERROR_NOT_ENOUGH_MEMORY via error and leaves+// adoption untouched. Non-null may report initialization failure: stop/poll/release+// it too, and refuse startup whenever error is nonzero. Adoption must be the+// successful exclusive fd3 transaction, not a handle. Every other function except+// release requires a non-null live Stream from this call.+Stream* CreateStream(Adoption& adoption, DWORD& error) noexcept;+// Copy all-or-nothing. Non-accepted calls retain no bytes and issue no ticket.+// Zero size is invalid. Max single write is kStreamQueueBytes. Retry backpressure+// only after queued capacity drops. Accepted writes remain ordered across partial+// completions; completion state, rather than callbacks, settles adapter promises.+// Tickets above completed_write must be rejected on abort/error/terminal EOF;+// successful native close alone does not mean all accepted writes were delivered.+WriteAdmission QueueStreamWrite(Stream*, const void*, size_t, uint64_t& ticket) noexcept;+// Each poll performs at most one completion/issue per direction, never waits.+// Reading pauses while a completed chunk is buffered (bounded read backpressure).+void PollStream(Stream*) noexcept;+size_t TakeStreamRead(Stream*, void* destination, size_t capacity) noexcept;+StreamStatus InspectStream(const Stream*) noexcept;+// Rejects further writes immediately. Drain writes preserves queued order, then+// cancels the outstanding read; abort cancels both and discards undelivered bytes+// only AFTER definitive completion. Drain may be escalated to abort, never reversed.+void StopStream(Stream*, StopMode) noexcept;+// No deadline is a reclamation guarantee. Adapter timeout may reject and continue+// polling, or release: release requests abort and quarantines any uncertain state+// until process exit without retry, wait, thread join, forced exit or callbacks.+// closed means pending I/O is drained AND event/Owner closes succeeded. A prior+// error remains observable even when resources subsequently close successfully.+// No operation is legal after release. Never report retained_failure as success.+void ReleaseStream(Stream*) noexcept;+} // namespace gentle_dot::app_channeldiff --git a/packages/daemon/native/windows-app-channel.cc b/packages/daemon/native/windows-app-channel.ccnew file mode 100644index 0000000..03273fa--- /dev/null+++ b/packages/daemon/native/windows-app-channel.cc@@ -0,0 +1,211 @@+#include "windows-app-channel.h"+#include <winternl.h>+#include <uv.h>+#include <atomic>+#include <new>++namespace gentle_dot::app_channel {+struct OwnerState {+ HANDLE handle = INVALID_HANDLE_VALUE;+ DWORD close_error = ERROR_SUCCESS;+ bool close_failed = false;+ OwnerState* next = nullptr;+};+namespace {+// Failed CloseHandle leaves ownership uncertain. Keep the exact owned duplicate+// and its preallocated record reachable until process exit; never retry it from+// a worker or a static destructor. The borrowed host CRT handle never enters here.+std::atomic<OwnerState*> quarantine{nullptr};+static_assert(std::atomic<OwnerState*>::is_always_lock_free,+ "Quarantine publication must not require allocated lock state");+void Quarantine(OwnerState* state) noexcept {+ OwnerState* head = quarantine.load(std::memory_order_relaxed);+ do {+ state->next = head;+ } while (!quarantine.compare_exchange_weak(head, state,+ std::memory_order_release, std::memory_order_relaxed));+}++// These two information classes/structures are the NT file-query ABI used by+// libuv's Windows pipe adoption. Some Windows SDK winternl.h versions omit the+// named declarations. Use private layouts and explicit class values, never an+// SDK-wide redefinition. IO_STATUS_BLOCK and FILE_INFORMATION_CLASS use SDK types.+struct AccessInformation { ACCESS_MASK flags; }; // FileAccessInformation = 8+struct ModeInformation { ULONG mode; }; // FileModeInformation = 16+constexpr ULONG kSynchronousAlert = 0x10;+constexpr ULONG kSynchronousNonalert = 0x20;+constexpr ACCESS_MASK kReadData = 0x1;+constexpr ACCESS_MASK kWriteData = 0x2;+using QueryFile = NTSTATUS (NTAPI*)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG,+ FILE_INFORMATION_CLASS);++// Use only the host Node/libuv CRT wrapper, including its invalid-descriptor+// handling. Never use this addon's CRT _get_osfhandle/_close. In particular the+// host wrapper, not uv_pipe_open or a raw CRT lookup, verifies removal of fd3.+HANDLE HostFd3() noexcept {+ return reinterpret_cast<HANDLE>(uv_get_osfhandle(3));+}+bool Valid(HANDLE handle) noexcept {+ return handle != nullptr && handle != INVALID_HANDLE_VALUE;+}+bool Noninheritable(HANDLE handle) noexcept {+ DWORD flags = 0;+ return GetHandleInformation(handle, &flags) && !(flags & HANDLE_FLAG_INHERIT);+}+} // namespace++Owner::~Owner() noexcept {+ // Same fully-drained/no-concurrent-use precondition as explicit close(). No+ // allocation, forced exit, or lost ownership on failure during local unwinding.+ if (!close()) {+ Quarantine(state_);+ state_ = nullptr;+ }+}+Owner::Owner(Owner&& other) noexcept : state_(other.state_) {+ other.state_ = nullptr;+}+HANDLE Owner::borrowed_handle() const noexcept {+ return state_ ? state_->handle : INVALID_HANDLE_VALUE;+}+bool Owner::close_failure(DWORD& error) const noexcept {+ const bool failed = state_ && state_->close_failed;+ error = failed ? state_->close_error : ERROR_SUCCESS;+ return failed;+}+bool Owner::close() noexcept {+ if (!state_) return true;+ if (state_->close_failed) return false; // Never retry an uncertain handle value.+ if (Valid(state_->handle) && !CloseHandle(state_->handle)) {+ state_->close_error = GetLastError();+ state_->close_failed = true;+ return false; // Keep the state and handle in this owner for caller disposition.+ }+ delete state_;+ state_ = nullptr;+ return true;+}++Adoption AdoptInheritedFd3(ExclusiveFd3Reservation) noexcept {+ Adoption result;+ auto fail = [&](Failure failure, DWORD error = ERROR_SUCCESS) {+ result.failure = failure;+ result.win32_error = error;+ };+ // Detect the standard Node bootstrap IPC collision where visible. Environment+ // absence is not proof of exclusivity: bootstrap can consume/delete this value.+ wchar_t ipc[32] = {};+ SetLastError(ERROR_SUCCESS);+ DWORD length = GetEnvironmentVariableW(L"NODE_CHANNEL_FD", ipc, 32);+ if (length == 0 && GetLastError() != ERROR_ENVVAR_NOT_FOUND &&+ GetLastError() != ERROR_SUCCESS) {+ fail(Failure::environment_query, GetLastError());+ return result;+ }+ if (length != 0) {+ if (length >= 32) {+ fail(Failure::environment_query, ERROR_INVALID_DATA); return result;+ }+ unsigned long long descriptor = 0;+ for (DWORD i = 0; i < length; ++i) {+ if (ipc[i] < L'0' || ipc[i] > L'9' || descriptor > 214748364ULL) {+ fail(Failure::environment_query, ERROR_INVALID_DATA); return result;+ }+ descriptor = descriptor * 10 + (ipc[i] - L'0');+ }+ if (descriptor == 3) {+ fail(Failure::node_ipc_collision); return result;+ }+ }+ HANDLE original = HostFd3(); // borrowed: never pass this to CloseHandle+ if (!Valid(original)) { fail(Failure::missing_fd3); return result; }+ if (GetFileType(original) != FILE_TYPE_PIPE) {+ fail(Failure::not_pipe, GetLastError()); return result;+ }+ DWORD flags = 0, state = 0;+ if (!GetNamedPipeInfo(original, &flags, nullptr, nullptr, nullptr) ||+ !GetNamedPipeHandleStateW(original, &state, nullptr, nullptr, nullptr, nullptr, 0)) {+ fail(Failure::pipe_metadata, GetLastError()); return result;+ }+ if ((flags & (PIPE_SERVER_END | PIPE_TYPE_MESSAGE)) || (state & PIPE_READMODE_MESSAGE)) {+ fail(Failure::not_byte_client); return result;+ }+ ULONG server_pid = 0, client_pid = 0;+ if (!GetNamedPipeServerProcessId(original, &server_pid) ||+ !GetNamedPipeClientProcessId(original, &client_pid)) {+ fail(Failure::connection_identity, GetLastError()); return result;+ }+ if (!server_pid || !client_pid) {+ fail(Failure::connection_identity); return result;+ }+ // Do not require client_pid == Node PID: the parent creates both endpoints.+ HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");+ auto query = ntdll ? reinterpret_cast<QueryFile>(+ GetProcAddress(ntdll, "NtQueryInformationFile")) : nullptr;+ if (!query) { fail(Failure::nt_query_unavailable, GetLastError()); return result; }+ // Neither query has an enforced startup deadline. Even the mode query can+ // block on a synchronous handle; exclusive reservation prohibits prior I/O.+ IO_STATUS_BLOCK status = {};+ ModeInformation mode = {};+ result.nt_status = query(original, &status, &mode, sizeof(mode),+ static_cast<FILE_INFORMATION_CLASS>(16));+ if (result.nt_status != 0 || status.Status != 0 || status.Information != sizeof(mode)) {+ fail(Failure::mode_query); return result;+ }+ if (mode.mode & (kSynchronousAlert | kSynchronousNonalert)) {+ fail(Failure::synchronous_handle); return result;+ }+ status = {};+ AccessInformation access = {};+ result.nt_status = query(original, &status, &access, sizeof(access),+ static_cast<FILE_INFORMATION_CLASS>(8));+ if (result.nt_status != 0 || status.Status != 0 || status.Information != sizeof(access)) {+ fail(Failure::access_query); return result;+ }+ if ((access.flags & (kReadData | kWriteData)) != (kReadData | kWriteData)) {+ fail(Failure::not_duplex); return result;+ }++ // Reserve the failure-retention record before acquisition or mutation. An+ // allocation failure is an ordinary failed adoption, not noexcept termination.+ result.owner.state_ = new (std::nothrow) OwnerState;+ if (!result.owner.state_) {+ fail(Failure::owner_allocation, ERROR_NOT_ENOUGH_MEMORY); return result;+ }+ // Independently retain this translation unit and its quarantine root before+ // the first handle mutation/acquisition. This irreversible process-lifetime+ // pin remains even if later adoption fails; it never depends on the stop API.+ HMODULE module = nullptr;+ if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN,+ reinterpret_cast<LPCWSTR>(&AdoptInheritedFd3), &module)) {+ fail(Failure::module_pin, GetLastError()); return result;+ }+ // All validation precedes the ownership mutation. No spawn may run on either+ // success or failure until the caller has inspected this transaction result.+ if (!SetHandleInformation(original, HANDLE_FLAG_INHERIT, 0) || !Noninheritable(original)) {+ fail(Failure::original_inheritance, GetLastError()); return result;+ }+ HANDLE duplicate = INVALID_HANDLE_VALUE;+ if (!DuplicateHandle(GetCurrentProcess(), original, GetCurrentProcess(),+ &duplicate, 0, FALSE, DUPLICATE_SAME_ACCESS)) {+ fail(Failure::duplication, GetLastError()); return result;+ }+ result.owner.state_->handle = duplicate; // account for ownership immediately+ if (!Noninheritable(duplicate)) {+ fail(Failure::duplicate_inheritance, GetLastError()); return result;+ }+ uv_fs_t request = {};+ result.uv_error = uv_fs_close(nullptr, &request, 3, nullptr);+ uv_fs_req_cleanup(&request);+ if (result.uv_error != 0) {+ fail(Failure::host_close); return result;+ }+ if (Valid(HostFd3())) {+ fail(Failure::descriptor_still_present); return result;+ }+ result.original_removed = true;+ // The original CRT entry is gone; only the noninheritable RAII duplicate is+ // retained here. Successful adoption still does NOT enable privileged JS IPC.+ return result;+}+} // namespace gentle_dot::app_channeldiff --git a/packages/daemon/native/windows-app-channel.h b/packages/daemon/native/windows-app-channel.hnew file mode 100644index 0000000..843ada0--- /dev/null+++ b/packages/daemon/native/windows-app-channel.h@@ -0,0 +1,72 @@+#pragma once+#define WIN32_LEAN_AND_MEAN+#define NOMINMAX+#include <windows.h>++namespace gentle_dot::app_channel {+// Ownership foundation only: no stream, JS acquisition, or export is implemented.+// Before calling, the startup caller must exclusively reserve host CRT fd3:+// no Node IPC/stream adoption, concurrent descriptor operations, outstanding I/O,+// CRT aliases, or other inheritable copies of this privileged endpoint. Neither+// pipe names nor creator PIDs authenticate a signed parent. The inherited+// connection is authority; a parent-created client legitimately has the parent's PID.+// The caller must run this transaction before ANY descendant spawn. A failed+// result binds startup refusal (even if the original descriptor remains open).+// Before ownership mutation, adoption independently pins this addon until process+// exit so quarantined owners/code survive unload attempts. The pin is irreversible,+// including on later adoption failure; no stop-listener construction is required.+struct ExclusiveFd3Reservation {};+struct Adoption;+struct OwnerState;++class Owner final {+ public:+ Owner() noexcept = default;+ ~Owner() noexcept;+ Owner(const Owner&) = delete;+ Owner& operator=(const Owner&) = delete;+ Owner(Owner&& other) noexcept;+ Owner& operator=(Owner&&) = delete;+ // Native-only borrowed access for a later stream unit. Never expose to JS or+ // close this handle elsewhere. Both explicit close AND destruction require all+ // future I/O and completions fully drained, with no concurrent borrowed-handle+ // use. This foundation issues no I/O and implements no drain operation.+ HANDLE borrowed_handle() const noexcept;+ // Failure retains ownership; callers must refuse startup/shutdown completion.+ // Later close calls remain failed without retrying the uncertain handle value.+ // If destruction then fails to close, preallocated state and the uncertain+ // owned handle enter process-lifetime quarantine without allocation or retry.+ // Each such failure retains one state and one handle until process exit.+ bool close() noexcept;+ // True only for a recorded close failure; error is its exact sticky Win32 code.+ // Otherwise sets error to ERROR_SUCCESS. Never closes or queries ambient error.+ bool close_failure(DWORD& error) const noexcept;+ private:+ friend struct Adoption;+ friend Adoption AdoptInheritedFd3(ExclusiveFd3Reservation) noexcept;+ OwnerState* state_ = nullptr;+};++enum class Failure {+ none, node_ipc_collision, environment_query, missing_fd3, not_pipe,+ pipe_metadata, not_byte_client, connection_identity, nt_query_unavailable,+ mode_query, synchronous_handle, access_query, not_duplex,+ owner_allocation, module_pin, original_inheritance, duplication, duplicate_inheritance,+ host_close, descriptor_still_present+};++struct Adoption {+ Owner owner;+ Failure failure = Failure::none;+ // Domain-specific evidence, not a rendered message or raw handle exposure.+ DWORD win32_error = ERROR_SUCCESS;+ LONG nt_status = 0;+ int uv_error = 0;+ // Never retry a close by descriptor number after this call. On close failure+ // fd3's state is uncertain; an unrelated descriptor could subsequently reuse 3.+ bool original_removed = false;+ bool startup_must_refuse() const noexcept { return failure != Failure::none; }+};++Adoption AdoptInheritedFd3(ExclusiveFd3Reservation) noexcept;+} // namespace gentle_dot::app_channel