Skip to content

feat(service): checked Windows stop primitives and operations, unwired (#7771 slice 1) - #8564

Merged
lidge-jun merged 5 commits into
devfrom
feat/windows-checked-stop-primitives-2
Nov 11, 2026
Merged

lidge-jun merged 5 commits into
devfrom
feat/windows-checked-stop-primitives-2

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

Summary

Slice 1 of 3 for #7771 Option B, the owner-approved design in devlog/_plan/261111_windows_service_stop/ (030 is the contract). It adds the checked Windows stop as tested library code. Nothing calls it yet, so behavior is unchanged on every platform; slice 2 wires the callers, and slice 3 (Desktop, #8560) is merged.

Module What it does
src/service/windows-process-native.ts Windows x64 Bun FFI, loaded only from resolveTrustedWindowsSystemDirectory() under the #8487 rules. It reads a process creation time (GetProcessTimes). The terminate opens the process, reads the creation time on that same handle, refuses a mismatch as reused, then calls TerminateProcess on the same handle and closes it in finally. Also an exit watch opened at bind time and the Schedule service PID (QueryServiceStatusEx). Returns null on ARM64 and whenever a test simulates the platform.
src/service/windows-process-evidence.ts One CIM process snapshot with CreationDate. On x64 a native creation time is kept only when it matches CIM to the millisecond, so a PID reused between the two reads counts as unreadable. Also a capped sc.exe queryex Schedule fallback, and the ARM64 PowerShell terminate (StartTime within 1 s, then Kill() on the same object).
src/service/windows-stop-binding.ts The 030 binding rule as a pure function: only wscript.exe, cscript.exe and cmd.exe carrying this home's launcher or service-script path as a whole token, bound by lineage (ancestor of the identity-checked child, child of a bound wrapper, parent gone only while this home's task is registered, or the Schedule service host), with a creation time. The proxy child is never a target. Unreadable candidates make the result unknown; they are never skipped or killed.
src/service/windows-stop-budget.ts The step caps, the admission arithmetic and the Part B window.
src/service/windows-checked-stop.ts Part A, stopWindowsServiceChecked. Every effect is injected; every step is capped except the exit-watch open and the updater authorizer, which run inside the shared terminate window (recorded in 060). Admission runs after the registration probe and returns unverified-budget, changing nothing, when the remaining deadline cannot hold the rest. Outcomes: absent / stopped / survived / denied / unknown, with a reason and the bound set. guardedStopWindowsServiceChecked (for the updater) re-authorizes before each terminate.
src/service/windows-stop-confirm.ts Part B, confirmWindowsStopFreed: the port stays free for a 6 s hold, then a final enumeration catches a relaunched wrapper. A remaining listener is classified as ours, foreign, or an exited owner (not foreign).

Two recorded departures from 030's numbers and wording:

  • Part B's last sample: the last port check can run up to 0.5 s past the 6 s window, and the budget counts it. The admission minimums become 48.5 / 56.5 / 42.5 s; the Desktop exit drain still fits its 72 s, at 70.5 s.
  • An unbound wrapper with nothing registered reports survived / unbound-wrapper, as 040 specifies.

ARM64: the bounded PowerShell fallback exists, but per 050, with no ARM64 device run, slice 2 ships ARM64 with the strict variant (kill nothing, report unknown).

Docs: new structure/ops/windows-checked-stop.md (linked from runtime.md, manifest and INDEX regenerated), and devlog/_plan/261111_windows_service_stop/060_implementation.md with the slice plan.

Refs #7771.

Verification

  • New hermetic tests in tests/windows/ use only an injected platform, injected effects and a virtual clock (no real schtasks, PowerShell or FFI calls): 72 pass, 2 skip (the live Windows x64 FFI cases, which run on the Windows lane), 0 fail, including one test per fail-closed rule (unreadable parent never binds; registered + unreadable parent is unknown; terminate overrun is unknown with no further kill; unreadable task or WinSW state is unknown; unreadable stray candidate is unknown; denied exit watch is denied; the child-ancestor lineage clause binds on its own; an unnamed-image listener is unknown), each shown to fail when its rule is mutated, and a regression test that fractional deadline-derived timeouts are floored before the fallback runs. They cover each 040 bullet for these modules: binding positives and negatives, PID reuse leaving the process untouched, denied stopping every further kill, unreadable evidence giving unknown with nothing killed, a stray wrapper with the task not running, an orphan bound only while registered, WinSW survived, caps giving unknown, admission refusal changing nothing, Part B catching a late relaunch, ours vs foreign, and a ghost listener.
  • Fail-first: with the modules absent every test file fails. Breaking the orphan, denied and late-relaunch rules one at a time fails exactly the intended tests.
  • Existing Windows service suites (guarded manager, process-state, winsw, wrappers, scheduler, stop-deferred-teardown, service): 584 pass, 31 skip, 0 fail. bun run test:changed selects only the new files, so nothing imports the modules yet.
  • bun run typecheck, bun run privacy:scan, bun run structure:check, test-layout, Lab boundary and file-size ratchet: pass (rebased on current dev).

