agent-steward 0.0.4 → 0.0.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 (190) hide show
  1. package/CHANGELOG.md +134 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +52 -7
  4. package/ROADMAP-STRATEGY.md +21 -18
  5. package/ROADMAP.md +140 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +351 -0
  9. package/dist/core/execution.d.ts +203 -0
  10. package/dist/core/execution.d.ts.map +1 -0
  11. package/dist/core/execution.js +309 -0
  12. package/dist/core/gate-integrity.d.ts +35 -0
  13. package/dist/core/gate-integrity.d.ts.map +1 -0
  14. package/dist/core/gate-integrity.js +132 -0
  15. package/dist/core/git-trigger.d.ts.map +1 -1
  16. package/dist/core/git-trigger.js +14 -2
  17. package/dist/core/guard-run.d.ts +4 -0
  18. package/dist/core/guard-run.d.ts.map +1 -0
  19. package/dist/core/guard-run.js +101 -0
  20. package/dist/core/guard.d.ts +52 -0
  21. package/dist/core/guard.d.ts.map +1 -0
  22. package/dist/core/guard.js +362 -0
  23. package/dist/core/lock.d.ts +41 -0
  24. package/dist/core/lock.d.ts.map +1 -1
  25. package/dist/core/lock.js +141 -29
  26. package/dist/core/matrix.d.ts.map +1 -1
  27. package/dist/core/matrix.js +75 -15
  28. package/dist/core/mission.d.ts +83 -0
  29. package/dist/core/mission.d.ts.map +1 -0
  30. package/dist/core/mission.js +334 -0
  31. package/dist/core/pipeline-apply.d.ts +38 -0
  32. package/dist/core/pipeline-apply.d.ts.map +1 -0
  33. package/dist/core/pipeline-apply.js +117 -0
  34. package/dist/core/pipeline-io.d.ts +13 -0
  35. package/dist/core/pipeline-io.d.ts.map +1 -0
  36. package/dist/core/pipeline-io.js +64 -0
  37. package/dist/core/pipeline-map.d.ts +46 -0
  38. package/dist/core/pipeline-map.d.ts.map +1 -0
  39. package/dist/core/pipeline-map.js +196 -0
  40. package/dist/core/pipeline-spec.d.ts +109 -0
  41. package/dist/core/pipeline-spec.d.ts.map +1 -0
  42. package/dist/core/pipeline-spec.js +554 -0
  43. package/dist/core/ps-wrapper.d.ts +19 -2
  44. package/dist/core/ps-wrapper.d.ts.map +1 -1
  45. package/dist/core/ps-wrapper.js +250 -62
  46. package/dist/core/record-history.d.ts.map +1 -1
  47. package/dist/core/record-history.js +130 -29
  48. package/dist/core/router/rules.d.ts.map +1 -1
  49. package/dist/core/router/rules.js +6 -0
  50. package/dist/core/scheduler/linux.d.ts +8 -1
  51. package/dist/core/scheduler/linux.d.ts.map +1 -1
  52. package/dist/core/scheduler/linux.js +34 -9
  53. package/dist/core/scheduler/mac.d.ts +44 -2
  54. package/dist/core/scheduler/mac.d.ts.map +1 -1
  55. package/dist/core/scheduler/mac.js +126 -15
  56. package/dist/core/scheduler/windows.d.ts.map +1 -1
  57. package/dist/core/scheduler/windows.js +15 -12
  58. package/dist/core/structured-log.d.ts +7 -1
  59. package/dist/core/structured-log.d.ts.map +1 -1
  60. package/dist/core/worktree-run.d.ts +4 -0
  61. package/dist/core/worktree-run.d.ts.map +1 -0
  62. package/dist/core/worktree-run.js +164 -0
  63. package/dist/core/worktree.d.ts +115 -0
  64. package/dist/core/worktree.d.ts.map +1 -0
  65. package/dist/core/worktree.js +462 -0
  66. package/dist/core/wrappers/bash.d.ts +17 -0
  67. package/dist/core/wrappers/bash.d.ts.map +1 -1
  68. package/dist/core/wrappers/bash.js +175 -24
  69. package/dist/db/capability-repo.d.ts +43 -2
  70. package/dist/db/capability-repo.d.ts.map +1 -1
  71. package/dist/db/capability-repo.js +96 -11
  72. package/dist/db/history-repo.d.ts +38 -5
  73. package/dist/db/history-repo.d.ts.map +1 -1
  74. package/dist/db/history-repo.js +88 -25
  75. package/dist/db/metrics-repo.js +2 -2
  76. package/dist/db/recovery.d.ts.map +1 -1
  77. package/dist/db/recovery.js +5 -4
  78. package/dist/db/run-journal.d.ts +33 -5
  79. package/dist/db/run-journal.d.ts.map +1 -1
  80. package/dist/db/run-journal.js +78 -14
  81. package/dist/db/run-resume.d.ts +5 -0
  82. package/dist/db/run-resume.d.ts.map +1 -1
  83. package/dist/db/run-resume.js +9 -2
  84. package/dist/db/runs-repo.d.ts +19 -2
  85. package/dist/db/runs-repo.d.ts.map +1 -1
  86. package/dist/db/runs-repo.js +22 -6
  87. package/dist/db/schema.d.ts +2 -2
  88. package/dist/db/schema.d.ts.map +1 -1
  89. package/dist/db/schema.js +63 -2
  90. package/dist/history.d.ts +1 -1
  91. package/dist/history.d.ts.map +1 -1
  92. package/dist/i18n.d.ts +5 -0
  93. package/dist/i18n.d.ts.map +1 -1
  94. package/dist/i18n.js +11 -4
  95. package/dist/index.d.ts +136 -2
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +378 -14
  98. package/dist/notifications.d.ts +22 -0
  99. package/dist/notifications.d.ts.map +1 -1
  100. package/dist/notifications.js +36 -8
  101. package/dist/profiles.d.ts.map +1 -1
  102. package/dist/profiles.js +25 -4
  103. package/dist/rpc.d.ts +246 -0
  104. package/dist/rpc.d.ts.map +1 -1
  105. package/dist/rpc.js +117 -0
  106. package/dist/server.d.ts +15 -0
  107. package/dist/server.d.ts.map +1 -1
  108. package/dist/server.js +77 -18
  109. package/dist/settings.d.ts +2 -2
  110. package/dist/settings.d.ts.map +1 -1
  111. package/dist/settings.js +3 -3
  112. package/dist/shared/jobs-view.d.ts +1 -1
  113. package/dist/shared/jobs-view.d.ts.map +1 -1
  114. package/dist/shared/jobs-view.js +2 -0
  115. package/dist/task-transfer.d.ts +16 -0
  116. package/dist/task-transfer.d.ts.map +1 -1
  117. package/dist/task-transfer.js +16 -0
  118. package/docs/ARCHITECTURE.md +281 -65
  119. package/docs/COMPATIBILITY.md +2 -2
  120. package/docs/CONCEPT.md +18 -4
  121. package/docs/CROSS_PLATFORM.ru.md +20 -0
  122. package/docs/CROSS_PLATFORM.zh.md +18 -0
  123. package/docs/EXECUTION-LOOP.md +22 -7
  124. package/docs/FEATURES.md +65 -4
  125. package/docs/FEATURES.zh.md +52 -4
  126. package/docs/MIGRATION.md +2 -2
  127. package/docs/PIPELINE.md +293 -0
  128. package/docs/README.ru.md +42 -3
  129. package/docs/README.zh.md +43 -3
  130. package/docs/SAFETY.md +23 -3
  131. package/gui-experimental.cjs +9 -8
  132. package/locales/en.json +17 -1
  133. package/locales/ru.json +17 -1
  134. package/locales/zh.json +17 -1
  135. package/opencode.pipeline.yaml +35 -0
  136. package/package.json +23 -4
  137. package/scripts/test-home.mjs +83 -0
  138. package/src/cli.ts +412 -0
  139. package/src/core/dry-run.ts +2 -2
  140. package/src/core/execution.ts +538 -0
  141. package/src/core/file-watcher.ts +2 -2
  142. package/src/core/gate-integrity.ts +160 -0
  143. package/src/core/git-trigger.ts +18 -5
  144. package/src/core/guard-run.ts +119 -0
  145. package/src/core/guard.ts +431 -0
  146. package/src/core/lock.ts +178 -37
  147. package/src/core/matrix.ts +95 -50
  148. package/src/core/mission.ts +485 -0
  149. package/src/core/native-notify.ts +1 -1
  150. package/src/core/pipeline-apply.ts +158 -0
  151. package/src/core/pipeline-io.ts +79 -0
  152. package/src/core/pipeline-map.ts +264 -0
  153. package/src/core/pipeline-spec.ts +775 -0
  154. package/src/core/ps-wrapper.ts +263 -63
  155. package/src/core/record-history.ts +164 -77
  156. package/src/core/router/rules.ts +6 -0
  157. package/src/core/schedule-gate.ts +1 -1
  158. package/src/core/scheduler/at-fallback.ts +1 -1
  159. package/src/core/scheduler/linux.ts +40 -11
  160. package/src/core/scheduler/logs.ts +2 -2
  161. package/src/core/scheduler/mac.ts +174 -14
  162. package/src/core/scheduler/registry.ts +2 -2
  163. package/src/core/scheduler/windows.ts +19 -15
  164. package/src/core/secrets.ts +8 -8
  165. package/src/core/structured-log.ts +22 -5
  166. package/src/core/telegram.ts +2 -2
  167. package/src/core/triage-worker.ts +7 -7
  168. package/src/core/triage.ts +2 -2
  169. package/src/core/worktree-run.ts +199 -0
  170. package/src/core/worktree.ts +600 -0
  171. package/src/core/wrappers/bash.ts +190 -23
  172. package/src/db/capability-repo.ts +127 -10
  173. package/src/db/history-repo.ts +129 -22
  174. package/src/db/metrics-repo.ts +2 -2
  175. package/src/db/recovery.ts +5 -4
  176. package/src/db/run-journal.ts +100 -13
  177. package/src/db/run-resume.ts +17 -1
  178. package/src/db/runs-repo.ts +36 -6
  179. package/src/db/schema.ts +65 -2
  180. package/src/gui.tsx +177 -13
  181. package/src/history.ts +1 -1
  182. package/src/i18n.ts +12 -4
  183. package/src/index.ts +524 -4
  184. package/src/notifications.ts +38 -8
  185. package/src/profiles.ts +26 -4
  186. package/src/rpc.ts +128 -0
  187. package/src/server.ts +94 -18
  188. package/src/settings.ts +5 -5
  189. package/src/shared/jobs-view.ts +3 -1
  190. package/src/task-transfer.ts +31 -0
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { PLUGIN_DIR, LOCK_DIR, WRAPPER_DIR, STALE_LOCK_MAX_AGE_MS, sanitizeName } from "../types.js";
4
+ import { createGateSnapshot } from "./gate-integrity.js";
4
5
  /**
5
6
  * Путь к единому generic-обёртке PowerShell, которая реализует запуск opencode run
6
7
  * с таймаутом и lock-логикой.
@@ -28,6 +29,41 @@ const WRAPPER_FILENAME = "run-task.ps1";
28
29
  * 5. При таймауте — убивает процесс и дочерние процессы.
29
30
  * 6. В finally выполняет post-flight и удаляет lock-файл.
30
31
  */
