agent-steward 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/CHANGELOG.md +154 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +54 -9
  4. package/ROADMAP-STRATEGY.md +23 -20
  5. package/ROADMAP.md +140 -143
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +351 -0
  9. package/dist/core/dlq-api.d.ts +44 -0
  10. package/dist/core/dlq-api.d.ts.map +1 -0
  11. package/dist/core/dlq-api.js +68 -0
  12. package/dist/core/dry-run.d.ts.map +1 -1
  13. package/dist/core/dry-run.js +18 -1
  14. package/dist/core/execution.d.ts +203 -0
  15. package/dist/core/execution.d.ts.map +1 -0
  16. package/dist/core/execution.js +309 -0
  17. package/dist/core/gate-integrity.d.ts +35 -0
  18. package/dist/core/gate-integrity.d.ts.map +1 -0
  19. package/dist/core/gate-integrity.js +132 -0
  20. package/dist/core/git-trigger.d.ts.map +1 -1
  21. package/dist/core/git-trigger.js +14 -2
  22. package/dist/core/guard-run.d.ts +4 -0
  23. package/dist/core/guard-run.d.ts.map +1 -0
  24. package/dist/core/guard-run.js +101 -0
  25. package/dist/core/guard.d.ts +52 -0
  26. package/dist/core/guard.d.ts.map +1 -0
  27. package/dist/core/guard.js +362 -0
  28. package/dist/core/lock.d.ts +61 -4
  29. package/dist/core/lock.d.ts.map +1 -1
  30. package/dist/core/lock.js +213 -26
  31. package/dist/core/matrix.d.ts.map +1 -1
  32. package/dist/core/matrix.js +75 -15
  33. package/dist/core/mission.d.ts +83 -0
  34. package/dist/core/mission.d.ts.map +1 -0
  35. package/dist/core/mission.js +334 -0
  36. package/dist/core/one-shot.d.ts +5 -1
  37. package/dist/core/one-shot.d.ts.map +1 -1
  38. package/dist/core/one-shot.js +33 -8
  39. package/dist/core/opencode-cli.d.ts +28 -0
  40. package/dist/core/opencode-cli.d.ts.map +1 -0
  41. package/dist/core/opencode-cli.js +74 -0
  42. package/dist/core/opencode-models.d.ts +62 -0
  43. package/dist/core/opencode-models.d.ts.map +1 -0
  44. package/dist/core/opencode-models.js +277 -0
  45. package/dist/core/pipeline-apply.d.ts +38 -0
  46. package/dist/core/pipeline-apply.d.ts.map +1 -0
  47. package/dist/core/pipeline-apply.js +117 -0
  48. package/dist/core/pipeline-io.d.ts +13 -0
  49. package/dist/core/pipeline-io.d.ts.map +1 -0
  50. package/dist/core/pipeline-io.js +64 -0
  51. package/dist/core/pipeline-map.d.ts +46 -0
  52. package/dist/core/pipeline-map.d.ts.map +1 -0
  53. package/dist/core/pipeline-map.js +196 -0
  54. package/dist/core/pipeline-spec.d.ts +109 -0
  55. package/dist/core/pipeline-spec.d.ts.map +1 -0
  56. package/dist/core/pipeline-spec.js +554 -0
  57. package/dist/core/ps-wrapper.d.ts +19 -2
  58. package/dist/core/ps-wrapper.d.ts.map +1 -1
  59. package/dist/core/ps-wrapper.js +261 -63
  60. package/dist/core/record-history.d.ts +15 -0
  61. package/dist/core/record-history.d.ts.map +1 -1
  62. package/dist/core/record-history.js +183 -58
  63. package/dist/core/router/dispatch.d.ts +36 -0
  64. package/dist/core/router/dispatch.d.ts.map +1 -0
  65. package/dist/core/router/dispatch.js +59 -0
  66. package/dist/core/router/escalation.d.ts +47 -0
  67. package/dist/core/router/escalation.d.ts.map +1 -0
  68. package/dist/core/router/escalation.js +87 -0
  69. package/dist/core/router/planner.d.ts +53 -0
  70. package/dist/core/router/planner.d.ts.map +1 -0
  71. package/dist/core/router/planner.js +113 -0
  72. package/dist/core/router/rules.d.ts +46 -0
  73. package/dist/core/router/rules.d.ts.map +1 -0
  74. package/dist/core/router/rules.js +91 -0
  75. package/dist/core/run-panel-api.d.ts +94 -0
  76. package/dist/core/run-panel-api.d.ts.map +1 -0
  77. package/dist/core/run-panel-api.js +169 -0
  78. package/dist/core/schedule-gate.js +5 -1
  79. package/dist/core/schedule-v2.d.ts +34 -0
  80. package/dist/core/schedule-v2.d.ts.map +1 -1
  81. package/dist/core/schedule-v2.js +91 -5
  82. package/dist/core/scheduler/at-fallback.d.ts +55 -2
  83. package/dist/core/scheduler/at-fallback.d.ts.map +1 -1
  84. package/dist/core/scheduler/at-fallback.js +135 -5
  85. package/dist/core/scheduler/linux.d.ts +18 -2
  86. package/dist/core/scheduler/linux.d.ts.map +1 -1
  87. package/dist/core/scheduler/linux.js +63 -20
  88. package/dist/core/scheduler/mac.d.ts +44 -2
  89. package/dist/core/scheduler/mac.d.ts.map +1 -1
  90. package/dist/core/scheduler/mac.js +126 -15
  91. package/dist/core/scheduler/posix.d.ts.map +1 -1
  92. package/dist/core/scheduler/posix.js +25 -1
  93. package/dist/core/scheduler/registry.d.ts +11 -0
  94. package/dist/core/scheduler/registry.d.ts.map +1 -1
  95. package/dist/core/scheduler/registry.js +83 -21
  96. package/dist/core/scheduler/run-now.d.ts +16 -0
  97. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  98. package/dist/core/scheduler/run-now.js +28 -0
  99. package/dist/core/scheduler/windows.d.ts.map +1 -1
  100. package/dist/core/scheduler/windows.js +15 -12
  101. package/dist/core/secrets.d.ts.map +1 -1
  102. package/dist/core/secrets.js +125 -28
  103. package/dist/core/session.d.ts.map +1 -1
  104. package/dist/core/session.js +18 -11
  105. package/dist/core/structured-log.d.ts +7 -1
  106. package/dist/core/structured-log.d.ts.map +1 -1
  107. package/dist/core/task-name.d.ts +24 -0
  108. package/dist/core/task-name.d.ts.map +1 -0
  109. package/dist/core/task-name.js +40 -0
  110. package/dist/core/worktree-run.d.ts +4 -0
  111. package/dist/core/worktree-run.d.ts.map +1 -0
  112. package/dist/core/worktree-run.js +164 -0
  113. package/dist/core/worktree.d.ts +115 -0
  114. package/dist/core/worktree.d.ts.map +1 -0
  115. package/dist/core/worktree.js +462 -0
  116. package/dist/core/wrappers/bash.d.ts +17 -0
  117. package/dist/core/wrappers/bash.d.ts.map +1 -1
  118. package/dist/core/wrappers/bash.js +224 -28
  119. package/dist/db/capability-repo.d.ts +124 -0
  120. package/dist/db/capability-repo.d.ts.map +1 -0
  121. package/dist/db/capability-repo.js +267 -0
  122. package/dist/db/history-repo.d.ts +46 -5
  123. package/dist/db/history-repo.d.ts.map +1 -1
  124. package/dist/db/history-repo.js +107 -25
  125. package/dist/db/index.d.ts +4 -0
  126. package/dist/db/index.d.ts.map +1 -1
  127. package/dist/db/index.js +39 -1
  128. package/dist/db/metrics-repo.js +2 -2
  129. package/dist/db/migrate.d.ts.map +1 -1
  130. package/dist/db/migrate.js +3 -1
  131. package/dist/db/recovery.d.ts.map +1 -1
  132. package/dist/db/recovery.js +5 -4
  133. package/dist/db/run-context.d.ts +103 -0
  134. package/dist/db/run-context.d.ts.map +1 -0
  135. package/dist/db/run-context.js +224 -0
  136. package/dist/db/run-dlq.d.ts +100 -0
  137. package/dist/db/run-dlq.d.ts.map +1 -0
  138. package/dist/db/run-dlq.js +191 -0
  139. package/dist/db/run-journal.d.ts +33 -5
  140. package/dist/db/run-journal.d.ts.map +1 -1
  141. package/dist/db/run-journal.js +78 -14
  142. package/dist/db/run-resume.d.ts +10 -2
  143. package/dist/db/run-resume.d.ts.map +1 -1
  144. package/dist/db/run-resume.js +39 -13
  145. package/dist/db/runs-repo.d.ts +32 -7
  146. package/dist/db/runs-repo.d.ts.map +1 -1
  147. package/dist/db/runs-repo.js +50 -11
  148. package/dist/db/schema.d.ts +2 -2
  149. package/dist/db/schema.d.ts.map +1 -1
  150. package/dist/db/schema.js +216 -3
  151. package/dist/db/settings-repo.d.ts +11 -0
  152. package/dist/db/settings-repo.d.ts.map +1 -1
  153. package/dist/db/settings-repo.js +25 -0
  154. package/dist/db/step-idempotency.d.ts +51 -0
  155. package/dist/db/step-idempotency.d.ts.map +1 -0
  156. package/dist/db/step-idempotency.js +136 -0
  157. package/dist/history.d.ts +1 -1
  158. package/dist/history.d.ts.map +1 -1
  159. package/dist/i18n.d.ts +5 -0
  160. package/dist/i18n.d.ts.map +1 -1
  161. package/dist/i18n.js +11 -4
  162. package/dist/index.d.ts +140 -6
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +480 -18
  165. package/dist/notifications.d.ts +22 -0
  166. package/dist/notifications.d.ts.map +1 -1
  167. package/dist/notifications.js +36 -8
  168. package/dist/profiles.d.ts.map +1 -1
  169. package/dist/profiles.js +25 -4
  170. package/dist/rpc.d.ts +924 -0
  171. package/dist/rpc.d.ts.map +1 -1
  172. package/dist/rpc.js +352 -0
  173. package/dist/server.d.ts +46 -0
  174. package/dist/server.d.ts.map +1 -1
  175. package/dist/server.js +172 -53
  176. package/dist/settings.d.ts +2 -2
  177. package/dist/settings.d.ts.map +1 -1
  178. package/dist/settings.js +3 -3
  179. package/dist/shared/jobs-view.d.ts +1 -1
  180. package/dist/shared/jobs-view.d.ts.map +1 -1
  181. package/dist/shared/jobs-view.js +2 -0
  182. package/dist/task-transfer.d.ts +16 -0
  183. package/dist/task-transfer.d.ts.map +1 -1
  184. package/dist/task-transfer.js +16 -0
  185. package/dist/types.d.ts.map +1 -1
  186. package/dist/types.js +7 -0
  187. package/dist/workspaces.d.ts +25 -3
  188. package/dist/workspaces.d.ts.map +1 -1
  189. package/dist/workspaces.js +43 -8
  190. package/docs/ARCHITECTURE.md +498 -58
  191. package/docs/COMPATIBILITY.md +2 -2
  192. package/docs/CONCEPT.md +185 -91
  193. package/docs/CROSS_PLATFORM.ru.md +20 -0
  194. package/docs/CROSS_PLATFORM.zh.md +18 -0
  195. package/docs/EXECUTION-LOOP.md +211 -0
  196. package/docs/FEATURES.md +65 -4
  197. package/docs/FEATURES.zh.md +52 -4
  198. package/docs/MIGRATION.md +2 -2
  199. package/docs/PIPELINE.md +293 -0
  200. package/docs/README.ru.md +44 -5
  201. package/docs/README.zh.md +46 -6
  202. package/docs/SAFETY.md +142 -0
  203. package/docs/SAVINGS.md +29 -0
  204. package/docs/SAVINGS.ru.md +29 -0
  205. package/docs/SAVINGS.zh.md +18 -0
  206. package/gui-experimental.cjs +9 -8
  207. package/locales/en.json +84 -1
  208. package/locales/ru.json +84 -1
  209. package/locales/zh.json +84 -1
  210. package/opencode.pipeline.yaml +35 -0
  211. package/package.json +46 -2
  212. package/scripts/audit-bundle.mjs +215 -0
  213. package/scripts/test-home.mjs +83 -0
  214. package/src/cli.ts +412 -0
  215. package/src/core/dlq-api.ts +98 -0
  216. package/src/core/dry-run.ts +27 -3
  217. package/src/core/execution.ts +538 -0
  218. package/src/core/file-watcher.ts +2 -2
  219. package/src/core/gate-integrity.ts +160 -0
  220. package/src/core/git-trigger.ts +18 -5
  221. package/src/core/guard-run.ts +119 -0
  222. package/src/core/guard.ts +431 -0
  223. package/src/core/lock.ts +244 -30
  224. package/src/core/matrix.ts +95 -50
  225. package/src/core/mission.ts +485 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/one-shot.ts +36 -8
  228. package/src/core/opencode-cli.ts +103 -0
  229. package/src/core/opencode-models.ts +315 -0
  230. package/src/core/pipeline-apply.ts +158 -0
  231. package/src/core/pipeline-io.ts +79 -0
  232. package/src/core/pipeline-map.ts +264 -0
  233. package/src/core/pipeline-spec.ts +775 -0
  234. package/src/core/ps-wrapper.ts +274 -64
  235. package/src/core/record-history.ts +229 -104
  236. package/src/core/router/dispatch.ts +94 -0
  237. package/src/core/router/escalation.ts +129 -0
  238. package/src/core/router/planner.ts +166 -0
  239. package/src/core/router/rules.ts +115 -0
  240. package/src/core/run-panel-api.ts +262 -0
  241. package/src/core/schedule-gate.ts +7 -3
  242. package/src/core/schedule-v2.ts +114 -5
  243. package/src/core/scheduler/at-fallback.ts +190 -5
  244. package/src/core/scheduler/linux.ts +72 -21
  245. package/src/core/scheduler/logs.ts +2 -2
  246. package/src/core/scheduler/mac.ts +174 -14
  247. package/src/core/scheduler/posix.ts +20 -1
  248. package/src/core/scheduler/registry.ts +107 -26
  249. package/src/core/scheduler/run-now.ts +32 -0
  250. package/src/core/scheduler/windows.ts +19 -15
  251. package/src/core/secrets.ts +131 -31
  252. package/src/core/session.ts +23 -10
  253. package/src/core/structured-log.ts +22 -5
  254. package/src/core/task-name.ts +67 -0
  255. package/src/core/telegram.ts +2 -2
  256. package/src/core/triage-worker.ts +7 -7
  257. package/src/core/triage.ts +2 -2
  258. package/src/core/worktree-run.ts +199 -0
  259. package/src/core/worktree.ts +600 -0
  260. package/src/core/wrappers/bash.ts +239 -27
  261. package/src/db/capability-repo.ts +402 -0
  262. package/src/db/history-repo.ts +151 -22
  263. package/src/db/index.ts +37 -1
  264. package/src/db/metrics-repo.ts +2 -2
  265. package/src/db/migrate.ts +3 -1
  266. package/src/db/recovery.ts +5 -4
  267. package/src/db/run-context.ts +370 -0
  268. package/src/db/run-dlq.ts +310 -0
  269. package/src/db/run-journal.ts +100 -13
  270. package/src/db/run-resume.ts +65 -13
  271. package/src/db/runs-repo.ts +66 -13
  272. package/src/db/schema.ts +218 -3
  273. package/src/db/settings-repo.ts +31 -0
  274. package/src/db/step-idempotency.ts +185 -0
  275. package/src/gui.tsx +692 -13
  276. package/src/history.ts +1 -1
  277. package/src/i18n.ts +12 -4
  278. package/src/index.ts +648 -8
  279. package/src/notifications.ts +38 -8
  280. package/src/profiles.ts +26 -4
  281. package/src/rpc.ts +379 -0
  282. package/src/server.ts +206 -54
  283. package/src/settings.ts +5 -5
  284. package/src/shared/jobs-view.ts +3 -1
  285. package/src/task-transfer.ts +31 -0
  286. package/src/types.ts +9 -0
  287. package/src/workspaces.ts +58 -9
