dsh-windows-parallel-mcp 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- # decide.ps1 -- the R2' channel decision, as a PURE function.
1
+ # decide.ps1 -- the channel decision, as a PURE function.
2
2
  #
3
- # WHY PURE AND FIRST. R2' turns on one table: which door a target has, and therefore whether an
4
- # action costs the user nothing or costs them a bounded flash. Everything that can go wrong in
5
- # that table goes wrong identically whether it is buried in a P/Invoke loop or written as a
6
- # 30-line function, but only the function can be tested in milliseconds against every branch.
7
- # The measured instruments in scripts/ proved the facts; this file is the part that consumes
8
- # them, and it is kept free of IO so a wrong verdict cannot hide behind a passing desktop.
3
+ # WHY PURE AND FIRST. The product turns on one table: which door a target has, and therefore what the
4
+ # action costs the owner. Everything that can go wrong in that table goes wrong identically whether it is
5
+ # buried in a P/Invoke loop or written as a 60-line function, but only the function can be tested in
6
+ # milliseconds against every branch. The measured instruments in scripts/ proved the facts; this file is
7
+ # the part that consumes them, and it is kept free of IO so a wrong verdict cannot hide behind a passing
8
+ # desktop.
9
9
  #
10
10
  # THE FACTS IT CONSUMES, and where each came from:
11
11
  # messageDoor -- 17/57 live windows expose a classic child door (neutral-coverage-census)
@@ -15,24 +15,39 @@
15
15
  # 0/0/0 the same day) -- scripts/uia-tree-content.ps1 re-measures it
16
16
  # uiaProbeFailed-- the probe's own exception, carried out of win.ps1 as a boolean so the code
17
17
  # selection never parses message text
18
- # cursor cost -- zero in every channel (channel-raise-matrix, 0 px across 24 rounds)
18
+ # cursor cost -- zero in the quiet/bounded-flash tiers (channel-raise-matrix, 0 px across 24 rounds);
19
+ # the takeover tier moves it BY REQUEST and must put it back (spec.md §2)
19
20
  # focus cost -- message door 0/6 raise; UIA pattern 6/6 and 12/12 raise
20
- # Each fact is a measurement, not a guess. A fact that was never measured is NOT allowed to
21
- # default to the flattering branch: missing facts refuse, they do not assume quiet.
21
+ # hudReady -- the HUD is up RIGHT NOW (hud.ps1 Test-WpmHudReady); never assumed
22
+ # foregroundIsTarget -- the target (or its child) is the foreground window, which is the only window
23
+ # SendInput writes into (measured: scripts/probe-sendinput-unicode.ps1)
24
+ # Each fact is a measurement, not a guess. A fact that was never measured is NOT allowed to default to
25
+ # the flattering branch: missing facts refuse, they do not assume quiet.
26
+ #
27
+ # FOUR TIERS, and the order the checks run in IS the safety design (spec.md §4):
28
+ # quiet window messages only; cursor 0px, focus untouched, no injection
29
+ # bounded-flash a UIA pattern; one foreground flash, reversed once
30
+ # takeover by explicit request: cursor moves to the point and is restored, focus held until the
31
+ # action ends, keyboard injection only if asked, HUD mandatory
32
+ # refuse a code and an executable next step
33
+ # The takeover tier never ADDS a click channel: a click still goes through message/UIA, SetCursorPos
34
+ # only makes the point visible, and SendInput is the last resort for targets that have no door at all.
22
35
 
23
36
  Set-StrictMode -Version 2.0
24
37
 
25
38
  # Refusal codes are a closed set on purpose. A generic 'failed' would make the product unable to
26
39
  # tell the model why, which is the one thing R3.2 forbids: 'bottoms out to a canned message'.
