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
@@ -0,0 +1,554 @@
1
+ /**
2
+ * Спринт 32 (Pipeline-as-code, 0.0.5): формат `opencode.pipeline.yaml`
3
+ * и его валидация.
4
+ *
5
+ * Pipeline описывает DAG шагов декларативно, чтобы его можно было
6
+ * ревьюить в PR. Модуль намеренно не трогает БД и планировщик ОС:
7
+ * здесь только типы и чистая валидация. Маппинг в TaskDefinition и
8
+ * идемпотентный apply — задачи P2-33.T2.
9
+ */
10
+ import { isValidIanaTimeZone, normalizeCron, parseCron, validateLaunchWindow, } from "./schedule-v2.js";
11
+ import { validateModelId, validateTaskName } from "../types.js";
12
+ import { normalizeTaskGuards } from "./guard.js";
13
+ /** Версия формата, которую понимает этот модуль. */
14
+ export const PIPELINE_VERSION = 1;
15
+ /** Защита от случайно огромного файла: шагов в одном pipeline. */
16
+ export const MAX_PIPELINE_STEPS = 200;
17
+ /** Максимальная длина id шага (id попадает в имена задач и логи). */
18
+ export const MAX_STEP_ID_LENGTH = 64;
19
+ const TRIGGERS = new Set([
20
+ "cron",
21
+ "file",
22
+ "git",
23
+ "mcp-event",
24
+ "once",
25
+ "dag",
26
+ ]);
27
+ const MATRIX_STRATEGIES = new Set(["parallel", "sequential"]);
28
+ const MATRIX_FAILURE_MODES = new Set(["continue", "stop"]);
29
+ const MATRIX_AGGREGATIONS = new Set(["summary", "per-task"]);
30
+ const WINDOW_POLICIES = new Set(["skip", "postpone", "run"]);
31
+ const TOP_LEVEL_KEYS = new Set(["version", "name", "description", "defaults", "steps"]);
32
+ const DEFAULTS_KEYS = new Set([
33
+ "schedule",
34
+ "trigger",
35
+ "model",
36
+ "priority",
37
+ "timeoutSeconds",
38
+ "workingDirectory",
39
+ "retryCount",
40
+ "retryDelay",
41
+ "allowedTools",
42
+ "deniedTools",
43
+ "timezone",
44
+ ]);
45
+ const STEP_KEYS = new Set([
46
+ "id",
47
+ "name",
48
+ "prompt",
49
+ "needs",
50
+ "schedule",
51
+ "trigger",
52
+ "runAt",
53
+ "model",
54
+ "priority",
55
+ "timeoutSeconds",
56
+ "workingDirectory",
57
+ "workspaceId",
58
+ "retryCount",
59
+ "retryDelay",
60
+ "qualityGate",
61
+ "beforeScript",
62
+ "afterScript",
63
+ "guards",
64
+ "allowedTools",
65
+ "deniedTools",
66
+ "matrix",
67
+ "timezone",
68
+ "notBefore",
69
+ "notAfter",
70
+ "activeDays",
71
+ "windowPolicy",
72
+ ]);
73
+ const MATRIX_KEYS = new Set([
74
+ "workspaces",
75
+ "workspaceIds",
76
+ "strategy",
77
+ "failureMode",
78
+ "aggregation",
79
+ "concurrency",
80
+ "createAggregator",
81
+ ]);
82
+ const STEP_ID_RE = /^[\p{L}\p{N}][\p{L}\p{N}_.-]*$/u;
83
+ const PIPELINE_NAME_RE = /^[\p{L}\p{N}_. -]+$/u;
84
+ function isPlainObject(value) {
85
+ return typeof value === "object" && value !== null && !Array.isArray(value);
86
+ }
87
+ function isNonEmptyString(value) {
88
+ return typeof value === "string" && value.trim().length > 0;
89
+ }
90
+ function isInteger(value) {
91
+ return typeof value === "number" && Number.isInteger(value);
92
+ }
93
+ /** Имя задачи по умолчанию для шага pipeline. */
94
+ export function pipelineStepTaskName(pipelineName, stepId) {
95
+ return `${pipelineName.trim()} ${stepId.trim()}`;
96
+ }
97
+ /**
98
+ * Валидирует произвольный разобранный YAML.
99
+ *
100
+ * Не бросает исключений: все проблемы складываются в `errors`/`warnings`,
101
+ * чтобы CLI мог напечатать их списком и вернуть exit code.
102
+ */
103
+ export function validatePipelineSpec(input) {
104
+ const errors = [];
105
+ const warnings = [];
106
+ const err = (path, message) => {
107
+ errors.push({ path, message });
108
+ };
109
+ const warn = (path, message) => {
110
+ warnings.push({ path, message });
111
+ };
112
+ if (!isPlainObject(input)) {
113
+ err("$", "Ожидался объект pipeline (корень YAML-документа).");
114
+ return { ok: false, errors, warnings };
115
+ }
116
+ for (const key of Object.keys(input)) {
117
+ if (!TOP_LEVEL_KEYS.has(key)) {
118
+ warn(key, "Неизвестное поле pipeline — будет проигнорировано.");
119
+ }
120
+ }
121
+ if (input.version !== PIPELINE_VERSION) {
122
+ err("version", `Поддерживается только version: ${PIPELINE_VERSION} (получено: ${JSON.stringify(input.version)}).`);
123
+ }
124
+ let pipelineName = null;
125
+ if (!isNonEmptyString(input.name)) {
126
+ err("name", "Укажите непустое имя pipeline.");
127
+ }
128
+ else {
129
+ const name = input.name.trim();
130
+ if (name.length > 120) {
131
+ err("name", `Имя pipeline слишком длинное (${name.length} символов, максимум 120).`);
132
+ }
133
+ else if (/[\u0000-\u001f\u007f]/.test(name)) {
134
+ err("name", "Имя pipeline не должно содержать управляющие символы.");
135
+ }
136
+ else if (!PIPELINE_NAME_RE.test(name)) {
137
+ err("name", "Имя pipeline может содержать буквы, цифры, пробел, «_», «-» и «.».");
138
+ }
139
+ else {
140
+ pipelineName = name;
141
+ }
142
+ }
143
+ if (input.description !== undefined && typeof input.description !== "string") {
144
+ err("description", "description должен быть строкой.");
145
+ }
146
+ let defaults = null;
147
+ if (input.defaults !== undefined) {
148
+ if (!isPlainObject(input.defaults)) {
149
+ err("defaults", "defaults должен быть объектом.");
150
+ }
151
+ else {
152
+ defaults = input.defaults;
153
+ validateDefaults(defaults, err, warn);
154
+ }
155
+ }
156
+ const steps = input.steps;
157
+ if (!Array.isArray(steps)) {
158
+ err("steps", "steps должен быть массивом шагов.");
159
+ return { ok: false, errors, warnings };
160
+ }
161
+ if (steps.length === 0) {
162
+ err("steps", "Pipeline должен содержать хотя бы один шаг.");
163
+ }
164
+ if (steps.length > MAX_PIPELINE_STEPS) {
165
+ err("steps", `Слишком много шагов: ${steps.length}, максимум ${MAX_PIPELINE_STEPS}.`);
166
+ }
167
+ const idToIndex = new Map();
168
+ const usedTaskNames = new Map();
169
+ const needsByStep = [];
170
+ steps.forEach((raw, index) => {
171
+ const path = `steps[${index}]`;
172
+ if (!isPlainObject(raw)) {
173
+ err(path, "Шаг должен быть объектом.");
174
+ return;
175
+ }
176
+ for (const key of Object.keys(raw)) {
177
+ if (!STEP_KEYS.has(key)) {
178
+ warn(`${path}.${key}`, "Неизвестное поле шага — будет проигнорировано.");
179
+ }
180
+ }
181
+ const rawId = raw.id;
182
+ let stepId = null;
183
+ if (!isNonEmptyString(rawId)) {
184
+ err(`${path}.id`, "Укажите непустой id шага.");
185
+ }
186
+ else {
187
+ const id = rawId.trim();
188
+ if (id.length > MAX_STEP_ID_LENGTH) {
189
+ err(`${path}.id`, `id шага слишком длинный (${id.length}, максимум ${MAX_STEP_ID_LENGTH}).`);
190
+ }
191
+ else if (!STEP_ID_RE.test(id)) {
192
+ err(`${path}.id`, "id шага может содержать буквы, цифры, «_», «-» и «.» и должен начинаться с буквы или цифры.");
193
+ }
194
+ else {
195
+ const key = id.toLowerCase();
196
+ const previous = idToIndex.get(key);
197
+ if (previous !== undefined) {
198
+ err(`${path}.id`, `id «${id}» уже используется шагом steps[${previous}].`);
199
+ }
200
+ else {
201
+ idToIndex.set(key, index);
202
+ stepId = id;
203
+ }
204
+ }
205
+ }
206
+ if (!isNonEmptyString(raw.prompt)) {
207
+ err(`${path}.prompt`, "Укажите непустой prompt шага.");
208
+ }
209
+ // Имя задачи: явное или автоматическое. Планировщик сравнивает имена
210
+ // без учёта регистра, поэтому коллизии проверяем по lower-case.
211
+ let effectiveName = null;
212
+ if (raw.name !== undefined) {
213
+ if (!isNonEmptyString(raw.name)) {
214
+ err(`${path}.name`, "name должен быть непустой строкой.");
215
+ }
216
+ else {
217
+ const nameError = validateTaskName(raw.name);
218
+ if (nameError) {
219
+ err(`${path}.name`, nameError);
220
+ }
221
+ else {
222
+ effectiveName = raw.name.trim();
223
+ }
224
+ }
225
+ }
226
+ else if (pipelineName && stepId) {
227
+ const candidate = pipelineStepTaskName(pipelineName, stepId);
228
+ const nameError = validateTaskName(candidate);
229
+ if (nameError) {
230
+ err(`${path}.name`, `Автоматическое имя задачи «${candidate}» недопустимо: ${nameError}`);
231
+ }
232
+ else {
233
+ effectiveName = candidate;
234
+ }
235
+ }
236
+ if (effectiveName) {
237
+ const key = effectiveName.toLowerCase();
238
+ const previous = usedTaskNames.get(key);
239
+ if (previous !== undefined) {
240
+ err(`${path}.name`, `Имя задачи «${effectiveName}» уже используется шагом steps[${previous}].`);
241
+ }
242
+ else {
243
+ usedTaskNames.set(key, index);
244
+ }
245
+ }
246
+ const needs = [];
247
+ if (raw.needs !== undefined) {
248
+ if (!Array.isArray(raw.needs)) {
249
+ err(`${path}.needs`, "needs должен быть массивом id шагов.");
250
+ }
251
+ else {
252
+ const seen = new Set();
253
+ raw.needs.forEach((need, needIndex) => {
254
+ if (!isNonEmptyString(need)) {
255
+ err(`${path}.needs[${needIndex}]`, "needs должен содержать непустые id шагов.");
256
+ return;
257
+ }
258
+ const trimmed = need.trim();
259
+ const key = trimmed.toLowerCase();
260
+ if (seen.has(key)) {
261
+ err(`${path}.needs[${needIndex}]`, `Зависимость «${trimmed}» указана повторно.`);
262
+ return;
263
+ }
264
+ seen.add(key);
265
+ if (stepId && key === stepId.toLowerCase()) {
266
+ err(`${path}.needs[${needIndex}]`, "Шаг не может зависеть от самого себя.");
267
+ return;
268
+ }
269
+ needs.push(trimmed);
270
+ });
271
+ }
272
+ }
273
+ if (stepId) {
274
+ needsByStep.push({ path, id: stepId, needs });
275
+ }
276
+ const stepTrigger = raw.trigger ?? defaults?.trigger ?? "cron";
277
+ const hasSchedule = raw.schedule !== undefined || defaults?.schedule !== undefined;
278
+ validateTriggerAndSchedule(path, stepTrigger, raw.schedule ?? defaults?.schedule, raw.runAt, needs.length, hasSchedule, err, warn);
279
+ validateModelField(raw.model, `${path}.model`, err);
280
+ validateOptionalInteger(raw.priority, `${path}.priority`, 0, 10, err);
281
+ validateOptionalInteger(raw.timeoutSeconds, `${path}.timeoutSeconds`, 1, undefined, err);
282
+ validateOptionalInteger(raw.retryCount, `${path}.retryCount`, 0, undefined, err);
283
+ validateOptionalInteger(raw.retryDelay, `${path}.retryDelay`, 0, undefined, err);
284
+ validateOptionalString(raw.workingDirectory, `${path}.workingDirectory`, err);
285
+ validateOptionalString(raw.workspaceId, `${path}.workspaceId`, err);
286
+ validateOptionalString(raw.qualityGate, `${path}.qualityGate`, err);
287
+ validateOptionalString(raw.beforeScript, `${path}.beforeScript`, err);
288
+ validateOptionalString(raw.afterScript, `${path}.afterScript`, err);
289
+ if (raw.guards !== undefined) {
290
+ const guardsResult = normalizeTaskGuards(raw.guards);
291
+ if (!guardsResult.ok)
292
+ err(`${path}.guards`, guardsResult.error);
293
+ }
294
+ validateTools(raw.allowedTools, `${path}.allowedTools`, true, err);
295
+ validateTools(raw.deniedTools, `${path}.deniedTools`, false, err);
296
+ if (raw.matrix !== undefined) {
297
+ validateMatrix(raw.matrix, `${path}.matrix`, raw.workspaceId, err, warn);
298
+ }
299
+ if (raw.timezone !== undefined) {
300
+ if (!isNonEmptyString(raw.timezone) || !isValidIanaTimeZone(raw.timezone)) {
301
+ err(`${path}.timezone`, `Неизвестный IANA-часовой пояс: ${JSON.stringify(raw.timezone)}.`);
302
+ }
303
+ }
304
+ const windowError = validateLaunchWindow(typeof raw.notBefore === "string" ? raw.notBefore : null, typeof raw.notAfter === "string" ? raw.notAfter : null);
305
+ if (windowError) {
306
+ err(`${path}.notBefore`, windowError);
307
+ }
308
+ if (raw.activeDays !== undefined) {
309
+ if (!Array.isArray(raw.activeDays) ||
310
+ raw.activeDays.some((day) => !isInteger(day) || day < 0 || day > 6)) {
311
+ err(`${path}.activeDays`, "activeDays — массив целых чисел 0…6 (0 = воскресенье).");
312
+ }
313
+ }
314
+ if (raw.windowPolicy !== undefined && !WINDOW_POLICIES.has(String(raw.windowPolicy))) {
315
+ err(`${path}.windowPolicy`, "windowPolicy: skip | postpone | run.");
316
+ }
317
+ });
318
+ // Ссылки на несуществующие шаги.
319
+ for (const entry of needsByStep) {
320
+ entry.needs.forEach((need, needIndex) => {
321
+ if (!idToIndex.has(need.toLowerCase())) {
322
+ err(`${entry.path}.needs[${needIndex}]`, `Шаг «${need}» не найден среди id шагов pipeline.`);
323
+ }
324
+ });
325
+ }
326
+ const cycle = findDependencyCycle(needsByStep);
327
+ if (cycle) {
328
+ err("steps", `Циклическая зависимость: ${cycle.join(" → ")}.`);
329
+ }
330
+ return { ok: errors.length === 0, errors, warnings };
331
+ }
332
+ function validateDefaults(defaults, err, warn) {
333
+ for (const key of Object.keys(defaults)) {
334
+ if (!DEFAULTS_KEYS.has(key)) {
335
+ warn(`defaults.${key}`, "Неизвестное поле defaults — будет проигнорировано.");
336
+ }
337
+ }
338
+ if (defaults.schedule !== undefined) {
339
+ validateCron(defaults.schedule, "defaults.schedule", err);
340
+ }
341
+ if (defaults.trigger !== undefined) {
342
+ if (!TRIGGERS.has(String(defaults.trigger))) {
343
+ err("defaults.trigger", "trigger: cron | file | git | mcp-event | once | dag.");
344
+ }
345
+ else if (defaults.trigger === "dag" || defaults.trigger === "once") {
346
+ warn("defaults.trigger", `trigger: ${String(defaults.trigger)} в defaults применяется ко всем шагам — обычно его задают на шаге.`);
347
+ }
348
+ }
349
+ validateModelField(defaults.model, "defaults.model", err);
350
+ validateOptionalInteger(defaults.priority, "defaults.priority", 0, 10, err);
351
+ validateOptionalInteger(defaults.timeoutSeconds, "defaults.timeoutSeconds", 1, undefined, err);
352
+ validateOptionalInteger(defaults.retryCount, "defaults.retryCount", 0, undefined, err);
353
+ validateOptionalInteger(defaults.retryDelay, "defaults.retryDelay", 0, undefined, err);
354
+ validateOptionalString(defaults.workingDirectory, "defaults.workingDirectory", err);
355
+ validateTools(defaults.allowedTools, "defaults.allowedTools", true, err);
356
+ validateTools(defaults.deniedTools, "defaults.deniedTools", false, err);
357
+ if (defaults.timezone !== undefined) {
358
+ if (!isNonEmptyString(defaults.timezone) || !isValidIanaTimeZone(defaults.timezone)) {
359
+ err("defaults.timezone", `Неизвестный IANA-часовой пояс: ${JSON.stringify(defaults.timezone)}.`);
360
+ }
361
+ }
362
+ }
363
+ function validateTriggerAndSchedule(path, trigger, schedule, runAt, needsCount, hasSchedule, err, warn) {
364
+ if (!TRIGGERS.has(String(trigger))) {
365
+ err(`${path}.trigger`, "trigger: cron | file | git | mcp-event | once | dag.");
366
+ return;
367
+ }
368
+ if (trigger === "dag") {
369
+ if (needsCount === 0) {
370
+ err(`${path}.trigger`, "trigger: dag допустим только для шага с непустым needs — иначе шаг никогда не запустится.");
371
+ }
372
+ if (schedule !== undefined) {
373
+ warn(`${path}.schedule`, "schedule игнорируется при trigger: dag.");
374
+ }
375
+ return;
376
+ }
377
+ if (trigger === "once") {
378
+ if (!isNonEmptyString(runAt)) {
379
+ err(`${path}.runAt`, "Для trigger: once нужен runAt (ISO-8601).");
380
+ }
381
+ else if (Number.isNaN(Date.parse(runAt))) {
382
+ err(`${path}.runAt`, "runAt должен быть корректной ISO-8601 датой.");
383
+ }
384
+ if (schedule !== undefined) {
385
+ warn(`${path}.schedule`, "schedule игнорируется при trigger: once.");
386
+ }
387
+ return;
388
+ }
389
+ if (trigger === "cron") {
390
+ if (!hasSchedule) {
391
+ err(`${path}.schedule`, "Для trigger: cron нужен schedule (в шаге или defaults.schedule); для DAG-шага без своего cron используйте trigger: dag.");
392
+ }
393
+ else if (schedule !== undefined) {
394
+ validateCron(schedule, `${path}.schedule`, err);
395
+ }
396
+ return;
397
+ }
398
+ // file / git / mcp-event: расписание не требуется.
399
+ if (schedule !== undefined) {
400
+ warn(`${path}.schedule`, `schedule игнорируется при trigger: ${String(trigger)}.`);
401
+ }
402
+ }
403
+ function validateCron(value, path, err) {
404
+ if (!isNonEmptyString(value)) {
405
+ err(path, "schedule должен быть непустой cron-строкой.");
406
+ return;
407
+ }
408
+ try {
409
+ parseCron(normalizeCron(value));
410
+ }
411
+ catch (error) {
412
+ const message = error instanceof Error ? error.message : String(error);
413
+ err(path, `Некорректный cron «${value}»: ${message}`);
414
+ }
415
+ }
416
+ function validateModelField(value, path, err) {
417
+ if (value === undefined)
418
+ return;
419
+ if (!isNonEmptyString(value)) {
420
+ err(path, "model должен быть непустой строкой вида provider/model.");
421
+ return;
422
+ }
423
+ const modelError = validateModelId(value);
424
+ if (modelError) {
425
+ err(path, modelError);
426
+ }
427
+ }
428
+ function validateOptionalString(value, path, err) {
429
+ if (value !== undefined && typeof value !== "string") {
430
+ err(path, "Ожидалась строка.");
431
+ }
432
+ }
433
+ function validateOptionalInteger(value, path, min, max, err) {
434
+ if (value === undefined)
435
+ return;
436
+ if (!isInteger(value)) {
437
+ err(path, "Ожидалось целое число.");
438
+ return;
439
+ }
440
+ if (value < min) {
441
+ err(path, `Значение должно быть не меньше ${min}.`);
442
+ }
443
+ if (max !== undefined && value > max) {
444
+ err(path, `Значение должно быть не больше ${max}.`);
445
+ }
446
+ }
447
+ function validateTools(value, path, requireNonEmpty, err) {
448
+ if (value === undefined)
449
+ return;
450
+ if (!Array.isArray(value)) {
451
+ err(path, "Ожидался массив имён инструментов.");
452
+ return;
453
+ }
454
+ if (requireNonEmpty && value.length === 0) {
455
+ err(path, "Пустой список allowedTools запрещён: «разрешено ничего» не имеет смысла.");
456
+ return;
457
+ }
458
+ value.forEach((tool, index) => {
459
+ if (!isNonEmptyString(tool)) {
460
+ err(`${path}[${index}]`, "Имя инструмента должно быть непустой строкой.");
461
+ }
462
+ });
463
+ }
464
+ function validateMatrix(value, path, workspaceId, err, warn) {
465
+ if (!isPlainObject(value)) {
466
+ err(path, "matrix должен быть объектом.");
467
+ return;
468
+ }
469
+ for (const key of Object.keys(value)) {
470
+ if (!MATRIX_KEYS.has(key)) {
471
+ warn(`${path}.${key}`, "Неизвестное поле matrix — будет проигнорировано.");
472
+ }
473
+ }
474
+ if (value.workspaces !== undefined && value.workspaceIds !== undefined) {
475
+ err(path, "Укажите что-то одно: matrix.workspaces или matrix.workspaceIds.");
476
+ }
477
+ const workspaces = value.workspaces ?? value.workspaceIds;
478
+ if (!Array.isArray(workspaces) || workspaces.length === 0) {
479
+ err(`${path}.workspaces`, "matrix.workspaces — непустой массив workspace.");
480
+ }
481
+ else {
482
+ const seen = new Set();
483
+ workspaces.forEach((workspace, index) => {
484
+ if (!isNonEmptyString(workspace)) {
485
+ err(`${path}.workspaces[${index}]`, "Ожидалось непустое имя/id workspace.");
486
+ return;
487
+ }
488
+ const key = workspace.trim().toLowerCase();
489
+ if (seen.has(key)) {
490
+ err(`${path}.workspaces[${index}]`, `Workspace «${workspace}» указан повторно.`);
491
+ }
492
+ seen.add(key);
493
+ });
494
+ }
495
+ if (value.strategy !== undefined && !MATRIX_STRATEGIES.has(String(value.strategy))) {
496
+ err(`${path}.strategy`, "strategy: parallel | sequential.");
497
+ }
498
+ if (value.failureMode !== undefined && !MATRIX_FAILURE_MODES.has(String(value.failureMode))) {
499
+ err(`${path}.failureMode`, "failureMode: continue | stop.");
500
+ }
501
+ if (value.aggregation !== undefined && !MATRIX_AGGREGATIONS.has(String(value.aggregation))) {
502
+ err(`${path}.aggregation`, "aggregation: summary | per-task.");
503
+ }
504
+ validateOptionalInteger(value.concurrency, `${path}.concurrency`, 1, undefined, err);
505
+ if (value.createAggregator !== undefined && typeof value.createAggregator !== "boolean") {
506
+ err(`${path}.createAggregator`, "createAggregator должен быть boolean.");
507
+ }
508
+ if (workspaceId !== undefined) {
509
+ err(path, "matrix нельзя сочетать с workspaceId: матрица сама задаёт workspace для клонов.");
510
+ }
511
+ }
512
+ function findDependencyCycle(entries) {
513
+ const graph = new Map();
514
+ const display = new Map();
515
+ for (const entry of entries) {
516
+ const key = entry.id.toLowerCase();
517
+ display.set(key, entry.id);
518
+ graph.set(key, entry.needs.map((need) => need.toLowerCase()));
519
+ }
520
+ const WHITE = 0;
521
+ const GRAY = 1;
522
+ const BLACK = 2;
523
+ const color = new Map();
524
+ const stack = [];
525
+ const visit = (node) => {
526
+ color.set(node, GRAY);
527
+ stack.push(node);
528
+ for (const dependency of graph.get(node) ?? []) {
529
+ if (!graph.has(dependency))
530
+ continue;
531
+ const state = color.get(dependency) ?? WHITE;
532
+ if (state === GRAY) {
533
+ const start = stack.indexOf(dependency);
534
+ return [...stack.slice(start), dependency].map((key) => display.get(key) ?? key);
535
+ }
536
+ if (state === WHITE) {
537
+ const found = visit(dependency);
538
+ if (found)
539
+ return found;
540
+ }
541
+ }
542
+ stack.pop();
543
+ color.set(node, BLACK);
544
+ return null;
545
+ };
546
+ for (const key of graph.keys()) {
547
+ if ((color.get(key) ?? WHITE) === WHITE) {
548
+ const found = visit(key);
549
+ if (found)
550
+ return found;
551
+ }
552
+ }
553
+ return null;
554
+ }