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
@@ -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,18 @@ 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 = "",
88
+ # PL-47: пути, которые задача вправе изменить (из -Files afterScript).
89
+ [string]$GateAllowPaths = "",
47
90
  [string]$BeforeScript,
48
91
  [string]$AfterScript,
49
92
  [string]$EnvFile,
50
93
  [string]$SessionMode,
51
94
  [string]$SessionId,
52
95
  [string]$SessionFile,
96
+ # B2: параметры оставлены только для совместимости со старыми .cmd.
97
+ # Ретраи принадлежат recorder'у — обёртка делает ровно одну попытку.
53
98
  [int]$RetryCount = 0,
54
99
  [int]$RetryDelaySeconds = 0,
55
100
  [int]$GateTimeoutSeconds = 300,
@@ -110,6 +155,8 @@ function Test-ProcessAlive {
110
155
  }
111
156
  }
112
157
 
158
+ ${PS_LOCK_PID_FUNCTION}
159
+
113
160
  # Гарантируем существование папки для лога (на случай прямого вызова обёртки).
114
161
  if ($LogFile) {
115
162
  try {
@@ -133,6 +180,15 @@ $script:timedOut = $false
133
180
  $script:attemptExitCode = 0
134
181
  $startedAtIso = $startTime.ToUniversalTime().ToString("o")
135
182
  $script:runId = ""
183
+ # PL-7.2: разделённые потоки последнего хука для структурированного журнала.
184
+ $script:lastHookStdout = ""
185
+ $script:lastHookStderr = ""
186
+ # PL-25: помощник целостности гейта и файл snapshot'а рабочего дерева.
187
+ $gateIntegrityFile = ""
188
+ if ($RecorderFile) {
189
+ $gateIntegrityFile = Join-Path (Split-Path $RecorderFile -Parent) "gate-integrity.js"
190
+ }
191
+ $worktreeSnapshotFile = ""
136
192
 
137
193
  # Hotfix 1.5.3.1: блокировка ДО записи в историю. Раньше lock существовал только
138
194
  # в in-process пути (LockManager/withLock), а schtasks-запуск обёртки его не
@@ -146,9 +202,9 @@ if ($LockFile) {
146
202
  }
147
203
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
148
204
  try {
149
- # Внутри lock храним время старта и PID владельца: по PID можно
150
- # отличить живой долгий запуск от осиротевшего после kill -9.
151
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
205
+ # B6: единый формат <pid>-<iso> — его читают Node и bash.
206
+ # По PID отличаем живой долгий запуск от осиротевшего после kill -9.
207
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
152
208
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
153
209
  } finally {
154
210
  $lockStream.Dispose()
@@ -161,10 +217,9 @@ if ($LockFile) {
161
217
  $holderPid = 0
162
218
  try {
163
219
  $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
- }
220
+ # B6: понимаем и новый <pid>-<iso>, и legacy <iso>|<pid>,
221
+ # и голый PID — иначе живой чужой lock вытеснялся по возрасту.
222
+ $holderPid = Get-LockOwnerPid -Content $holderRaw
168
223
  } catch {}
169
224
  if ($holderPid -gt 0) {
170
225
  $stale = -not (Test-ProcessAlive -ProcessId $holderPid)
@@ -189,7 +244,7 @@ if ($LockFile) {
189
244
  try {
190
245
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
191
246
  try {
192
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
247
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
193
248
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
194
249
  } finally {
195
250
  $lockStream.Dispose()
@@ -232,6 +287,9 @@ function Invoke-HookScript {
232
287
  if (-not $timeout -or $timeout -le 0) {
233
288
  $output = & cmd.exe /c $Command 2>&1
234
289
  $code = $LASTEXITCODE
290
+ # Без таймаута потоки.cmd объединены — сохраняем как stdout, stderr пуст.
291
+ $script:lastHookStdout = (@($output) -join "\`n")
292
+ $script:lastHookStderr = ""
235
293
  foreach ($line in @($output)) {
236
294
  Write-Log "[hook] $line"
237
295
  }
@@ -277,6 +335,8 @@ function Invoke-HookScript {
277
335
  $errText = ""
278
336
  if ($outTask.Wait(5000)) { try { $outText = $outTask.Result } catch {} }
279
337
  if ($errTask.Wait(5000)) { try { $errText = $errTask.Result } catch {} }
338
+ $script:lastHookStdout = $outText
339
+ $script:lastHookStderr = $errText
280
340
  foreach ($text in @($outText, $errText)) {
281
341
  foreach ($line in @($text -split "\r?\n")) {
282
342
  if ($line -ne "") {
@@ -293,16 +353,44 @@ function Invoke-HookScript {
293
353
  }
294
354
  }
295
355
 
356
+ # PL-7.2: пишет отдельное событие hook.output с реальным exit code и
357
+ # разделёнными stdout/stderr. Наблюдаемость не должна ломать задачу.
358
+ function Write-HookStructuredOutput {
359
+ param([string]$Phase, [int]$ExitCode)
360
+ if (-not $RecorderFile) { return }
361
+ $helper = Join-Path (Split-Path $RecorderFile -Parent) "hook-output.js"
362
+ if (-not (Test-Path -LiteralPath $helper)) { return }
363
+ $outFile = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-hook-out-" + [guid]::NewGuid().ToString("N") + ".txt")
364
+ $errFile = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-hook-err-" + [guid]::NewGuid().ToString("N") + ".txt")
365
+ try {
366
+ Set-Content -LiteralPath $outFile -Value ([string]$script:lastHookStdout) -Encoding UTF8
367
+ Set-Content -LiteralPath $errFile -Value ([string]$script:lastHookStderr) -Encoding UTF8
368
+ & node "$helper" $Phase $TaskName $ExitCode $outFile $errFile "$script:runId" 2>$null | Out-Null
369
+ } catch {
370
+ } finally {
371
+ Remove-Item -LiteralPath $outFile -Force -ErrorAction SilentlyContinue
372
+ Remove-Item -LiteralPath $errFile -Force -ErrorAction SilentlyContinue
373
+ }
374
+ }
375
+
296
376
  # Hotfix 1.5.3.1: запуск opencode с реальным таймаутом.
297
377
  # Раньше TimeoutSeconds принимался, но нигде не использовался — задача работала
298
378
  # до конца, а статус 'timeout' не выставлялся никогда. Теперь параллельно
299
379
  # стартует сторожевой job: по истечении лимита он помечает маркер и убивает
300
380
  # дерево процессов задачи (taskkill /T), а обёртка переводит статус в 'timeout'.
381
+ # B8: снимок дерева процессов. CIM — основной источник; при его сбое
382
+ # пробуем старый WMI, а если и он недоступен — Get-Process/tasklist.
383
+ # Иерархию Get-Process и tasklist не отдают, поэтому при отсутствии данных
384
+ # сторож переходит в fail-closed и убивает дерево по корневому PID.
301
385
  function Invoke-OpenCodeOnce {
302
386
  param([string]$CommandPath, [string[]]$Arguments)
303
387
 
304
388
  $watch = $null
305
389
  $timeoutMarker = ""
390
+ # PL-51: состояние health-check лога (отдельный сторожевой job).
391
+ $healthWatch = $null
392
+ $healthMarker = ""
393
+ $healthFailure = ""
306
394
  if ($TimeoutSeconds -gt 0) {
307
395
  $timeoutMarker = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-timeout-" + [guid]::NewGuid().ToString("N") + ".flag")
308
396
  $watch = Start-Job -ScriptBlock {
@@ -310,19 +398,25 @@ function Invoke-OpenCodeOnce {
310
398
  Start-Sleep -Seconds $Seconds
311
399
  $selfId = $PID
312
400
  $all = @()
313
- try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId) } catch { $all = @() }
401
+ try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
402
+ if ($all.Count -eq 0) {
403
+ try { $all = @(Get-WmiObject Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
404
+ }
405
+ $dataAvailable = $all.Count -gt 0
314
406
  $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)
407
+ if ($dataAvailable) {
408
+ $queue = New-Object System.Collections.Generic.Queue[int]
409
+ $queue.Enqueue($RootId)
410
+ $guard = 0
411
+ while ($queue.Count -gt 0 -and $guard -lt 2000) {
412
+ $guard++
413
+ $current = $queue.Dequeue()
414
+ foreach ($p in $all) {
415
+ $childId = [int]$p.ProcessId
416
+ if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
417
+ $targets.Add($childId)
418
+ $queue.Enqueue($childId)
419
+ }
326
420
  }
327
421
  }
328
422
  }
@@ -331,10 +425,76 @@ function Invoke-OpenCodeOnce {
331
425
  foreach ($targetId in @($targets)) {
332
426
  try { & taskkill.exe /F /T /PID $targetId 2>$null | Out-Null } catch {}
333
427
  }
428
+ } elseif (-not $dataAvailable) {
429
+ # Fail-closed: дерево построить нельзя (CIM/WMI упали, Get-Process
430
+ # и tasklist не дают родительских связей). Помечаем таймаут и
431
+ # убиваем всё дерево от корня, иначе задача переживёт лимит.
432
+ try { Set-Content -Path $Marker -Value "timeout" -Encoding UTF8 } catch {}
433
+ $listing = $false
434
+ try {
435
+ if (@(tasklist.exe /FO CSV /NH 2>$null).Count -gt 0) { $listing = $true }
436
+ } catch {}
437
+ if (-not $listing) {
438
+ try {
439
+ if (@(Get-Process -ErrorAction Stop).Count -gt 0) { $listing = $true }
440
+ } catch {}
441
+ }
442
+ try {
443
+ Start-Process -FilePath "taskkill.exe" -ArgumentList @("/F", "/T", "/PID", [string]$RootId) -WindowStyle Hidden -ErrorAction Stop
444
+ } catch {
445
+ if ($listing) {
446
+ try { & taskkill.exe /F /T /PID $RootId 2>$null | Out-Null } catch {}
447
+ }
448
+ }
334
449
  }
335
450
  } -ArgumentList $PID, $TimeoutSeconds, $timeoutMarker
336
451
  }
337
452
 
453
+ # PL-51: health-check лога. Некоторые модели уходят в бесконечный retry
454
+ # (ECONNRESET / Free usage limit reached / Insufficient Balance) и висят
455
+ # до самого TimeoutSeconds, не делая полезной работы. Сторожевой job читает
456
+ # хвост лога и при повторяющейся ошибке пишет причину в лог, маркер и
457
+ # завершает дерево процесса задачи — как сторож таймаута.
458
+ # Пороги настраиваются env, по умолчанию: 15 с, 3 повтора, 40 строк.
459
+ if ($env:AGENT_STEWARD_HEALTH_CHECK -ne "0" -and $LogFile) {
460
+ $healthInterval = 15
461
+ $healthThreshold = 3
462
+ $healthTail = 40
463
+ try {
464
+ if ($env:AGENT_STEWARD_HEALTH_INTERVAL_SEC -match '^\\d+$') { $healthInterval = [Math]::Max(2, [int]$env:AGENT_STEWARD_HEALTH_INTERVAL_SEC) }
465
+ if ($env:AGENT_STEWARD_HEALTH_REPEAT_THRESHOLD -match '^\\d+$') { $healthThreshold = [Math]::Max(1, [int]$env:AGENT_STEWARD_HEALTH_REPEAT_THRESHOLD) }
466
+ if ($env:AGENT_STEWARD_HEALTH_TAIL_LINES -match '^\\d+$') { $healthTail = [Math]::Max(5, [int]$env:AGENT_STEWARD_HEALTH_TAIL_LINES) }
467
+ } catch {}
468
+ $healthMarker = Join-Path ([System.IO.Path]::GetTempPath()) ("sched-health-" + [guid]::NewGuid().ToString("N") + ".flag")
469
+ $healthWatch = Start-Job -ScriptBlock {
470
+ param([int]$RootId, [string]$Marker, [string]$LogPath, [int]$IntervalSec, [int]$Threshold, [int]$TailLines)
471
+ $pattern = 'ECONNRESET|Free usage limit reached|Insufficient Balance|ECONNREFUSED|ETIMEDOUT'
472
+ # Базовая линия: старые ошибки из предыдущих попыток не должны
473
+ # убивать здоровый запуск — реагируем только на рост числа ошибок.
474
+ $baseline = -1
475
+ while ($true) {
476
+ Start-Sleep -Seconds $IntervalSec
477
+ if (-not $LogPath -or -not (Test-Path -LiteralPath $LogPath)) { continue }
478
+ try { $tail = @(Get-Content -LiteralPath $LogPath -Tail $TailLines -ErrorAction Stop) } catch { continue }
479
+ $bad = @($tail | Where-Object { $_ -match $pattern })
480
+ if ($baseline -lt 0 -or $bad.Count -lt $baseline) { $baseline = $bad.Count; continue }
481
+ if ($bad.Count -ge $baseline + $Threshold) {
482
+ $reason = "PL-51: модель повторяет ошибку ($($bad.Count) за последние $TailLines строк): $($bad[-1])"
483
+ try { Add-Content -LiteralPath $LogPath -Value "[agent-steward] $reason" -Encoding UTF8 } catch {}
484
+ try { Set-Content -LiteralPath $Marker -Value $reason -Encoding UTF8 } catch {}
485
+ try { & taskkill.exe /F /T /PID $RootId 2>$null | Out-Null } catch {}
486
+ break
487
+ }
488
+ }
489
+ } -ArgumentList $PID, $healthMarker, $LogFile, $healthInterval, $healthThreshold, $healthTail
490
+ }
491
+
492
+ # QV-8: дочерний opencode run не должен загружать инструменты планировщика
493
+ # (иначе ребёнок видит все 30 инструментов и может рекурсивно создавать задачи).
494
+ # Маркер живёт только время запуска ИИ и восстанавливается в finally.
495
+ $previousChildRun = $env:AGENT_STEWARD_CHILD_RUN
496
+ $env:AGENT_STEWARD_CHILD_RUN = "1"
497
+
338
498
  $script:timedOut = $false
339
499
  $script:attemptExitCode = 0
340
500
  # Состояние фильтра лога сбрасываем на каждой попытке: иначе незакрытый
@@ -366,16 +526,31 @@ function Invoke-OpenCodeOnce {
366
526
  }
367
527
  }
368
528
  } finally {
529
+ if ($null -eq $previousChildRun) {
530
+ Remove-Item Env:\AGENT_STEWARD_CHILD_RUN -ErrorAction SilentlyContinue
531
+ } else {
532
+ $env:AGENT_STEWARD_CHILD_RUN = $previousChildRun
533
+ }
369
534
  if ($timeoutMarker -and (Test-Path -LiteralPath $timeoutMarker)) {
370
535
  $script:timedOut = $true
371
536
  }
537
+ if ($healthMarker -and (Test-Path -LiteralPath $healthMarker)) {
538
+ try { $healthFailure = (Get-Content -LiteralPath $healthMarker -Raw -ErrorAction Stop).Trim() } catch { $healthFailure = "модель повторяет ошибку подряд" }
539
+ }
372
540
  if ($watch) {
373
541
  Stop-Job -Job $watch -ErrorAction SilentlyContinue
374
542
  Remove-Job -Job $watch -Force -ErrorAction SilentlyContinue
375
543
  }
544
+ if ($healthWatch) {
545
+ Stop-Job -Job $healthWatch -ErrorAction SilentlyContinue
546
+ Remove-Job -Job $healthWatch -Force -ErrorAction SilentlyContinue
547
+ }
376
548
  if ($timeoutMarker) {
377
549
  Remove-Item -LiteralPath $timeoutMarker -Force -ErrorAction SilentlyContinue
378
550
  }
551
+ if ($healthMarker) {
552
+ Remove-Item -LiteralPath $healthMarker -Force -ErrorAction SilentlyContinue
553
+ }
379
554
  }
380
555
 
381
556
  if ($script:timedOut) {
@@ -383,6 +558,11 @@ function Invoke-OpenCodeOnce {
383
558
  $script:errorMessage = "Таймаут: превышено $TimeoutSeconds с"
384
559
  return 124
385
560
  }
561
+ if ($healthFailure) {
562
+ Write-Log "[agent-steward] PL-51: задача '$TaskName' остановлена health-check: $healthFailure"
563
+ $script:errorMessage = "Ошибка модели при запуске: $healthFailure"
564
+ return 125
565
+ }
386
566
  return $script:attemptExitCode
387
567
  }
388
568
 
@@ -477,7 +657,12 @@ function Get-UsageFromLog {
477
657
  )
478
658
  $costPatterns = @(
479
659
  ($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]?\\s*\\$\\s*([0-9]+(?:[.,][0-9]+)?)'),
480
- ($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)')
660
+ ($prefix + '(?i)(?:cost|total\\s+cost)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)'),
661
+ # QA-F.1: OpenCode печатает costUsd=0.1 / cost_usd=0.75 / cost=0.25 без
662
+ # валютного знака. Без этих шаблонов PS-обёртка теряла стоимость, тогда
663
+ # как TS-парсер (src/core/record-history.ts) её уже распознавал.
664
+ ($prefix + '(?i)(?:costUsd|cost_usd|cost(?:\\s*usd)?)\\s*[:=]\\s*\\$?\\s*([0-9]+(?:[.,][0-9]+)?)'),
665
+ ($prefix + '(?i)(?:costUsd|cost_usd|cost(?:\\s*usd)?)\\s*[:=]\\s*([0-9]+(?:[.,][0-9]+)?)\\s*(?:usd|\\$)')
481
666
  )
482
667
 
483
668
  # Идём с конца: OpenCode печатает итог последним, а более ранние строки
@@ -526,6 +711,16 @@ try {
526
711
  Set-Location $Workdir
527
712
  }
528
713
 
714
+ # PL-25: фиксируем состояние рабочего дерева до запуска ИИ. Перед гейтом
715
+ # сверяем его, чтобы чужие незакоммиченные правки src/ не давали ложный зелёный.
716
+ if ($QualityGate -and $GateSnapshotFile -and $Workdir -and $gateIntegrityFile -and (Test-Path -LiteralPath $gateIntegrityFile)) {
717
+ $worktreeSnapshotFile = [System.IO.Path]::ChangeExtension($GateSnapshotFile, ".worktree.json")
718
+ $snapAllowArgs = @()
719
+ if ($GateAllowPaths) { $snapAllowArgs = @("--allow", $GateAllowPaths) }
720
+ $snapOut = & node $gateIntegrityFile worktree-snapshot --dir "$Workdir" --out "$worktreeSnapshotFile" @snapAllowArgs 2>&1
721
+ foreach ($line in $snapOut) { Write-Log "[agent-steward] $line" }
722
+ }
723
+
529
724
  if ($WorkspaceName) {
530
725
  $gitBranch = "-"
531
726
  $gitRemote = "-"
@@ -623,8 +818,10 @@ try {
623
818
  if ($BeforeScript) {
624
819
  Write-Log "[agent-steward] Pre-flight: $BeforeScript"
625
820
  $preCode = Invoke-HookScript -Command $BeforeScript
821
+ Write-HookStructuredOutput -Phase "preFlight" -ExitCode $preCode
626
822
  if ($preCode -ne 0) {
627
- Write-Log "[agent-steward] ОШИБКА: Pre-flight script failed (код $preCode)."
823
+ # PL-6.1: SilentlyContinue не гарантирует код 0 — подсказываем явный exit 0.
824
+ Write-Log "[agent-steward] ОШИБКА: Pre-flight script failed (код $preCode). Завершите хук явным 'exit 0' (например: if (Test-Path -LiteralPath '<path>') { Remove-Item -LiteralPath '<path>' -Force }; exit 0)."
628
825
  $script:preFlightStatus = "error"
629
826
  $script:errorMessage = "Pre-flight script failed"
630
827
  $script:exitCode = 1
@@ -636,8 +833,24 @@ try {
636
833
  }
637
834
 
638
835
  if (-not $script:skipMainTask) {
836
+ # QA-P0.2: граница реального прогона для extractLastRunLog(). Маркер пишется
837
+ # без префикса времени и только после guard/pre-flight — отменённый запуск
838
+ # не должен выглядеть как реальный. Лог дописывается, показываем последний сегмент.
839
+ if ($LogFile) {
840
+ try {
841
+ Add-Content -Path $LogFile -Value ("[agent-steward] === Run started " + $startedAtIso + " (" + $TaskName + ") ===") -Encoding utf8
842
+ } catch {}
843
+ }
639
844
  $prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
640
845
 
846
+ # W-1: запуск в одноразовом git worktree — сообщаем путь агенту.
847
+ # Переменную выставляет .cmd-обёртка после успешного создания копии.
848
+ if ($env:AGENT_STEWARD_WORKTREE) {
849
+ Write-Log "[agent-steward] Git worktree: $env:AGENT_STEWARD_WORKTREE (repo: $env:AGENT_STEWARD_WORKTREE_REPO)"
850
+ $worktreeContext = "[agent-steward] Рабочая директория запуска - одноразовый git worktree: " + $env:AGENT_STEWARD_WORKTREE + [Environment]::NewLine
851
+ $prompt = $worktreeContext + $prompt
852
+ }
853
+
641
854
  # CreateProcess ограничивает командную строку 32767 символами, а промпт
642
855
  # передаётся opencode аргументом ($opencodeArgs += $prompt). Явная ошибка
643
856
  # понятнее, чем обрезанный/отвергнутый запуск. Основная валидация — в schedule_task.
@@ -699,55 +912,89 @@ try {
699
912
  $opencodeArgs += @("--continue")
700
913
  }
701
914
  if ($prompt) {
702
- $opencodeArgs += $prompt
915
+ # B11.1: «--» завершает разбор флагов opencode. Без него промпт,
916
+ # начинающийся с «-», CLI принял бы за неизвестный флаг.
917
+ $opencodeArgs += @("--", $prompt)
703
918
  }
704
919
 
705
920
  # Запускаем opencode и НАПРЯМУЮ направляем весь вывод (stdout + stderr) в лог.
706
921
  # Out-File -Append -Encoding utf8 пишет по мере поступления строк, поэтому
707
922
  # ответ ИИ появляется в 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
- }
923
+ # B2: обёртка делает РОВНО одну попытку. Повторы — зона recorder'а
924
+ # (retryCount/retryDelay в БД), иначе на Windows получалось (1+N)^2
925
+ # запусков: N попыток внутри обёртки × N+1 запуск из recorder'а.
926
+ # Параметры -RetryCount/-RetryDelaySeconds принимаются, но игнорируются.
927
+ $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
728
928
 
729
929
  # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
730
930
  # завершения opencode run. Если ИИ упал — шлюз не запускаем.
731
931
  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
932
+ # G-1.2: перед запуском гейта сверяем его входы со snapshot'ом,
933
+ # снятым при создании задачи. При расхождении гейт НЕ выполняется.
934
+ $gateIntegrityOk = $false
935
+ if ($GateSnapshotFile -and (Test-Path -LiteralPath $GateSnapshotFile)) {
936
+ if (Test-Path -LiteralPath $gateIntegrityFile) {
937
+ $verifyOutput = & node $gateIntegrityFile verify --snapshot "$GateSnapshotFile" --gate-file "$QualityGate" --prompt-file "$PromptFile" --timeout $GateTimeoutSeconds 2>&1
938
+ $verifyCode = $LASTEXITCODE
939
+ foreach ($line in $verifyOutput) { Write-Log "[agent-steward] $line" }
940
+ if ($verifyCode -eq 0) {
941
+ $gateIntegrityOk = $true
942
+ } else {
943
+ Write-Log "[agent-steward] ОШИБКА: целостность входов Quality Gate нарушена (snapshot mismatch)."
944
+ $script:errorMessage = "Quality Gate: целостность входов нарушена (snapshot mismatch)"
945
+ $script:exitCode = 1
946
+ }
947
+ } else {
948
+ Write-Log "[agent-steward] ОШИБКА: не найден помощник проверки целостности гейта."
949
+ $script:errorMessage = "Quality Gate: помощник проверки целостности не найден"
950
+ $script:exitCode = 1
951
+ }
744
952
  } else {
745
- Write-Log "[agent-steward] Quality Gate пройден."
953
+ Write-Log "[agent-steward] ОШИБКА: snapshot гейта отсутствует — запуск с гейтом невозможен."
954
+ $script:errorMessage = "Quality Gate: snapshot входов отсутствует"
955
+ $script:exitCode = 1
956
+ }
957
+
958
+ if ($gateIntegrityOk -and $worktreeSnapshotFile -and (Test-Path -LiteralPath $worktreeSnapshotFile)) {
959
+ $verifyAllowArgs = @()
960
+ if ($GateAllowPaths) { $verifyAllowArgs = @("--allow", $GateAllowPaths) }
961
+ $worktreeOut = & node $gateIntegrityFile worktree-verify --dir "$Workdir" --snapshot "$worktreeSnapshotFile" @verifyAllowArgs 2>&1
962
+ $worktreeCode = $LASTEXITCODE
963
+ foreach ($line in $worktreeOut) { Write-Log "[agent-steward] $line" }
964
+ if ($worktreeCode -ne 0) {
965
+ $gateIntegrityOk = $false
966
+ Write-Log "[agent-steward] ОШИБКА: рабочее дерево изменилось во время прогона — гейт не доверяем."
967
+ $script:errorMessage = "Quality Gate: рабочее дерево изменилось во время прогона"
968
+ $script:exitCode = 1
969
+ }
970
+ }
971
+
972
+ if ($gateIntegrityOk) {
973
+ Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
974
+ # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
975
+ $gateCode = Invoke-HookScript -Command $QualityGate
976
+
977
+ if ($gateCode -eq 124) {
978
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
979
+ $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
980
+ $script:exitCode = 1
981
+ } elseif ($gateCode -ne 0) {
982
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
983
+ $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
984
+ $script:exitCode = 1
985
+ } else {
986
+ Write-Log "[agent-steward] Quality Gate пройден."
987
+ }
746
988
  }
747
989
  }
748
990
 
749
991
  if ($script:exitCode -ne 0) {
750
- Write-Log "[agent-steward] Задача '$TaskName' завершилась с кодом $script:exitCode."
992
+ # Раньше пустое errorMessage превращалось в "-" в истории: причина
993
+ # падения терялась (например, при отказе модели до вывода в лог).
994
+ if (-not $script:errorMessage) {
995
+ $script:errorMessage = "Код возврата $($script:exitCode)"
996
+ }
997
+ Write-Log "[agent-steward] ОШИБКА: задача '$TaskName' завершилась с кодом $($script:exitCode). $script:errorMessage"
751
998
  } else {
752
999
  Write-Log "[agent-steward] Задача '$TaskName' успешно завершена."
753
1000
  }
@@ -761,6 +1008,7 @@ try {
761
1008
  if ($AfterScript) {
762
1009
  Write-Log "[agent-steward] Post-flight: $AfterScript"
763
1010
  $postCode = Invoke-HookScript -Command $AfterScript
1011
+ Write-HookStructuredOutput -Phase "postFlight" -ExitCode $postCode
764
1012
  if ($postCode -ne 0) {
765
1013
  Write-Log "[agent-steward] ОШИБКА: Post-flight script failed (код $postCode)."
766
1014
  $script:postFlightStatus = "error"
@@ -862,6 +1110,22 @@ export function lockFilePath(taskName: string): string {
862
1110
  return path.join(PLUGIN_DIR, "locks", `${sanitizeName(taskName)}.lock`);
863
1111
  }
864
1112
 
1113
+ /**
1114
+ * PL-47: извлекает список `-Files "a;b"` из PowerShell afterScript; возвращает
1115
+ * строку `a|b` для gate-integrity. Возвращает "", если afterScript не коммитит
1116
+ * через pl-commit.ps1 (тогда гейт работает по старой схеме).
1117
+ */
1118
+ export function gateAllowPathsFromAfterScript(afterScript?: string): string {
1119
+ if (!afterScript) return "";
1120
+ const match = /-Files\s+"([^"]+)"/i.exec(afterScript);
1121
+ if (!match) return "";
1122
+ return match[1]
1123
+ .split(";")
1124
+ .map((item) => item.trim().replace(/\\/g, "/").replace(/^\.\//, ""))
1125
+ .filter(Boolean)
1126
+ .join("|");
1127
+ }
1128
+
865
1129
  /**
866
1130
  * Генерирует per-task .cmd-обёртку, которую schtasks вызывает через /tr.
867
1131
  * Внутри .cmd — жёстко заданный вызов run-task.ps1 с задачей, промптом,
@@ -935,12 +1199,20 @@ export async function writeWrapperCmd(
935
1199
  envFile?: string,
936
1200
  sessionMode?: "new" | "reuse" | "last",
937
1201
  sessionId?: string,
938
- retryCount?: number,
939
- retryDelaySeconds?: number,
940
1202
  gateTimeoutSeconds?: number,
941
1203
  permissionsConfig?: string,
942
1204
  policyMeta?: unknown,
943
1205
  sessionFile?: string,
1206
+ /** W-1: запустить задачу в одноразовом git worktree. */
1207
+ worktree?: boolean,
1208
+ /** Путь к dist/core/worktree-run.js (обязателен при worktree=true). */
1209
+ worktreeHelperFile?: string,
1210
+ /** W-3: guard-условия перед запуском opencode. */
1211
+ guards?: TaskGuards,
1212
+ /** Путь к dist/core/guard-run.js (обязателен при guards). */
1213
+ guardHelperFile?: string,
1214
+ /** PL-47: RELATIVE-пути, которые задача вправе изменить (из -Files). */
1215
+ gateAllowPaths?: string,
944
1216
  ): Promise<string> {
945
1217
  await fs.mkdir(WRAPPER_DIR, { recursive: true });
946
1218
  const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
@@ -966,13 +1238,10 @@ export async function writeWrapperCmd(
966
1238
  : 300;
967
1239
  psArgs.push(`-GateTimeoutSeconds ${safeGateTimeout}`);
968
1240
 
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
- }
1241
+ // B2: ретраи сознательно не передаются в обёртку — единственный владелец
1242
+ // повторов это recorder (retryCount/retryDelay), иначе на Windows получается
1243
+ // (1+N)^2 запусков. Старые .cmd с -RetryCount продолжают работать: параметр
1244
+ // принимается, но игнорируется.
976
1245
 
977
1246
  if (logFile) {
978
1247
  psArgs.push(`-LogFile "${logFile}"`);
@@ -987,6 +1256,29 @@ export async function writeWrapperCmd(
987
1256
  // внутри неё больше не ломают однострочный вызов powershell.exe.
988
1257
  const gateFile = await writeHookFile(sanitizedName, "gate", qualityGate);
989
1258
  psArgs.push(`-QualityGate "${gateFile}"`);
1259
+
1260
+ // G-1.2: фиксируем входы гейта до первого запуска. Snapshot лежит в
1261
+ // PLUGIN_DIR, вне рабочей директории задачи.
1262
+ let prompt = "";
1263
+ let hook = qualityGate;
1264
+ try {
1265
+ prompt = await fs.readFile(promptFile, "utf8");
1266
+ } catch {
1267
+ // Промпт мог быть уже удалён — уникальность snapshot от этого не страдает.
1268
+ }
1269
+ try {
1270
+ hook = await fs.readFile(gateFile, "utf8");
1271
+ } catch {
1272
+ // Используем исходную команду, если прочитать хук не удалось.
1273
+ }
1274
+ const snapshotFile = createGateSnapshot(taskName, {
1275
+ gate: hook,
1276
+ prompt,
1277
+ gateTimeoutSeconds: safeGateTimeout,
1278
+ });
1279
+ psArgs.push(`-GateSnapshotFile "${snapshotFile}"`);
1280
+ const safeAllow = (gateAllowPaths ?? "").replace(/[\r\n"]+/g, "").trim();
1281
+ if (safeAllow) psArgs.push(`-GateAllowPaths "${safeAllow}"`);
990
1282
  }
991
1283
 
992
1284
  if (model?.trim()) {
@@ -1118,8 +1410,85 @@ export async function writeWrapperCmd(
1118
1410
  lines.push("if \"%errorlevel%\"==\"3\" exit /b 0");
1119
1411
  }
1120
1412
 
1413
+ // W-1 (0.0.6): одноразовый git worktree. Создаётся после гейта расписания,
1414
+ // чтобы пропущенный тик не плодил рабочие копии. Ошибка создания — fail-closed:
1415
+ // задача не должна молча работать в основном дереве.
1416
+ let wtHelper = "";
1417
+ let wtRepo = "";
1418
+ let wtLogRedirect = "";
1419
+ if (worktree) {
1420
+ wtHelper = (worktreeHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1421
+ wtRepo = effectiveWorkdir.replace(/[\r\n"]+/g, "").trim();
1422
+ const safeTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1423
+ wtLogRedirect = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1424
+ const helperErr = logFile?.trim() ? `2>> "${logFile.trim()}"` : "";
1425
+ lines.push('set "AGENT_STEWARD_WORKTREE="');
1426
+ lines.push(
1427
+ `for /f "usebackq delims=" %%W in (\`node "${wtHelper}" --repo "${wtRepo}" --task "${safeTaskName}" ${helperErr}\`) do set "AGENT_STEWARD_WORKTREE=%%W"`,
1428
+ );
1429
+ lines.push("if not defined AGENT_STEWARD_WORKTREE (");
1430
+ lines.push(` echo [agent-steward] ERROR: git worktree creation failed ${wtLogRedirect}`);
1431
+ lines.push(" exit /b 1");
1432
+ lines.push(")");
1433
+ lines.push('cd /d "%AGENT_STEWARD_WORKTREE%"');
1434
+ lines.push(`set "AGENT_STEWARD_WORKTREE_REPO=${wtRepo}"`);
1435
+ }
1436
+
1437
+ // W-3 (0.0.6): guard-условия до запуска opencode. Код 4 — штатный skip,
1438
+ // любой другой ненулевой код — ошибка проверки; в обоих случаях opencode
1439
+ // не запускается. Созданный worktree сразу убираем, чтобы не оставлять мусор.
1440
+ if (guards) {
1441
+ const guardHelper = (guardHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1442
+ const guardB64 = Buffer.from(JSON.stringify(guards), "utf8").toString("base64");
1443
+ const skipTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1444
+ const skipRecorder = (recorderFile ?? "").replace(/[\r\n"]+/g, "").trim();
1445
+ const skipReasonB64 = Buffer.from("guard conditions not met", "utf8").toString("base64");
1446
+ const guardLog = logFile?.trim() ? `1>> "${logFile.trim()}" 2>&1` : "";
1447
+ const guardLogAppend = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1448
+ const pushWorktreeCleanup = () => {
1449
+ if (!worktree) return;
1450
+ lines.push(` cd /d "${wtRepo}"`);
1451
+ lines.push(
1452
+ ` node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`,
1453
+ );
1454
+ };
1455
+ lines.push(`node "${guardHelper}" --cwd "%CD%" --guards-b64 "${guardB64}" ${guardLog}`);
1456
+ lines.push('set "AGENT_STEWARD_GUARD_STATUS=%errorlevel%"');
1457
+ lines.push('if "%AGENT_STEWARD_GUARD_STATUS%"=="4" (');
1458
+ lines.push(` echo [agent-steward] guard: run skipped ${guardLogAppend}`);
1459
+ // W-4: пишем skipped в историю/метрики. Причина фиксированная (в базе),
1460
+ // подробности guard-проверки остаются в логе задачи.
1461
+ if (skipRecorder) {
1462
+ lines.push(
1463
+ ` node "${skipRecorder}" --skip "${skipTaskName}" "${skipReasonB64}" ${guardLogAppend}`,
1464
+ );
1465
+ }
1466
+ pushWorktreeCleanup();
1467
+ lines.push(" exit /b 0");
1468
+ lines.push(")");
1469
+ lines.push('if not "%AGENT_STEWARD_GUARD_STATUS%"=="0" (');
1470
+ lines.push(
1471
+ ` echo [agent-steward] ERROR: guard failed with code %AGENT_STEWARD_GUARD_STATUS% ${guardLogAppend}`,
1472
+ );
1473
+ pushWorktreeCleanup();
1474
+ lines.push(" exit /b 1");
1475
+ lines.push(")");
1476
+ }
1477
+
1121
1478
  lines.push(psArgs.join(" "));
1122
1479
 
1480
+ // W-2.1: удаляем одноразовый worktree после прогона при любом коде возврата.
1481
+ // Сначала выходим из него (Windows не даёт удалить текущий каталог), затем
1482
+ // возвращаем исходный код задачи — ошибка очистки не маскирует результат.
1483
+ if (worktree) {
1484
+ lines.push('set "AGENT_STEWARD_EXIT_CODE=%errorlevel%"');
1485
+ lines.push(`cd /d "${wtRepo}"`);
1486
+ lines.push(
1487
+ `node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`,
1488
+ );
1489
+ lines.push("exit /b %AGENT_STEWARD_EXIT_CODE%");
1490
+ }
1491
+
1123
1492
  await fs.writeFile(cmdPath, lines.join("\r\n"), "utf8");
1124
1493
  return cmdPath;
1125
1494
  }