27
40
  $script:WpmRefusals = @{
28
- no_hwnd = 'no target hwnd supplied; refuse rather than guess from screen coordinates'
29
- paused = 'owner paused input; server-side refusal, not a prompt-level hint'
30
- elevated_target = 'target runs at a higher integrity level; a non-elevated process cannot write to it'
31
- unreachable = 'no message door and no usable UIA pattern; this target cannot be driven without physical input'
32
- uia_tree_empty = 'the accessibility tree holds no content element at all: no pattern can ever appear here, and re-querying has nothing to wait for'
33
- uia_probe_failed = 'the accessibility probe itself threw before it could measure this target; whether a usable pattern exists was never learned'
34
- terminal_no_door = 'terminal text surface exposes no child HWND and no Document element'
35
- needs_facts = 'the caller supplied no measured facts for this target; refusing instead of assuming quiet'
41
+ no_hwnd = 'no target hwnd supplied; refuse rather than guess from screen coordinates'
42
+ paused = 'owner paused input; server-side refusal, not a prompt-level hint'
43
+ elevated_target = 'target runs at a higher integrity level; a non-elevated process cannot write to it, and UIPI refuses synthetic input to it as well'
44
+ unreachable = 'no message door and no usable UIA pattern; this target cannot be driven without physical input'
45
+ uia_tree_empty = 'the accessibility tree holds no content element at all: no pattern can ever appear here, and re-querying has nothing to wait for'
46
+ uia_probe_failed = 'the accessibility probe itself threw before it could measure this target; whether a usable pattern exists was never learned'
47
+ terminal_no_door = 'terminal text surface has child windows but none of them is writable: no WM_CHAR/WM_SETTEXT door and no UIA pattern. Keyboard injection into this host''s terminal was MEASURED not to work (findings §G3: Unicode and scan-code arms both accepted by SendInput, neither executed), so it is not offered as a next step. Next step: pick a target with a real door (an address bar, a text field, a WinForms edit) -- the terminal family remains read-blocked and, on this desktop, write-blocked too'
48
+ needs_facts = 'the caller supplied no measured facts for this target; refusing instead of assuming quiet'
49
+ takeover_unavailable = 'takeover was requested but cannot run safely right now: the HUD is not up, or the takeover gate is off. Next step: enable takeoverAllowed in settings (the HUD is a hard precondition, not a decoration) or call without takeover:true'
50
+ keyinject_unavailable= 'keyboard injection was requested but cannot run: this target is not the foreground window and could not be raised (or it is elevated). Next step: bring the target to the front yourself, or call without keyInput:''inject'''
36
51
  }
37
52
 
38
53
  function New-WpmFacts {
@@ -49,26 +64,33 @@ function New-WpmFacts {
49
64
  [string]$Action = 'click', # click | type | key | scroll
50
65
  [bool]$FactsMeasured = $false,
51
66
  [bool]$UiaTreeEmpty = $false, # the walked tree contained zero content elements (win.ps1 Test-WpmUiaTreeHasContent)
52
- [bool]$UiaProbeFailed = $false # the UIA probe threw; uiaErr carries the exception text (win.ps1)
67
+ [bool]$UiaProbeFailed = $false, # the UIA probe threw; uiaErr carries the exception text (win.ps1)
68
+ [bool]$TakeoverRequested = $false, # caller asked for the takeover tier (takeover:true)
69
+ [bool]$KeyInjectRequested = $false, # caller asked for keyboard injection (keyInput:'inject')
70
+ [bool]$KeyInjectAllowed = $false, # the host gate (keyInjectAllowed) let the request through
71
+ [bool]$HudReady = $false, # hud.ps1 says a HUD window is up RIGHT NOW
72
+ [bool]$ForegroundIsTarget = $false # GetForegroundWindow() (or its root) IS this target
53
73
  )
54
74
  return @{
55
75
  hwnd = $Hwnd; paused = $Paused; elevatedTarget = $ElevatedTarget; family = $Family
56
76
  messageDoor = $MessageDoor; hasPattern = $HasPattern; patternKind = $PatternKind
57
77
  action = $Action; factsMeasured = $FactsMeasured
58
78
  uiaTreeEmpty = $UiaTreeEmpty; uiaProbeFailed = $UiaProbeFailed
79
+ takeoverRequested = $TakeoverRequested; keyInjectRequested = $KeyInjectRequested
80
+ keyInjectAllowed = $KeyInjectAllowed; hudReady = $HudReady; foregroundIsTarget = $ForegroundIsTarget
59
81
  }
60
82
  }
61
83
 
62
84
  function Get-WpmChannelDecision {
63
85
  <#
64
86
  Returns @{ channel; tier; needsRestore; refusal; reason }
65
- channel 'message' | 'uia' | 'refuse'
66
- tier 'quiet' | 'bounded-flash' | 'none'
67
- needsRestore true only for the bounded-flash tier
68
- ORDER OF CHECKS IS THE DESIGN. Pause and elevation are checked before any capability, because a
69
- capability check that runs first can return a working channel for an action that must be
70
- refused outright -- and the caller would then act while paused. The cheapest disqualifiers
71
- come first; the capability table only decides between tiers that are both permitted.
87
+ channel 'message' | 'uia' | 'input' | 'refuse'
88
+ tier 'quiet' | 'bounded-flash' | 'takeover' | 'none'
89
+ needsRestore true only for the tiers that may take the foreground (uia / takeover-through-uia)
90
+ ORDER OF CHECKS IS THE DESIGN. Pause, elevation and the takeover preconditions are checked before any
91
+ capability, because a capability check that runs first can return a working channel for an action that
92
+ must be refused outright. The cheapest disqualifiers come first; the capability table only decides
93
+ between tiers that are both permitted.
72
94
  #>
73
95
  param([hashtable]$Facts)
74
96
 
@@ -88,28 +110,63 @@ function Get-WpmChannelDecision {
88
110
  return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
89
111
  refusal = 'elevated_target'; reason = $script:WpmRefusals.elevated_target }
90
112
  }
