opencode-windows-scheduler 1.5.2 → 1.5.4

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 (64) hide show
  1. package/CHANGELOG.md +46 -1
  2. package/LICENSE +21 -21
  3. package/README.md +3 -2
  4. package/ROADMAP-STRATEGY.md +5 -4
  5. package/ROADMAP.md +251 -72
  6. package/dist/core/local-ai.d.ts +52 -0
  7. package/dist/core/local-ai.d.ts.map +1 -0
  8. package/dist/core/local-ai.js +119 -0
  9. package/dist/core/ps-wrapper.d.ts +2 -30
  10. package/dist/core/ps-wrapper.d.ts.map +1 -1
  11. package/dist/core/ps-wrapper.js +211 -39
  12. package/dist/core/triage-chain.d.ts +34 -0
  13. package/dist/core/triage-chain.d.ts.map +1 -0
  14. package/dist/core/triage-chain.js +70 -0
  15. package/dist/core/triage-rules.d.ts +23 -0
  16. package/dist/core/triage-rules.d.ts.map +1 -0
  17. package/dist/core/triage-rules.js +174 -0
  18. package/dist/core/triage-shadow.d.ts +47 -0
  19. package/dist/core/triage-shadow.d.ts.map +1 -0
  20. package/dist/core/triage-shadow.js +48 -0
  21. package/dist/core/triage.d.ts +76 -0
  22. package/dist/core/triage.d.ts.map +1 -0
  23. package/dist/core/triage.js +271 -0
  24. package/dist/gui-experimental.cjs +1 -0
  25. package/dist/i18n.d.ts.map +1 -1
  26. package/dist/i18n.js +34 -7
  27. package/dist/index.d.ts +27 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +187 -2
  30. package/dist/notifications.d.ts.map +1 -1
  31. package/dist/notifications.js +9 -1
  32. package/dist/rpc.d.ts +259 -0
  33. package/dist/rpc.d.ts.map +1 -1
  34. package/dist/rpc.js +58 -0
  35. package/dist/settings.d.ts +80 -0
  36. package/dist/settings.d.ts.map +1 -1
  37. package/dist/settings.js +199 -0
  38. package/docs/ARCHITECTURE.md +9 -7
  39. package/docs/FEATURES.md +22 -2
  40. package/docs/LOCAL-AI.md +202 -0
  41. package/docs/MIGRATION.md +17 -0
  42. package/docs/README.ru.md +5 -4
  43. package/docs/spikes/local-model-structured-output.md +81 -0
  44. package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
  45. package/docs/spikes/ollama-qwen3-4b.json +163 -0
  46. package/gui-experimental.cjs +8 -8
  47. package/locales/en.json +32 -0
  48. package/locales/ru.json +32 -0
  49. package/package.json +9 -2
  50. package/scripts/bench-local.mjs +321 -0
  51. package/scripts/spike-local-structured.mjs +182 -0
  52. package/skills/scheduled-job-best-practices/references/recipes.md +40 -0
  53. package/src/core/local-ai.ts +173 -0
  54. package/src/core/ps-wrapper.ts +218 -38
  55. package/src/core/triage-chain.ts +116 -0
  56. package/src/core/triage-rules.ts +215 -0
  57. package/src/core/triage-shadow.ts +96 -0
  58. package/src/core/triage.ts +366 -0
  59. package/src/gui.tsx +4761 -4533
  60. package/src/i18n.ts +32 -9
  61. package/src/index.ts +222 -2
  62. package/src/notifications.ts +16 -0
  63. package/src/rpc.ts +58 -0
  64. package/src/settings.ts +318 -0
@@ -121,3 +121,43 @@ Why: explicit protected list, dry-run first, auditable report. Ask the user to r
121
121
  4. Fix the cause (`update_task` on the parent for a definition bug, or the repository itself).
122
122
  5. Re-run only the failed clone with `run_task_now`, then confirm the aggregate becomes
123
123
  `success`.
