dsh-windows-parallel-mcp 0.8.2 → 0.9.0-rc.2

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.
Files changed (53) hide show
  1. package/CHANGELOG.de.md +444 -419
  2. package/CHANGELOG.es.md +444 -419
  3. package/CHANGELOG.fr.md +444 -419
  4. package/CHANGELOG.it.md +444 -419
  5. package/CHANGELOG.ja.md +444 -419
  6. package/CHANGELOG.ko.md +444 -419
  7. package/CHANGELOG.md +965 -940
  8. package/CHANGELOG.pt.md +444 -419
  9. package/CHANGELOG.ru.md +444 -419
  10. package/CHANGELOG.zh.md +444 -419
  11. package/INSTALL.de.md +126 -126
  12. package/INSTALL.es.md +126 -126
  13. package/INSTALL.fr.md +126 -126
  14. package/INSTALL.it.md +126 -126
  15. package/INSTALL.ja.md +126 -126
  16. package/INSTALL.ko.md +126 -126
  17. package/INSTALL.md +122 -122
  18. package/INSTALL.pt.md +126 -126
  19. package/INSTALL.ru.md +126 -126
  20. package/INSTALL.zh.md +126 -126
  21. package/README.de.md +684 -684
  22. package/README.es.md +684 -684
  23. package/README.fr.md +684 -684
  24. package/README.it.md +684 -684
  25. package/README.ja.md +684 -684
  26. package/README.ko.md +684 -684
  27. package/README.md +680 -680
  28. package/README.pt.md +684 -684
  29. package/README.ru.md +684 -684
  30. package/README.zh.md +684 -684
  31. package/cordis.patch.yml +15 -15
  32. package/docs/refusals.md +90 -90
  33. package/docs/takeover.md +128 -128
  34. package/dsh.plugin.json +18 -18
  35. package/lib/config.js +275 -275
  36. package/lib/engine.js +252 -252
  37. package/lib/host-tools.js +365 -338
  38. package/lib/index.js +1275 -1249
  39. package/lib/peers-schemastery.js +23 -23
  40. package/lib/peers-tools.js +15 -15
  41. package/lib/proof-window.mjs +427 -427
  42. package/package.json +122 -122
  43. package/server.json +110 -110
  44. package/src/engine/decide.ps1 +356 -356
  45. package/src/engine/engine.ps1 +1208 -1208
  46. package/src/engine/hud.ps1 +411 -411
  47. package/src/engine/input-inject.ps1 +176 -176
  48. package/src/engine/overlay.ps1 +389 -389
  49. package/src/engine/takeover.ps1 +144 -144
  50. package/src/engine/win.ps1 +1881 -1881
  51. package/src/engine/worker.ps1 +310 -310
  52. package/src/schema/tools.json +533 -533
  53. package/types/index.d.ts +190 -187
