agent-steward 0.0.4 → 0.0.6

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 (279) hide show
  1. package/CHANGELOG.md +309 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +55 -8
  4. package/ROADMAP-STRATEGY.md +22 -19
  5. package/ROADMAP.md +230 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +356 -0
  9. package/dist/core/analytics.d.ts +6 -0
  10. package/dist/core/analytics.d.ts.map +1 -1
  11. package/dist/core/analytics.js +20 -3
  12. package/dist/core/audit.d.ts +6 -0
  13. package/dist/core/audit.d.ts.map +1 -1
  14. package/dist/core/audit.js +24 -0
  15. package/dist/core/budget.d.ts +118 -0
  16. package/dist/core/budget.d.ts.map +1 -0
  17. package/dist/core/budget.js +206 -0
  18. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  19. package/dist/core/cron-to-schtasks.js +38 -0
  20. package/dist/core/dry-run.d.ts +26 -1
  21. package/dist/core/dry-run.d.ts.map +1 -1
  22. package/dist/core/dry-run.js +199 -8
  23. package/dist/core/execution.d.ts +203 -0
  24. package/dist/core/execution.d.ts.map +1 -0
  25. package/dist/core/execution.js +309 -0
  26. package/dist/core/feedback.d.ts +192 -0
  27. package/dist/core/feedback.d.ts.map +1 -0
  28. package/dist/core/feedback.js +426 -0
  29. package/dist/core/gate-integrity.d.ts +71 -0
  30. package/dist/core/gate-integrity.d.ts.map +1 -0
  31. package/dist/core/gate-integrity.js +275 -0
  32. package/dist/core/git-trigger.d.ts.map +1 -1
  33. package/dist/core/git-trigger.js +14 -2
  34. package/dist/core/guard-run.d.ts +4 -0
  35. package/dist/core/guard-run.d.ts.map +1 -0
  36. package/dist/core/guard-run.js +101 -0
  37. package/dist/core/guard.d.ts +52 -0
  38. package/dist/core/guard.d.ts.map +1 -0
  39. package/dist/core/guard.js +362 -0
  40. package/dist/core/local-ai.d.ts.map +1 -1
  41. package/dist/core/local-ai.js +7 -3
  42. package/dist/core/lock.d.ts +41 -0
  43. package/dist/core/lock.d.ts.map +1 -1
  44. package/dist/core/lock.js +141 -29
  45. package/dist/core/matrix.d.ts +8 -0
  46. package/dist/core/matrix.d.ts.map +1 -1
  47. package/dist/core/matrix.js +132 -17
  48. package/dist/core/mission.d.ts +103 -0
  49. package/dist/core/mission.d.ts.map +1 -0
  50. package/dist/core/mission.js +374 -0
  51. package/dist/core/opencode-models.d.ts +2 -2
  52. package/dist/core/opencode-models.d.ts.map +1 -1
  53. package/dist/core/opencode-models.js +28 -21
  54. package/dist/core/opencode-usage.d.ts +35 -0
  55. package/dist/core/opencode-usage.d.ts.map +1 -0
  56. package/dist/core/opencode-usage.js +132 -0
  57. package/dist/core/pipeline-apply.d.ts +38 -0
  58. package/dist/core/pipeline-apply.d.ts.map +1 -0
  59. package/dist/core/pipeline-apply.js +117 -0
  60. package/dist/core/pipeline-io.d.ts +13 -0
  61. package/dist/core/pipeline-io.d.ts.map +1 -0
  62. package/dist/core/pipeline-io.js +78 -0
  63. package/dist/core/pipeline-map.d.ts +52 -0
  64. package/dist/core/pipeline-map.d.ts.map +1 -0
  65. package/dist/core/pipeline-map.js +208 -0
  66. package/dist/core/pipeline-spec.d.ts +109 -0
  67. package/dist/core/pipeline-spec.d.ts.map +1 -0
  68. package/dist/core/pipeline-spec.js +554 -0
  69. package/dist/core/ps-wrapper.d.ts +27 -2
  70. package/dist/core/ps-wrapper.d.ts.map +1 -1
  71. package/dist/core/ps-wrapper.js +424 -65
  72. package/dist/core/record-history.d.ts.map +1 -1
  73. package/dist/core/record-history.js +206 -33
  74. package/dist/core/router/rules.d.ts.map +1 -1
  75. package/dist/core/router/rules.js +6 -0
  76. package/dist/core/run-mode.d.ts +12 -0
  77. package/dist/core/run-mode.d.ts.map +1 -0
  78. package/dist/core/run-mode.js +17 -0
  79. package/dist/core/scheduler/linux.d.ts +8 -1
  80. package/dist/core/scheduler/linux.d.ts.map +1 -1
  81. package/dist/core/scheduler/linux.js +34 -9
  82. package/dist/core/scheduler/logs.d.ts +4 -0
  83. package/dist/core/scheduler/logs.d.ts.map +1 -1
  84. package/dist/core/scheduler/logs.js +25 -1
  85. package/dist/core/scheduler/mac.d.ts +44 -2
  86. package/dist/core/scheduler/mac.d.ts.map +1 -1
  87. package/dist/core/scheduler/mac.js +126 -15
  88. package/dist/core/scheduler/windows.d.ts.map +1 -1
  89. package/dist/core/scheduler/windows.js +15 -12
  90. package/dist/core/secrets.d.ts.map +1 -1
  91. package/dist/core/secrets.js +18 -8
  92. package/dist/core/self-analysis.d.ts +32 -2
  93. package/dist/core/self-analysis.d.ts.map +1 -1
  94. package/dist/core/self-analysis.js +38 -27
  95. package/dist/core/shutdown.d.ts +33 -2
  96. package/dist/core/shutdown.d.ts.map +1 -1
  97. package/dist/core/shutdown.js +58 -2
  98. package/dist/core/structured-log.d.ts +37 -1
  99. package/dist/core/structured-log.d.ts.map +1 -1
  100. package/dist/core/structured-log.js +37 -0
  101. package/dist/core/usage-surface.d.ts +25 -0
  102. package/dist/core/usage-surface.d.ts.map +1 -0
  103. package/dist/core/usage-surface.js +41 -0
  104. package/dist/core/worktree-run.d.ts +4 -0
  105. package/dist/core/worktree-run.d.ts.map +1 -0
  106. package/dist/core/worktree-run.js +164 -0
  107. package/dist/core/worktree.d.ts +115 -0
  108. package/dist/core/worktree.d.ts.map +1 -0
  109. package/dist/core/worktree.js +462 -0
  110. package/dist/core/wrappers/bash.d.ts +19 -0
  111. package/dist/core/wrappers/bash.d.ts.map +1 -1
  112. package/dist/core/wrappers/bash.js +230 -27
  113. package/dist/db/capability-repo.d.ts +43 -2
  114. package/dist/db/capability-repo.d.ts.map +1 -1
  115. package/dist/db/capability-repo.js +96 -11
  116. package/dist/db/history-repo.d.ts +70 -5
  117. package/dist/db/history-repo.d.ts.map +1 -1
  118. package/dist/db/history-repo.js +170 -29
  119. package/dist/db/metrics-repo.d.ts +20 -2
  120. package/dist/db/metrics-repo.d.ts.map +1 -1
  121. package/dist/db/metrics-repo.js +35 -13
  122. package/dist/db/migrate.d.ts.map +1 -1
  123. package/dist/db/migrate.js +37 -17
  124. package/dist/db/recovery.d.ts +3 -1
  125. package/dist/db/recovery.d.ts.map +1 -1
  126. package/dist/db/recovery.js +11 -5
  127. package/dist/db/run-journal.d.ts +33 -5
  128. package/dist/db/run-journal.d.ts.map +1 -1
  129. package/dist/db/run-journal.js +78 -14
  130. package/dist/db/run-resume.d.ts +5 -0
  131. package/dist/db/run-resume.d.ts.map +1 -1
  132. package/dist/db/run-resume.js +9 -2
  133. package/dist/db/runs-repo.d.ts +19 -2
  134. package/dist/db/runs-repo.d.ts.map +1 -1
  135. package/dist/db/runs-repo.js +91 -60
  136. package/dist/db/schema.d.ts +2 -2
  137. package/dist/db/schema.d.ts.map +1 -1
  138. package/dist/db/schema.js +132 -2
  139. package/dist/db/templates-repo.d.ts +2 -2
  140. package/dist/db/templates-repo.d.ts.map +1 -1
  141. package/dist/db/templates-repo.js +5 -3
  142. package/dist/history.d.ts +7 -2
  143. package/dist/history.d.ts.map +1 -1
  144. package/dist/history.js +4 -2
  145. package/dist/hook-output.d.ts +2 -0
  146. package/dist/hook-output.d.ts.map +1 -0
  147. package/dist/hook-output.js +31 -0
  148. package/dist/i18n.d.ts +5 -0
  149. package/dist/i18n.d.ts.map +1 -1
  150. package/dist/i18n.js +11 -4
  151. package/dist/index.d.ts +375 -47
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +1344 -192
  154. package/dist/notifications.d.ts +53 -2
  155. package/dist/notifications.d.ts.map +1 -1
  156. package/dist/notifications.js +168 -21
  157. package/dist/profiles.d.ts.map +1 -1
  158. package/dist/profiles.js +82 -10
  159. package/dist/rpc.d.ts +354 -0
  160. package/dist/rpc.d.ts.map +1 -1
  161. package/dist/rpc.js +145 -0
  162. package/dist/server.d.ts +32 -2
  163. package/dist/server.d.ts.map +1 -1
  164. package/dist/server.js +154 -30
  165. package/dist/settings.d.ts +44 -2
  166. package/dist/settings.d.ts.map +1 -1
  167. package/dist/settings.js +85 -3
  168. package/dist/shared/jobs-view.d.ts +1 -1
  169. package/dist/shared/jobs-view.d.ts.map +1 -1
  170. package/dist/shared/jobs-view.js +2 -0
  171. package/dist/task-transfer.d.ts +21 -0
  172. package/dist/task-transfer.d.ts.map +1 -1
  173. package/dist/task-transfer.js +64 -3
  174. package/dist/templates.d.ts +2 -2
  175. package/dist/templates.d.ts.map +1 -1
  176. package/dist/templates.js +3 -3
  177. package/dist/types.d.ts +22 -2
  178. package/dist/types.d.ts.map +1 -1
  179. package/dist/workspaces.d.ts.map +1 -1
  180. package/dist/workspaces.js +34 -11
  181. package/docs/ARCHITECTURE.md +319 -66
  182. package/docs/COMPATIBILITY.md +2 -2
  183. package/docs/CONCEPT.md +18 -4
  184. package/docs/CROSS_PLATFORM.ru.md +20 -0
  185. package/docs/CROSS_PLATFORM.zh.md +18 -0
  186. package/docs/EXECUTION-LOOP.md +28 -10
  187. package/docs/FEATURES.md +129 -7
  188. package/docs/FEATURES.zh.md +97 -6
  189. package/docs/MIGRATION.md +2 -2
  190. package/docs/PIPELINE.md +293 -0
  191. package/docs/QA-A2-GUI-TUI.md +205 -0
  192. package/docs/README.ru.md +43 -4
  193. package/docs/README.zh.md +44 -4
  194. package/docs/SAFETY.md +23 -3
  195. package/gui-experimental.cjs +9 -8
  196. package/locales/en.json +58 -3
  197. package/locales/ru.json +58 -3
  198. package/locales/zh.json +58 -3
  199. package/opencode.pipeline.yaml +35 -0
  200. package/package.json +36 -4
  201. package/scripts/check-eslint-baseline.mjs +139 -0
  202. package/scripts/gen-test-plan-counters.mjs +117 -0
  203. package/scripts/github-ci-fetch.ps1 +37 -0
  204. package/scripts/pl-commit.ps1 +112 -0
  205. package/scripts/qa-a2-commit.ps1 +104 -0
  206. package/scripts/test-home.mjs +107 -0
  207. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  208. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  209. package/src/cli.ts +417 -0
  210. package/src/core/analytics.ts +27 -4
  211. package/src/core/audit.ts +25 -0
  212. package/src/core/budget.ts +340 -0
  213. package/src/core/cron-to-schtasks.ts +42 -0
  214. package/src/core/dry-run.ts +235 -12
  215. package/src/core/execution.ts +538 -0
  216. package/src/core/feedback.ts +582 -0
  217. package/src/core/file-watcher.ts +2 -2
  218. package/src/core/gate-integrity.ts +330 -0
  219. package/src/core/git-trigger.ts +18 -5
  220. package/src/core/guard-run.ts +119 -0
  221. package/src/core/guard.ts +431 -0
  222. package/src/core/local-ai.ts +7 -3
  223. package/src/core/lock.ts +178 -37
  224. package/src/core/matrix.ts +158 -52
  225. package/src/core/mission.ts +531 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/opencode-models.ts +30 -21
  228. package/src/core/opencode-usage.ts +182 -0
  229. package/src/core/pipeline-apply.ts +158 -0
  230. package/src/core/pipeline-io.ts +96 -0
  231. package/src/core/pipeline-map.ts +283 -0
  232. package/src/core/pipeline-spec.ts +775 -0
  233. package/src/core/ps-wrapper.ts +435 -66
  234. package/src/core/record-history.ts +258 -81
  235. package/src/core/router/rules.ts +6 -0
  236. package/src/core/run-mode.ts +19 -0
  237. package/src/core/schedule-gate.ts +1 -1
  238. package/src/core/scheduler/at-fallback.ts +1 -1
  239. package/src/core/scheduler/linux.ts +40 -11
  240. package/src/core/scheduler/logs.ts +34 -3
  241. package/src/core/scheduler/mac.ts +174 -14
  242. package/src/core/scheduler/registry.ts +2 -2
  243. package/src/core/scheduler/windows.ts +19 -15
  244. package/src/core/secrets.ts +26 -19
  245. package/src/core/self-analysis.ts +75 -29
  246. package/src/core/shutdown.ts +90 -4
  247. package/src/core/structured-log.ts +89 -5
  248. package/src/core/telegram.ts +2 -2
  249. package/src/core/triage-worker.ts +7 -7
  250. package/src/core/triage.ts +2 -2
  251. package/src/core/usage-surface.ts +70 -0
  252. package/src/core/worktree-run.ts +199 -0
  253. package/src/core/worktree.ts +600 -0
  254. package/src/core/wrappers/bash.ts +248 -26
  255. package/src/db/capability-repo.ts +127 -10
  256. package/src/db/history-repo.ts +281 -40
  257. package/src/db/metrics-repo.ts +40 -13
  258. package/src/db/migrate.ts +57 -32
  259. package/src/db/recovery.ts +12 -5
  260. package/src/db/run-journal.ts +100 -13
  261. package/src/db/run-resume.ts +17 -1
  262. package/src/db/runs-repo.ts +147 -65
  263. package/src/db/schema.ts +134 -2
  264. package/src/db/templates-repo.ts +5 -3
  265. package/src/gui.tsx +438 -18
  266. package/src/history.ts +11 -4
  267. package/src/hook-output.ts +39 -0
  268. package/src/i18n.ts +12 -4
  269. package/src/index.ts +1902 -320
  270. package/src/notifications.ts +227 -47
  271. package/src/profiles.ts +88 -10
  272. package/src/rpc.ts +158 -0
  273. package/src/server.ts +201 -41
  274. package/src/settings.ts +125 -5
  275. package/src/shared/jobs-view.ts +3 -1
  276. package/src/task-transfer.ts +90 -6
  277. package/src/templates.ts +3 -3
  278. package/src/types.ts +23 -2
  279. package/src/workspaces.ts +37 -14