32
+ /**
33
+ * B6: разбор PID из lock-файла для PowerShell-обёртки.
34
+ *
35
+ * Формат общий с Node: `<pid>-<iso>`. Legacy-файлы тоже читаются:
36
+ * `<iso>|<pid>` (прошлый PS) и голый `<pid>` (pid-файл bash-обёртки).
37
+ * Обратные слэши в regex удвоены — так же, как в остальном WRAPPER_SCRIPT.
38
+ */
39
+ export const PS_LOCK_PID_FUNCTION = `# B6: PID владельца lock-файла в любом формате (Node/PS/bash).
40
+ function Get-LockOwnerPid {
41
+ param([string]$Content)
42
+ $text = "$Content".Trim()
43
+ if (-not $text) { return 0 }
44
+ # Legacy PS: <iso>|<pid>. Проверяем ДО разбора по дефису, иначе год
45
+ # из ISO (2026) был бы принят за PID.
46
+ if ($text.Contains("|")) {
47
+ $parts = $text.Split([char]124)
48
+ $parsed = 0
49
+ if ($parts.Count -ge 2 -and [int]::TryParse($parts[1].Trim(), [ref]$parsed) -and $parsed -gt 0) {
50
+ return $parsed
51
+ }
52
+ return 0
53
+ }
54
+ # Голый ISO без PID (старый чужой lock) не должен давать год как PID:
55
+ # для свежего файла это означало бы вытеснение активной блокировки.
56
+ if ($text -match '^\\d{4}-\\d{2}-\\d{2}T') { return 0 }
57
+ # Единый формат <pid>-<iso> и старый Node <pid>-<epoch>-<uuid>.
58
+ if ($text -match '^(\\d+)-') { return [int]$matches[1] }
59
+ # Голый PID (pid-файл bash-обёртки).
60
+ if ($text -match '^\\d+$') {
61
+ $parsed = 0
62
+ if ([int]::TryParse($text, [ref]$parsed) -and $parsed -gt 0) { return $parsed }
63
+ return 0
64
+ }
65
+ return 0
66
+ }`;
31
67
  export const WRAPPER_SCRIPT = `param(
32
68
  [string]$TaskName,
33
69
  [string]$PromptFile,
@@ -41,12 +77,16 @@ export const WRAPPER_SCRIPT = `param(
41
77
  [string]$LogFile,
42
78
  [string]$RecorderFile,
43
79
  [string]$QualityGate,
80
+ # G-1.2: snapshot входов гейта, снятый при создании обёртки.
81
+ [string]$GateSnapshotFile = "",
44
82
  [string]$BeforeScript,
45
83
  [string]$AfterScript,
46
84
  [string]$EnvFile,
47
85
  [string]$SessionMode,
48
86
  [string]$SessionId,
49
87
  [string]$SessionFile,
88
+ # B2: параметры оставлены только для совместимости со старыми .cmd.
89
+ # Ретраи принадлежат recorder'у — обёртка делает ровно одну попытку.
50
90
  [int]$RetryCount = 0,
51
91
  [int]$RetryDelaySeconds = 0,
52
92
  [int]$GateTimeoutSeconds = 300,
@@ -107,6 +147,8 @@ function Test-ProcessAlive {
107
147
  }
108
148
  }