NOT RUN: Windows real device and ARM64; the live FFI tests on this host (Windows CI lane only); full bun run test (nothing calls the new code).

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed.
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.

…wired

Adds the library half of #7771 option B as tested code that nothing calls yet,
so behavior is unchanged on every platform:

- windows-process-native: x64 FFI from the trusted system directory for the
  process creation time (GetProcessTimes), a handle terminate that compares the
  creation time on the same handle it terminates, a bind-time exit watch, and the
  Task Scheduler service PID (QueryServiceStatusEx).
- windows-process-evidence: the CIM snapshot with creation times (native times
  kept only when they agree with CIM to the ms), an sc.exe queryex fallback, and
  the bounded ARM64 PowerShell terminate (StartTime check within 1 s, Kill() on the
  same object, exit read back).
- windows-stop-binding: the 030 binding rule as a pure function.
- windows-stop-budget: the caps and the admission arithmetic, including the 0.5 s
  closing port sample part B can take past its window (48.5 / 56.5 / 42.5 s).
- windows-checked-stop: part A with every effect injected, admission after the
  registration probe, and the authorizer-gated variant for the updater.
- windows-stop-confirm: part B (6 s hold, final enumeration, ours vs foreign vs
  exited-owner listener) and the port resolution order.

Contract in structure/ops/windows-checked-stop.md; slice plan and the points
where this differs from 030 in devlog/_plan/261111_windows_service_stop/060.

Refs #7771
@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner November 11, 2026 16:16
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T16:20:07.871785Z c4456bd PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

✅ Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added the enhancement New feature or request label Nov 11, 2026
@coderabbitai

coderabbitai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

This change adds Windows process-evidence primitives, wrapper-binding rules, checked manager-stop and port-confirmation operations, and associated tests and documentation. The new operations use bounded execution and return outcomes based on process and manager evidence. Existing stop paths do not call them.

Changes: Windows Checked Service Stop