@@ -1,356 +1,356 @@
1
- # decide.ps1 -- the channel decision, as a PURE function.
2
- #
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
- #
10
- # THE FACTS IT CONSUMES, and where each came from:
11
- # messageDoor -- 17/57 live windows expose a classic child door (neutral-coverage-census)
12
- # hasPattern -- WPF/UWP/Chromium expose UIA patterns; WinForms exposes none (probe-winform)
13
- # uiaTreeEmpty -- an a11y-off Chromium window walks to ZERO content elements and never grows
14
- # one under re-query (uTools 1/1/1 raw, 0/0/0 content, 2026-11-21; census read
15
- # 0/0/0 the same day) -- scripts/uia-tree-content.ps1 re-measures it
16
- # uiaProbeFailed-- the probe's own exception, carried out of win.ps1 as a boolean so the code
17
- # selection never parses message text
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)
20
- # focus cost -- message door 0/6 raise; UIA pattern 6/6 and 12/12 raise
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.
35
-
36
- Set-StrictMode -Version 2.0
37
-
38
- # Refusal codes are a closed set on purpose. A generic 'failed' would make the product unable to
39
- # tell the model why, which is the one thing R3.2 forbids: 'bottoms out to a canned message'.
40
- $script:WpmRefusals = @{
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'''
51
- # ---- 0.7.0 authorization model. Three codes, each naming the NEXT STEP rather than describing the
52
- # symptom, because all three are settings decisions and a caller that cannot tell which setting to
53
- # raise will retry the same call forever.
54
- policy_denied = 'the action''s declared tier is above what the policy setting allows. Next step: raise policy in settings (readonly < quiet < balanced < full) -- NOT retrying this call'
55
- user_active = 'the owner was at the keyboard when this was asked for (last physical input younger than policyIdleMs) and the action needs the takeover tier. This product does not open a dialog at someone who is typing -- a popup is a second disturbance dressed as consent. Next step: wait for idle, or pass forceUserActive:true explicitly (it is recorded in the audit log as forced)'
56
- app_launch_denied = 'launch is not authorised: appLaunchAllowed is off, or the program is not on the appLaunchAllow whitelist (an empty whitelist means nothing may launch). Next step: the OWNER adds the exact name to the whitelist; a wildcard does not exist and this refusal is not a transient failure to retry through'
57
- }
58
-
59
- # THE LADDER, mirrored from lib/policy.js. Two copies of an ordering is normally the bug pattern this
60
- # repo refuses, and it is allowed here for exactly one reason: the engine and the host each need the
61
- # comparison in their own process, and scripts/check-policy-table.mjs asserts the two copies agree
62
- # (rung set, order, and every action's declared tier in tools.json). A drift between them is red at build
63
- # time instead of being a permission the owner believes they revoked.
64
- $script:WpmTierOrder = @('readonly', 'quiet', 'flash', 'takeover')
65
- $script:WpmPolicyCeiling = @{
66
- readonly = 'readonly'; quiet = 'quiet'; balanced = 'flash'; full = 'takeover'
67
- }
68
-
69
- function Test-WpmTierAllowed {
70
- # Pure, and it fails CLOSED in both directions: an unknown policy or an unknown rung answers false.
71
- # "Unparseable setting" and "everything allowed" must never read the same way.
72
- param([string]$Policy, [string]$Required)
73
- if (-not $script:WpmPolicyCeiling.ContainsKey($Policy)) { return $false }
74
- $need = [Array]::IndexOf($script:WpmTierOrder, $Required)
75
- if ($need -lt 0) { return $false }
76
- return $need -le [Array]::IndexOf($script:WpmTierOrder, $script:WpmPolicyCeiling[$Policy])
77
- }
78
-
79
- function New-WpmFacts {
80
- # Explicit constructor so a missing field is a compile-time-shaped mistake in review rather
81
- # than a silent $null that compares false and lands in the quiet branch.
82
- param(
83
- [string]$Hwnd = '',
84
- [bool]$Paused = $false,
85
- [bool]$ElevatedTarget = $false,
86
- [string]$Family = 'unknown', # win32-classic | winforms | wpf | uwp | chromium | terminal | unknown
87
- [bool]$MessageDoor = $false,
88
- [bool]$HasPattern = $false,
89
- [string]$PatternKind = 'none', # invoke | value | toggle | selectionitem | legacy | none
90
- [string]$Action = 'click', # click | type | key | scroll
91
- [bool]$FactsMeasured = $false,
92
- [bool]$UiaTreeEmpty = $false, # the walked tree contained zero content elements (win.ps1 Test-WpmUiaTreeHasContent)
93
- [bool]$UiaProbeFailed = $false, # the UIA probe threw; uiaErr carries the exception text (win.ps1)
94
- [bool]$TakeoverRequested = $false, # caller asked for the takeover tier (takeover:true)
95
- [bool]$KeyInjectRequested = $false, # caller asked for keyboard injection (keyInput:'inject')
96
- [bool]$KeyInjectAllowed = $false, # the host gate (keyInjectAllowed) let the request through
97
- [bool]$HudReady = $false, # hud.ps1 says a HUD window is up RIGHT NOW
98
- [bool]$ForegroundIsTarget = $false, # GetForegroundWindow() (or its root) IS this target
99
- # ---- 0.7.0 authorization facts, supplied by the caller because decide.ps1 does no IO: it cannot
100
- # read settings, and a table that read its own permissions could not be unit-tested.
101
- [string]$Policy = 'balanced', # the ceiling the owner set (readonly|quiet|balanced|full)
102
- [string]$RequiredTier = 'quiet', # what THIS action needs at minimum (tools.json#requiresTier)
103
- [long]$LastInputAgeMs = -1, # -1 = UNKNOWN; unknown refuses, it does not mean "idle"
104
- [int]$PolicyIdleMs = 3000,
105
- [bool]$ForceUserActive = $false, # the caller's explicit override, recorded in the audit
106
- [bool]$AppLaunchAllowed = $false,
107
- [string[]]$AppLaunchAllow = @(),
108
- [string]$LaunchTarget = ''
109
- )
110
- return @{
111
- hwnd = $Hwnd; paused = $Paused; elevatedTarget = $ElevatedTarget; family = $Family
112
- messageDoor = $MessageDoor; hasPattern = $HasPattern; patternKind = $PatternKind
113
- action = $Action; factsMeasured = $FactsMeasured
114
- uiaTreeEmpty = $UiaTreeEmpty; uiaProbeFailed = $UiaProbeFailed
115
- takeoverRequested = $TakeoverRequested; keyInjectRequested = $KeyInjectRequested
116
- keyInjectAllowed = $KeyInjectAllowed; hudReady = $HudReady; foregroundIsTarget = $ForegroundIsTarget
117
- policy = $Policy; requiredTier = $RequiredTier
118
- lastInputAgeMs = $LastInputAgeMs; policyIdleMs = $PolicyIdleMs; forceUserActive = $ForceUserActive
119
- appLaunchAllowed = $AppLaunchAllowed; appLaunchAllow = $AppLaunchAllow; launchTarget = $LaunchTarget
120
- }
121
- }
122
-
123
- function Get-WpmChannelDecision {
124
- <#
125
- Returns @{ channel; tier; needsRestore; refusal; reason }
126
- channel 'message' | 'uia' | 'input' | 'refuse'
127
- tier 'quiet' | 'bounded-flash' | 'takeover' | 'none'
128
- needsRestore true only for the tiers that may take the foreground (uia / takeover-through-uia)
129
- ORDER OF CHECKS IS THE DESIGN. Pause, elevation and the takeover preconditions are checked before any
130
- capability, because a capability check that runs first can return a working channel for an action that
131
- must be refused outright. The cheapest disqualifiers come first; the capability table only decides
132
- between tiers that are both permitted.
133
- #>
134
- param([hashtable]$Facts)
135
-
136
- if (-not $Facts) {
137
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
138
- refusal = 'needs_facts'; reason = $script:WpmRefusals.needs_facts }
139
- }
140
- if ($Facts.paused) {
141
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
142
- refusal = 'paused'; reason = $script:WpmRefusals.paused }
143
- }
144
- # ---- 0.7.0 launch is not a windowed action, so the target checks do not apply to it ----------
145
- # `no_hwnd` and `elevated_target` are statements ABOUT A TARGET WINDOW. `launch` has no target window at
146
- # the moment it is decided -- that is precisely the point of the action -- and letting a hwnd check run
147
- # first would turn every launch refusal into a wrong one (`no_hwnd` tells the caller to go find a
148
- # handle, which is not what an unauthorised program name means). Guarded by the action rather than by
149
- # handing the table a fake hwnd, because a fabricated fact in a decision table is how tables lie.
150
- $isWindowedAction = $Facts.action -ne 'launch'
151
- if ($isWindowedAction -and (-not $Facts.hwnd)) {
152
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
153
- refusal = 'no_hwnd'; reason = $script:WpmRefusals.no_hwnd }
154
- }
155
- if ($isWindowedAction -and $Facts.elevatedTarget) {
156
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
157
- refusal = 'elevated_target'; reason = $script:WpmRefusals.elevated_target }
158
- }
159
-
160
- # ---- 0.7.0-A the policy ceiling, BEFORE any capability is consulted --------------------------
161
- # Why here and not at the takeover branch: `policy` answers "may this rung be used at all", and a
162
- # capability check that runs first can produce a working channel for an action the owner excluded --
163
- # the same ordering mistake the pause check documents above. The refusal names the setting to raise,
164
- # because the correct response to this code is a settings change, never a retry.
165
- if (-not (Test-WpmTierAllowed $Facts.policy $Facts.requiredTier)) {
166
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
167
- refusal = 'policy_denied'
168
- reason = $script:WpmRefusals.policy_denied + " [action needs $($Facts.requiredTier); policy '$($Facts.policy)' allows at most $($script:WpmPolicyCeiling[$Facts.policy])]" }
169
- }
170
-
171
- # ---- R3 preconditions. These are refusals about the REQUEST, not about the target, and they come
172
- # before the door table because a takeover that cannot show its HUD must not reach any primitive.
173
- if ($Facts.takeoverRequested -and -not $Facts.hudReady) {
174
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
175
- refusal = 'takeover_unavailable'; reason = $script:WpmRefusals.takeover_unavailable }
176
- }
177
- if ($Facts.keyInjectRequested -and (-not $Facts.takeoverRequested -or -not $Facts.keyInjectAllowed)) {
178
- # Injection is allowed ONLY inside the takeover tier (spec.md §1: SendInput writes to the foreground,
179
- # so without the HUD and the cursor contract it would be a blind keystroke into whatever is in front).
180
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
181
- refusal = 'keyinject_unavailable'; reason = $script:WpmRefusals.keyinject_unavailable }
182
- }
183
- if ($Facts.keyInjectRequested -and -not $Facts.foregroundIsTarget) {
184
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
185
- refusal = 'keyinject_unavailable'; reason = $script:WpmRefusals.keyinject_unavailable }
186
- }
187
-
188
- # ---- 0.7.0 the launch gate and its whitelist, double-checked here -----------------------------
189
- # The host applies this BEFORE any worker request; this is the second line, because a permission that
190
- # exists only in one process is a permission that can be reached around by calling the other one (the
191
- # same argument that puts the HUD re-check in engine.ps1 rather than trusting the gate). ORDER MATTERS:
192
- # this runs after the per-tier preconditions and BEFORE the idle check, which is the sequence the plan
193
- # specifies -- an unauthorised program must be reported as unauthorised, not as "the owner is busy",
194
- # because the two refusals tell the caller to change two different things.
195
- if ($Facts.action -eq 'launch') {
196
- if (-not $Facts.appLaunchAllowed) {
197
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
198
- refusal = 'app_launch_denied'; reason = $script:WpmRefusals.app_launch_denied + ' [appLaunchAllowed is off]' }
199
- }
200
- $t = if ($Facts.launchTarget) { $Facts.launchTarget.ToLower() } else { '' }
201
- $hit = $false
202
- foreach ($w in @($Facts.appLaunchAllow)) {
203
- # EXACT match, case-folded. No wildcard, no prefix, no substring: `notepad` must not authorise
204
- # `notepad-helper.exe`, and a prefix rule is the shape of a whitelist that expands by accident.
205
- if ($w -and ([string]$w).Trim().ToLower() -ceq $t) { $hit = $true; break }
206
- }
207
- if (-not $hit) {
208
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
209
- refusal = 'app_launch_denied'
210
- reason = $script:WpmRefusals.app_launch_denied + " [no exact entry for '$t'; whitelist holds $(@($Facts.appLaunchAllow).Count) name(s)]" }
211
- }
212
- # Fall through to the idle check below: an authorised name is still not permission to start a program
213
- # while someone is typing at this keyboard.
214
- }
215
-
216
- # ---- 0.7.0-B idle sensing: the owner is at the keyboard, so do not interrupt them -------------
217
- # Only a takeover-tier action is refused here. The quiet and flash tiers do not touch the owner's
218
- # cursor or hold their focus, so "you are busy" does not apply to them -- refusing those would refuse
219
- # the reason this product exists. `launch` reaches here with requiredTier 'takeover', so starting a
220
- # program while the owner is typing is refused too: that is the plan's order, and it is the correct
221
- # one, because a program started at the wrong moment is the least interruptible action in this product.
222
- #
223
- # AN UNKNOWN AGE ALLOWS, and that is a decision rather than an oversight. `LastInputAgeMs` answers -1
224
- # when GetLastInputInfo fails; refusing on -1 would block every takeover on a machine where that one
225
- # API does not answer, and the owner who opted into takeoverAllowed has already accepted the tier. This
226
- # is the OPPOSITE of how the proof path treats -1 (there, unknown must never be read as "the desktop
227
- # was still", because that would launder a disturbance into innocence) -- the two directions differ
228
- # because the costs differ: here unknown costs an agent a convenience, there it costs the owner the
229
- # truth. Both choices are stated where the comparison is made rather than inherited from a convention.
230
- #
231
- # Written as one-line conditions: a multi-line `if (A -and -not B` newline `-and C)` expression reads
232
- # fine to a human and fails the PowerShell parser at the `-and` that opens the continuation line -- a
233
- # runtime-only parse failure in a dot-sourced file, which surfaces as `action_failed` from the worker.
234
- $needsTakeover = ($Facts.requiredTier -eq 'takeover')
235
- $ageKnown = ([long]$Facts.lastInputAgeMs -ge 0)
236
- $ownerPresent = ($ageKnown -and ([long]$Facts.lastInputAgeMs -lt [int]$Facts.policyIdleMs))
237
- if ($needsTakeover -and $ownerPresent -and (-not $Facts.forceUserActive)) {
238
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
239
- refusal = 'user_active'
240
- reason = $script:WpmRefusals.user_active + " [last physical input $($Facts.lastInputAgeMs)ms ago; policyIdleMs=$($Facts.policyIdleMs)]" }
241
- }
242
-
243
- if ($Facts.action -eq 'launch') {
244
- return @{ channel = 'launch'; tier = 'takeover'; needsRestore = $false; refusal = ''
245
- reason = 'launch is authorised by both switches and the owner is not at the keyboard' }
246
- }
247
-
248
- $tier = if ($Facts.takeoverRequested) { 'takeover' } else { 'quiet' }
249
-
250
- # TIER 1: message door. Measured free -- 0/6 raises, effect verified app-side in 6/6, cursor 0 px.
251
- # Preferred whenever it exists, which INVERTS the original R2.2 priority (UIA first). The original
252
- # order preferred the channel that steals focus; this one prefers the channel that does not.
253
- if ($Facts.messageDoor) {
254
- return @{ channel = 'message'; tier = $tier; needsRestore = $false; refusal = ''
255
- reason = 'classic child window accepts target-window messages' }
256
- }
257
-
258
- # TIER 2: UIA pattern. Measured to raise 6/6 and 12/12, therefore it always needs restoration.
259
- if ($Facts.hasPattern -and $Facts.patternKind -ne 'none') {
260
- return @{ channel = 'uia'; tier = $tier; needsRestore = $true; refusal = ''
261
- 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' }) }
262
- }
263
-
264
- # TIER 3: no door at all. A terminal is the measured case (findings §B): three child HWNDs, none
265
- # writable.
266
- #
267
- # THE TERMINAL INJECTION PATH WAS WITHDRAWN ON MEASURED EVIDENCE, and this branch is where that decision
268
- # lives. R3's plan was to drive a terminal by typing into it once the owner asked for takeover+inject.
269
- # Two independent probes say it does not work on this host (findings §G3, 2026-11-23):
270
- # * scripts/probe-console-inject.ps1 -- KEYEVENTF_UNICODE: 242 events accepted by SendInput, the
271
- # foreground WAS the terminal, Enter was pressed, and the shell never executed the typed command;
272
- # * scripts/probe-console-scan.ps1 -- KEYEVENTF_SCANCODE with the layout's own VK mapping: 262
273
- # events, same setup, still nothing executed.
274
- # So "the only door left is the keyboard" was wrong for the terminal family on this desktop, and making
275
- # the code path look like a capability would be a promise the product cannot keep. The refusal keeps its
276
- # diagnostic value and points at what DOES work (a target with a real door).
277
- if ($Facts.family -eq 'terminal' -and -not $Facts.messageDoor -and -not $Facts.hasPattern) {
278
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
279
- refusal = 'terminal_no_door'; reason = $script:WpmRefusals.terminal_no_door }
280
- }
281
-
282
- # A doorless, patternless NON-terminal target can also be driven by injection when explicitly asked:
283
- # the measured UWP/Chromium families sometimes expose neither door, and the keyboard is real input.
284
- if ($Facts.takeoverRequested -and $Facts.keyInjectRequested -and $Facts.factsMeasured) {
285
- return @{ channel = 'input'; tier = 'takeover'; needsRestore = $false; refusal = ''
286
- reason = 'no message door and no usable pattern; typing into the foreground target at the owner''s explicit request' }
287
- }
288
-
289
- # Neither door. Refuse, and say which one was missing -- an unmeasured target must not be
290
- # guessed into the quiet branch, which is the failure this whole plan exists to avoid.
291
- if (-not $Facts.factsMeasured) {
292
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
293
- refusal = 'needs_facts'; reason = $script:WpmRefusals.needs_facts }
294
- }
295
-
296
- # THREE WORLDS USED TO SHARE ONE CODE ('unreachable'), and they have different fixes, which is why they
297
- # stopped sharing it (2026-11-21: 0.1.5's point-probe fix exposed uiaErr arriving here as dead data; the
298
- # census the same day exposed the tree split). A tree with NO content element needs the APPLICATION to
299
- # enable accessibility -- launch-time for Chromium (--force-renderer-accessibility); re-querying cannot
300
- # help, which is exactly why no retry or polling exists anywhere in this engine. A probe that THREW
301
- # means the measurement itself failed, so no conclusion about the target is licensed -- the exception
302
- # text rides the reason (engine.ps1 appends it). Probe failure outranks tree-empty: a measurement that
303
- # threw cannot also certify emptiness. And a usable door still outranks every diagnosis.
304
- if ($Facts.uiaProbeFailed) {
305
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
306
- refusal = 'uia_probe_failed'; reason = $script:WpmRefusals.uia_probe_failed }
307
- }
308
- if ($Facts.uiaTreeEmpty) {
309
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
310
- refusal = 'uia_tree_empty'; reason = $script:WpmRefusals.uia_tree_empty }
311
- }
312
- return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
313
- refusal = 'unreachable'; reason = $script:WpmRefusals.unreachable }
314
- }
315
-
316
- function Get-WpmRestoreDecision {
317
- <#
318
- Whether to put the focus back after an action that may have taken it, and why.
319
- This is the safety property of R2'.4-R2'.7 expressed as a table, because these are the branches
320
- that, if wrong, act on a window the product does not own.
321
-
322
- currentFg == raisedHwnd -> restore (we caused it, we undo it)
323
- currentFg pid == target pid -> skip: dialog (the app deliberately focused its own dialog)
324
- currentFg is a third window -> skip: taken (the user or another app chose it; never fight)
325
- nothing was raised -> skip: nothing (restoring here would fight the user)
326
- restore already attempted once -> skip: done (one-shot; a watchdog would fight the owner)
327
-
328
- The dialog branch is not a nicety: without it, restoring after an action that opened a Save dialog
329
- pulls the focus out of the dialog the action just created, so the box is visible and unresponsive.
330
- Same-pid is the discriminator because the dialog belongs to the target process.
331
- #>
332
- param(
333
- [string]$CurrentFg = '',
334
- [string]$RaisedHwnd = '',
335
- [string]$TargetPid = '',
336
- [string]$CurrentFgPid = '',
337
- [bool]$RaisedHappened = $false,
338
- [bool]$AlreadyRestored = $false
339
- )
340
- if ($AlreadyRestored) {
341
- return @{ restore = $false; outcome = 'skip'; reason = 'one-shot: a restore was already attempted for this action' }
342
- }
343
- if (-not $RaisedHappened) {
344
- return @{ restore = $false; outcome = 'skip'; reason = 'no raise occurred; restoring would fight the owner' }
345
- }
346
- if (-not $CurrentFg -or -not $RaisedHwnd) {
347
- return @{ restore = $false; outcome = 'skip'; reason = 'foreground or raised hwnd unknown' }
348
- }
349
- if ($CurrentFg -eq $RaisedHwnd) {
350
- return @{ restore = $true; outcome = 'restore'; reason = 'our own raised window owns the foreground; safe to reverse' }
351
- }
352
- if ($TargetPid -and $CurrentFgPid -and ($CurrentFgPid -eq $TargetPid)) {
353
- return @{ restore = $false; outcome = 'skip-dialog'; reason = 'same pid as the target: this is the app''s own dialog, not our theft' }
354
- }
355
- return @{ restore = $false; outcome = 'skip-taken'; reason = 'a third window holds the foreground; never pull it from the user' }
356
- }
1
+ # decide.ps1 -- the channel decision, as a PURE function.
2
+ #
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
+ #
10
+ # THE FACTS IT CONSUMES, and where each came from:
11
+ # messageDoor -- 17/57 live windows expose a classic child door (neutral-coverage-census)
12
+ # hasPattern -- WPF/UWP/Chromium expose UIA patterns; WinForms exposes none (probe-winform)
13
+ # uiaTreeEmpty -- an a11y-off Chromium window walks to ZERO content elements and never grows
14
+ # one under re-query (uTools 1/1/1 raw, 0/0/0 content, 2026-11-21; census read
15
+ # 0/0/0 the same day) -- scripts/uia-tree-content.ps1 re-measures it
16
+ # uiaProbeFailed-- the probe's own exception, carried out of win.ps1 as a boolean so the code
17
+ # selection never parses message text
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)
20
+ # focus cost -- message door 0/6 raise; UIA pattern 6/6 and 12/12 raise
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.
35
+
36
+ Set-StrictMode -Version 2.0
37
+
38
+ # Refusal codes are a closed set on purpose. A generic 'failed' would make the product unable to
39
+ # tell the model why, which is the one thing R3.2 forbids: 'bottoms out to a canned message'.
40
+ $script:WpmRefusals = @{
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'''
51
+ # ---- 0.7.0 authorization model. Three codes, each naming the NEXT STEP rather than describing the
52
+ # symptom, because all three are settings decisions and a caller that cannot tell which setting to
53
+ # raise will retry the same call forever.
54
+ policy_denied = 'the action''s declared tier is above what the policy setting allows. Next step: raise policy in settings (readonly < quiet < balanced < full) -- NOT retrying this call'
55
+ user_active = 'the owner was at the keyboard when this was asked for (last physical input younger than policyIdleMs) and the action needs the takeover tier. This product does not open a dialog at someone who is typing -- a popup is a second disturbance dressed as consent. Next step: wait for idle, or pass forceUserActive:true explicitly (it is recorded in the audit log as forced)'
56
+ app_launch_denied = 'launch is not authorised: appLaunchAllowed is off, or the program is not on the appLaunchAllow whitelist (an empty whitelist means nothing may launch). Next step: the OWNER adds the exact name to the whitelist; a wildcard does not exist and this refusal is not a transient failure to retry through'
57
+ }
58
+
59
+ # THE LADDER, mirrored from lib/policy.js. Two copies of an ordering is normally the bug pattern this
60
+ # repo refuses, and it is allowed here for exactly one reason: the engine and the host each need the
61
+ # comparison in their own process, and scripts/check-policy-table.mjs asserts the two copies agree
62
+ # (rung set, order, and every action's declared tier in tools.json). A drift between them is red at build
63
+ # time instead of being a permission the owner believes they revoked.
64
+ $script:WpmTierOrder = @('readonly', 'quiet', 'flash', 'takeover')
65
+ $script:WpmPolicyCeiling = @{
66
+ readonly = 'readonly'; quiet = 'quiet'; balanced = 'flash'; full = 'takeover'
67
+ }
68
+
69
+ function Test-WpmTierAllowed {
70
+ # Pure, and it fails CLOSED in both directions: an unknown policy or an unknown rung answers false.
71
+ # "Unparseable setting" and "everything allowed" must never read the same way.
72
+ param([string]$Policy, [string]$Required)
73
+ if (-not $script:WpmPolicyCeiling.ContainsKey($Policy)) { return $false }
74
+ $need = [Array]::IndexOf($script:WpmTierOrder, $Required)
75
+ if ($need -lt 0) { return $false }
76
+ return $need -le [Array]::IndexOf($script:WpmTierOrder, $script:WpmPolicyCeiling[$Policy])
77
+ }
78
+
79
+ function New-WpmFacts {
80
+ # Explicit constructor so a missing field is a compile-time-shaped mistake in review rather
81
+ # than a silent $null that compares false and lands in the quiet branch.
82
+ param(
83
+ [string]$Hwnd = '',
84
+ [bool]$Paused = $false,
85
+ [bool]$ElevatedTarget = $false,
86
+ [string]$Family = 'unknown', # win32-classic | winforms | wpf | uwp | chromium | terminal | unknown
87
+ [bool]$MessageDoor = $false,
88
+ [bool]$HasPattern = $false,
89
+ [string]$PatternKind = 'none', # invoke | value | toggle | selectionitem | legacy | none
90
+ [string]$Action = 'click', # click | type | key | scroll
91
+ [bool]$FactsMeasured = $false,
92
+ [bool]$UiaTreeEmpty = $false, # the walked tree contained zero content elements (win.ps1 Test-WpmUiaTreeHasContent)
93
+ [bool]$UiaProbeFailed = $false, # the UIA probe threw; uiaErr carries the exception text (win.ps1)
94
+ [bool]$TakeoverRequested = $false, # caller asked for the takeover tier (takeover:true)
95
+ [bool]$KeyInjectRequested = $false, # caller asked for keyboard injection (keyInput:'inject')
96
+ [bool]$KeyInjectAllowed = $false, # the host gate (keyInjectAllowed) let the request through
97
+ [bool]$HudReady = $false, # hud.ps1 says a HUD window is up RIGHT NOW
98
+ [bool]$ForegroundIsTarget = $false, # GetForegroundWindow() (or its root) IS this target
99
+ # ---- 0.7.0 authorization facts, supplied by the caller because decide.ps1 does no IO: it cannot
100
+ # read settings, and a table that read its own permissions could not be unit-tested.
101
+ [string]$Policy = 'balanced', # the ceiling the owner set (readonly|quiet|balanced|full)
102
+ [string]$RequiredTier = 'quiet', # what THIS action needs at minimum (tools.json#requiresTier)
103
+ [long]$LastInputAgeMs = -1, # -1 = UNKNOWN; unknown refuses, it does not mean "idle"
104
+ [int]$PolicyIdleMs = 3000,
105
+ [bool]$ForceUserActive = $false, # the caller's explicit override, recorded in the audit
106
+ [bool]$AppLaunchAllowed = $false,
107
+ [string[]]$AppLaunchAllow = @(),
108
+ [string]$LaunchTarget = ''
109
+ )
110
+ return @{
111
+ hwnd = $Hwnd; paused = $Paused; elevatedTarget = $ElevatedTarget; family = $Family
112
+ messageDoor = $MessageDoor; hasPattern = $HasPattern; patternKind = $PatternKind
113
+ action = $Action; factsMeasured = $FactsMeasured
114
+ uiaTreeEmpty = $UiaTreeEmpty; uiaProbeFailed = $UiaProbeFailed
115
+ takeoverRequested = $TakeoverRequested; keyInjectRequested = $KeyInjectRequested
116
+ keyInjectAllowed = $KeyInjectAllowed; hudReady = $HudReady; foregroundIsTarget = $ForegroundIsTarget
117
+ policy = $Policy; requiredTier = $RequiredTier
118
+ lastInputAgeMs = $LastInputAgeMs; policyIdleMs = $PolicyIdleMs; forceUserActive = $ForceUserActive
119
+ appLaunchAllowed = $AppLaunchAllowed; appLaunchAllow = $AppLaunchAllow; launchTarget = $LaunchTarget
120
+ }
121
+ }
122
+
123
+ function Get-WpmChannelDecision {
124
+ <#
125
+ Returns @{ channel; tier; needsRestore; refusal; reason }
126
+ channel 'message' | 'uia' | 'input' | 'refuse'
127
+ tier 'quiet' | 'bounded-flash' | 'takeover' | 'none'
128
+ needsRestore true only for the tiers that may take the foreground (uia / takeover-through-uia)
129
+ ORDER OF CHECKS IS THE DESIGN. Pause, elevation and the takeover preconditions are checked before any
130
+ capability, because a capability check that runs first can return a working channel for an action that
131
+ must be refused outright. The cheapest disqualifiers come first; the capability table only decides
132
+ between tiers that are both permitted.
133
+ #>
134
+ param([hashtable]$Facts)
135
+
136
+ if (-not $Facts) {
137
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
138
+ refusal = 'needs_facts'; reason = $script:WpmRefusals.needs_facts }
139
+ }
140
+ if ($Facts.paused) {
141
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
142
+ refusal = 'paused'; reason = $script:WpmRefusals.paused }
143
+ }
144
+ # ---- 0.7.0 launch is not a windowed action, so the target checks do not apply to it ----------
145
+ # `no_hwnd` and `elevated_target` are statements ABOUT A TARGET WINDOW. `launch` has no target window at
146
+ # the moment it is decided -- that is precisely the point of the action -- and letting a hwnd check run
147
+ # first would turn every launch refusal into a wrong one (`no_hwnd` tells the caller to go find a
148
+ # handle, which is not what an unauthorised program name means). Guarded by the action rather than by
149
+ # handing the table a fake hwnd, because a fabricated fact in a decision table is how tables lie.
150
+ $isWindowedAction = $Facts.action -ne 'launch'
151
+ if ($isWindowedAction -and (-not $Facts.hwnd)) {
152
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
153
+ refusal = 'no_hwnd'; reason = $script:WpmRefusals.no_hwnd }
154
+ }
155
+ if ($isWindowedAction -and $Facts.elevatedTarget) {
156
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
157
+ refusal = 'elevated_target'; reason = $script:WpmRefusals.elevated_target }
158
+ }
159
+
160
+ # ---- 0.7.0-A the policy ceiling, BEFORE any capability is consulted --------------------------
161
+ # Why here and not at the takeover branch: `policy` answers "may this rung be used at all", and a
162
+ # capability check that runs first can produce a working channel for an action the owner excluded --
163
+ # the same ordering mistake the pause check documents above. The refusal names the setting to raise,
164
+ # because the correct response to this code is a settings change, never a retry.
165
+ if (-not (Test-WpmTierAllowed $Facts.policy $Facts.requiredTier)) {
166
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
167
+ refusal = 'policy_denied'
168
+ reason = $script:WpmRefusals.policy_denied + " [action needs $($Facts.requiredTier); policy '$($Facts.policy)' allows at most $($script:WpmPolicyCeiling[$Facts.policy])]" }
169
+ }
170
+
171
+ # ---- R3 preconditions. These are refusals about the REQUEST, not about the target, and they come
172
+ # before the door table because a takeover that cannot show its HUD must not reach any primitive.
173
+ if ($Facts.takeoverRequested -and -not $Facts.hudReady) {
174
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
175
+ refusal = 'takeover_unavailable'; reason = $script:WpmRefusals.takeover_unavailable }
176
+ }
177
+ if ($Facts.keyInjectRequested -and (-not $Facts.takeoverRequested -or -not $Facts.keyInjectAllowed)) {
178
+ # Injection is allowed ONLY inside the takeover tier (spec.md §1: SendInput writes to the foreground,
179
+ # so without the HUD and the cursor contract it would be a blind keystroke into whatever is in front).
180
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
181
+ refusal = 'keyinject_unavailable'; reason = $script:WpmRefusals.keyinject_unavailable }
182
+ }
183
+ if ($Facts.keyInjectRequested -and -not $Facts.foregroundIsTarget) {
184
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
185
+ refusal = 'keyinject_unavailable'; reason = $script:WpmRefusals.keyinject_unavailable }
186
+ }
187
+
188
+ # ---- 0.7.0 the launch gate and its whitelist, double-checked here -----------------------------
189
+ # The host applies this BEFORE any worker request; this is the second line, because a permission that
190
+ # exists only in one process is a permission that can be reached around by calling the other one (the
191
+ # same argument that puts the HUD re-check in engine.ps1 rather than trusting the gate). ORDER MATTERS:
192
+ # this runs after the per-tier preconditions and BEFORE the idle check, which is the sequence the plan
193
+ # specifies -- an unauthorised program must be reported as unauthorised, not as "the owner is busy",
194
+ # because the two refusals tell the caller to change two different things.
195
+ if ($Facts.action -eq 'launch') {
196
+ if (-not $Facts.appLaunchAllowed) {
197
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
198
+ refusal = 'app_launch_denied'; reason = $script:WpmRefusals.app_launch_denied + ' [appLaunchAllowed is off]' }
199
+ }
200
+ $t = if ($Facts.launchTarget) { $Facts.launchTarget.ToLower() } else { '' }
201
+ $hit = $false
202
+ foreach ($w in @($Facts.appLaunchAllow)) {
203
+ # EXACT match, case-folded. No wildcard, no prefix, no substring: `notepad` must not authorise
204
+ # `notepad-helper.exe`, and a prefix rule is the shape of a whitelist that expands by accident.
205
+ if ($w -and ([string]$w).Trim().ToLower() -ceq $t) { $hit = $true; break }
206
+ }
207
+ if (-not $hit) {
208
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
209
+ refusal = 'app_launch_denied'
210
+ reason = $script:WpmRefusals.app_launch_denied + " [no exact entry for '$t'; whitelist holds $(@($Facts.appLaunchAllow).Count) name(s)]" }
211
+ }
212
+ # Fall through to the idle check below: an authorised name is still not permission to start a program
213
+ # while someone is typing at this keyboard.
214
+ }
215
+
216
+ # ---- 0.7.0-B idle sensing: the owner is at the keyboard, so do not interrupt them -------------
217
+ # Only a takeover-tier action is refused here. The quiet and flash tiers do not touch the owner's
218
+ # cursor or hold their focus, so "you are busy" does not apply to them -- refusing those would refuse
219
+ # the reason this product exists. `launch` reaches here with requiredTier 'takeover', so starting a
220
+ # program while the owner is typing is refused too: that is the plan's order, and it is the correct
221
+ # one, because a program started at the wrong moment is the least interruptible action in this product.
222
+ #
223
+ # AN UNKNOWN AGE ALLOWS, and that is a decision rather than an oversight. `LastInputAgeMs` answers -1
224
+ # when GetLastInputInfo fails; refusing on -1 would block every takeover on a machine where that one
225
+ # API does not answer, and the owner who opted into takeoverAllowed has already accepted the tier. This
226
+ # is the OPPOSITE of how the proof path treats -1 (there, unknown must never be read as "the desktop
227
+ # was still", because that would launder a disturbance into innocence) -- the two directions differ
228
+ # because the costs differ: here unknown costs an agent a convenience, there it costs the owner the
229
+ # truth. Both choices are stated where the comparison is made rather than inherited from a convention.
230
+ #
231
+ # Written as one-line conditions: a multi-line `if (A -and -not B` newline `-and C)` expression reads
232
+ # fine to a human and fails the PowerShell parser at the `-and` that opens the continuation line -- a
233
+ # runtime-only parse failure in a dot-sourced file, which surfaces as `action_failed` from the worker.
234
+ $needsTakeover = ($Facts.requiredTier -eq 'takeover')
235
+ $ageKnown = ([long]$Facts.lastInputAgeMs -ge 0)
236
+ $ownerPresent = ($ageKnown -and ([long]$Facts.lastInputAgeMs -lt [int]$Facts.policyIdleMs))
237
+ if ($needsTakeover -and $ownerPresent -and (-not $Facts.forceUserActive)) {
238
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
239
+ refusal = 'user_active'
240
+ reason = $script:WpmRefusals.user_active + " [last physical input $($Facts.lastInputAgeMs)ms ago; policyIdleMs=$($Facts.policyIdleMs)]" }
241
+ }
242
+
243
+ if ($Facts.action -eq 'launch') {
244
+ return @{ channel = 'launch'; tier = 'takeover'; needsRestore = $false; refusal = ''
245
+ reason = 'launch is authorised by both switches and the owner is not at the keyboard' }
246
+ }
247
+
248
+ $tier = if ($Facts.takeoverRequested) { 'takeover' } else { 'quiet' }
249
+
250
+ # TIER 1: message door. Measured free -- 0/6 raises, effect verified app-side in 6/6, cursor 0 px.
251
+ # Preferred whenever it exists, which INVERTS the original R2.2 priority (UIA first). The original
252
+ # order preferred the channel that steals focus; this one prefers the channel that does not.
253
+ if ($Facts.messageDoor) {
254
+ return @{ channel = 'message'; tier = $tier; needsRestore = $false; refusal = ''
255
+ reason = 'classic child window accepts target-window messages' }
256
+ }
257
+
258
+ # TIER 2: UIA pattern. Measured to raise 6/6 and 12/12, therefore it always needs restoration.
259
+ if ($Facts.hasPattern -and $Facts.patternKind -ne 'none') {
260
+ return @{ channel = 'uia'; tier = $tier; needsRestore = $true; refusal = ''
261
+ 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' }) }
262
+ }
263
+
264
+ # TIER 3: no door at all. A terminal is the measured case (findings §B): three child HWNDs, none
265
+ # writable.
266
+ #
267
+ # THE TERMINAL INJECTION PATH WAS WITHDRAWN ON MEASURED EVIDENCE, and this branch is where that decision
268
+ # lives. R3's plan was to drive a terminal by typing into it once the owner asked for takeover+inject.
269
+ # Two independent probes say it does not work on this host (findings §G3, 2026-11-23):
270
+ # * scripts/probe-console-inject.ps1 -- KEYEVENTF_UNICODE: 242 events accepted by SendInput, the
271
+ # foreground WAS the terminal, Enter was pressed, and the shell never executed the typed command;
272
+ # * scripts/probe-console-scan.ps1 -- KEYEVENTF_SCANCODE with the layout's own VK mapping: 262
273
+ # events, same setup, still nothing executed.
274
+ # So "the only door left is the keyboard" was wrong for the terminal family on this desktop, and making
275
+ # the code path look like a capability would be a promise the product cannot keep. The refusal keeps its
276
+ # diagnostic value and points at what DOES work (a target with a real door).
277
+ if ($Facts.family -eq 'terminal' -and -not $Facts.messageDoor -and -not $Facts.hasPattern) {
278
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
279
+ refusal = 'terminal_no_door'; reason = $script:WpmRefusals.terminal_no_door }
280
+ }
281
+
282
+ # A doorless, patternless NON-terminal target can also be driven by injection when explicitly asked:
283
+ # the measured UWP/Chromium families sometimes expose neither door, and the keyboard is real input.
284
+ if ($Facts.takeoverRequested -and $Facts.keyInjectRequested -and $Facts.factsMeasured) {
285
+ return @{ channel = 'input'; tier = 'takeover'; needsRestore = $false; refusal = ''
286
+ reason = 'no message door and no usable pattern; typing into the foreground target at the owner''s explicit request' }
287
+ }
288
+
289
+ # Neither door. Refuse, and say which one was missing -- an unmeasured target must not be
290
+ # guessed into the quiet branch, which is the failure this whole plan exists to avoid.
291
+ if (-not $Facts.factsMeasured) {
292
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
293
+ refusal = 'needs_facts'; reason = $script:WpmRefusals.needs_facts }
294
+ }
295
+
296
+ # THREE WORLDS USED TO SHARE ONE CODE ('unreachable'), and they have different fixes, which is why they
297
+ # stopped sharing it (2026-11-21: 0.1.5's point-probe fix exposed uiaErr arriving here as dead data; the
298
+ # census the same day exposed the tree split). A tree with NO content element needs the APPLICATION to
299
+ # enable accessibility -- launch-time for Chromium (--force-renderer-accessibility); re-querying cannot
300
+ # help, which is exactly why no retry or polling exists anywhere in this engine. A probe that THREW
301
+ # means the measurement itself failed, so no conclusion about the target is licensed -- the exception
302
+ # text rides the reason (engine.ps1 appends it). Probe failure outranks tree-empty: a measurement that
303
+ # threw cannot also certify emptiness. And a usable door still outranks every diagnosis.
304
+ if ($Facts.uiaProbeFailed) {
305
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
306
+ refusal = 'uia_probe_failed'; reason = $script:WpmRefusals.uia_probe_failed }
307
+ }
308
+ if ($Facts.uiaTreeEmpty) {
309
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
310
+ refusal = 'uia_tree_empty'; reason = $script:WpmRefusals.uia_tree_empty }
311
+ }
312
+ return @{ channel = 'refuse'; tier = 'none'; needsRestore = $false
313
+ refusal = 'unreachable'; reason = $script:WpmRefusals.unreachable }
314
+ }
315
+
316
+ function Get-WpmRestoreDecision {
317
+ <#
318
+ Whether to put the focus back after an action that may have taken it, and why.
319
+ This is the safety property of R2'.4-R2'.7 expressed as a table, because these are the branches
320
+ that, if wrong, act on a window the product does not own.
321
+
322
+ currentFg == raisedHwnd -> restore (we caused it, we undo it)
323
+ currentFg pid == target pid -> skip: dialog (the app deliberately focused its own dialog)
324
+ currentFg is a third window -> skip: taken (the user or another app chose it; never fight)
325
+ nothing was raised -> skip: nothing (restoring here would fight the user)
326
+ restore already attempted once -> skip: done (one-shot; a watchdog would fight the owner)
327
+
328
+ The dialog branch is not a nicety: without it, restoring after an action that opened a Save dialog
329
+ pulls the focus out of the dialog the action just created, so the box is visible and unresponsive.
330
+ Same-pid is the discriminator because the dialog belongs to the target process.
331
+ #>
332
+ param(
333
+ [string]$CurrentFg = '',
334
+ [string]$RaisedHwnd = '',
335
+ [string]$TargetPid = '',
336
+ [string]$CurrentFgPid = '',
337
+ [bool]$RaisedHappened = $false,
338
+ [bool]$AlreadyRestored = $false
339
+ )
340
+ if ($AlreadyRestored) {
341
+ return @{ restore = $false; outcome = 'skip'; reason = 'one-shot: a restore was already attempted for this action' }
342
+ }
343
+ if (-not $RaisedHappened) {
344
+ return @{ restore = $false; outcome = 'skip'; reason = 'no raise occurred; restoring would fight the owner' }
345
+ }
346
+ if (-not $CurrentFg -or -not $RaisedHwnd) {
347
+ return @{ restore = $false; outcome = 'skip'; reason = 'foreground or raised hwnd unknown' }
348
+ }
349
+ if ($CurrentFg -eq $RaisedHwnd) {
350
+ return @{ restore = $true; outcome = 'restore'; reason = 'our own raised window owns the foreground; safe to reverse' }
351
+ }
352
+ if ($TargetPid -and $CurrentFgPid -and ($CurrentFgPid -eq $TargetPid)) {
353
+ return @{ restore = $false; outcome = 'skip-dialog'; reason = 'same pid as the target: this is the app''s own dialog, not our theft' }
354
+ }
355
+ return @{ restore = $false; outcome = 'skip-taken'; reason = 'a third window holds the foreground; never pull it from the user' }
356
+ }