109
149
 
150
+ ${PS_LOCK_PID_FUNCTION}
151
+
110
152
  # Гарантируем существование папки для лога (на случай прямого вызова обёртки).
111
153
  if ($LogFile) {
112
154
  try {
@@ -143,9 +185,9 @@ if ($LockFile) {
143
185
  }
144
186
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
145
187
  try {
146
- # Внутри lock храним время старта и PID владельца: по PID можно
147
- # отличить живой долгий запуск от осиротевшего после kill -9.
148
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
188
+ # B6: единый формат <pid>-<iso> — его читают Node и bash.
189
+ # По PID отличаем живой долгий запуск от осиротевшего после kill -9.
190
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
149
191
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
150
192
  } finally {
151
193
  $lockStream.Dispose()
@@ -158,10 +200,9 @@ if ($LockFile) {
158
200
  $holderPid = 0
159
201
  try {
160
202
  $holderRaw = "$(Get-Content -LiteralPath $LockFile -Raw -ErrorAction Stop)".Trim()
161
- $holderParts = $holderRaw.Split([char]124)
162
- if ($holderParts.Count -ge 2) {
163
- [void][int]::TryParse($holderParts[1], [ref]$holderPid)
164
- }
203
+ # B6: понимаем и новый <pid>-<iso>, и legacy <iso>|<pid>,
204
+ # и голый PID — иначе живой чужой lock вытеснялся по возрасту.
205
+ $holderPid = Get-LockOwnerPid -Content $holderRaw
165
206
  } catch {}
166
207
  if ($holderPid -gt 0) {
167
208
  $stale = -not (Test-ProcessAlive -ProcessId $holderPid)
@@ -186,7 +227,7 @@ if ($LockFile) {
186
227
  try {
187
228
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
188
229
  try {
189
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
230
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
190
231
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
191
232
  } finally {
192
233
  $lockStream.Dispose()
@@ -295,6 +336,10 @@ function Invoke-HookScript {
295
336
  # до конца, а статус 'timeout' не выставлялся никогда. Теперь параллельно
296
337
  # стартует сторожевой job: по истечении лимита он помечает маркер и убивает
297
338
  # дерево процессов задачи (taskkill /T), а обёртка переводит статус в 'timeout'.
339
+ # B8: снимок дерева процессов. CIM — основной источник; при его сбое
340
+ # пробуем старый WMI, а если и он недоступен — Get-Process/tasklist.
341
+ # Иерархию Get-Process и tasklist не отдают, поэтому при отсутствии данных
342
+ # сторож переходит в fail-closed и убивает дерево по корневому PID.
298
343
  function Invoke-OpenCodeOnce {
299
344
  param([string]$CommandPath, [string[]]$Arguments)
300
345
 
@@ -307,19 +352,25 @@ function Invoke-OpenCodeOnce {
307
352
  Start-Sleep -Seconds $Seconds
308
353
  $selfId = $PID
309
354
  $all = @()
310
- try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId) } catch { $all = @() }
355
+ try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
356
+ if ($all.Count -eq 0) {
357
+ try { $all = @(Get-WmiObject Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
358
+ }
359
+ $dataAvailable = $all.Count -gt 0
311
360
  $targets = New-Object System.Collections.Generic.List[int]
312
- $queue = New-Object System.Collections.Generic.Queue[int]
313
- $queue.Enqueue($RootId)
314
- $guard = 0
315
- while ($queue.Count -gt 0 -and $guard -lt 2000) {
316
- $guard++
317
- $current = $queue.Dequeue()
318
- foreach ($p in $all) {
319
- $childId = [int]$p.ProcessId
320
- if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
321
- $targets.Add($childId)
322
- $queue.Enqueue($childId)
361
+ if ($dataAvailable) {
362
+ $queue = New-Object System.Collections.Generic.Queue[int]
363
+ $queue.Enqueue($RootId)
364
+ $guard = 0
365
+ while ($queue.Count -gt 0 -and $guard -lt 2000) {
366
+ $guard++
367
+ $current = $queue.Dequeue()
368
+ foreach ($p in $all) {
369
+ $childId = [int]$p.ProcessId
370
+ if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
371
+ $targets.Add($childId)
372
+ $queue.Enqueue($childId)
373
+ }
323
374
  }
324
375
  }
325
376
  }
@@ -328,6 +379,27 @@ function Invoke-OpenCodeOnce {
328
379
  foreach ($targetId in @($targets)) {
329
380
  try { & taskkill.exe /F /T /PID $targetId 2>$null | Out-Null } catch {}
330
381
  }
382
+ } elseif (-not $dataAvailable) {
383
+ # Fail-closed: дерево построить нельзя (CIM/WMI упали, Get-Process
384
+ # и tasklist не дают родительских связей). Помечаем таймаут и
385
+ # убиваем всё дерево от корня, иначе задача переживёт лимит.
386
+ try { Set-Content -Path $Marker -Value "timeout" -Encoding UTF8 } catch {}
387
+ $listing = $false
388
+ try {
389
+ if (@(tasklist.exe /FO CSV /NH 2>$null).Count -gt 0) { $listing = $true }
390
+ } catch {}
391
+ if (-not $listing) {
392
+ try {
393
+ if (@(Get-Process -ErrorAction Stop).Count -gt 0) { $listing = $true }
394
+ } catch {}
395
+ }
396
+ try {
397
+ Start-Process -FilePath "taskkill.exe" -ArgumentList @("/F", "/T", "/PID", [string]$RootId) -WindowStyle Hidden -ErrorAction Stop
398
+ } catch {
399
+ if ($listing) {
400
+ try { & taskkill.exe /F /T /PID $RootId 2>$null | Out-Null } catch {}
401
+ }
402
+ }
331
403
  }
332
404
  } -ArgumentList $PID, $TimeoutSeconds, $timeoutMarker
333
405
  }
@@ -635,6 +707,14 @@ try {
635
707
  if (-not $script:skipMainTask) {
636
708
  $prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
637
709
 
710
+ # W-1: запуск в одноразовом git worktree — сообщаем путь агенту.
711
+ # Переменную выставляет .cmd-обёртка после успешного создания копии.
712
+ if ($env:AGENT_STEWARD_WORKTREE) {
713
+ Write-Log "[agent-steward] Git worktree: $env:AGENT_STEWARD_WORKTREE (repo: $env:AGENT_STEWARD_WORKTREE_REPO)"
714
+ $worktreeContext = "[agent-steward] Рабочая директория запуска - одноразовый git worktree: " + $env:AGENT_STEWARD_WORKTREE + [Environment]::NewLine
715
+ $prompt = $worktreeContext + $prompt
716
+ }
717
+
638
718
  # CreateProcess ограничивает командную строку 32767 символами, а промпт
639
719
  # передаётся opencode аргументом ($opencodeArgs += $prompt). Явная ошибка
640
720
  # понятнее, чем обрезанный/отвергнутый запуск. Основная валидация — в schedule_task.
@@ -696,50 +776,66 @@ try {
696
776
  $opencodeArgs += @("--continue")
697
777
  }
698
778
  if ($prompt) {
699
- $opencodeArgs += $prompt
779
+ # B11.1: «--» завершает разбор флагов opencode. Без него промпт,
780
+ # начинающийся с «-», CLI принял бы за неизвестный флаг.
781
+ $opencodeArgs += @("--", $prompt)
700
782
  }
701
783
 
702
784
  # Запускаем opencode и НАПРЯМУЮ направляем весь вывод (stdout + stderr) в лог.
703
785
  # Out-File -Append -Encoding utf8 пишет по мере поступления строк, поэтому
704
786
  # ответ ИИ появляется в GUI ещё до завершения задачи.
705
- # Hotfix 1.5.3.1: retryCount из схемы раньше нигде не применялся — теперь
706
- # неудачная попытка повторяется до RetryCount раз с паузой RetryDelaySeconds.
707
- $maxAttempts = 1 + [Math]::Max(0, $RetryCount)
708
- $attempt = 0
709
- while ($attempt -lt $maxAttempts) {
710
- $attempt++
711
- if ($attempt -gt 1) {
712
- $waitSeconds = [Math]::Max(0, $RetryDelaySeconds)
713
- Write-Log "[agent-steward] Повтор $($attempt - 1) из $($maxAttempts - 1) через $waitSeconds с..."
714
- if ($waitSeconds -gt 0) { Start-Sleep -Seconds $waitSeconds }
715
- $script:errorMessage = ""
716
- }
717
- $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
718
- if ($script:exitCode -eq 0) { break }
719
- # Таймаут повторять бессмысленно: каждая попытка снова съест весь лимит.
720
- if ($script:timedOut) { break }
721
- if ($attempt -lt $maxAttempts) {
722
- Write-Log "[agent-steward] Попытка $attempt завершилась с кодом $($script:exitCode)."
723
- }
724
- }
787
+ # B2: обёртка делает РОВНО одну попытку. Повторы — зона recorder'а
788
+ # (retryCount/retryDelay в БД), иначе на Windows получалось (1+N)^2
789
+ # запусков: N попыток внутри обёртки × N+1 запуск из recorder'а.
790
+ # Параметры -RetryCount/-RetryDelaySeconds принимаются, но игнорируются.
791
+ $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
725
792
 
726
793
  # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
727
794
  # завершения opencode run. Если ИИ упал — шлюз не запускаем.
728
795
  if ($QualityGate -and $script:exitCode -eq 0) {
729
- Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
730
- # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
731
- $gateCode = Invoke-HookScript -Command $QualityGate
732
-
733
- if ($gateCode -eq 124) {
734
- Write-Log "[agent-steward] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
735
- $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
736
- $script:exitCode = 1
737
- } elseif ($gateCode -ne 0) {
738
- Write-Log "[agent-steward] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
739
- $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
740
- $script:exitCode = 1
796
+ # G-1.2: перед запуском гейта сверяем его входы со snapshot'ом,
797
+ # снятым при создании задачи. При расхождении гейт НЕ выполняется.
798
+ $gateIntegrityOk = $false
799
+ if ($GateSnapshotFile -and (Test-Path -LiteralPath $GateSnapshotFile)) {
800
+ $gateIntegrityFile = Join-Path (Split-Path $RecorderFile -Parent) "gate-integrity.js"
801
+ if (Test-Path -LiteralPath $gateIntegrityFile) {
802
+ $verifyOutput = & node $gateIntegrityFile verify --snapshot "$GateSnapshotFile" --gate-file "$QualityGate" --prompt-file "$PromptFile" --timeout $GateTimeoutSeconds 2>&1
803
+ $verifyCode = $LASTEXITCODE
804
+ foreach ($line in $verifyOutput) { Write-Log "[agent-steward] $line" }
805
+ if ($verifyCode -eq 0) {
806
+ $gateIntegrityOk = $true
807
+ } else {
808
+ Write-Log "[agent-steward] ОШИБКА: целостность входов Quality Gate нарушена (snapshot mismatch)."
809
+ $script:errorMessage = "Quality Gate: целостность входов нарушена (snapshot mismatch)"
810
+ $script:exitCode = 1
811
+ }
812
+ } else {
813
+ Write-Log "[agent-steward] ОШИБКА: не найден помощник проверки целостности гейта."
814
+ $script:errorMessage = "Quality Gate: помощник проверки целостности не найден"
815
+ $script:exitCode = 1
816
+ }
741
817
  } else {
742
- Write-Log "[agent-steward] Quality Gate пройден."
818
+ Write-Log "[agent-steward] ОШИБКА: snapshot гейта отсутствует — запуск с гейтом невозможен."
819
+ $script:errorMessage = "Quality Gate: snapshot входов отсутствует"
820
+ $script:exitCode = 1
821
+ }
822
+
823
+ if ($gateIntegrityOk) {
824
+ Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
825
+ # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
826
+ $gateCode = Invoke-HookScript -Command $QualityGate
827
+
828
+ if ($gateCode -eq 124) {
829
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
830
+ $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
831
+ $script:exitCode = 1
832
+ } elseif ($gateCode -ne 0) {
833
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
834
+ $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
835
+ $script:exitCode = 1
836
+ } else {
837
+ Write-Log "[agent-steward] Quality Gate пройден."
838
+ }
743
839
  }
744
840
  }
745
841
 
@@ -898,7 +994,15 @@ async function writeHookFile(sanitizedName, kind, command) {
898
994
  await fs.writeFile(file, `@echo off\r\nchcp 65001 >nul\r\n${command}\r\n`, "utf8");
899
995
  return file;
900
996
  }
901
- 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) {
997
+ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeoutSeconds, lockFile, workdir, logFile, recorderFile, qualityGate, model, beforeScript, afterScript, workspaceName, allowedTools, deniedTools, scheduleGate, envFile, sessionMode, sessionId, gateTimeoutSeconds, permissionsConfig, policyMeta, sessionFile,
998
+ /** W-1: запустить задачу в одноразовом git worktree. */
999
+ worktree,
1000
+ /** Путь к dist/core/worktree-run.js (обязателен при worktree=true). */
1001
+ worktreeHelperFile,
1002
+ /** W-3: guard-условия перед запуском opencode. */
1003
+ guards,
1004
+ /** Путь к dist/core/guard-run.js (обязателен при guards). */
1005
+ guardHelperFile) {
902
1006
  await fs.mkdir(WRAPPER_DIR, { recursive: true });
903
1007
  const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
904
1008
  const ps1Path = path.join(WRAPPER_DIR, WRAPPER_FILENAME);
@@ -919,13 +1023,10 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
919
1023
  ? Math.max(0, Math.floor(gateTimeoutSeconds))
920
1024
  : 300;
921
1025
  psArgs.push(`-GateTimeoutSeconds ${safeGateTimeout}`);
922
- // Hotfix 1.5.3.1: ретраи. Параметр не передаём при 0 — обёртка по умолчанию
923
- // делает ровно одну попытку, как раньше.
924
- const safeRetryCount = Math.max(0, Math.floor(retryCount ?? 0));
925
- if (safeRetryCount > 0) {
926
- psArgs.push(`-RetryCount ${safeRetryCount}`);
927
- psArgs.push(`-RetryDelaySeconds ${Math.max(0, Math.floor(retryDelaySeconds ?? 0))}`);
928
- }
1026
+ // B2: ретраи сознательно не передаются в обёртку — единственный владелец
1027
+ // повторов это recorder (retryCount/retryDelay), иначе на Windows получается
1028
+ // (1+N)^2 запусков. Старые .cmd с -RetryCount продолжают работать: параметр
1029
+ // принимается, но игнорируется.
929
1030
  if (logFile) {
930
1031
  psArgs.push(`-LogFile "${logFile}"`);
931
1032
  }
@@ -937,6 +1038,28 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
937
1038
  // внутри неё больше не ломают однострочный вызов powershell.exe.
938
1039
  const gateFile = await writeHookFile(sanitizedName, "gate", qualityGate);
939
1040
  psArgs.push(`-QualityGate "${gateFile}"`);
1041
+ // G-1.2: фиксируем входы гейта до первого запуска. Snapshot лежит в
1042
+ // PLUGIN_DIR, вне рабочей директории задачи.
1043
+ let prompt = "";
1044
+ let hook = qualityGate;
1045
+ try {
1046
+ prompt = await fs.readFile(promptFile, "utf8");
1047
+ }
1048
+ catch {
1049
+ // Промпт мог быть уже удалён — уникальность snapshot от этого не страдает.
1050
+ }
1051
+ try {
1052
+ hook = await fs.readFile(gateFile, "utf8");
1053
+ }
1054
+ catch {
1055
+ // Используем исходную команду, если прочитать хук не удалось.
1056
+ }
1057
+ const snapshotFile = createGateSnapshot(taskName, {
1058
+ gate: hook,
1059
+ prompt,
1060
+ gateTimeoutSeconds: safeGateTimeout,
1061
+ });
1062
+ psArgs.push(`-GateSnapshotFile "${snapshotFile}"`);
940
1063
  }
941
1064
  if (model?.trim()) {
942
1065
  const safeModel = model.replace(/[\r\n"]+/g, "").trim();
@@ -1056,7 +1179,72 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
1056
1179
  lines.push(gateArgs.join(" "));
1057
1180
  lines.push("if \"%errorlevel%\"==\"3\" exit /b 0");
1058
1181
  }
1182
+ // W-1 (0.0.6): одноразовый git worktree. Создаётся после гейта расписания,
1183
+ // чтобы пропущенный тик не плодил рабочие копии. Ошибка создания — fail-closed:
1184
+ // задача не должна молча работать в основном дереве.
1185
+ let wtHelper = "";
1186
+ let wtRepo = "";
1187
+ let wtLogRedirect = "";
1188
+ if (worktree) {
1189
+ wtHelper = (worktreeHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1190
+ wtRepo = effectiveWorkdir.replace(/[\r\n"]+/g, "").trim();
1191
+ const safeTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1192
+ wtLogRedirect = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1193
+ const helperErr = logFile?.trim() ? `2>> "${logFile.trim()}"` : "";
1194
+ lines.push('set "AGENT_STEWARD_WORKTREE="');
1195
+ lines.push(`for /f "usebackq delims=" %%W in (\`node "${wtHelper}" --repo "${wtRepo}" --task "${safeTaskName}" ${helperErr}\`) do set "AGENT_STEWARD_WORKTREE=%%W"`);
1196
+ lines.push("if not defined AGENT_STEWARD_WORKTREE (");
1197
+ lines.push(` echo [agent-steward] ERROR: git worktree creation failed ${wtLogRedirect}`);
1198
+ lines.push(" exit /b 1");
1199
+ lines.push(")");
1200
+ lines.push('cd /d "%AGENT_STEWARD_WORKTREE%"');
1201
+ lines.push(`set "AGENT_STEWARD_WORKTREE_REPO=${wtRepo}"`);
1202
+ }
1203
+ // W-3 (0.0.6): guard-условия до запуска opencode. Код 4 — штатный skip,
1204
+ // любой другой ненулевой код — ошибка проверки; в обоих случаях opencode
1205
+ // не запускается. Созданный worktree сразу убираем, чтобы не оставлять мусор.
1206
+ if (guards) {
1207
+ const guardHelper = (guardHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1208
+ const guardB64 = Buffer.from(JSON.stringify(guards), "utf8").toString("base64");
1209
+ const skipTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1210
+ const skipRecorder = (recorderFile ?? "").replace(/[\r\n"]+/g, "").trim();
1211
+ const skipReasonB64 = Buffer.from("guard conditions not met", "utf8").toString("base64");
1212
+ const guardLog = logFile?.trim() ? `1>> "${logFile.trim()}" 2>&1` : "";
1213
+ const guardLogAppend = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1214
+ const pushWorktreeCleanup = () => {
1215
+ if (!worktree)
1216
+ return;
1217
+ lines.push(` cd /d "${wtRepo}"`);
1218
+ lines.push(` node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`);
1219
+ };
1220
+ lines.push(`node "${guardHelper}" --cwd "%CD%" --guards-b64 "${guardB64}" ${guardLog}`);
1221
+ lines.push('set "AGENT_STEWARD_GUARD_STATUS=%errorlevel%"');
1222
+ lines.push('if "%AGENT_STEWARD_GUARD_STATUS%"=="4" (');
1223
+ lines.push(` echo [agent-steward] guard: run skipped ${guardLogAppend}`);
1224
+ // W-4: пишем skipped в историю/метрики. Причина фиксированная (в базе),
1225
+ // подробности guard-проверки остаются в логе задачи.
1226
+ if (skipRecorder) {
1227
+ lines.push(` node "${skipRecorder}" --skip "${skipTaskName}" "${skipReasonB64}" ${guardLogAppend}`);
1228
+ }
1229
+ pushWorktreeCleanup();
1230
+ lines.push(" exit /b 0");
1231
+ lines.push(")");
1232
+ lines.push('if not "%AGENT_STEWARD_GUARD_STATUS%"=="0" (');
1233
+ lines.push(` echo [agent-steward] ERROR: guard failed with code %AGENT_STEWARD_GUARD_STATUS% ${guardLogAppend}`);
1234
+ pushWorktreeCleanup();
1235
+ lines.push(" exit /b 1");
1236
+ lines.push(")");
1237
+ }
1059
1238
  lines.push(psArgs.join(" "));
1239
+ // W-2.1: удаляем одноразовый worktree после прогона при любом коде возврата.
1240
+ // Сначала выходим из него (Windows не даёт удалить текущий каталог), затем
1241
+ // возвращаем исходный код задачи — ошибка очистки не маскирует результат.
1242
+ if (worktree) {
1243
+ lines.push('set "AGENT_STEWARD_EXIT_CODE=%errorlevel%"');
1244
+ lines.push(`cd /d "${wtRepo}"`);
1245
+ lines.push(`node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`);
1246
+ lines.push("exit /b %AGENT_STEWARD_EXIT_CODE%");
1247
+ }
1060
1248
  await fs.writeFile(cmdPath, lines.join("\r\n"), "utf8");
1061
1249
  return cmdPath;
1062
1250
  }
@@ -1 +1 @@
1
- {"version":3,"file":"record-history.d.ts","sourceRoot":"","sources":["../../src/core/record-history.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAiCnD,MAAM,WAAW,SAAS;IACxB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAwBD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAmC5D;AA6GD;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CACvC,aAAa,EAAE,MAAM,EACrB,WAAW,EAAE,cAAc,EAAE,EAC7B,OAAO,EAAE,aAAa,EAAE,GACvB,MAAM,EAAE,CA0EV;AAiLD,4DAA4D;AAC5D,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;IAC3B,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,cAAc,GAAG,SAAS,CAAC;IAC7D,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9C;AAED;;;;;;;GAOG;AACH,wBAAsB,yBAAyB,CAC7C,QAAQ,EAAE,MAAM,EAChB,IAAI,GAAE,kBAAuB,GAC5B,OAAO,CAAC,OAAO,CAAC,CAyBlB"}
1
+ {"version":3,"file":"record-history.d.ts","sourceRoot":"","sources":["../../src/core/record-history.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AA8DnD,MAAM,WAAW,SAAS;IACxB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAwBD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAmC5D;AAuGD;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CACvC,aAAa,EAAE,MAAM,EACrB,WAAW,EAAE,cAAc,EAAE,EAC7B,OAAO,EAAE,aAAa,EAAE,GACvB,MAAM,EAAE,CA0EV;AA0PD,4DAA4D;AAC5D,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC;IAC3B,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,cAAc,GAAG,SAAS,CAAC;IAC7D,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9C;AAED;;;;;;;GAOG;AACH,wBAAsB,yBAAyB,CAC7C,QAAQ,EAAE,MAAM,EAChB,IAAI,GAAE,kBAAuB,GAC5B,OAAO,CAAC,OAAO,CAAC,CAqBlB"}