@@ -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,18 @@ 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 = "",
82
+ # PL-47: пути, которые задача вправе изменить (из -Files afterScript).
83
+ [string]$GateAllowPaths = "",
44
84
  [string]$BeforeScript,
45
85
  [string]$AfterScript,
46
86
  [string]$EnvFile,
47
87
  [string]$SessionMode,
48
88
  [string]$SessionId,
49
89
  [string]$SessionFile,
90
+ # B2: параметры оставлены только для совместимости со старыми .cmd.
91
+ # Ретраи принадлежат recorder'у — обёртка делает ровно одну попытку.
50
92
  [int]$RetryCount = 0,
51
93
  [int]$RetryDelaySeconds = 0,
52
94
  [int]$GateTimeoutSeconds = 300,
@@ -107,6 +149,8 @@ function Test-ProcessAlive {
107
149
  }
108
150
  }
109
151
 
152
+ ${PS_LOCK_PID_FUNCTION}
153
+
110
154
  # Гарантируем существование папки для лога (на случай прямого вызова обёртки).
111
155
  if ($LogFile) {
112
156
  try {
@@ -130,6 +174,15 @@ $script:timedOut = $false
130
174
  $script:attemptExitCode = 0
131
175
  $startedAtIso = $startTime.ToUniversalTime().ToString("o")
132
176
  $script:runId = ""
177
+ # PL-7.2: разделённые потоки последнего хука для структурированного журнала.
178
+ $script:lastHookStdout = ""
179
+ $script:lastHookStderr = ""
180
+ # PL-25: помощник целостности гейта и файл snapshot'а рабочего дерева.
181
+ $gateIntegrityFile = ""
182
+ if ($RecorderFile) {
183
+ $gateIntegrityFile = Join-Path (Split-Path $RecorderFile -Parent) "gate-integrity.js"
184
+ }
185
+ $worktreeSnapshotFile = ""
133
186
 
134
187
  # Hotfix 1.5.3.1: блокировка ДО записи в историю. Раньше lock существовал только
135
188
  # в in-process пути (LockManager/withLock), а schtasks-запуск обёртки его не
@@ -143,9 +196,9 @@ if ($LockFile) {
143
196
  }
144
197
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
145
198
  try {
146
- # Внутри lock храним время старта и PID владельца: по PID можно
147
- # отличить живой долгий запуск от осиротевшего после kill -9.
148
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
199
+ # B6: единый формат <pid>-<iso> — его читают Node и bash.
200
+ # По PID отличаем живой долгий запуск от осиротевшего после kill -9.
201
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
149
202
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
150
203
  } finally {
151
204
  $lockStream.Dispose()
@@ -158,10 +211,9 @@ if ($LockFile) {
158
211
  $holderPid = 0
159
212
  try {
160
213
  $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
- }
214
+ # B6: понимаем и новый <pid>-<iso>, и legacy <iso>|<pid>,
215
+ # и голый PID — иначе живой чужой lock вытеснялся по возрасту.
216
+ $holderPid = Get-LockOwnerPid -Content $holderRaw
165
217
  } catch {}
166
218
  if ($holderPid -gt 0) {
167
219
  $stale = -not (Test-ProcessAlive -ProcessId $holderPid)
@@ -186,7 +238,7 @@ if ($LockFile) {
186
238
  try {
187
239
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
188
240
  try {
189
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
241
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
190
242
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
191
243
  } finally {
192
244
  $lockStream.Dispose()
@@ -229,6 +281,9 @@ function Invoke-HookScript {
229
281
  if (-not $timeout -or $timeout -le 0) {
230
282
  $output = & cmd.exe /c $Command 2>&1
231
283
  $code = $LASTEXITCODE
284
+ # Без таймаута потоки.cmd объединены — сохраняем как stdout, stderr пуст.
285
+ $script:lastHookStdout = (@($output) -join "\`n")
286
+ $script:lastHookStderr = ""
232
287
  foreach ($line in @($output)) {
233
288
  Write-Log "[hook] $line"
234
289
  }
@@ -274,6 +329,8 @@ function Invoke-HookScript {
274
329
  $errText = ""
275
330
  if ($outTask.Wait(5000)) { try { $outText = $outTask.Result } catch {} }
276
331
  if ($errTask.Wait(5000)) { try { $errText = $errTask.Result } catch {} }
332
+ $script:lastHookStdout = $outText
333
+ $script:lastHookStderr = $errText
277
334
  foreach ($text in @($outText, $errText)) {
278
335
  foreach ($line in @($text -split "\r?\n")) {
279
336
  if ($line -ne "") {
@@ -290,16 +347,44 @@ function Invoke-HookScript {
290
347
  }
291
348
  }
292
349
 
350
+ # PL-7.2: пишет отдельное событие hook.output с реальным exit code и
351
+ # разделёнными stdout/stderr. Наблюдаемость не должна ломать задачу.
352
+ function Write-HookStructuredOutput {
353
+ param([string]$Phase, [int]$ExitCode)
354
+ if (-not $RecorderFile) { return }
355
+ $helper = Join-Path (Split-Path $RecorderFile -Parent) "hook-output.js"
356
+ if (-not (Test-Path -LiteralPath $helper)) { return }
357
+ $outFile = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-hook-out-" + [guid]::NewGuid().ToString("N") + ".txt")
358
+ $errFile = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-hook-err-" + [guid]::NewGuid().ToString("N") + ".txt")
359
+ try {
360
+ Set-Content -LiteralPath $outFile -Value ([string]$script:lastHookStdout) -Encoding UTF8
361
+ Set-Content -LiteralPath $errFile -Value ([string]$script:lastHookStderr) -Encoding UTF8
362
+ & node "$helper" $Phase $TaskName $ExitCode $outFile $errFile "$script:runId" 2>$null | Out-Null
363
+ } catch {
364
+ } finally {
365
+ Remove-Item -LiteralPath $outFile -Force -ErrorAction SilentlyContinue
366
+ Remove-Item -LiteralPath $errFile -Force -ErrorAction SilentlyContinue
367
+ }
368
+ }
369
+
293
370
  # Hotfix 1.5.3.1: запуск opencode с реальным таймаутом.
294
371
  # Раньше TimeoutSeconds принимался, но нигде не использовался — задача работала
295
372
  # до конца, а статус 'timeout' не выставлялся никогда. Теперь параллельно
296
373
  # стартует сторожевой job: по истечении лимита он помечает маркер и убивает
297
374
  # дерево процессов задачи (taskkill /T), а обёртка переводит статус в 'timeout'.
375
+ # B8: снимок дерева процессов. CIM — основной источник; при его сбое
376
+ # пробуем старый WMI, а если и он недоступен — Get-Process/tasklist.
377
+ # Иерархию Get-Process и tasklist не отдают, поэтому при отсутствии данных
378
+ # сторож переходит в fail-closed и убивает дерево по корневому PID.
298
379
  function Invoke-OpenCodeOnce {
299
380
  param([string]$CommandPath, [string[]]$Arguments)
300
381
 
301
382
  $watch = $null
302
383
  $timeoutMarker = ""
384
+ # PL-51: состояние health-check лога (отдельный сторожевой job).
385
+ $healthWatch = $null
386
+ $healthMarker = ""
387
+ $healthFailure = ""
303
388
  if ($TimeoutSeconds -gt 0) {
304
389
  $timeoutMarker = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-timeout-" + [guid]::NewGuid().ToString("N") + ".flag")
305
390
  $watch = Start-Job -ScriptBlock {
@@ -307,19 +392,25 @@ function Invoke-OpenCodeOnce {
307
392
  Start-Sleep -Seconds $Seconds
308
393
  $selfId = $PID
309
394
  $all = @()
310
- try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId) } catch { $all = @() }
395
+ try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
396
+ if ($all.Count -eq 0) {
397
+ try { $all = @(Get-WmiObject Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
398
+ }
399
+ $dataAvailable = $all.Count -gt 0
311
400
  $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)
401
+ if ($dataAvailable) {
402
+ $queue = New-Object System.Collections.Generic.Queue[int]
403
+ $queue.Enqueue($RootId)
404
+ $guard = 0
405
+ while ($queue.Count -gt 0 -and $guard -lt 2000) {
406
+ $guard++
407
+ $current = $queue.Dequeue()
408
+ foreach ($p in $all) {
409
+ $childId = [int]$p.ProcessId
410
+ if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
411
+ $targets.Add($childId)
412
+ $queue.Enqueue($childId)
413
+ }
323
414
  }
324
415
  }
325
416
  }
@@ -328,10 +419,76 @@ function Invoke-OpenCodeOnce {
328
419
  foreach ($targetId in @($targets)) {
329
420
  try { & taskkill.exe /F /T /PID $targetId 2>$null | Out-Null } catch {}
330
421
  }
422
+ } elseif (-not $dataAvailable) {
423
+ # Fail-closed: дерево построить нельзя (CIM/WMI упали, Get-Process
424
+ # и tasklist не дают родительских связей). Помечаем таймаут и
425
+ # убиваем всё дерево от корня, иначе задача переживёт лимит.
426
+ try { Set-Content -Path $Marker -Value "timeout" -Encoding UTF8 } catch {}
427
+ $listing = $false
428
+ try {
429
+ if (@(tasklist.exe /FO CSV /NH 2>$null).Count -gt 0) { $listing = $true }
430
+ } catch {}
431
+ if (-not $listing) {
432
+ try {
433
+ if (@(Get-Process -ErrorAction Stop).Count -gt 0) { $listing = $true }
434
+ } catch {}
435
+ }
436
+ try {
437
+ Start-Process -FilePath "taskkill.exe" -ArgumentList @("/F", "/T", "/PID", [string]$RootId) -WindowStyle Hidden -ErrorAction Stop
438
+ } catch {
439
+ if ($listing) {
440
+ try { & taskkill.exe /F /T /PID $RootId 2>$null | Out-Null } catch {}
441
+ }
442
+ }
331
443
  }
332
444
  } -ArgumentList $PID, $TimeoutSeconds, $timeoutMarker
333
445
  }
334
446
 
447
+ # PL-51: health-check лога. Некоторые модели уходят в бесконечный retry
448
+ # (ECONNRESET / Free usage limit reached / Insufficient Balance) и висят
449
+ # до самого TimeoutSeconds, не делая полезной работы. Сторожевой job читает
450
+ # хвост лога и при повторяющейся ошибке пишет причину в лог, маркер и
451
+ # завершает дерево процесса задачи — как сторож таймаута.
452
+ # Пороги настраиваются env, по умолчанию: 15 с, 3 повтора, 40 строк.
453
+ if ($env:AGENT_STEWARD_HEALTH_CHECK -ne "0" -and $LogFile) {
454
+ $healthInterval = 15
455
+ $healthThreshold = 3
456
+ $healthTail = 40
457
+ try {
458
+ if ($env:AGENT_STEWARD_HEALTH_INTERVAL_SEC -match '^\\d+$') { $healthInterval = [Math]::Max(2, [int]$env:AGENT_STEWARD_HEALTH_INTERVAL_SEC) }
459
+ if ($env:AGENT_STEWARD_HEALTH_REPEAT_THRESHOLD -match '^\\d+$') { $healthThreshold = [Math]::Max(1, [int]$env:AGENT_STEWARD_HEALTH_REPEAT_THRESHOLD) }
460
+ if ($env:AGENT_STEWARD_HEALTH_TAIL_LINES -match '^\\d+$') { $healthTail = [Math]::Max(5, [int]$env:AGENT_STEWARD_HEALTH_TAIL_LINES) }
461
+ } catch {}
462
+ $healthMarker = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-health-" + [guid]::NewGuid().ToString("N") + ".flag")
463
+ $healthWatch = Start-Job -ScriptBlock {
464
+ param([int]$RootId, [string]$Marker, [string]$LogPath, [int]$IntervalSec, [int]$Threshold, [int]$TailLines)
465
+ $pattern = 'ECONNRESET|Free usage limit reached|Insufficient Balance|ECONNREFUSED|ETIMEDOUT'
466
+ # Базовая линия: старые ошибки из предыдущих попыток не должны
467
+ # убивать здоровый запуск — реагируем только на рост числа ошибок.
468
+ $baseline = -1
469
+ while ($true) {
470
+ Start-Sleep -Seconds $IntervalSec
471
+ if (-not $LogPath -or -not (Test-Path -LiteralPath $LogPath)) { continue }
472
+ try { $tail = @(Get-Content -LiteralPath $LogPath -Tail $TailLines -ErrorAction Stop) } catch { continue }
473
+ $bad = @($tail | Where-Object { $_ -match $pattern })
474
+ if ($baseline -lt 0 -or $bad.Count -lt $baseline) { $baseline = $bad.Count; continue }
475
+ if ($bad.Count -ge $baseline + $Threshold) {
476
+ $reason = "PL-51: модель повторяет ошибку ($($bad.Count) за последние $TailLines строк): $($bad[-1])"
477
+ try { Add-Content -LiteralPath $LogPath -Value "[agent-steward] $reason" -Encoding UTF8 } catch {}
478
+ try { Set-Content -LiteralPath $Marker -Value $reason -Encoding UTF8 } catch {}
479
+ try { & taskkill.exe /F /T /PID $RootId 2>$null | Out-Null } catch {}
480
+ break
481
+ }
482
+ }
483
+ } -ArgumentList $PID, $healthMarker, $LogFile, $healthInterval, $healthThreshold, $healthTail
484
+ }
485
+
486
+ # QV-8: дочерний opencode run не должен загружать инструменты планировщика
487
+ # (иначе ребёнок видит все 30 инструментов и может рекурсивно создавать задачи).
488
+ # Маркер живёт только время запуска ИИ и восстанавливается в finally.
489
+ $previousChildRun = $env:AGENT_STEWARD_CHILD_RUN
490
+ $env:AGENT_STEWARD_CHILD_RUN = "1"
491
+
335
492
  $script:timedOut = $false
336
493
  $script:attemptExitCode = 0
337
494
  # Состояние фильтра лога сбрасываем на каждой попытке: иначе незакрытый
@@ -363,16 +520,31 @@ function Invoke-OpenCodeOnce {
363
520
  }
364
521
  }
365
522
  } finally {
523
+ if ($null -eq $previousChildRun) {
524
+ Remove-Item Env:\AGENT_STEWARD_CHILD_RUN -ErrorAction SilentlyContinue
525
+ } else {
526
+ $env:AGENT_STEWARD_CHILD_RUN = $previousChildRun
527
+ }
366
528
  if ($timeoutMarker -and (Test-Path -LiteralPath $timeoutMarker)) {
367
529
  $script:timedOut = $true
368
530
  }
531
+ if ($healthMarker -and (Test-Path -LiteralPath $healthMarker)) {
532
+ try { $healthFailure = (Get-Content -LiteralPath $healthMarker -Raw -ErrorAction Stop).Trim() } catch { $healthFailure = "модель повторяет ошибку подряд" }
533
+ }
369
534
  if ($watch) {
370
535
  Stop-Job -Job $watch -ErrorAction SilentlyContinue
371
536
  Remove-Job -Job $watch -Force -ErrorAction SilentlyContinue
372
537
  }
538
+ if ($healthWatch) {
539
+ Stop-Job -Job $healthWatch -ErrorAction SilentlyContinue
540
+ Remove-Job -Job $healthWatch -Force -ErrorAction SilentlyContinue
541
+ }
373
542
  if ($timeoutMarker) {
374
543
  Remove-Item -LiteralPath $timeoutMarker -Force -ErrorAction SilentlyContinue
375
544
  }
545
+ if ($healthMarker) {
546
+ Remove-Item -LiteralPath $healthMarker -Force -ErrorAction SilentlyContinue
547
+ }
376
548
  }
377
549
 
378
550
  if ($script:timedOut) {
@@ -380,6 +552,11 @@ function Invoke-OpenCodeOnce {
380
552
  $script:errorMessage = "Таймаут: превышено $TimeoutSeconds с"
381
553
  return 124
382
554
  }
555
+ if ($healthFailure) {
556
+ Write-Log "[agent-steward] PL-51: задача '$TaskName' остановлена health-check: $healthFailure"
557
+ $script:errorMessage = "Ошибка модели при запуске: $healthFailure"
558
+ return 125
559
+ }
383
560
  return $script:attemptExitCode
384
561
  }
385
562
 
@@ -474,7 +651,12 @@ function Get-UsageFromLog {
474
651
  )
475
652
  $costPatterns = @(
476
653
  ($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]?\\s*\\$\\s*([0-9]+(?:[.,][0-9]+)?)'),
477
- ($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)')
654
+ ($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)'),
655
+ # QA-F.1: OpenCode печатает costUsd=0.1 / cost_usd=0.75 / cost=0.25 без
656
+ # валютного знака. Без этих шаблонов PS-обёртка теряла стоимость, тогда
657
+ # как TS-парсер (src/core/record-history.ts) её уже распознавал.
658
+ ($prefix + '(?i)(?:costUsd|cost_usd|cost(?:\\s*usd)?)\\s*[:=]\\s*\\$?\\s*([0-9]+(?:[.,][0-9]+)?)'),
659
+ ($prefix + '(?i)(?:costUsd|cost_usd|cost(?:\\s*usd)?)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)')
478
660
  )
479
661
 
480
662
  # Идём с конца: OpenCode печатает итог последним, а более ранние строки
@@ -523,6 +705,16 @@ try {
523
705
  Set-Location $Workdir
524
706
  }
525
707
 
708
+ # PL-25: фиксируем состояние рабочего дерева до запуска ИИ. Перед гейтом
709
+ # сверяем его, чтобы чужие незакоммиченные правки src/ не давали ложный зелёный.
710
+ if ($QualityGate -and $GateSnapshotFile -and $Workdir -and $gateIntegrityFile -and (Test-Path -LiteralPath $gateIntegrityFile)) {
711
+ $worktreeSnapshotFile = [System.IO.Path]::ChangeExtension($GateSnapshotFile, ".worktree.json")
712
+ $snapAllowArgs = @()
713
+ if ($GateAllowPaths) { $snapAllowArgs = @("--allow", $GateAllowPaths) }
714
+ $snapOut = & node $gateIntegrityFile worktree-snapshot --dir "$Workdir" --out "$worktreeSnapshotFile" @snapAllowArgs 2>&1
715
+ foreach ($line in $snapOut) { Write-Log "[agent-steward] $line" }
716
+ }
717
+
526
718
  if ($WorkspaceName) {
527
719
  $gitBranch = "-"
528
720
  $gitRemote = "-"
@@ -620,8 +812,10 @@ try {
620
812
  if ($BeforeScript) {
621
813
  Write-Log "[agent-steward] Pre-flight: $BeforeScript"
622
814
  $preCode = Invoke-HookScript -Command $BeforeScript
815
+ Write-HookStructuredOutput -Phase "preFlight" -ExitCode $preCode
623
816
  if ($preCode -ne 0) {
624
- Write-Log "[agent-steward] ОШИБКА: Pre-flight script failed (код $preCode)."
817
+ # PL-6.1: SilentlyContinue не гарантирует код 0 — подсказываем явный exit 0.
818
+ Write-Log "[agent-steward] ОШИБКА: Pre-flight script failed (код $preCode). Завершите хук явным 'exit 0' (например: if (Test-Path -LiteralPath '<path>') { Remove-Item -LiteralPath '<path>' -Force }; exit 0)."
625
819
  $script:preFlightStatus = "error"
626
820
  $script:errorMessage = "Pre-flight script failed"
627
821
  $script:exitCode = 1
@@ -633,8 +827,24 @@ try {
633
827
  }
634
828
 
635
829
  if (-not $script:skipMainTask) {
830
+ # QA-P0.2: граница реального прогона для extractLastRunLog(). Маркер пишется
831
+ # без префикса времени и только после guard/pre-flight — отменённый запуск
832
+ # не должен выглядеть как реальный. Лог дописывается, показываем последний сегмент.
833
+ if ($LogFile) {
834
+ try {
835
+ Add-Content -Path $LogFile -Value ("[agent-steward] === Run started " + $startedAtIso + " (" + $TaskName + ") ===") -Encoding utf8
836
+ } catch {}
837
+ }
636
838
  $prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
637
839
 
840
+ # W-1: запуск в одноразовом git worktree — сообщаем путь агенту.
841
+ # Переменную выставляет .cmd-обёртка после успешного создания копии.
842
+ if ($env:AGENT_STEWARD_WORKTREE) {
843
+ Write-Log "[agent-steward] Git worktree: $env:AGENT_STEWARD_WORKTREE (repo: $env:AGENT_STEWARD_WORKTREE_REPO)"
844
+ $worktreeContext = "[agent-steward] Рабочая директория запуска - одноразовый git worktree: " + $env:AGENT_STEWARD_WORKTREE + [Environment]::NewLine
845
+ $prompt = $worktreeContext + $prompt
846
+ }
847
+
638
848
  # CreateProcess ограничивает командную строку 32767 символами, а промпт
639
849
  # передаётся opencode аргументом ($opencodeArgs += $prompt). Явная ошибка
640
850
  # понятнее, чем обрезанный/отвергнутый запуск. Основная валидация — в schedule_task.
@@ -696,55 +906,89 @@ try {
696
906
  $opencodeArgs += @("--continue")
697
907
  }
698
908
  if ($prompt) {
699
- $opencodeArgs += $prompt
909
+ # B11.1: «--» завершает разбор флагов opencode. Без него промпт,
910
+ # начинающийся с «-», CLI принял бы за неизвестный флаг.
911
+ $opencodeArgs += @("--", $prompt)
700
912
  }
701
913
 
702
914
  # Запускаем opencode и НАПРЯМУЮ направляем весь вывод (stdout + stderr) в лог.
703
915
  # Out-File -Append -Encoding utf8 пишет по мере поступления строк, поэтому
704
916
  # ответ ИИ появляется в 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
- }
917
+ # B2: обёртка делает РОВНО одну попытку. Повторы — зона recorder'а
918
+ # (retryCount/retryDelay в БД), иначе на Windows получалось (1+N)^2
919
+ # запусков: N попыток внутри обёртки × N+1 запуск из recorder'а.
920
+ # Параметры -RetryCount/-RetryDelaySeconds принимаются, но игнорируются.
921
+ $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
725
922
 
726
923
  # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
727
924
  # завершения opencode run. Если ИИ упал — шлюз не запускаем.
728
925
  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
926
+ # G-1.2: перед запуском гейта сверяем его входы со snapshot'ом,
927
+ # снятым при создании задачи. При расхождении гейт НЕ выполняется.
928
+ $gateIntegrityOk = $false
929
+ if ($GateSnapshotFile -and (Test-Path -LiteralPath $GateSnapshotFile)) {
930
+ if (Test-Path -LiteralPath $gateIntegrityFile) {
931
+ $verifyOutput = & node $gateIntegrityFile verify --snapshot "$GateSnapshotFile" --gate-file "$QualityGate" --prompt-file "$PromptFile" --timeout $GateTimeoutSeconds 2>&1
932
+ $verifyCode = $LASTEXITCODE
933
+ foreach ($line in $verifyOutput) { Write-Log "[agent-steward] $line" }
934
+ if ($verifyCode -eq 0) {
935
+ $gateIntegrityOk = $true
936
+ } else {
937
+ Write-Log "[agent-steward] ОШИБКА: целостность входов Quality Gate нарушена (snapshot mismatch)."
938
+ $script:errorMessage = "Quality Gate: целостность входов нарушена (snapshot mismatch)"
939
+ $script:exitCode = 1
940
+ }
941
+ } else {
942
+ Write-Log "[agent-steward] ОШИБКА: не найден помощник проверки целостности гейта."
943
+ $script:errorMessage = "Quality Gate: помощник проверки целостности не найден"
944
+ $script:exitCode = 1
945
+ }
741
946
  } else {
742
- Write-Log "[agent-steward] Quality Gate пройден."
947
+ Write-Log "[agent-steward] ОШИБКА: snapshot гейта отсутствует — запуск с гейтом невозможен."
948
+ $script:errorMessage = "Quality Gate: snapshot входов отсутствует"
949
+ $script:exitCode = 1
950
+ }
951
+
952
+ if ($gateIntegrityOk -and $worktreeSnapshotFile -and (Test-Path -LiteralPath $worktreeSnapshotFile)) {
953
+ $verifyAllowArgs = @()
954
+ if ($GateAllowPaths) { $verifyAllowArgs = @("--allow", $GateAllowPaths) }
955
+ $worktreeOut = & node $gateIntegrityFile worktree-verify --dir "$Workdir" --snapshot "$worktreeSnapshotFile" @verifyAllowArgs 2>&1
956
+ $worktreeCode = $LASTEXITCODE
957
+ foreach ($line in $worktreeOut) { Write-Log "[agent-steward] $line" }
958
+ if ($worktreeCode -ne 0) {
959
+ $gateIntegrityOk = $false
960
+ Write-Log "[agent-steward] ОШИБКА: рабочее дерево изменилось во время прогона — гейт не доверяем."
961
+ $script:errorMessage = "Quality Gate: рабочее дерево изменилось во время прогона"
962
+ $script:exitCode = 1
963
+ }
964
+ }
965
+
966
+ if ($gateIntegrityOk) {
967
+ Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
968
+ # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
969
+ $gateCode = Invoke-HookScript -Command $QualityGate
970
+
971
+ if ($gateCode -eq 124) {
972
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
973
+ $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
974
+ $script:exitCode = 1
975
+ } elseif ($gateCode -ne 0) {
976
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
977
+ $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
978
+ $script:exitCode = 1
979
+ } else {
980
+ Write-Log "[agent-steward] Quality Gate пройден."
981
+ }
743
982
  }
744
983
  }
745
984
 
746
985
  if ($script:exitCode -ne 0) {
747
- Write-Log "[agent-steward] Задача '$TaskName' завершилась с кодом $script:exitCode."
986
+ # Раньше пустое errorMessage превращалось в "-" в истории: причина
987
+ # падения терялась (например, при отказе модели до вывода в лог).
988
+ if (-not $script:errorMessage) {
989
+ $script:errorMessage = "Код возврата $($script:exitCode)"
990
+ }
991
+ Write-Log "[agent-steward] ОШИБКА: задача '$TaskName' завершилась с кодом $($script:exitCode). $script:errorMessage"
748
992
  } else {
749
993
  Write-Log "[agent-steward] Задача '$TaskName' успешно завершена."
750
994
  }
@@ -758,6 +1002,7 @@ try {
758
1002
  if ($AfterScript) {
759
1003
  Write-Log "[agent-steward] Post-flight: $AfterScript"
760
1004
  $postCode = Invoke-HookScript -Command $AfterScript
1005
+ Write-HookStructuredOutput -Phase "postFlight" -ExitCode $postCode
761
1006
  if ($postCode -ne 0) {
762
1007
  Write-Log "[agent-steward] ОШИБКА: Post-flight script failed (код $postCode)."
763
1008
  $script:postFlightStatus = "error"
@@ -855,6 +1100,23 @@ export async function writePromptFile(taskName, prompt) {
855
1100
  export function lockFilePath(taskName) {
856
1101
  return path.join(PLUGIN_DIR, "locks", `${sanitizeName(taskName)}.lock`);
857
1102
  }
1103
+ /**
1104
+ * PL-47: извлекает список `-Files "a;b"` из PowerShell afterScript; возвращает
1105
+ * строку `a|b` для gate-integrity. Возвращает "", если afterScript не коммитит
1106
+ * через pl-commit.ps1 (тогда гейт работает по старой схеме).
1107
+ */
1108
+ export function gateAllowPathsFromAfterScript(afterScript) {
1109
+ if (!afterScript)
1110
+ return "";
1111
+ const match = /-Files\s+"([^"]+)"/i.exec(afterScript);
1112
+ if (!match)
1113
+ return "";
1114
+ return match[1]
1115
+ .split(";")
1116
+ .map((item) => item.trim().replace(/\\/g, "/").replace(/^\.\//, ""))
1117
+ .filter(Boolean)
1118
+ .join("|");
1119
+ }
858
1120
  /**
859
1121
  * Генерирует per-task .cmd-обёртку, которую schtasks вызывает через /tr.
860
1122
  * Внутри .cmd — жёстко заданный вызов run-task.ps1 с задачей, промптом,
@@ -898,7 +1160,17 @@ async function writeHookFile(sanitizedName, kind, command) {
898
1160
  await fs.writeFile(file, `@echo off\r\nchcp 65001 >nul\r\n${command}\r\n`, "utf8");
899
1161
  return file;
900
1162
  }
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) {
1163
+ 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,
1164
+ /** W-1: запустить задачу в одноразовом git worktree. */
1165
+ worktree,
1166
+ /** Путь к dist/core/worktree-run.js (обязателен при worktree=true). */
1167
+ worktreeHelperFile,
1168
+ /** W-3: guard-условия перед запуском opencode. */
1169
+ guards,
1170
+ /** Путь к dist/core/guard-run.js (обязателен при guards). */
1171
+ guardHelperFile,
1172
+ /** PL-47: RELATIVE-пути, которые задача вправе изменить (из -Files). */
1173
+ gateAllowPaths) {
902
1174
  await fs.mkdir(WRAPPER_DIR, { recursive: true });
903
1175
  const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
904
1176
  const ps1Path = path.join(WRAPPER_DIR, WRAPPER_FILENAME);
@@ -919,13 +1191,10 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
919
1191
  ? Math.max(0, Math.floor(gateTimeoutSeconds))
920
1192
  : 300;
921
1193
  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
- }
1194
+ // B2: ретраи сознательно не передаются в обёртку — единственный владелец
1195
+ // повторов это recorder (retryCount/retryDelay), иначе на Windows получается
1196
+ // (1+N)^2 запусков. Старые .cmd с -RetryCount продолжают работать: параметр
1197
+ // принимается, но игнорируется.
929
1198
  if (logFile) {
930
1199
  psArgs.push(`-LogFile "${logFile}"`);
931
1200
  }
@@ -937,6 +1206,31 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
937
1206
  // внутри неё больше не ломают однострочный вызов powershell.exe.
938
1207
  const gateFile = await writeHookFile(sanitizedName, "gate", qualityGate);
939
1208
  psArgs.push(`-QualityGate "${gateFile}"`);
1209
+ // G-1.2: фиксируем входы гейта до первого запуска. Snapshot лежит в
1210
+ // PLUGIN_DIR, вне рабочей директории задачи.
1211
+ let prompt = "";
1212
+ let hook = qualityGate;
1213
+ try {
1214
+ prompt = await fs.readFile(promptFile, "utf8");
1215
+ }
1216
+ catch {
1217
+ // Промпт мог быть уже удалён — уникальность snapshot от этого не страдает.
1218
+ }
1219
+ try {
1220
+ hook = await fs.readFile(gateFile, "utf8");
1221
+ }
1222
+ catch {
1223
+ // Используем исходную команду, если прочитать хук не удалось.
1224
+ }
1225
+ const snapshotFile = createGateSnapshot(taskName, {
1226
+ gate: hook,
1227
+ prompt,
1228
+ gateTimeoutSeconds: safeGateTimeout,
1229
+ });
1230
+ psArgs.push(`-GateSnapshotFile "${snapshotFile}"`);
1231
+ const safeAllow = (gateAllowPaths ?? "").replace(/[\r\n"]+/g, "").trim();
1232
+ if (safeAllow)
1233
+ psArgs.push(`-GateAllowPaths "${safeAllow}"`);
940
1234
  }
941
1235
  if (model?.trim()) {
942
1236
  const safeModel = model.replace(/[\r\n"]+/g, "").trim();
@@ -1056,7 +1350,72 @@ export async function writeWrapperCmd(sanitizedName, taskName, promptFile, timeo
1056
1350
  lines.push(gateArgs.join(" "));
1057
1351
  lines.push("if \"%errorlevel%\"==\"3\" exit /b 0");
1058
1352
  }
1353
+ // W-1 (0.0.6): одноразовый git worktree. Создаётся после гейта расписания,
1354
+ // чтобы пропущенный тик не плодил рабочие копии. Ошибка создания — fail-closed:
1355
+ // задача не должна молча работать в основном дереве.
1356
+ let wtHelper = "";
1357
+ let wtRepo = "";
1358
+ let wtLogRedirect = "";
1359
+ if (worktree) {
1360
+ wtHelper = (worktreeHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1361
+ wtRepo = effectiveWorkdir.replace(/[\r\n"]+/g, "").trim();
1362
+ const safeTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1363
+ wtLogRedirect = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1364
+ const helperErr = logFile?.trim() ? `2>> "${logFile.trim()}"` : "";
1365
+ lines.push('set "AGENT_STEWARD_WORKTREE="');
1366
+ lines.push(`for /f "usebackq delims=" %%W in (\`node "${wtHelper}" --repo "${wtRepo}" --task "${safeTaskName}" ${helperErr}\`) do set "AGENT_STEWARD_WORKTREE=%%W"`);
1367
+ lines.push("if not defined AGENT_STEWARD_WORKTREE (");
1368
+ lines.push(` echo [agent-steward] ERROR: git worktree creation failed ${wtLogRedirect}`);
1369
+ lines.push(" exit /b 1");
1370
+ lines.push(")");
1371
+ lines.push('cd /d "%AGENT_STEWARD_WORKTREE%"');
1372
+ lines.push(`set "AGENT_STEWARD_WORKTREE_REPO=${wtRepo}"`);
1373
+ }
1374
+ // W-3 (0.0.6): guard-условия до запуска opencode. Код 4 — штатный skip,
1375
+ // любой другой ненулевой код — ошибка проверки; в обоих случаях opencode
1376
+ // не запускается. Созданный worktree сразу убираем, чтобы не оставлять мусор.
1377
+ if (guards) {
1378
+ const guardHelper = (guardHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1379
+ const guardB64 = Buffer.from(JSON.stringify(guards), "utf8").toString("base64");
1380
+ const skipTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1381
+ const skipRecorder = (recorderFile ?? "").replace(/[\r\n"]+/g, "").trim();
1382
+ const skipReasonB64 = Buffer.from("guard conditions not met", "utf8").toString("base64");
1383
+ const guardLog = logFile?.trim() ? `1>> "${logFile.trim()}" 2>&1` : "";
1384
+ const guardLogAppend = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1385
+ const pushWorktreeCleanup = () => {
1386
+ if (!worktree)
1387
+ return;
1388
+ lines.push(` cd /d "${wtRepo}"`);
1389
+ lines.push(` node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`);
1390
+ };
1391
+ lines.push(`node "${guardHelper}" --cwd "%CD%" --guards-b64 "${guardB64}" ${guardLog}`);
1392
+ lines.push('set "AGENT_STEWARD_GUARD_STATUS=%errorlevel%"');
1393
+ lines.push('if "%AGENT_STEWARD_GUARD_STATUS%"=="4" (');
1394
+ lines.push(` echo [agent-steward] guard: run skipped ${guardLogAppend}`);
1395
+ // W-4: пишем skipped в историю/метрики. Причина фиксированная (в базе),
1396
+ // подробности guard-проверки остаются в логе задачи.
1397
+ if (skipRecorder) {
1398
+ lines.push(` node "${skipRecorder}" --skip "${skipTaskName}" "${skipReasonB64}" ${guardLogAppend}`);
1399
+ }
1400
+ pushWorktreeCleanup();
1401
+ lines.push(" exit /b 0");
1402
+ lines.push(")");
1403
+ lines.push('if not "%AGENT_STEWARD_GUARD_STATUS%"=="0" (');
1404
+ lines.push(` echo [agent-steward] ERROR: guard failed with code %AGENT_STEWARD_GUARD_STATUS% ${guardLogAppend}`);
1405
+ pushWorktreeCleanup();
1406
+ lines.push(" exit /b 1");
1407
+ lines.push(")");
1408
+ }
1059
1409
  lines.push(psArgs.join(" "));
1410
+ // W-2.1: удаляем одноразовый worktree после прогона при любом коде возврата.
1411
+ // Сначала выходим из него (Windows не даёт удалить текущий каталог), затем
1412
+ // возвращаем исходный код задачи — ошибка очистки не маскирует результат.
1413
+ if (worktree) {
1414
+ lines.push('set "AGENT_STEWARD_EXIT_CODE=%errorlevel%"');
1415
+ lines.push(`cd /d "${wtRepo}"`);
1416
+ lines.push(`node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`);
1417
+ lines.push("exit /b %AGENT_STEWARD_EXIT_CODE%");
1418
+ }
1060
1419
  await fs.writeFile(cmdPath, lines.join("\r\n"), "utf8");
1061
1420
  return cmdPath;
1062
1421
  }