code-coordinator 0.5.613__py3-none-any.whl → 0.5.615__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-coordinator
3
- Version: 0.5.613
3
+ Version: 0.5.615
4
4
  Summary: Coordinate Claude Code workers across multiple machines and repos.
5
5
  Author-email: John Donaghy <johnfdonaghy@gmail.com>
6
6
  License-Expression: LicenseRef-FSL-1.1-MIT
@@ -1,4 +1,4 @@
1
- code_coordinator-0.5.613.dist-info/licenses/LICENSE,sha256=851BVZZwf_pEv2ydSlMmcZrwnwSS5YJ98wdLze7lyL8,4212
1
+ code_coordinator-0.5.615.dist-info/licenses/LICENSE,sha256=851BVZZwf_pEv2ydSlMmcZrwnwSS5YJ98wdLze7lyL8,4212
2
2
  coord/__init__.py,sha256=3FN2qrrxtW87xSsSD557YcMwHLDahnFK8LvqQI7Wlf4,9783
3
3
  coord/_board_mapping.py,sha256=U4DnAG_P8jv6IppoT-_-yJg3-0Ps0iYXYfRH7-pOg_E,12645
4
4
  coord/acceptance.py,sha256=WspJv7soXc2cSXgn9s78BHD8y0qeGBIyaNmsAl4pYVc,119974
@@ -151,7 +151,7 @@ coord/usage.py,sha256=Gyl1AXSMWiR1yCs1GXuNN_jdfUIU7WZNfr4qJAFEZr8,39933
151
151
  coord/usage_limits.py,sha256=NJHINN42s_AFzMCm58fo97t0Q5fZn3o8ozBTcXbFGJw,21884
152
152
  coord/usage_rollup.py,sha256=8ktXVJnKqrN6lcOX2LD22STXIKSvbp7Ji1fhnT94HwQ,29549
153
153
  coord/win_native_bridge.py,sha256=bUGqHf6h_Rxm8AlwtVhJ36kwy6x7SUFABoOjMNP0qqk,29822
154
- coord/win_native_driver.py,sha256=esJRDxXqh54ZTo9BnC5wP8FHJxyUBb5KdyMKewv5cew,102983
154
+ coord/win_native_driver.py,sha256=8CmnnYJIvahVHaXVAGsEXQL1aYkcTPVQviYM-wixqSs,132501
155
155
  coord/worker_events.py,sha256=nsrr2rvHx69ex2vU8h6kxO33WJD6H-a4nGZ8F7GpNPg,62810
156
156
  coord/agents/opencode/.gitignore,sha256=ILxVS75q0F95TKz1WTf-kIzd9uN3M5zoJHzQkUuwbIc,687
157
157
  coord/agents/opencode/routing.jsonc,sha256=853ltOkE3T0wBKBNXIPiHg-hVoyeQ21QnA8S8L_yU4Q,2596
@@ -292,8 +292,8 @@ coord/skills/review-verdict-recovery/SKILL.md,sha256=Grg8GWkJLK20ct2YiigbTFfNOki
292
292
  coord/skills/tui-quadraui-workflow/SKILL.md,sha256=4hUZza9wSSnPhf0eRAOh2r_MQZxK2pXYO5g-kxmJq-U,3832
293
293
  coord/skills/update-issue/SKILL.md,sha256=VrPinEmLZrCSNDrnz96hQomyO403o5c4i0RdsnUnWA0,3642
294
294
  coord/templates/deploy-cloudflare.node.yml,sha256=icsTiWn2ziQJnpZODhhFKYlnqjt2xAXsbwlQufdxhuM,2078
295
- code_coordinator-0.5.613.dist-info/METADATA,sha256=ZZcf7rEC9iJ7HkwUar5vhZFmrld7kmQ-TdcPbu3JyhE,17031
296
- code_coordinator-0.5.613.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
297
- code_coordinator-0.5.613.dist-info/entry_points.txt,sha256=o-Hq8pvG7ReGePvN_4iOKjLNqiq-MJ43HbPurqjNPZo,41
298
- code_coordinator-0.5.613.dist-info/top_level.txt,sha256=w5sTrXesTCebhXyYv2qufOZGo0PoD1Lxgn0Q3MAXjh4,6
299
- code_coordinator-0.5.613.dist-info/RECORD,,
295
+ code_coordinator-0.5.615.dist-info/METADATA,sha256=EtIBo7Tec2kK9FA_erxVKK16b4Qpp4VV9pR4rSOvhyw,17031
296
+ code_coordinator-0.5.615.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
297
+ code_coordinator-0.5.615.dist-info/entry_points.txt,sha256=o-Hq8pvG7ReGePvN_4iOKjLNqiq-MJ43HbPurqjNPZo,41
298
+ code_coordinator-0.5.615.dist-info/top_level.txt,sha256=w5sTrXesTCebhXyYv2qufOZGo0PoD1Lxgn0Q3MAXjh4,6
299
+ code_coordinator-0.5.615.dist-info/RECORD,,
@@ -78,11 +78,49 @@ own convention for entering a route's working directory first), both
78
78
  the resolved exe (plus that fixture dir, and/or a conventional ``.smoke``
79
79
  one, when present) onto the real local Windows filesystem — a fresh
80
80
  ``%LOCALAPPDATA%\\Temp\\coord-app-drive\\<session>\\`` directory — and
81
- launch from there instead, with ``cwd`` rewritten to match. Anything more
82
- complex (a second shell operator, an absolute/off-``cwd`` exe) is left
83
- alone, falling back to the ``pushd`` wrap above unchanged — this driver
84
- only ever rewrites the ONE leading executable token of a command it can
85
- parse with confidence, never an opaque shell pipeline.
81
+ launch from there instead, with ``cwd`` rewritten to match. An exe token
82
+ that is itself absolute is staged too when it's reachable only over the
83
+ network — a UNC path, a drive letter mapped to one, or a `/`-rooted
84
+ WSL-style token normalized onto the UNC form (#3633 — see below) — and
85
+ left alone only when it's already genuinely local. Anything more complex
86
+ (a second shell operator) is left alone, falling back to the ``pushd``
87
+ wrap above unchanged — this driver only ever rewrites the ONE leading
88
+ executable token of a command it can parse with confidence, never an
89
+ opaque shell pipeline.
90
+
91
+ **#3633: a route's own relative exe path can disagree with where the
92
+ fleet actually built it.** A ``run:`` naming ``../target/<triple>/
93
+ release/X.exe`` assumes cargo's default in-tree ``target/``, but this
94
+ fleet builds with a shared, per-repo ``CARGO_TARGET_DIR``
95
+ (``coord.cargo_cache``, #1402) — so that relative path resolves to
96
+ nothing, and a worker substitutes the real, absolute build path instead.
97
+ Nothing in this repo normalizes that substituted text — it is whatever
98
+ the worker typed — and it does NOT reliably come out as a UNC path: the
99
+ issue's own dell64 evidence showed every launch running from
100
+ ``Z:\\home\\john\\.coord\\cargo-target\\...``, a drive letter MAPPED to
101
+ the WSL tree, which ``ntpath.isabs``/:func:`_is_unc_path` alone cannot
102
+ tell apart from a genuinely local ``C:\\...`` exe. Launching straight off
103
+ either unstaged shape pays the exact same ``\\wsl$`` 9P cost #3617 exists
104
+ to avoid — and pre-#3633, :func:`_plan_staging` declined to stage ANY
105
+ absolute exe token, so this case silently never staged at all.
106
+ :func:`_plan_staging` now stages an absolute exe token whenever
107
+ :func:`_is_remote_exe_token` says it's reachable only over the network
108
+ (UNC outright, or a drive letter :func:`_get_drive_type` reports as
109
+ mapped/remote — real Windows' own ``GetDriveTypeW``, injectable for
110
+ testing), after first normalizing a bare `/`-rooted WSL-style token
111
+ (``/home/...``) onto the ``\\wsl.localhost\\<distro>\\...`` UNC shape
112
+ (:func:`_normalize_posix_exe_token`, borrowing *cwd*'s own distro
113
+ prefix). Staged by basename alone, rewriting *command*'s own leading
114
+ token to the staged copy; left alone only when the token is already
115
+ genuinely local, or is a `/`-rooted one with no distro to borrow from
116
+ *cwd* (nothing to safely guess either way).
117
+
118
+ Whether a token counts as "absolute" at all is decided by
119
+ :func:`_is_rooted_or_drive_qualified`, **not** :func:`ntpath.isabs` —
120
+ 3.13 narrowed the latter's meaning and reports ``False`` for exactly the
121
+ ``/``-rooted WSL token above, which on that interpreter alone dropped it
122
+ into the relative-exe path and staged it to the drive root. See that
123
+ function's docstring.
86
124
 
87
125
  :meth:`Win32Calls.kill` deletes the staged session directory it created,
88
126
  once it has signalled that launch's own pid — the normal (``close``/
@@ -95,6 +133,49 @@ self-expiry is the backstop, the explicit teardown is the normal path"
95
133
  shape :data:`coord.app_drive.DEFAULT_IDLE_TIMEOUT` already uses, just
96
134
  applied to a directory instead of a process.
97
135
 
136
+ **Process-tree teardown, including on an abnormal exit of THIS process
137
+ (#3634).** A 2026-10-05 bugbash lane left 4 simultaneous ``vimcode.exe``
138
+ processes running on an operator's desktop: every failed/retried launch's
139
+ own process survived, because :meth:`Win32Calls.kill` used to terminate
140
+ only the exact pid it was handed — ``cmd.exe``'s pid for a ``shell=True``
141
+ launch (#3542), never the real app grandchild cmd.exe itself never owns a
142
+ window for — and only walked the whole descendant tree for a *staged*
143
+ session's own cleanup, never as ``kill``'s general contract. Two fixes:
144
+
145
+ 1. :meth:`Win32Calls.kill` now ALWAYS terminates *pid*'s whole descendant
146
+ tree (:meth:`Win32Calls._descendant_pids`), not just when there's a
147
+ staged directory to clean up afterward — so every existing caller
148
+ (:meth:`NativeRunner._teardown`, :meth:`WinNativeSession.close`) that
149
+ already called ``kill`` now actually reaches the real app, not just
150
+ its shell wrapper.
151
+ 2. :class:`WinNativeSession`'s constructor now kills the pid it just
152
+ launched before re-raising if ``find_top_window``/``move_window``
153
+ fails — previously, a launch whose window never appeared left that
154
+ constructor's caller (:mod:`coord.app_drive_daemon`'s ``serve``) with
155
+ no object to ever call ``close``/``kill`` on at all, so a daemon that
156
+ retries ``open`` after a failed window discovery leaked one more
157
+ process per attempt — exactly the bugbash's 4-stray-window evidence.
158
+
159
+ Neither of those alone covers the case Windows has no POSIX analogue for:
160
+ *this* process (the ``win-native`` daemon) itself crashing or being
161
+ force-killed before its own ``kill()``/``close()`` ever runs — there is
162
+ no cooperating parent left to walk a descendant tree with. For that,
163
+ :meth:`Win32Calls.launch`/:meth:`~Win32Calls.launch_in_terminal` assign
164
+ every freshly-launched process to a fresh Windows **Job Object** with
165
+ ``JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`` set
166
+ (:meth:`Win32Calls._assign_kill_on_close_job`), and keep the one handle to
167
+ it open for the life of the session. Windows itself — not this process —
168
+ tears down every process still assigned to that job, including a
169
+ ``cmd.exe /c`` grandchild, the instant its last handle closes; closing it
170
+ ourselves is what :meth:`Win32Calls.kill` now does FIRST (before the
171
+ ``_descendant_pids`` walk, which stays as a backstop for a host/fake where
172
+ job-object assignment wasn't available at launch time), and an abnormal
173
+ exit of this very process closes it automatically too, since Windows
174
+ closes every handle a terminated process held. Best-effort throughout:
175
+ job-object creation/assignment never blocks or fails a launch — a host
176
+ where it's unavailable just falls back to the weaker (but still
177
+ code-path-correct) ``_descendant_pids``-only teardown.
178
+
98
179
  **Spec steps** (:func:`parse_native_spec`, YAML — the ``win-native``
99
180
  sibling of ``tui-pty``'s smoke spec):
100
181
 
@@ -224,6 +305,54 @@ _KEYEVENTF_KEYUP = 0x0002
224
305
  _KEYEVENTF_UNICODE = 0x0004
225
306
  _VK_SHIFT, _VK_CONTROL, _VK_MENU, _VK_LWIN = 0x10, 0x11, 0x12, 0x5B
226
307
 
308
+ #: Windows Job Object plumbing for #3634's process-tree teardown — see the
309
+ #: module docstring's "Process-tree teardown" paragraph and
310
+ #: :meth:`Win32Calls._assign_kill_on_close_job`. Pure ``ctypes`` struct/
311
+ #: constant definitions, same as ``_INPUT``/``_KEYBDINPUT`` above: these
312
+ #: import fine on any platform; only actually calling a Job Object API
313
+ #: through ``self._kernel32`` requires Windows.
314
+ JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
315
+ _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS = 9
316
+ _PROCESS_TERMINATE = 0x0001
317
+ _PROCESS_SET_QUOTA = 0x0100
318
+
319
+
320
+ class _JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
321
+ _fields_ = [
322
+ ("PerProcessUserTimeLimit", ctypes.c_int64),
323
+ ("PerJobUserTimeLimit", ctypes.c_int64),
324
+ ("LimitFlags", _wintypes.DWORD),
325
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
326
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
327
+ ("ActiveProcessLimit", _wintypes.DWORD),
328
+ ("Affinity", ctypes.c_void_p),
329
+ ("PriorityClass", _wintypes.DWORD),
330
+ ("SchedulingClass", _wintypes.DWORD),
331
+ ]
332
+
333
+
334
+ class _IO_COUNTERS(ctypes.Structure):
335
+ _fields_ = [
336
+ ("ReadOperationCount", ctypes.c_uint64),
337
+ ("WriteOperationCount", ctypes.c_uint64),
338
+ ("OtherOperationCount", ctypes.c_uint64),
339
+ ("ReadTransferCount", ctypes.c_uint64),
340
+ ("WriteTransferCount", ctypes.c_uint64),
341
+ ("OtherTransferCount", ctypes.c_uint64),
342
+ ]
343
+
344
+
345
+ class _JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
346
+ _fields_ = [
347
+ ("BasicLimitInformation", _JOBOBJECT_BASIC_LIMIT_INFORMATION),
348
+ ("IoInfo", _IO_COUNTERS),
349
+ ("ProcessMemoryLimit", ctypes.c_size_t),
350
+ ("JobMemoryLimit", ctypes.c_size_t),
351
+ ("PeakProcessMemoryUsed", ctypes.c_size_t),
352
+ ("PeakJobMemoryUsed", ctypes.c_size_t),
353
+ ]
354
+
355
+
227
356
  _log = logging.getLogger(__name__)
228
357
 
229
358
 
@@ -965,6 +1094,134 @@ def _is_unc_path(path: str) -> bool:
965
1094
  return path.startswith("\\\\")
966
1095
 
967
1096
 
1097
+ #: Win32 ``GetDriveTypeW``'s own ``DRIVE_REMOTE`` constant — a drive letter
1098
+ #: mapped to a network share (``net use Z: \\wsl$\Ubuntu...``), the exact
1099
+ #: shape #3633's own dell64 evidence showed (every staged-looking exe still
1100
+ #: running from ``Z:\home\john\.coord\cargo-target\...``): ``ntpath.isabs``
1101
+ #: reports ``True`` for it and :func:`_is_unc_path` reports ``False``, so
1102
+ #: neither of #3617's original checks ever caught it — it was mislabelled
1103
+ #: "already genuinely local" and the 9P cost staging exists to avoid was
1104
+ #: paid anyway.
1105
+ _DRIVE_REMOTE = 4
1106
+
1107
+
1108
+ def _is_rooted_or_drive_qualified(path: str) -> bool:
1109
+ r"""True when *path* is anything other than a plain, *cwd*-relative
1110
+ path — i.e. it carries a root (``\foo``, ``/foo``), a UNC prefix
1111
+ (``\\server\share\...``, ``//server/share/...``) or a drive letter
1112
+ (``C:\foo``, and even the drive-relative ``C:foo``).
1113
+
1114
+ **This exists instead of :func:`ntpath.isabs` because `ntpath.isabs`
1115
+ is not stable across the Python versions this repo supports (#3633
1116
+ CI).** Python 3.13 rewrote it to mean "absolute" strictly — only a
1117
+ drive-plus-root (``C:\``) or a UNC prefix — so a ``/``-rooted token
1118
+ like ``/home/john/.coord/cargo-target/.../vimcode.exe``, the exact
1119
+ WSL-style shape #3633 exists to normalize and stage, reports
1120
+ ``True`` on 3.12 and ``False`` on 3.13.
1121
+
1122
+ That difference is not cosmetic: on 3.13 such a token fell past
1123
+ :func:`_plan_staging`'s absolute-exe branch into the *relative*-exe
1124
+ one, where ``ntpath.join(session_root, "\\home\\me\\...")`` discards
1125
+ ``session_root`` wholesale (joining a rooted path replaces the
1126
+ root) and yields ``dest_exe = C:\home\me\...`` — staging the exe to
1127
+ the *drive root*, outside this session's own directory, which is
1128
+ precisely what the ``..``-escape guard further down exists to
1129
+ prevent. So the relative branch must only ever see genuinely
1130
+ relative tokens, on every supported interpreter; deciding that from
1131
+ the string itself rather than from ``ntpath``'s version-dependent
1132
+ notion of absoluteness is what makes that true.
1133
+
1134
+ A drive-relative ``C:foo`` (no root — ``ntpath.isabs`` is ``False``
1135
+ for it on *both* versions) is deliberately included: it is not
1136
+ *cwd*-relative either, ``ntpath.join`` treats it specially too, and
1137
+ the absolute branch's own classification safely declines to stage
1138
+ anything it cannot prove is remote.
1139
+ """
1140
+ if not path:
1141
+ return False
1142
+ if path[0] in ("\\", "/"):
1143
+ return True
1144
+ return bool(ntpath.splitdrive(path)[0])
1145
+
1146
+
1147
+ def _get_drive_type(path: str) -> int:
1148
+ """``GetDriveTypeW`` for the drive letter *path* starts with — a real
1149
+ (cheap, read-only) Win32 call, injectable via :func:`_is_remote_exe_token`'s
1150
+ ``get_drive_type`` kwarg so the decision logic built on top of it stays
1151
+ pure/testable with fabricated path strings on any host OS, the same
1152
+ shape :func:`_local_app_data_via_known_folder`'s caller
1153
+ (:meth:`Win32Calls._staging_root`) already uses its own
1154
+ ``known_folder_resolver`` kwarg for. Returns ``0`` (``DRIVE_UNKNOWN`` —
1155
+ never ``DRIVE_REMOTE``, so callers never mistake "couldn't ask" for "is
1156
+ local") on any non-Windows platform, a path with no drive letter at
1157
+ all (a UNC path, or one with no root), or any failure. The real call
1158
+ only ever happens on a real Windows host, where ``os.path`` already IS
1159
+ ``ntpath``.
1160
+ """
1161
+ if os.name != "nt":
1162
+ return 0
1163
+ drive = ntpath.splitdrive(path)[0]
1164
+ if not drive:
1165
+ return 0
1166
+ try:
1167
+ return ctypes.windll.kernel32.GetDriveTypeW(drive + "\\")
1168
+ except Exception: # noqa: BLE001 — best-effort only, never worth crashing a launch over
1169
+ return 0
1170
+
1171
+
1172
+ #: The ``\\wsl.localhost\<distro>`` prefix :func:`coord.win_native_bridge
1173
+ #: .translate_to_windows_path` puts on a translated ``cwd`` (#3543) —
1174
+ #: reused by :func:`_normalize_posix_exe_token` to turn a bare `/`-rooted
1175
+ #: exe token into that same UNC shape, without ever having to guess a
1176
+ #: distro name from nowhere.
1177
+ _WSL_LOCALHOST_PREFIX_RE = re.compile(r"^\\\\wsl\.localhost\\[^\\]+", re.IGNORECASE)
1178
+
1179
+
1180
+ def _normalize_posix_exe_token(exe_token: str, cwd: str) -> str | None:
1181
+ """A `/`-rooted POSIX/WSL-style exe token (``/home/john/...``) that
1182
+ reached the Windows side unmapped — #3633's fix option (b) names this
1183
+ shape explicitly alongside the UNC one. It is never a real Windows
1184
+ path: Windows path APIs resolve a bare leading ``/`` against the
1185
+ *current drive's* root directory, not WSL's filesystem, so launching
1186
+ (or even just ``isfile``-checking) it unchanged would silently fail
1187
+ or — worse — resolve to an unrelated file on whatever drive happens
1188
+ to be current.
1189
+
1190
+ Rewrites it onto the ``\\wsl.localhost\\<distro>\\...`` UNC shape
1191
+ instead, borrowing *cwd*'s own ``\\wsl.localhost\\<distro>`` prefix —
1192
+ *cwd* is already known to be exactly that shape whenever this is
1193
+ reached (the :func:`_is_unc_path` gate at the top of
1194
+ :func:`_plan_staging`) — rather than fabricating a distro name from
1195
+ nothing. Returns ``None`` when *cwd* doesn't carry that prefix (a
1196
+ same-host, non-WSL UNC share, e.g. ``\\fileserver\\tools\\...``, has
1197
+ no WSL distro to borrow one from); the caller then leaves the token
1198
+ alone rather than guess.
1199
+ """
1200
+ match = _WSL_LOCALHOST_PREFIX_RE.match(cwd)
1201
+ if match is None:
1202
+ return None
1203
+ return match.group(0) + exe_token.replace("/", "\\")
1204
+
1205
+
1206
+ def _is_remote_exe_token(exe_token: str, *, get_drive_type=_get_drive_type) -> bool:
1207
+ """True when *exe_token* — already known to be an absolute path,
1208
+ and already run through :func:`_normalize_posix_exe_token` when it
1209
+ started life as a `/`-rooted one — is reachable only over the network,
1210
+ i.e. genuinely worth staging onto the local filesystem (#3633):
1211
+
1212
+ - a UNC path (:func:`_is_unc_path` — ``\\\\server\\share\\...`` /
1213
+ ``\\\\wsl.localhost\\...``), or
1214
+ - a drive-letter path whose drive is itself a mapped network drive
1215
+ (*get_drive_type* reports :data:`_DRIVE_REMOTE` — dell64's own
1216
+ observed shape, ``Z:\\home\\...``).
1217
+
1218
+ False for a drive-letter path on a genuinely local (fixed/removable)
1219
+ drive — nothing to stage for an exe already on local NTFS."""
1220
+ if _is_unc_path(exe_token):
1221
+ return True
1222
+ return get_drive_type(exe_token) == _DRIVE_REMOTE
1223
+
1224
+
968
1225
  def _popen_command_and_cwd(command: str, cwd: str) -> tuple[str, str | None]:
969
1226
  """Resolve the ``command``/``cwd`` pair to actually hand
970
1227
  ``subprocess.Popen(..., shell=True)`` (#3543).
@@ -1127,12 +1384,33 @@ def _leading_token(command: str) -> tuple[str, str]:
1127
1384
  class _StagingPlan:
1128
1385
  """What :func:`_plan_staging` decided — ``staged=False`` means "leave
1129
1386
  *command*/*cwd* exactly as given", the caller's cue to fall back to
1130
- :func:`_popen_command_and_cwd`'s own UNC ``pushd`` wrap unchanged."""
1387
+ :func:`_popen_command_and_cwd`'s own UNC ``pushd`` wrap unchanged.
1388
+
1389
+ ``command`` is ``None`` (the default) whenever the original *command*
1390
+ text stays correct unchanged — the common (relative-exe) case, where
1391
+ only ``cwd`` moves and every relative reference in *command* keeps
1392
+ resolving against the new root exactly as it did against the old one
1393
+ (see the function docstring). It is set only for the #3633
1394
+ absolute-exe case below, where the exe token itself must be rewritten
1395
+ to point at its staged copy; :meth:`Win32Calls._stage_if_needed`
1396
+ treats ``None`` as "use the *command* I was called with unchanged"
1397
+ (#3617/#3633 review: a plain ``str`` field defaulting to ``""`` made
1398
+ "unchanged" and "a literal empty command" indistinguishable by
1399
+ construction — ``None`` says the same thing without that footgun).
1400
+
1401
+ ``skip_reason`` is set (and non-empty) on EVERY ``staged=False``
1402
+ return — never on a ``staged=True`` one — so
1403
+ :meth:`Win32Calls._stage_if_needed` can log/warn something more
1404
+ useful than one generic "could not parse" message for every skip
1405
+ reason, including the deliberate "parsed fine, already genuinely
1406
+ local, nothing to gain" case (#3633 review nit)."""
1131
1407
 
1132
1408
  staged: bool
1133
1409
  cwd: str = ""
1410
+ command: str | None = None
1134
1411
  source_exe: str = ""
1135
1412
  dest_exe: str = ""
1413
+ skip_reason: str = ""
1136
1414
  #: ``(source_dir, dest_dir)`` pairs to copy wholesale when the source
1137
1415
  #: exists — never an error when one doesn't (an optional fixture dir
1138
1416
  #: nobody provided this time).
@@ -1150,10 +1428,22 @@ class _StagingPlan:
1150
1428
  #: from pre-#3617, where the app edited the tree directly. No current
1151
1429
  #: spec asserts on post-run fixture content, but a future one that
1152
1430
  #: does must read it from the staged dir, not the WSL tree.
1431
+ #:
1432
+ #: Also (#3633 review, non-blocking): the absolute-exe case re-roots
1433
+ #: ``cwd`` to ``session_root`` for a command that, pre-#3633, launched
1434
+ #: unstaged against the real repo tree — but only ``cd_dir``/
1435
+ #: ``.smoke`` are copied here. A route like
1436
+ #: ``\\wsl...\x.exe docs/sample.txt`` (a relative DATA argument not
1437
+ #: under either) silently resolves to a file that was never staged.
1438
+ #: Pre-existing #3617 design for a relative exe; this just extends the
1439
+ #: exposure to a shape (absolute exe) that was previously never
1440
+ #: staged at all.
1153
1441
  fixture_copies: tuple[tuple[str, str], ...] = ()
1154
1442
 
1155
1443
 
1156
- def _plan_staging(command: str, cwd: str, *, session_root: str) -> _StagingPlan:
1444
+ def _plan_staging(
1445
+ command: str, cwd: str, *, session_root: str, get_drive_type=_get_drive_type,
1446
+ ) -> _StagingPlan:
1157
1447
  """Decide whether/how to stage *command*'s exe (plus its fixture
1158
1448
  dir(s)) from *cwd* into *session_root* instead of launching straight
1159
1449
  off *cwd* (#3617).
@@ -1166,50 +1456,166 @@ def _plan_staging(command: str, cwd: str, *, session_root: str) -> _StagingPlan:
1166
1456
  (``staged=False``) for anything else containing a shell metacharacter
1167
1457
  (:data:`_SHELL_METACHARACTERS` — a second ``&&``, a pipe, a
1168
1458
  redirection, ...) this driver cannot safely rewrite with confidence,
1169
- an already-absolute exe token (nothing of *cwd*'s own tree to stage
1170
- for it), or an exe whose path relative to ``cwd``/``cd_dir`` climbs
1171
- ABOVE ``cwd`` itself without a ``cd_dir`` to cancel it back out
1172
- (staged at the same offset from ``session_root``, it would escape
1173
- this session's own directory into the shared parent every other
1174
- session's own root also lives under).
1175
-
1176
- *command* itself is returned unchanged in the resulting plan — ``cwd``
1177
- moves to ``session_root`` ALWAYS, even when a ``cd <fixture-dir> &&
1178
- ...`` prefix was recognized — because *command* still carries that
1179
- same ``cd <fixture-dir>`` prefix unchanged, and it is *command* (run
1180
- from the new ``cwd``) that does the navigating into the fixture dir,
1181
- exactly as it did from the old (UNC) ``cwd``. (#3617 review: an
1182
- earlier revision set ``cwd`` to ``session_root/<fixture-dir>``
1183
- *itself* — i.e. pre-navigated — while leaving command's own ``cd
1184
- <fixture-dir> &&`` in place too, so cmd.exe ran the ``cd`` a SECOND
1185
- time from a directory that already had no further ``<fixture-dir>``
1186
- child staged under it, failed with a nonzero errorlevel, and `&&`
1187
- short-circuited the whole launch before the exe ever ran.) The exe
1188
- itself is copied to the SAME path, relative to *session_root*, that
1189
- it already held relative to *cwd* (:func:`ntpath.normpath` applied to
1190
- ``cd_dir`` + the exe token), so every relative reference in *command*
1191
- — the ``cd`` itself, a ``../`` the exe token carries, a trailing
1192
- argument resolved against the post-``cd`` directory — keeps resolving
1193
- correctly against the new, local root exactly as it did against the
1194
- old, UNC one.
1459
+ an already-absolute-AND-already-local exe token (nothing of *cwd*'s
1460
+ own tree to stage for it — see the #3633 paragraph below for the
1461
+ absolute-but-still-UNC case, which IS staged), or an exe whose path
1462
+ relative to ``cwd``/``cd_dir`` climbs ABOVE ``cwd`` itself without a
1463
+ ``cd_dir`` to cancel it back out (staged at the same offset from
1464
+ ``session_root``, it would escape this session's own directory into
1465
+ the shared parent every other session's own root also lives under).
1466
+
1467
+ *command* itself is returned unchanged (``plan.command is None``, the
1468
+ caller's cue to keep using the *command* it already has) in the
1469
+ common, relative-exe case — ``cwd`` moves to ``session_root`` ALWAYS,
1470
+ even when a ``cd <fixture-dir> && ...`` prefix was recognized —
1471
+ because *command* still carries that same ``cd <fixture-dir>`` prefix
1472
+ unchanged, and it is *command* (run from the new ``cwd``) that does
1473
+ the navigating into the fixture dir, exactly as it did from the old
1474
+ (UNC) ``cwd``. (#3617 review: an earlier revision set ``cwd`` to
1475
+ ``session_root/<fixture-dir>`` *itself* — i.e. pre-navigated — while
1476
+ leaving command's own ``cd <fixture-dir> &&`` in place too, so cmd.exe
1477
+ ran the ``cd`` a SECOND time from a directory that already had no
1478
+ further ``<fixture-dir>`` child staged under it, failed with a
1479
+ nonzero errorlevel, and `&&` short-circuited the whole launch before
1480
+ the exe ever ran.) The exe itself is copied to the SAME path, relative
1481
+ to *session_root*, that it already held relative to *cwd*
1482
+ (:func:`ntpath.normpath` applied to ``cd_dir`` + the exe token), so
1483
+ every relative reference in *command* — the ``cd`` itself, a ``../``
1484
+ the exe token carries, a trailing argument resolved against the
1485
+ post-``cd`` directory — keeps resolving correctly against the new,
1486
+ local root exactly as it did against the old, UNC one.
1487
+
1488
+ **#3633: an absolute exe token reachable only over the network is
1489
+ staged too, not left alone.** A route's ``run:`` naming a relative
1490
+ exe path (e.g. ``../target/<triple>/release/vimcode.exe``) assumes
1491
+ cargo's default in-tree ``target/`` — but this fleet builds with a
1492
+ shared, per-repo ``CARGO_TARGET_DIR`` (``coord.cargo_cache``, #1402),
1493
+ so that relative path resolves to nothing and a worker substitutes
1494
+ the real, absolute build path instead. *That* substituted text is
1495
+ whatever the worker typed — nothing in this repo normalizes it — and
1496
+ #3633's own dell64 evidence showed it does NOT reliably come out as a
1497
+ UNC path: ``Get-Process`` there showed every launch running from
1498
+ ``Z:\\home\\john\\.coord\\cargo-target\\...``, a drive letter MAPPED
1499
+ to the WSL tree (``net use Z: \\wsl$\\Ubuntu...``) — ``ntpath.isabs``
1500
+ is ``True`` for that and :func:`_is_unc_path` is ``False``, so it
1501
+ still paid the exact same ``\\wsl$`` 9P cost staging exists to avoid,
1502
+ mislabelled "already genuinely local". :func:`_is_remote_exe_token`
1503
+ (UNC, or a drive letter :data:`_get_drive_type` reports as
1504
+ :data:`_DRIVE_REMOTE`) is what actually decides now, and a bare
1505
+ `/`-rooted WSL-style token (``/home/...`` — the issue's other named
1506
+ shape) is rewritten onto the ``\\wsl.localhost\\<distro>\\...`` UNC
1507
+ form first (:func:`_normalize_posix_exe_token`, borrowing *cwd*'s own
1508
+ distro prefix) before that same check runs. An absolute token that is
1509
+ already genuinely LOCAL (e.g. a real ``C:\\...`` exe on a fixed
1510
+ drive) is still left alone — nothing to gain from staging something
1511
+ already on local NTFS — and so is a `/`-rooted token when *cwd*
1512
+ itself isn't a ``\\wsl.localhost\\...`` UNC path to borrow a distro
1513
+ prefix from (nothing to safely guess). Staged by basename alone, at
1514
+ the top of *session_root* — an absolute token carries no meaningful
1515
+ position relative to *cwd* to preserve the way a relative one does —
1516
+ and *command*'s own leading token is rewritten (``plan.command``,
1517
+ always set — never ``None`` — here) to the staged, quoted destination
1518
+ path, with
1519
+ any recognized ``cd <fixture-dir> && `` prefix and trailing arguments
1520
+ carried through unchanged.
1195
1521
  """
1196
1522
  if not _is_unc_path(cwd):
1197
- return _StagingPlan(staged=False)
1523
+ return _StagingPlan(staged=False, skip_reason="cwd is not a UNC path — already local")
1198
1524
  cd_dir, remainder = _strip_cd_prefix(command)
1199
- if cd_dir and ntpath.isabs(cd_dir):
1200
- # An absolute `cd_dir` (`cd C:\foo && ...`) would collapse
1201
- # `ntpath.join(session_root, cd_dir)` down to `cd_dir` alone,
1525
+ if cd_dir and _is_rooted_or_drive_qualified(cd_dir):
1526
+ # A non-relative `cd_dir` (`cd C:\foo && ...`, `cd \foo && ...`)
1527
+ # would collapse `ntpath.join(session_root, cd_dir)` down to
1528
+ # `cd_dir` alone — or onto `session_root`'s drive ROOT —
1202
1529
  # discarding `session_root` entirely and landing `source_exe`/
1203
1530
  # `dest_exe` on the SAME absolute path (a `shutil.copy2`
1204
1531
  # `SameFileError`) — the `..`-escape guard below only ever
1205
- # assumed a relative `cd_dir`, same as `exe_token`'s own
1206
- # `ntpath.isabs` check just below.
1207
- return _StagingPlan(staged=False)
1532
+ # assumed a relative `cd_dir`, same as `exe_token`'s own check
1533
+ # just below. #3633 CI: this deliberately uses
1534
+ # `_is_rooted_or_drive_qualified` rather than `ntpath.isabs`,
1535
+ # whose meaning differs between 3.12 and 3.13 (see that
1536
+ # function's docstring).
1537
+ return _StagingPlan(
1538
+ staged=False,
1539
+ skip_reason=f"could not parse: cd prefix {cd_dir!r} is not cwd-relative",
1540
+ )
1208
1541
  if _looks_shell_composed(remainder):
1209
- return _StagingPlan(staged=False)
1210
- exe_token, _rest = _leading_token(remainder)
1211
- if not exe_token or ntpath.isabs(exe_token):
1212
- return _StagingPlan(staged=False)
1542
+ return _StagingPlan(
1543
+ staged=False,
1544
+ skip_reason="could not parse: command contains more than one shell operator",
1545
+ )
1546
+ exe_token, rest = _leading_token(remainder)
1547
+ if not exe_token:
1548
+ return _StagingPlan(staged=False, skip_reason="could not parse: command is empty")
1549
+
1550
+ fixture_dirnames: list[str] = []
1551
+ for name in (cd_dir, _STAGING_FIXTURE_DIRNAME):
1552
+ if name and name not in fixture_dirnames:
1553
+ fixture_dirnames.append(name)
1554
+ fixture_copies = tuple(
1555
+ (ntpath.join(cwd, name), ntpath.join(session_root, name))
1556
+ for name in fixture_dirnames
1557
+ )
1558
+
1559
+ if _is_rooted_or_drive_qualified(exe_token):
1560
+ # #3633 CI: NOT `ntpath.isabs` — that would route a `/`-rooted
1561
+ # WSL-style token here on 3.12 and into the relative branch
1562
+ # below on 3.13 (which stages it to the drive root, escaping
1563
+ # `session_root`). See `_is_rooted_or_drive_qualified`.
1564
+ resolved_token = exe_token
1565
+ if exe_token.startswith("//"):
1566
+ # An altsep-spelled UNC token (`//wsl.localhost/Ubuntu/...`)
1567
+ # — the same path, just not in Windows' own spelling. Respell
1568
+ # it rather than letting the `/`-rooted branch below treat it
1569
+ # as a distro-relative path and graft a second UNC prefix in
1570
+ # front of it.
1571
+ resolved_token = exe_token.replace("/", "\\")
1572
+ elif exe_token.startswith("/"):
1573
+ # #3633: a bare `/`-rooted WSL/POSIX-style token — never a
1574
+ # real Windows path as-is (a leading `/` resolves against
1575
+ # whatever drive happens to be CURRENT, not WSL's
1576
+ # filesystem). Rewrite it onto the `\\wsl.localhost\<distro>`
1577
+ # UNC shape by borrowing `cwd`'s own distro prefix; if `cwd`
1578
+ # isn't that shape there's no distro to borrow, and this
1579
+ # token is left alone rather than guessed at.
1580
+ normalized = _normalize_posix_exe_token(exe_token, cwd)
1581
+ if normalized is None:
1582
+ return _StagingPlan(
1583
+ staged=False,
1584
+ skip_reason=(
1585
+ f"exe token {exe_token!r} is a /-rooted WSL-style path, "
1586
+ "but cwd has no \\\\wsl.localhost\\<distro> prefix to "
1587
+ "borrow a distro name from"
1588
+ ),
1589
+ )
1590
+ resolved_token = normalized
1591
+ if not _is_remote_exe_token(resolved_token, get_drive_type=get_drive_type):
1592
+ # Already local (or a root-relative `\foo` shape with no
1593
+ # drive to classify at all) — nothing of cwd's own tree to
1594
+ # stage for it.
1595
+ return _StagingPlan(
1596
+ staged=False,
1597
+ skip_reason=(
1598
+ f"exe token {resolved_token!r} is not on a drive we can "
1599
+ "see as remote — already local, nothing to gain from "
1600
+ "staging it"
1601
+ ),
1602
+ )
1603
+ # #3633: reachable only over the network (UNC, or a drive letter
1604
+ # `get_drive_type` reports as mapped/remote), just not resolved
1605
+ # through `cwd` — stage it by basename alone and rewrite
1606
+ # `command`'s own leading token to point at the staged copy.
1607
+ dest_exe = ntpath.join(session_root, ntpath.basename(resolved_token))
1608
+ cd_prefix = f'cd "{cd_dir}" && ' if cd_dir else ""
1609
+ rest_suffix = f" {rest}" if rest else ""
1610
+ new_command = f'{cd_prefix}"{dest_exe}"{rest_suffix}'
1611
+ return _StagingPlan(
1612
+ staged=True,
1613
+ cwd=session_root,
1614
+ command=new_command,
1615
+ source_exe=resolved_token,
1616
+ dest_exe=dest_exe,
1617
+ fixture_copies=fixture_copies,
1618
+ )
1213
1619
 
1214
1620
  exe_rel = ntpath.normpath(ntpath.join(cd_dir, exe_token)) if cd_dir else ntpath.normpath(exe_token)
1215
1621
  if exe_rel == ".." or exe_rel.startswith(f"..{ntpath.sep}"):
@@ -1224,7 +1630,14 @@ def _plan_staging(command: str, cwd: str, *, session_root: str) -> _StagingPlan:
1224
1630
  # than risked — the `cd .smoke && ../target/...` shape above
1225
1631
  # cancels its own `..` back inside `cwd` and is unaffected by
1226
1632
  # this guard.
1227
- return _StagingPlan(staged=False)
1633
+ return _StagingPlan(
1634
+ staged=False,
1635
+ skip_reason=(
1636
+ f"relative exe {exe_token!r} resolves to {exe_rel!r}, which "
1637
+ "climbs above cwd itself with no cd prefix to cancel it back "
1638
+ "out — staging it would escape this session's own directory"
1639
+ ),
1640
+ )
1228
1641
  # #3617 review: always `session_root` — NEVER `session_root/cd_dir`.
1229
1642
  # `command` still carries its own (unmodified) `cd <cd_dir> && `
1230
1643
  # prefix, which does the navigating into the staged fixture dir once
@@ -1232,15 +1645,6 @@ def _plan_staging(command: str, cwd: str, *, session_root: str) -> _StagingPlan:
1232
1645
  # the double-`cd` bug this comment's sibling above explains.
1233
1646
  new_cwd = session_root
1234
1647
 
1235
- fixture_dirnames: list[str] = []
1236
- for name in (cd_dir, _STAGING_FIXTURE_DIRNAME):
1237
- if name and name not in fixture_dirnames:
1238
- fixture_dirnames.append(name)
1239
- fixture_copies = tuple(
1240
- (ntpath.join(cwd, name), ntpath.join(session_root, name))
1241
- for name in fixture_dirnames
1242
- )
1243
-
1244
1648
  return _StagingPlan(
1245
1649
  staged=True,
1246
1650
  cwd=new_cwd,
@@ -1287,6 +1691,19 @@ def _execute_staging(
1287
1691
  exercising this function with fabricated Windows-style strings on a
1288
1692
  non-Windows host must pass genuinely local (``tmp_path``-rooted)
1289
1693
  paths instead, as every test in this module already does.
1694
+
1695
+ Also raises when *dest_exe* still doesn't exist immediately AFTER
1696
+ ``copy_file`` returns (#3633 review) — pre-#3633, a bad/incomplete
1697
+ copy still left a correct, if slow, UNC command behind (staging only
1698
+ ever moved ``cwd``); now that the absolute-exe case REWRITES
1699
+ *command* itself to point at ``dest_exe``
1700
+ (:attr:`_StagingPlan.command`), an exe that silently isn't actually
1701
+ there any more degrades to a confusing, late ``find_top_window``
1702
+ timeout instead of the documented "staging is a performance
1703
+ optimization, not a correctness requirement" fallback
1704
+ (:meth:`Win32Calls._stage_if_needed` catches this exactly like the
1705
+ pre-copy ``source_exe`` check, falling back to the pre-#3617
1706
+ ``pushd``/UNC launch).
1290
1707
  """
1291
1708
  if not plan.staged:
1292
1709
  return
@@ -1298,6 +1715,12 @@ def _execute_staging(
1298
1715
  )
1299
1716
  makedirs(dirname(plan.dest_exe), exist_ok=True)
1300
1717
  copy_file(plan.source_exe, plan.dest_exe)
1718
+ if not isfile(plan.dest_exe):
1719
+ raise WinNativeRuntimeError(
1720
+ f"win-native launch staging (#3617): copy to {plan.dest_exe!r} "
1721
+ "reported success but the file isn't there afterward — "
1722
+ "refusing to launch a command rewritten to point at it"
1723
+ )
1301
1724
  for source_dir, dest_dir in plan.fixture_copies:
1302
1725
  if isdir(source_dir):
1303
1726
  copy_tree(source_dir, dest_dir, dirs_exist_ok=True)
@@ -1429,6 +1852,14 @@ class Win32Calls:
1429
1852
  #: itself grows unboundedly in a long-lived process that never
1430
1853
  #: calls `kill`.
1431
1854
  self._staged_session_dirs: dict[int, str] = {}
1855
+ #: #3634: pid -> the open handle to the ``KILL_ON_JOB_CLOSE`` Job
1856
+ #: Object `launch`/`launch_in_terminal` assigned it to (see
1857
+ #: `_assign_kill_on_close_job`) — absent for a pid whose job
1858
+ #: assignment failed/was unavailable (a scripted test fake, or in
1859
+ #: principle a very old Windows missing one of these exports).
1860
+ #: `kill` pops and closes this FIRST, before its own
1861
+ #: `_descendant_pids` walk/`TerminateProcess` backstop.
1862
+ self._job_handles: dict[int, int] = {}
1432
1863
  #: #3617 review: non-``None`` after `_stage_if_needed` skipped
1433
1864
  #: staging for a UNC `cwd` (as opposed to the common, unremarkable
1434
1865
  #: case of a same-host, already-local `cwd` where staging never
@@ -1468,8 +1899,20 @@ class Win32Calls:
1468
1899
  proc = subprocess.Popen(
1469
1900
  full_command, shell=True, cwd=popen_cwd, **_NO_HANDLE_INHERITANCE,
1470
1901
  )
1471
- if staged_dir is not None:
1472
- self._staged_session_dirs[proc.pid] = staged_dir
1902
+ # #3634: same unbound-`self`-safety requirement as above —
1903
+ # `TestLaunchPipeInheritanceRealSubprocess` calls this method
1904
+ # completely unbound (`self=None`) to drive a REAL subprocess tree
1905
+ # without needing a real (Windows-only) `Win32Calls` instance. Job
1906
+ # Object assignment needs a real `self._kernel32`, so it's skipped
1907
+ # whenever there's no `self` to assign through — exactly the case
1908
+ # where nothing tracks this pid for `kill` to reach later either,
1909
+ # so there is no regression in what gets torn down vs. before.
1910
+ if self is not None:
1911
+ if staged_dir is not None:
1912
+ self._staged_session_dirs[proc.pid] = staged_dir
1913
+ job = self._assign_kill_on_close_job(proc.pid)
1914
+ if job is not None:
1915
+ self._job_handles[proc.pid] = job
1473
1916
  return proc.pid
1474
1917
 
1475
1918
  def launch_in_terminal(self, command: str, cwd: str, terminal_app: str) -> int:
@@ -1488,27 +1931,96 @@ class Win32Calls:
1488
1931
  )
1489
1932
  if staged_dir is not None:
1490
1933
  self._staged_session_dirs[proc.pid] = staged_dir
1934
+ job = self._assign_kill_on_close_job(proc.pid)
1935
+ if job is not None:
1936
+ self._job_handles[proc.pid] = job
1491
1937
  return proc.pid
1492
1938
 
1939
+ def _assign_kill_on_close_job(self, pid: int) -> int | None:
1940
+ """#3634: wrap *pid* (the pid `launch`/`launch_in_terminal` just
1941
+ returned — ``cmd.exe``'s own pid for a ``shell=True`` launch, see
1942
+ :meth:`_descendant_pids`'s docstring, #3542) in a fresh Windows Job
1943
+ Object with ``JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`` set, and return
1944
+ the handle for the caller to hold onto (:attr:`_job_handles`) —
1945
+ ``None`` on any failure (`CreateJobObjectW` returning a null
1946
+ handle, `SetInformationJobObject`/`OpenProcess`/
1947
+ `AssignProcessToJobObject` returning false/null, or a scripted
1948
+ test fake with no Job Object support at all, caught as
1949
+ ``AttributeError``).
1950
+
1951
+ As long as the returned handle stays open, Windows itself — not
1952
+ this process — tears down EVERY process still assigned to the job,
1953
+ including a ``cmd.exe /c`` grandchild this driver never otherwise
1954
+ tracks, the instant the job's LAST handle closes: either
1955
+ explicitly, when :meth:`kill` closes it, or automatically, if
1956
+ *this very process* (the ``win-native`` daemon holding the handle)
1957
+ crashes or is force-killed before its own ``kill()``/``close()``
1958
+ ever runs — Windows closes every handle a terminated process held,
1959
+ which is exactly the guarantee #3634 needs and that a
1960
+ `_descendant_pids`-walking `TerminateProcess` loop alone cannot
1961
+ give, since that walk needs a live, cooperating process to run it.
1962
+
1963
+ Best-effort and silent on failure: a host where Job Objects are
1964
+ unavailable still gets the weaker (but still code-path-correct for
1965
+ every explicit `kill()` call) `_descendant_pids`-only teardown —
1966
+ this never blocks or fails a launch over it."""
1967
+ try:
1968
+ job = self._kernel32.CreateJobObjectW(None, None)
1969
+ if not job:
1970
+ return None
1971
+ info = _JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
1972
+ info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
1973
+ if not self._kernel32.SetInformationJobObject(
1974
+ job, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS,
1975
+ self._ctypes.byref(info), self._ctypes.sizeof(info),
1976
+ ):
1977
+ self._kernel32.CloseHandle(job)
1978
+ return None
1979
+ process_handle = self._kernel32.OpenProcess(
1980
+ _PROCESS_SET_QUOTA | _PROCESS_TERMINATE, False, pid,
1981
+ )
1982
+ if not process_handle:
1983
+ self._kernel32.CloseHandle(job)
1984
+ return None
1985
+ try:
1986
+ if not self._kernel32.AssignProcessToJobObject(job, process_handle):
1987
+ self._kernel32.CloseHandle(job)
1988
+ return None
1989
+ finally:
1990
+ self._kernel32.CloseHandle(process_handle)
1991
+ return job
1992
+ except AttributeError:
1993
+ # A scripted test fake (or, in principle, a very old Windows
1994
+ # missing one of these exports) with no Job Object support at
1995
+ # all — not a failure, just "unavailable"; see the docstring's
1996
+ # best-effort note.
1997
+ return None
1998
+
1493
1999
  def kill(self, pid: int) -> None:
1494
2000
  # By PID (plus its own descendants) only — see the module
1495
2001
  # docstring's safety note. No image-name-based lookup exists
1496
2002
  # anywhere in this class.
1497
2003
  PROCESS_TERMINATE = 0x0001
1498
2004
  staged_dir = self._staged_session_dirs.pop(pid, None)
1499
- # #3617 review: a staged session's exe is a GRANDCHILD of *pid*
1500
- # (`subprocess.Popen(..., shell=True)` returns cmd.exe's own pid —
1501
- # see `_descendant_pids`'s docstring, #3542), which a bare
1502
- # `TerminateProcess(pid)` never touches. Windows locks a running
1503
- # image's file, so deleting the staged dir while that grandchild
1504
- # is still alive would silently leave the exe (and therefore the
1505
- # directory) behind — only `_sweep_stale_sessions`'s 24h backstop
1506
- # would ever clean it up. Terminating the whole descendant tree
1507
- # FIRST — only when there's a staged dir to clean up, to keep the
1508
- # overwhelmingly common (non-staged) `kill` exactly as cheap as it
1509
- # always was — makes the delete that follows actually able to
1510
- # succeed.
1511
- targets = self._descendant_pids(pid) if staged_dir is not None else {pid}
2005
+ # #3634: close OUR last handle to *pid*'s KILL_ON_JOB_CLOSE Job
2006
+ # Object FIRST, if one was successfully assigned at launch time —
2007
+ # this alone tears down the WHOLE descendant tree (including a
2008
+ # `cmd.exe /c` grandchild, #3542) regardless of whether this
2009
+ # process can still see/walk it. See
2010
+ # `_assign_kill_on_close_job`'s docstring.
2011
+ job = self._job_handles.pop(pid, None)
2012
+ if job is not None:
2013
+ self._kernel32.CloseHandle(job)
2014
+ # #3634: ALWAYS terminate the whole descendant tree, not only when
2015
+ # there's a staged dir to clean up afterward — a 2026-10-05
2016
+ # bugbash lane showed this `kill` previously left every grandchild
2017
+ # (the real app under `cmd.exe`, #3542) running in the
2018
+ # overwhelmingly common (non-staged) case, since only a staged
2019
+ # session's own cleanup needed the walk to delete its directory.
2020
+ # Redundant with the Job Object close above whenever that
2021
+ # succeeded, but it's the ONLY teardown on a host/fake where job
2022
+ # assignment was unavailable, so it always runs regardless.
2023
+ targets = self._descendant_pids(pid)
1512
2024
  for target in targets:
1513
2025
  handle = self._kernel32.OpenProcess(PROCESS_TERMINATE, False, target)
1514
2026
  if handle:
@@ -1609,7 +2121,14 @@ class Win32Calls:
1609
2121
  records why on :attr:`staging_warning` and logs it — #3617 review:
1610
2122
  a silent fallback here would otherwise surface only much later, as
1611
2123
  a confusing ``find_top_window`` timeout with no indication staging
1612
- was ever involved."""
2124
+ was ever involved.
2125
+
2126
+ #3633: the returned *command* is ``plan.command`` when the plan set
2127
+ one (the absolute-exe case, where the exe token itself had to be
2128
+ rewritten to its staged copy) or the original *command* when it
2129
+ didn't (``plan.command is None`` — the common relative-exe case,
2130
+ where *command* already resolves correctly against the staged
2131
+ ``cwd`` unchanged)."""
1613
2132
  self.staging_warning = None
1614
2133
  try:
1615
2134
  root = self._staging_root()
@@ -1620,10 +2139,16 @@ class Win32Calls:
1620
2139
  session_root = os.path.join(root, uuid.uuid4().hex[:12])
1621
2140
  plan = _plan_staging(command, cwd, session_root=session_root)
1622
2141
  if not plan.staged:
2142
+ # #3633 review nit: `plan.skip_reason` distinguishes an
2143
+ # actually-unparseable command/cwd shape from the deliberate
2144
+ # "parsed fine, exe is already genuinely local, nothing to
2145
+ # gain" skip — a prior, single generic "could not parse"
2146
+ # message here claimed the latter never parsed at all, which
2147
+ # is misleading for anyone diagnosing a lane from the log.
1623
2148
  self.staging_warning = (
1624
- "win-native launch staging (#3617) could not parse this "
1625
- f"launch command/cwd shape for staging — launching from "
1626
- f"the UNC path {cwd!r} unstaged (slow \\\\wsl$ I/O)"
2149
+ f"win-native launch staging (#3617/#3633): {plan.skip_reason} "
2150
+ f"— launching from the UNC path {cwd!r} unstaged (slow "
2151
+ "\\\\wsl$ I/O)"
1627
2152
  )
1628
2153
  _log.warning("%s", self.staging_warning)
1629
2154
  return command, cwd, None
@@ -1634,7 +2159,7 @@ class Win32Calls:
1634
2159
  self.staging_warning = str(exc)
1635
2160
  _log.warning("%s", exc)
1636
2161
  return command, cwd, None
1637
- return command, plan.cwd, session_root
2162
+ return (plan.command if plan.command is not None else command), plan.cwd, session_root
1638
2163
 
1639
2164
  # -- session precheck (#3510) --
1640
2165
 
@@ -2056,8 +2581,25 @@ class WinNativeSession:
2056
2581
  ) -> None:
2057
2582
  self._calls: WinCalls = calls if calls is not None else Win32Calls()
2058
2583
  self._pid = self._calls.launch(launch_command, cwd)
2059
- self._hwnd = self._calls.find_top_window(self._pid, timeout_s)
2060
- self._calls.move_window(self._hwnd, 0, 0, width, height)
2584
+ try:
2585
+ self._hwnd = self._calls.find_top_window(self._pid, timeout_s)
2586
+ self._calls.move_window(self._hwnd, 0, 0, width, height)
2587
+ except Exception:
2588
+ # #3634: this constructor never returns a usable session when
2589
+ # `find_top_window`/`move_window` fails, so there is no
2590
+ # `WinNativeSession` object for anyone to ever call
2591
+ # `close()`/`kill()` on — without this, the process `launch`
2592
+ # just started (and its real-app grandchild, #3542) leaked on
2593
+ # every failed/retried open, exactly the 2026-10-05 bugbash
2594
+ # evidence (4 simultaneous stray `vimcode.exe`). Kill it HERE,
2595
+ # before re-raising, so a failed open — and every retry of
2596
+ # one — cleans up after itself instead of accumulating one
2597
+ # more stray window per attempt.
2598
+ try:
2599
+ self._calls.kill(self._pid)
2600
+ except Exception: # noqa: BLE001 — teardown-on-failure must not mask the real error
2601
+ pass
2602
+ raise
2061
2603
 
2062
2604
  @property
2063
2605
  def pid(self) -> int:
@@ -2069,9 +2611,10 @@ class WinNativeSession:
2069
2611
  See :meth:`_descendant_pids`'s own docstring (#3542): this is
2070
2612
  ``cmd.exe``'s pid, not the real app's — ``Win32Calls.launch``'s
2071
2613
  ``shell=True`` makes the real app a grandchild this pid never
2072
- owns a window for. Killing this pid alone can leave that
2073
- grandchild running; tracked separately from #3590, same class as
2074
- the mac-native/gtk-native shell-vs-app gap."""
2614
+ owns a window for. :meth:`WinCalls.kill` (#3634) now always
2615
+ terminates the whole descendant tree for whatever pid it's given,
2616
+ so killing this one pid alone no longer leaves that grandchild
2617
+ running."""
2075
2618
  return self._pid
2076
2619
 
2077
2620
  @property