Layer / File(s) Summary
Process identity evidence
src/service/windows-process-native.ts, src/service/windows-process-evidence.ts, tests/windows/windows-process-evidence.test.ts, structure/ops/windows-checked-stop.md
Adds native x64 process identity, termination, exit-watch, and Task Scheduler PID primitives. Adds bounded command-based snapshot and termination fallbacks, with tests for native and fallback behavior.
Wrapper binding and stop budgets
src/service/windows-stop-binding.ts, src/service/windows-stop-budget.ts, tests/windows/windows-stop-binding.test.ts, tests/windows/windows-checked-stop.test.ts, structure/ops/windows-checked-stop.md
Adds path and lineage checks for wrapper candidates, deepest-first binding, and stop-budget calculations. Tests cover binding rules and budget limits.
Checked manager-stop workflow
src/service/windows-checked-stop.ts, tests/helpers/windows-checked-stop-fixtures.ts, tests/windows/windows-checked-stop.test.ts, scripts/test-layout/layout.json, tests/fixtures/test-layout-expected.json, devlog/_plan/261111_windows_service_stop/*, structure/INDEX.md, structure/manifest.json, structure/ops/windows-checked-stop.md, structure/runtime.md
Adds injected, capped manager-stop operations with authorization checks, identity-bound wrapper termination, and post-stop verification. Tests cover outcome, timing, admission, and refusal cases. The plan and documentation state that caller wiring remains for later work.
Port-release confirmation
src/service/windows-stop-confirm.ts, tests/windows/windows-stop-confirm.test.ts, structure/ops/windows-checked-stop.md
Adds bounded port sampling and final process checks. Outcomes distinguish a free port, a foreign listener, a surviving local listener or wrapper, and incomplete or unreadable evidence.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Stop as stopWindowsServiceChecked
  participant Deps as WindowsCheckedStopDeps
  participant Binding as bindWindowsStopWrappers
  participant Process as Windows process evidence
  Stop->>Deps: Probe manager registration and enumerate processes
  Stop->>Binding: Bind eligible wrappers from process evidence
  Stop->>Deps: Request registered manager stop
  Stop->>Process: Terminate bound wrappers and watch for exit
  Stop->>Deps: Read manager state for final verification
Loading

Possibly related issues

  • Issue 7771 describes a Windows service-wrapper case where a wrapper can relaunch the proxy and keep port 10100 occupied. This change adds checked-stop and port-confirmation operations for that case, but does not wire them to callers.
  • Issue 8545 concerns safe restart and disconnect when runtime ownership cannot be proven. This change adds Windows process evidence, PID-reuse checks, wrapper binding, and checked-stop outcomes, but does not wire them to restart or disconnect callers.

Possibly related PRs

  • lidge-jun/opencodex#8546: Defines the Windows stop contract implemented by these primitives, including manager-first stopping, identity-bound termination, bounded verification, and port confirmation.
  • lidge-jun/opencodex#8560: Implements the later Desktop slice described in this change’s plan, including the Windows drain deadline and readers for stop-result fields.

Suggested labels: enhancement

Pre-merge checks: Passed 2

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly identifies the main change: adding checked Windows stop primitives and operations that remain unwired in slice 1.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c4456bda7f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/service/windows-process-evidence.ts Outdated
Comment on lines +266 to +270
const exitWaitMs = Math.max(0, Math.min(FALLBACK_TERMINATE_EXIT_WAIT_MS, options.timeoutMs - 500));
try {
return parseFallbackTerminateOutput(await run({
program: "powershell",
args: powershellArgs(windowsFallbackTerminateScript(pid, boundStartTime, exitWaitMs)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize deadline-derived timeouts before spawning the fallback

When the spawned terminate fallback is used, Part A passes windowEnd - clock.now() through runCapped, so the real performance.now() clock normally produces a fractional timeout. The default runner forwards that directly to execFile, which rejects non-integer timeouts before spawning PowerShell. With less than 1.5 seconds remaining, the computed exitWaitMs also becomes fractional and fails windowsFallbackTerminateScript's integer validation; passing timeoutMs: 1250.5 reproduces unavailable without invoking even an injected runner. Thus the fallback can leave bound wrappers running despite having time available. Floor the positive remaining timeout and derived exit wait to integer milliseconds before constructing the script and invoking the runner.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid; being fixed in this PR: positive remaining timeouts and derived exit waits are floored to integer milliseconds before the fallback script is built and the runner is called, with a regression test.

A cap derived from the deadline (windowEnd - now) is fractional on the
real clock. execFile and windowsFallbackTerminateScript take whole
milliseconds, so the spawned fallback answered unavailable. Floor the
timeout and the derived exit wait, and spawn nothing when it floors to 0,
which execFile would read as no timeout.

Refs #7771
One test per fail-closed branch, each shown to fail when its rule is
mutated: an unreadable parent PID never binds and, with the task
registered, is unreadable; the child-ancestor lineage clause binds on its
own; a terminate overrun, an unreadable task or WinSW state, an
unreadable stray candidate and a denied bind-time watch end Part A as
unknown or denied; an unnamed image carrying this home's path is unknown
in Part B.

Refs #7771
ARM64 ships the strict variant in slice 2 and its adapter must gate it,
because terminateWindowsProcessBound falls back to PowerShell on its own.
Record the Schedule PID read before admission, that openWatch and the
authorizer are not capped, and the route's need for an outer race.

Refs #7771
@lidge-jun

Copy link
Copy Markdown
Owner Author

Maintainer judgment (#7771 Option B, slice 1: checked Windows stop primitives)

  • Value: adds the parts of the owner-approved Option B design that do the risky work: the binding rule that decides which processes may be ended, a terminate that checks the process creation time on the same handle it terminates with, Part A (manager and wrapper stop) and Part B (the port stays free), and the time budget. Slice 2 wires them into ocx stop, /api/stop, service stop/uninstall/install and the updater.
  • UX change: none in this PR. Nothing calls the new modules (test:changed selects only the new tests).
  • Regression evidence for existing users: no existing code path changed. The existing Windows service suites still pass (584 pass, 31 skip). The new hermetic tests (75 pass, 2 skip) pin every applicable 040 bullet and each fail-closed rule, including the unavailable watch and terminate paths. Each rule's test was shown to fail when that rule is mutated, by the implementer, the coordinator and the reviewers.
  • Windows impact: Windows-only code. On x64 it uses Bun FFI loaded from the trusted system directory: kernel32 OpenProcess/GetProcessTimes/TerminateProcess on one handle, and advapi32 for the Schedule service PID. The only processes that can ever be bound for termination are wscript.exe, cscript.exe and cmd.exe carrying this home's launcher or service-script path; the proxy child never is. Unreadable or denied evidence ends with nothing killed. On ARM64 the bounded PowerShell fallback exists but stays unreachable: per 050, slice 2 ships the strict variant until an ARM64 device run.
  • Verification scope: fresh independent general review APPROVE and separate fresh security review SECURITY APPROVE, both on the exact head 4046d43c6c, after three review rounds. Typecheck, privacy, structure, layout and file-size gates pass.
  • NOT RUN (Windows): a real Windows device (the 040 matrix: /end leaving the loop alive, restart-on-failure behavior, an elevated task seen from an unelevated shell, npm vs bundled runtime, logon/unlock triggers, WinSW, slow startup and antivirus, ARM64); the two live x64 FFI tests, including the GetLastError mapping (Windows CI lane only); full bun run test. PR CI had no failures on this head at merge time.

@lidge-jun
lidge-jun merged commit 4ed97f1 into dev Nov 11, 2026
33 checks passed
@lidge-jun
lidge-jun deleted the feat/windows-checked-stop-primitives-2 branch November 11, 2026 16:38
lidge-jun added a commit that referenced this pull request Nov 13, 2026
 slice 2) (#8573)

* feat(service): add checked Windows stop primitives and operations, unwired

Adds the library half of #7771 option B as tested code that nothing calls yet,
so behavior is unchanged on every platform:

- windows-process-native: x64 FFI from the trusted system directory for the
  process creation time (GetProcessTimes), a handle terminate that compares the
  creation time on the same handle it terminates, a bind-time exit watch, and the
  Task Scheduler service PID (QueryServiceStatusEx).
- windows-process-evidence: the CIM snapshot with creation times (native times
  kept only when they agree with CIM to the ms), an sc.exe queryex fallback, and
  the bounded ARM64 PowerShell terminate (StartTime check within 1 s, Kill() on the
  same object, exit read back).
- windows-stop-binding: the 030 binding rule as a pure function.
- windows-stop-budget: the caps and the admission arithmetic, including the 0.5 s
  closing port sample part B can take past its window (48.5 / 56.5 / 42.5 s).
- windows-checked-stop: part A with every effect injected, admission after the
  registration probe, and the authorizer-gated variant for the updater.
- windows-stop-confirm: part B (6 s hold, final enumeration, ours vs foreign vs
  exited-owner listener) and the port resolution order.

Contract in structure/ops/windows-checked-stop.md; slice plan and the points
where this differs from 030 in devlog/_plan/261111_windows_service_stop/060.

Refs #7771

* fix(service): floor fractional timeouts in the terminate fallback

A cap derived from the deadline (windowEnd - now) is fractional on the
real clock. execFile and windowsFallbackTerminateScript take whole
milliseconds, so the spawned fallback answered unavailable. Floor the
timeout and the derived exit wait, and spawn nothing when it floors to 0,
which execFile would read as no timeout.

Refs #7771

* test(service): pin each fail-closed rule of the checked Windows stop

One test per fail-closed branch, each shown to fail when its rule is
mutated: an unreadable parent PID never binds and, with the task
registered, is unreadable; the child-ancestor lineage clause binds on its
own; a terminate overrun, an unreadable task or WinSW state, an
unreadable stray candidate and a denied bind-time watch end Part A as
unknown or denied; an unnamed image carrying this home's path is unknown
in Part B.

Refs #7771

* docs(service): record the ARM64 decision and the uncapped steps

ARM64 ships the strict variant in slice 2 and its adapter must gate it,
because terminateWindowsProcessBound falls back to PowerShell on its own.
Record the Schedule PID read before admission, that openWatch and the
authorizer are not capped, and the route's need for an outer race.

Refs #7771

* feat(service): wire the checked Windows stop into every stop path

Every Windows stop path now uses the checked stop from #8564 (part A ends the
manager and the wrappers it can bind; part B confirms the port stays free):

- stopServiceIfInstalledDetailed / stopServiceIfInstalledReport are async and
  run part A on Windows; Task Scheduler no longer reports stopped-respawnable.
- Plain ocx stop: a part A outcome other than stopped/absent sends no
  /api/stop POST, blocks the shared teardown and records service failed (or
  state-unknown), proxy unknown. After a stopped part A, part B replaces the
  respawn re-poll and the POST skips stopProxy's port wait; orphan discovery is
  capped at 3 s. The receipt carries the part A record.
- Guarded (consent) path: the inspection reads windowsProcessSnapshot and the
  Schedule PID once, a not-running task with wrappers the binding rule ties to
  the approved PID is bound-stray (revalidation compares the wrapper set), part
  A binds on the revalidation's snapshot before signalApproved, and part B runs
  after settle.
- ocx stop --deadline-ms <n> and OCX_STOP_DEADLINE_MS (flag wins, empty or
  invalid is absent, 60 s default), measured from process start; admission
  refuses with unverified-budget before anything changes.
- /api/stop skips part A for a receipt whose part A record names the
  registered managers, caps it at 6 s otherwise and sweeps a deleted task's
  stray wrapper in 4 s; WinSW keeps its in-process stop.
- ocx service stop claims a teardown receipt before the deferred child stop and
  completes it after part B and the restore; service uninstall/remove and
  prepareServiceInstall refuse before deleting or replacing the task; install
  and switch stop when another program holds the port; ocx uninstall runs part
  B as its respawn window.
- The updater runs guardedStopWindowsChecked for Task Scheduler; each of its
  three call sites aborts the restart unless the outcome is stopped or absent.
- ocx-stop/1 gains the additive serviceStopReason and portHeldByForeign.
- ARM64 ships strict: the terminate adapter answers unavailable whenever the
  native API is missing, so the PowerShell fallback is unreachable.
- Interactive callers refuse part A when the stopper descends from this home's
  wrapper; /api/stop and the updater opt out by design.
- Forced taskkill gets a 5 s timeout. The best-effort wrapper sweep has no
  remaining stop-path caller.

Docs: structure/ops/windows-checked-stop.md (now wired), runtime,
update-supervised-recovery and cli-management structure docs, the CLI
lifecycle and management API references, and devlog 000/030/060 (030's
admission minimums are now 48.5 / 56.5 / 42.5 s and the Desktop drain 70.5 s).

Refs #7771

* fix(service): the updater re-checks its authority right before each manager stop

Refs #7771

* refactor(service): move commandLineHasPathToken to a leaf module to break the guarded-manager import cycle

Refs #7771

* fix(service): the own-wrapper refusal is unknown even with nothing registered

The guard turns the bind enumeration unreadable, and Part A's stray path read an
unreadable table with nothing registered as absent: "no service, nothing to end".
Plain `ocx stop` then stopped the child, restored shared config and recorded
{partA:"absent"} beneath this home's own looping wrapper, which can relaunch the
proxy over the restored config.

The refusal now answers for itself in both paths: unknown, evidence-unreadable,
UNDER_OWN_WRAPPER_DETAIL, changed false, with no /end and no terminate. Nothing has
changed at that point, so nothing has to be undone. `allowUnderOwnWrapper` (the
route and the updater) keeps its sweep.

Refs #7771

* fix(cli): Part B owns the port wait on the guarded and uninstall paths too

The skipPortWait key was windowsPartBDue(), which is snapshotless-only because
it also gates the legacy respawn re-poll. The guarded path's Part B runs after
settle, and uninstall's Part B runs as the respawn window, so both still ran
stopProxy's legacy 15 s waitForStoppedPort on top of Part B.

WindowsPartBOwnsPortWait() answers only the port-wait question for both Windows
paths; windowsPartBDue() keeps the snapshotless-only respawn semantics. The two
uninstall stopProxy calls pass the same predicate. Non-Windows is unchanged
because both predicates require the simulated win32 platform.

Refs #7771

* fix(service): removal claims its teardown receipt before the child stop

Part A leaves the Task Scheduler task registered, so the receipt-less POST from
ocx service uninstall / remove still answered 409 respawnable_service and the
uninstall refused with the proxy running. Removal now claims a receipt carrying
Part A's record before the tracked stop, exactly as ocx service stop does, sends
no child stop when the claim fails, and keeps the receipt until the restore
succeeds (cli.ts completes it there).

windowsServiceRemovalStop returns { ok, nonce } instead of a bare boolean so the
caller can discharge the obligation at the right boundary.

Refs #7771

* fix(service): a not-running task promotes its survivors only once it is proven ours

The guarded inspection read "the task is not running" as "this home's task is
not running" and bound every surviving wrapper of this home as a terminable
bound-stray. The state word says nothing about ownership: a same-named foreign
registration would have made hand-started wrappers terminable. Read the
definition and require it to be a recognised OpenCodex registration before the
promotion; an unreadable definition stays unknown with evidence-unreadable and a
foreign one stays unknown, exactly as the running path already decided.

* fix(service): an unreadable listener identity is unknown, not foreign

verifyPidIdentity answers null both for "this is not an ocx process" and for
"the probe could not read it", and identifyWindowsStopListener mapped every
null to foreign. A Part B closing sample that could not read an elevated or
other-account listener therefore reported portHeldByForeign, and the caller
would restore shared config with the proxy possibly still alive.

inspectOcxStartProcessIdentity already answers the tri-state; only a positive
"mismatch" is foreign now, and "unverifiable" or a throwing probe stays
unknown so nothing further is changed.

Refs #7771

* fix(service): the Part B port sample honors its timeout

sampleWindowsStopPort ignored the timeoutMs Part B passed it and called the
synchronous scanListenPids, so the closing sample could stall the stop for the
helper's own budget and never yielded to Part B's deadline.

The sample is async now: the production scan runs netstat -ano from the trusted
System32 path through execFile with the caller's timeout and SIGKILL, so a
helper that overruns is terminated rather than abandoned. A scan that does not
answer in time is an unknown sample, and the timeout is floored with a value
below 1 ms sampling nothing, because execFile reads 0 as unlimited.

Refs #7771

* fix(service): orphan discovery takes the cap its caller admitted

stopTrackedProxyIfRunning hard-coded a 7 s deadline for the identity-checked
orphan discovery that follows the tracked stop, and applied it on every platform
and to every caller — including one whose Part A and Part B were already paid for
out of a checked Windows stop's admitted budget, which reserves 3 s for exactly
this step. The stop could then run past the deadline its own admission had just
proven.

The helper takes an orphanDiscoveryCapMs and keeps 7 s when none is passed, so
macOS and Linux stops are unchanged. The checked Windows callers — both service
command stops and prepareServiceInstall — pass WINDOWS_STOP_CAPS.orphanDiscovery,
and the plain ocx stop path reads the same constant instead of restating 3000.

Refs #7771

* fix(service): only ocx stop measures its deadline from command start

--deadline-ms and OCX_STOP_DEADLINE_MS are a command-start budget: the
operator's clock begins when they typed the command. Every other caller
reaches the stop after work it cannot charge to the stop -- the scheduler
registration and the UAC prompt -- so a 60 s budget measured from process
start could already be spent, and admission refused `unverified-budget` a
stop that had its whole budget left.

An explicit command deadline still wins and stays absolute; with none
recorded, the first deadline read in a stop phase arms the default 60 s and
every later read inside that phase keeps it, so one deadline governs the
whole stop instead of sliding forward.

Refs #7771

* test(cli): uninstall's authorization expectations name their platform

The base case asserted that a clean `stopped` authorizes shared teardown
without naming a platform, so it inherited process.platform. On Windows that
input is refused: a clean stop there is Part B of the checked stop and owes a
verified respawn window. The test therefore passed on darwin/linux hosts and
failed on Windows for a reason that has nothing to do with the code under
test.

Every expectation now passes its platform, and Windows gets the full matrix:
`stopped` needs the window, `absent` does not, `stopped-respawnable` needs it
everywhere, and a failed/unknown stop, a failed/absent removal or an unproven
proxy refuses even with the window.

Refs #7771, #3008, #764

* docs(windows): record the wiring review's timing and evidence rules

The contract doc and the 030/060 design records now say what the wiring
actually does: the port wait is Part B's on both Windows paths, the deadline's
origin depends on the caller, orphan discovery takes the cap its caller
admitted, the listener identity is tri-state, the Part B port sample is
bounded, service removal claims its receipt before the child stop, and a
not-running task needs its registration proof before bound-stray.

Refs #7771

* fix(cli): uninstall's port wait asks the port-wait question

The two `stopProxy` calls in `handleUninstall` were keyed to
`windowsPartBDue()`, which is snapshotless-only because it also gates the legacy
respawn re-poll. Uninstall's Part B is the respawn-window step that follows
service removal, so keying the skip to the snapshotless re-poll rule was the
wrong question: the calls skipped the legacy 15 s wait only by accident of that
rule's current shape, while the contract doc already said they pass the same
predicate as the guarded path.

Both calls now pass `windowsPartBOwnsPortWait()`, the predicate that answers
only "does Part B own the port wait". Non-Windows behavior is unchanged (the
predicate requires the simulated win32 platform), and `windowsPartBDue` keeps
its snapshotless-only respawn semantics.

Fail-before: `bun test tests/cli/uninstall.test.ts` -> 2 fail (both
`stopProxy(... skipPortWait: windowsPartBOwnsPortWait())` assertions), pass-after
-> 53 pass, 0 fail.

Refs #7771

* test(service): pin the not-running definition check with a bindable tree

The guarded-manager test for this rule used fixtures without creation times,
so binding refused as unknown whether or not the definition was checked: it
passed with the fix reverted. This case uses the tree that binds to
bound-stray when the registration is ours and shows a foreign or unreadable
definition keeps it unknown. Fails with 968290c's source change reverted.

Refs #7771

* fix(cli): uninstall's proxy stop claims the teardown receipt first

`ocx uninstall` sent /api/stop with no deferral, so the proxy performed the
shared client teardown during the stop — before the Windows respawn-window
check ran. If that check then failed, native Codex and the Grok fence were
already restored under a wrapper that could still relaunch the proxy (#3008).

The stop now lives in `src/cli/uninstall-stop.ts` so the decision is callable
rather than only readable, and on Windows it claims a pending-teardown receipt
carrying Part A's record before the child stop, sends its nonce on the POST,
and leaves the receipt for recovery unless Part B and the shared restore both
succeeded. Off Windows nothing changes.

Refs #7771

* fix(cli): uninstall never forces a stop its Part A could not prove

The proxy-stop step ran after a failed or unreadable service stop, and
`stopProxy` falls back to `taskkill /T /F` when the POST times out, the
transport fails, or the answer is not a 409. Under a manager that would not
stop, that forced kill is the one outcome the checked Windows stop exists to
prevent: the wrapper can relaunch the proxy after its teardown already ran.

`stopProxy` gains `allowForcedFallback` (default true, so every other caller is
unchanged) and uninstall sets it false when Part A did not end stopped/absent.
The graceful POST still goes out, the uninstall failure stays recorded, and an
unconfirmed stop no longer claims the proxy was proven down. A 409 refusal
still never reaches the ladder.

Refs #7771

* fix(service): an absent Part A is not proof the proxy is down

`windowsServiceRemovalStop` returned ok for a Part A "absent" without proving
anything about the endpoint. "Absent" only says no manager is registered:
`findLiveProxy` inside the tracked stop can return null when its discovery cap
runs out while the endpoint is live, and the task was then deleted and shared
config restored under a running proxy.

Removal now asks the endpoint itself, the way `windowsServiceStopBeforeRestore`
already does for absent, and refuses with the task intact when something still
answers. No respawn hold is requested: with no manager there is nothing that
could relaunch the proxy.

Refs #7771

* test(service): stop the absent-Part-A caller test waiting on the real probe

The caller test ran `windowsServiceStopBeforeRestore` with an absent Part A,
which falls through to the real `proxyStillLiveAfterStop`. On Windows that
spends its full 7 s respawn window before answering, and with the removal
path's new endpoint check it would wait twice.

Both callers are now given `survivor`, which also pins that the removal path
asks for no respawn hold while the stop path keeps its default, and that both
consulted the injection instead of the machine.

Refs #7771

* fix(service): install preparation resolves the stop port before the tracked cleanup

Part B was reading windowsServiceStopPort() after the tracked cleanup deleted the runtime
record, so it confirmed the wrapper's port (10100) instead of the stopped proxy's port
(12000). Resolve the port once before Part A and carry it into Part B.

Refs #7771

* fix(service): Part A proves the WinSW registration is this home's before stopping it

sc query answers that `opencodex-proxy-native` exists, not that it is this installation's
service. A successful query was treated as ownership, so Part A could run `sc stop` on
another installation's WinSW service under the fixed ID. The live probe now reads the
registered BINARY_PATH_NAME with `sc qc` and requires this home's WinSW executable, the
same proof the guarded manager path uses. An unreadable registration is unknown; a foreign
one is reported as nonexistent, so nothing is stopped.

Refs #7771

* fix(server): clear only an exited owner's TCP rows on the stopped port

Part B's sampler cleared every IPv4 TCP row on the port once the listening PID was
found exited. A program that took the port between scans owns its rows, so that reset
could break a connection this stop does not own. parseTcpQuadsForLocalPort and
dropWindowsTcpRowsForLocalPort accept an owner PID filter, and the sampler passes the
exited PID(s); the hard-kill path keeps clearing the whole port.

Refs #7771

* docs: name repair as the remaining stop exception and record the wiring decisions

structure/ops/windows-checked-stop.md claimed every Windows stop path uses the checked
stop; ocx service repair still stops through stopWindows() (repair.ts:259) and does not
restore shared state, so it is the remaining exception. 060 records it as its own
follow-up slice and captures the decisions from the review round (uninstall receipt,
no forced fallback, absent Part A, resolved stop port, WinSW ownership, owner-filtered
TCP drop), and 030 gains the WinSW ownership probe.

Refs #7771

* test(service): follow the uninstall stop into its helper when pinning the transport default

* fix(service): the WinSW ownership read shares one cap with the state query

The ownership read's budget was measured from after the state query, so the
two reads together could take twice the probe's cap. Measure from before
the state query and answer unknown when nothing is left.

Refs #7771

* fix(lib): keep stopProxy's forced kill a literal killProxy(pid) call

The forced-fallback seam rewrote the call as (io.forceKill ?? killProxy)(pid),
which hid it from the source check that the 409 refusal is handled before
any kill (grok-lifecycle 'a 409 does not escalate to a forced kill'). Call
killProxy(pid) literally and use the seam only when a test injects it.

Refs #7771

* fix(cli): resolve the uninstall stop target before claiming its receipt

`stopUninstallProxy` claimed the deferred-teardown receipt from
`defaultReceiptEndpoint()` before it knew what it would stop. That helper
marked any runtime record "exact", so a stale record plus a proxy discovered
on another port produced a receipt naming an endpoint the stop never
contacted; and when Part A failed with no proxy at all, a "guessed" receipt
was left outstanding that recovery refuses to finish.

The target is now resolved first — the tracked pid with its own runtime
record, or the discovered live proxy's endpoint — and only then is a receipt
claimed, with the same endpoint handed to `stopProxy`. No target means no
receipt. The tracked record is removed only for a stop that was proven, and
the step reports `changed` only when state actually changed.

Refs #7771

* fix(lib): make an unconfirmed stop's port wait observational

`waitForStoppedPort` reclaimed the port with `killOcxHolders` and
`onlyKillPids: [pid]` on every path, so a stop that had forbidden the forced
ladder could still terminate a verified-but-live listener through
`killProxy` — the very forced stop the caller had just refused.

When `allowForcedFallback` is false the wait is now observational: it runs
for the same window, but with no kill eligible. The reclaim dependency is
injectable (`reclaimPort`) so the rule is proven against a verified listener
without signalling a process; the literal `killProxy(pid)` call in
`stopProxy` stays as the refusal-ordering oracle requires.

Refs #7771

* fix(service): prove an absent-Part-A endpoint down before deleting the task

`windowsServiceRemovalStop` read `proxyStillLiveAfterStop({canRespawn:false})`
as the answer to "is anything still serving after a Part A that found no
manager". Its null is returned for a probe that timed out or failed as well as
for a dead endpoint, so an unreadable answer was treated as success and the
task was deleted — and a claimed receipt reported as discharged.

Removal now asks the captured endpoint itself with the same tri-state contract
as `endpointProvenDown` / `proxyEndpointProvenDown`, and only a definitive
"dead" permits deletion; "live" and "unknown" refuse and keep the receipt. The
receipt and the probe share one resolved endpoint.

Refs #7771

* fix(cli): gate Windows service removal on a proven stop and re-check ownership

`ocx uninstall` deleted the Windows registration with `uninstallServiceDetailed()`
even when Part A had failed to stop the manager, and the WinSW branch stopped and
deleted whatever was registered under the fixed `opencodex-proxy-native` ID — which
can be another installation's service.

Removal now requires a Part A that ended stopped or absent (`serviceRemovalAllowed`,
Windows only; other platforms unchanged) and records `failed` otherwise, so the shared
teardown stays blocked as `ocx service uninstall` already did. `uninstallServiceDetailed`
re-reads `sc qc` BINARY_PATH_NAME right before the native removal: foreign leaves the
registration untouched, unreadable refuses and keeps install state.

Refs #7771

* docs(windows): record the uninstall stop wiring and removal gates

structure/ops/windows-checked-stop.md and devlog 060 now describe items 1-5:
the uninstall stop resolving its target before claiming, the observational wait
under a forbidden fallback, the tri-state absent-Part-A probe, and the Windows
removal gates (Part A outcome plus a fresh `sc qc` ownership check).

Refs #7771

* refactor(cli): keep the uninstall removal gate out of src/cli/index.ts

The gate pushed src/cli/index.ts to 2005 lines, over the 2000-line ratchet.
`uninstallServiceRemoval` now holds the rule and the call in `uninstall-plan`,
so the command body stays one call and the refusal is testable directly.

Refs #7771

* fix(cli): prove the endpoint down when the uninstall stop is unconfirmed

stopProxy answers false without contacting anything when the tracked pid is
already dead, so an unconfirmed stop said nothing about a different proxy on
the configured port. The tracked path now asks the same tri-state probe the
discovery path requires before reporting provenDown, and still forbids the
forced fallback.

Refs #7771

* fix(service): prove every candidate endpoint before Windows removal

With Part A absent only the receipt endpoint was probed, so a stale runtime
record naming a closed port could prove removal while the configured port had
a live listener. Removal now proves the same candidate set ocx uninstall
proves, and any live or unreadable candidate refuses and keeps the receipt.

Refs #7771

* fix(service): probe Windows removal before deleting anything

The scheduler task was deleted before the WinSW status and ownership probes, so an unreadable sc qc left a half-removed install with no task to retry from. Read both probes first and refuse on unknown before the first destructive step (Refs #7771).

* test(lib): spawn the runtime's own binary for pid-taking stop tests

spawn("sleep", ["60"]) depends on a POSIX sleep on PATH and hangs forever if the spawn fails, because only the spawn event was awaited. Use process.execPath with a short-lived -e script and reject on error (Refs #7771).

* fix(service): expose the candidate-endpoint seam on the removal stop's io type

The absent-Part-A proof reads io.endpoints, but the Pick omitted it, so typecheck failed on the committed seam (Refs #7771).

* fix(service): claim the install's teardown receipt before the stopped-part-A stop

Part A leaves the scheduler task registered, so the tracked stop's /api/stop answered 409 respawnable_service without a receipt; stopProxy threw and the install aborted while the old proxy kept serving. prepareServiceInstall now claims a receipt carrying Part A's record before the stop and forwards its nonce. installServiceSafely clears it once the replacement is installed and started, and keeps it when install fails so the next ocx stop can finish (Refs #7771).

* fix(service): prove every endpoint down when install preparation finds no manager

With Part A absent, Part B is skipped and the tracked stop can return "none" after its orphan-discovery cap while an unresponsive proxy still holds the port, so the install published and started over it. prepareServiceInstall now resolves the candidate set before cleanup and requires every endpoint to be definitively dead; live or unknown refuses before the install callback. The candidate/probe helpers move to windows-service-stop so the removal and install paths share them (Refs #7771).

* docs(structure): record the round-9 checked-stop wiring decisions

Removal probes before deleting, install claims and completes its teardown receipt, an absent Part A proves every endpoint down, and an unconfirmed uninstall stop asks the endpoint (Refs #7771).

* Hold Windows child stop when Part A throws

* Refuse Windows stop when teardown receipt fails

* Check wrappers for WinSW-only stops

* Guard updater WinSW stops with checked stop

* Require dead endpoint proof before service restore

* Bind service stop receipts to resolved proxy targets

* Align Windows stop design notes with checked behavior

* fix(cli): an absent-Part-A uninstall proves every candidate endpoint dead after a confirmed stop

A confirmed tracked stop proved only the tracked proxy down. After an absent
Part A on Windows no Part B follows, so a second proxy on another candidate
endpoint went unseen and shared config could be restored under it (#3008).
The stop now also requires every candidate endpoint to answer dead, with the
candidate set captured before the stop removes the runtime record. After a
stopped Part A, Part B confirms the port as before.

Refs #7771

* docs(service): describe every receipt writer and the all-endpoint proof

Refs #7771

---------

Co-authored-by: t <a@b.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant