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
@@ -45,7 +45,9 @@ export const WRAPPER_SCRIPT = `param(
45
45
  [string]$AfterScript,
46
46
  [string]$EnvFile,
47
47
  [string]$SessionMode,
48
- [string]$SessionId
48
+ [string]$SessionId,
49
+ [int]$RetryCount = 0,
50
+ [int]$RetryDelaySeconds = 0
49
51
  )
50
52
 
51
53
  [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
@@ -83,9 +85,56 @@ $script:errorMessage = ""
83
85
  $script:preFlightStatus = "skipped"
84
86
  $script:postFlightStatus = "skipped"
85
87
  $script:skipMainTask = $false
88
+ $script:lockAcquired = $false
89
+ $script:timedOut = $false
90
+ $script:attemptExitCode = 0
86
91
  $startedAtIso = $startTime.ToUniversalTime().ToString("o")
87
92
  $script:runId = ""
88
93
 
94
+ # Hotfix 1.5.3.1: блокировка ДО записи в историю. Раньше lock существовал только
95
+ # в in-process пути (LockManager/withLock), а schtasks-запуск обёртки его не
96
+ # проверял: два одновременных запуска дублировали задачу и дрались за лог.
97
+ # Атомарное создание файла (CreateNew) даёт ту же гарантию, что и Node-лок.
98
+ if ($LockFile) {
99
+ try {
100
+ $lockDir = Split-Path -Parent $LockFile
101
+ if ($lockDir -and -not (Test-Path -LiteralPath $lockDir)) {
102
+ New-Item -ItemType Directory -Force -Path $lockDir | Out-Null
103
+ }
104
+ $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
105
+ try {
106
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes($startedAtIso)
107
+ $lockStream.Write($lockBytes, 0, $lockBytes.Length)
108
+ } finally {
109
+ $lockStream.Dispose()
110
+ }
111
+ $script:lockAcquired = $true
112
+ } catch [System.IO.IOException] {
113
+ # Зависший lock (старше 24 ч — как STALE_LOCK_MAX_AGE_MS) снимаем один раз,
114
+ # иначе после аварийного завершения задача залипла бы навсегда.
115
+ $stale = $false
116
+ try {
117
+ $ageMs = ((Get-Date) - (Get-Item -LiteralPath $LockFile).LastWriteTime).TotalMilliseconds
118
+ if ($ageMs -gt 86400000) { $stale = $true }
119
+ } catch {}
120
+ if ($stale) {
121
+ try { Remove-Item -LiteralPath $LockFile -Force } catch {}
122
+ try {
123
+ $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
124
+ $lockStream.Dispose()
125
+ $script:lockAcquired = $true
126
+ } catch {}
127
+ }
128
+ if (-not $script:lockAcquired) {
129
+ Write-Log "[windows-scheduler] Запуск задачи '$TaskName' пропущен: удерживается активная блокировка."
130
+ exit 0
131
+ }
132
+ } catch {
133
+ Write-Log "[windows-scheduler] Не удалось захватить блокировку задачи '$TaskName': $_"
134
+ exit 0
135
+ }
136
+ }
137
+
89
138
  # Crash recovery: фиксируем начало ДО pre-flight и основной задачи.
90
139
  # Если процесс убьют (таймаут/KILL/перезагрузка), останется finished_at = NULL,
91
140
  # и при следующем старте плагина recovery пометит запись как error.
@@ -110,6 +159,94 @@ function Invoke-HookScript {
110
159
  return $code
111
160
  }
112
161
 
162
+ # Hotfix 1.5.3.1: запуск opencode с реальным таймаутом.
163
+ # Раньше TimeoutSeconds принимался, но нигде не использовался — задача работала
164
+ # до конца, а статус 'timeout' не выставлялся никогда. Теперь параллельно
165
+ # стартует сторожевой job: по истечении лимита он помечает маркер и убивает
166
+ # дерево процессов задачи (taskkill /T), а обёртка переводит статус в 'timeout'.
167
+ function Invoke-OpenCodeOnce {
168
+ param([string]$CommandPath, [string[]]$Arguments)
169
+
170
+ $watch = $null
171
+ $timeoutMarker = ""
172
+ if ($TimeoutSeconds -gt 0) {
173
+ $timeoutMarker = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-timeout-" + [guid]::NewGuid().ToString("N") + ".flag")
174
+ $watch = Start-Job -ScriptBlock {
175
+ param([int]$RootId, [int]$Seconds, [string]$Marker)
176
+ Start-Sleep -Seconds $Seconds
177
+ $selfId = $PID
178
+ $all = @()
179
+ try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId) } catch { $all = @() }
180
+ $targets = New-Object System.Collections.Generic.List[int]
181
+ $queue = New-Object System.Collections.Generic.Queue[int]
182
+ $queue.Enqueue($RootId)
183
+ $guard = 0
184
+ while ($queue.Count -gt 0 -and $guard -lt 2000) {
185
+ $guard++
186
+ $current = $queue.Dequeue()
187
+ foreach ($p in $all) {
188
+ $childId = [int]$p.ProcessId
189
+ if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
190
+ $targets.Add($childId)
191
+ $queue.Enqueue($childId)
192
+ }
193
+ }
194
+ }
195
+ if ($targets.Count -gt 0) {
196
+ try { Set-Content -Path $Marker -Value "timeout" -Encoding UTF8 } catch {}
197
+ foreach ($targetId in @($targets)) {
198
+ try { & taskkill.exe /F /T /PID $targetId 2>$null | Out-Null } catch {}
199
+ }
200
+ }
201
+ } -ArgumentList $PID, $TimeoutSeconds, $timeoutMarker
202
+ }
203
+
204
+ $script:timedOut = $false
205
+ $script:attemptExitCode = 0
206
+ try {
207
+ if ($LogFile) {
208
+ if ($CommandPath -like "*.ps1") {
209
+ & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 |
210
+ ForEach-Object { Format-LogLine $_ } |
211
+ Out-File -FilePath $LogFile -Append -Encoding utf8
212
+ } else {
213
+ & $CommandPath @Arguments *>&1 |
214
+ ForEach-Object { Format-LogLine $_ } |
215
+ Out-File -FilePath $LogFile -Append -Encoding utf8
216
+ }
217
+ } else {
218
+ if ($CommandPath -like "*.ps1") {
219
+ & powershell.exe -ExecutionPolicy Bypass -NoProfile -File $CommandPath @Arguments *>&1 |
220
+ ForEach-Object { Format-LogLine $_ } |
221
+ Out-Host
222
+ } else {
223
+ & $CommandPath @Arguments *>&1 |
224
+ ForEach-Object { Format-LogLine $_ } |
225
+ Out-Host
226
+ }
227
+ }
228
+ $script:attemptExitCode = $LASTEXITCODE
229
+ } finally {
230
+ if ($timeoutMarker -and (Test-Path -LiteralPath $timeoutMarker)) {
231
+ $script:timedOut = $true
232
+ }
233
+ if ($watch) {
234
+ Stop-Job -Job $watch -ErrorAction SilentlyContinue
235
+ Remove-Job -Job $watch -Force -ErrorAction SilentlyContinue
236
+ }
237
+ if ($timeoutMarker) {
238
+ Remove-Item -LiteralPath $timeoutMarker -Force -ErrorAction SilentlyContinue
239
+ }
240
+ }
241
+
242
+ if ($script:timedOut) {
243
+ Write-Log "[windows-scheduler] Таймаут: задача '$TaskName' превысила лимит $TimeoutSeconds с — процесс остановлен."
244
+ $script:errorMessage = "Таймаут: превышено $TimeoutSeconds с"
245
+ return 124
246
+ }
247
+ return $script:attemptExitCode
248
+ }
249
+
113
250
  # Фильтр технического шума и служебных блоков OpenCode.
114
251
  # Строки ответа ИИ проходят без изменений.
115
252
  #
@@ -362,28 +499,26 @@ try {
362
499
  # Запускаем opencode и НАПРЯМУЮ направляем весь вывод (stdout + stderr) в лог.
363
500
  # Out-File -Append -Encoding utf8 пишет по мере поступления строк, поэтому
364
501
  # ответ ИИ появляется в 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
374
- }
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
502
+ # Hotfix 1.5.3.1: retryCount из схемы раньше нигде не применялся — теперь
503
+ # неудачная попытка повторяется до RetryCount раз с паузой RetryDelaySeconds.
504
+ $maxAttempts = 1 + [Math]::Max(0, $RetryCount)
505
+ $attempt = 0
506
+ while ($attempt -lt $maxAttempts) {
507
+ $attempt++
508
+ if ($attempt -gt 1) {
509
+ $waitSeconds = [Math]::Max(0, $RetryDelaySeconds)
510
+ Write-Log "[windows-scheduler] Повтор $($attempt - 1) из $($maxAttempts - 1) через $waitSeconds с..."
511
+ if ($waitSeconds -gt 0) { Start-Sleep -Seconds $waitSeconds }
512
+ $script:errorMessage = ""
513
+ }
514
+ $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
515
+ if ($script:exitCode -eq 0) { break }
516
+ # Таймаут повторять бессмысленно: каждая попытка снова съест весь лимит.
517
+ if ($script:timedOut) { break }
518
+ if ($attempt -lt $maxAttempts) {
519
+ Write-Log "[windows-scheduler] Попытка $attempt завершилась с кодом $($script:exitCode)."
384
520
  }
385
521
  }
386
- $script:exitCode = $LASTEXITCODE
387
522
 
388
523
  # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
389
524
  # завершения opencode run. Если ИИ упал — шлюз не запускаем.
@@ -440,7 +575,14 @@ try {
440
575
  # Фиксируем факт выполнения в историю и метрики (независимо от того, кто запустил: GUI или Windows)
441
576
  $endTime = Get-Date
442
577
  $durationMs = [int](($endTime - $startTime).TotalMilliseconds)
443
- $status = if ($script:exitCode -eq 0) { "success" } else { "error" }
578
+ # Hotfix 1.5.3.1: статус timeout теперь реально выставляется (см. Invoke-OpenCodeOnce).
579
+ if ($script:timedOut) {
580
+ $status = "timeout"
581
+ } elseif ($script:exitCode -eq 0) {
582
+ $status = "success"
583
+ } else {
584
+ $status = "error"
585
+ }
444
586
  $usage = Get-UsageFromLog -File $LogFile
445
587
  $tokensArg = "-"
446
588
  if ($usage.Tokens) { $tokensArg = $usage.Tokens }
@@ -448,19 +590,26 @@ try {
448
590
  if ($usage.Cost) { $costArg = $usage.Cost }
449
591
  $modelArg = "-"
450
592
  if ($Model) { $modelArg = $Model }
593
+ # Hotfix 1.5.3.1: пустая строка ошибки раньше «съедалась» PowerShell и
594
+ # сдвигала все следующие аргументы recorder (model получал preFlight,
595
+ # postFlight терялся). Теперь всегда передаём непустое значение.
596
+ $errorArg = "-"
597
+ if ($script:errorMessage) { $errorArg = $script:errorMessage }
451
598
  if ($RecorderFile) {
452
599
  try {
453
600
  if ($script:runId) {
454
- & node "$RecorderFile" --finish "$script:runId" "$TaskName" "$status" $durationMs $script:errorMessage $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
601
+ & node "$RecorderFile" --finish "$script:runId" "$TaskName" "$status" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
455
602
  } else {
456
603
  # Fallback: --start не удался (например, старая установка) —
457
604
  # пишем завершённую запись старым способом, без потери истории.
458
- & node "$RecorderFile" "$TaskName" "$status" "$startedAtIso" $durationMs $script:errorMessage $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
605
+ & node "$RecorderFile" "$TaskName" "$status" "$startedAtIso" $durationMs "$errorArg" $tokensArg $costArg "$modelArg" "$script:preFlightStatus" "$script:postFlightStatus"
459
606
  }
460
607
  } catch {}
461
608
  }
462
609
 
463
- if ($LockFile -and (Test-Path $LockFile)) {
610
+ # Снимаем блокировку только если мы её захватили: иначе пропущенный
611
+ # параллельный запуск удалял бы lock активной задачи.
612
+ if ($script:lockAcquired -and $LockFile -and (Test-Path $LockFile)) {
464
613
  try {
465
614
  Remove-Item $LockFile -Force
466
615
  } catch {}
@@ -528,7 +677,22 @@ export function lockFilePath(taskName) {
528
677
  * без флагов), "reuse" (--session $SessionId), "last" (--continue)
529
678
  * @param sessionId идентификатор сессии для режима "reuse" (спринт 24, опционально)
530
679
  */
531
- export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeoutSeconds, lockFile, workdir, logFile, recorderFile, qualityGate, model, beforeScript, afterScript, workspaceName, allowedTools, deniedTools, scheduleGate, envFile, sessionMode, sessionId) {
680
+ /**
681
+ * Hotfix 1.5.3.1: хуки и Quality Gate пишутся в отдельные .cmd-файлы.
682
+ *
683
+ * Раньше команда передавалась аргументом в однострочный вызов powershell.exe,
684
+ * а кавычки внутри неё заменялись на апострофы: `echo x > "C:\Program Files\out.txt"`
685
+ * превращался в нерабочий `echo x > 'C:\Program Files\out.txt'`. Файл снимает
686
+ * проблему целиком — внутри .cmd можно использовать любые кавычки и пайпы.
687
+ */
688
+ async function writeHookFile(sanitizedName, kind, command) {
689
+ const dir = path.join(WRAPPER_DIR, "hooks");
690
+ await fs.mkdir(dir, { recursive: true });
691
+ const file = path.join(dir, `run-${sanitizedName}-${kind}.cmd`);
692
+ await fs.writeFile(file, `@echo off\r\nchcp 65001 >nul\r\n${command}\r\n`, "utf8");
693
+ return file;
694
+ }
695
+ 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) {
532
696
  await fs.mkdir(WRAPPER_DIR, { recursive: true });
533
697
  const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
534
698
  const ps1Path = path.join(WRAPPER_DIR, WRAPPER_FILENAME);
@@ -543,18 +707,24 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
543
707
  `-TimeoutSeconds ${timeoutSeconds}`,
544
708
  `-LockFile "${lockFile}"`,
545
709
  ];
710
+ // Hotfix 1.5.3.1: ретраи. Параметр не передаём при 0 — обёртка по умолчанию
711
+ // делает ровно одну попытку, как раньше.
712
+ const safeRetryCount = Math.max(0, Math.floor(retryCount ?? 0));
713
+ if (safeRetryCount > 0) {
714
+ psArgs.push(`-RetryCount ${safeRetryCount}`);
715
+ psArgs.push(`-RetryDelaySeconds ${Math.max(0, Math.floor(retryDelaySeconds ?? 0))}`);
716
+ }
546
717
  if (logFile) {
547
718
  psArgs.push(`-LogFile "${logFile}"`);
548
719
  }
549
720
  if (recorderFile) {
550
721
  psArgs.push(`-RecorderFile "${recorderFile}"`);
551
722
  }
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
- }
723
+ if (qualityGate?.trim()) {
724
+ // Hotfix 1.5.3.1: команда пишется в отдельный .cmd — кавычки и пайпы
725
+ // внутри неё больше не ломают однострочный вызов powershell.exe.
726
+ const gateFile = await writeHookFile(sanitizedName, "gate", qualityGate);
727
+ psArgs.push(`-QualityGate "${gateFile}"`);
558
728
  }
559
729
  if (model?.trim()) {
560
730
  const safeModel = model.replace(/[\r\n"]+/g, "").trim();
@@ -582,14 +752,16 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
582
752
  psArgs.push(`${flag} "${safe}"`);
583
753
  }
584
754
  }
585
- // Хуки передаются одной строкой: кавычки заменяем на апострофы, как у Quality Gate.
586
- for (const [flag, script] of [
587
- ["-BeforeScript", beforeScript],
588
- ["-AfterScript", afterScript],
755
+ // Hotfix 1.5.3.1: хуки — в отдельные .cmd-файлы (см. writeHookFile).
756
+ // Раньше кавычки заменялись на апострофы, из-за чего хуки с путями в кавычках
757
+ // (например, "C:\Program Files\...") падали.
758
+ for (const [flag, script, kind] of [
759
+ ["-BeforeScript", beforeScript, "before"],
760
+ ["-AfterScript", afterScript, "after"],
589
761
  ]) {
590
- const safe = script?.replace(/[\r\n]+/g, " ").replace(/"/g, "'").trim();
591
- if (safe) {
592
- psArgs.push(`${flag} "${safe}"`);
762
+ if (script?.trim()) {
763
+ const hookFile = await writeHookFile(sanitizedName, kind, script);
764
+ psArgs.push(`${flag} "${hookFile}"`);
593
765
  }
594
766
  }
595
767
  // Спринт 21: env-файл workspace (пары KEY=VALUE). Значения не логируются.
@@ -0,0 +1,34 @@
1
+ import { type TriageFailure, type TriageInput, type TriageOptions, type TriageVerdict } from "./triage.js";
2
+ import type { TriageSettings } from "../settings.js";
3
+ /** Что делать с уведомлением после триажа. */
4
+ export type TriageAction = "notify" | "skip";
5
+ /** Откуда взято решение — для shadow-режима и диагностики. */
6
+ export type TriageSource = "off" | "llm" | "rules" | "fallback";
7
+ /** Итог цепочки LLM → правила → fail-open. */
8
+ export interface TriageDecision {
9
+ action: TriageAction;
10
+ source: TriageSource;
11
+ verdict?: TriageVerdict;
12
+ /** Причина, по которой LLM не дал пригодного вердикта. */
13
+ failure?: TriageFailure | "low-confidence";
14
+ attempts: number;
15
+ latencyMs: number;
16
+ /** id сработавшего правила, если решение приняли правила. */
17
+ ruleId?: string;
18
+ }
19
+ /**
20
+ * Применяет цепочку деградации к одному уведомлению.
21
+ *
22
+ * - `off` — триаж выключен, уведомление отправляется.
23
+ * - `rules` — решают только правила; нет совпадения = отправить.
24
+ * - `llm`/`auto` — LLM классифицирует, но сам ничего не подавляет; при
25
+ * ошибке, таймауте или низкой уверенности управление переходит к правилам
26
+ * (если `fallback: "rules"`) либо уведомление отправляется без правил.
27
+ *
28
+ * Функция никогда не бросает исключение и по умолчанию возвращает `notify`:
29
+ * недоступный классификатор не должен терять уведомление.
30
+ */
31
+ export declare function decideTriage(input: TriageInput, settings: TriageSettings | undefined, options?: TriageOptions): Promise<TriageDecision>;
32
+ /** Записывает решение в shadow-журнал, если shadow-режим активен. */
33
+ export declare function recordShadow(input: TriageInput, decision: TriageDecision, shadow: TriageSettings["shadow"] | undefined): void;
34
+ //# sourceMappingURL=triage-chain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"triage-chain.d.ts","sourceRoot":"","sources":["../../src/core/triage-chain.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,aAAa,EACnB,MAAM,aAAa,CAAC;AAGrB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAErD,8CAA8C;AAC9C,MAAM,MAAM,YAAY,GAAG,QAAQ,GAAG,MAAM,CAAC;AAE7C,8DAA8D;AAC9D,MAAM,MAAM,YAAY,GAAG,KAAK,GAAG,KAAK,GAAG,OAAO,GAAG,UAAU,CAAC;AAEhE,8CAA8C;AAC9C,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,YAAY,CAAC;IACrB,MAAM,EAAE,YAAY,CAAC;IACrB,OAAO,CAAC,EAAE,aAAa,CAAC;IACxB,0DAA0D;IAC1D,OAAO,CAAC,EAAE,aAAa,GAAG,gBAAgB,CAAC;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAoBD;;;;;;;;;;;GAWG;AACH,wBAAsB,YAAY,CAChC,KAAK,EAAE,WAAW,EAClB,QAAQ,EAAE,cAAc,GAAG,SAAS,EACpC,OAAO,GAAE,aAAkB,GAC1B,OAAO,CAAC,cAAc,CAAC,CAyCzB;AAED,qEAAqE;AACrE,wBAAgB,YAAY,CAC1B,KAAK,EAAE,WAAW,EAClB,QAAQ,EAAE,cAAc,EACxB,MAAM,EAAE,cAAc,CAAC,QAAQ,CAAC,GAAG,SAAS,GAC3C,IAAI,CAGN"}
@@ -0,0 +1,70 @@
1
+ import { classifyNotification, } from "./triage.js";
2
+ import { evaluateTriageRules } from "./triage-rules.js";
3
+ import { recordShadowDecision } from "./triage-shadow.js";
4
+ const NOTIFY = "notify";
5
+ function ruleDecision(input, settings, source) {
6
+ const result = evaluateTriageRules(input, settings.rules);
7
+ return {
8
+ action: result.action,
9
+ source,
10
+ verdict: result.verdict,
11
+ attempts: 0,
12
+ latencyMs: 0,
13
+ ruleId: result.ruleId,
14
+ };
15
+ }
16
+ /**
17
+ * Применяет цепочку деградации к одному уведомлению.
18
+ *
19
+ * - `off` — триаж выключен, уведомление отправляется.
20
+ * - `rules` — решают только правила; нет совпадения = отправить.
21
+ * - `llm`/`auto` — LLM классифицирует, но сам ничего не подавляет; при
22
+ * ошибке, таймауте или низкой уверенности управление переходит к правилам
23
+ * (если `fallback: "rules"`) либо уведомление отправляется без правил.
24
+ *
25
+ * Функция никогда не бросает исключение и по умолчанию возвращает `notify`:
26
+ * недоступный классификатор не должен терять уведомление.
27
+ */
28
+ export async function decideTriage(input, settings, options = {}) {
29
+ if (!settings || settings.mode === "off") {
30
+ return { action: NOTIFY, source: "off", attempts: 0, latencyMs: 0 };
31
+ }
32
+ if (settings.mode === "rules") {
33
+ return ruleDecision(input, settings, "rules");
34
+ }
35
+ const llm = await classifyNotification(input, settings, options);
36
+ if (llm.ok && llm.verdict && llm.verdict.confidence >= settings.confidenceThreshold) {
37
+ return {
38
+ action: NOTIFY,
39
+ source: "llm",
40
+ verdict: llm.verdict,
41
+ attempts: llm.attempts,
42
+ latencyMs: llm.latencyMs,
43
+ };
44
+ }
45
+ const failure = llm.ok
46
+ ? "low-confidence"
47
+ : llm.failure ?? "invalid-response";
48
+ if (settings.fallback === "skip") {
49
+ return {
50
+ action: NOTIFY,
51
+ source: "fallback",
52
+ failure,
53
+ attempts: llm.attempts,
54
+ latencyMs: llm.latencyMs,
55
+ };
56
+ }
57
+ const byRules = ruleDecision(input, settings, "fallback");
58
+ return {
59
+ ...byRules,
60
+ failure,
61
+ attempts: llm.attempts,
62
+ latencyMs: llm.latencyMs,
63
+ };
64
+ }
65
+ /** Записывает решение в shadow-журнал, если shadow-режим активен. */
66
+ export function recordShadow(input, decision, shadow) {
67
+ if (!shadow || !shadow.enabled)
68
+ return;
69
+ recordShadowDecision(input, decision);
70
+ }
@@ -0,0 +1,23 @@
1
+ import type { TriageRule, TriageRuleAction } from "../settings.js";
2
+ import type { TriageInput, TriageVerdict } from "./triage.js";
3
+ /**
4
+ * Rules-движок триажа (Спринт 30.4).
5
+ *
6
+ * Проверяет правила по убыванию priority, при равенстве — в порядке массива.
7
+ * Срабатывает только первое совпавшее правило. Движок чистый: ничего не
8
+ * отправляет и не пишет в БД, поэтому его легко использовать в 30.5.
9
+ */
10
+ export interface TriageRuleResult {
11
+ matched: boolean;
12
+ ruleId?: string;
13
+ action: TriageRuleAction;
14
+ verdict: TriageVerdict;
15
+ }
16
+ /**
17
+ * Встроенные правила. Работают, если в настройках нет поля `rules`
18
+ * (пустой массив отключает их). Специфичные ошибки важнее статуса.
19
+ */
20
+ export declare const DEFAULT_TRIAGE_RULES: readonly TriageRule[];
21
+ /** Оценивает одно уведомление по правилам. Не бросает исключений. */
22
+ export declare function evaluateTriageRules(input: TriageInput, rules?: readonly TriageRule[] | undefined): TriageRuleResult;
23
+ //# sourceMappingURL=triage-rules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"triage-rules.d.ts","sourceRoot":"","sources":["../../src/core/triage-rules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,KAAK,EAEV,WAAW,EAEX,aAAa,EACd,MAAM,aAAa,CAAC;AAErB;;;;;;GAMG;AAEH,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,gBAAgB,CAAC;IACzB,OAAO,EAAE,aAAa,CAAC;CACxB;AAID;;;GAGG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAAS,UAAU,EAgFrD,CAAC;AA8DF,qEAAqE;AACrE,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,WAAW,EAClB,KAAK,GAAE,SAAS,UAAU,EAAE,GAAG,SAAgC,GAC9D,gBAAgB,CAuClB"}
@@ -0,0 +1,174 @@
1
+ const DEFAULT_REASON = "Правило не совпало.";
2
+ /**
3
+ * Встроенные правила. Работают, если в настройках нет поля `rules`
4
+ * (пустой массив отключает их). Специфичные ошибки важнее статуса.
5
+ */
6
+ export const DEFAULT_TRIAGE_RULES = [
7
+ {
8
+ id: "error-timeout",
9
+ field: "error",
10
+ operator: "regex",
11
+ value: "timeout|timed out|таймаут|deadline exceeded",
12
+ category: "timeout",
13
+ severity: "high",
14
+ confidence: 0.9,
15
+ priority: 100,
16
+ reason: "В ошибке есть признак таймаута.",
17
+ },
18
+ {
19
+ id: "error-permission",
20
+ field: "error",
21
+ operator: "regex",
22
+ value: "permission denied|access denied|eacces|unauthorized|forbidden|доступ запрещ|нет прав",
23
+ category: "permission",
24
+ severity: "high",
25
+ confidence: 0.9,
26
+ priority: 100,
27
+ reason: "В ошибке есть признак отказа доступа.",
28
+ },
29
+ {
30
+ id: "error-network",
31
+ field: "error",
32
+ operator: "regex",
33
+ value: "econnrefused|enotfound|eai_again|network error|connection reset|dns|сеть недоступна|соединение",
34
+ category: "network",
35
+ severity: "high",
36
+ confidence: 0.85,
37
+ priority: 100,
38
+ reason: "В ошибке есть признак сетевой проблемы.",
39
+ },
40
+ {
41
+ id: "error-quality",
42
+ field: "error",
43
+ operator: "regex",
44
+ value: "quality gate|tests? failed|build failed|lint|тест[ыа]? не прош|сборка",
45
+ category: "quality",
46
+ severity: "high",
47
+ confidence: 0.85,
48
+ priority: 100,
49
+ reason: "В ошибке есть признак проблемы качества.",
50
+ },
51
+ {
52
+ id: "status-error",
53
+ field: "status",
54
+ operator: "equals",
55
+ value: "error",
56
+ category: "unknown",
57
+ severity: "high",
58
+ confidence: 0.8,
59
+ priority: 10,
60
+ reason: "Задача завершилась ошибкой.",
61
+ },
62
+ {
63
+ id: "status-partial",
64
+ field: "status",
65
+ operator: "equals",
66
+ value: "partial",
67
+ category: "unknown",
68
+ severity: "medium",
69
+ confidence: 0.8,
70
+ priority: 10,
71
+ reason: "Часть работы завершилась ошибкой.",
72
+ },
73
+ {
74
+ id: "status-success",
75
+ field: "status",
76
+ operator: "equals",
77
+ value: "success",
78
+ category: "unknown",
79
+ severity: "low",
80
+ confidence: 0.8,
81
+ priority: 10,
82
+ reason: "Задача завершилась успешно.",
83
+ },
84
+ ];
85
+ function textFor(field, input) {
86
+ switch (field) {
87
+ case "status":
88
+ return input.status ?? "";
89
+ case "task":
90
+ return input.taskName ?? "";
91
+ case "error":
92
+ return input.error ?? "";
93
+ default:
94
+ return null;
95
+ }
96
+ }
97
+ function compareNumber(actual, operator, expected) {
98
+ switch (operator) {
99
+ case "equals":
100
+ return actual === expected;
101
+ case "gt":
102
+ return actual > expected;
103
+ case "lt":
104
+ return actual < expected;
105
+ case "gte":
106
+ return actual >= expected;
107
+ case "lte":
108
+ return actual <= expected;
109
+ default:
110
+ return false;
111
+ }
112
+ }
113
+ function matches(rule, input) {
114
+ if (rule.field === "cost") {
115
+ const cost = Number(input.costUsd);
116
+ if (!Number.isFinite(cost) || typeof rule.value !== "number")
117
+ return false;
118
+ return compareNumber(cost, rule.operator, rule.value);
119
+ }
120
+ const text = textFor(rule.field, input);
121
+ if (text === null || typeof rule.value !== "string")
122
+ return false;
123
+ if (rule.operator === "equals") {
124
+ return text.trim().toLowerCase() === rule.value.trim().toLowerCase();
125
+ }
126
+ if (rule.operator === "contains") {
127
+ return text.toLowerCase().includes(rule.value.toLowerCase());
128
+ }
129
+ if (rule.operator === "regex") {
130
+ try {
131
+ return new RegExp(rule.value, "i").test(text);
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ }
137
+ return false;
138
+ }
139
+ function conditionLabel(rule) {
140
+ return rule.id ?? `${rule.field} ${rule.operator} ${rule.value}`;
141
+ }
142
+ /** Оценивает одно уведомление по правилам. Не бросает исключений. */
143
+ export function evaluateTriageRules(input, rules = DEFAULT_TRIAGE_RULES) {
144
+ const ordered = (rules ?? [])
145
+ .map((rule, index) => ({ rule, index }))
146
+ .sort((a, b) => (b.rule.priority ?? 0) - (a.rule.priority ?? 0) || a.index - b.index);
147
+ for (const { rule } of ordered) {
148
+ if (!matches(rule, input))
149
+ continue;
150
+ const category = (rule.category ?? "unknown");
151
+ const severity = (rule.severity ?? "medium");
152
+ const confidence = typeof rule.confidence === "number" && Number.isFinite(rule.confidence)
153
+ ? Math.min(1, Math.max(0, rule.confidence))
154
+ : 0.8;
155
+ const reason = rule.reason?.trim() ||
156
+ `Правило "${conditionLabel(rule)}" совпало: ${rule.field} ${rule.operator} ${rule.value}.`;
157
+ return {
158
+ matched: true,
159
+ ruleId: rule.id,
160
+ action: rule.action ?? "notify",
161
+ verdict: { category, severity, confidence, reason },
162
+ };
163
+ }
164
+ return {
165
+ matched: false,
166
+ action: "notify",
167
+ verdict: {
168
+ category: "unknown",
169
+ severity: "low",
170
+ confidence: 0,
171
+ reason: DEFAULT_REASON,
172
+ },
173
+ };
174
+ }