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
@@ -2,6 +2,8 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { PLUGIN_DIR, LOG_DIR, LOCK_DIR, WRAPPER_DIR, STALE_LOCK_MAX_AGE_MS, sanitizeName } from "../types.js";
4
4
  import type { ScheduleGateSpec } from "./schedule-v2.js";
5
+ import type { TaskGuards } from "./guard.js";
6
+ import { createGateSnapshot } from "./gate-integrity.js";
5
7
 
6
8
  /**
7
9
  * Путь к единому generic-обёртке PowerShell, которая реализует запуск opencode run
@@ -31,6 +33,43 @@ const WRAPPER_FILENAME = "run-task.ps1";
31
33
  * 5. При таймауте — убивает процесс и дочерние процессы.
32
34
  * 6. В finally выполняет post-flight и удаляет lock-файл.
33
35
  */
36
+
37
+ /**
38
+ * B6: разбор PID из lock-файла для PowerShell-обёртки.
39
+ *
40
+ * Формат общий с Node: `<pid>-<iso>`. Legacy-файлы тоже читаются:
41
+ * `<iso>|<pid>` (прошлый PS) и голый `<pid>` (pid-файл bash-обёртки).
42
+ * Обратные слэши в regex удвоены — так же, как в остальном WRAPPER_SCRIPT.
43
+ */
44
+ export const PS_LOCK_PID_FUNCTION = `# B6: PID владельца lock-файла в любом формате (Node/PS/bash).
45
+ function Get-LockOwnerPid {
46
+ param([string]$Content)
47
+ $text = "$Content".Trim()
48
+ if (-not $text) { return 0 }
49
+ # Legacy PS: <iso>|<pid>. Проверяем ДО разбора по дефису, иначе год
50
+ # из ISO (2026) был бы принят за PID.
51
+ if ($text.Contains("|")) {
52
+ $parts = $text.Split([char]124)
53
+ $parsed = 0
54
+ if ($parts.Count -ge 2 -and [int]::TryParse($parts[1].Trim(), [ref]$parsed) -and $parsed -gt 0) {
55
+ return $parsed
56
+ }
57
+ return 0
58
+ }
59
+ # Голый ISO без PID (старый чужой lock) не должен давать год как PID:
60
+ # для свежего файла это означало бы вытеснение активной блокировки.
61
+ if ($text -match '^\\d{4}-\\d{2}-\\d{2}T') { return 0 }
62
+ # Единый формат <pid>-<iso> и старый Node <pid>-<epoch>-<uuid>.
63
+ if ($text -match '^(\\d+)-') { return [int]$matches[1] }
64
+ # Голый PID (pid-файл bash-обёртки).
65
+ if ($text -match '^\\d+$') {
66
+ $parsed = 0
67
+ if ([int]::TryParse($text, [ref]$parsed) -and $parsed -gt 0) { return $parsed }
68
+ return 0
69
+ }
70
+ return 0
71
+ }`;
72
+
34
73
  export const WRAPPER_SCRIPT = `param(
35
74
  [string]$TaskName,
36
75
  [string]$PromptFile,
@@ -44,12 +83,16 @@ export const WRAPPER_SCRIPT = `param(
44
83
  [string]$LogFile,
45
84
  [string]$RecorderFile,
46
85
  [string]$QualityGate,
86
+ # G-1.2: snapshot входов гейта, снятый при создании обёртки.
87
+ [string]$GateSnapshotFile = "",
47
88
  [string]$BeforeScript,
48
89
  [string]$AfterScript,
49
90
  [string]$EnvFile,
50
91
  [string]$SessionMode,
51
92
  [string]$SessionId,
52
93
  [string]$SessionFile,
94
+ # B2: параметры оставлены только для совместимости со старыми .cmd.
95
+ # Ретраи принадлежат recorder'у — обёртка делает ровно одну попытку.
53
96
  [int]$RetryCount = 0,
54
97
  [int]$RetryDelaySeconds = 0,
55
98
  [int]$GateTimeoutSeconds = 300,
@@ -110,6 +153,8 @@ function Test-ProcessAlive {
110
153
  }
111
154
  }
112
155
 
156
+ ${PS_LOCK_PID_FUNCTION}
157
+
113
158
  # Гарантируем существование папки для лога (на случай прямого вызова обёртки).
