opencode-windows-scheduler 1.5.2 → 1.5.5

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 (231) hide show
  1. package/CHANGELOG.md +107 -2
  2. package/CROSS_PLATFORM.md +107 -71
  3. package/LICENSE +21 -21
  4. package/README.md +74 -26
  5. package/ROADMAP-STRATEGY.md +11 -4
  6. package/ROADMAP.md +322 -112
  7. package/dist/core/analytics.d.ts +3 -0
  8. package/dist/core/analytics.d.ts.map +1 -1
  9. package/dist/core/analytics.js +4 -0
  10. package/dist/core/audit.d.ts +2 -1
  11. package/dist/core/audit.d.ts.map +1 -1
  12. package/dist/core/audit.js +32 -1
  13. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  14. package/dist/core/cron-to-schtasks.js +21 -4
  15. package/dist/core/file-watcher.d.ts.map +1 -1
  16. package/dist/core/file-watcher.js +16 -1
  17. package/dist/core/git-trigger.d.ts +4 -2
  18. package/dist/core/git-trigger.d.ts.map +1 -1
  19. package/dist/core/git-trigger.js +34 -16
  20. package/dist/core/local-ai.d.ts +52 -0
  21. package/dist/core/local-ai.d.ts.map +1 -0
  22. package/dist/core/local-ai.js +119 -0
  23. package/dist/core/lock.d.ts +14 -0
  24. package/dist/core/lock.d.ts.map +1 -1
  25. package/dist/core/lock.js +81 -4
  26. package/dist/core/matrix.d.ts.map +1 -1
  27. package/dist/core/matrix.js +3 -2
  28. package/dist/core/native-notify.d.ts.map +1 -1
  29. package/dist/core/native-notify.js +3 -0
  30. package/dist/core/one-shot.d.ts +7 -1
  31. package/dist/core/one-shot.d.ts.map +1 -1
  32. package/dist/core/one-shot.js +15 -2
  33. package/dist/core/permissions.d.ts +69 -0
  34. package/dist/core/permissions.d.ts.map +1 -0
  35. package/dist/core/permissions.js +143 -0
  36. package/dist/core/ps-wrapper.d.ts +9 -30
  37. package/dist/core/ps-wrapper.d.ts.map +1 -1
  38. package/dist/core/ps-wrapper.js +477 -108
  39. package/dist/core/record-history.d.ts +11 -0
  40. package/dist/core/record-history.d.ts.map +1 -1
  41. package/dist/core/record-history.js +106 -4
  42. package/dist/core/savings.d.ts +70 -0
  43. package/dist/core/savings.d.ts.map +1 -0
  44. package/dist/core/savings.js +87 -0
  45. package/dist/core/schedule-gate.js +7 -3
  46. package/dist/core/schedule-v2.js +1 -1
  47. package/dist/core/scheduler/index.d.ts +13 -1
  48. package/dist/core/scheduler/index.d.ts.map +1 -1
  49. package/dist/core/scheduler/index.js +35 -4
  50. package/dist/core/scheduler/linux.d.ts +4 -1
  51. package/dist/core/scheduler/linux.d.ts.map +1 -1
  52. package/dist/core/scheduler/linux.js +53 -20
  53. package/dist/core/scheduler/mac.d.ts +2 -1
  54. package/dist/core/scheduler/mac.d.ts.map +1 -1
  55. package/dist/core/scheduler/mac.js +24 -6
  56. package/dist/core/scheduler/posix.d.ts +1 -1
  57. package/dist/core/scheduler/posix.d.ts.map +1 -1
  58. package/dist/core/scheduler/posix.js +2 -2
  59. package/dist/core/scheduler/registry.d.ts +3 -2
  60. package/dist/core/scheduler/registry.d.ts.map +1 -1
  61. package/dist/core/scheduler/registry.js +6 -5
  62. package/dist/core/scheduler/windows.d.ts +49 -1
  63. package/dist/core/scheduler/windows.d.ts.map +1 -1
  64. package/dist/core/scheduler/windows.js +219 -34
  65. package/dist/core/secrets.d.ts +5 -3
  66. package/dist/core/secrets.d.ts.map +1 -1
  67. package/dist/core/secrets.js +86 -8
  68. package/dist/core/self-analysis.d.ts +117 -0
  69. package/dist/core/self-analysis.d.ts.map +1 -0
  70. package/dist/core/self-analysis.js +539 -0
  71. package/dist/core/session.d.ts +11 -3
  72. package/dist/core/session.d.ts.map +1 -1
  73. package/dist/core/session.js +34 -5
  74. package/dist/core/shutdown.d.ts +26 -0
  75. package/dist/core/shutdown.d.ts.map +1 -0
  76. package/dist/core/shutdown.js +49 -0
  77. package/dist/core/summary.d.ts +69 -0
  78. package/dist/core/summary.d.ts.map +1 -0
  79. package/dist/core/summary.js +250 -0
  80. package/dist/core/telegram.d.ts +10 -0
  81. package/dist/core/telegram.d.ts.map +1 -1
  82. package/dist/core/telegram.js +228 -47
  83. package/dist/core/triage-chain.d.ts +40 -0
  84. package/dist/core/triage-chain.d.ts.map +1 -0
  85. package/dist/core/triage-chain.js +80 -0
  86. package/dist/core/triage-compare.d.ts +68 -0
  87. package/dist/core/triage-compare.d.ts.map +1 -0
  88. package/dist/core/triage-compare.js +184 -0
  89. package/dist/core/triage-rules.d.ts +23 -0
  90. package/dist/core/triage-rules.d.ts.map +1 -0
  91. package/dist/core/triage-rules.js +196 -0
  92. package/dist/core/triage-shadow.d.ts +91 -0
  93. package/dist/core/triage-shadow.d.ts.map +1 -0
  94. package/dist/core/triage-shadow.js +160 -0
  95. package/dist/core/triage-worker.d.ts +55 -0
  96. package/dist/core/triage-worker.d.ts.map +1 -0
  97. package/dist/core/triage-worker.js +314 -0
  98. package/dist/core/triage.d.ts +76 -0
  99. package/dist/core/triage.d.ts.map +1 -0
  100. package/dist/core/triage.js +271 -0
  101. package/dist/core/watch-paths.d.ts +6 -0
  102. package/dist/core/watch-paths.d.ts.map +1 -0
  103. package/dist/core/watch-paths.js +62 -0
  104. package/dist/core/wrappers/bash.d.ts +15 -3
  105. package/dist/core/wrappers/bash.d.ts.map +1 -1
  106. package/dist/core/wrappers/bash.js +153 -120
  107. package/dist/db/history-repo.d.ts +1 -1
  108. package/dist/db/history-repo.d.ts.map +1 -1
  109. package/dist/db/history-repo.js +29 -14
  110. package/dist/db/schema.d.ts +1 -1
  111. package/dist/db/schema.d.ts.map +1 -1
  112. package/dist/db/schema.js +31 -0
  113. package/dist/history.d.ts +2 -2
  114. package/dist/history.d.ts.map +1 -1
  115. package/dist/history.js +3 -3
  116. package/dist/i18n.d.ts +25 -2
  117. package/dist/i18n.d.ts.map +1 -1
  118. package/dist/i18n.js +75 -10
  119. package/dist/index.d.ts +66 -3
  120. package/dist/index.d.ts.map +1 -1
  121. package/dist/index.js +527 -68
  122. package/dist/integrations.d.ts +9 -1
  123. package/dist/integrations.d.ts.map +1 -1
  124. package/dist/integrations.js +34 -6
  125. package/dist/notifications.d.ts +30 -2
  126. package/dist/notifications.d.ts.map +1 -1
  127. package/dist/notifications.js +289 -10
  128. package/dist/profiles.d.ts +1 -1
  129. package/dist/profiles.d.ts.map +1 -1
  130. package/dist/profiles.js +21 -3
  131. package/dist/rpc.d.ts +401 -5
  132. package/dist/rpc.d.ts.map +1 -1
  133. package/dist/rpc.js +138 -5
  134. package/dist/server.d.ts +20 -0
  135. package/dist/server.d.ts.map +1 -1
  136. package/dist/server.js +136 -14
  137. package/dist/settings.d.ts +167 -3
  138. package/dist/settings.d.ts.map +1 -1
  139. package/dist/settings.js +322 -3
  140. package/dist/task-transfer.d.ts +8 -1
  141. package/dist/task-transfer.d.ts.map +1 -1
  142. package/dist/task-transfer.js +2 -2
  143. package/dist/types.d.ts +8 -1
  144. package/dist/types.d.ts.map +1 -1
  145. package/dist/types.js +23 -5
  146. package/dist/workspaces.d.ts +9 -0
  147. package/dist/workspaces.d.ts.map +1 -1
  148. package/dist/workspaces.js +25 -0
  149. package/docs/ARCHITECTURE.md +48 -28
  150. package/docs/CONCEPT.md +230 -0
  151. package/docs/CROSS_PLATFORM.ru.md +150 -0
  152. package/docs/CROSS_PLATFORM.zh.md +146 -0
  153. package/docs/FAQ.md +52 -0
  154. package/docs/FAQ.ru.md +53 -0
  155. package/docs/FAQ.zh.md +43 -0
  156. package/docs/FEATURES.md +141 -44
  157. package/docs/FEATURES.zh.md +655 -0
  158. package/docs/LOCAL-AI.md +300 -0
  159. package/docs/MIGRATION.md +17 -0
  160. package/docs/README.ru.md +22 -16
  161. package/docs/README.zh.md +286 -0
  162. package/docs/SAVINGS.md +61 -0
  163. package/docs/SAVINGS.ru.md +60 -0
  164. package/docs/SAVINGS.zh.md +52 -0
  165. package/docs/ZH-LOCALE-PLAN.md +324 -0
  166. package/docs/spikes/local-model-structured-output.md +81 -0
  167. package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
  168. package/docs/spikes/ollama-qwen3-4b.json +163 -0
  169. package/gui-experimental.cjs +8 -8
  170. package/locales/en.json +85 -0
  171. package/locales/ru.json +85 -0
  172. package/locales/zh.json +780 -0
  173. package/package.json +31 -7
  174. package/scripts/bench-local.mjs +321 -0
  175. package/scripts/check-zh-locale.mjs +218 -0
  176. package/scripts/run-tests.mjs +236 -0
  177. package/scripts/spike-local-structured.mjs +182 -0
  178. package/scripts/test-locale.mjs +4 -3
  179. package/skills/scheduled-job-best-practices/SKILL.md +6 -3
  180. package/skills/scheduled-job-best-practices/references/recipes.md +40 -0
  181. package/src/core/analytics.ts +10 -0
  182. package/src/core/audit.ts +39 -1
  183. package/src/core/cron-to-schtasks.ts +23 -4
  184. package/src/core/file-watcher.ts +20 -1
  185. package/src/core/git-trigger.ts +34 -16
  186. package/src/core/local-ai.ts +173 -0
  187. package/src/core/lock.ts +88 -3
  188. package/src/core/matrix.ts +5 -1
  189. package/src/core/native-notify.ts +3 -0
  190. package/src/core/one-shot.ts +18 -2
  191. package/src/core/permissions.ts +200 -0
  192. package/src/core/ps-wrapper.ts +492 -108
  193. package/src/core/record-history.ts +111 -4
  194. package/src/core/savings.ts +150 -0
  195. package/src/core/schedule-gate.ts +9 -3
  196. package/src/core/schedule-v2.ts +1 -1
  197. package/src/core/scheduler/index.ts +41 -3
  198. package/src/core/scheduler/linux.ts +67 -22
  199. package/src/core/scheduler/mac.ts +24 -7
  200. package/src/core/scheduler/posix.ts +2 -2
  201. package/src/core/scheduler/registry.ts +7 -5
  202. package/src/core/scheduler/windows.ts +237 -32
  203. package/src/core/secrets.ts +101 -7
  204. package/src/core/self-analysis.ts +744 -0
  205. package/src/core/session.ts +40 -5
  206. package/src/core/shutdown.ts +69 -0
  207. package/src/core/summary.ts +318 -0
  208. package/src/core/telegram.ts +266 -55
  209. package/src/core/triage-chain.ts +125 -0
  210. package/src/core/triage-compare.ts +277 -0
  211. package/src/core/triage-rules.ts +238 -0
  212. package/src/core/triage-shadow.ts +240 -0
  213. package/src/core/triage-worker.ts +344 -0
  214. package/src/core/triage.ts +366 -0
  215. package/src/core/watch-paths.ts +70 -0
  216. package/src/core/wrappers/bash.ts +181 -138
  217. package/src/db/history-repo.ts +31 -18
  218. package/src/db/schema.ts +31 -0
  219. package/src/gui.tsx +551 -14
  220. package/src/history.ts +7 -3
  221. package/src/i18n.ts +87 -13
  222. package/src/index.ts +649 -71
  223. package/src/integrations.ts +50 -6
  224. package/src/notifications.ts +468 -5
  225. package/src/profiles.ts +21 -3
  226. package/src/rpc.ts +143 -5
  227. package/src/server.ts +135 -16
  228. package/src/settings.ts +582 -5
  229. package/src/task-transfer.ts +10 -3
  230. package/src/types.ts +24 -5
  231. package/src/workspaces.ts +22 -0
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { PLUGIN_DIR, LOCK_DIR, WRAPPER_DIR, sanitizeName } from "../types.js";
3
+ import { PLUGIN_DIR, LOCK_DIR, WRAPPER_DIR, STALE_LOCK_MAX_AGE_MS, sanitizeName } from "../types.js";
4
4
  /**
5
5
  * Путь к единому generic-обёртке PowerShell, которая реализует запуск opencode run
6
6
  * с таймаутом и lock-логикой.
@@ -45,7 +45,14 @@ export const WRAPPER_SCRIPT = `param(
45
45
  [string]$AfterScript,
46
46
  [string]$EnvFile,
47
47
  [string]$SessionMode,
48
- [string]$SessionId
48
+ [string]$SessionId,
49
+ [string]$SessionFile,
50
+ [int]$RetryCount = 0,
51
+ [int]$RetryDelaySeconds = 0,
52
+ [int]$GateTimeoutSeconds = 300,
53
+ [int]$StaleLockMaxAgeMs = 86400000,
54
+ [string]$PermissionsB64 = "",
55
+ [string]$PolicyB64 = ""
49
56
  )
50
57
 
51
58
  [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
@@ -65,6 +72,20 @@ function Write-Log {
65
72
  Write-Host $line
66
73
  }
67
74
 
75
+
76
+ # Проверяет, что процесс с указанным PID ещё существует. Нужно для stale-lock:
77
+ # возраст файла сам по себе не говорит, что владелец мёртв (задача может идти долго).
78
+ function Test-ProcessAlive {
79
+ param([int]$ProcessId)
80
+ if ($ProcessId -le 0) { return $false }
81
+ try {
82
+ $null = Get-Process -Id $ProcessId -ErrorAction Stop
83
+ return $true
84
+ } catch {
85
+ return $false
86
+ }
87
+ }
88
+
68
89
  # Гарантируем существование папки для лога (на случай прямого вызова обёртки).
69
90
  if ($LogFile) {
70
91
  try {
@@ -83,9 +104,87 @@ $script:errorMessage = ""
83
104
  $script:preFlightStatus = "skipped"
84
105
  $script:postFlightStatus = "skipped"
85
106
  $script:skipMainTask = $false
107
+ $script:lockAcquired = $false
108
+ $script:timedOut = $false
109
+ $script:attemptExitCode = 0
86
110
  $startedAtIso = $startTime.ToUniversalTime().ToString("o")
87
111
  $script:runId = ""
88
112
 
113
+ # Hotfix 1.5.3.1: блокировка ДО записи в историю. Раньше lock существовал только
114
+ # в in-process пути (LockManager/withLock), а schtasks-запуск обёртки его не
115
+ # проверял: два одновременных запуска дублировали задачу и дрались за лог.
116
+ # Атомарное создание файла (CreateNew) даёт ту же гарантию, что и Node-лок.
117
+ if ($LockFile) {
118
+ try {
119
+ $lockDir = Split-Path -Parent $LockFile
120
+ if ($lockDir -and -not (Test-Path -LiteralPath $lockDir)) {
121
+ New-Item -ItemType Directory -Force -Path $lockDir | Out-Null
122
+ }
123
+ $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
124
+ try {
125
+ # Внутри lock храним время старта и PID владельца: по PID можно
126
+ # отличить живой долгий запуск от осиротевшего после kill -9.
127
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
128
+ $lockStream.Write($lockBytes, 0, $lockBytes.Length)
129
+ } finally {
130
+ $lockStream.Dispose()
131
+ }
132
+ $script:lockAcquired = $true
133
+ } catch [System.IO.IOException] {
134
+ # Зависший lock снимаем только если владелец мёртв (или файл старше
135
+ # StaleLockMaxAgeMs и PID в нём отсутствует — lock от старой версии).
136
+ $stale = $false
137
+ $holderPid = 0
138
+ try {
139
+ $holderRaw = "$(Get-Content -LiteralPath $LockFile -Raw -ErrorAction Stop)".Trim()
140
+ $holderParts = $holderRaw.Split([char]124)
141
+ if ($holderParts.Count -ge 2) {
142
+ [void][int]::TryParse($holderParts[1], [ref]$holderPid)
143
+ }
144
+ } catch {}
145
+ if ($holderPid -gt 0) {
146
+ $stale = -not (Test-ProcessAlive -ProcessId $holderPid)
147
+ } else {
148
+ try {
149
+ $ageMs = ((Get-Date) - (Get-Item -LiteralPath $LockFile).LastWriteTime).TotalMilliseconds
150
+ if ($ageMs -gt $StaleLockMaxAgeMs) { $stale = $true }
151
+ } catch {}
152
+ }
153
+ if ($stale) {
154
+ # T-03: не удаляем lock напрямую. Remove-Item + CreateNew давал
155
+ # гонку: второй воркер мог снести lock, который первый только что
156
+ # создал, и запустить ту же задачу повторно. Атомарно уводим старый
157
+ # файл в уникальное имя; если rename не удался — чужой lock не трогаем.
158
+ $staleLockPath = "$LockFile.stale-$PID-$([DateTime]::UtcNow.Ticks)"
159
+ $staleMoved = $false
160
+ try {
161
+ Move-Item -LiteralPath $LockFile -Destination $staleLockPath -Force -ErrorAction Stop
162
+ $staleMoved = $true
163
+ } catch {}
164
+ if ($staleMoved) {
165
+ try {
166
+ $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
167
+ try {
168
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
169
+ $lockStream.Write($lockBytes, 0, $lockBytes.Length)
170
+ } finally {
171
+ $lockStream.Dispose()
172
+ }
173
+ $script:lockAcquired = $true
174
+ } catch {}
175
+ try { Remove-Item -LiteralPath $staleLockPath -Force -ErrorAction SilentlyContinue } catch {}
176
+ }
177
+ }
178
+ if (-not $script:lockAcquired) {
179
+ Write-Log "[windows-scheduler] Запуск задачи '$TaskName' пропущен: удерживается активная блокировка."
180
+ exit 0
181
+ }
182
+ } catch {
183
+ Write-Log "[windows-scheduler] Не удалось захватить блокировку задачи '$TaskName': $_"
184
+ exit 0
185
+ }
186
+ }
187
+
89
188
  # Crash recovery: фиксируем начало ДО pre-flight и основной задачи.
90
189
  # Если процесс убьют (таймаут/KILL/перезагрузка), останется finished_at = NULL,
91
190
  # и при следующем старте плагина recovery пометит запись как error.
@@ -100,14 +199,167 @@ if ($RecorderFile) {
100
199
  }
101
200
 
102
201
  # Выполняет команду оболочки и построчно пишет её вывод в лог.
202
+ # GateTimeoutSeconds ограничивает время хука: зависший pre-flight/Quality Gate
203
+ # раньше держал lock до истечения общего таймаута задачи (до 24 ч).
103
204
  function Invoke-HookScript {
104
205
  param([string]$Command)
105
- $output = & cmd.exe /c $Command 2>&1
106
- $code = $LASTEXITCODE
107
- foreach ($line in @($output)) {
108
- Write-Log "[hook] $line"
206
+ $timeout = $GateTimeoutSeconds
207
+
208
+ if (-not $timeout -or $timeout -le 0) {
209
+ $output = & cmd.exe /c $Command 2>&1
210
+ $code = $LASTEXITCODE
211
+ foreach ($line in @($output)) {
212
+ Write-Log "[hook] $line"
213
+ }
214
+ return $code
215
+ }
216
+
217
+ # ВАЖНО: расширение должно быть .cmd. GetTempFileName() даёт .tmp, а
218
+ # запуск файла .tmp через cmd.exe /c может зависнуть вместо быстрого выполнения.
219
+ $hookFile = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-hook-" + [guid]::NewGuid().ToString("N") + ".cmd")
220
+ try {
221
+ # Команду кладём в .cmd, чтобы кавычки/пайпы не ломали аргументы.
222
+ $lines = @('@echo off', 'chcp 65001 >nul', $Command)
223
+ Set-Content -LiteralPath $hookFile -Value $lines -Encoding Default
224
+ # Не используем Start-Process с -RedirectStandardOutput/-RedirectStandardError:
225
+ # в Windows PowerShell 5.1 такой вызов может зависнуть на закрытии потоков,
226
+ # даже если сам хук уже завершился. Запускаем процесс напрямую и читаем
227
+ # stdout/stderr асинхронно — это не блокирует WaitForExit(timeout).
228
+ $psi = New-Object System.Diagnostics.ProcessStartInfo
229
+ $psi.FileName = "cmd.exe"
230
+ $psi.Arguments = '/c "' + $hookFile + '"'
231
+ $psi.UseShellExecute = $false
232
+ $psi.RedirectStandardOutput = $true
233
+ $psi.RedirectStandardError = $true
234
+ $psi.CreateNoWindow = $true
235
+ $psi.StandardOutputEncoding = [System.Text.Encoding]::UTF8
236
+ $psi.StandardErrorEncoding = [System.Text.Encoding]::UTF8
237
+ $proc = New-Object System.Diagnostics.Process
238
+ $proc.StartInfo = $psi
239
+ $null = $proc.Start()
240
+ $outTask = $proc.StandardOutput.ReadToEndAsync()
241
+ $errTask = $proc.StandardError.ReadToEndAsync()
242
+ $finished = $proc.WaitForExit([int]($timeout * 1000))
243
+ if (-not $finished) {
244
+ try { & taskkill.exe /F /T /PID $proc.Id 2>$null | Out-Null } catch {}
245
+ try { $proc.WaitForExit(5000) | Out-Null } catch {}
246
+ $code = 124
247
+ Write-Log "[windows-scheduler] Таймаут хука ($timeout с): $Command"
248
+ } else {
249
+ try { $proc.WaitForExit() } catch {}
250
+ $code = $proc.ExitCode
251
+ }
252
+ $outText = ""
253
+ $errText = ""
254
+ if ($outTask.Wait(5000)) { try { $outText = $outTask.Result } catch {} }
255
+ if ($errTask.Wait(5000)) { try { $errText = $errTask.Result } catch {} }
256
+ foreach ($text in @($outText, $errText)) {
257
+ foreach ($line in @($text -split "\r?\n")) {
258
+ if ($line -ne "") {
259
+ Write-Log "[hook] $line"
260
+ }
261
+ }
262
+ }
263
+ return $code
264
+ } catch {
265
+ Write-Log "[windows-scheduler] Не удалось выполнить хук: $_"
266
+ return 1
267
+ } finally {
268
+ Remove-Item -LiteralPath $hookFile -Force -ErrorAction SilentlyContinue
109
269
  }
110
- return $code
270
+ }
271
+
272
+ # Hotfix 1.5.3.1: запуск opencode с реальным таймаутом.
273
+ # Раньше TimeoutSeconds принимался, но нигде не использовался — задача работала
274
+ # до конца, а статус 'timeout' не выставлялся никогда. Теперь параллельно
275
+ # стартует сторожевой job: по истечении лимита он помечает маркер и убивает
276
+ # дерево процессов задачи (taskkill /T), а обёртка переводит статус в 'timeout'.
277
+ function Invoke-OpenCodeOnce {
278
+ param([string]$CommandPath, [string[]]$Arguments)
279
+
280
+ $watch = $null
281
+ $timeoutMarker = ""
282
+ if ($TimeoutSeconds -gt 0) {
283
+ $timeoutMarker = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-timeout-" + [guid]::NewGuid().ToString("N") + ".flag")
284
+ $watch = Start-Job -ScriptBlock {
285
+ param([int]$RootId, [int]$Seconds, [string]$Marker)
286
+ Start-Sleep -Seconds $Seconds
287
+ $selfId = $PID
288
+ $all = @()
289
+ try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId) } catch { $all = @() }
290
+ $targets = New-Object System.Collections.Generic.List[int]
291
+ $queue = New-Object System.Collections.Generic.Queue[int]
292
+ $queue.Enqueue($RootId)
293
+ $guard = 0
294
+ while ($queue.Count -gt 0 -and $guard -lt 2000) {
295
+ $guard++
296
+ $current = $queue.Dequeue()
297
+ foreach ($p in $all) {
298
+ $childId = [int]$p.ProcessId
299
+ if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
300
+ $targets.Add($childId)
301
+ $queue.Enqueue($childId)
302
+ }
303
+ }
304
+ }
305
+ if ($targets.Count -gt 0) {
306
+ try { Set-Content -Path $Marker -Value "timeout" -Encoding UTF8 } catch {}
307
+ foreach ($targetId in @($targets)) {
308
+ try { & taskkill.exe /F /T /PID $targetId 2>$null | Out-Null } catch {}
309
+ }
310
+ }
311
+ } -ArgumentList $PID, $TimeoutSeconds, $timeoutMarker
312
+ }
313
+
314
+ $script:timedOut = $false
315
+ $script:attemptExitCode = 0
316
+ # Состояние фильтра лога сбрасываем на каждой попытке: иначе незакрытый
317
+ # служебный блок из упавшего запуска «съедал» бы весь лог следующей попытки.
318
+ $script:inServiceBlock = $false
319
+ $script:inComment = $false
320
+ try {
321
+ # Живой стриминг: вывод opencode проходит через конвейер и пишется в лог
322
+ # (Out-File -Append) или консоль (Out-Host) построчно, по мере поступления.
323
+ # Раньше вывод сначала копился в $output и сбрасывался одним куском только
324
+ # после завершения процесса: дашборд/get_task_logs были слепы во время
325
+ # долгих запусков, росла память, а при kill обёртки лог терялся целиком.
326
+ # $LASTEXITCODE после конвейера сохраняет код последней нативной команды.
327
+ if ($LogFile) {
328
+ if ($CommandPath -like "*.ps1") {
329
+ & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 | ForEach-Object { Format-LogLine $_ } | Out-File -FilePath $LogFile -Append -Encoding utf8
330
+ $script:attemptExitCode = $LASTEXITCODE
331
+ } else {
332
+ & $CommandPath @Arguments *>&1 | ForEach-Object { Format-LogLine $_ } | Out-File -FilePath $LogFile -Append -Encoding utf8
333
+ $script:attemptExitCode = $LASTEXITCODE
334
+ }
335
+ } else {
336
+ if ($CommandPath -like "*.ps1") {
337
+ & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 | ForEach-Object { Format-LogLine $_ } | Out-Host
338
+ $script:attemptExitCode = $LASTEXITCODE
339
+ } else {
340
+ & $CommandPath @Arguments *>&1 | ForEach-Object { Format-LogLine $_ } | Out-Host
341
+ $script:attemptExitCode = $LASTEXITCODE
342
+ }
343
+ }
344
+ } finally {
345
+ if ($timeoutMarker -and (Test-Path -LiteralPath $timeoutMarker)) {
346
+ $script:timedOut = $true
347
+ }
348
+ if ($watch) {
349
+ Stop-Job -Job $watch -ErrorAction SilentlyContinue
350
+ Remove-Job -Job $watch -Force -ErrorAction SilentlyContinue
351
+ }
352
+ if ($timeoutMarker) {
353
+ Remove-Item -LiteralPath $timeoutMarker -Force -ErrorAction SilentlyContinue
354
+ }
355
+ }
356
+
357
+ if ($script:timedOut) {
358
+ Write-Log "[windows-scheduler] Таймаут: задача '$TaskName' превысила лимит $TimeoutSeconds с — процесс остановлен."
359
+ $script:errorMessage = "Таймаут: превышено $TimeoutSeconds с"
360
+ return 124
361
+ }
362
+ return $script:attemptExitCode
111
363
  }
112
364
 
113
365
  # Фильтр технического шума и служебных блоков OpenCode.
@@ -173,12 +425,10 @@ function Format-LogLine {
173
425
  return $text
174
426
  }
175
427
 
176
- /**
177
- * Пытается вытащить из лога задачи информацию о расходе токенов и стоимости.
178
- * OpenCode может печатать строки вида "Tokens: 1234", "Usage: 1234 tokens",
179
- * "cost: $0.012" и т.п. Если данные не найдены — возвращает пустые строки,
180
- * чтобы recorder записал поля как отсутствующие.
181
- */
428
+ # Пытается вытащить из лога задачи информацию о расходе токенов и стоимости.
429
+ # OpenCode может печатать строки вида "Tokens: 1234", "Usage: 1234 tokens",
430
+ # "cost: $0.012" и т.п. Если данные не найдены — возвращает пустые строки,
431
+ # чтобы recorder записал поля как отсутствующие.
182
432
  function Get-UsageFromLog {
183
433
  param([string]$File)
184
434
 
@@ -193,18 +443,24 @@ function Get-UsageFromLog {
193
443
  } catch { return $result }
194
444
  if (-not $tail) { return $result }
195
445
 
446
+ # Шаблоны намеренно «якорные»: метка должна стоять в начале строки
447
+ # (допускается префикс времени лога). Раньше подходило любое "token=" или
448
+ # "cost:" внутри текста — конфиг-дампы и проза ИИ давали ложный расход.
449
+ $prefix = '^\\s*(?:\\[[^\\]]{4,40}\\]\\s*)?'
196
450
  $tokenPatterns = @(
197
- '(?i)tokens?\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*([kKmM])?',
198
- '(?i)(?:input|output|total)\\s+tokens?\\s*[:=]?\\s*([0-9]+(?:[.,][0-9]+)?)\\s*([kKmM])?',
199
- '(?i)usage[^\\r\\n]*?([0-9]+)\\s+tokens?'
451
+ ($prefix + '(?i)(?:tokens?|token\\s+usage|usage)\\s*[:=]\\s*([0-9][0-9.,]*)\\s*([kKmM])?\\b'),
452
+ ($prefix + '(?i)(?:input|output|total)\\s+tokens?\\s*[:=]?\\s*([0-9][0-9.,]*)\\s*([kKmM])?\\b')
200
453
  )
201
454
  $costPatterns = @(
202
- '(?i)(?:cost|price|стоимость)\\s*[:=]?\\s*\\$\\s*([0-9]+(?:[.,][0-9]+)?)',
203
- '(?i)(?:cost|price|стоимость)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)'
455
+ ($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]?\\s*\\$\\s*([0-9]+(?:[.,][0-9]+)?)'),
456
+ ($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)')
204
457
  )
205
458
 
206
- foreach ($line in $tail) {
207
- $text = "$line"
459
+ # Идём с конца: OpenCode печатает итог последним, а более ранние строки
460
+ # могут быть эхом промпта или промежуточной статистикой.
461
+ for ($i = $tail.Count - 1; $i -ge 0; $i--) {
462
+ $text = "$($tail[$i])"
463
+ if ($text -match '(?i)opencode\\.json|OPENCODE_CONFIG') { continue }
208
464
 
209
465
  if (-not $result.Tokens) {
210
466
  foreach ($pattern in $tokenPatterns) {
@@ -233,6 +489,8 @@ function Get-UsageFromLog {
233
489
  }
234
490
  }
235
491
  }
492
+
493
+ if ($result.Tokens -and $result.Cost) { break }
236
494
  }
237
495
 
238
496
  return $result
@@ -258,53 +516,84 @@ try {
258
516
  Write-Log "[workspace] name=$WorkspaceName, cwd=$Workdir, branch=$gitBranch, remote=$gitRemote"
259
517
  }
260
518
 
261
- # Спринт 29.2: права задачи передаются через OPENCODE_CONFIG_CONTENT.
262
- # opencode run CLI (v2.2.3) не поддерживает --allow-tool/--deny-tool, а файл
263
- # opencode.jsonc в Workdir мог бы перезаписать проектный конфиг.
519
+ # Спринт 32 / релиз 1.6: политика прав вычисляется в TypeScript
520
+ # (src/core/permissions.ts) и передаётся готовым JSON в base64.
521
+ # Старые .cmd, созданные до 1.6, параметр не передают — для них остаётся
522
+ # прежнее поведение «разрешено всё» (fallback ниже).
264
523
  $toolToAction = @{
265
524
  "read" = "read"; "write" = "edit"; "edit" = "edit"; "apply_patch" = "edit"; "remove" = "edit"
266
525
  "bash" = "shell"; "shell" = "shell"; "glob" = "glob"; "grep" = "grep"
267
526
  "webfetch" = "webfetch"; "websearch" = "websearch"; "question" = "question"
268
527
  "subagent" = "subagent"; "skill" = "skill"
269
528
  }
270
- $defaultPermissions = @(
271
- @{ action = "read"; resource = "*"; effect = "allow" },
272
- @{ action = "edit"; resource = "*"; effect = "allow" },
273
- @{ action = "glob"; resource = "*"; effect = "allow" },
274
- @{ action = "grep"; resource = "*"; effect = "allow" },
275
- @{ action = "shell"; resource = "*"; effect = "allow" },
276
- @{ action = "subagent"; resource = "*"; effect = "allow" },
277
- @{ action = "skill"; resource = "*"; effect = "allow" },
278
- @{ action = "question"; resource = "*"; effect = "allow" },
279
- @{ action = "webfetch"; resource = "*"; effect = "allow" },
280
- @{ action = "websearch"; resource = "*"; effect = "allow" }
281
- )
282
- $permissions = @()
283
- foreach ($p in $defaultPermissions) { $permissions += $p }
284
- if ($DeniedTools) {
285
- $deniedList = @($DeniedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
286
- foreach ($tool in $deniedList) {
287
- $action = $toolToAction[$tool]
288
- if ($action) {
289
- $idx = $permissions | Where-Object { $_.action -eq $action }
290
- if ($idx) { $idx.effect = "deny" }
529
+ if ($PermissionsB64) {
530
+ try {
531
+ $decoded = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($PermissionsB64))
532
+ $config = $decoded | ConvertFrom-Json
533
+ $env:OPENCODE_CONFIG_CONTENT = ($config | ConvertTo-Json -Depth 5 -Compress)
534
+ Write-Log "[role-scoped] opencode config passed via OPENCODE_CONFIG_CONTENT"
535
+ } catch {
536
+ Write-Log "[policy] ERROR: cannot decode PermissionsB64 ($($_.Exception.Message)); falling back to legacy permissions"
537
+ $PermissionsB64 = ""
538
+ }
539
+ }
540
+ if ($PolicyB64) {
541
+ try {
542
+ $policyJson = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($PolicyB64)) | ConvertFrom-Json
543
+ $legacyFlag = ""
544
+ if ($policyJson.legacyShell) { $legacyFlag = ", legacyShell=true" }
545
+ Write-Log "[policy] policy=$($policyJson.policy)$legacyFlag"
546
+ foreach ($denied in @($policyJson.denied)) {
547
+ if ($denied.action) {
548
+ Write-Log "[policy] deny $($denied.action): $($denied.hint)"
549
+ }
291
550
  }
551
+ } catch {
552
+ Write-Log "[policy] WARN: cannot decode PolicyB64 ($($_.Exception.Message))"
292
553
  }
293
554
  }
294
- if ($AllowedTools) {
295
- $allowedList = @($AllowedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
296
- $allowedActions = @{}
297
- foreach ($tool in $allowedList) {
298
- $action = $toolToAction[$tool]
299
- if ($action) { $allowedActions[$action] = $true }
555
+ if (-not $PermissionsB64) {
556
+ # Legacy fallback для обёрток, созданных до 1.6: все action разрешены,
557
+ # DeniedTools/AllowedTools применяются как раньше.
558
+ $defaultPermissions = @(
559
+ @{ action = "read"; resource = "*"; effect = "allow" },
560
+ @{ action = "edit"; resource = "*"; effect = "allow" },
561
+ @{ action = "glob"; resource = "*"; effect = "allow" },
562
+ @{ action = "grep"; resource = "*"; effect = "allow" },
563
+ @{ action = "shell"; resource = "*"; effect = "allow" },
564
+ @{ action = "subagent"; resource = "*"; effect = "allow" },
565
+ @{ action = "skill"; resource = "*"; effect = "allow" },
566
+ @{ action = "question"; resource = "*"; effect = "allow" },
567
+ @{ action = "webfetch"; resource = "*"; effect = "allow" },
568
+ @{ action = "websearch"; resource = "*"; effect = "allow" }
569
+ )
570
+ $permissions = @()
571
+ foreach ($p in $defaultPermissions) { $permissions += $p }
572
+ if ($DeniedTools) {
573
+ $deniedList = @($DeniedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
574
+ foreach ($tool in $deniedList) {
575
+ $action = $toolToAction[$tool]
576
+ if ($action) {
577
+ $idx = $permissions | Where-Object { $_.action -eq $action }
578
+ if ($idx) { $idx.effect = "deny" }
579
+ }
580
+ }
300
581
  }
301
- foreach ($p in $permissions) {
302
- if (-not $allowedActions.ContainsKey($p.action)) { $p.effect = "deny" }
582
+ if ($AllowedTools) {
583
+ $allowedList = @($AllowedTools -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
584
+ $allowedActions = @{}
585
+ foreach ($tool in $allowedList) {
586
+ $action = $toolToAction[$tool]
587
+ if ($action) { $allowedActions[$action] = $true }
588
+ }
589
+ foreach ($p in $permissions) {
590
+ if (-not $allowedActions.ContainsKey($p.action)) { $p.effect = "deny" }
591
+ }
303
592
  }
593
+ $config = @{ "$schema" = "https://opencode.ai/config.json"; "permissions" = $permissions }
594
+ $env:OPENCODE_CONFIG_CONTENT = ($config | ConvertTo-Json -Depth 3 -Compress)
595
+ Write-Log "[role-scoped] opencode config passed via OPENCODE_CONFIG_CONTENT (legacy fallback)"
304
596
  }
305
- $config = @{ "$schema" = "https://opencode.ai/config.json"; "permissions" = $permissions }
306
- $env:OPENCODE_CONFIG_CONTENT = ($config | ConvertTo-Json -Depth 3 -Compress)
307
- Write-Log "[role-scoped] opencode config passed via OPENCODE_CONFIG_CONTENT"
308
597
 
309
598
  # Pre-flight: выполняется ДО основной задачи. Ненулевой код отменяет запуск.
310
599
  if ($BeforeScript) {
@@ -325,6 +614,13 @@ try {
325
614
  if (-not $script:skipMainTask) {
326
615
  $prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
327
616
 
617
+ # CreateProcess ограничивает командную строку 32767 символами, а промпт
618
+ # передаётся opencode аргументом ($opencodeArgs += $prompt). Явная ошибка
619
+ # понятнее, чем обрезанный/отвергнутый запуск. Основная валидация — в schedule_task.
620
+ if ($prompt -and $prompt.Length -gt 30000) {
621
+ throw "Промпт слишком длинный для командной строки Windows: $($prompt.Length) символов (максимум 30000). Сократите промпт."
622
+ }
623
+
328
624
  # Спринт 21: env-переменные workspace. Файл пишет плагин, значения не логируются.
329
625
  if ($EnvFile -and (Test-Path -LiteralPath $EnvFile)) {
330
626
  try {
@@ -350,8 +646,21 @@ try {
350
646
  if ($Model) {
351
647
  $opencodeArgs += @("--model", $Model)
352
648
  }
353
- if ($SessionMode -eq 'reuse' -and $SessionId) {
354
- $opencodeArgs += @("--session", $SessionId)
649
+ if ($SessionMode -eq 'reuse') {
650
+ # Спринт 24: актуальный id читаем из sidecar-файла — ротация сессии
651
+ # обновляет файл, и обёртку не нужно пересоздавать.
652
+ $effectiveSessionId = $SessionId
653
+ if ($SessionFile -and (Test-Path -LiteralPath $SessionFile)) {
654
+ try {
655
+ $fromFile = (Get-Content -LiteralPath $SessionFile -Raw -ErrorAction Stop).Trim()
656
+ if ($fromFile) { $effectiveSessionId = $fromFile }
657
+ } catch {
658
+ Write-Log "[windows-scheduler] Не удалось прочитать файл сессии: $($_.Exception.Message)"
659
+ }
660
+ }
661
+ if ($effectiveSessionId) {
662
+ $opencodeArgs += @("--session", $effectiveSessionId)
663
+ }
355
664
  } elseif ($SessionMode -eq 'last') {
356
665
  $opencodeArgs += @("--continue")
357
666
  }
@@ -362,45 +671,39 @@ try {
362
671
  # Запускаем opencode и НАПРЯМУЮ направляем весь вывод (stdout + stderr) в лог.
363
672
  # Out-File -Append -Encoding utf8 пишет по мере поступления строк, поэтому
364
673
  # ответ ИИ появляется в GUI ещё до завершения задачи.
365
- if ($LogFile) {
366
- if ($opencodeCmd -like "*.ps1") {
367
- & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $opencodeCmd @opencodeArgs *>&1 |
368
- ForEach-Object { Format-LogLine $_ } |
369
- Out-File -FilePath $LogFile -Append -Encoding utf8
370
- } else {
371
- & $opencodeCmd @opencodeArgs *>&1 |
372
- ForEach-Object { Format-LogLine $_ } |
373
- Out-File -FilePath $LogFile -Append -Encoding utf8
674
+ # Hotfix 1.5.3.1: retryCount из схемы раньше нигде не применялся — теперь
675
+ # неудачная попытка повторяется до RetryCount раз с паузой RetryDelaySeconds.
676
+ $maxAttempts = 1 + [Math]::Max(0, $RetryCount)
677
+ $attempt = 0
678
+ while ($attempt -lt $maxAttempts) {
679
+ $attempt++
680
+ if ($attempt -gt 1) {
681
+ $waitSeconds = [Math]::Max(0, $RetryDelaySeconds)
682
+ Write-Log "[windows-scheduler] Повтор $($attempt - 1) из $($maxAttempts - 1) через $waitSeconds с..."
683
+ if ($waitSeconds -gt 0) { Start-Sleep -Seconds $waitSeconds }
684
+ $script:errorMessage = ""
374
685
  }
375
- } else {
376
- if ($opencodeCmd -like "*.ps1") {
377
- & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $opencodeCmd @opencodeArgs *>&1 |
378
- ForEach-Object { Format-LogLine $_ } |
379
- Out-Host
380
- } else {
381
- & $opencodeCmd @opencodeArgs *>&1 |
382
- ForEach-Object { Format-LogLine $_ } |
383
- Out-Host
686
+ $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
687
+ if ($script:exitCode -eq 0) { break }
688
+ # Таймаут повторять бессмысленно: каждая попытка снова съест весь лимит.
689
+ if ($script:timedOut) { break }
690
+ if ($attempt -lt $maxAttempts) {
691
+ Write-Log "[windows-scheduler] Попытка $attempt завершилась с кодом $($script:exitCode)."
384
692
  }
385
693
  }
386
- $script:exitCode = $LASTEXITCODE
387
694
 
388
695
  # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
389
696
  # завершения opencode run. Если ИИ упал — шлюз не запускаем.
390
697
  if ($QualityGate -and $script:exitCode -eq 0) {
391
698
  Write-Log "[windows-scheduler] Запуск Quality Gate: $QualityGate"
392
- $gateOutput = & cmd.exe /c $QualityGate 2>&1
393
- $gateCode = $LASTEXITCODE
699
+ # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
700
+ $gateCode = Invoke-HookScript -Command $QualityGate
394
701
 
395
- if ($LogFile) {
396
- try {
397
- $gateOutput | ForEach-Object { Add-Content -Path $LogFile -Value "$_" -Encoding utf8 }
398
- } catch {}
399
- } else {
400
- $gateOutput | Out-Host
401
- }
402
-
403
- if ($gateCode -ne 0) {
702
+ if ($gateCode -eq 124) {
703
+ Write-Log "[windows-scheduler] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
704
+ $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
705
+ $script:exitCode = 1
706
+ } elseif ($gateCode -ne 0) {
404
707
  Write-Log "[windows-scheduler] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
405
708
  $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
406
709
  $script:exitCode = 1
@@ -440,7 +743,14 @@ try {
440
743
  # Фиксируем факт выполнения в историю и метрики (независимо от того, кто запустил: GUI или Windows)
441
744
  $endTime = Get-Date
442
745
  $durationMs = [int](($endTime - $startTime).TotalMilliseconds)
443
- $status = if ($script:exitCode -eq 0) { "success" } else { "error" }
746
+ # Hotfix 1.5.3.1: статус timeout теперь реально выставляется (см. Invoke-OpenCodeOnce).
747
+ if ($script:timedOut) {
748
+ $status = "timeout"
749
+ } elseif ($script:exitCode -eq 0) {
750
+ $status = "success"
751
+ } else {
752
+ $status = "error"
753
+ }
444
754
  $usage = Get-UsageFromLog -File $LogFile
445
755
  $tokensArg = "-"
446
756
  if ($usage.Tokens) { $tokensArg = $usage.Tokens }
@@ -448,19 +758,26 @@ try {
448
758
  if ($usage.Cost) { $costArg = $usage.Cost }
449
759
  $modelArg = "-"
450
760
  if ($Model) { $modelArg = $Model }
761
+ # Hotfix 1.5.3.1: пустая строка ошибки раньше «съедалась» PowerShell и
762
+ # сдвигала все следующие аргументы recorder (model получал preFlight,
763
+ # postFlight терялся). Теперь всегда передаём непустое значение.
764
+ $errorArg = "-"
765
+ if ($script:errorMessage) { $errorArg = $script:errorMessage }
451
766
  if ($RecorderFile) {
452
767
  try {
453
768
  if ($script:runId) {
454
- & node "$RecorderFile" --finish "$script:runId" "$TaskName" "$status" $durationMs $script:errorMessage $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
769
+ & node "$RecorderFile" --finish "$script:runId" "$TaskName" "$status" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus" "$LogFile"
455
770
  } else {
456
771
  # Fallback: --start не удался (например, старая установка) —
457
772
  # пишем завершённую запись старым способом, без потери истории.
458
- & node "$RecorderFile" "$TaskName" "$status" "$startedAtIso" $durationMs $script:errorMessage $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
773
+ & node "$RecorderFile" "$TaskName" "$status" "$startedAtIso" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus" "$LogFile"
459
774
  }
460
775
  } catch {}
461
776
  }
462
777
 
463
- if ($LockFile -and (Test-Path $LockFile)) {
778
+ # Снимаем блокировку только если мы её захватили: иначе пропущенный
779
+ # параллельный запуск удалял бы lock активной задачи.
780
+ if ($script:lockAcquired -and $LockFile -and (Test-Path $LockFile)) {
464
781
  try {
465
782
  Remove-Item $LockFile -Force
466
783
  } catch {}
@@ -483,11 +800,15 @@ export async function ensureWrapper() {
483
800
  }
484
801
  /**
485
802
  * Записывает промпт задачи во временный файл и возвращает его путь.
803
+ *
804
+ * Имя санитизируется внутри функции, а не только у вызывающей стороны:
805
+ * defence-in-depth против path traversal, если taskName когда-либо придёт
806
+ * из недоверенного источника (импорт, шаблон, RPC).
486
807
  */
487
808
  export async function writePromptFile(taskName, prompt) {
488
809
  const promptDir = path.join(PLUGIN_DIR, "prompts");
489
810
  await fs.mkdir(promptDir, { recursive: true });
490
- const promptPath = path.join(promptDir, `${taskName}.txt`);
811
+ const promptPath = path.join(promptDir, `${sanitizeName(taskName)}.txt`);
491
812
  // BOM помогает Windows PowerShell 5.1 правильно прочитать кириллицу.
492
813
  // На POSIX BOM попал бы в промпт как мусорный символ — не пишем его.
493
814
  const content = process.platform === "win32" ? "\uFEFF" + prompt : prompt;
@@ -496,9 +817,12 @@ export async function writePromptFile(taskName, prompt) {
496
817
  }
497
818
  /**
498
819
  * Возвращает путь к lock-файлу задачи.
820
+ *
821
+ * Как и writePromptFile, санитизирует имя внутри: без этого значение с `../`
822
+ * могло бы создать lock вне каталога locks.
499
823
  */
500
824
  export function lockFilePath(taskName) {
501
- return path.join(PLUGIN_DIR, "locks", `${taskName}.lock`);
825
+ return path.join(PLUGIN_DIR, "locks", `${sanitizeName(taskName)}.lock`);
502
826
  }
503
827
  /**
504
828
  * Генерирует per-task .cmd-обёртку, которую schtasks вызывает через /tr.
@@ -528,7 +852,22 @@ export function lockFilePath(taskName) {
528
852
  * без флагов), "reuse" (--session $SessionId), "last" (--continue)
529
853
  * @param sessionId идентификатор сессии для режима "reuse" (спринт 24, опционально)
530
854
  */
531
- export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeoutSeconds, lockFile, workdir, logFile, recorderFile, qualityGate, model, beforeScript, afterScript, workspaceName, allowedTools, deniedTools, scheduleGate, envFile, sessionMode, sessionId) {
855
+ /**
856
+ * Hotfix 1.5.3.1: хуки и Quality Gate пишутся в отдельные .cmd-файлы.
857
+ *
858
+ * Раньше команда передавалась аргументом в однострочный вызов powershell.exe,
859
+ * а кавычки внутри неё заменялись на апострофы: `echo x > "C:\Program Files\out.txt"`
860
+ * превращался в нерабочий `echo x > 'C:\Program Files\out.txt'`. Файл снимает
861
+ * проблему целиком — внутри .cmd можно использовать любые кавычки и пайпы.
862
+ */
863
+ async function writeHookFile(sanitizedName, kind, command) {
864
+ const dir = path.join(WRAPPER_DIR, "hooks");
865
+ await fs.mkdir(dir, { recursive: true });
866
+ const file = path.join(dir, `run-${sanitizedName}-${kind}.cmd`);
867
+ await fs.writeFile(file, `@echo off\r\nchcp 65001 >nul\r\n${command}\r\n`, "utf8");
868
+ return file;
869
+ }
870
+ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeoutSeconds, lockFile, workdir, logFile, recorderFile, qualityGate, model, beforeScript, afterScript, workspaceName, allowedTools, deniedTools, scheduleGate, envFile, sessionMode, sessionId, retryCount, retryDelaySeconds, gateTimeoutSeconds, permissionsConfig, policyMeta, sessionFile) {
532
871
  await fs.mkdir(WRAPPER_DIR, { recursive: true });
533
872
  const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
534
873
  const ps1Path = path.join(WRAPPER_DIR, WRAPPER_FILENAME);
@@ -542,19 +881,31 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
542
881
  `-PromptFile "${promptFile}"`,
543
882
  `-TimeoutSeconds ${timeoutSeconds}`,
544
883
  `-LockFile "${lockFile}"`,
884
+ `-StaleLockMaxAgeMs ${STALE_LOCK_MAX_AGE_MS}`,
545
885
  ];
886
+ // Таймаут хуков/Quality Gate: 300 с по умолчанию, 0 — без ограничения.
887
+ const safeGateTimeout = typeof gateTimeoutSeconds === "number" && Number.isFinite(gateTimeoutSeconds)
888
+ ? Math.max(0, Math.floor(gateTimeoutSeconds))
889
+ : 300;
890
+ psArgs.push(`-GateTimeoutSeconds ${safeGateTimeout}`);
891
+ // Hotfix 1.5.3.1: ретраи. Параметр не передаём при 0 — обёртка по умолчанию
892
+ // делает ровно одну попытку, как раньше.
893
+ const safeRetryCount = Math.max(0, Math.floor(retryCount ?? 0));
894
+ if (safeRetryCount > 0) {
895
+ psArgs.push(`-RetryCount ${safeRetryCount}`);
896
+ psArgs.push(`-RetryDelaySeconds ${Math.max(0, Math.floor(retryDelaySeconds ?? 0))}`);
897
+ }
546
898
  if (logFile) {
547
899
  psArgs.push(`-LogFile "${logFile}"`);
548
900
  }
549
901
  if (recorderFile) {
550
902
  psArgs.push(`-RecorderFile "${recorderFile}"`);
551
903
  }
552
- if (qualityGate) {
553
- // Кавычки в .cmd-строке ломают передачу аргумента, переводы строк — тоже.
554
- const safeGate = qualityGate.replace(/[\r\n]+/g, " ").replace(/"/g, "'").trim();
555
- if (safeGate) {
556
- psArgs.push(`-QualityGate "${safeGate}"`);
557
- }
904
+ if (qualityGate?.trim()) {
905
+ // Hotfix 1.5.3.1: команда пишется в отдельный .cmd — кавычки и пайпы
906
+ // внутри неё больше не ломают однострочный вызов powershell.exe.
907
+ const gateFile = await writeHookFile(sanitizedName, "gate", qualityGate);
908
+ psArgs.push(`-QualityGate "${gateFile}"`);
558
909
  }
559
910
  if (model?.trim()) {
560
911
  const safeModel = model.replace(/[\r\n"]+/g, "").trim();
@@ -582,14 +933,26 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
582
933
  psArgs.push(`${flag} "${safe}"`);
583
934
  }
584
935
  }
585
- // Хуки передаются одной строкой: кавычки заменяем на апострофы, как у Quality Gate.
586
- for (const [flag, script] of [
587
- ["-BeforeScript", beforeScript],
588
- ["-AfterScript", afterScript],
936
+ // Спринт 32: готовый JSON политики и метаданные для лога — в base64.
937
+ // Base64 не содержит кавычек и переводов строк, поэтому безопасен для .cmd.
938
+ if (permissionsConfig) {
939
+ const b64 = Buffer.from(permissionsConfig, "utf8").toString("base64");
940
+ psArgs.push(`-PermissionsB64 "${b64}"`);
941
+ }
942
+ if (policyMeta) {
943
+ const b64 = Buffer.from(JSON.stringify(policyMeta), "utf8").toString("base64");
944
+ psArgs.push(`-PolicyB64 "${b64}"`);
945
+ }
946
+ // Hotfix 1.5.3.1: хуки — в отдельные .cmd-файлы (см. writeHookFile).
947
+ // Раньше кавычки заменялись на апострофы, из-за чего хуки с путями в кавычках
948
+ // (например, "C:\Program Files\...") падали.
949
+ for (const [flag, script, kind] of [
950
+ ["-BeforeScript", beforeScript, "before"],
951
+ ["-AfterScript", afterScript, "after"],
589
952
  ]) {
590
- const safe = script?.replace(/[\r\n]+/g, " ").replace(/"/g, "'").trim();
591
- if (safe) {
592
- psArgs.push(`${flag} "${safe}"`);
953
+ if (script?.trim()) {
954
+ const hookFile = await writeHookFile(sanitizedName, kind, script);
955
+ psArgs.push(`${flag} "${hookFile}"`);
593
956
  }
594
957
  }
595
958
  // Спринт 21: env-файл workspace (пары KEY=VALUE). Значения не логируются.
@@ -608,6 +971,12 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
608
971
  if (safeSessionId) {
609
972
  psArgs.push(`-SessionId "${safeSessionId}"`);
610
973
  }
974
+ if (sessionFile?.trim()) {
975
+ const safeSessionFile = sessionFile.replace(/[\r\n"]+/g, "").trim();
976
+ if (safeSessionFile) {
977
+ psArgs.push(`-SessionFile "${safeSessionFile}"`);
978
+ }
979
+ }
611
980
  }
612
981
  }
613
982
  const lines = ["@echo off", "chcp 65001 >nul"];
@@ -672,7 +1041,7 @@ export const FORCE_FILE_TTL_MS = 2 * 60 * 1000;
672
1041
  * поэтому обёртка (--force-file) и агент указывают на один и тот же файл.
673
1042
  */
674
1043
  export function forceFilePath(taskName) {
675
- return `${lockFilePath(sanitizeName(taskName))}.force`;
1044
+ return `${lockFilePath(taskName)}.force`;
676
1045
  }
677
1046
  /**
678
1047
  * Создаёт маркер «запустить сейчас» перед вызовом планировщика ОС.