agent-steward 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/CHANGELOG.md +309 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +55 -8
  4. package/ROADMAP-STRATEGY.md +22 -19
  5. package/ROADMAP.md +230 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +356 -0
  9. package/dist/core/analytics.d.ts +6 -0
  10. package/dist/core/analytics.d.ts.map +1 -1
  11. package/dist/core/analytics.js +20 -3
  12. package/dist/core/audit.d.ts +6 -0
  13. package/dist/core/audit.d.ts.map +1 -1
  14. package/dist/core/audit.js +24 -0
  15. package/dist/core/budget.d.ts +118 -0
  16. package/dist/core/budget.d.ts.map +1 -0
  17. package/dist/core/budget.js +206 -0
  18. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  19. package/dist/core/cron-to-schtasks.js +38 -0
  20. package/dist/core/dry-run.d.ts +26 -1
  21. package/dist/core/dry-run.d.ts.map +1 -1
  22. package/dist/core/dry-run.js +199 -8
  23. package/dist/core/execution.d.ts +203 -0
  24. package/dist/core/execution.d.ts.map +1 -0
  25. package/dist/core/execution.js +309 -0
  26. package/dist/core/feedback.d.ts +192 -0
  27. package/dist/core/feedback.d.ts.map +1 -0
  28. package/dist/core/feedback.js +426 -0
  29. package/dist/core/gate-integrity.d.ts +71 -0
  30. package/dist/core/gate-integrity.d.ts.map +1 -0
  31. package/dist/core/gate-integrity.js +275 -0
  32. package/dist/core/git-trigger.d.ts.map +1 -1
  33. package/dist/core/git-trigger.js +14 -2
  34. package/dist/core/guard-run.d.ts +4 -0
  35. package/dist/core/guard-run.d.ts.map +1 -0
  36. package/dist/core/guard-run.js +101 -0
  37. package/dist/core/guard.d.ts +52 -0
  38. package/dist/core/guard.d.ts.map +1 -0
  39. package/dist/core/guard.js +362 -0
  40. package/dist/core/local-ai.d.ts.map +1 -1
  41. package/dist/core/local-ai.js +7 -3
  42. package/dist/core/lock.d.ts +41 -0
  43. package/dist/core/lock.d.ts.map +1 -1
  44. package/dist/core/lock.js +141 -29
  45. package/dist/core/matrix.d.ts +8 -0
  46. package/dist/core/matrix.d.ts.map +1 -1
  47. package/dist/core/matrix.js +132 -17
  48. package/dist/core/mission.d.ts +103 -0
  49. package/dist/core/mission.d.ts.map +1 -0
  50. package/dist/core/mission.js +374 -0
  51. package/dist/core/opencode-models.d.ts +2 -2
  52. package/dist/core/opencode-models.d.ts.map +1 -1
  53. package/dist/core/opencode-models.js +28 -21
  54. package/dist/core/opencode-usage.d.ts +35 -0
  55. package/dist/core/opencode-usage.d.ts.map +1 -0
  56. package/dist/core/opencode-usage.js +132 -0
  57. package/dist/core/pipeline-apply.d.ts +38 -0
  58. package/dist/core/pipeline-apply.d.ts.map +1 -0
  59. package/dist/core/pipeline-apply.js +117 -0
  60. package/dist/core/pipeline-io.d.ts +13 -0
  61. package/dist/core/pipeline-io.d.ts.map +1 -0
  62. package/dist/core/pipeline-io.js +78 -0
  63. package/dist/core/pipeline-map.d.ts +52 -0
  64. package/dist/core/pipeline-map.d.ts.map +1 -0
  65. package/dist/core/pipeline-map.js +208 -0
  66. package/dist/core/pipeline-spec.d.ts +109 -0
  67. package/dist/core/pipeline-spec.d.ts.map +1 -0
  68. package/dist/core/pipeline-spec.js +554 -0
  69. package/dist/core/ps-wrapper.d.ts +27 -2
  70. package/dist/core/ps-wrapper.d.ts.map +1 -1
  71. package/dist/core/ps-wrapper.js +424 -65
  72. package/dist/core/record-history.d.ts.map +1 -1
  73. package/dist/core/record-history.js +206 -33
  74. package/dist/core/router/rules.d.ts.map +1 -1
  75. package/dist/core/router/rules.js +6 -0
  76. package/dist/core/run-mode.d.ts +12 -0
  77. package/dist/core/run-mode.d.ts.map +1 -0
  78. package/dist/core/run-mode.js +17 -0
  79. package/dist/core/scheduler/linux.d.ts +8 -1
  80. package/dist/core/scheduler/linux.d.ts.map +1 -1
  81. package/dist/core/scheduler/linux.js +34 -9
  82. package/dist/core/scheduler/logs.d.ts +4 -0
  83. package/dist/core/scheduler/logs.d.ts.map +1 -1
  84. package/dist/core/scheduler/logs.js +25 -1
  85. package/dist/core/scheduler/mac.d.ts +44 -2
  86. package/dist/core/scheduler/mac.d.ts.map +1 -1
  87. package/dist/core/scheduler/mac.js +126 -15
  88. package/dist/core/scheduler/windows.d.ts.map +1 -1
  89. package/dist/core/scheduler/windows.js +15 -12
  90. package/dist/core/secrets.d.ts.map +1 -1
  91. package/dist/core/secrets.js +18 -8
  92. package/dist/core/self-analysis.d.ts +32 -2
  93. package/dist/core/self-analysis.d.ts.map +1 -1
  94. package/dist/core/self-analysis.js +38 -27
  95. package/dist/core/shutdown.d.ts +33 -2
  96. package/dist/core/shutdown.d.ts.map +1 -1
  97. package/dist/core/shutdown.js +58 -2
  98. package/dist/core/structured-log.d.ts +37 -1
  99. package/dist/core/structured-log.d.ts.map +1 -1
  100. package/dist/core/structured-log.js +37 -0
  101. package/dist/core/usage-surface.d.ts +25 -0
  102. package/dist/core/usage-surface.d.ts.map +1 -0
  103. package/dist/core/usage-surface.js +41 -0
  104. package/dist/core/worktree-run.d.ts +4 -0
  105. package/dist/core/worktree-run.d.ts.map +1 -0
  106. package/dist/core/worktree-run.js +164 -0
  107. package/dist/core/worktree.d.ts +115 -0
  108. package/dist/core/worktree.d.ts.map +1 -0
  109. package/dist/core/worktree.js +462 -0
  110. package/dist/core/wrappers/bash.d.ts +19 -0
  111. package/dist/core/wrappers/bash.d.ts.map +1 -1
  112. package/dist/core/wrappers/bash.js +230 -27
  113. package/dist/db/capability-repo.d.ts +43 -2
  114. package/dist/db/capability-repo.d.ts.map +1 -1
  115. package/dist/db/capability-repo.js +96 -11
  116. package/dist/db/history-repo.d.ts +70 -5
  117. package/dist/db/history-repo.d.ts.map +1 -1
  118. package/dist/db/history-repo.js +170 -29
  119. package/dist/db/metrics-repo.d.ts +20 -2
  120. package/dist/db/metrics-repo.d.ts.map +1 -1
  121. package/dist/db/metrics-repo.js +35 -13
  122. package/dist/db/migrate.d.ts.map +1 -1
  123. package/dist/db/migrate.js +37 -17
  124. package/dist/db/recovery.d.ts +3 -1
  125. package/dist/db/recovery.d.ts.map +1 -1
  126. package/dist/db/recovery.js +11 -5
  127. package/dist/db/run-journal.d.ts +33 -5
  128. package/dist/db/run-journal.d.ts.map +1 -1
  129. package/dist/db/run-journal.js +78 -14
  130. package/dist/db/run-resume.d.ts +5 -0
  131. package/dist/db/run-resume.d.ts.map +1 -1
  132. package/dist/db/run-resume.js +9 -2
  133. package/dist/db/runs-repo.d.ts +19 -2
  134. package/dist/db/runs-repo.d.ts.map +1 -1
  135. package/dist/db/runs-repo.js +91 -60
  136. package/dist/db/schema.d.ts +2 -2
  137. package/dist/db/schema.d.ts.map +1 -1
  138. package/dist/db/schema.js +132 -2
  139. package/dist/db/templates-repo.d.ts +2 -2
  140. package/dist/db/templates-repo.d.ts.map +1 -1
  141. package/dist/db/templates-repo.js +5 -3
  142. package/dist/history.d.ts +7 -2
  143. package/dist/history.d.ts.map +1 -1
  144. package/dist/history.js +4 -2
  145. package/dist/hook-output.d.ts +2 -0
  146. package/dist/hook-output.d.ts.map +1 -0
  147. package/dist/hook-output.js +31 -0
  148. package/dist/i18n.d.ts +5 -0
  149. package/dist/i18n.d.ts.map +1 -1
  150. package/dist/i18n.js +11 -4
  151. package/dist/index.d.ts +375 -47
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +1344 -192
  154. package/dist/notifications.d.ts +53 -2
  155. package/dist/notifications.d.ts.map +1 -1
  156. package/dist/notifications.js +168 -21
  157. package/dist/profiles.d.ts.map +1 -1
  158. package/dist/profiles.js +82 -10
  159. package/dist/rpc.d.ts +354 -0
  160. package/dist/rpc.d.ts.map +1 -1
  161. package/dist/rpc.js +145 -0
  162. package/dist/server.d.ts +32 -2
  163. package/dist/server.d.ts.map +1 -1
  164. package/dist/server.js +154 -30
  165. package/dist/settings.d.ts +44 -2
  166. package/dist/settings.d.ts.map +1 -1
  167. package/dist/settings.js +85 -3
  168. package/dist/shared/jobs-view.d.ts +1 -1
  169. package/dist/shared/jobs-view.d.ts.map +1 -1
  170. package/dist/shared/jobs-view.js +2 -0
  171. package/dist/task-transfer.d.ts +21 -0
  172. package/dist/task-transfer.d.ts.map +1 -1
  173. package/dist/task-transfer.js +64 -3
  174. package/dist/templates.d.ts +2 -2
  175. package/dist/templates.d.ts.map +1 -1
  176. package/dist/templates.js +3 -3
  177. package/dist/types.d.ts +22 -2
  178. package/dist/types.d.ts.map +1 -1
  179. package/dist/workspaces.d.ts.map +1 -1
  180. package/dist/workspaces.js +34 -11
  181. package/docs/ARCHITECTURE.md +319 -66
  182. package/docs/COMPATIBILITY.md +2 -2
  183. package/docs/CONCEPT.md +18 -4
  184. package/docs/CROSS_PLATFORM.ru.md +20 -0
  185. package/docs/CROSS_PLATFORM.zh.md +18 -0
  186. package/docs/EXECUTION-LOOP.md +28 -10
  187. package/docs/FEATURES.md +129 -7
  188. package/docs/FEATURES.zh.md +97 -6
  189. package/docs/MIGRATION.md +2 -2
  190. package/docs/PIPELINE.md +293 -0
  191. package/docs/QA-A2-GUI-TUI.md +205 -0
  192. package/docs/README.ru.md +43 -4
  193. package/docs/README.zh.md +44 -4
  194. package/docs/SAFETY.md +23 -3
  195. package/gui-experimental.cjs +9 -8
  196. package/locales/en.json +58 -3
  197. package/locales/ru.json +58 -3
  198. package/locales/zh.json +58 -3
  199. package/opencode.pipeline.yaml +35 -0
  200. package/package.json +36 -4
  201. package/scripts/check-eslint-baseline.mjs +139 -0
  202. package/scripts/gen-test-plan-counters.mjs +117 -0
  203. package/scripts/github-ci-fetch.ps1 +37 -0
  204. package/scripts/pl-commit.ps1 +112 -0
  205. package/scripts/qa-a2-commit.ps1 +104 -0
  206. package/scripts/test-home.mjs +107 -0
  207. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  208. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  209. package/src/cli.ts +417 -0
  210. package/src/core/analytics.ts +27 -4
  211. package/src/core/audit.ts +25 -0
  212. package/src/core/budget.ts +340 -0
  213. package/src/core/cron-to-schtasks.ts +42 -0
  214. package/src/core/dry-run.ts +235 -12
  215. package/src/core/execution.ts +538 -0
  216. package/src/core/feedback.ts +582 -0
  217. package/src/core/file-watcher.ts +2 -2
  218. package/src/core/gate-integrity.ts +330 -0
  219. package/src/core/git-trigger.ts +18 -5
  220. package/src/core/guard-run.ts +119 -0
  221. package/src/core/guard.ts +431 -0
  222. package/src/core/local-ai.ts +7 -3
  223. package/src/core/lock.ts +178 -37
  224. package/src/core/matrix.ts +158 -52
  225. package/src/core/mission.ts +531 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/opencode-models.ts +30 -21
  228. package/src/core/opencode-usage.ts +182 -0
  229. package/src/core/pipeline-apply.ts +158 -0
  230. package/src/core/pipeline-io.ts +96 -0
  231. package/src/core/pipeline-map.ts +283 -0
  232. package/src/core/pipeline-spec.ts +775 -0
  233. package/src/core/ps-wrapper.ts +435 -66
  234. package/src/core/record-history.ts +258 -81
  235. package/src/core/router/rules.ts +6 -0
  236. package/src/core/run-mode.ts +19 -0
  237. package/src/core/schedule-gate.ts +1 -1
  238. package/src/core/scheduler/at-fallback.ts +1 -1
  239. package/src/core/scheduler/linux.ts +40 -11
  240. package/src/core/scheduler/logs.ts +34 -3
  241. package/src/core/scheduler/mac.ts +174 -14
  242. package/src/core/scheduler/registry.ts +2 -2
  243. package/src/core/scheduler/windows.ts +19 -15
  244. package/src/core/secrets.ts +26 -19
  245. package/src/core/self-analysis.ts +75 -29
  246. package/src/core/shutdown.ts +90 -4
  247. package/src/core/structured-log.ts +89 -5
  248. package/src/core/telegram.ts +2 -2
  249. package/src/core/triage-worker.ts +7 -7
  250. package/src/core/triage.ts +2 -2
  251. package/src/core/usage-surface.ts +70 -0
  252. package/src/core/worktree-run.ts +199 -0
  253. package/src/core/worktree.ts +600 -0
  254. package/src/core/wrappers/bash.ts +248 -26
  255. package/src/db/capability-repo.ts +127 -10
  256. package/src/db/history-repo.ts +281 -40
  257. package/src/db/metrics-repo.ts +40 -13
  258. package/src/db/migrate.ts +57 -32
  259. package/src/db/recovery.ts +12 -5
  260. package/src/db/run-journal.ts +100 -13
  261. package/src/db/run-resume.ts +17 -1
  262. package/src/db/runs-repo.ts +147 -65
  263. package/src/db/schema.ts +134 -2
  264. package/src/db/templates-repo.ts +5 -3
  265. package/src/gui.tsx +438 -18
  266. package/src/history.ts +11 -4
  267. package/src/hook-output.ts +39 -0
  268. package/src/i18n.ts +12 -4
  269. package/src/index.ts +1902 -320
  270. package/src/notifications.ts +227 -47
  271. package/src/profiles.ts +88 -10
  272. package/src/rpc.ts +158 -0
  273. package/src/server.ts +201 -41
  274. package/src/settings.ts +125 -5
  275. package/src/shared/jobs-view.ts +3 -1
  276. package/src/task-transfer.ts +90 -6
  277. package/src/templates.ts +3 -3
  278. package/src/types.ts +23 -2
  279. package/src/workspaces.ts +37 -14
