agent-steward 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/CHANGELOG.md +134 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +52 -7
  4. package/ROADMAP-STRATEGY.md +21 -18
  5. package/ROADMAP.md +140 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +351 -0
  9. package/dist/core/execution.d.ts +203 -0
  10. package/dist/core/execution.d.ts.map +1 -0
  11. package/dist/core/execution.js +309 -0
  12. package/dist/core/gate-integrity.d.ts +35 -0
  13. package/dist/core/gate-integrity.d.ts.map +1 -0
  14. package/dist/core/gate-integrity.js +132 -0
  15. package/dist/core/git-trigger.d.ts.map +1 -1
  16. package/dist/core/git-trigger.js +14 -2
  17. package/dist/core/guard-run.d.ts +4 -0
  18. package/dist/core/guard-run.d.ts.map +1 -0
  19. package/dist/core/guard-run.js +101 -0
  20. package/dist/core/guard.d.ts +52 -0
  21. package/dist/core/guard.d.ts.map +1 -0
  22. package/dist/core/guard.js +362 -0
  23. package/dist/core/lock.d.ts +41 -0
  24. package/dist/core/lock.d.ts.map +1 -1
  25. package/dist/core/lock.js +141 -29
  26. package/dist/core/matrix.d.ts.map +1 -1
  27. package/dist/core/matrix.js +75 -15
  28. package/dist/core/mission.d.ts +83 -0
  29. package/dist/core/mission.d.ts.map +1 -0
  30. package/dist/core/mission.js +334 -0
  31. package/dist/core/pipeline-apply.d.ts +38 -0
  32. package/dist/core/pipeline-apply.d.ts.map +1 -0
  33. package/dist/core/pipeline-apply.js +117 -0
  34. package/dist/core/pipeline-io.d.ts +13 -0
  35. package/dist/core/pipeline-io.d.ts.map +1 -0
  36. package/dist/core/pipeline-io.js +64 -0
  37. package/dist/core/pipeline-map.d.ts +46 -0
  38. package/dist/core/pipeline-map.d.ts.map +1 -0
  39. package/dist/core/pipeline-map.js +196 -0
  40. package/dist/core/pipeline-spec.d.ts +109 -0
  41. package/dist/core/pipeline-spec.d.ts.map +1 -0
  42. package/dist/core/pipeline-spec.js +554 -0
  43. package/dist/core/ps-wrapper.d.ts +19 -2
  44. package/dist/core/ps-wrapper.d.ts.map +1 -1
  45. package/dist/core/ps-wrapper.js +250 -62
  46. package/dist/core/record-history.d.ts.map +1 -1
  47. package/dist/core/record-history.js +130 -29
  48. package/dist/core/router/rules.d.ts.map +1 -1
  49. package/dist/core/router/rules.js +6 -0
  50. package/dist/core/scheduler/linux.d.ts +8 -1
  51. package/dist/core/scheduler/linux.d.ts.map +1 -1
  52. package/dist/core/scheduler/linux.js +34 -9
  53. package/dist/core/scheduler/mac.d.ts +44 -2
  54. package/dist/core/scheduler/mac.d.ts.map +1 -1
  55. package/dist/core/scheduler/mac.js +126 -15
  56. package/dist/core/scheduler/windows.d.ts.map +1 -1
  57. package/dist/core/scheduler/windows.js +15 -12
  58. package/dist/core/structured-log.d.ts +7 -1
  59. package/dist/core/structured-log.d.ts.map +1 -1
  60. package/dist/core/worktree-run.d.ts +4 -0
  61. package/dist/core/worktree-run.d.ts.map +1 -0
  62. package/dist/core/worktree-run.js +164 -0
  63. package/dist/core/worktree.d.ts +115 -0
  64. package/dist/core/worktree.d.ts.map +1 -0
  65. package/dist/core/worktree.js +462 -0
  66. package/dist/core/wrappers/bash.d.ts +17 -0
  67. package/dist/core/wrappers/bash.d.ts.map +1 -1
  68. package/dist/core/wrappers/bash.js +175 -24
  69. package/dist/db/capability-repo.d.ts +43 -2
  70. package/dist/db/capability-repo.d.ts.map +1 -1
  71. package/dist/db/capability-repo.js +96 -11
  72. package/dist/db/history-repo.d.ts +38 -5
  73. package/dist/db/history-repo.d.ts.map +1 -1
  74. package/dist/db/history-repo.js +88 -25
  75. package/dist/db/metrics-repo.js +2 -2
  76. package/dist/db/recovery.d.ts.map +1 -1
  77. package/dist/db/recovery.js +5 -4
  78. package/dist/db/run-journal.d.ts +33 -5
  79. package/dist/db/run-journal.d.ts.map +1 -1
  80. package/dist/db/run-journal.js +78 -14
  81. package/dist/db/run-resume.d.ts +5 -0
  82. package/dist/db/run-resume.d.ts.map +1 -1
  83. package/dist/db/run-resume.js +9 -2
  84. package/dist/db/runs-repo.d.ts +19 -2
  85. package/dist/db/runs-repo.d.ts.map +1 -1
  86. package/dist/db/runs-repo.js +22 -6
  87. package/dist/db/schema.d.ts +2 -2
  88. package/dist/db/schema.d.ts.map +1 -1
  89. package/dist/db/schema.js +63 -2
  90. package/dist/history.d.ts +1 -1
  91. package/dist/history.d.ts.map +1 -1
  92. package/dist/i18n.d.ts +5 -0
  93. package/dist/i18n.d.ts.map +1 -1
  94. package/dist/i18n.js +11 -4
  95. package/dist/index.d.ts +136 -2
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +378 -14
  98. package/dist/notifications.d.ts +22 -0
  99. package/dist/notifications.d.ts.map +1 -1
  100. package/dist/notifications.js +36 -8
  101. package/dist/profiles.d.ts.map +1 -1
  102. package/dist/profiles.js +25 -4
  103. package/dist/rpc.d.ts +246 -0
  104. package/dist/rpc.d.ts.map +1 -1
  105. package/dist/rpc.js +117 -0
  106. package/dist/server.d.ts +15 -0
  107. package/dist/server.d.ts.map +1 -1
  108. package/dist/server.js +77 -18
  109. package/dist/settings.d.ts +2 -2
  110. package/dist/settings.d.ts.map +1 -1
  111. package/dist/settings.js +3 -3
  112. package/dist/shared/jobs-view.d.ts +1 -1
  113. package/dist/shared/jobs-view.d.ts.map +1 -1
  114. package/dist/shared/jobs-view.js +2 -0
  115. package/dist/task-transfer.d.ts +16 -0
  116. package/dist/task-transfer.d.ts.map +1 -1
  117. package/dist/task-transfer.js +16 -0
  118. package/docs/ARCHITECTURE.md +281 -65
  119. package/docs/COMPATIBILITY.md +2 -2
  120. package/docs/CONCEPT.md +18 -4
  121. package/docs/CROSS_PLATFORM.ru.md +20 -0
  122. package/docs/CROSS_PLATFORM.zh.md +18 -0
  123. package/docs/EXECUTION-LOOP.md +22 -7
  124. package/docs/FEATURES.md +65 -4
  125. package/docs/FEATURES.zh.md +52 -4
  126. package/docs/MIGRATION.md +2 -2
  127. package/docs/PIPELINE.md +293 -0
  128. package/docs/README.ru.md +42 -3
  129. package/docs/README.zh.md +43 -3
  130. package/docs/SAFETY.md +23 -3
  131. package/gui-experimental.cjs +9 -8
  132. package/locales/en.json +17 -1
  133. package/locales/ru.json +17 -1
  134. package/locales/zh.json +17 -1
  135. package/opencode.pipeline.yaml +35 -0
  136. package/package.json +23 -4
  137. package/scripts/test-home.mjs +83 -0
  138. package/src/cli.ts +412 -0
  139. package/src/core/dry-run.ts +2 -2
  140. package/src/core/execution.ts +538 -0
  141. package/src/core/file-watcher.ts +2 -2
  142. package/src/core/gate-integrity.ts +160 -0
  143. package/src/core/git-trigger.ts +18 -5
  144. package/src/core/guard-run.ts +119 -0
  145. package/src/core/guard.ts +431 -0
  146. package/src/core/lock.ts +178 -37
  147. package/src/core/matrix.ts +95 -50
  148. package/src/core/mission.ts +485 -0
  149. package/src/core/native-notify.ts +1 -1
  150. package/src/core/pipeline-apply.ts +158 -0
  151. package/src/core/pipeline-io.ts +79 -0
  152. package/src/core/pipeline-map.ts +264 -0
  153. package/src/core/pipeline-spec.ts +775 -0
  154. package/src/core/ps-wrapper.ts +263 -63
  155. package/src/core/record-history.ts +164 -77
  156. package/src/core/router/rules.ts +6 -0
  157. package/src/core/schedule-gate.ts +1 -1
  158. package/src/core/scheduler/at-fallback.ts +1 -1
  159. package/src/core/scheduler/linux.ts +40 -11
  160. package/src/core/scheduler/logs.ts +2 -2
  161. package/src/core/scheduler/mac.ts +174 -14
  162. package/src/core/scheduler/registry.ts +2 -2
  163. package/src/core/scheduler/windows.ts +19 -15
  164. package/src/core/secrets.ts +8 -8
  165. package/src/core/structured-log.ts +22 -5
  166. package/src/core/telegram.ts +2 -2
  167. package/src/core/triage-worker.ts +7 -7
  168. package/src/core/triage.ts +2 -2
  169. package/src/core/worktree-run.ts +199 -0
  170. package/src/core/worktree.ts +600 -0
  171. package/src/core/wrappers/bash.ts +190 -23
  172. package/src/db/capability-repo.ts +127 -10
  173. package/src/db/history-repo.ts +129 -22
  174. package/src/db/metrics-repo.ts +2 -2
  175. package/src/db/recovery.ts +5 -4
  176. package/src/db/run-journal.ts +100 -13
  177. package/src/db/run-resume.ts +17 -1
  178. package/src/db/runs-repo.ts +36 -6
  179. package/src/db/schema.ts +65 -2
  180. package/src/gui.tsx +177 -13
  181. package/src/history.ts +1 -1
  182. package/src/i18n.ts +12 -4
  183. package/src/index.ts +524 -4
  184. package/src/notifications.ts +38 -8
  185. package/src/profiles.ts +26 -4
  186. package/src/rpc.ts +128 -0
  187. package/src/server.ts +94 -18
  188. package/src/settings.ts +5 -5
  189. package/src/shared/jobs-view.ts +3 -1
  190. package/src/task-transfer.ts +31 -0