@@ -2,6 +2,8 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { PLUGIN_DIR, LOG_DIR, LOCK_DIR, WRAPPER_DIR, STALE_LOCK_MAX_AGE_MS, sanitizeName } from "../types.js";
4
4
  import type { ScheduleGateSpec } from "./schedule-v2.js";
5
+ import type { TaskGuards } from "./guard.js";
6
+ import { createGateSnapshot } from "./gate-integrity.js";
5
7
 
6
8
  /**
7
9
  * Путь к единому generic-обёртке PowerShell, которая реализует запуск opencode run
@@ -31,6 +33,43 @@ const WRAPPER_FILENAME = "run-task.ps1";
31
33
  * 5. При таймауте — убивает процесс и дочерние процессы.
32
34
  * 6. В finally выполняет post-flight и удаляет lock-файл.
33
35
  */
36
+
37
+ /**
38
+ * B6: разбор PID из lock-файла для PowerShell-обёртки.
39
+ *
40
+ * Формат общий с Node: `<pid>-<iso>`. Legacy-файлы тоже читаются:
41
+ * `<iso>|<pid>` (прошлый PS) и голый `<pid>` (pid-файл bash-обёртки).
42
+ * Обратные слэши в regex удвоены — так же, как в остальном WRAPPER_SCRIPT.
43
+ */
44
+ export const PS_LOCK_PID_FUNCTION = `# B6: PID владельца lock-файла в любом формате (Node/PS/bash).
45
+ function Get-LockOwnerPid {
46
+ param([string]$Content)
47
+ $text = "$Content".Trim()
48
+ if (-not $text) { return 0 }
49
+ # Legacy PS: <iso>|<pid>. Проверяем ДО разбора по дефису, иначе год
50
+ # из ISO (2026) был бы принят за PID.
51
+ if ($text.Contains("|")) {
52
+ $parts = $text.Split([char]124)
53
+ $parsed = 0
54
+ if ($parts.Count -ge 2 -and [int]::TryParse($parts[1].Trim(), [ref]$parsed) -and $parsed -gt 0) {
55
+ return $parsed
56
+ }
57
+ return 0
58
+ }
59
+ # Голый ISO без PID (старый чужой lock) не должен давать год как PID:
60
+ # для свежего файла это означало бы вытеснение активной блокировки.
61
+ if ($text -match '^\\d{4}-\\d{2}-\\d{2}T') { return 0 }
62
+ # Единый формат <pid>-<iso> и старый Node <pid>-<epoch>-<uuid>.
63
+ if ($text -match '^(\\d+)-') { return [int]$matches[1] }
64
+ # Голый PID (pid-файл bash-обёртки).
65
+ if ($text -match '^\\d+$') {
66
+ $parsed = 0
67
+ if ([int]::TryParse($text, [ref]$parsed) -and $parsed -gt 0) { return $parsed }
68
+ return 0
69
+ }
70
+ return 0
71
+ }`;
72
+
34
73
  export const WRAPPER_SCRIPT = `param(
35
74
  [string]$TaskName,
36
75
  [string]$PromptFile,
@@ -44,12 +83,16 @@ export const WRAPPER_SCRIPT = `param(
44
83
  [string]$LogFile,
45
84
  [string]$RecorderFile,
46
85
  [string]$QualityGate,
86
+ # G-1.2: snapshot входов гейта, снятый при создании обёртки.
87
+ [string]$GateSnapshotFile = "",
47
88
  [string]$BeforeScript,
48
89
  [string]$AfterScript,
49
90
  [string]$EnvFile,
50
91
  [string]$SessionMode,
51
92
  [string]$SessionId,
52
93
  [string]$SessionFile,
94
+ # B2: параметры оставлены только для совместимости со старыми .cmd.
95
+ # Ретраи принадлежат recorder'у — обёртка делает ровно одну попытку.
53
96
  [int]$RetryCount = 0,
54
97
  [int]$RetryDelaySeconds = 0,
55
98
  [int]$GateTimeoutSeconds = 300,
@@ -110,6 +153,8 @@ function Test-ProcessAlive {
110
153
  }
111
154
  }