124
+
125
+ ## 8. Safe rollout of local triage
126
+
127
+ Start in shadow mode so the model logs decisions without suppressing notifications,
128
+ then verify with the benchmark and the shadow report before enforcing.
129
+
130
+ ```json
131
+ {
132
+ "action": "update",
133
+ "mode": "auto",
134
+ "baseUrl": "http://127.0.0.1:11434",
135
+ "model": "qwen3:4b",
136
+ "timeoutMs": 45000,
137
+ "fallback": "rules",
138
+ "confidenceThreshold": 0.6,
139
+ "shadow": { "enabled": true, "days": 14 }
140
+ }
141
+ ```
142
+
143
+ Check readiness and run one classification request:
144
+
145
+ ```json
146
+ { "action": "get" }
147
+ ```
148
+
149
+ ```json
150
+ { "action": "test", "model": "qwen3:4b" }
151
+ ```
152
+
153
+ Measure the machine before trusting the model:
154
+
155
+ ```bash
156
+ npm run bench:local -- --model qwen3:4b --runs 3 --out bench.json
157
+ ```
158
+
159
+ Why: `auto` keeps the rules engine as a fallback, `fallback: "rules"` is
160
+ fail-open, and shadow mode makes false skips visible. Only disable shadow mode
161
+ after the shadow report shows no false positives. See `docs/LOCAL-AI.md` for
162
+ model tiers by RAM, `OLLAMA_CONTEXT_LENGTH` troubleshooting and the full JSON
163
+ report format.
@@ -0,0 +1,173 @@
1
+ import type {
2
+ TriageFallback,
3
+ TriageMode,
4
+ TriageSettings,
5
+ TriageShadowSettings,
6
+ } from "../settings.js";
7
+ import { DEFAULT_SHADOW_DAYS, isShadowActive } from "../settings.js";
8
+
9
+ /**
10
+ * Настройки локального ассистента (Спринт 30.7 `manage_local_ai`).
11
+ *
12
+ * Здесь только чистые функции: слияние патча с текущими настройками
13
+ * триажа, нормализация значений и человекочитаемая сводка. Никаких
14
+ * сетевых вызовов и записи на диск — их делают инструмент и GUI.
15
+ */
16
+
17
+ export const LOCAL_AI_TIMEOUT_MIN = 1_000;
18
+ export const LOCAL_AI_TIMEOUT_MAX = 120_000;
19
+ export const LOCAL_AI_SELF_TEST_PROMPT =
20
+ "Тест связи: задача завершилась ошибкой Quality Gate (2 упавших теста).";
21
+
22
+ /** Патч настроек: любое подмножество полей. */
23
+ export interface LocalAiPatch {
24
+ mode?: TriageMode;
25
+ baseUrl?: string;
26
+ model?: string;
27
+ timeoutMs?: number;
28
+ fallback?: TriageFallback;
29
+ confidenceThreshold?: number;
30
+ shadow?: Partial<TriageShadowSettings>;
31
+ }
32
+
33
+ /** Сводка настроек для ответа инструмента и GUI. */
34
+ export interface LocalAiSummary {
35
+ mode: TriageMode;
36
+ baseUrl: string;
37
+ model: string;
38
+ timeoutMs: number;
39
+ fallback: TriageFallback;
40
+ confidenceThreshold: number;
41
+ /** Сколько пользовательских правил задано; null — встроенный набор. */
42
+ rules: number | null;
43
+ shadow: TriageShadowSettings;
44
+ /** Триаж реально спрашивает модель (mode llm/auto и заполнены baseUrl+model). */
45
+ llmReady: boolean;
46
+ /** Идёт shadow-период: решения пишутся в отчёт, но не подавляют. */
47
+ shadowActive: boolean;
48
+ /** Протокол по baseUrl: `.../v1` — OpenAI-совместимый, иначе Ollama. */
49
+ protocol: "openai" | "ollama";
50
+ }
51
+
52
+ function clamp(value: number, min: number, max: number, fallback: number): number {
53
+ if (!Number.isFinite(value)) return fallback;
54
+ return Math.min(max, Math.max(min, Math.round(value)));
55
+ }
56
+
57
+ function trimUrl(value: string): string {
58
+ return value.trim().replace(/\/+$/, "");
59
+ }
60
+
61
+ /** Протокол по базовому URL — то же правило, что в `classifyNotification`. */
62
+ export function protocolFor(baseUrl: string): "openai" | "ollama" {
63
+ const trimmed = trimUrl(baseUrl);
64
+ return /\/v1$/i.test(trimmed) ? "openai" : "ollama";
65
+ }
66
+
67
+ /**
68
+ * Сливает патч с текущими настройками. Возвращает новые настройки и
69
+ * список имён изменённых полей (для ответа инструмента и аудита).
70
+ */
71
+ export function applyLocalAiPatch(
72
+ current: TriageSettings,
73
+ patch: LocalAiPatch
74
+ ): { settings: TriageSettings; changed: string[] } {
75
+ const next: TriageSettings = { ...current, shadow: { ...current.shadow } as TriageShadowSettings };
76
+ const changed: string[] = [];
77
+
78
+ if (patch.mode !== undefined && patch.mode !== current.mode) {
79
+ next.mode = patch.mode;
80
+ changed.push("mode");
81
+ }
82
+ if (patch.baseUrl !== undefined) {
83
+ const baseUrl = trimUrl(patch.baseUrl);
84
+ if (baseUrl !== current.baseUrl) {
85
+ next.baseUrl = baseUrl;
86
+ changed.push("baseUrl");
87
+ }
88
+ }
89
+ if (patch.model !== undefined) {
90
+ const model = patch.model.trim().slice(0, 200);
91
+ if (model !== current.model) {
92
+ next.model = model;
93
+ changed.push("model");
94
+ }
95
+ }
96
+ if (patch.timeoutMs !== undefined) {
97
+ const timeoutMs = clamp(
98
+ patch.timeoutMs,
99
+ LOCAL_AI_TIMEOUT_MIN,
100
+ LOCAL_AI_TIMEOUT_MAX,
101
+ current.timeoutMs
102
+ );
103
+ if (timeoutMs !== current.timeoutMs) {
104
+ next.timeoutMs = timeoutMs;
105
+ changed.push("timeoutMs");
106
+ }
107
+ }
108
+ if (patch.fallback !== undefined && patch.fallback !== current.fallback) {
109
+ next.fallback = patch.fallback;
110
+ changed.push("fallback");
111
+ }
112
+ if (patch.confidenceThreshold !== undefined) {
113
+ const threshold = clamp(patch.confidenceThreshold, 0, 1, current.confidenceThreshold);
114
+ if (threshold !== current.confidenceThreshold) {
115
+ next.confidenceThreshold = threshold;
116
+ changed.push("confidenceThreshold");
117
+ }
118
+ }
119
+ const shadow = next.shadow ?? {
120
+ enabled: false,
121
+ days: DEFAULT_SHADOW_DAYS,
122
+ startedAt: null,
123
+ };
124
+ const shadowPatch = patch.shadow;
125
+ if (shadowPatch && typeof shadowPatch === "object") {
126
+ if (shadowPatch.enabled !== undefined && Boolean(shadowPatch.enabled) !== shadow.enabled) {
127
+ shadow.enabled = Boolean(shadowPatch.enabled);
128
+ changed.push("shadow.enabled");
129
+ }
130
+ if (shadowPatch.days !== undefined) {
131
+ const days = clamp(shadowPatch.days, 1, 365, shadow.days);
132
+ if (days !== shadow.days) {
133
+ shadow.days = days;
134
+ changed.push("shadow.days");
135
+ }
136
+ }
137
+ if (shadowPatch.startedAt !== undefined && shadowPatch.startedAt !== shadow.startedAt) {
138
+ shadow.startedAt = shadowPatch.startedAt;
139
+ changed.push("shadow.startedAt");
140
+ }
141
+ }
142
+ next.shadow = shadow;
143
+
144
+ return { settings: next, changed };
145
+ }
146
+
147
+ /** Компактная сводка настроек для ответа инструмента. */
148
+ export function summarizeLocalAi(settings: TriageSettings): LocalAiSummary {
149
+ const shadow = settings.shadow ?? {
150
+ enabled: false,
151
+ days: DEFAULT_SHADOW_DAYS,
152
+ startedAt: null,
153
+ };
154
+ const baseUrl = settings.baseUrl ?? "";
155
+ const model = settings.model ?? "";
156
+ return {
157
+ mode: settings.mode,
158
+ baseUrl,
159
+ model,
160
+ timeoutMs: settings.timeoutMs,
161
+ fallback: settings.fallback,
162
+ confidenceThreshold: settings.confidenceThreshold,
163
+ rules: Array.isArray(settings.rules) ? settings.rules.length : null,
164
+ shadow,
165
+ llmReady:
166
+ settings.mode !== "off" &&
167
+ settings.mode !== "rules" &&
168
+ baseUrl.trim().length > 0 &&
169
+ model.trim().length > 0,
170
+ shadowActive: isShadowActive(shadow),
171
+ protocol: protocolFor(baseUrl),
172
+ };
173
+ }
@@ -48,7 +48,9 @@ export const WRAPPER_SCRIPT = `param(
48
48
  [string]$AfterScript,
49
49
  [string]$EnvFile,
50
50
  [string]$SessionMode,
51
- [string]$SessionId
51
+ [string]$SessionId,
52
+ [int]$RetryCount = 0,
53
+ [int]$RetryDelaySeconds = 0
52
54
  )
53
55
 
54
56
  [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
@@ -86,9 +88,56 @@ $script:errorMessage = ""
86
88
  $script:preFlightStatus = "skipped"
87
89
  $script:postFlightStatus = "skipped"
88
90
  $script:skipMainTask = $false
91
+ $script:lockAcquired = $false
92
+ $script:timedOut = $false
93
+ $script:attemptExitCode = 0
89
94
  $startedAtIso = $startTime.ToUniversalTime().ToString("o")
90
95
  $script:runId = ""
91
96
 
97
+ # Hotfix 1.5.3.1: блокировка ДО записи в историю. Раньше lock существовал только
98
+ # в in-process пути (LockManager/withLock), а schtasks-запуск обёртки его не
99
+ # проверял: два одновременных запуска дублировали задачу и дрались за лог.
100
+ # Атомарное создание файла (CreateNew) даёт ту же гарантию, что и Node-лок.
101
+ if ($LockFile) {
102
+ try {
103
+ $lockDir = Split-Path -Parent $LockFile
104
+ if ($lockDir -and -not (Test-Path -LiteralPath $lockDir)) {
105
+ New-Item -ItemType Directory -Force -Path $lockDir | Out-Null
106
+ }
107
+ $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
108
+ try {
109
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes($startedAtIso)
110
+ $lockStream.Write($lockBytes, 0, $lockBytes.Length)
111
+ } finally {
112
+ $lockStream.Dispose()
113
+ }
114
+ $script:lockAcquired = $true
115
+ } catch [System.IO.IOException] {
116
+ # Зависший lock (старше 24 ч — как STALE_LOCK_MAX_AGE_MS) снимаем один раз,
117
+ # иначе после аварийного завершения задача залипла бы навсегда.
118
+ $stale = $false
119
+ try {
120
+ $ageMs = ((Get-Date) - (Get-Item -LiteralPath $LockFile).LastWriteTime).TotalMilliseconds
121
+ if ($ageMs -gt 86400000) { $stale = $true }
122
+ } catch {}
123
+ if ($stale) {
124
+ try { Remove-Item -LiteralPath $LockFile -Force } catch {}
125
+ try {
126
+ $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
127
+ $lockStream.Dispose()
128
+ $script:lockAcquired = $true
129
+ } catch {}
130
+ }
131
+ if (-not $script:lockAcquired) {
132
+ Write-Log "[windows-scheduler] Запуск задачи '$TaskName' пропущен: удерживается активная блокировка."
133
+ exit 0
134
+ }
135
+ } catch {
136
+ Write-Log "[windows-scheduler] Не удалось захватить блокировку задачи '$TaskName': $_"
137
+ exit 0
138
+ }
139
+ }
140
+
92
141
  # Crash recovery: фиксируем начало ДО pre-flight и основной задачи.
93
142
  # Если процесс убьют (таймаут/KILL/перезагрузка), останется finished_at = NULL,
94
143
  # и при следующем старте плагина recovery пометит запись как error.
@@ -113,6 +162,94 @@ function Invoke-HookScript {
113
162
  return $code
114
163
  }
115
164
 
165
+ # Hotfix 1.5.3.1: запуск opencode с реальным таймаутом.
166
+ # Раньше TimeoutSeconds принимался, но нигде не использовался — задача работала
167
+ # до конца, а статус 'timeout' не выставлялся никогда. Теперь параллельно
168
+ # стартует сторожевой job: по истечении лимита он помечает маркер и убивает
169
+ # дерево процессов задачи (taskkill /T), а обёртка переводит статус в 'timeout'.
170
+ function Invoke-OpenCodeOnce {
171
+ param([string]$CommandPath, [string[]]$Arguments)
172
+
173
+ $watch = $null
174
+ $timeoutMarker = ""
175
+ if ($TimeoutSeconds -gt 0) {
176
+ $timeoutMarker = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-timeout-" + [guid]::NewGuid().ToString("N") + ".flag")
177
+ $watch = Start-Job -ScriptBlock {
178
+ param([int]$RootId, [int]$Seconds, [string]$Marker)
179
+ Start-Sleep -Seconds $Seconds
180
+ $selfId = $PID
181
+ $all = @()
182
+ try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId) } catch { $all = @() }
183
+ $targets = New-Object System.Collections.Generic.List[int]
184
+ $queue = New-Object System.Collections.Generic.Queue[int]
185
+ $queue.Enqueue($RootId)
186
+ $guard = 0
187
+ while ($queue.Count -gt 0 -and $guard -lt 2000) {
188
+ $guard++
189
+ $current = $queue.Dequeue()
190
+ foreach ($p in $all) {
191
+ $childId = [int]$p.ProcessId
192
+ if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
193
+ $targets.Add($childId)
194
+ $queue.Enqueue($childId)
195
+ }
196
+ }
197
+ }
198
+ if ($targets.Count -gt 0) {
199
+ try { Set-Content -Path $Marker -Value "timeout" -Encoding UTF8 } catch {}
200
+ foreach ($targetId in @($targets)) {
201
+ try { & taskkill.exe /F /T /PID $targetId 2>$null | Out-Null } catch {}
202
+ }
203
+ }
204
+ } -ArgumentList $PID, $TimeoutSeconds, $timeoutMarker
205
+ }
206
+
207
+ $script:timedOut = $false
208
+ $script:attemptExitCode = 0
209
+ try {
210
+ if ($LogFile) {
211
+ if ($CommandPath -like "*.ps1") {
212
+ & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 |
213
+ ForEach-Object { Format-LogLine $_ } |
214
+ Out-File -FilePath $LogFile -Append -Encoding utf8
215
+ } else {
216
+ & $CommandPath @Arguments *>&1 |
217
+ ForEach-Object { Format-LogLine $_ } |
218
+ Out-File -FilePath $LogFile -Append -Encoding utf8
219
+ }
220
+ } else {
221
+ if ($CommandPath -like "*.ps1") {
222
+ & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 |
223
+ ForEach-Object { Format-LogLine $_ } |
224
+ Out-Host
225
+ } else {
226
+ & $CommandPath @Arguments *>&1 |
227
+ ForEach-Object { Format-LogLine $_ } |
228
+ Out-Host
229
+ }
230
+ }
231
+ $script:attemptExitCode = $LASTEXITCODE
232
+ } finally {
233
+ if ($timeoutMarker -and (Test-Path -LiteralPath $timeoutMarker)) {
234
+ $script:timedOut = $true
235
+ }
236
+ if ($watch) {
237
+ Stop-Job -Job $watch -ErrorAction SilentlyContinue
238
+ Remove-Job -Job $watch -Force -ErrorAction SilentlyContinue
239
+ }
240
+ if ($timeoutMarker) {
241
+ Remove-Item -LiteralPath $timeoutMarker -Force -ErrorAction SilentlyContinue
242
+ }
243
+ }
244
+
245
+ if ($script:timedOut) {
246
+ Write-Log "[windows-scheduler] Таймаут: задача '$TaskName' превысила лимит $TimeoutSeconds с — процесс остановлен."
247
+ $script:errorMessage = "Таймаут: превышено $TimeoutSeconds с"
248
+ return 124
249
+ }
250
+ return $script:attemptExitCode
251
+ }
252
+
116
253
  # Фильтр технического шума и служебных блоков OpenCode.
117
254
  # Строки ответа ИИ проходят без изменений.
118
255
  #
@@ -365,28 +502,26 @@ try {
365
502
  # Запускаем opencode и НАПРЯМУЮ направляем весь вывод (stdout + stderr) в лог.
366
503
  # Out-File -Append -Encoding utf8 пишет по мере поступления строк, поэтому
367
504
  # ответ ИИ появляется в GUI ещё до завершения задачи.
368
- if ($LogFile) {
369
- if ($opencodeCmd -like "*.ps1") {
370
- & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $opencodeCmd @opencodeArgs *>&1 |
371
- ForEach-Object { Format-LogLine $_ } |
372
- Out-File -FilePath $LogFile -Append -Encoding utf8
373
- } else {
374
- & $opencodeCmd @opencodeArgs *>&1 |
375
- ForEach-Object { Format-LogLine $_ } |
376
- Out-File -FilePath $LogFile -Append -Encoding utf8
505
+ # Hotfix 1.5.3.1: retryCount из схемы раньше нигде не применялся — теперь
506
+ # неудачная попытка повторяется до RetryCount раз с паузой RetryDelaySeconds.
507
+ $maxAttempts = 1 + [Math]::Max(0, $RetryCount)
508
+ $attempt = 0
509
+ while ($attempt -lt $maxAttempts) {
510
+ $attempt++
511
+ if ($attempt -gt 1) {
512
+ $waitSeconds = [Math]::Max(0, $RetryDelaySeconds)
513
+ Write-Log "[windows-scheduler] Повтор $($attempt - 1) из $($maxAttempts - 1) через $waitSeconds с..."
514
+ if ($waitSeconds -gt 0) { Start-Sleep -Seconds $waitSeconds }
515
+ $script:errorMessage = ""
377
516
  }
378
- } else {
379
- if ($opencodeCmd -like "*.ps1") {
380
- & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $opencodeCmd @opencodeArgs *>&1 |
381
- ForEach-Object { Format-LogLine $_ } |
382
- Out-Host
383
- } else {
384
- & $opencodeCmd @opencodeArgs *>&1 |
385
- ForEach-Object { Format-LogLine $_ } |
386
- Out-Host
517
+ $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
518
+ if ($script:exitCode -eq 0) { break }
519
+ # Таймаут повторять бессмысленно: каждая попытка снова съест весь лимит.
520
+ if ($script:timedOut) { break }
521
+ if ($attempt -lt $maxAttempts) {
522
+ Write-Log "[windows-scheduler] Попытка $attempt завершилась с кодом $($script:exitCode)."
387
523
  }
388
524
  }
389
- $script:exitCode = $LASTEXITCODE
390
525
 
391
526
  # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
392
527
  # завершения opencode run. Если ИИ упал — шлюз не запускаем.
@@ -443,7 +578,14 @@ try {
443
578
  # Фиксируем факт выполнения в историю и метрики (независимо от того, кто запустил: GUI или Windows)
444
579
  $endTime = Get-Date
445
580
  $durationMs = [int](($endTime - $startTime).TotalMilliseconds)
446
- $status = if ($script:exitCode -eq 0) { "success" } else { "error" }
581
+ # Hotfix 1.5.3.1: статус timeout теперь реально выставляется (см. Invoke-OpenCodeOnce).
582
+ if ($script:timedOut) {
583
+ $status = "timeout"
584
+ } elseif ($script:exitCode -eq 0) {
585
+ $status = "success"
586
+ } else {
587
+ $status = "error"
588
+ }
447
589
  $usage = Get-UsageFromLog -File $LogFile
448
590
  $tokensArg = "-"
449
591
  if ($usage.Tokens) { $tokensArg = $usage.Tokens }
@@ -451,19 +593,26 @@ try {
451
593
  if ($usage.Cost) { $costArg = $usage.Cost }
452
594
  $modelArg = "-"
453
595
  if ($Model) { $modelArg = $Model }
596
+ # Hotfix 1.5.3.1: пустая строка ошибки раньше «съедалась» PowerShell и
597
+ # сдвигала все следующие аргументы recorder (model получал preFlight,
598
+ # postFlight терялся). Теперь всегда передаём непустое значение.
599
+ $errorArg = "-"
600
+ if ($script:errorMessage) { $errorArg = $script:errorMessage }
454
601
  if ($RecorderFile) {
455
602
  try {
456
603
  if ($script:runId) {
457
- & node "$RecorderFile" --finish "$script:runId" "$TaskName" "$status" $durationMs $script:errorMessage $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
604
+ & node "$RecorderFile" --finish "$script:runId" "$TaskName" "$status" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
458
605
  } else {
459
606
  # Fallback: --start не удался (например, старая установка) —
460
607
  # пишем завершённую запись старым способом, без потери истории.
461
- & node "$RecorderFile" "$TaskName" "$status" "$startedAtIso" $durationMs $script:errorMessage $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
608
+ & node "$RecorderFile" "$TaskName" "$status" "$startedAtIso" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
462
609
  }
463
610
  } catch {}
464
611
  }
465
612
 
466
- if ($LockFile -and (Test-Path $LockFile)) {
613
+ # Снимаем блокировку только если мы её захватили: иначе пропущенный
614
+ # параллельный запуск удалял бы lock активной задачи.
615
+ if ($script:lockAcquired -and $LockFile -and (Test-Path $LockFile)) {
467
616
  try {
468
617
  Remove-Item $LockFile -Force
469
618
  } catch {}
@@ -535,6 +684,26 @@ export function lockFilePath(taskName: string): string {
535
684
  * без флагов), "reuse" (--session $SessionId), "last" (--continue)
536
685
  * @param sessionId идентификатор сессии для режима "reuse" (спринт 24, опционально)
537
686
  */
687
+ /**
688
+ * Hotfix 1.5.3.1: хуки и Quality Gate пишутся в отдельные .cmd-файлы.
689
+ *
690
+ * Раньше команда передавалась аргументом в однострочный вызов powershell.exe,
691
+ * а кавычки внутри неё заменялись на апострофы: `echo x > "C:\Program Files\out.txt"`
692
+ * превращался в нерабочий `echo x > 'C:\Program Files\out.txt'`. Файл снимает
693
+ * проблему целиком — внутри .cmd можно использовать любые кавычки и пайпы.
694
+ */
695
+ async function writeHookFile(
696
+ sanitizedName: string,
697
+ kind: "before" | "after" | "gate",
698
+ command: string
699
+ ): Promise<string> {
700
+ const dir = path.join(WRAPPER_DIR, "hooks");
701
+ await fs.mkdir(dir, { recursive: true });
702
+ const file = path.join(dir, `run-${sanitizedName}-${kind}.cmd`);
703
+ await fs.writeFile(file, `@echo off\r\nchcp 65001 >nul\r\n${command}\r\n`, "utf8");
704
+ return file;
705
+ }
706
+
538
707
  export async function writeWrapperCmd(
539
708
  sanitizedName: string,
540
709
  taskName: string,
@@ -559,7 +728,9 @@ export async function writeWrapperCmd(
559
728
  },
560
729
  envFile?: string,
561
730
  sessionMode?: "new" | "reuse" | "last",
562
- sessionId?: string
731
+ sessionId?: string,
732
+ retryCount?: number,
733
+ retryDelaySeconds?: number
563
734
  ): Promise<string> {
564
735
  await fs.mkdir(WRAPPER_DIR, { recursive: true });
565
736
  const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
@@ -577,6 +748,14 @@ export async function writeWrapperCmd(
577
748
  `-LockFile "${lockFile}"`,
578
749
  ];
579
750
 
751
+ // Hotfix 1.5.3.1: ретраи. Параметр не передаём при 0 — обёртка по умолчанию
752
+ // делает ровно одну попытку, как раньше.
753
+ const safeRetryCount = Math.max(0, Math.floor(retryCount ?? 0));
754
+ if (safeRetryCount > 0) {
755
+ psArgs.push(`-RetryCount ${safeRetryCount}`);
756
+ psArgs.push(`-RetryDelaySeconds ${Math.max(0, Math.floor(retryDelaySeconds ?? 0))}`);
757
+ }
758
+
580
759
  if (logFile) {
581
760
  psArgs.push(`-LogFile "${logFile}"`);
582
761
  }
@@ -585,12 +764,11 @@ export async function writeWrapperCmd(
585
764
  psArgs.push(`-RecorderFile "${recorderFile}"`);
586
765
  }
587
766
 
588
- if (qualityGate) {
589
- // Кавычки в .cmd-строке ломают передачу аргумента, переводы строк — тоже.
590
- const safeGate = qualityGate.replace(/[\r\n]+/g, " ").replace(/"/g, "'").trim();
591
- if (safeGate) {
592
- psArgs.push(`-QualityGate "${safeGate}"`);
593
- }
767
+ if (qualityGate?.trim()) {
768
+ // Hotfix 1.5.3.1: команда пишется в отдельный .cmd — кавычки и пайпы
769
+ // внутри неё больше не ломают однострочный вызов powershell.exe.
770
+ const gateFile = await writeHookFile(sanitizedName, "gate", qualityGate);
771
+ psArgs.push(`-QualityGate "${gateFile}"`);
594
772
  }
595
773
 
596
774
  if (model?.trim()) {
@@ -622,14 +800,16 @@ export async function writeWrapperCmd(
622
800
  }
623
801
  }
624
802
 
625
- // Хуки передаются одной строкой: кавычки заменяем на апострофы, как у Quality Gate.
626
- for (const [flag, script] of [
627
- ["-BeforeScript", beforeScript],
628
- ["-AfterScript", afterScript],
803
+ // Hotfix 1.5.3.1: хуки — в отдельные .cmd-файлы (см. writeHookFile).
804
+ // Раньше кавычки заменялись на апострофы, из-за чего хуки с путями в кавычках
805
+ // (например, "C:\Program Files\...") падали.
806
+ for (const [flag, script, kind] of [
807
+ ["-BeforeScript", beforeScript, "before"],
808
+ ["-AfterScript", afterScript, "after"],
629
809
  ] as const) {
630
- const safe = script?.replace(/[\r\n]+/g, " ").replace(/"/g, "'").trim();
631
- if (safe) {
632
- psArgs.push(`${flag} "${safe}"`);
810
+ if (script?.trim()) {
811
+ const hookFile = await writeHookFile(sanitizedName, kind, script);
812
+ psArgs.push(`${flag} "${hookFile}"`);
633
813
  }
634
814
  }
635
815