91
- # Terminal is its own code, not folded into 'unreachable': the two have different fixes (one is
92
- # "pick another target", the other is "this class will never work"), and a product that reports
93
- # one generic failure cannot be diagnosed by the person reading the output.
94
- if ($Facts.family -eq 'terminal' -and -not $Facts.messageDoor -and -not $Facts.hasPattern) {
113
+
114
+ # ---- R3 preconditions. These are refusals about the REQUEST, not about the target, and they come
115
+ # before the door table because a takeover that cannot show its HUD must not reach any primitive.
116
+ if ($Facts.takeoverRequested -and -not $Facts.hudReady) {
95
117
  return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
96
- refusal = 'terminal_no_door'; reason = $script:WpmRefusals.terminal_no_door }
118
+ refusal = 'takeover_unavailable'; reason = $script:WpmRefusals.takeover_unavailable }
119
+ }
120
+ if ($Facts.keyInjectRequested -and (-not $Facts.takeoverRequested -or -not $Facts.keyInjectAllowed)) {
121
+ # Injection is allowed ONLY inside the takeover tier (spec.md §1: SendInput writes to the foreground,
122
+ # so without the HUD and the cursor contract it would be a blind keystroke into whatever is in front).
123
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
124
+ refusal = 'keyinject_unavailable'; reason = $script:WpmRefusals.keyinject_unavailable }
125
+ }
126
+ if ($Facts.keyInjectRequested -and -not $Facts.foregroundIsTarget) {
127
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
128
+ refusal = 'keyinject_unavailable'; reason = $script:WpmRefusals.keyinject_unavailable }
97
129
  }
98
130
 
131
+ $tier = if ($Facts.takeoverRequested) { 'takeover' } else { 'quiet' }
132
+
99
133
  # TIER 1: message door. Measured free -- 0/6 raises, effect verified app-side in 6/6, cursor 0 px.
100
- # Preferred whenever it exists, which INVERTS the original R2.2 priority (UIA first). The
101
- # original order preferred the channel that steals focus; this one prefers the channel that
102
- # does not. That inversion is the whole point of R2'.
134
+ # Preferred whenever it exists, which INVERTS the original R2.2 priority (UIA first). The original
135
+ # order preferred the channel that steals focus; this one prefers the channel that does not.
103
136
  if ($Facts.messageDoor) {
104
- return @{ channel = 'message'; tier = 'quiet'; needsRestore = $false; refusal = ''; reason = 'classic child window accepts target-window messages' }
137
+ return @{ channel = 'message'; tier = $tier; needsRestore = $false; refusal = ''
138
+ reason = 'classic child window accepts target-window messages' }
105
139
  }
106
140
 
107
141
  # TIER 2: UIA pattern. Measured to raise 6/6 and 12/12, therefore it always needs restoration.
108
- # A pattern with no path to restoration would be a permanent focus theft, so the caller is told
109
- # needsRestore=true and must honour it; the decision itself does not attempt the restore because
110
- # a pure function cannot.
111
142
  if ($Facts.hasPattern -and $Facts.patternKind -ne 'none') {
112
- return @{ channel = 'uia'; tier = 'bounded-flash'; needsRestore = $true; refusal = ''; reason = "UIA $($Facts.patternKind) pattern available; costs one bounded foreground flash" }
143
+ return @{ channel = 'uia'; tier = $tier; needsRestore = $true; refusal = ''
144
+ reason = "UIA $($Facts.patternKind) pattern available" + $(if ($Facts.takeoverRequested) { '; takeover keeps the focus until the action ends, then restores it' } else { '; costs one bounded foreground flash' }) }
145
+ }
146
+
147
+ # TIER 3: no door at all. A terminal is the measured case (findings §B): three child HWNDs, none
148
+ # writable.
149
+ #
150
+ # THE TERMINAL INJECTION PATH WAS WITHDRAWN ON MEASURED EVIDENCE, and this branch is where that decision
151
+ # lives. R3's plan was to drive a terminal by typing into it once the owner asked for takeover+inject.
152
+ # Two independent probes say it does not work on this host (findings §G3, 2026-11-23):
153
+ # * scripts/probe-console-inject.ps1 -- KEYEVENTF_UNICODE: 242 events accepted by SendInput, the
154
+ # foreground WAS the terminal, Enter was pressed, and the shell never executed the typed command;
155
+ # * scripts/probe-console-scan.ps1 -- KEYEVENTF_SCANCODE with the layout's own VK mapping: 262
156
+ # events, same setup, still nothing executed.
157
+ # So "the only door left is the keyboard" was wrong for the terminal family on this desktop, and making
158
+ # the code path look like a capability would be a promise the product cannot keep. The refusal keeps its
159
+ # diagnostic value and points at what DOES work (a target with a real door).
160
+ if ($Facts.family -eq 'terminal' -and -not $Facts.messageDoor -and -not $Facts.hasPattern) {
161
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
162
+ refusal = 'terminal_no_door'; reason = $script:WpmRefusals.terminal_no_door }
163
+ }
164
+
165
+ # A doorless, patternless NON-terminal target can also be driven by injection when explicitly asked:
166
+ # the measured UWP/Chromium families sometimes expose neither door, and the keyboard is real input.
167
+ if ($Facts.takeoverRequested -and $Facts.keyInjectRequested -and $Facts.factsMeasured) {
168
+ return @{ channel = 'input'; tier = 'takeover'; needsRestore = $false; refusal = ''
169
+ reason = 'no message door and no usable pattern; typing into the foreground target at the owner''s explicit request' }
113
170
  }