112
155
 
156
+ ${PS_LOCK_PID_FUNCTION}
157
+
113
158
  # Гарантируем существование папки для лога (на случай прямого вызова обёртки).
114
159
  if ($LogFile) {
115
160
  try {
@@ -146,9 +191,9 @@ if ($LockFile) {
146
191
  }
147
192
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
148
193
  try {
149
- # Внутри lock храним время старта и PID владельца: по PID можно
150
- # отличить живой долгий запуск от осиротевшего после kill -9.
151
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
194
+ # B6: единый формат <pid>-<iso> — его читают Node и bash.
195
+ # По PID отличаем живой долгий запуск от осиротевшего после kill -9.
196
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
152
197
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
153
198
  } finally {
154
199
  $lockStream.Dispose()
@@ -161,10 +206,9 @@ if ($LockFile) {
161
206
  $holderPid = 0
162
207
  try {
163
208
  $holderRaw = "$(Get-Content -LiteralPath $LockFile -Raw -ErrorAction Stop)".Trim()
164
- $holderParts = $holderRaw.Split([char]124)
165
- if ($holderParts.Count -ge 2) {
166
- [void][int]::TryParse($holderParts[1], [ref]$holderPid)
167
- }
209
+ # B6: понимаем и новый <pid>-<iso>, и legacy <iso>|<pid>,
210
+ # и голый PID — иначе живой чужой lock вытеснялся по возрасту.
211
+ $holderPid = Get-LockOwnerPid -Content $holderRaw
168
212
  } catch {}
169
213
  if ($holderPid -gt 0) {
170
214
  $stale = -not (Test-ProcessAlive -ProcessId $holderPid)
@@ -189,7 +233,7 @@ if ($LockFile) {
189
233
  try {
190
234
  $lockStream = [System.IO.File]::Open($LockFile, [System.IO.FileMode]::CreateNew, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
191
235
  try {
192
- $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$startedAtIso|$PID")
236
+ $lockBytes = [System.Text.Encoding]::UTF8.GetBytes("$PID-$startedAtIso")
193
237
  $lockStream.Write($lockBytes, 0, $lockBytes.Length)
194
238
  } finally {
195
239
  $lockStream.Dispose()
@@ -298,6 +342,10 @@ function Invoke-HookScript {
298
342
  # до конца, а статус 'timeout' не выставлялся никогда. Теперь параллельно
299
343
  # стартует сторожевой job: по истечении лимита он помечает маркер и убивает
300
344
  # дерево процессов задачи (taskkill /T), а обёртка переводит статус в 'timeout'.
345
+ # B8: снимок дерева процессов. CIM — основной источник; при его сбое
346
+ # пробуем старый WMI, а если и он недоступен — Get-Process/tasklist.
347
+ # Иерархию Get-Process и tasklist не отдают, поэтому при отсутствии данных
348
+ # сторож переходит в fail-closed и убивает дерево по корневому PID.
301
349
  function Invoke-OpenCodeOnce {
302
350
  param([string]$CommandPath, [string[]]$Arguments)
303
351
 
@@ -310,19 +358,25 @@ function Invoke-OpenCodeOnce {
310
358
  Start-Sleep -Seconds $Seconds
311
359
  $selfId = $PID
312
360
  $all = @()
313
- try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId) } catch { $all = @() }
361
+ try { $all = @(Get-CimInstance Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
362
+ if ($all.Count -eq 0) {
363
+ try { $all = @(Get-WmiObject Win32_Process -Property ProcessId, ParentProcessId -ErrorAction Stop) } catch { $all = @() }
364
+ }
365
+ $dataAvailable = $all.Count -gt 0
314
366
  $targets = New-Object System.Collections.Generic.List[int]
315
- $queue = New-Object System.Collections.Generic.Queue[int]
316
- $queue.Enqueue($RootId)
317
- $guard = 0
318
- while ($queue.Count -gt 0 -and $guard -lt 2000) {
319
- $guard++
320
- $current = $queue.Dequeue()
321
- foreach ($p in $all) {
322
- $childId = [int]$p.ProcessId
323
- if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
324
- $targets.Add($childId)
325
- $queue.Enqueue($childId)
367
+ if ($dataAvailable) {
368
+ $queue = New-Object System.Collections.Generic.Queue[int]
369
+ $queue.Enqueue($RootId)
370
+ $guard = 0
371
+ while ($queue.Count -gt 0 -and $guard -lt 2000) {
372
+ $guard++
373
+ $current = $queue.Dequeue()
374
+ foreach ($p in $all) {
375
+ $childId = [int]$p.ProcessId
376
+ if ([int]$p.ParentProcessId -eq $current -and $childId -ne $selfId -and -not $targets.Contains($childId)) {
377
+ $targets.Add($childId)
378
+ $queue.Enqueue($childId)
379
+ }
326
380
  }
327
381
  }
328
382
  }
@@ -331,6 +385,27 @@ function Invoke-OpenCodeOnce {
331
385
  foreach ($targetId in @($targets)) {
332
386
  try { & taskkill.exe /F /T /PID $targetId 2>$null | Out-Null } catch {}
333
387
  }
388
+ } elseif (-not $dataAvailable) {
389
+ # Fail-closed: дерево построить нельзя (CIM/WMI упали, Get-Process
390
+ # и tasklist не дают родительских связей). Помечаем таймаут и
391
+ # убиваем всё дерево от корня, иначе задача переживёт лимит.
392
+ try { Set-Content -Path $Marker -Value "timeout" -Encoding UTF8 } catch {}
393
+ $listing = $false
394
+ try {
395
+ if (@(tasklist.exe /FO CSV /NH 2>$null).Count -gt 0) { $listing = $true }
396
+ } catch {}
397
+ if (-not $listing) {
398
+ try {
399
+ if (@(Get-Process -ErrorAction Stop).Count -gt 0) { $listing = $true }
400
+ } catch {}
401
+ }
402
+ try {
403
+ Start-Process -FilePath "taskkill.exe" -ArgumentList @("/F", "/T", "/PID", [string]$RootId) -WindowStyle Hidden -ErrorAction Stop
404
+ } catch {
405
+ if ($listing) {
406
+ try { & taskkill.exe /F /T /PID $RootId 2>$null | Out-Null } catch {}
407
+ }
408
+ }
334
409
  }
335
410
  } -ArgumentList $PID, $TimeoutSeconds, $timeoutMarker
336
411
  }
@@ -638,6 +713,14 @@ try {
638
713
  if (-not $script:skipMainTask) {
639
714
  $prompt = Get-Content -Path $PromptFile -Raw -Encoding UTF8
640
715
 
716
+ # W-1: запуск в одноразовом git worktree — сообщаем путь агенту.
717
+ # Переменную выставляет .cmd-обёртка после успешного создания копии.
718
+ if ($env:AGENT_STEWARD_WORKTREE) {
719
+ Write-Log "[agent-steward] Git worktree: $env:AGENT_STEWARD_WORKTREE (repo: $env:AGENT_STEWARD_WORKTREE_REPO)"
720
+ $worktreeContext = "[agent-steward] Рабочая директория запуска - одноразовый git worktree: " + $env:AGENT_STEWARD_WORKTREE + [Environment]::NewLine
721
+ $prompt = $worktreeContext + $prompt
722
+ }
723
+
641
724
  # CreateProcess ограничивает командную строку 32767 символами, а промпт
642
725
  # передаётся opencode аргументом ($opencodeArgs += $prompt). Явная ошибка
643
726
  # понятнее, чем обрезанный/отвергнутый запуск. Основная валидация — в schedule_task.
@@ -651,12 +734,22 @@ try {
651
734
  Get-Content -Path $EnvFile -Encoding UTF8 | ForEach-Object {
652
735
  $line = $_.Trim()
653
736
  if ($line -and -not $line.StartsWith("#") -and $line -match "^([A-Za-z_][A-Za-z0-9_]*)=(.*)$") {
654
- Set-Item -Path ("env:" + $matches[1]) -Value $matches[2]
737
+ $envKey = $matches[1]
738
+ $envValue = $matches[2]
739
+ # P2-21: секрет удалён/переименован — не подставляем литерал
740
+ # \${secret:...} агенту, а прерываем запуск с понятной ошибкой.
741
+ if ($envValue -match '\$\{secret:[^}]+\}') {
742
+ throw "Workspace '$WorkspaceName': переменная $envKey содержит неразрешённый секрет. Запуск отменён."
743
+ }
744
+ Set-Item -Path ("env:" + $envKey) -Value $envValue
655
745
  }
656
746
  }
657
747
  Write-Log "[agent-steward] Переменные окружения workspace загружены."
658
748
  } catch {
659
749
  Write-Log "[agent-steward] Не удалось загрузить env-файл workspace: $($_.Exception.Message)"
750
+ # P2-21: ошибка конфигурации секретов должна валить задачу,
751
+ # а не оставлять её работать без переменной окружения.
752
+ throw
660
753
  }
661
754
  }
662
755
 
@@ -689,50 +782,66 @@ try {
689
782
  $opencodeArgs += @("--continue")
690
783
  }
691
784
  if ($prompt) {
692
- $opencodeArgs += $prompt
785
+ # B11.1: «--» завершает разбор флагов opencode. Без него промпт,
786
+ # начинающийся с «-», CLI принял бы за неизвестный флаг.
787
+ $opencodeArgs += @("--", $prompt)
693
788
  }
694
789
 
695
790
  # Запускаем opencode и НАПРЯМУЮ направляем весь вывод (stdout + stderr) в лог.
696
791
  # Out-File -Append -Encoding utf8 пишет по мере поступления строк, поэтому
697
792
  # ответ ИИ появляется в GUI ещё до завершения задачи.
698
- # Hotfix 1.5.3.1: retryCount из схемы раньше нигде не применялся — теперь
699
- # неудачная попытка повторяется до RetryCount раз с паузой RetryDelaySeconds.
700
- $maxAttempts = 1 + [Math]::Max(0, $RetryCount)
701
- $attempt = 0
702
- while ($attempt -lt $maxAttempts) {
703
- $attempt++
704
- if ($attempt -gt 1) {
705
- $waitSeconds = [Math]::Max(0, $RetryDelaySeconds)
706
- Write-Log "[agent-steward] Повтор $($attempt - 1) из $($maxAttempts - 1) через $waitSeconds с..."
707
- if ($waitSeconds -gt 0) { Start-Sleep -Seconds $waitSeconds }
708
- $script:errorMessage = ""
709
- }
710
- $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
711
- if ($script:exitCode -eq 0) { break }
712
- # Таймаут повторять бессмысленно: каждая попытка снова съест весь лимит.
713
- if ($script:timedOut) { break }
714
- if ($attempt -lt $maxAttempts) {
715
- Write-Log "[agent-steward] Попытка $attempt завершилась с кодом $($script:exitCode)."
716
- }
717
- }
793
+ # B2: обёртка делает РОВНО одну попытку. Повторы — зона recorder'а
794
+ # (retryCount/retryDelay в БД), иначе на Windows получалось (1+N)^2
795
+ # запусков: N попыток внутри обёртки × N+1 запуск из recorder'а.
796
+ # Параметры -RetryCount/-RetryDelaySeconds принимаются, но игнорируются.
797
+ $script:exitCode = Invoke-OpenCodeOnce -CommandPath $opencodeCmd -Arguments $opencodeArgs
718
798
 
719
799
  # Quality Gate: проверочная команда выполняется ТОЛЬКО после успешного
720
800
  # завершения opencode run. Если ИИ упал — шлюз не запускаем.
721
801
  if ($QualityGate -and $script:exitCode -eq 0) {
722
- Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
723
- # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
724
- $gateCode = Invoke-HookScript -Command $QualityGate
725
-
726
- if ($gateCode -eq 124) {
727
- Write-Log "[agent-steward] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
728
- $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
729
- $script:exitCode = 1
730
- } elseif ($gateCode -ne 0) {
731
- Write-Log "[agent-steward] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
732
- $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
733
- $script:exitCode = 1
802
+ # G-1.2: перед запуском гейта сверяем его входы со snapshot'ом,
803
+ # снятым при создании задачи. При расхождении гейт НЕ выполняется.
804
+ $gateIntegrityOk = $false
805
+ if ($GateSnapshotFile -and (Test-Path -LiteralPath $GateSnapshotFile)) {
806
+ $gateIntegrityFile = Join-Path (Split-Path $RecorderFile -Parent) "gate-integrity.js"
807
+ if (Test-Path -LiteralPath $gateIntegrityFile) {
808
+ $verifyOutput = & node $gateIntegrityFile verify --snapshot "$GateSnapshotFile" --gate-file "$QualityGate" --prompt-file "$PromptFile" --timeout $GateTimeoutSeconds 2>&1
809
+ $verifyCode = $LASTEXITCODE
810
+ foreach ($line in $verifyOutput) { Write-Log "[agent-steward] $line" }
811
+ if ($verifyCode -eq 0) {
812
+ $gateIntegrityOk = $true
813
+ } else {
814
+ Write-Log "[agent-steward] ОШИБКА: целостность входов Quality Gate нарушена (snapshot mismatch)."
815
+ $script:errorMessage = "Quality Gate: целостность входов нарушена (snapshot mismatch)"
816
+ $script:exitCode = 1
817
+ }
818
+ } else {
819
+ Write-Log "[agent-steward] ОШИБКА: не найден помощник проверки целостности гейта."
820
+ $script:errorMessage = "Quality Gate: помощник проверки целостности не найден"
821
+ $script:exitCode = 1
822
+ }
734
823
  } else {
735
- Write-Log "[agent-steward] Quality Gate пройден."
824
+ Write-Log "[agent-steward] ОШИБКА: snapshot гейта отсутствует — запуск с гейтом невозможен."
825
+ $script:errorMessage = "Quality Gate: snapshot входов отсутствует"
826
+ $script:exitCode = 1
827
+ }
828
+
829
+ if ($gateIntegrityOk) {
830
+ Write-Log "[agent-steward] Запуск Quality Gate: $QualityGate"
831
+ # Тот же таймаут, что у хуков: зависший gate не должен держать lock.
832
+ $gateCode = Invoke-HookScript -Command $QualityGate
833
+
834
+ if ($gateCode -eq 124) {
835
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate превысил таймаут $GateTimeoutSeconds с и был остановлен."
836
+ $script:errorMessage = "Quality Gate: превышен таймаут $GateTimeoutSeconds с"
837
+ $script:exitCode = 1
838
+ } elseif ($gateCode -ne 0) {
839
+ Write-Log "[agent-steward] ОШИБКА: Quality Gate провален. Код возврата: $gateCode"
840
+ $script:errorMessage = "Quality Gate провален. Код возврата: $gateCode"
841
+ $script:exitCode = 1
842
+ } else {
843
+ Write-Log "[agent-steward] Quality Gate пройден."
844
+ }
736
845
  }
737
846
  }
738
847
 
@@ -925,12 +1034,18 @@ export async function writeWrapperCmd(
925
1034
  envFile?: string,
926
1035
  sessionMode?: "new" | "reuse" | "last",
927
1036
  sessionId?: string,
928
- retryCount?: number,
929
- retryDelaySeconds?: number,
930
1037
  gateTimeoutSeconds?: number,
931
1038
  permissionsConfig?: string,
932
1039
  policyMeta?: unknown,
933
1040
  sessionFile?: string,
1041
+ /** W-1: запустить задачу в одноразовом git worktree. */
1042
+ worktree?: boolean,
1043
+ /** Путь к dist/core/worktree-run.js (обязателен при worktree=true). */
1044
+ worktreeHelperFile?: string,
1045
+ /** W-3: guard-условия перед запуском opencode. */
1046
+ guards?: TaskGuards,
1047
+ /** Путь к dist/core/guard-run.js (обязателен при guards). */
1048
+ guardHelperFile?: string,
934
1049
  ): Promise<string> {
935
1050
  await fs.mkdir(WRAPPER_DIR, { recursive: true });
936
1051
  const cmdPath = path.join(WRAPPER_DIR, `run-${sanitizedName}.cmd`);
@@ -956,13 +1071,10 @@ export async function writeWrapperCmd(
956
1071
  : 300;
957
1072
  psArgs.push(`-GateTimeoutSeconds ${safeGateTimeout}`);
958
1073
 
959
- // Hotfix 1.5.3.1: ретраи. Параметр не передаём при 0 — обёртка по умолчанию
960
- // делает ровно одну попытку, как раньше.
961
- const safeRetryCount = Math.max(0, Math.floor(retryCount ?? 0));
962
- if (safeRetryCount > 0) {
963
- psArgs.push(`-RetryCount ${safeRetryCount}`);
964
- psArgs.push(`-RetryDelaySeconds ${Math.max(0, Math.floor(retryDelaySeconds ?? 0))}`);
965
- }
1074
+ // B2: ретраи сознательно не передаются в обёртку — единственный владелец
1075
+ // повторов это recorder (retryCount/retryDelay), иначе на Windows получается
1076
+ // (1+N)^2 запусков. Старые .cmd с -RetryCount продолжают работать: параметр
1077
+ // принимается, но игнорируется.
966
1078
 
967
1079
  if (logFile) {
968
1080
  psArgs.push(`-LogFile "${logFile}"`);
@@ -977,6 +1089,27 @@ export async function writeWrapperCmd(
977
1089
  // внутри неё больше не ломают однострочный вызов powershell.exe.
978
1090
  const gateFile = await writeHookFile(sanitizedName, "gate", qualityGate);
979
1091
  psArgs.push(`-QualityGate "${gateFile}"`);
1092
+
1093
+ // G-1.2: фиксируем входы гейта до первого запуска. Snapshot лежит в
1094
+ // PLUGIN_DIR, вне рабочей директории задачи.
1095
+ let prompt = "";
1096
+ let hook = qualityGate;
1097
+ try {
1098
+ prompt = await fs.readFile(promptFile, "utf8");
1099
+ } catch {
1100
+ // Промпт мог быть уже удалён — уникальность snapshot от этого не страдает.
1101
+ }
1102
+ try {
1103
+ hook = await fs.readFile(gateFile, "utf8");
1104
+ } catch {
1105
+ // Используем исходную команду, если прочитать хук не удалось.
1106
+ }
1107
+ const snapshotFile = createGateSnapshot(taskName, {
1108
+ gate: hook,
1109
+ prompt,
1110
+ gateTimeoutSeconds: safeGateTimeout,
1111
+ });
1112
+ psArgs.push(`-GateSnapshotFile "${snapshotFile}"`);
980
1113
  }
981
1114
 
982
1115
  if (model?.trim()) {
@@ -1108,8 +1241,85 @@ export async function writeWrapperCmd(
1108
1241
  lines.push("if \"%errorlevel%\"==\"3\" exit /b 0");
1109
1242
  }
1110
1243
 
1244
+ // W-1 (0.0.6): одноразовый git worktree. Создаётся после гейта расписания,
1245
+ // чтобы пропущенный тик не плодил рабочие копии. Ошибка создания — fail-closed:
1246
+ // задача не должна молча работать в основном дереве.
1247
+ let wtHelper = "";
1248
+ let wtRepo = "";
1249
+ let wtLogRedirect = "";
1250
+ if (worktree) {
1251
+ wtHelper = (worktreeHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1252
+ wtRepo = effectiveWorkdir.replace(/[\r\n"]+/g, "").trim();
1253
+ const safeTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1254
+ wtLogRedirect = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1255
+ const helperErr = logFile?.trim() ? `2>> "${logFile.trim()}"` : "";
1256
+ lines.push('set "AGENT_STEWARD_WORKTREE="');
1257
+ lines.push(
1258
+ `for /f "usebackq delims=" %%W in (\`node "${wtHelper}" --repo "${wtRepo}" --task "${safeTaskName}" ${helperErr}\`) do set "AGENT_STEWARD_WORKTREE=%%W"`,
1259
+ );
1260
+ lines.push("if not defined AGENT_STEWARD_WORKTREE (");
1261
+ lines.push(` echo [agent-steward] ERROR: git worktree creation failed ${wtLogRedirect}`);
1262
+ lines.push(" exit /b 1");
1263
+ lines.push(")");
1264
+ lines.push('cd /d "%AGENT_STEWARD_WORKTREE%"');
1265
+ lines.push(`set "AGENT_STEWARD_WORKTREE_REPO=${wtRepo}"`);
1266
+ }
1267
+
1268
+ // W-3 (0.0.6): guard-условия до запуска opencode. Код 4 — штатный skip,
1269
+ // любой другой ненулевой код — ошибка проверки; в обоих случаях opencode
1270
+ // не запускается. Созданный worktree сразу убираем, чтобы не оставлять мусор.
1271
+ if (guards) {
1272
+ const guardHelper = (guardHelperFile ?? "").replace(/[\r\n"]+/g, "").trim();
1273
+ const guardB64 = Buffer.from(JSON.stringify(guards), "utf8").toString("base64");
1274
+ const skipTaskName = taskName.replace(/[\r\n"]+/g, "").trim();
1275
+ const skipRecorder = (recorderFile ?? "").replace(/[\r\n"]+/g, "").trim();
1276
+ const skipReasonB64 = Buffer.from("guard conditions not met", "utf8").toString("base64");
1277
+ const guardLog = logFile?.trim() ? `1>> "${logFile.trim()}" 2>&1` : "";
1278
+ const guardLogAppend = logFile?.trim() ? `>> "${logFile.trim()}" 2>&1` : "";
1279
+ const pushWorktreeCleanup = () => {
1280
+ if (!worktree) return;
1281
+ lines.push(` cd /d "${wtRepo}"`);
1282
+ lines.push(
1283
+ ` node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`,
1284
+ );
1285
+ };
1286
+ lines.push(`node "${guardHelper}" --cwd "%CD%" --guards-b64 "${guardB64}" ${guardLog}`);
1287
+ lines.push('set "AGENT_STEWARD_GUARD_STATUS=%errorlevel%"');
1288
+ lines.push('if "%AGENT_STEWARD_GUARD_STATUS%"=="4" (');
1289
+ lines.push(` echo [agent-steward] guard: run skipped ${guardLogAppend}`);
1290
+ // W-4: пишем skipped в историю/метрики. Причина фиксированная (в базе),
1291
+ // подробности guard-проверки остаются в логе задачи.
1292
+ if (skipRecorder) {
1293
+ lines.push(
1294
+ ` node "${skipRecorder}" --skip "${skipTaskName}" "${skipReasonB64}" ${guardLogAppend}`,
1295
+ );
1296
+ }
1297
+ pushWorktreeCleanup();
1298
+ lines.push(" exit /b 0");
1299
+ lines.push(")");
1300
+ lines.push('if not "%AGENT_STEWARD_GUARD_STATUS%"=="0" (');
1301
+ lines.push(
1302
+ ` echo [agent-steward] ERROR: guard failed with code %AGENT_STEWARD_GUARD_STATUS% ${guardLogAppend}`,
1303
+ );
1304
+ pushWorktreeCleanup();
1305
+ lines.push(" exit /b 1");
1306
+ lines.push(")");
1307
+ }
1308
+
1111
1309
  lines.push(psArgs.join(" "));
1112
1310
 
1311
+ // W-2.1: удаляем одноразовый worktree после прогона при любом коде возврата.
1312
+ // Сначала выходим из него (Windows не даёт удалить текущий каталог), затем
1313
+ // возвращаем исходный код задачи — ошибка очистки не маскирует результат.
1314
+ if (worktree) {
1315
+ lines.push('set "AGENT_STEWARD_EXIT_CODE=%errorlevel%"');
1316
+ lines.push(`cd /d "${wtRepo}"`);
1317
+ lines.push(
1318
+ `node "${wtHelper}" cleanup --path "%AGENT_STEWARD_WORKTREE%" --repo "${wtRepo}" ${wtLogRedirect}`,
1319
+ );
1320
+ lines.push("exit /b %AGENT_STEWARD_EXIT_CODE%");
1321
+ }
1322
+
1113
1323
  await fs.writeFile(cmdPath, lines.join("\r\n"), "utf8");
1114
1324
  return cmdPath;
1115
1325
  }