package/src/cli.ts ADDED
@@ -0,0 +1,417 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI agent-steward (Спринт 32, Pipeline-as-code).
4
+ *
5
+ * Команды:
6
+ * agent-steward pipeline validate <file> [--json]
7
+ * agent-steward pipeline apply <file> [--dry-run] [--json]
8
+ * agent-steward pipeline export --pipeline <name> [--out <file>]
9
+ *
10
+ * Exit-коды: 0 — успех, 1 — ошибки валидации/применения, 2 — неверные аргументы.
11
+ */
12
+ import { writeFileSync } from "node:fs";
13
+ import { stringify } from "yaml";
14
+ import { closeDb, initDb } from "./db/index.js";
15
+ import { listTasks } from "./db/tasks-repo.js";
16
+ import { loadPipelineFile } from "./core/pipeline-io.js";
17
+ import { executePipelineApply, planPipelineApply } from "./core/pipeline-apply.js";
18
+ import { tasksToPipelineSpec } from "./core/pipeline-map.js";
19
+ import { saveTaskDefinition, type TaskDefinition } from "./task-transfer.js";
20
+ import { listWorkspaces } from "./workspaces.js";
21
+ import { runMission, type MissionSpec } from "./core/mission.js";
22
+
23
+ const USAGE = `agent-steward — планировщик agent jobs
24
+
25
+ Использование:
26
+ agent-steward pipeline validate <file> [--json]
27
+ agent-steward pipeline apply <file> [--dry-run] [--json]
28
+ agent-steward pipeline export --pipeline <name> [--out <file>]
29
+
30
+ Команды:
31
+ validate проверить opencode.pipeline.yaml, не меняя задачи
32
+ apply создать/обновить задачи из файла (идемпотентно)
33
+ export выгрузить задачи pipeline из БД обратно в YAML
34
+
35
+ Опции:
36
+ --json машинный вывод
37
+ --dry-run показать план apply без изменений
38
+ --pipeline имя pipeline для export
39
+ --out файл для export (по умолчанию stdout)
40
+ `;
41
+
42
+ interface PrintedIssue {
43
+ path: string;
44
+ message: string;
45
+ }
46
+
47
+ function printIssueList(label: string, issues: PrintedIssue[]): void {
48
+ if (issues.length === 0) return;
49
+ console.error(label);
50
+ for (const issue of issues) {
51
+ console.error(` - ${issue.path}: ${issue.message}`);
52
+ }
53
+ }
54
+
55
+ function requireFile(args: string[]): string {
56
+ const file = args.find((arg) => !arg.startsWith("--"));
57
+ if (!file) {
58
+ console.error("Не указан файл pipeline.\n");
59
+ console.error(USAGE);
60
+ process.exit(2);
61
+ }
62
+ return file;
63
+ }
64
+
65
+ function flagValue(args: string[], name: string): string | undefined {
66
+ const index = args.indexOf(name);
67
+ if (index === -1) return undefined;
68
+ const value = args[index + 1];
69
+ if (!value || value.startsWith("--")) {
70
+ console.error(`Опция ${name} требует значение.`);
71
+ process.exit(2);
72
+ }
73
+ return value;
74
+ }
75
+
76
+ function workspaceResolver(): (value: string) => string | undefined {
77
+ const workspaces = listWorkspaces();
78
+ const byId = new Map(workspaces.map((ws) => [ws.id.toLowerCase(), ws.id]));
79
+ const byName = new Map(workspaces.map((ws) => [ws.name.trim().toLowerCase(), ws.id]));
80
+ return (value) => {
81
+ const key = value.trim().toLowerCase();
82
+ return byId.get(key) ?? byName.get(key);
83
+ };
84
+ }
85
+
86
+ /** Создаёт задачу через общий путь schedulerCreateTask и сохраняет определение. */
87
+ async function persistDefinition(def: TaskDefinition): Promise<void> {
88
+ const { schedulerCreateTask } = await import("./index.js");
89
+ await schedulerCreateTask(
90
+ def.name,
91
+ def.schedule,
92
+ def.prompt,
93
+ def.timeoutSeconds,
94
+ def.workingDirectory,
95
+ def.retryCount,
96
+ def.retryDelay,
97
+ def.qualityGate,
98
+ def.nextTaskOnSuccess,
99
+ def.nextTaskOnError,
100
+ def.triggerType,
101
+ def.watchPath,
102
+ def.dependsOn,
103
+ def.model,
104
+ def.priority,
105
+ def.beforeScript,
106
+ def.afterScript,
107
+ def.mcpEvent,
108
+ def.workspaceId,
109
+ def.allowedTools,
110
+ def.deniedTools,
111
+ def.matrix,
112
+ def.matrixParentId,
113
+ "create",
114
+ def.timezone,
115
+ def.notBefore,
116
+ def.notAfter,
117
+ def.pausedUntil,
118
+ def.runAt,
119
+ def.session,
120
+ def.sessionId,
121
+ def.sessionMaxRuns,
122
+ {
123
+ activeDays: def.activeDays,
124
+ windowPolicy: def.windowPolicy,
125
+ watchGlobs: def.watchGlobs,
126
+ watchIgnore: def.watchIgnore,
127
+ gitBranch: def.gitBranch,
128
+ gitPaths: def.gitPaths,
129
+ gitIgnore: def.gitIgnore,
130
+ gitPollSeconds: def.gitPollSeconds,
131
+ },
132
+ def.runWhenLoggedOff,
133
+ def.paused,
134
+ def.legacyShell,
135
+ );
136
+ await saveTaskDefinition(def);
137
+ }
138
+
139
+ async function runValidate(args: string[]): Promise<number> {
140
+ const file = requireFile(args);
141
+ const json = args.includes("--json");
142
+ const result = await loadPipelineFile(file);
143
+
144
+ if (json) {
145
+ console.log(
146
+ JSON.stringify(
147
+ {
148
+ ok: result.ok,
149
+ errors: result.errors,
150
+ warnings: result.warnings,
151
+ steps: result.spec?.steps.length ?? 0,
152
+ },
153
+ null,
154
+ 2,
155
+ ),
156
+ );
157
+ } else {
158
+ printIssueList("Ошибки:", result.errors);
159
+ printIssueList("Предупреждения:", result.warnings);
160
+ if (result.ok && result.spec) {
161
+ console.log(
162
+ `OK: «${result.spec.name}», шагов: ${result.spec.steps.length}`,
163
+ );
164
+ }
165
+ }
166
+
167
+ return result.ok ? 0 : 1;
168
+ }
169
+
170
+ async function runExport(args: string[]): Promise<number> {
171
+ const pipelineName = flagValue(args, "--pipeline");
172
+ if (!pipelineName) {
173
+ console.error("Для export укажите --pipeline <name>.\n");
174
+ console.error(USAGE);
175
+ return 2;
176
+ }
177
+ const out = flagValue(args, "--out");
178
+
179
+ initDb();
180
+ try {
181
+ const exported = tasksToPipelineSpec(listTasks(), pipelineName);
182
+ if (exported.spec.steps.length === 0) {
183
+ console.error(`Pipeline «${pipelineName}» не найден в БД.`);
184
+ return 1;
185
+ }
186
+ for (const warning of exported.warnings) console.error(`Предупреждение: ${warning}`);
187
+ const yaml = stringify(exported.spec, { lineWidth: 0 });
188
+ if (out) {
189
+ writeFileSync(out, yaml, "utf8");
190
+ console.log(`Записано: ${out} (шагов: ${exported.spec.steps.length})`);
191
+ } else {
192
+ process.stdout.write(yaml);
193
+ }
194
+ return 0;
195
+ } finally {
196
+ closeDb();
197
+ }
198
+ }
199
+
200
+ async function runApply(args: string[]): Promise<number> {
201
+ const file = requireFile(args);
202
+ const dryRun = args.includes("--dry-run");
203
+ const json = args.includes("--json");
204
+
205
+ const parsed = await loadPipelineFile(file);
206
+ if (!parsed.ok || !parsed.spec) {
207
+ printIssueList("Ошибки:", parsed.errors);
208
+ printIssueList("Предупреждения:", parsed.warnings);
209
+ return 1;
210
+ }
211
+
212
+ initDb();
213
+ try {
214
+ const plan = planPipelineApply(parsed.spec, listTasks(), {
215
+ resolveWorkspaceId: workspaceResolver(),
216
+ });
217
+ for (const warning of plan.warnings) console.error(`Предупреждение: ${warning}`);
218
+
219
+ if (!dryRun) {
220
+ await executePipelineApply(plan, {
221
+ create: persistDefinition,
222
+ update: persistDefinition,
223
+ });
224
+ }
225
+
226
+ const summary = {
227
+ pipeline: parsed.spec.name,
228
+ dryRun,
229
+ creates: plan.creates.map((task) => task.name),
230
+ updates: plan.updates.map((entry) => entry.task.name),
231
+ unchanged: plan.unchanged.map((task) => task.name),
232
+ stale: plan.stale.map((task) => task.name),
233
+ };
234
+ if (json) {
235
+ console.log(JSON.stringify(summary, null, 2));
236
+ } else {
237
+ const verb = dryRun ? "Будет создано" : "Создано";
238
+ console.log(`${verb}: ${summary.creates.length}`);
239
+ console.log(`Обновлено: ${summary.updates.length}`);
240
+ console.log(`Без изменений: ${summary.unchanged.length}`);
241
+ if (summary.stale.length > 0) {
242
+ console.log(`Устаревшие (не удалены): ${summary.stale.join(", ")}`);
243
+ }
244
+ for (const name of summary.creates) console.log(` + ${name}`);
245
+ for (const name of summary.updates) console.log(` ~ ${name}`);
246
+ }
247
+ return 0;
248
+ } catch (err) {
249
+ console.error(`Ошибка apply: ${err instanceof Error ? err.message : String(err)}`);
250
+ return 1;
251
+ } finally {
252
+ closeDb();
253
+ }
254
+ }
255
+
256
+ function listFlag(args: string[], name: string): string[] | undefined {
257
+ const value = flagValue(args, name);
258
+ if (value === undefined) return undefined;
259
+ const list = value
260
+ .split(",")
261
+ .map((item) => item.trim())
262
+ .filter(Boolean);
263
+ return list.length > 0 ? list : undefined;
264
+ }
265
+
266
+ /**
267
+ * AB-8.2: `agent-steward run <prompt>` — ad-hoc миссия без регистрации в ОС.
268
+ * Проходит тот же runtime, что и задачи: план → маршрут → GATE → ledger.
269
+ */
270
+ async function runAdHoc(args: string[]): Promise<number> {
271
+ const valueFlags = new Set([
272
+ "--cwd",
273
+ "--gate",
274
+ "--task-type",
275
+ "--model",
276
+ "--timeout",
277
+ "--policy",
278
+ "--allow-tools",
279
+ "--deny-tools",
280
+ "--session",
281
+ "--session-id",
282
+ "--name",
283
+ ]);
284
+ let prompt: string | undefined;
285
+ for (let index = 0; index < args.length; index++) {
286
+ const arg = args[index];
287
+ if (arg.startsWith("--")) {
288
+ if (valueFlags.has(arg)) index++;
289
+ continue;
290
+ }
291
+ prompt = arg;
292
+ break;
293
+ }
294
+ if (!prompt?.trim()) {
295
+ console.error(
296
+ "agent-steward run <prompt> [--cwd <dir>] [--gate <cmd>] [--task-type <type>] " +
297
+ "[--model <model>] [--timeout <sec>] [--policy hybrid|secure|legacy] " +
298
+ "[--allow-tools a,b] [--deny-tools a,b] [--session new|reuse|last] " +
299
+ "[--session-id ses_...] [--name <name>] [--dry-run] [--json]",
300
+ );
301
+ return 2;
302
+ }
303
+
304
+ const json = args.includes("--json");
305
+ const timeoutRaw = flagValue(args, "--timeout");
306
+ const timeoutSeconds = timeoutRaw === undefined ? undefined : Number(timeoutRaw);
307
+ if (timeoutSeconds !== undefined && (!Number.isInteger(timeoutSeconds) || timeoutSeconds <= 0)) {
308
+ console.error("--timeout должен быть целым положительным числом секунд.");
309
+ return 2;
310
+ }
311
+ const policyRaw = flagValue(args, "--policy");
312
+ if (policyRaw && !["hybrid", "secure", "legacy"].includes(policyRaw)) {
313
+ console.error("--policy должен быть hybrid, secure или legacy.");
314
+ return 2;
315
+ }
316
+ const sessionRaw = flagValue(args, "--session");
317
+ if (sessionRaw && !["new", "reuse", "last"].includes(sessionRaw)) {
318
+ console.error("--session должен быть new, reuse или last.");
319
+ return 2;
320
+ }
321
+
322
+ const spec: MissionSpec = {
323
+ prompt,
324
+ cwd: flagValue(args, "--cwd"),
325
+ taskName: flagValue(args, "--name"),
326
+ taskType: flagValue(args, "--task-type"),
327
+ model: flagValue(args, "--model"),
328
+ session: sessionRaw as MissionSpec["session"],
329
+ sessionId: flagValue(args, "--session-id"),
330
+ timeoutSeconds,
331
+ gate: flagValue(args, "--gate"),
332
+ gateTimeoutSeconds: undefined,
333
+ policy: policyRaw as MissionSpec["policy"],
334
+ allowedTools: listFlag(args, "--allow-tools"),
335
+ deniedTools: listFlag(args, "--deny-tools"),
336
+ dryRun: args.includes("--dry-run"),
337
+ };
338
+
339
+ initDb();
340
+ try {
341
+ const result = await runMission(spec);
342
+ if (json) {
343
+ console.log(
344
+ JSON.stringify(
345
+ {
346
+ success: result.success,
347
+ dryRun: result.dryRun,
348
+ runId: result.runId,
349
+ status: result.status,
350
+ description: result.description,
351
+ error: result.error,
352
+ logFile: result.logFile,
353
+ steps: result.steps,
354
+ },
355
+ null,
356
+ 2,
357
+ ),
358
+ );
359
+ } else {
360
+ console.log(result.description);
361
+ for (const step of result.steps) {
362
+ console.log(` ${step.stepName}: ${step.status} (attempt ${step.attempt})`);
363
+ }
364
+ if (result.error) console.error(`Ошибка: ${result.error}`);
365
+ if (result.logFile) console.log(`Лог: ${result.logFile}`);
366
+ if (result.runId) console.log(`Запуск: ${result.runId}`);
367
+ }
368
+ return result.success ? 0 : 1;
369
+ } catch (err) {
370
+ console.error(`Ошибка миссии: ${err instanceof Error ? err.message : String(err)}`);
371
+ return 1;
372
+ } finally {
373
+ closeDb();
374
+ }
375
+ }
376
+
377
+ async function main(argv: string[]): Promise<number> {
378
+ const [group, command, ...rest] = argv;
379
+ if (group === "--help" || group === "-h" || group === "help" || !group) {
380
+ console.log(USAGE);
381
+ return group ? 0 : 2;
382
+ }
383
+ if (group === "run") {
384
+ return runAdHoc([command, ...rest].filter((value): value is string => Boolean(value)));
385
+ }
386
+ if (group !== "pipeline") {
387
+ console.error(`Неизвестная команда «${group}».\n`);
388
+ console.error(USAGE);
389
+ return 2;
390
+ }
391
+ switch (command) {
392
+ case "--help":
393
+ case "-h":
394
+ case "help":
395
+ console.log(USAGE);
396
+ return 0;
397
+ case "validate":
398
+ return runValidate(rest);
399
+ case "apply":
400
+ return runApply(rest);
401
+ case "export":
402
+ return runExport(rest);
403
+ default:
404
+ console.error(`Неизвестная команда pipeline «${command ?? ""}».\n`);
405
+ console.error(USAGE);
406
+ return 2;
407
+ }
408
+ }
409
+
410
+ main(process.argv.slice(2))
411
+ .then((code) => {
412
+ process.exitCode = code;
413
+ })
414
+ .catch((err) => {
415
+ console.error(`Ошибка: ${err instanceof Error ? err.message : String(err)}`);
416
+ process.exitCode = 1;
417
+ });
@@ -31,6 +31,8 @@ export interface AnalyticsRecord {
31
31
  export interface AnalyticsTaskRef {
32
32
  name: string;
33
33
  matrixParentId?: string | null;
34
+ /** Экономика v2 (E-2): лимит токенов на запуск (0/undefined — без лимита). */
35
+ tokenBudget?: number;
34
36
  }
35
37
 
36
38
  export interface DailyBucket {
@@ -58,6 +60,10 @@ export interface TaskAnalyticsRow {
58
60
  /** Задача — клон матрицы (matrixParentId задан). */
59
61
  isMatrixClone: boolean;
60
62
  matrixParentId: string | null;
63
+ /** Экономика v2 (E-2): лимит токенов на запуск (0 — без лимита). */
64
+ tokenBudget?: number;
65
+ /** Сумма токенов за период превысила лимит на задачу. */
66
+ tokenBudgetExceeded?: boolean;
61
67
  }
62
68
 
63
69
  export interface MatrixAnalyticsRow {
@@ -187,13 +193,18 @@ export function buildAnalytics(
187
193
  });
188
194
  }
189
195
 
190
- const byTask = new Map<string, TaskAnalyticsRow>();
196
+ const byTask = new Map<string, TaskAnalyticsRow & { maxRunTokens: number }>();
191
197
  const byModel = new Map<string, ModelAnalyticsRow>();
192
198
  const byError = new Map<string, ErrorAnalyticsRow>();
193
199
  const cloneParent = new Map<string, string>();
200
+ const taskTokenBudget = new Map<string, number>();
194
201
  for (const task of options.tasks ?? []) {
195
202
  const parentId = task.matrixParentId?.trim();
196
203
  if (parentId) cloneParent.set(task.name.toLowerCase(), parentId);
204
+ const budget = Number(task.tokenBudget);
205
+ if (Number.isFinite(budget) && budget > 0) {
206
+ taskTokenBudget.set(task.name.toLowerCase(), budget);
207
+ }
197
208
  }
198
209
 
199
210
  let totalsTotal = 0;
@@ -257,7 +268,11 @@ export function buildAnalytics(
257
268
  costUsd: 0,
258
269
  isMatrixClone: cloneParent.has(taskKey),
259
270
  matrixParentId: cloneParent.get(taskKey) ?? null,
271
+ tokenBudget: taskTokenBudget.get(taskKey),
272
+ tokenBudgetExceeded: false,
273
+ maxRunTokens: 0,
260
274
  };
275
+ existing.maxRunTokens = Math.max(existing.maxRunTokens, tokens);
261
276
  existing.total += 1;
262
277
  if (status === "success") existing.success += 1;
263
278
  else existing.error += 1;
@@ -277,9 +292,12 @@ export function buildAnalytics(
277
292
 
278
293
  // Топ ошибок: группируем по тексту, чтобы дайджест показывал частые причины.
279
294
  if (status !== "success" && status !== "partial") {
295
+ // QA-P1.5: легаси-записи успешных запусков содержат "-" вместо текста
296
+ // ошибки. Такой маркер не является сообщением и не должен попадать в топ.
297
+ const rawError = typeof record.error === "string" ? record.error.trim() : "";
280
298
  const message =
281
- typeof record.error === "string" && record.error.trim()
282
- ? record.error.trim().slice(0, 160)
299
+ rawError && rawError !== "-"
300
+ ? rawError.slice(0, 160)
283
301
  : "(без текста)";
284
302
  const errorRow = byError.get(message) ?? {
285
303
  message,
@@ -298,11 +316,16 @@ export function buildAnalytics(
298
316
  }
299
317
 
300
318
  const tasks = [...byTask.values()]
301
- .map((row) => ({
319
+ .map(({ maxRunTokens, ...row }) => ({
302
320
  ...row,
303
321
  successRate: percent(row.success, row.total),
304
322
  avgDurationMs: Math.round(row.avgDurationMs),
305
323
  costUsd: Math.round(row.costUsd * 1e6) / 1e6,
324
+ // E-2: бюджет задаётся на один запуск, поэтому флаг выставляем по
325
+ // максимальному расходу токенов за запуск, а не по сумме за период.
326
+ tokenBudgetExceeded: row.tokenBudget
327
+ ? maxRunTokens > row.tokenBudget
328
+ : false,
306
329
  }))
307
330
  .sort((a, b) => b.total - a.total || a.taskName.localeCompare(b.taskName));
308
331
 
package/src/core/audit.ts CHANGED
@@ -301,8 +301,33 @@ export function recordTaskToolBlocks(
301
301
  return written;
302
302
  }
303
303
 
304
+ /**
305
+ * QA-P3.1: единообразная проверка ISO-дат для фильтров аудита.
306
+ * Возвращает текст ошибки или null — чтобы все вызывающие (MCP, RPC, HTTP)
307
+ * отвечали одинаково, а не молча отдавали пустую выборку.
308
+ */
309
+ export function auditDateFilterError(
310
+ value: string | null | undefined,
311
+ name: "since" | "until",
312
+ ): string | null {
313
+ if (value === null || value === undefined) return null;
314
+ const trimmed = String(value).trim();
315
+ if (!trimmed) return null;
316
+ if (Number.isNaN(Date.parse(trimmed))) {
317
+ return `Некорректный параметр ${name}: ожидается ISO-дата.`;
318
+ }
319
+ return null;
320
+ }
321
+
304
322
  /** Читает журнал аудита (новые сверху). */
305
323
  export function readAuditLog(filter: ReadAuditFilter = {}): ReadAuditResult {
324
+ for (const [name, value] of [
325
+ ["since", filter.since],
326
+ ["until", filter.until],
327
+ ] as const) {
328
+ const dateError = auditDateFilterError(value, name);
329
+ if (dateError) throw new Error(dateError);
330
+ }
306
331
  const limit = Math.max(1, Math.min(5000, Math.floor(filter.limit ?? 200) || 200));
307
332
  const where: string[] = [];
308
333
  const params: unknown[] = [];