114
171
 
115
172
  # Neither door. Refuse, and say which one was missing -- an unmeasured target must not be
@@ -119,18 +176,14 @@ function Get-WpmChannelDecision {
119
176
  refusal = 'needs_facts'; reason = $script:WpmRefusals.needs_facts }
120
177
  }
121
178
 
122
- # THREE WORLDS USED TO SHARE ONE CODE ('unreachable'), and they have different fixes, which is
123
- # why they stopped sharing it (2026-11-21: 0.1.5's point-probe fix exposed uiaErr arriving here
124
- # as dead data; the census the same day exposed the tree split). A tree with NO content element
125
- # needs the APPLICATION to enable accessibility -- launch-time for Chromium
126
- # (--force-renderer-accessibility); re-querying cannot help, which is exactly why no retry or
127
- # polling exists anywhere in this engine. A probe that THREW means the measurement itself
128
- # failed, so no conclusion about the target is licensed -- the exception text rides the reason
129
- # (engine.ps1 appends it), and the caller reads it instead of guessing. The plain door-less
130
- # case with a live tree means 'pick another target or point'. Probe failure outranks
131
- # tree-empty: a measurement that threw cannot also certify emptiness. And a usable door still
132
- # outranks every diagnosis -- these branches only replace the terminal refusal, never a
133
- # working channel.
179
+ # THREE WORLDS USED TO SHARE ONE CODE ('unreachable'), and they have different fixes, which is why they
180
+ # stopped sharing it (2026-11-21: 0.1.5's point-probe fix exposed uiaErr arriving here as dead data; the
181
+ # census the same day exposed the tree split). A tree with NO content element needs the APPLICATION to
182
+ # enable accessibility -- launch-time for Chromium (--force-renderer-accessibility); re-querying cannot
183
+ # help, which is exactly why no retry or polling exists anywhere in this engine. A probe that THREW
184
+ # means the measurement itself failed, so no conclusion about the target is licensed -- the exception
185
+ # text rides the reason (engine.ps1 appends it). Probe failure outranks tree-empty: a measurement that
186
+ # threw cannot also certify emptiness. And a usable door still outranks every diagnosis.
134
187
  if ($Facts.uiaProbeFailed) {
135
188
  return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
136
189
  refusal = 'uia_probe_failed'; reason = $script:WpmRefusals.uia_probe_failed }