@@ -0,0 +1,431 @@
1
+ /**
2
+ * W-3 (0.0.6): guard-условия задачи.
3
+ *
4
+ * Guard — опциональный набор предварительных проверок перед запуском агента.
5
+ * Если проверка не проходит, прогон пропускается без запуска opencode:
6
+ * - semantic: файлы/ветка/изменённые пути в git-worktree;
7
+ * - command: произвольная shell-команда (exit 0 = можно запускать).
8
+ *
9
+ * Модуль не бросает исключения наружу: ошибка проверки трактуется как
10
+ * fail-closed (прогон пропускается).
11
+ */
12
+ import { execFile, spawn } from "node:child_process";
13
+ import fs from "node:fs/promises";
14
+ import path from "node:path";
15
+ import { promisify } from "node:util";
16
+ import { matchesAnyGlob, matchesGlob } from "./glob.js";
17
+
18
+ const execFileAsync = promisify(execFile);
19
+
20
+ /** Код выхода CLI-помощника: guard не пройден, прогон нужно пропустить. */
21
+ export const GUARD_SKIP_EXIT_CODE = 4;
22
+ /** Таймаут shell-guard по умолчанию. */
23
+ export const DEFAULT_GUARD_TIMEOUT_SECONDS = 60;
24
+ const MAX_COMMAND_LENGTH = 4000;
25
+ const MAX_TIMEOUT_SECONDS = 3600;
26
+ const MAX_LIST_ITEMS = 200;
27
+ const MAX_CAPTURED_OUTPUT = 16 * 1024;
28
+
29
+ export interface SemanticGuardConfig {
30
+ /** Все пути должны существовать (относительно рабочей директории). */
31
+ filesExist?: string[];
32
+ /** Ни один из путей не должен существовать. */
33
+ filesMissing?: string[];
34
+ /** Glob-шаблон текущей git-ветки, например `feature/*`. */
35
+ branch?: string;
36
+ /** Glob-шаблоны изменённых путей; достаточно совпадения хотя бы с одним. */
37
+ changedPaths?: string[];
38
+ /** Git-ref для сравнения изменений. По умолчанию `HEAD~1`. */
39
+ changedSince?: string;
40
+ }
41
+
42
+ export interface TaskGuards {
43
+ /** Shell-команда: exit 0 — запускать, любой другой код — пропустить. */
44
+ command?: string;
45
+ /** Таймаут shell-guard в секундах (1..3600, по умолчанию 60). */
46
+ timeoutSeconds?: number;
47
+ /** Семантические проверки рабочей директории. */
48
+ semantic?: SemanticGuardConfig;
49
+ }
50
+
51
+ export interface GuardEvaluation {
52
+ /** true — все проверки пройдены, задачу можно запускать. */
53
+ passed: boolean;
54
+ /** Причины пропуска (человекочитаемые). */
55
+ reasons: string[];
56
+ /** Выполненные проверки (для лога). */
57
+ checks: string[];
58
+ }
59
+
60
+ export type NormalizeGuardsResult =
61
+ | { ok: true; guards?: TaskGuards }
62
+ | { ok: false; error: string };
63
+
64
+ interface GitResult {
65
+ ok: boolean;
66
+ stdout: string;
67
+ stderr: string;
68
+ }
69
+
70
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
71
+ return typeof value === "object" && value !== null && !Array.isArray(value);
72
+ }
73
+
74
+ function normalizeRelativePath(raw: string): string | null {
75
+ const trimmed = raw.trim().replace(/\\/g, "/");
76
+ if (!trimmed || trimmed.includes("\0")) return null;
77
+ if (path.isAbsolute(trimmed) || /^[A-Za-z]:/.test(trimmed) || trimmed.startsWith("/")) {
78
+ return null;
79
+ }
80
+ const segments = trimmed.split("/");
81
+ if (segments.some((segment) => segment === ".." || segment === "." || segment === "")) {
82
+ return null;
83
+ }
84
+ return trimmed;
85
+ }
86
+
87
+ function readStringList(
88
+ raw: unknown,
89
+ label: string,
90
+ errors: string[],
91
+ ): string[] | undefined {
92
+ if (raw === undefined || raw === null) return undefined;
93
+ if (!Array.isArray(raw)) {
94
+ errors.push(`${label} должен быть массивом строк.`);
95
+ return undefined;
96
+ }
97
+ if (raw.length > MAX_LIST_ITEMS) {
98
+ errors.push(`${label}: не больше ${MAX_LIST_ITEMS} элементов.`);
99
+ return undefined;
100
+ }
101
+ const seen = new Set<string>();
102
+ const result: string[] = [];
103
+ for (const item of raw) {
104
+ if (typeof item !== "string") {
105
+ errors.push(`${label} должен содержать только строки.`);
106
+ return undefined;
107
+ }
108
+ const normalized = normalizeRelativePath(item);
109
+ if (!normalized) {
110
+ errors.push(
111
+ `${label}: путь «${item}» должен быть относительным и не содержать «.» или «..».`,
112
+ );
113
+ return undefined;
114
+ }
115
+ const key = process.platform === "win32" ? normalized.toLowerCase() : normalized;
116
+ if (seen.has(key)) continue;
117
+ seen.add(key);
118
+ result.push(normalized);
119
+ }
120
+ return result.length > 0 ? result : undefined;
121
+ }
122
+
123
+ function normalizeSemantic(
124
+ raw: unknown,
125
+ errors: string[],
126
+ ): SemanticGuardConfig | undefined {
127
+ if (raw === undefined || raw === null) return undefined;
128
+ if (!isPlainObject(raw)) {
129
+ errors.push("guards.semantic должен быть объектом.");
130
+ return undefined;
131
+ }
132
+ const allowed = new Set(["filesExist", "filesMissing", "branch", "changedPaths", "changedSince"]);
133
+ for (const key of Object.keys(raw)) {
134
+ if (!allowed.has(key)) errors.push(`guards.semantic: неизвестное поле «${key}».`);
135
+ }
136
+
137
+ const filesExist = readStringList(raw.filesExist, "guards.semantic.filesExist", errors);
138
+ const filesMissing = readStringList(raw.filesMissing, "guards.semantic.filesMissing", errors);
139
+ const changedPaths = readStringList(raw.changedPaths, "guards.semantic.changedPaths", errors);
140
+
141
+ let branch: string | undefined;
142
+ if (raw.branch !== undefined && raw.branch !== null) {
143
+ if (typeof raw.branch !== "string" || !raw.branch.trim()) {
144
+ errors.push("guards.semantic.branch должен быть непустой строкой.");
145
+ } else if (raw.branch.length > 200 || /[\u0000-\u001f\u007f]/.test(raw.branch)) {
146
+ errors.push("guards.semantic.branch слишком длинный или содержит управляющие символы.");
147
+ } else {
148
+ branch = raw.branch.trim();
149
+ }
150
+ }
151
+
152
+ let changedSince: string | undefined;
153
+ if (raw.changedSince !== undefined && raw.changedSince !== null) {
154
+ if (
155
+ typeof raw.changedSince !== "string" ||
156
+ !/^[A-Za-z0-9._/@{}~^-]+$/.test(raw.changedSince) ||
157
+ raw.changedSince.startsWith("-")
158
+ ) {
159
+ errors.push(
160
+ "guards.semantic.changedSince должен быть git-ref (буквы, цифры, . _ / @ { } ~ ^ -).",
161
+ );
162
+ } else {
163
+ changedSince = raw.changedSince;
164
+ }
165
+ }
166
+
167
+ if (!filesExist && !filesMissing && !branch && !changedPaths && !changedSince) {
168
+ return undefined;
169
+ }
170
+ return {
171
+ ...(filesExist ? { filesExist } : {}),
172
+ ...(filesMissing ? { filesMissing } : {}),
173
+ ...(branch ? { branch } : {}),
174
+ ...(changedPaths ? { changedPaths } : {}),
175
+ ...(changedSince ? { changedSince } : {}),
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Валидирует guard-конфигурацию из JSON/инструмента/импорта.
181
+ * Возвращает нормализованный объект либо ошибку; никогда не бросает.
182
+ */
183
+ export function normalizeTaskGuards(input: unknown): NormalizeGuardsResult {
184
+ if (input === undefined || input === null) return { ok: true };
185
+ if (!isPlainObject(input)) return { ok: false, error: "guards должен быть объектом." };
186
+
187
+ const errors: string[] = [];
188
+ const allowed = new Set(["command", "timeoutSeconds", "semantic"]);
189
+ for (const key of Object.keys(input)) {
190
+ if (!allowed.has(key)) errors.push(`guards: неизвестное поле «${key}».`);
191
+ }
192
+
193
+ let command: string | undefined;
194
+ if (input.command !== undefined && input.command !== null) {
195
+ if (typeof input.command !== "string") {
196
+ errors.push("guards.command должен быть строкой.");
197
+ } else {
198
+ const trimmed = input.command.trim();
199
+ if (!trimmed) {
200
+ errors.push("guards.command не должен быть пустым.");
201
+ } else if (trimmed.length > MAX_COMMAND_LENGTH) {
202
+ errors.push(`guards.command длиннее ${MAX_COMMAND_LENGTH} символов.`);
203
+ } else if (trimmed.includes("\0")) {
204
+ errors.push("guards.command содержит NUL-символ.");
205
+ } else {
206
+ command = trimmed;
207
+ }
208
+ }
209
+ }
210
+
211
+ let timeoutSeconds: number | undefined;
212
+ if (input.timeoutSeconds !== undefined && input.timeoutSeconds !== null) {
213
+ if (
214
+ typeof input.timeoutSeconds !== "number" ||
215
+ !Number.isInteger(input.timeoutSeconds) ||
216
+ input.timeoutSeconds < 1 ||
217
+ input.timeoutSeconds > MAX_TIMEOUT_SECONDS
218
+ ) {
219
+ errors.push(`guards.timeoutSeconds должен быть целым числом 1..${MAX_TIMEOUT_SECONDS}.`);
220
+ } else {
221
+ timeoutSeconds = input.timeoutSeconds;
222
+ }
223
+ }
224
+
225
+ const semantic = normalizeSemantic(input.semantic, errors);
226
+ if (errors.length > 0) return { ok: false, error: errors.join(" ") };
227
+
228
+ if (!command && !semantic) return { ok: true };
229
+ return {
230
+ ok: true,
231
+ guards: {
232
+ ...(command ? { command } : {}),
233
+ ...(timeoutSeconds ? { timeoutSeconds } : {}),
234
+ ...(semantic ? { semantic } : {}),
235
+ },
236
+ };
237
+ }
238
+
239
+ async function git(cwd: string, args: string[]): Promise<GitResult> {
240
+ try {
241
+ const { stdout, stderr } = await execFileAsync("git", ["-C", cwd, ...args], {
242
+ encoding: "utf8",
243
+ timeout: 30_000,
244
+ windowsHide: true,
245
+ maxBuffer: 1024 * 1024,
246
+ });
247
+ return { ok: true, stdout: String(stdout), stderr: String(stderr) };
248
+ } catch (error) {
249
+ const err = error as { stdout?: unknown; stderr?: unknown; message?: unknown };
250
+ return {
251
+ ok: false,
252
+ stdout: typeof err.stdout === "string" ? err.stdout : "",
253
+ stderr:
254
+ typeof err.stderr === "string"
255
+ ? err.stderr
256
+ : typeof err.message === "string"
257
+ ? err.message
258
+ : String(error),
259
+ };
260
+ }
261
+ }
262
+
263
+ function resolveInside(cwd: string, relative: string): string | null {
264
+ const base = path.resolve(cwd);
265
+ const target = path.resolve(base, relative);
266
+ const rel = path.relative(base, target);
267
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null;
268
+ return target;
269
+ }
270
+
271
+ async function lastOutputLine(command: string, cwd: string, timeoutSeconds: number): Promise<{
272
+ code: number | null;
273
+ timedOut: boolean;
274
+ output: string;
275
+ }> {
276
+ return await new Promise((resolve) => {
277
+ let output = "";
278
+ let settled = false;
279
+ let timedOut = false;
280
+ const child = spawn(command, {
281
+ cwd,
282
+ shell: true,
283
+ windowsHide: true,
284
+ stdio: ["ignore", "pipe", "pipe"],
285
+ env: { ...process.env, AGENT_STEWARD_GUARD: "1" },
286
+ });
287
+
288
+ const finish = (code: number | null) => {
289
+ if (settled) return;
290
+ settled = true;
291
+ if (timer) clearTimeout(timer);
292
+ resolve({ code, timedOut, output });
293
+ };
294
+
295
+ const append = (chunk: Buffer | string) => {
296
+ if (output.length >= MAX_CAPTURED_OUTPUT) return;
297
+ output += chunk.toString().slice(0, MAX_CAPTURED_OUTPUT - output.length);
298
+ };
299
+ child.stdout?.on("data", append);
300
+ child.stderr?.on("data", append);
301
+
302
+ const timer = setTimeout(() => {
303
+ timedOut = true;
304
+ try {
305
+ child.kill();
306
+ } catch {
307
+ // ignore
308
+ }
309
+ finish(null);
310
+ }, timeoutSeconds * 1000);
311
+ timer.unref?.();
312
+
313
+ child.on("error", (error) => {
314
+ output += String(error);
315
+ finish(null);
316
+ });
317
+ child.on("close", (code) => finish(code));
318
+ });
319
+ }
320
+
321
+ /**
322
+ * Выполняет guard-проверки в указанной рабочей директории.
323
+ * Никогда не бросает: любая ошибка означает «пропустить».
324
+ */
325
+ export async function evaluateGuards(
326
+ guards: TaskGuards,
327
+ options: { cwd: string },
328
+ ): Promise<GuardEvaluation> {
329
+ const checks: string[] = [];
330
+ const reasons: string[] = [];
331
+ const cwd = path.resolve(options.cwd);
332
+
333
+ const fail = (reason: string): GuardEvaluation => {
334
+ reasons.push(reason);
335
+ return { passed: false, reasons, checks };
336
+ };
337
+
338
+ try {
339
+ const semantic = guards.semantic;
340
+ if (semantic) {
341
+ if (semantic.filesExist) {
342
+ for (const relative of semantic.filesExist) {
343
+ const target = resolveInside(cwd, relative);
344
+ if (!target) return fail(`файл вне рабочей директории: ${relative}`);
345
+ try {
346
+ await fs.access(target);
347
+ checks.push(`filesExist: ${relative}`);
348
+ } catch {
349
+ return fail(`нет файла: ${relative}`);
350
+ }
351
+ }
352
+ }
353
+
354
+ if (semantic.filesMissing) {
355
+ for (const relative of semantic.filesMissing) {
356
+ const target = resolveInside(cwd, relative);
357
+ if (!target) return fail(`файл вне рабочей директории: ${relative}`);
358
+ try {
359
+ await fs.access(target);
360
+ return fail(`файл не должен существовать: ${relative}`);
361
+ } catch {
362
+ checks.push(`filesMissing: ${relative}`);
363
+ }
364
+ }
365
+ }
366
+
367
+ if (semantic.branch) {
368
+ const result = await git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
369
+ if (!result.ok) return fail(`не удалось определить git-ветку: ${result.stderr.trim()}`);
370
+ const branch = result.stdout.trim();
371
+ if (!branch || branch === "HEAD") return fail("git-ветка не определена (detached HEAD)");
372
+ if (!matchesGlob(branch, semantic.branch)) {
373
+ return fail(`ветка «${branch}» не соответствует «${semantic.branch}»`);
374
+ }
375
+ checks.push(`branch: ${branch}`);
376
+ }
377
+
378
+ if (semantic.changedPaths) {
379
+ const base = semantic.changedSince ?? "HEAD~1";
380
+ let diff = await git(cwd, ["diff", "--name-only", `${base}..HEAD`]);
381
+ if (!diff.ok) {
382
+ // Корневой коммит: у HEAD~1 нет родителя.
383
+ diff = await git(cwd, ["show", "--name-only", "--format=", "HEAD"]);
384
+ }
385
+ if (!diff.ok) {
386
+ return fail(`не удалось получить изменённые пути: ${diff.stderr.trim()}`);
387
+ }
388
+ const changed = diff.stdout
389
+ .split(/\r?\n/)
390
+ .map((line) => line.trim())
391
+ .filter(Boolean)
392
+ .map((line) => line.replace(/\\/g, "/"));
393
+ const matched = changed.find((file) => matchesAnyGlob(file, semantic.changedPaths));
394
+ if (!matched) {
395
+ return fail(
396
+ `нет изменённых путей по шаблонам «${semantic.changedPaths.join(", ")}» (${base})`,
397
+ );
398
+ }
399
+ checks.push(`changedPaths: ${matched}`);
400
+ }
401
+ }
402
+
403
+ if (guards.command) {
404
+ const timeout = guards.timeoutSeconds ?? DEFAULT_GUARD_TIMEOUT_SECONDS;
405
+ const result = await lastOutputLine(guards.command, cwd, timeout);
406
+ const lastLine =
407
+ result.output
408
+ .split(/\r?\n/)
409
+ .map((line) => line.trim())
410
+ .filter(Boolean)
411
+ .pop()
412
+ ?.slice(0, 300) ?? "";
413
+ if (result.timedOut) {
414
+ return fail(`shell guard превысил таймаут ${timeout} с`);
415
+ }
416
+ if (result.code !== 0) {
417
+ const suffix = lastLine ? `: ${lastLine}` : "";
418
+ return fail(
419
+ result.code === null
420
+ ? `shell guard не выполнился${suffix}`
421
+ : `shell guard завершился с кодом ${result.code}${suffix}`,
422
+ );
423
+ }
424
+ checks.push("command: exit 0");
425
+ }
426
+ } catch (error) {
427
+ return fail(`ошибка проверки guard: ${error instanceof Error ? error.message : String(error)}`);
428
+ }
429
+
430
+ return { passed: reasons.length === 0, reasons, checks };
431
+ }