114
159
  if ($LogFile) {
115
160
  try {
@@ -146,9 +191,9 @@ if ($LockFile) {
146
191
  }
147
192
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
148
193
  try {
149
- # Внутри lock храним время старта и PID владельца: по PID можно
150
- # отличить живой долгий запуск от осиротевшего после kill -9.
151
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
194
+ # B6: единый формат <pid>-<iso> — его читают Node и bash.
195
+ # По PID отличаем живой долгий запуск от осиротевшего после kill -9.
196
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
152
197
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
153
198
  } finally {
154
199
  $lockStream.Dispose()
@@ -161,10 +206,9 @@ if ($LockFile) {
161
206
  $holderPid = 0
162
207
  try {
163
208
  $holderRaw = "$(Get-Content -LiteralPath $LockFile -Raw -ErrorAction Stop)".Trim()
164
- $holderParts = $holderRaw.Split([char]124)
165
- if ($holderParts.Count -ge 2) {
166
- [void][int]::TryParse($holderParts[1], [ref]$holderPid)
167
- }
209
+ # B6: понимаем и новый <pid>-<iso>, и legacy <iso>|<pid>,
210
+ # и голый PID — иначе живой чужой lock вытеснялся по возрасту.
211
+ $holderPid = Get-LockOwnerPid -Content $holderRaw
168
212
  } catch {}
169
213
  if ($holderPid -gt 0) {
170
214
  $stale = -not (Test-ProcessAlive -ProcessId $holderPid)
@@ -189,7 +233,7 @@ if ($LockFile) {
189
233
  try {
190
234
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
191
235
  try {
192
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
236
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
193
237
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
194
238
  } finally {
195
239
  $lockStream.Dispose()
@@ -298,6 +342,10 @@ function Invoke-HookScript {
298
342
  # до конца, а статус 'timeout' не выставлялся никогда. Теперь параллельно
299
343
  # стартует сторожевой job: по истечении лимита он помечает маркер и убивает
300
344
  # дерево процессов задачи (taskkill /T), а обёртка переводит статус в 'timeout'.
345
+ # B8: снимок дерева процессов. CIM — основной источник; при его сбое
346
+ # пробуем старый WMI, а если и он недоступен — Get-Process/tasklist.
347
+ # Иерархию Get-Process и tasklist не отдают, поэтому при отсутствии данных
348
+ # сторож переходит в fail-closed и убивает дерево по корневому PID.
301
349
  function Invoke-OpenCodeOnce {
302
350
  param([string]$CommandPath, [string[]]$Arguments)
303
351
 
@@ -310,19 +358,25 @@ function Invoke-OpenCodeOnce {
310
358
  Start-Sleep -Seconds $Seconds
311
359
  $selfId = $PID
312
360
  $all = @()
313
- try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId) } catch { $all = @() }
361
+ try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
362
+ if ($all.Count -eq 0) {
363
+ try { $all = @(Get-WmiObject Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
364
+ }
365
+ $dataAvailable = $all.Count -gt 0
314
366
  $targets = New-Object System.Collections.Generic.List[int]
315
- $queue = New-Object System.Collections.Generic.Queue[int]
316
- $queue.Enqueue($RootId)
317
- $guard = 0
318
- while ($queue.Count -gt 0 -and $guard -lt 2000) {
319
- $guard++
320
- $current = $queue.Dequeue()
321
- foreach ($p in $all) {
322
- $childId = [int]$p.ProcessId
323
- if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
324
- $targets.Add($childId)
325
- $queue.Enqueue($childId)
367
+ if ($dataAvailable) {
368
+ $queue = New-Object System.Collections.Generic.Queue[int]
369
+ $queue.Enqueue($RootId)
370
+ $guard = 0
371
+ while ($queue.Count -gt 0 -and $guard -lt 2000) {
372
+ $guard++
373
+ $current = $queue.Dequeue()
374
+ foreach ($p in $all) {
375
+ $childId = [int]$p.ProcessId
376
+ if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
377
+ $targets.Add($childId)
378
+ $queue.Enqueue($childId)
379
+ }
326
380
  }
327
381
  }
328
382
  }
@@ -331,6 +385,27 @@ function Invoke-OpenCodeOnce {
331
385
  foreach ($targetId in @($targets)) {
332
386
  try { & taskkill.exe /F /T /PID $targetId 2>$null | Out-Null } catch {}
333
387
  }
388
+ } elseif (-not $dataAvailable) {
389
+ # Fail-closed: дерево построить нельзя (CIM/WMI упали, Get-Process
390
+ # и tasklist не дают родительских связей). Помечаем таймаут и
391
+ # убиваем всё дерево от корня, иначе задача переживёт лимит.
392
+ try { Set-Content -Path $Marker -Value "timeout" -Encoding UTF8 } catch {}
393
+ $listing = $false
394
+ try {
395
+ if (@(tasklist.exe /FO CSV /NH 2>$null).Count -gt 0) { $listing = $true }
396
+ } catch {}
397
+ if (-not $listing) {
398
+ try {
399
+ if (@(Get-Process -ErrorAction Stop).Count -gt 0) { $listing = $true }
400
+ } catch {}
401
+ }
402
+ try {
403
+ Start-Process -FilePath "taskkill.exe" -ArgumentList @("/F", "/T", "/PID", [string]$RootId) -WindowStyle Hidden -ErrorAction Stop
404
+ } catch {
405
+ if ($listing) {
406
+ try { & taskkill.exe /F /T /PID $RootId 2>$null | Out-Null } catch {}
407
+ }
408
+ }
334
409
  }
335
410
  } -ArgumentList $PID, $TimeoutSeconds, $timeoutMarker
336
411
  }
@@ -638,6 +713,14 @@ try {
638
713
  if (-not $script:skipMainTask) {
639
714
  $prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
640
715
 
716
+ # W-1: запуск в одноразовом git worktree — сообщаем путь агенту.
717
+ # Переменную выставляет .cmd-обёртка после успешного создания копии.
718
+ if ($env:AGENT_STEWARD_WORKTREE) {
719
+ Write-Log "[agent-steward] Git worktree: $env:AGENT_STEWARD_WORKTREE (repo: $env:AGENT_STEWARD_WORKTREE_REPO)"
720
+ $worktreeContext = "[agent-steward] Рабочая директория запуска - одноразовый git worktree: " + $env:AGENT_STEWARD_WORKTREE + [Environment]::NewLine
721
+ $prompt = $worktreeContext + $prompt
722
+ }
723
+
641
724
  # CreateProcess ограничивает командную строку 32767 символами, а промпт
642
725
  # передаётся opencode аргументом ($opencodeArgs += $prompt). Явная ошибка
643
726
  # понятнее, чем обрезанный/отвергнутый запуск. Основная валидация — в schedule_task.
@@ -699,50 +782,66 @@ try {
699
782
  $opencodeArgs += @("--continue")
700
783
  }
701
784
  if ($prompt) {
702
- $opencodeArgs += $prompt
785
+ # B11.1: «--» завершает разбор флагов opencode. Без него промпт,
786
+ # начинающийся с «-», CLI принял бы за неизвестный флаг.
787
+ $opencodeArgs += @("--", $prompt)
703
788
  }
704
789
 
705
790
  # Запускаем opencode и НАПРЯМУЮ направляем весь вывод (stdout + stderr) в лог.
706
791
  # Out-File -Append -Encoding utf8 пишет по мере поступления строк, поэтому
707
792
  # ответ ИИ появляется в GUI ещё до завершения задачи.
708
- # Hotfix 1.5.3.1: retryCount из схемы раньше нигде не применялся — теперь
709
- # неудачная попытка повторяется до RetryCount раз с паузой RetryDelaySeconds.
710
- $maxAttempts = 1 + [Math]::Max(0, $RetryCount)
711
- $attempt = 0
712
- while ($attempt -lt $maxAttempts) {
713
- $attempt++
714
- if ($attempt -gt 1) {
715
- $waitSeconds = [Math]::Max(0, $RetryDelaySeconds)
716
- Write-Log "[agent-steward] Повтор $($attempt - 1) из $($maxAttempts - 1) через $waitSeconds с..."
717
- if ($waitSeconds -gt 0) { Start-Sleep -Seconds $waitSeconds }
718
- $script:errorMessage = ""
719
- }
720
- $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
721
- if ($script:exitCode -eq 0) { break }
722
- # Таймаут повторять бессмысленно: каждая попытка снова съест весь лимит.
723
- if ($script:timedOut) { break }
724
- if ($attempt -lt $maxAttempts) {
725
- Write-Log "[agent-steward] Попытка $attempt завершилась с кодом $($script:exitCode)."
726
- }
727
- }
793
+ # B2: обёртка делает РОВНО одну попытку. Повторы — зона recorder'а
794
+ # (retryCount/retryDelay в БД), иначе на Windows получалось (1+N)^2
795
+ # запусков: N попыток внутри обёртки × N+1 запуск из recorder'а.
796
+ # Параметры -RetryCount/-RetryDelaySeconds принимаются, но игнорируются.
797
+ $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
728
798
 
729
799
  # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
730
800
  # завершения opencode run. Если ИИ упал — шлюз не запускаем.
731
801
  if ($QualityGate -and $script:exitCode -eq 0) {
732
- Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
733
- # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
734
- $gateCode = Invoke-HookScript -Command $QualityGate
735
-
736
- if ($gateCode -eq 124) {
737
- Write-Log "[agent-steward] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
738
- $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
739
- $script:exitCode = 1
740
- } elseif ($gateCode -ne 0) {
741
- Write-Log "[agent-steward] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
742
- $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
743
- $script:exitCode = 1
802
+ # G-1.2: перед запуском гейта сверяем его входы со snapshot'ом,
803
+ # снятым при создании задачи. При расхождении гейт НЕ выполняется.
804
+ $gateIntegrityOk = $false
805
+ if ($GateSnapshotFile -and (Test-Path -LiteralPath $GateSnapshotFile)) {
806
+ $gateIntegrityFile = Join-Path (Split-Path $RecorderFile -Parent) "gate-integrity.js"
807
+ if (Test-Path -LiteralPath $gateIntegrityFile) {
808
+ $verifyOutput = & node $gateIntegrityFile verify --snapshot "$GateSnapshotFile" --gate-file "$QualityGate" --prompt-file "$PromptFile" --timeout $GateTimeoutSeconds 2>&1
809
+ $verifyCode = $LASTEXITCODE
810
+ foreach ($line in $verifyOutput) { Write-Log "[agent-steward] $line" }
811
+ if ($verifyCode -eq 0) {
812
+ $gateIntegrityOk = $true
813
+ } else {
814
+ Write-Log "[agent-steward] ОШИБКА: целостность входов Quality Gate нарушена (snapshot mismatch)."
815
+ $script:errorMessage = "Quality Gate: целостность входов нарушена (snapshot mismatch)"
816
+ $script:exitCode = 1
817
+ }
818
+ } else {
819
+ Write-Log "[agent-steward] ОШИБКА: не найден помощник проверки целостности гейта."
820
+ $script:errorMessage = "Quality Gate: помощник проверки целостности не найден"
821
+ $script:exitCode = 1
822
+ }
744
823
  } else {
745
- Write-Log "[agent-steward] Quality Gate пройден."
824
+ Write-Log "[agent-steward] ОШИБКА: snapshot гейта отсутствует — запуск с гейтом невозможен."
825
+ $script:errorMessage = "Quality Gate: snapshot входов отсутствует"
826
+ $script:exitCode = 1
827
+ }
828
+
829
+ if ($gateIntegrityOk) {
830
+ Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
831
+ # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
832
+ $gateCode = Invoke-HookScript -Command $QualityGate
833
+
834
+ if ($gateCode -eq 124) {
835
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
836
+ $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
837
+ $script:exitCode = 1
838
+ } elseif ($gateCode -ne 0) {
839
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
840
+ $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
841
+ $script:exitCode = 1
842
+ } else {
843
+ Write-Log "[agent-steward] Quality Gate пройден."
844
+ }
746
845
  }
747
846
  }
748
847
 
@@ -935,12 +1034,18 @@ export async function writeWrapperCmd(
935
1034
  envFile?: string,
936
1035
  sessionMode?: "new" | "reuse" | "last",
937
1036
  sessionId?: string,
938
- retryCount?: number,
939
- retryDelaySeconds?: number,
940
1037
  gateTimeoutSeconds?: number,
941
1038
  permissionsConfig?: string,
942
1039
  policyMeta?: unknown,
943
1040
  sessionFile?: string,
1041
+ /** W-1: запустить задачу в одноразовом git worktree. */
1042
+ worktree?: boolean,
1043
+ /** Путь к dist/core/worktree-run.js (обязателен при worktree=true). */
1044
+ worktreeHelperFile?: string,
1045
+ /** W-3: guard-условия перед запуском opencode. */
1046
+ guards?: TaskGuards,
1047
+ /** Путь к dist/core/guard-run.js (обязателен при guards). */
1048
+ guardHelperFile?: string,
944
1049
  ): Promise<string> {
945
1050
  await fs.mkdir(WRAPPER_DIR, { recursive: true });
946
1051
  const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
@@ -966,13 +1071,10 @@ export async function writeWrapperCmd(
966
1071
  : 300;
967
1072
  psArgs.push(`-GateTimeoutSeconds ${safeGateTimeout}`);
968
1073
 
969
- // Hotfix 1.5.3.1: ретраи. Параметр не передаём при 0 — обёртка по умолчанию
970
- // делает ровно одну попытку, как раньше.
971
- const safeRetryCount = Math.max(0, Math.floor(retryCount ?? 0));
972
- if (safeRetryCount > 0) {
973
- psArgs.push(`-RetryCount ${safeRetryCount}`);
974
- psArgs.push(`-RetryDelaySeconds ${Math.max(0, Math.floor(retryDelaySeconds ?? 0))}`);
975
- }
1074
+ // B2: ретраи сознательно не передаются в обёртку — единственный владелец
1075
+ // повторов это recorder (retryCount/retryDelay), иначе на Windows получается
1076
+ // (1+N)^2 запусков. Старые .cmd с -RetryCount продолжают работать: параметр
1077
+ // принимается, но игнорируется.
976
1078
 
977
1079
  if (logFile) {
978
1080
  psArgs.push(`-LogFile "${logFile}"`);
@@ -987,6 +1089,27 @@ export async function writeWrapperCmd(
987
1089
  // внутри неё больше не ломают однострочный вызов powershell.exe.
988
1090
  const gateFile = await writeHookFile(sanitizedName, "gate", qualityGate);
989
1091
  psArgs.push(`-QualityGate "${gateFile}"`);
1092
+
1093
+ // G-1.2: фиксируем входы гейта до первого запуска. Snapshot лежит в
1094
+ // PLUGIN_DIR, вне рабочей директории задачи.
1095
+ let prompt = "";
1096
+ let hook = qualityGate;
1097
+ try {
1098
+ prompt = await fs.readFile(promptFile, "utf8");
1099
+ } catch {
1100
+ // Промпт мог быть уже удалён — уникальность snapshot от этого не страдает.
1101
+ }
1102
+ try {
1103
+ hook = await fs.readFile(gateFile, "utf8");
1104
+ } catch {
1105
+ // Используем исходную команду, если прочитать хук не удалось.
1106
+ }
1107
+ const snapshotFile = createGateSnapshot(taskName, {
1108
+ gate: hook,
1109
+ prompt,
1110
+ gateTimeoutSeconds: safeGateTimeout,
1111
+ });
1112
+ psArgs.push(`-GateSnapshotFile "${snapshotFile}"`);
990
1113
  }
991
1114
 
992
1115
  if (model?.trim()) {
@@ -1118,8 +1241,85 @@ export async function writeWrapperCmd(
1118
1241
  lines.push("if \"%errorlevel%\"==\"3\" exit /b 0");
1119
1242
  }
1120
1243
 
1244
+ // W-1 (0.0.6): одноразовый git worktree. Создаётся после гейта расписания,
1245
+ // чтобы пропущенный тик не плодил рабочие копии. Ошибка создания — fail-closed:
1246
+ // задача не должна молча работать в основном дереве.
1247
+ let wtHelper = "";
1248
+ let wtRepo = "";
1249
+ let wtLogRedirect = "";
1250
+ if (worktree) {
1251
+ wtHelper = (worktreeHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1252
+ wtRepo = effectiveWorkdir.replace(/[\r\n"]+/g, "").trim();
1253
+ const safeTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1254
+ wtLogRedirect = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1255
+ const helperErr = logFile?.trim() ? `2>> "${logFile.trim()}"` : "";
1256
+ lines.push('set "AGENT_STEWARD_WORKTREE="');
1257
+ lines.push(
1258
+ `for /f "usebackq delims=" %%W in (\`node "${wtHelper}" --repo "${wtRepo}" --task "${safeTaskName}" ${helperErr}\`) do set "AGENT_STEWARD_WORKTREE=%%W"`,
1259
+ );
1260
+ lines.push("if not defined AGENT_STEWARD_WORKTREE (");
1261
+ lines.push(` echo [agent-steward] ERROR: git worktree creation failed ${wtLogRedirect}`);
1262
+ lines.push(" exit /b 1");
1263
+ lines.push(")");
1264
+ lines.push('cd /d "%AGENT_STEWARD_WORKTREE%"');
1265
+ lines.push(`set "AGENT_STEWARD_WORKTREE_REPO=${wtRepo}"`);
1266
+ }
1267
+
1268
+ // W-3 (0.0.6): guard-условия до запуска opencode. Код 4 — штатный skip,
1269
+ // любой другой ненулевой код — ошибка проверки; в обоих случаях opencode
1270
+ // не запускается. Созданный worktree сразу убираем, чтобы не оставлять мусор.
1271
+ if (guards) {
1272
+ const guardHelper = (guardHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1273
+ const guardB64 = Buffer.from(JSON.stringify(guards), "utf8").toString("base64");
1274
+ const skipTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1275
+ const skipRecorder = (recorderFile ?? "").replace(/[\r\n"]+/g, "").trim();
1276
+ const skipReasonB64 = Buffer.from("guard conditions not met", "utf8").toString("base64");
1277
+ const guardLog = logFile?.trim() ? `1>> "${logFile.trim()}" 2>&1` : "";
1278
+ const guardLogAppend = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1279
+ const pushWorktreeCleanup = () => {
1280
+ if (!worktree) return;
1281
+ lines.push(` cd /d "${wtRepo}"`);
1282
+ lines.push(
1283
+ ` node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`,
1284
+ );
1285
+ };
1286
+ lines.push(`node "${guardHelper}" --cwd "%CD%" --guards-b64 "${guardB64}" ${guardLog}`);
1287
+ lines.push('set "AGENT_STEWARD_GUARD_STATUS=%errorlevel%"');
1288
+ lines.push('if "%AGENT_STEWARD_GUARD_STATUS%"=="4" (');
1289
+ lines.push(` echo [agent-steward] guard: run skipped ${guardLogAppend}`);
1290
+ // W-4: пишем skipped в историю/метрики. Причина фиксированная (в базе),
1291
+ // подробности guard-проверки остаются в логе задачи.
1292
+ if (skipRecorder) {
1293
+ lines.push(
1294
+ ` node "${skipRecorder}" --skip "${skipTaskName}" "${skipReasonB64}" ${guardLogAppend}`,
1295
+ );
1296
+ }
1297
+ pushWorktreeCleanup();
1298
+ lines.push(" exit /b 0");
1299
+ lines.push(")");
1300
+ lines.push('if not "%AGENT_STEWARD_GUARD_STATUS%"=="0" (');
1301
+ lines.push(
1302
+ ` echo [agent-steward] ERROR: guard failed with code %AGENT_STEWARD_GUARD_STATUS% ${guardLogAppend}`,
1303
+ );
1304
+ pushWorktreeCleanup();
1305
+ lines.push(" exit /b 1");
1306
+ lines.push(")");
1307
+ }
1308
+
1121
1309
  lines.push(psArgs.join(" "));
1122
1310
 
1311
+ // W-2.1: удаляем одноразовый worktree после прогона при любом коде возврата.
1312
+ // Сначала выходим из него (Windows не даёт удалить текущий каталог), затем
1313
+ // возвращаем исходный код задачи — ошибка очистки не маскирует результат.
1314
+ if (worktree) {
1315
+ lines.push('set "AGENT_STEWARD_EXIT_CODE=%errorlevel%"');
1316
+ lines.push(`cd /d "${wtRepo}"`);
1317
+ lines.push(
1318
+ `node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`,
1319
+ );
1320
+ lines.push("exit /b %AGENT_STEWARD_EXIT_CODE%");
1321
+ }
1322
+
1123
1323
  await fs.writeFile(cmdPath, lines.join("\r\n"), "utf8");
1124
1324
  return cmdPath;
1125
1325
  }