@@ -145,9 +198,9 @@ function Get-WpmChannelDecision {
145
198
 
146
199
  function Get-WpmRestoreDecision {
147
200
  <#
148
- Whether to put the focus back after a bounded-flash action, and why.
149
- This is the safety property of R2'.4-R2'.7 expressed as a table, because these are the
150
- branches that, if wrong, act on a window the product does not own.
201
+ Whether to put the focus back after an action that may have taken it, and why.
202
+ This is the safety property of R2'.4-R2'.7 expressed as a table, because these are the branches
203
+ that, if wrong, act on a window the product does not own.
151
204
 
152
205
  currentFg == raisedHwnd -> restore (we caused it, we undo it)
153
206
  currentFg pid == target pid -> skip: dialog (the app deliberately focused its own dialog)
@@ -155,9 +208,9 @@ function Get-WpmRestoreDecision {
155
208
  nothing was raised -> skip: nothing (restoring here would fight the user)
156
209
  restore already attempted once -> skip: done (one-shot; a watchdog would fight the owner)
157
210
 
158
- The dialog branch is not a nicety: without it, restoring after an action that opened a Save
159
- dialog pulls the focus out of the dialog the action just created, so the box is visible and
160
- unresponsive. Same-pid is the discriminator because the dialog belongs to the target process.
211
+ The dialog branch is not a nicety: without it, restoring after an action that opened a Save dialog
212
+ pulls the focus out of the dialog the action just created, so the box is visible and unresponsive.
213
+ Same-pid is the discriminator because the dialog belongs to the target process.
161
214
  #>
162
215
  param(
163
216
  [string]$CurrentFg = '',
@@ -1,4 +1,4 @@
1
- # engine.ps1 -- the only place where a decision becomes a syscall.
1
+ # engine.ps1 -- the only place where a decision becomes a syscall.
2
2
  #
3
3
  # One entry point, Invoke-WpmAction, and it always returns a result object rather than throwing on
4
4
  # a refusal: 'refused' is a normal outcome of this product, not an error path, and R3.2 requires
@@ -45,11 +45,18 @@ function Get-WpmStatus {
45
45
  # Ctrl+Alt+Q promise untrue with no way to notice.
46
46
  overlayRunning = [bool][WpmCtl]::OverlayOn
47
47
  overlayHwnd = [string][WpmCtl]::OverlayHwnd
48
+ # The HUD travels with status for the same reason the overlay does: "the takeover surface exists"
49
+ # must be checkable by the owner and by an independent oracle, not inferred from a successful call.
50
+ hudOn = [bool][WpmCtl]::HudOn
51
+ hudHwnd = [string][WpmCtl]::HudHwnd
52
+ hudPhase = [string][WpmCtl]::HudPhase
53
+ abortChord = [string][WpmCtl]::AbortChordLabel
54
+ abortRequested = [bool][WpmCtl]::TakeoverAbort
48
55
  hotkeyRegistered = [bool][WpmCtl]::HotkeyOk
49
56
  hotkeyLabel = [string][WpmCtl]::HotkeyLabel
50
57
  overlayReason = [string][WpmCtl]::Reason
51
58
  dpiAware = [bool]$script:WpmDpiAware
52
- stance = 'no physical injection; no forged-Alt foreground trick'
59
+ stance = 'quiet tier: no physical input at all; takeover tier (opt-in, HUD mandatory): cursor moves and is always restored, keyboard typed only when asked, three interrupt paths, no mouse injection'
53
60
  }
54
61
  }
55
62
 
@@ -140,7 +147,16 @@ function Invoke-WpmAction {
140
147
  [string]$Text = '',
141
148
  [string]$ElementName = '',
142
149
  [switch]$Replace,
143
- [int]$SettleMs = 350
150
+ [int]$SettleMs = 350,
151
+ # ---- R3 ------------------------------------------------------------------------------------
152
+ # Takeover is a REQUEST with preconditions, never a flag that silently upgrades an action
153
+ # (spec.md §4). TakeoverArmMs is the cancellation window; HudDoneMs is how long the "returned"
154
+ # phase stays on screen before the HUD is torn down.
155
+ [switch]$Takeover,
156
+ [int]$TakeoverMaxMs = 10000,
157
+ [switch]$KeyInject,
158
+ [int]$TakeoverArmMs = 800,
159
+ [int]$HudDoneMs = 1500
144
160
  )
145
161
  $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
146
162
  $h = [IntPtr][int64]$Hwnd
@@ -149,6 +165,10 @@ function Invoke-WpmAction {
149
165
  refusal = ''; reason = ''; detail = ''; latencyMs = 0
150
166
  focusTaken = 'false'; restoreOutcome = ''; restoreSetFg = ''; restoreJoined = ''
151
167
  effect = 'unverified'; proofSamples = @()
168
+ # R3 fields. Empty strings rather than $null so the host half can test truthiness without
169
+ # distinguishing "not a takeover" from "a takeover that said nothing".
170
+ takeover = 'false'; cursorMoved = ''; cursorRestored = ''; takeoverMs = 0
171
+ abortChord = ''; keysInjected = 0; injectedChars = 0
152
172
  }
153
173
 
154
174
  # A QUERY IS NOT AN ACTION, and this branch is early on purpose. It used to sit inside the action
@@ -190,11 +210,85 @@ function Invoke-WpmAction {
190
210
  # to raise the window would report the cheap tier for the expensive action.
191
211
  $facts.messageDoor = $false
192
212
  }
213
+ # ---- R3: the takeover request, and the HUD that must exist BEFORE the table can approve it ----
214
+ # Order is the safety design: cheap disqualifiers first (a paused or elevated refusal must never spawn
215
+ # a window), then the HUD, then the full decision. $Facts.hudReady is therefore a MEASUREMENT of the
216
+ # HUD that was actually started, not an assumption that "we are about to start one".
217
+ $facts.takeoverRequested = [bool]$Takeover
218
+ $facts.keyInjectRequested = [bool]$KeyInject
219
+ $facts.keyInjectAllowed = [bool]$KeyInject # the host gate already stripped the field when off
220
+ $facts.hudReady = $false
221
+ $facts.foregroundIsTarget = $false
222
+ $preFacts = $facts.Clone()
223
+ $preFacts.takeoverRequested = $false
224
+ $preFacts.keyInjectRequested = $false
225
+ $pre = Get-WpmChannelDecision $preFacts
226
+ if ($pre.channel -eq 'refuse' -and (@('paused', 'no_hwnd', 'elevated_target') -contains $pre.refusal)) {
227
+ $result.refusal = $pre.refusal; $result.reason = $pre.reason
228
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
229
+ return $result
230
+ }
231
+ # BEFORE ANY RAISE. If the injection path has to bring the target forward, the focus table must be
232
+ # captured first, or the raise looks like a third party's and would never be reversed.
233
+ $entry = Get-WpmFocusEntry
234
+ $hudStarted = $false
235
+ $raisedByUs = $false
236
+ if ($facts.takeoverRequested) {
237
+ # G2: the two primitive modules are dot-sourced INSIDE this branch and nowhere else. The quiet and
238
+ # bounded-flash tiers never even load SetCursorPos/SendInput into the session.
239
+ . (Join-Path $PSScriptRoot 'takeover.ps1')
240
+ . (Join-Path $PSScriptRoot 'input-inject.ps1')
241
+ . (Join-Path $PSScriptRoot 'hud.ps1')
242
+ # A CANCELLATION THAT ARRIVES DURING SETUP MUST NOT BE THROWN AWAY. The host writes the latch as soon as
243
+ # the signal fires, and setup (module load + HUD start) can take longer than that. Clearing the latch
244
+ # unconditionally at this point would delete a cancellation that was meant for THIS call -- measured
245
+ # with test/signal-test.mjs: the abort landed, the latch was written, and the action ran to completion.
246
+ # So: snapshot, then clear (a stale latch from a crashed action must not poison every later call), then
247
+ # honour what was found.
248
+ $preAborted = Test-WpmTakeoverAbort
249
+ Reset-WpmTakeoverAbort | Out-Null
250
+ $armClamped = [Math]::Max(0, [Math]::Min(5000, $TakeoverArmMs))
251
+ $maxClamped = [Math]::Max(500, [Math]::Min(60000, $TakeoverMaxMs))
252
+ $hud = Start-WpmHud -Action $Action -MaxMs $maxClamped -ArmMs $armClamped
253
+ $hudStarted = [bool]$hud.ready
254
+ $facts.hudReady = $hudStarted
255
+ if ($facts.keyInjectRequested -and $hudStarted -and -not $facts.elevatedTarget) {
256
+ # S1: SendInput writes to the FOREGROUND window. One raise attempt through the same input-queue
257
+ # unlock the focus restore uses, then re-measure -- a decision made now is evidence; a decision
258
+ # made 800ms ago is not.
259
+ $fg0 = Test-WpmTargetForeground -Hwnd $Hwnd
260
+ if (-not $fg0.ok) {
261
+ $raised = [WpmWin]::RestoreForeground([IntPtr]$h)
262
+ if ($raised -like 'true*') { $raisedByUs = $true }
263
+ Start-Sleep -Milliseconds 60
264
+ }
265
+ $fg1 = Test-WpmTargetForeground -Hwnd $Hwnd
266
+ $facts.foregroundIsTarget = [bool]$fg1.ok
267
+ }
268
+ }
193
269
  $decision = Get-WpmChannelDecision $facts
270
+ # G3, and not ceremony: the HUD runs on its own thread and can fail between Start-WpmHud and here. The
271
+ # decision approved takeover on a fact measured a moment ago; re-measure before a primitive exists in
272
+ # the call path. scripts/check-takeover-path.mjs asserts this check sits between the branch entry and
273
+ # every call to Set-WpmCursorTakeover / Send-WpmKeyText.
274
+ if ($facts.takeoverRequested -and $decision.tier -eq 'takeover' -and -not (Test-WpmHudReady)) {
275
+ if ($hudStarted) { [void](Stop-WpmHud) }
276
+ $result.refusal = 'takeover_unavailable'
277
+ $result.reason = $script:WpmRefusals.takeover_unavailable + ' [the HUD stopped between start and arming]'
278
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
279
+ return $result
280
+ }
281
+ if ($raisedByUs -and -not $decision.needsRestore) {
282
+ # We moved the owner's foreground for the injection; the same table that reverses a UIA flash has to
283
+ # reverse this too, or "we only borrow what we give back" would have a hole exactly where the
284
+ # loudest primitive is.
285
+ $decision.needsRestore = $true
286
+ }
194
287
 
195
288
  $result.channel = $decision.channel; $result.tier = $decision.tier
196
289
  $result.family = $probe.family; $result.cls = $probe.cls
197
290
  if ($decision.channel -eq 'refuse') {
291
+ if ($hudStarted) { [void](Stop-WpmHud) }
198
292
  $result.refusal = $decision.refusal; $result.reason = $decision.reason
199
293
  # A refusal that says only 'unreachable' makes the reader guess which of two very different
200
294
  # things happened. When the point probe ran, it knows: the point is outside the target, or the
@@ -212,10 +306,9 @@ function Invoke-WpmAction {
212
306
  return $result
213
307
  }
214
308
 
215
- # Capture the focus table BEFORE the action when the tier may cost a flash. For the quiet tier it
216
- # is still captured, because 'the quiet channel did not take focus' is a claim that needs a
217
- # before-value to be falsifiable.
218
- $entry = Get-WpmFocusEntry
309
+ # The focus table was captured above (before any raise). For the quiet tier it is still needed,
310
+ # because 'the quiet channel did not take focus' is a claim that needs a before-value to be
311
+ # falsifiable.
219
312
  $raisedHwnd = ''
220
313
  # THE PRE-ACTION CONTROL WINDOW. Sampled here, immediately BEFORE the door call, so that during it,
221
314
  # by construction, WE have done nothing. WHY A CONTROL IS REQUIRED AND NOT JUST A THRESHOLD:
@@ -231,8 +324,54 @@ function Invoke-WpmAction {
231
324
  $controlSamples = Get-WpmProofWindow -Ms 80
232
325
  $tAct = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
233
326
 
327
+ # ---- the takeover choreography (spec.md §3) -------------------------------------------------
328
+ # Everything from here to the finally exists because R3 promises three things the quiet tier never
329
+ # did: the pointer move is VISIBLE (so the owner is warned before it costs them anything), the
330
+ # pointer is ALWAYS returned, and the whole thing can be interrupted from three different places.
331
+ $takeover = ($decision.tier -eq 'takeover')
332
+ $cursorEntry = $null
333
+ $abortedBeforeAct = $false
334
+ $abortedByPause = $false
335
+ $abortedDuringSetup = $false
336
+ # $preAborted is NOT re-initialised here: it was snapshotted before Reset-WpmTakeoverAbort cleared the
337
+ # flag, and re-zeroing it at this point silently discarded a cancellation that arrived during setup.
338
+ # (Measured by test/signal-test.mjs -- the abort landed, the latch existed, and the action still ran.)
339
+ $takeoverStartMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
340
+ if ($takeover) {
341
+ $result.takeover = 'true'
342
+ if ($preAborted) { $abortedBeforeAct = $true; $abortedDuringSetup = $true }
343
+ $result.hudHwnd = [string][WpmCtl]::HudHwnd
344
+ # ARMING is a real cancellation window, not a sleep: all three interruption paths are read every
345
+ # 50ms, and the HUD clock is updated so a long arming still shows progress.
346
+ $armMs = [Math]::Max(0, [Math]::Min(5000, $TakeoverArmMs))
347
+ $armDeadline = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + $armMs
348
+ Set-WpmHudPhase -Phase 'arming' -Action $Action -MaxMs $TakeoverMaxMs -ElapsedMs 0 | Out-Null
349
+ while ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -lt $armDeadline) {
350
+ # C12: the PAUSE switch is an interruption too, not a flag only read at decision time. The owner can
351
+ # press it while the HUD is counting, and the promise is "stops now", not "stops next time".
352
+ if (Test-WpmTakeoverAbort) { $abortedBeforeAct = $true; break }
353
+ if ([WpmCtl]::Paused) { $abortedBeforeAct = $true; $abortedByPause = $true; break }
354
+ Set-WpmHudPhase -Phase 'arming' -ElapsedMs ([int]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $takeoverStartMs)) | Out-Null
355
+ Start-Sleep -Milliseconds 50
356
+ }
357
+ if (-not $abortedBeforeAct) { Set-WpmHudPhase -Phase 'active' | Out-Null }
358
+ }
359
+
234
360
  try {
235
- if ($decision.channel -eq 'message') {
361
+ # THE CURSOR MOVE LIVES INSIDE THE SAME try THAT OWNS THE RESTORE (spec.md §6 G4): an exception in
362
+ # the door call below still reaches the finally that puts the pointer back.
363
+ if ($takeover -and -not $abortedBeforeAct -and $Action -eq 'click' -and $X -ge 0 -and $Y -ge 0) {
364
+ $cursorEntry = Set-WpmCursorTakeover -X $X -Y $Y
365
+ $result.cursorMoved = if ($cursorEntry.applied) { 'true' } else { 'false' }
366
+ $result.cursorX = [int]$cursorEntry.x
367
+ $result.cursorY = [int]$cursorEntry.y
368
+ $result.cursorBeforeX = [int]$cursorEntry.beforeX
369
+ $result.cursorBeforeY = [int]$cursorEntry.beforeY
370
+ }
371
+ if ($abortedBeforeAct) {
372
+ $result.refusal = 'takeover_aborted'
373
+ $result.reason = if ($abortedByPause) { 'the owner paused the engine during the arming window; nothing was clicked or typed' } elseif ($abortedDuringSetup) { 'cancelled by the host before the arming window opened; nothing was clicked or typed' } else { 'interrupted during the arming window; nothing was clicked or typed' }
374
+ } elseif ($decision.channel -eq 'message') {
236
375
  if ($Action -eq 'type') {
237
376
  # The door kind is decided ONCE, in the probe (win.ps1), and consumed here by kind.
238
377
  # This path used to re-match class names with its own copy of the pattern -- and that copy
@@ -266,6 +405,29 @@ function Invoke-WpmAction {
266
405
  $result.detail = "msg=$r child=$($child.ToInt64())"
267
406
  $result.effect = 'reported-by-send'
268
407
  }
408
+ } elseif ($decision.channel -eq 'input') {
409
+ # THE MEASURED DOORLESS CASE (a terminal, findings §B): typing into the FOREGROUND window. The
410
+ # foreground assertion is repeated here, at the moment of sending, because the desktop can change
411
+ # during the arming window -- the decision's fact is evidence about then, not about now.
412
+ $fgNow = Test-WpmTargetForeground -Hwnd $Hwnd
413
+ if (-not $fgNow.ok) {
414
+ $result.refusal = 'keyinject_unavailable'
415
+ $result.reason = $script:WpmRefusals.keyinject_unavailable + ' [foreground at send time: ' + $fgNow.foreground + ']'
416
+ } else {
417
+ # The pause switch rides the same abort probe: a long injection must stop when the owner says so.
418
+ $inj = Send-WpmKeyText -Text $Text -ShouldAbort { (Test-WpmTakeoverAbort) -or [WpmCtl]::Paused }
419
+ $result.detail = 'inject=unicode chars=' + $inj.chars + ' events=' + $inj.sent
420
+ $result.keysInjected = [int]$inj.sent
421
+ $result.injectedChars = [int]$inj.chars
422
+ $result.effect = if ($inj.chars -gt 0) { 'reported-by-send' } else { 'unverified' }
423
+ if ($inj.aborted) {
424
+ $result.refusal = 'takeover_aborted'
425
+ $result.reason = $inj.reason
426
+ } elseif (-not $inj.ok) {
427
+ $result.refusal = 'keyinject_unavailable'
428
+ $result.reason = $inj.reason
429
+ }
430
+ }
269
431
  } elseif ($Action -eq 'focus') {
270
432
  # Focusing a control is a real operation an agent needs (type into a field, then read it).
271
433
  # It is also the one action that MUST change keyboard focus, so it is the honest way to
@@ -314,6 +476,37 @@ function Invoke-WpmAction {
314
476
  $result.refusal = 'action_failed'
315
477
  $result.reason = 'the channel call threw: ' + $_.Exception.Message
316
478
  $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
479
+ } finally {
480
+ # THE BORROWED POINTER IS RETURNED HERE, UNCONDITIONALLY. Success, exception, refusal and
481
+ # interruption all arrive at this block, which is the whole reason the move was placed inside the
482
+ # try above. 'restored' is the READ-BACK, not the intent: a restore the OS refused reports
483
+ # cursorRestored=false and becomes a hard proof failure downstream (spec.md §6, C5).
484
+ if ($takeover) {
485
+ if ($cursorEntry) {
486
+ $cur = Restore-WpmCursorTakeover -Entry $cursorEntry
487
+ $result.cursorRestored = if ($cur.restored) { 'true' } else { 'false' }
488
+ $result.cursorAfterX = [int]$cur.x
489
+ $result.cursorAfterY = [int]$cur.y
490
+ if (-not $cur.restored) { $result.cursorRestoreReason = $cur.reason }
491
+ } else {
492
+ # No click point, so nothing was borrowed: the honest report is restored=true with moved=false.
493
+ $result.cursorRestored = 'true'
494
+ }
495
+ $result.injectedChars = [int][WpmCtl]::InjectedChars
496
+ $result.abortChord = [string][WpmCtl]::AbortChordLabel
497
+ $result.takeoverMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $takeoverStartMs
498
+ if ($TakeoverMaxMs -gt 0 -and $result.takeoverMs -gt $TakeoverMaxMs) {
499
+ $result.takeoverNote = 'the action exceeded takeoverMaxMs=' + $TakeoverMaxMs + '; it was still restored'
500
+ }
501
+ # A LATCH LEFT BEHIND WOULD ABORT THE NEXT CALL. The host clears its own copy on dispose, but the
502
+ # worker pid outlives a single action, so the engine clears it here as well -- after the restore, so
503
+ # an interruption that arrives during cleanup is still visible to this action's own accounting.
504
+ Reset-WpmTakeoverAbort | Out-Null
505
+ Set-WpmHudPhase -Phase 'done' -ElapsedMs ([int]$result.takeoverMs) | Out-Null
506
+ $dwell = if ($result.refusal) { 120 } else { [Math]::Max(0, [Math]::Min(5000, $HudDoneMs)) }
507
+ if ($dwell -gt 0) { Start-Sleep -Milliseconds $dwell }
508
+ [void](Stop-WpmHud)
509
+ }
317
510
  }
318
511
 
319
512
  # THE ACTION WINDOW. Sampled DURING the settle sleep the engine already performed, so collecting