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/index.ts CHANGED
@@ -1,12 +1,17 @@
1
1
  import { Plugin, Rpc } from "@opencode/plugin";
2
- import {
3
- tool as v1Tool,
4
- type Hooks as V1Hooks,
5
- type PluginInput as V1PluginInput,
6
- type PluginModule as V1PluginModule,
2
+ import type {
3
+ Hooks as V1Hooks,
4
+ PluginInput as V1PluginInput,
5
+ PluginModule as V1PluginModule,
7
6
  } from "@opencode-ai/plugin";
7
+ // V1 `tool()` — тривиальная identity-функция (`input => input`). Инлайним её,
8
+ // чтобы точка входа V2 не импортировала devDependency @opencode-ai/plugin:
9
+ // у пользователя OpenCode 2 этот пакет не установлен, и статический импорт
10
+ // ломал загрузку плагина целиком (ERR_MODULE_NOT_FOUND).
11
+ const v1Tool = <T>(input: T): T => input;
8
12
  import { z } from "zod";
9
13
  import type { Tool } from "@opencode/schema/tool";
14
+ import type { Skill } from "@opencode/schema/skill";
10
15
  import { createRequire } from "node:module";
11
16
  import { existsSync } from "node:fs";
12
17
  import fs from "node:fs/promises";
@@ -35,19 +40,25 @@ import {
35
40
  writeSessionStateFile,
36
41
  type SessionMode,
37
42
  } from "./core/session.js";
38
- import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
43
+ import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun, gateAllowPathsFromAfterScript } from "./core/ps-wrapper.js";
39
44
  import { getSchedulerBackend, LinuxScheduler } from "./core/scheduler/index.js";
40
45
  import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
41
46
  import { getTaskLogs } from "./core/scheduler/logs.js";
42
47
  import { findSanitizedNameConflict, sanitizedConflictMessage } from "./core/task-name.js";
43
48
  import { writeBashWrapper } from "./core/wrappers/bash.js";
44
- import { simulatePipeline } from "./core/dry-run.js";
49
+ import { normalizeTaskGuards, type TaskGuards } from "./core/guard.js";
50
+ import {
51
+ simulatePipeline,
52
+ workingDirectoryDriftWarning,
53
+ type DryRunReport,
54
+ } from "./core/dry-run.js";
45
55
  import {
46
56
  aggregateMatrixResults,
47
57
  cancelPendingMatrixClones,
48
58
  expandMatrixTask,
49
59
  findOrphanedMatrixTasks,
50
60
  getMatrixDeletionGuard,
61
+ isKnownMatrix,
51
62
  matrixCompleteName,
52
63
  planMatrixFamilyDelete,
53
64
  removeMatrixChildren,
@@ -55,10 +66,36 @@ import {
55
66
  syncMatrixFamily,
56
67
  } from "./core/matrix.js";
57
68
  import { normalizeWatchPath, validateWatchGlobs } from "./core/watch-paths.js";
58
- import { createShutdownGate } from "./core/shutdown.js";
69
+ import { createShutdownGate, type ShutdownGateState } from "./core/shutdown.js";
70
+ import { CHILD_RUN_ENV, isChildRunMode } from "./core/run-mode.js";
59
71
  import { SchedulerRpc } from "./rpc.js";
72
+ import {
73
+ validatePipelineSpec,
74
+ type PipelineValidationResult,
75
+ } from "./core/pipeline-spec.js";
76
+ import {
77
+ loadPipelineFile,
78
+ parsePipelineYaml,
79
+ type PipelineParseResult,
80
+ } from "./core/pipeline-io.js";
81
+ import {
82
+ planPipelineApply,
83
+ executePipelineApply,
84
+ type PipelineApplyPlan,
85
+ } from "./core/pipeline-apply.js";
86
+ import {
87
+ pipelineExportLookupError,
88
+ pipelineSpecToTasks,
89
+ tasksToPipelineSpec,
90
+ } from "./core/pipeline-map.js";
91
+ import { stringify as yamlStringify } from "yaml";
60
92
  import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
61
- import { defaultNotifications, loadSettings, saveSettings } from "./settings.js";
93
+ import {
94
+ defaultNotifications,
95
+ loadSettings,
96
+ saveSettings,
97
+ type FeedbackSettings,
98
+ } from "./settings.js";
62
99
  import { resolveLocale, setLocale, t, type Locale, type LocaleMode } from "./i18n.js";
63
100
  import type {
64
101
  AuditSettings,
@@ -68,6 +105,7 @@ import type {
68
105
  PermissionSettings,
69
106
  TriageSettings,
70
107
  } from "./settings.js";
108
+ import { formatLogRunMarker, runMission, type MissionSpec } from "./core/mission.js";
71
109
  import {
72
110
  DEFAULT_PERMISSION_POLICY,
73
111
  buildOpencodeConfig,
@@ -76,8 +114,25 @@ import {
76
114
  } from "./core/permissions.js";
77
115
  import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
78
116
  import { buildAnalytics } from "./core/analytics.js";
117
+ import {
118
+ buildBudgetReport,
119
+ evaluateBudgetGate,
120
+ evaluateTaskTokenBudgetGate,
121
+ formatBudgetSkipMessage,
122
+ formatTaskTokenBudgetSkipMessage,
123
+ startOfUtcWeek,
124
+ type BudgetGateDecision,
125
+ type BudgetSettings,
126
+ type TaskTokenBudgetDecision,
127
+ } from "./core/budget.js";
79
128
  import { generateSelfAnalysisReport } from "./core/self-analysis.js";
80
- import { getHistory, listRunningRecords } from "./db/history-repo.js";
129
+ import {
130
+ getHistoryForAnalytics,
131
+ getHistoryForBudget,
132
+ listRunningRecords,
133
+ recordRun,
134
+ } from "./db/history-repo.js";
135
+ import { appendStructuredLog } from "./core/structured-log.js";
81
136
  import { getAllMetrics } from "./db/metrics-repo.js";
82
137
  import { discardDlq, listDlq, retryDlq } from "./core/dlq-api.js";
83
138
  import {
@@ -88,10 +143,18 @@ import {
88
143
  import {
89
144
  findStuckMatrixClones,
90
145
  maybeSendDigest,
146
+ notifyBudgetExceeded,
91
147
  notifyStuckMatrix,
148
+ sendBugReport,
92
149
  sendDigestNow,
93
150
  sendTestNotification,
94
151
  } from "./notifications.js";
152
+ import {
153
+ FEEDBACK_LIMITS,
154
+ flushOutbox,
155
+ redactText,
156
+ reportFeedback,
157
+ } from "./core/feedback.js";
95
158
  import {
96
159
  shadowReport,
97
160
  resetShadowDecisions,
@@ -117,7 +180,13 @@ import type {
117
180
  } from "./task-transfer.js";
118
181
  import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
119
182
  import type { TaskTemplate } from "./templates.js";
120
- import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
183
+ import {
184
+ startDashboardServer,
185
+ closeDashboardServer,
186
+ getDashboardPort,
187
+ probeDashboardOn,
188
+ discoverDashboardPort,
189
+ } from "./server.js";
121
190
  import {
122
191
  DEFAULT_PROFILE,
123
192
  createProfile,
@@ -147,11 +216,13 @@ import {
147
216
  import {
148
217
  deleteSecret,
149
218
  collectSecretNames,
219
+ getSecret,
150
220
  hasSecret,
151
221
  listSecrets,
152
222
  setSecret,
153
223
  } from "./core/secrets.js";
154
224
  import {
225
+ auditDateFilterError,
155
226
  cleanupAuditLog,
156
227
  readAuditLog,
157
228
  recordAudit,
@@ -204,6 +275,41 @@ const gatePath = (() => {
204
275
  return distPath;
205
276
  })();
206
277
 
278
+ /**
279
+ * W-1: путь к помощнику создания одноразового git worktree
280
+ * (dist/core/worktree-run.js). Обёртка вызывает его перед opencode.
281
+ */
282
+ const worktreeHelperPath = (() => {
283
+ const resolved = require.resolve("./core/worktree-run.js");
284
+ if (!resolved.endsWith(".ts")) return resolved;
285
+ const distPath = resolved
286
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
287
+ .replace(/\.ts$/, ".js");
288
+ if (existsSync(distPath)) return distPath;
289
+ console.warn(
290
+ "[agent-steward] Не найден собранный worktree-run.js: " +
291
+ `${distPath}. Изоляция в git worktree не будет работать. Выполните npm run build.`,
292
+ );
293
+ return distPath;
294
+ })();
295
+
296
+ /**
297
+ * W-3: путь к CLI-помощнику guard-условий (dist/core/guard-run.js).
298
+ */
299
+ const guardHelperPath = (() => {
300
+ const resolved = require.resolve("./core/guard-run.js");
301
+ if (!resolved.endsWith(".ts")) return resolved;
302
+ const distPath = resolved
303
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
304
+ .replace(/\.ts$/, ".js");
305
+ if (existsSync(distPath)) return distPath;
306
+ console.warn(
307
+ "[agent-steward] Не найден собранный guard-run.js: " +
308
+ `${distPath}. Guard-условия не будут проверяться. Выполните npm run build.`,
309
+ );
310
+ return distPath;
311
+ })();
312
+
207
313
  /** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
208
314
  const scheduler = getSchedulerBackend();
209
315
 
@@ -259,12 +365,125 @@ export const matrixSchema = z.object({
259
365
  ),
260
366
  });
261
367
 
368
+ /** W-3: guard-условия задачи. */
369
+ export const guardsSchema = z.object({
370
+ command: z
371
+ .string()
372
+ .max(4000)
373
+ .optional()
374
+ .describe("Shell command evaluated before the run. Exit 0 runs the task; any other code skips it."),
375
+ timeoutSeconds: z
376
+ .number()
377
+ .int()
378
+ .min(1)
379
+ .max(3600)
380
+ .optional()
381
+ .describe("Shell guard timeout in seconds (default 60)."),
382
+ semantic: z
383
+ .object({
384
+ filesExist: z.array(z.string()).max(200).optional().describe("Paths that must exist."),
385
+ filesMissing: z.array(z.string()).max(200).optional().describe("Paths that must not exist."),
386
+ branch: z.string().max(200).optional().describe("Glob for the current git branch, e.g. feature/*."),
387
+ changedPaths: z
388
+ .array(z.string())
389
+ .max(200)
390
+ .optional()
391
+ .describe("Globs of changed paths; at least one must match."),
392
+ changedSince: z
393
+ .string()
394
+ .max(100)
395
+ .optional()
396
+ .describe("Git ref to diff against (default HEAD~1)."),
397
+ })
398
+ .optional()
399
+ .describe("Semantic pre-run checks inside the working directory."),
400
+ }).describe("W-3: guard conditions. If a check fails, the run is skipped before opencode starts.");
401
+
402
+ /**
403
+ * QA-P2.1: маска glob не может быть пустой или содержать пробелы.
404
+ * Пробел в `** /*.md` молча сужает совпадение до файлов с пробелом в имени.
405
+ */
406
+ const globMaskSchema = z.string().min(1).refine((mask) => !/\s/.test(mask), {
407
+ message: "Glob mask must be non-empty and contain no whitespace.",
408
+ });
409
+
410
+ /**
411
+ * QA-P2.1: единая проверка диапазонов для MCP и RPC.
412
+ * Zod-схемы защищают только MCP-путь; RPC (create_task/update_task) принимает
413
+ * сырой JSON и вызывает эту функцию явно, до normalizePriority(), который
414
+ * молча обрезает priority до 0..10.
415
+ * Возвращает текст ошибки или null.
416
+ */
417
+ export function validateTaskInputRanges(input: {
418
+ prompt?: string;
419
+ timeoutSeconds?: number;
420
+ priority?: number;
421
+ retryCount?: number;
422
+ retryDelay?: number;
423
+ watchPath?: string;
424
+ triggerType?: string;
425
+ watchGlobs?: string[];
426
+ watchIgnore?: string[];
427
+ gitPaths?: string[];
428
+ gitIgnore?: string[];
429
+ }): string | null {
430
+ if (input.prompt !== undefined && !input.prompt.trim()) {
431
+ return "prompt must be a non-empty string.";
432
+ }
433
+ if (
434
+ input.timeoutSeconds !== undefined &&
435
+ (!Number.isInteger(input.timeoutSeconds) || input.timeoutSeconds <= 0)
436
+ ) {
437
+ return "timeoutSeconds must be a positive integer.";
438
+ }
439
+ if (
440
+ input.priority !== undefined &&
441
+ (!Number.isInteger(input.priority) || input.priority < 0 || input.priority > 10)
442
+ ) {
443
+ return "priority must be an integer between 0 and 10.";
444
+ }
445
+ if (
446
+ input.retryCount !== undefined &&
447
+ (!Number.isInteger(input.retryCount) || input.retryCount < 0)
448
+ ) {
449
+ return "retryCount must be a non-negative integer.";
450
+ }
451
+ if (
452
+ input.retryDelay !== undefined &&
453
+ (!Number.isInteger(input.retryDelay) || input.retryDelay < 0)
454
+ ) {
455
+ return "retryDelay must be a non-negative integer.";
456
+ }
457
+ const globFields: [string, string[] | undefined][] = [
458
+ ["watchGlobs", input.watchGlobs],
459
+ ["watchIgnore", input.watchIgnore],
460
+ ["gitPaths", input.gitPaths],
461
+ ["gitIgnore", input.gitIgnore],
462
+ ];
463
+ for (const [field, masks] of globFields) {
464
+ if (!Array.isArray(masks)) continue;
465
+ for (const mask of masks) {
466
+ if (typeof mask !== "string" || !mask.trim() || /\s/.test(mask)) {
467
+ return `${field} masks must be non-empty strings without whitespace.`;
468
+ }
469
+ }
470
+ }
471
+ if (
472
+ input.triggerType === "file" &&
473
+ input.watchPath !== undefined &&
474
+ !input.watchPath.trim()
475
+ ) {
476
+ return "watchPath must be a non-empty path when triggerType is file.";
477
+ }
478
+ return null;
479
+ }
480
+
262
481
  /** Zod-схема аргументов schedule_task */
263
482
  export const scheduleTaskSchema = z.object({
264
483
  name: z
265
484
  .string()
266
485
  .describe(
267
- "Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen.",
486
+ "Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and ASCII hyphen '-'. Do NOT use the em dash '—' or round brackets '()': validation rejects them and the original title will be lost. Use ASCII '-' and plain words instead, e.g. 'QA-A2 - Full plugin typing epic'.",
268
487
  ),
269
488
  schedule: z
270
489
  .string()
@@ -319,9 +538,13 @@ export const scheduleTaskSchema = z.object({
319
538
  .describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
320
539
  prompt: z
321
540
  .string()
541
+ .min(1, "prompt must be a non-empty string.")
542
+ .refine((value) => value.trim().length > 0, "prompt must be a non-empty string.")
322
543
  .describe("Prompt passed to the agent on every run."),
323
544
  timeoutSeconds: z
324
545
  .number()
546
+ .int()
547
+ .positive()
325
548
  .optional()
326
549
  .describe("Run timeout in seconds (default 3600)."),
327
550
  model: z
@@ -332,6 +555,9 @@ export const scheduleTaskSchema = z.object({
332
555
  ),
333
556
  priority: z
334
557
  .number()
558
+ .int()
559
+ .min(0)
560
+ .max(10)
335
561
  .optional()
336
562
  .describe("Task priority 0..10 (10 is the highest). Default 5 (normal)."),
337
563
  beforeScript: z
@@ -360,10 +586,14 @@ export const scheduleTaskSchema = z.object({
360
586
  ),
361
587
  retryCount: z
362
588
  .number()
589
+ .int()
590
+ .nonnegative()
363
591
  .optional()
364
592
  .describe("How many times to retry a failed run (default 0)."),
365
593
  retryDelay: z
366
594
  .number()
595
+ .int()
596
+ .nonnegative()
367
597
  .optional()
368
598
  .describe("Delay between retries in seconds (default 60)."),
369
599
  nextTaskOnSuccess: z
@@ -383,12 +613,23 @@ export const scheduleTaskSchema = z.object({
383
613
  mcpEvent: z
384
614
  .object({
385
615
  server: z.string(),
386
- event: z.string(),
616
+ event: z
617
+ .string()
618
+ .optional()
619
+ .describe(
620
+ "event or eventName (alias); eventName is accepted for emit_event compatibility",
621
+ ),
622
+ eventName: z
623
+ .string()
624
+ .optional()
625
+ .describe(
626
+ "event or eventName (alias); eventName is accepted for emit_event compatibility",
627
+ ),
387
628
  filter: z.string().optional(),
388
629
  })
389
630
  .optional()
390
631
  .describe(
391
- "MCP event trigger: server, event name and an optional filter (key=value or regex).",
632
+ "MCP event trigger: server, event (or its alias eventName) and an optional filter (key=value or regex). At least one of event/eventName is required for triggerType=mcp-event.",
392
633
  ),
393
634
  watchPath: z
394
635
  .string()
@@ -397,13 +638,13 @@ export const scheduleTaskSchema = z.object({
397
638
  "File or directory to watch when triggerType is \"file\". Can be set here or later via update_task.",
398
639
  ),
399
640
  watchGlobs: z
400
- .array(z.string())
641
+ .array(globMaskSchema)
401
642
  .optional()
402
643
  .describe(
403
644
  "Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath.",
404
645
  ),
405
646
  watchIgnore: z
406
- .array(z.string())
647
+ .array(globMaskSchema)
407
648
  .optional()
408
649
  .describe(
409
650
  "Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include.",
@@ -415,13 +656,13 @@ export const scheduleTaskSchema = z.object({
415
656
  "Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch.",
416
657
  ),
417
658
  gitPaths: z
418
- .array(z.string())
659
+ .array(globMaskSchema)
419
660
  .optional()
420
661
  .describe(
421
662
  "Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only).",
422
663
  ),
423
664
  gitIgnore: z
424
- .array(z.string())
665
+ .array(globMaskSchema)
425
666
  .optional()
426
667
  .describe("Only for triggerType=git: glob masks of changed files to ignore."),
427
668
  gitPollSeconds: z
@@ -478,6 +719,26 @@ export const scheduleTaskSchema = z.object({
478
719
  .describe(
479
720
  "Windows only: run the task even when no user is logged on (/ru SYSTEM). The task runs in session 0 without the user's profile, mapped drives or saved credentials, so tasks that need the user's environment may fail. Creating such a task usually requires an elevated shell. Default false: interactive only — the task runs only while the user is logged on.",
480
721
  ),
722
+ worktree: z
723
+ .boolean()
724
+ .optional()
725
+ .describe(
726
+ "W-1: run each tick in a one-off git worktree created from HEAD of workingDirectory. Keeps fan-out runs isolated from each other and from the main checkout. Requires a git repository; creation failure fails the run closed. Default false.",
727
+ ),
728
+ guards: guardsSchema
729
+ .optional()
730
+ .describe(
731
+ "W-3: pre-run guard conditions. If a semantic check or shell command fails, the run is skipped (no opencode, no side effects). Combined with worktree: checks run inside the fresh worktree.",
732
+ ),
733
+ tokenBudget: z
734
+ .number()
735
+ .int()
736
+ .min(0)
737
+ .max(10_000_000)
738
+ .optional()
739
+ .describe(
740
+ "Economics v2 (E-2): per-run token budget. 0 or omitted = no task limit (fail-open). Exceeded runs are flagged in analytics; stopping is E-2.2.",
741
+ ),
481
742
  matrix: matrixSchema
482
743
  .optional()
483
744
  .describe(
@@ -517,16 +778,37 @@ export const scheduleTaskSchema = z.object({
517
778
  message: t("tool.error.onceFields"),
518
779
  });
519
780
  }
781
+ // QA-P2.1: явная пустая строка watchPath при file-триггере бессмысленна.
782
+ if (trigger === "file" && value.watchPath !== undefined && !value.watchPath.trim()) {
783
+ ctx.addIssue({
784
+ code: z.ZodIssueCode.custom,
785
+ path: ["watchPath"],
786
+ message: "watchPath must be a non-empty path when triggerType is file.",
787
+ });
788
+ }
520
789
  });
521
790
 
522
791
  const listTasksSchema = z.object({});
523
792
 
793
+ /** PL-43: структурированный ответ list_tasks для Code Mode (V2). */
794
+ const listTasksOutputSchema = z.object({
795
+ success: z.boolean(),
796
+ message: z.string(),
797
+ tasks: z.array(z.unknown()),
798
+ osAvailable: z.boolean(),
799
+ osError: z.string().optional(),
800
+ });
801
+
524
802
  const deleteTaskSchema = z.object({
525
803
  name: z.string().describe("Task name to delete."),
526
804
  });
527
805
 
528
806
  const runTaskNowSchema = z.object({
529
- name: z.string().describe("Task name to run immediately."),
807
+ name: z
808
+ .string()
809
+ .describe(
810
+ "Task name to run immediately. While the plugin unloads the tool returns a structured PLUGIN_SHUTTING_DOWN error (message + retry hint).",
811
+ ),
530
812
  });
531
813
 
532
814
  export const updateTaskSchema = z.object({
@@ -593,11 +875,11 @@ export const updateTaskSchema = z.object({
593
875
  "Windows only: true runs the task without a logged-on user (/ru SYSTEM, session 0 without the user profile, mapped drives or saved credentials; usually requires an elevated shell). false/omitted keeps the task interactive-only.",
594
876
  ),
595
877
  watchGlobs: z
596
- .array(z.string())
878
+ .array(globMaskSchema)
597
879
  .optional()
598
880
  .describe("New glob masks for a file trigger. Empty array clears them."),
599
881
  watchIgnore: z
600
- .array(z.string())
882
+ .array(globMaskSchema)
601
883
  .optional()
602
884
  .describe("New ignore masks for a file trigger. Empty array clears them."),
603
885
  gitBranch: z
@@ -605,11 +887,11 @@ export const updateTaskSchema = z.object({
605
887
  .optional()
606
888
  .describe("New git branch filter (glob, comma-separated). Empty string clears it."),
607
889
  gitPaths: z
608
- .array(z.string())
890
+ .array(globMaskSchema)
609
891
  .optional()
610
892
  .describe("New changed-file masks for a git trigger. Empty array clears them."),
611
893
  gitIgnore: z
612
- .array(z.string())
894
+ .array(globMaskSchema)
613
895
  .optional()
614
896
  .describe("New ignored changed-file masks for a git trigger. Empty array clears them."),
615
897
  gitPollSeconds: z
@@ -620,14 +902,26 @@ export const updateTaskSchema = z.object({
620
902
  .describe("New git polling interval in seconds."),
621
903
  prompt: z
622
904
  .string()
905
+ .refine((value) => value.trim().length > 0, "prompt must be a non-empty string.")
623
906
  .optional()
624
907
  .describe("New prompt. Keeps the current value when omitted."),
625
- timeoutSeconds: z.number().optional().describe("New run timeout in seconds."),
908
+ timeoutSeconds: z
909
+ .number()
910
+ .int()
911
+ .positive()
912
+ .optional()
913
+ .describe("New run timeout in seconds."),
626
914
  model: z
627
915
  .string()
628
916
  .optional()
629
917
  .describe("New model in OpenCode format. Empty string clears it (default model)."),
630
- priority: z.number().optional().describe("New priority 0..10."),
918
+ priority: z
919
+ .number()
920
+ .int()
921
+ .min(0)
922
+ .max(10)
923
+ .optional()
924
+ .describe("New priority 0..10."),
631
925
  beforeScript: z
632
926
  .string()
633
927
  .optional()
@@ -644,8 +938,8 @@ export const updateTaskSchema = z.object({
644
938
  .array(z.string())
645
939
  .optional()
646
940
  .describe("New DAG dependencies. Empty array clears them."),
647
- retryCount: z.number().optional().describe("New retry count."),
648
- retryDelay: z.number().optional().describe("New retry delay in seconds."),
941
+ retryCount: z.number().int().nonnegative().optional().describe("New retry count."),
942
+ retryDelay: z.number().int().nonnegative().optional().describe("New retry delay in seconds."),
649
943
  nextTaskOnSuccess: z
650
944
  .string()
651
945
  .optional()
@@ -661,11 +955,24 @@ export const updateTaskSchema = z.object({
661
955
  mcpEvent: z
662
956
  .object({
663
957
  server: z.string(),
664
- event: z.string(),
958
+ event: z
959
+ .string()
960
+ .optional()
961
+ .describe(
962
+ "event or eventName (alias); eventName is accepted for emit_event compatibility",
963
+ ),
964
+ eventName: z
965
+ .string()
966
+ .optional()
967
+ .describe(
968
+ "event or eventName (alias); eventName is accepted for emit_event compatibility",
969
+ ),
665
970
  filter: z.string().optional(),
666
971
  })
667
972
  .optional()
668
- .describe("New MCP event trigger."),
973
+ .describe(
974
+ "New MCP event trigger: event (or its alias eventName); at least one of them is required for triggerType=mcp-event.",
975
+ ),
669
976
  watchPath: z
670
977
  .string()
671
978
  .optional()
@@ -692,6 +999,24 @@ export const updateTaskSchema = z.object({
692
999
  .describe(
693
1000
  "Transitional flag (release 1.6): re-enable shell under the hybrid policy for this task.",
694
1001
  ),
1002
+ worktree: z
1003
+ .boolean()
1004
+ .optional()
1005
+ .describe(
1006
+ "W-1: run each tick in a one-off git worktree created from HEAD of workingDirectory. Default false.",
1007
+ ),
1008
+ guards: guardsSchema
1009
+ .optional()
1010
+ .describe("W-3: pre-run guard conditions; a failed check skips the run."),
1011
+ tokenBudget: z
1012
+ .number()
1013
+ .int()
1014
+ .min(0)
1015
+ .max(10_000_000)
1016
+ .optional()
1017
+ .describe(
1018
+ "Economics v2 (E-2): per-run token budget. 0 or omitted = no task limit (fail-open). Pass 0 to clear a previous limit.",
1019
+ ),
695
1020
  matrix: matrixSchema
696
1021
  .nullable()
697
1022
  .optional()
@@ -717,6 +1042,18 @@ export const updateTaskSchema = z.object({
717
1042
  message: t("tool.error.onceMatrixUpdate"),
718
1043
  });
719
1044
  }
1045
+ // QA-P2.1: пустой watchPath допустим только для очистки не-file триггера.
1046
+ if (
1047
+ value.triggerType === "file" &&
1048
+ value.watchPath !== undefined &&
1049
+ !value.watchPath.trim()
1050
+ ) {
1051
+ ctx.addIssue({
1052
+ code: z.ZodIssueCode.custom,
1053
+ path: ["watchPath"],
1054
+ message: "watchPath must be a non-empty path when triggerType is file.",
1055
+ });
1056
+ }
720
1057
  });
721
1058
 
722
1059
  const pauseTaskSchema = z.object({
@@ -748,8 +1085,9 @@ const getHistorySchema = z.object({
748
1085
  .describe("Maximum number of records to return (default 20, max 200)."),
749
1086
  });
750
1087
 
751
- const getTaskLogsSchema = z.object({
752
- name: z.string().describe("Task name to read logs for."),
1088
+ export const getTaskLogsSchema = z.object({
1089
+ name: z.string().optional().describe("Task name to read logs for (alias: taskName)."),
1090
+ taskName: z.string().optional().describe("Alias for name; both spellings are accepted."),
753
1091
  lines: z
754
1092
  .number()
755
1093
  .optional()
@@ -765,6 +1103,61 @@ const dryRunSchema = z.object({
765
1103
  ),
766
1104
  });
767
1105
 
1106
+ /** pipeline_validate — проверить опencode.pipeline.yaml (путь или исходник). */
1107
+ export const pipelineValidateSchema = z.object({
1108
+ path: z
1109
+ .string()
1110
+ .optional()
1111
+ .describe("Путь к файлу opencode.pipeline.yaml (относительный резолвится против cwd) или source."),
1112
+ source: z.string().optional().describe("Исходное содержимое YAML (альтернатива path)."),
1113
+ workingDirectory: z
1114
+ .string()
1115
+ .optional()
1116
+ .describe("База для относительного path (по умолчанию cwd процесса, затем подсказки окружения)."),
1117
+ dryRun: z
1118
+ .boolean()
1119
+ .optional()
1120
+ .default(true)
1121
+ .describe("Если true — только валидация без применения (по умолчанию true)."),
1122
+ });
1123
+
1124
+ /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
1125
+ export const pipelineApplySchema = z.object({
1126
+ path: z
1127
+ .string()
1128
+ .optional()
1129
+ .describe("Путь к файлу opencode.pipeline.yaml (относительный резолвится против cwd) или source."),
1130
+ source: z.string().optional().describe("Исходное содержимое YAML (альтернатива path)."),
1131
+ workingDirectory: z
1132
+ .string()
1133
+ .optional()
1134
+ .describe("База для относительного path (по умолчанию cwd процесса, затем подсказки окружения)."),
1135
+ dryRun: z
1136
+ .boolean()
1137
+ .optional()
1138
+ .default(false)
1139
+ .describe("Если true — прогон diff'а без применения изменений (по умолчанию false)."),
1140
+ });
1141
+
1142
+ /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
1143
+ export const pipelineExportSchema = z
1144
+ .object({
1145
+ pipeline: z.string().optional().describe("Имя конвейера (pipelineName)."),
1146
+ pipelineName: z.string().optional().describe("Алиас параметра pipeline — имя конвейера."),
1147
+ })
1148
+ .superRefine((value, ctx) => {
1149
+ // QA-P3.2: разные имена в двух полях — ошибка, а не молчаливый приоритет pipeline.
1150
+ const explicit = value.pipeline?.trim();
1151
+ const alias = value.pipelineName?.trim();
1152
+ if (explicit && alias && explicit.toLowerCase() !== alias.toLowerCase()) {
1153
+ ctx.addIssue({
1154
+ code: z.ZodIssueCode.custom,
1155
+ path: ["pipelineName"],
1156
+ message: "Конфликт параметров: pipeline и pipelineName задают разные имена конвейера.",
1157
+ });
1158
+ }
1159
+ });
1160
+
768
1161
  const manageWorkspacesSchema = z.object({
769
1162
  action: z
770
1163
  .enum(["list", "add", "update", "delete"])
@@ -869,8 +1262,8 @@ export const selfAnalysisSchema = z.object({
869
1262
  /** manage_settings — глобальные настройки планировщика. */
870
1263
  export const manageSettingsSchema = z.object({
871
1264
  action: z
872
- .enum(["get", "update"])
873
- .describe("get — current settings; update — merge the provided fields and save."),
1265
+ .enum(["get", "list", "update"])
1266
+ .describe("get - current settings; list - same as get (agent-friendly alias); update - merge the provided fields and save."),
874
1267
  maxConcurrent: z
875
1268
  .number()
876
1269
  .int()
@@ -882,7 +1275,7 @@ export const manageSettingsSchema = z.object({
882
1275
  .enum(["auto", "ru", "en", "zh"])
883
1276
  .optional()
884
1277
  .describe(
885
- "Interface language: auto (follow OpenCode), ru (default), en or zh. Applies without restart.",
1278
+ "Interface language: auto (default, follows OpenCode), ru, en or zh. Applies without restart.",
886
1279
  ),
887
1280
  winterMode: z
888
1281
  .boolean()
@@ -917,6 +1310,28 @@ export const manageSettingsSchema = z.object({
917
1310
  .describe(
918
1311
  "Tool permission policy for background tasks: hybrid (default; shell/question denied), secure (read-only), legacy (allow everything, 1.5.x behaviour).",
919
1312
  ),
1313
+ budgets: z
1314
+ .object({
1315
+ enabled: z.boolean().optional(),
1316
+ dailyUsd: z.number().min(0).max(1_000_000).optional(),
1317
+ weeklyUsd: z.number().min(0).max(1_000_000).optional(),
1318
+ })
1319
+ .optional()
1320
+ .describe(
1321
+ "Daily/weekly USD budgets (0 = no limit). Accounting is exposed by get_analytics as report.budgets.",
1322
+ ),
1323
+ feedback: z
1324
+ .object({
1325
+ enabled: z.boolean().optional(),
1326
+ endpoint: z.string().max(2048).optional(),
1327
+ includeLogs: z.boolean().optional(),
1328
+ contactEmail: z.string().max(254).optional(),
1329
+ maxPerHour: z.number().int().min(1).max(100).optional(),
1330
+ })
1331
+ .optional()
1332
+ .describe(
1333
+ "Author feedback (bug reports → GitHub Issues). disabled by default; endpoint must be https (http only for localhost).",
1334
+ ),
920
1335
  });
921
1336
 
922
1337
  /** manage_local_ai — настройки локального ассистента и триажа (Спринт 30.7). */
@@ -981,8 +1396,8 @@ export const manageLocalAiSchema = z.object({
981
1396
  export const manageTemplatesSchema = z.object({
982
1397
  action: z
983
1398
  .enum(["list", "save", "delete"])
984
- .describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
985
- id: z.string().optional().describe("Template id for update/delete."),
1399
+ .describe("list — all templates; save — create or update (id omitted = create); delete — remove by id or name."),
1400
+ id: z.string().optional().describe("Template id for update; for delete an id or a template name is accepted."),
986
1401
  name: z.string().optional().describe("Template name."),
987
1402
  prompt: z.string().optional().describe("Prompt text stored in the template."),
988
1403
  schedule: z.string().optional().describe("Cron expression."),
@@ -1001,10 +1416,24 @@ export const manageTemplatesSchema = z.object({
1001
1416
  mcpEvent: z
1002
1417
  .object({
1003
1418
  server: z.string(),
1004
- event: z.string(),
1419
+ event: z
1420
+ .string()
1421
+ .optional()
1422
+ .describe(
1423
+ "event or eventName (alias); eventName is accepted for emit_event compatibility",
1424
+ ),
1425
+ eventName: z
1426
+ .string()
1427
+ .optional()
1428
+ .describe(
1429
+ "event or eventName (alias); eventName is accepted for emit_event compatibility",
1430
+ ),
1005
1431
  filter: z.string().optional(),
1006
1432
  })
1007
- .optional(),
1433
+ .optional()
1434
+ .describe(
1435
+ "MCP event trigger: event (or its alias eventName); at least one of them is required for triggerType=mcp-event.",
1436
+ ),
1008
1437
  watchPath: z.string().optional(),
1009
1438
  workingDirectory: z.string().optional(),
1010
1439
  allowedTools: z.array(z.string()).optional(),
@@ -1037,6 +1466,22 @@ export const sendNotificationSchema = z.object({
1037
1466
  .describe("For action=test: which channel to check (default all enabled)."),
1038
1467
  });
1039
1468
 
1469
+ /** report_bug — отчёт о баге; по умолчанию уходит автору через приёмник F-2 (Деталь 3.8). */
1470
+ export const reportBugSchema = z.object({
1471
+ description: z.string().min(1).max(FEEDBACK_LIMITS.description).describe("Описание бага от пользователя (обязательно)."),
1472
+ taskName: z.string().max(FEEDBACK_LIMITS.taskName).optional().describe("Имя задачи, к которой относится баг (для прикрепления логов)."),
1473
+ /** Приватность: по умолчанию логи НЕ прикладываются (F-1.3). */
1474
+ includeLogs: z.boolean().optional().default(false).describe("Включить логи задачи (по умолчанию false)."),
1475
+ includeAnalytics: z.boolean().optional().default(true).describe("Включить метрики и аналитику за последние 7 дней."),
1476
+ /** Канал локальных уведомлений (для destination local/both). */
1477
+ channel: z.enum(["all", "webhook", "telegram", "native"]).optional().describe("Канал локального уведомления."),
1478
+ /** Направление: автор (по умолчанию), локальные каналы или оба (F-1.5). */
1479
+ destination: z.enum(["author", "local", "both"]).optional().default("author").describe("Куда отправить отчёт."),
1480
+ contactEmail: z.string().max(FEEDBACK_LIMITS.contactEmail).optional().describe("Обратный адрес (опционально)."),
1481
+ /** Показать точный payload без отправки (F-3.1). */
1482
+ dryRun: z.boolean().optional().default(false).describe("Предпросмотр без отправки."),
1483
+ });
1484
+
1040
1485
  /** get_dashboard_info — сведения о панели управления. */
1041
1486
  export const getDashboardInfoSchema = z.object({});
1042
1487
 
@@ -1050,6 +1495,10 @@ export const cleanupHistorySchema = z.object({
1050
1495
  export const emitEventSchema = z.object({
1051
1496
  eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
1052
1497
  payload: z.any().optional().describe("Event payload passed to trigger filters."),
1498
+ server: z
1499
+ .string()
1500
+ .optional()
1501
+ .describe("Optional MCP source/server name (e.g. 'github'). When set, only tasks with the same mcpEvent.server are triggered."),
1053
1502
  });
1054
1503
 
1055
1504
  /** manage_secrets — зашифрованное хранилище секретов (Спринт 26). */
@@ -1100,11 +1549,15 @@ type TemplatesArgs = z.infer<typeof manageTemplatesSchema>;
1100
1549
  type ProfilesArgs = z.infer<typeof manageProfilesSchema>;
1101
1550
  type TransferArgs = z.infer<typeof transferTasksSchema>;
1102
1551
  type NotificationArgs = z.infer<typeof sendNotificationSchema>;
1552
+ type ReportBugArgs = z.infer<typeof reportBugSchema>;
1103
1553
  type DashboardInfoArgs = z.infer<typeof getDashboardInfoSchema>;
1104
1554
  type CleanupHistoryArgs = z.infer<typeof cleanupHistorySchema>;
1105
1555
  type EmitEventArgs = z.infer<typeof emitEventSchema>;
1106
1556
  type SecretsArgs = z.infer<typeof manageSecretsSchema>;
1107
1557
  type AuditLogArgs = z.infer<typeof getAuditLogSchema>;
1558
+ type PipelineValidateArgs = z.infer<typeof pipelineValidateSchema>;
1559
+ type PipelineApplyArgs = z.infer<typeof pipelineApplySchema>;
1560
+ type PipelineExportArgs = z.infer<typeof pipelineExportSchema>;
1108
1561
 
1109
1562
  /**
1110
1563
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
@@ -1113,22 +1566,43 @@ type AuditLogArgs = z.infer<typeof getAuditLogSchema>;
1113
1566
  */
1114
1567
  let projectDirectory: string | undefined;
1115
1568
 
1569
+ /**
1570
+ * Общий контекст execute-обработчиков. Обработчики не читают поля контекста,
1571
+ * а контексты V1 и V2 устроены по-разному, поэтому на границе адаптеров он
1572
+ * сводится к `unknown`. Это позволяет не тащить `Tool.Context` из
1573
+ * @opencode/schema/tool в общий контракт инструментов.
1574
+ */
1575
+ type ToolExecuteContext = unknown;
1576
+
1116
1577
  /**
1117
1578
  * Обёртка execute-функции: ловит ошибки и возвращает Tool.Result с content.
1118
- * Использует Tool.Context из @opencode/schema/tool.
1119
1579
  */
1120
1580
  function wrapExecute<Args>(
1121
- fn: (args: Args, ctx: Tool.Context) => Promise<Tool.Result>,
1122
- ): (input: Args, context: Tool.Context) => Promise<Tool.Result> {
1581
+ fn: (args: Args, ctx: ToolExecuteContext) => Promise<Tool.Result>,
1582
+ ): (input: Args, context: ToolExecuteContext) => Promise<Tool.Result> {
1123
1583
  return async (input, context) => {
1124
1584
  try {
1125
1585
  return await fn(input, context);
1126
- } catch (err: any) {
1586
+ } catch (err) {
1587
+ const shutdown =
1588
+ err instanceof PluginShutdownError
1589
+ ? {
1590
+ code: err.code,
1591
+ hint: err.hint,
1592
+ retryable: err.retryable,
1593
+ shutdownState: err.state,
1594
+ }
1595
+ : {};
1596
+ // PL-43: тот же payload отдаём и структурированным output, и строкой
1597
+ // content — V1-адаптер по-прежнему читает content.
1598
+ const output = {
1599
+ success: false,
1600
+ error: err instanceof Error ? err.message : String(err),
1601
+ ...shutdown,
1602
+ };
1127
1603
  return {
1128
- content: JSON.stringify({
1129
- success: false,
1130
- error: err instanceof Error ? err.message : String(err),
1131
- }),
1604
+ output,
1605
+ content: JSON.stringify(output),
1132
1606
  };
1133
1607
  }
1134
1608
  };
@@ -1220,6 +1694,9 @@ function computeTaskNextRun(
1220
1694
 
1221
1695
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
1222
1696
  const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
1697
+ // QA-P2.1: RPC-путь не проходит Zod — проверяем диапазоны явно.
1698
+ const rangeError = validateTaskInputRanges(args);
1699
+ if (rangeError) throw new Error(rangeError);
1223
1700
  const {
1224
1701
  name,
1225
1702
  schedule,
@@ -1260,6 +1737,9 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
1260
1737
  gitPollSeconds,
1261
1738
  runWhenLoggedOff,
1262
1739
  legacyShell,
1740
+ worktree,
1741
+ guards,
1742
+ tokenBudget,
1263
1743
  } = args;
1264
1744
 
1265
1745
  let effectiveRunAt: string | undefined;
@@ -1328,8 +1808,11 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
1328
1808
  runWhenLoggedOff === true,
1329
1809
  undefined,
1330
1810
  legacyShell === true,
1811
+ worktree === true,
1812
+ guards,
1813
+ tokenBudget,
1331
1814
  );
1332
- } catch (err: any) {
1815
+ } catch (err) {
1333
1816
  return {
1334
1817
  content: JSON.stringify({
1335
1818
  success: false,
@@ -1394,6 +1877,8 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
1394
1877
  workspaceId: workspace?.id ?? null,
1395
1878
  workspaceName: workspace?.name ?? null,
1396
1879
  matrix: matrix ?? null,
1880
+ worktree: worktree === true,
1881
+ guards: guards ?? null,
1397
1882
  },
1398
1883
  }),
1399
1884
  };
@@ -1404,30 +1889,28 @@ const listTasksExecute = wrapExecute<ListArgs>(async () => {
1404
1889
  const { tasks, osAvailable, osError } = await collectTasksView();
1405
1890
 
1406
1891
  if (tasks.length === 0) {
1407
- return {
1408
- content: JSON.stringify({
1409
- success: true,
1410
- message: osAvailable
1411
- ? t("tool.task.listEmpty")
1412
- : t("tool.task.listOsUnavailable"),
1413
- tasks: [],
1414
- osAvailable,
1415
- ...(osError ? { osError } : {}),
1416
- }),
1417
- };
1418
- }
1419
-
1420
- return {
1421
- content: JSON.stringify({
1892
+ const output = {
1422
1893
  success: true,
1423
1894
  message: osAvailable
1424
- ? t("tool.task.found", { count: tasks.length })
1425
- : t("tool.task.foundOsUnavailable", { count: tasks.length }),
1426
- tasks,
1895
+ ? t("tool.task.listEmpty")
1896
+ : t("tool.task.listOsUnavailable"),
1897
+ tasks: [],
1427
1898
  osAvailable,
1428
1899
  ...(osError ? { osError } : {}),
1429
- }),
1900
+ };
1901
+ return { output, content: JSON.stringify(output) };
1902
+ }
1903
+
1904
+ const output = {
1905
+ success: true,
1906
+ message: osAvailable
1907
+ ? t("tool.task.found", { count: tasks.length })
1908
+ : t("tool.task.foundOsUnavailable", { count: tasks.length }),
1909
+ tasks,
1910
+ osAvailable,
1911
+ ...(osError ? { osError } : {}),
1430
1912
  };
1913
+ return { output, content: JSON.stringify(output) };
1431
1914
  });
1432
1915
 
1433
1916
  /**
@@ -1458,7 +1941,7 @@ async function cancelMatrixRun(
1458
1941
  // Удаление запущенной задачи планировщика останавливает её процесс.
1459
1942
  try {
1460
1943
  await scheduler.deleteTask(clone.name);
1461
- } catch (err: any) {
1944
+ } catch (err) {
1462
1945
  warnings.push(
1463
1946
  t("tool.matrix.stopFailed", {
1464
1947
  clone: clone.name,
@@ -1507,8 +1990,12 @@ async function cancelMatrixRun(
1507
1990
  clone.runWhenLoggedOff,
1508
1991
  clone.paused,
1509
1992
  clone.legacyShell,
1993
+ clone.worktree,
1994
+ clone.guards,
1995
+ // QA-P0.1 (E-2.1): клон матрицы наследует tokenBudget родителя.
1996
+ clone.tokenBudget,
1510
1997
  );
1511
- } catch (err: any) {
1998
+ } catch (err) {
1512
1999
  warnings.push(
1513
2000
  t("tool.matrix.recreateFailed", {
1514
2001
  clone: clone.name,
@@ -1733,11 +2220,11 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
1733
2220
  : t("tool.task.deleted", { name }),
1734
2221
  }),
1735
2222
  };
1736
- } catch (err: any) {
2223
+ } catch (err) {
1737
2224
  return {
1738
2225
  content: JSON.stringify({
1739
2226
  success: false,
1740
- error: err.message || String(err),
2227
+ error: err instanceof Error ? err.message : String(err),
1741
2228
  }),
1742
2229
  };
1743
2230
  }
@@ -1747,15 +2234,22 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
1747
2234
  const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
1748
2235
  const { name } = args;
1749
2236
 
2237
+ // PL-8.1: тот же дрейф HEAD, что и в dry_run, показываем при ручном старте.
2238
+ const definition = getTask(name);
2239
+ const warning =
2240
+ definition?.workingDirectory && definition.createdAt
2241
+ ? workingDirectoryDriftWarning(definition, definition.workingDirectory)
2242
+ : null;
2243
+
1750
2244
  let alreadyRunning = false;
1751
2245
  try {
1752
2246
  const result = await runTaskEntry(name);
1753
2247
  alreadyRunning = result.alreadyRunning;
1754
- } catch (err: any) {
2248
+ } catch (err) {
1755
2249
  return {
1756
2250
  content: JSON.stringify({
1757
2251
  success: false,
1758
- error: err.message || String(err),
2252
+ error: err instanceof Error ? err.message : String(err),
1759
2253
  }),
1760
2254
  };
1761
2255
  }
@@ -1766,6 +2260,7 @@ const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
1766
2260
  message: alreadyRunning
1767
2261
  ? t("tool.task.alreadyRunning", { name })
1768
2262
  : t("tool.task.started", { name }),
2263
+ ...(warning ? { warning } : {}),
1769
2264
  }),
1770
2265
  };
1771
2266
  });
@@ -1834,6 +2329,12 @@ async function updateTaskFromInput(
1834
2329
  return { success: false, message: t("tool.error.taskNameMissing") };
1835
2330
  }
1836
2331
 
2332
+ // QA-P2.1: RPC не проходит Zod — проверяем диапазоны явно.
2333
+ const rangeError = validateTaskInputRanges(input);
2334
+ if (rangeError) {
2335
+ return { success: false, message: rangeError };
2336
+ }
2337
+
1837
2338
  const previous = getTask(name);
1838
2339
  if (!previous) {
1839
2340
  return { success: false, message: t("tool.error.taskNotFound", { name }) };
@@ -2019,6 +2520,10 @@ async function updateTaskFromInput(
2019
2520
  input.runWhenLoggedOff ?? previous.runWhenLoggedOff,
2020
2521
  wasPaused,
2021
2522
  input.legacyShell ?? previous.legacyShell,
2523
+ input.worktree ?? previous.worktree,
2524
+ input.guards ?? previous.guards,
2525
+ // QA-P0.1 (E-2.1): budget переживает пересоздание задачи. 0 очищает лимит.
2526
+ input.tokenBudget ?? previous.tokenBudget,
2022
2527
  );
2023
2528
 
2024
2529
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
@@ -2072,7 +2577,7 @@ async function updateTaskFromInput(
2072
2577
  nextRun: computeTaskNextRun(updated, { paused }),
2073
2578
  message: t("tool.task.updated", { name }),
2074
2579
  };
2075
- } catch (err: any) {
2580
+ } catch (err) {
2076
2581
  const cause = err instanceof Error ? err.message : String(err);
2077
2582
 
2078
2583
  // Спринт 27.5.6: задача удалена из ОС, но новую версию создать не удалось.
@@ -2102,7 +2607,7 @@ async function updateTaskFromInput(
2102
2607
  restored: true,
2103
2608
  message: t("tool.task.rollbackRestored", { cause }),
2104
2609
  };
2105
- } catch (restoreErr: any) {
2610
+ } catch (restoreErr) {
2106
2611
  const restoreMessage =
2107
2612
  restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
2108
2613
  return {
@@ -2150,7 +2655,10 @@ async function pauseOrResumeTask(
2150
2655
  message: t("tool.error.taskNotFound", { name: trimmed }),
2151
2656
  affected: [],
2152
2657
  warnings: [],
2153
- paused,
2658
+ // QA-P3.8: в ошибке `paused` должен отражать реальное состояние,
2659
+ // а не запрошенное действие (иначе resume про несуществующей задаче
2660
+ // сообщает paused:false, а pause — paused:true).
2661
+ paused: false,
2154
2662
  nextRun: null,
2155
2663
  pausedUntil: null,
2156
2664
  };
@@ -2166,7 +2674,7 @@ async function pauseOrResumeTask(
2166
2674
  message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
2167
2675
  affected: [],
2168
2676
  warnings: [],
2169
- paused,
2677
+ paused: definition.paused ?? false,
2170
2678
  nextRun: null,
2171
2679
  pausedUntil: definition.pausedUntil ?? null,
2172
2680
  };
@@ -2177,7 +2685,7 @@ async function pauseOrResumeTask(
2177
2685
  message: t("tool.error.pauseDatePast", { name: trimmed }),
2178
2686
  affected: [],
2179
2687
  warnings: [],
2180
- paused,
2688
+ paused: definition.paused ?? false,
2181
2689
  nextRun: null,
2182
2690
  pausedUntil: definition.pausedUntil ?? null,
2183
2691
  };
@@ -2194,7 +2702,7 @@ async function pauseOrResumeTask(
2194
2702
  message: t("tool.error.matrixNoClones", { name: trimmed }),
2195
2703
  affected: [],
2196
2704
  warnings: [],
2197
- paused,
2705
+ paused: definition.paused ?? false,
2198
2706
  nextRun: null,
2199
2707
  pausedUntil: definition.pausedUntil ?? null,
2200
2708
  };
@@ -2210,7 +2718,7 @@ async function pauseOrResumeTask(
2210
2718
  await scheduler.resumeTask(target);
2211
2719
  }
2212
2720
  affected.push(target);
2213
- } catch (err: any) {
2721
+ } catch (err) {
2214
2722
  warnings.push(
2215
2723
  `${target}: ${err instanceof Error ? err.message : String(err)}`,
2216
2724
  );
@@ -2229,7 +2737,7 @@ async function pauseOrResumeTask(
2229
2737
  if (definitionUpdates && affected.length > 0) {
2230
2738
  try {
2231
2739
  saveTask({ ...definition, ...definitionUpdates });
2232
- } catch (err: any) {
2740
+ } catch (err) {
2233
2741
  warnings.push(
2234
2742
  t("tool.task.autosave", {
2235
2743
  error: err instanceof Error ? err.message : String(err),
@@ -2328,7 +2836,7 @@ async function resumeExpiredPauses(): Promise<void> {
2328
2836
  console.log(
2329
2837
  `[agent-steward] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`,
2330
2838
  );
2331
- } catch (err: any) {
2839
+ } catch (err) {
2332
2840
  console.error(
2333
2841
  `[agent-steward] Не удалось автопродолжить задачу "${definition.name}": ${
2334
2842
  err instanceof Error ? err.message : String(err)
@@ -2383,6 +2891,9 @@ async function checkStuckMatrices(): Promise<void> {
2383
2891
  /** get_history — история запусков с фильтрами по задаче и статусу. */
2384
2892
  const getHistoryExecute = wrapExecute<HistoryArgs>(async (args) => {
2385
2893
  const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
2894
+ // PL-46: зависшие записи (schtasks /End) должны закрываться не только при
2895
+ // setup, но и при наблюдении истории — иначе остаются running навсегда.
2896
+ recoverInterruptedRuns();
2386
2897
  const records = await loadHistory(args.taskName, limit, args.status);
2387
2898
 
2388
2899
  return {
@@ -2396,7 +2907,14 @@ const getHistoryExecute = wrapExecute<HistoryArgs>(async (args) => {
2396
2907
 
2397
2908
  /** get_task_logs — последние строки лога задачи. */
2398
2909
  const getTaskLogsExecute = wrapExecute<TaskLogsArgs>(async (args) => {
2399
- const result = await getTaskLogs(args.name, args.lines ?? 200);
2910
+ // PL-19: MCP-клиенты передают и name, и taskName — принимаем оба написания.
2911
+ const taskName = args.name?.trim() || args.taskName?.trim();
2912
+ if (!taskName) {
2913
+ return {
2914
+ content: JSON.stringify({ success: false, logs: "", error: "Укажите name или taskName задачи" }),
2915
+ };
2916
+ }
2917
+ const result = await getTaskLogs(taskName, args.lines ?? 200);
2400
2918
  if (result.error) {
2401
2919
  return {
2402
2920
  content: JSON.stringify({ success: false, logs: "", error: result.error }),
@@ -2416,11 +2934,11 @@ const dryRunExecute = wrapExecute<DryRunArgs>(async (args) => {
2416
2934
  }
2417
2935
 
2418
2936
  const definitions = await loadTaskDefinitions();
2419
- const reports: any[] = [];
2937
+ const reports: (DryRunReport & { error?: string })[] = [];
2420
2938
  for (const definition of definitions) {
2421
2939
  try {
2422
2940
  reports.push(await simulatePipeline(definition.name));
2423
- } catch (err: any) {
2941
+ } catch (err) {
2424
2942
  reports.push({
2425
2943
  success: false,
2426
2944
  taskName: definition.name,
@@ -2445,6 +2963,270 @@ const dryRunExecute = wrapExecute<DryRunArgs>(async (args) => {
2445
2963
  };
2446
2964
  });
2447
2965
 
2966
+ /** pipeline_validate — проверить opencode.pipeline.yaml (путь или исходник). */
2967
+ const pipelineValidateExecute = wrapExecute<PipelineValidateArgs>(async (args) => {
2968
+ if (args.path === undefined && args.source === undefined) {
2969
+ return {
2970
+ content: JSON.stringify({
2971
+ success: false,
2972
+ pipeline: null,
2973
+ errors: ["Укажите path к файлу или source с содержимым YAML"],
2974
+ warnings: [],
2975
+ }),
2976
+ };
2977
+ }
2978
+ const parsed =
2979
+ args.source !== undefined
2980
+ ? validatePipelineSpecFromSource(args.source)
2981
+ : await loadPipelineFile(args.path!, args.workingDirectory);
2982
+ if (!parsed.ok) {
2983
+ return {
2984
+ content: JSON.stringify({
2985
+ success: false,
2986
+ pipeline: null,
2987
+ errors: parsed.errors,
2988
+ warnings: parsed.warnings,
2989
+ }),
2990
+ };
2991
+ }
2992
+ const spec = parsed.spec!;
2993
+ return {
2994
+ content: JSON.stringify({
2995
+ success: true,
2996
+ pipeline: spec.name,
2997
+ steps: spec.steps.length,
2998
+ errors: [],
2999
+ warnings: parsed.warnings,
3000
+ }),
3001
+ };
3002
+ });
3003
+
3004
+ function validatePipelineSpecFromSource(source: string): PipelineParseResult {
3005
+ const parsed = parsePipelineYaml(source);
3006
+ return parsed;
3007
+ }
3008
+
3009
+ /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
3010
+ const pipelineApplyExecute = wrapExecute<PipelineApplyArgs>(async (args) => {
3011
+ const dryRun = args.dryRun !== false;
3012
+ if (args.path === undefined && args.source === undefined) {
3013
+ return {
3014
+ content: JSON.stringify({
3015
+ success: false,
3016
+ pipeline: null,
3017
+ errors: ["Укажите path к файлу или source с содержимым YAML"],
3018
+ warnings: [],
3019
+ }),
3020
+ };
3021
+ }
3022
+ const parsed =
3023
+ args.source !== undefined
3024
+ ? validatePipelineSpecFromSource(args.source)
3025
+ : await loadPipelineFile(args.path!, args.workingDirectory);
3026
+ if (!parsed.ok) {
3027
+ return {
3028
+ content: JSON.stringify({
3029
+ success: false,
3030
+ pipeline: null,
3031
+ errors: parsed.errors,
3032
+ warnings: parsed.warnings,
3033
+ }),
3034
+ };
3035
+ }
3036
+
3037
+ const spec = parsed.spec!;
3038
+ const existing = await listTaskDefinitions();
3039
+ const plan = planPipelineApply(spec, existing, {
3040
+ resolveWorkspaceId: (nameOrId: string) => {
3041
+ const ws = getWorkspace(nameOrId);
3042
+ return ws ? ws.id : undefined;
3043
+ },
3044
+ });
3045
+
3046
+ let created = 0;
3047
+ let updated = 0;
3048
+ const errors: string[] = [];
3049
+
3050
+ if (!dryRun) {
3051
+ for (const task of plan.creates) {
3052
+ try {
3053
+ await schedulerCreateTask(
3054
+ task.name,
3055
+ task.schedule,
3056
+ task.prompt,
3057
+ task.timeoutSeconds,
3058
+ task.workingDirectory ?? task.workdir ?? undefined,
3059
+ task.retryCount,
3060
+ task.retryDelay,
3061
+ task.qualityGate,
3062
+ task.nextTaskOnSuccess,
3063
+ task.nextTaskOnError,
3064
+ task.triggerType ?? "cron",
3065
+ task.watchPath,
3066
+ task.dependsOn,
3067
+ task.model,
3068
+ task.priority,
3069
+ task.beforeScript,
3070
+ task.afterScript,
3071
+ task.mcpEvent,
3072
+ task.workspaceId,
3073
+ task.allowedTools,
3074
+ task.deniedTools,
3075
+ task.matrix,
3076
+ task.matrixParentId,
3077
+ "create",
3078
+ task.timezone,
3079
+ task.notBefore,
3080
+ task.notAfter,
3081
+ task.pausedUntil,
3082
+ task.runAt,
3083
+ task.session,
3084
+ task.sessionId,
3085
+ task.sessionMaxRuns,
3086
+ {
3087
+ activeDays: task.activeDays,
3088
+ windowPolicy: task.windowPolicy,
3089
+ watchGlobs: task.watchGlobs ?? [],
3090
+ watchIgnore: task.watchIgnore ?? [],
3091
+ gitBranch: task.gitBranch,
3092
+ gitPaths: task.gitPaths,
3093
+ gitIgnore: task.gitIgnore,
3094
+ gitPollSeconds: task.gitPollSeconds,
3095
+ },
3096
+ task.runWhenLoggedOff ?? false,
3097
+ task.paused ?? false,
3098
+ task.legacyShell ?? false,
3099
+ task.worktree ?? false,
3100
+ task.guards,
3101
+ );
3102
+ await saveTaskDefinition(task);
3103
+ created++;
3104
+ } catch (err) {
3105
+ errors.push(`create ${task.name}: ${err instanceof Error ? err.message : String(err)}`);
3106
+ }
3107
+ }
3108
+ for (const item of plan.updates) {
3109
+ try {
3110
+ await schedulerCreateTask(
3111
+ item.task.name,
3112
+ item.task.schedule,
3113
+ item.task.prompt,
3114
+ item.task.timeoutSeconds,
3115
+ item.task.workingDirectory ?? item.task.workdir ?? undefined,
3116
+ item.task.retryCount,
3117
+ item.task.retryDelay,
3118
+ item.task.qualityGate,
3119
+ item.task.nextTaskOnSuccess,
3120
+ item.task.nextTaskOnError,
3121
+ item.task.triggerType ?? "cron",
3122
+ item.task.watchPath,
3123
+ item.task.dependsOn,
3124
+ item.task.model,
3125
+ item.task.priority,
3126
+ item.task.beforeScript,
3127
+ item.task.afterScript,
3128
+ item.task.mcpEvent,
3129
+ item.task.workspaceId,
3130
+ item.task.allowedTools,
3131
+ item.task.deniedTools,
3132
+ item.task.matrix,
3133
+ item.task.matrixParentId,
3134
+ "sync",
3135
+ item.task.timezone,
3136
+ item.task.notBefore,
3137
+ item.task.notAfter,
3138
+ item.task.pausedUntil,
3139
+ item.task.runAt,
3140
+ item.task.session,
3141
+ item.task.sessionId,
3142
+ item.task.sessionMaxRuns,
3143
+ {
3144
+ activeDays: item.task.activeDays,
3145
+ windowPolicy: item.task.windowPolicy,
3146
+ watchGlobs: item.task.watchGlobs ?? [],
3147
+ watchIgnore: item.task.watchIgnore ?? [],
3148
+ gitBranch: item.task.gitBranch,
3149
+ gitPaths: item.task.gitPaths,
3150
+ gitIgnore: item.task.gitIgnore,
3151
+ gitPollSeconds: item.task.gitPollSeconds,
3152
+ },
3153
+ item.task.runWhenLoggedOff ?? false,
3154
+ item.task.paused ?? false,
3155
+ item.task.legacyShell ?? false,
3156
+ item.task.worktree ?? false,
3157
+ item.task.guards,
3158
+ );
3159
+ await saveTaskDefinition(item.task);
3160
+ updated++;
3161
+ } catch (err) {
3162
+ errors.push(`update ${item.task.name}: ${err instanceof Error ? err.message : String(err)}`);
3163
+ }
3164
+ }
3165
+ refreshTriggers();
3166
+ }
3167
+
3168
+ return {
3169
+ content: JSON.stringify({
3170
+ success: errors.length === 0,
3171
+ pipeline: spec.name,
3172
+ dryRun,
3173
+ created,
3174
+ updated,
3175
+ unchanged: plan.unchanged.length,
3176
+ stale: plan.stale.length,
3177
+ warnings: [...plan.warnings, ...errors],
3178
+ errors,
3179
+ }),
3180
+ };
3181
+ });
3182
+
3183
+ /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
3184
+ const pipelineExportExecute = wrapExecute<PipelineExportArgs>(async (args) => {
3185
+ const allTasks = await listTaskDefinitions();
3186
+ // QA-P3.2: два имени — это ошибка, а не молчаливый выбор первого.
3187
+ const explicit = args.pipeline?.trim();
3188
+ const alias = args.pipelineName?.trim();
3189
+ if (explicit && alias && explicit.toLowerCase() !== alias.toLowerCase()) {
3190
+ return {
3191
+ content: JSON.stringify({
3192
+ success: false,
3193
+ error: "Конфликт параметров: pipeline и pipelineName задают разные имена конвейера.",
3194
+ }),
3195
+ };
3196
+ }
3197
+ const pipelineName = explicit || alias;
3198
+ if (!pipelineName) {
3199
+ return {
3200
+ content: JSON.stringify({
3201
+ success: false,
3202
+ error: "Не задано имя конвейера: укажите pipeline или pipelineName.",
3203
+ }),
3204
+ };
3205
+ }
3206
+ const result = tasksToPipelineSpec(allTasks, pipelineName);
3207
+ // QA-P3.2: spec всегда создаётся, поэтому «не найден» проверяем по шагам.
3208
+ const lookupError = pipelineExportLookupError(allTasks, pipelineName);
3209
+ if (!result.spec || lookupError) {
3210
+ return {
3211
+ content: JSON.stringify({
3212
+ success: false,
3213
+ error: lookupError ?? `Конвейер "${pipelineName}" не найден.`,
3214
+ warnings: result.warnings,
3215
+ }),
3216
+ };
3217
+ }
3218
+ const yamlText = yamlStringify(result.spec, { lineWidth: 0 });
3219
+ return {
3220
+ content: JSON.stringify({
3221
+ success: true,
3222
+ pipeline: pipelineName,
3223
+ steps: result.spec.steps.length,
3224
+ yaml: yamlText,
3225
+ warnings: result.warnings,
3226
+ }),
3227
+ };
3228
+ });
3229
+
2448
3230
  /**
2449
3231
  * Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
2450
3232
  * Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
@@ -2458,7 +3240,7 @@ async function refreshWorkspaceEnvFiles(workspaceId: string): Promise<number> {
2458
3240
  try {
2459
3241
  writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
2460
3242
  refreshed += 1;
2461
- } catch (err: any) {
3243
+ } catch (err) {
2462
3244
  // P2-21: не разрешаем задаче работать с литералом ${secret:...}.
2463
3245
  console.error(
2464
3246
  `[workspace] Задача "${task.name}": env-файл не обновлён — ${
@@ -2574,7 +3356,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
2574
3356
  };
2575
3357
  }
2576
3358
  }
2577
- } catch (err: any) {
3359
+ } catch (err) {
2578
3360
  return {
2579
3361
  content: JSON.stringify({
2580
3362
  success: false,
@@ -2644,7 +3426,7 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
2644
3426
  cancelled: result.cancelled,
2645
3427
  }),
2646
3428
  };
2647
- } catch (err: any) {
3429
+ } catch (err) {
2648
3430
  return {
2649
3431
  content: JSON.stringify({
2650
3432
  success: false,
@@ -2654,10 +3436,22 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
2654
3436
  }
2655
3437
  }
2656
3438
 
3439
+ // QA-P3.7: `results` должен так же проверять тип задачи, как `cancel`.
3440
+ // Иначе неизвестное имя даёт success:true с пустым отчётом вместо
3441
+ // внятной ошибки «задача не является матрицей».
3442
+ if (!isKnownMatrix(name)) {
3443
+ return {
3444
+ content: JSON.stringify({
3445
+ success: false,
3446
+ error: t("tool.error.matrixNotMatrix", { name }),
3447
+ }),
3448
+ };
3449
+ }
3450
+
2657
3451
  try {
2658
3452
  const report = aggregateMatrixResults(name);
2659
3453
  return { content: JSON.stringify({ success: true, report }) };
2660
- } catch (err: any) {
3454
+ } catch (err) {
2661
3455
  return {
2662
3456
  content: JSON.stringify({
2663
3457
  success: false,
@@ -2670,42 +3464,60 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
2670
3464
  /** get_metrics — суммарная статистика запусков. */
2671
3465
  const getMetricsExecute = wrapExecute<MetricsArgs>(async () => {
2672
3466
  const metrics = await loadMetrics();
2673
- return { content: JSON.stringify({ success: true, metrics }) };
3467
+ // PL-4.1: блокировки инструментов — показатель корректности hybrid-политики.
3468
+ const since = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString();
3469
+ const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
3470
+ return { content: JSON.stringify({ success: true, metrics: { ...metrics, toolBlocked } }) };
2674
3471
  });
2675
3472
 
2676
3473
  /** get_analytics — аналитика запусков и стоимости за период. */
2677
3474
  const getAnalyticsExecute = wrapExecute<AnalyticsArgs>(async (args) => {
2678
3475
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
2679
- const records = getHistory(null, 20000);
3476
+ const records = getHistoryForAnalytics(windowDays);
2680
3477
  const definitions = await loadTaskDefinitions();
2681
3478
  const report = buildAnalytics(records, {
2682
3479
  days: windowDays,
2683
3480
  topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
2684
- tasks: definitions.map((definition) => ({
3481
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
2685
3482
  name: definition.name,
2686
3483
  matrixParentId: definition.matrixParentId,
3484
+ tokenBudget: definition.tokenBudget,
2687
3485
  })),
2688
3486
  });
2689
- return { content: JSON.stringify({ success: true, report }) };
3487
+ // Экономика v2 (E-1.1): учёт расхода за день/неделю рядом с аналитикой.
3488
+ const settings = await loadSettings();
3489
+ const budgets = buildBudgetReport(records, settings.budgets, new Date());
3490
+ // PL-4.1: tool.blocked — метрика корректности прав политики, а не ошибка
3491
+ // запуска. Считаем за то же окно, что и аналитику; readAuditLog отдаёт total
3492
+ // независимо от limit, поэтому одной строки выборки достаточно для счётчика.
3493
+ const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1000).toISOString();
3494
+ const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
3495
+ return {
3496
+ content: JSON.stringify({
3497
+ success: true,
3498
+ report: { ...report, budgets, toolBlocked },
3499
+ }),
3500
+ };
2690
3501
  });
2691
3502
 
2692
3503
  /** self_analysis — система самоанализа: здоровье, аномалии, тренды, рекомендации. */
2693
3504
  const selfAnalysisExecute = wrapExecute<SelfAnalysisArgs>(async (args) => {
2694
3505
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
2695
- const records = getHistory(null, 20000);
3506
+ const records = getHistoryForAnalytics(windowDays);
2696
3507
  const definitions = await loadTaskDefinitions();
2697
3508
 
2698
3509
  const report = generateSelfAnalysisReport(records, {
2699
3510
  days: windowDays,
2700
3511
  topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
2701
- tasks: definitions.map((definition) => ({
3512
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
2702
3513
  name: definition.name,
2703
3514
  matrixParentId: definition.matrixParentId,
3515
+ tokenBudget: definition.tokenBudget,
2704
3516
  })),
2705
3517
  });
2706
3518
 
2707
3519
  // Фильтруем секции если нужно
2708
- const result: any = {
3520
+ const result: Partial<typeof report> = {
2709
3521
  generatedAt: report.generatedAt,
2710
3522
  windowDays: report.windowDays,
2711
3523
  health: report.health,
@@ -2729,7 +3541,7 @@ const selfAnalysisExecute = wrapExecute<SelfAnalysisArgs>(async (args) => {
2729
3541
  /** manage_settings — чтение и изменение глобальных настроек. */
2730
3542
  const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
2731
3543
  const current = await loadSettings();
2732
- if (args.action === "get") {
3544
+ if (args.action === "get" || args.action === "list") {
2733
3545
  return { content: JSON.stringify({ success: true, settings: current }) };
2734
3546
  }
2735
3547
 
@@ -2741,7 +3553,9 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
2741
3553
  args.history === undefined &&
2742
3554
  args.integrations === undefined &&
2743
3555
  args.audit === undefined &&
2744
- args.permissions === undefined
3556
+ args.permissions === undefined &&
3557
+ args.budgets === undefined &&
3558
+ args.feedback === undefined
2745
3559
  ) {
2746
3560
  return {
2747
3561
  content: JSON.stringify({
@@ -2761,6 +3575,8 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
2761
3575
  integrations: args.integrations as IntegrationSettings | undefined,
2762
3576
  audit: args.audit as AuditSettings | undefined,
2763
3577
  permissions: args.permissions as PermissionSettings | undefined,
3578
+ budgets: args.budgets as BudgetSettings | undefined,
3579
+ feedback: args.feedback as FeedbackSettings | undefined,
2764
3580
  });
2765
3581
  // Локаль процесса меняется сразу — перезапуск плагина не нужен.
2766
3582
  setLocale(resolveLocale(settings.locale, settings.uiLocale));
@@ -2874,12 +3690,14 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
2874
3690
  }
2875
3691
 
2876
3692
  if (args.action === "delete") {
2877
- const id = args.id?.trim();
3693
+ // PL-17/PL-28/PL-32: name — такой же алиас id, как и в репозитории.
3694
+ const id = args.id?.trim() || args.name?.trim();
2878
3695
  if (!id) {
2879
3696
  return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
2880
3697
  }
2881
3698
  const before = await loadTemplates();
2882
- const existed = before.some((template) => template.id === id);
3699
+ // QA-P3.3: name является алиасом id при удалении.
3700
+ const existed = before.some((template) => template.id === id || template.name === id);
2883
3701
  await deleteTemplate(id);
2884
3702
  return {
2885
3703
  content: JSON.stringify({
@@ -3029,10 +3847,30 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
3029
3847
  def.notAfter,
3030
3848
  def.pausedUntil,
3031
3849
  def.runAt,
3850
+ def.session,
3851
+ def.sessionId,
3852
+ def.sessionMaxRuns,
3853
+ {
3854
+ activeDays: def.activeDays,
3855
+ windowPolicy: def.windowPolicy,
3856
+ watchGlobs: def.watchGlobs,
3857
+ watchIgnore: def.watchIgnore,
3858
+ gitBranch: def.gitBranch,
3859
+ gitPaths: def.gitPaths,
3860
+ gitIgnore: def.gitIgnore,
3861
+ gitPollSeconds: def.gitPollSeconds,
3862
+ },
3863
+ def.runWhenLoggedOff,
3864
+ def.paused,
3865
+ def.legacyShell,
3866
+ def.worktree,
3867
+ def.guards,
3868
+ // QA-P0.1 (E-2.1): импорт через transfer_tasks сохраняет tokenBudget.
3869
+ def.tokenBudget,
3032
3870
  );
3033
3871
  await saveTaskDefinition(def);
3034
3872
  imported.push(def.name);
3035
- } catch (err: any) {
3873
+ } catch (err) {
3036
3874
  errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
3037
3875
  }
3038
3876
  }
@@ -3051,9 +3889,157 @@ const sendNotificationExecute = wrapExecute<NotificationArgs>(async (args) => {
3051
3889
  return { content: JSON.stringify(result) };
3052
3890
  });
3053
3891
 
3892
+ /**
3893
+ * Общий сборщик текста баг-репорта (устраняет дублирование между MCP-тулом
3894
+ * и RPC-хендлером — QA-находка 3.8). Возвращает также сырые логи и метрики
3895
+ * для структурированного payload (F-1.1).
3896
+ */
3897
+ async function buildBugReportText(input: {
3898
+ description: string;
3899
+ taskName?: string;
3900
+ includeLogs?: boolean;
3901
+ includeAnalytics?: boolean;
3902
+ }): Promise<{ text: string; logs?: string; metrics?: Record<string, number> }> {
3903
+ const lines: string[] = [];
3904
+ lines.push("🐛 *Bug report — agent-steward plugin*");
3905
+ lines.push(`Время: ${new Date().toISOString()}`);
3906
+ lines.push(`Описание: ${input.description}`);
3907
+ let logs: string | undefined;
3908
+ if (input.taskName) {
3909
+ lines.push(`Задача: ${input.taskName}`);
3910
+ if (input.includeLogs) {
3911
+ try {
3912
+ const taskLogs = await getTaskLogs(input.taskName);
3913
+ if (taskLogs.logs) {
3914
+ logs = String(taskLogs.logs).slice(0, 2000);
3915
+ lines.push(`\n--- Логи задачи ${input.taskName} ---`);
3916
+ lines.push(logs);
3917
+ }
3918
+ } catch (err) {
3919
+ lines.push(`\n--- Логи задачи ${input.taskName}: ошибка чтения ---`);
3920
+ lines.push(err instanceof Error ? err.message : String(err));
3921
+ }
3922
+ }
3923
+ }
3924
+ let metrics: Record<string, number> | undefined;
3925
+ if (input.includeAnalytics !== false) {
3926
+ try {
3927
+ const raw = await loadMetrics();
3928
+ metrics = {
3929
+ total: raw.total,
3930
+ success: raw.success,
3931
+ error: raw.error,
3932
+ partial: raw.partial ?? 0,
3933
+ };
3934
+ lines.push("\n--- Метрики ---");
3935
+ lines.push(`Всего запусков: ${metrics.total}`);
3936
+ lines.push(`Успех: ${metrics.success}`);
3937
+ lines.push(`Ошибок: ${metrics.error}`);
3938
+ if (metrics.partial) lines.push(`Частично: ${metrics.partial}`);
3939
+ } catch (err) {
3940
+ lines.push(`\n--- Метрики: ошибка чтения: ${err instanceof Error ? err.message : String(err)} ---`);
3941
+ }
3942
+ try {
3943
+ const records = getHistoryForAnalytics(7);
3944
+ const definitions = await loadTaskDefinitions();
3945
+ const report = buildAnalytics(records, {
3946
+ days: 7,
3947
+ topLimit: 10,
3948
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
3949
+ name: definition.name,
3950
+ matrixParentId: definition.matrixParentId,
3951
+ tokenBudget: definition.tokenBudget,
3952
+ })),
3953
+ });
3954
+ lines.push("\n--- Аналитика (7 дней) ---");
3955
+ lines.push(`Всего запусков: ${report.totals.total}`);
3956
+ lines.push(`Успех: ${report.totals.success}`);
3957
+ lines.push(`Ошибок: ${report.totals.error}`);
3958
+ if (report.totals.partial) lines.push(`Частично: ${report.totals.partial}`);
3959
+ const errorTasks = report.tasks.filter((task) => task.error > 0).slice(0, 5);
3960
+ if (errorTasks.length > 0) {
3961
+ lines.push(
3962
+ `Задачи с ошибками: ${errorTasks.map((task) => `${task.taskName} (${task.error})`).join(", ")}`,
3963
+ );
3964
+ }
3965
+ } catch (err) {
3966
+ lines.push(`\n--- Аналитика: ошибка чтения: ${err instanceof Error ? err.message : String(err)} ---`);
3967
+ }
3968
+ }
3969
+ return { text: lines.join("\n"), logs, metrics };
3970
+ }
3971
+
3972
+ /**
3973
+ * Значения всех секретов из manage_secrets — используются только для
3974
+ * редактирования текста (F-1.4). Ни одно значение не попадает в payload.
3975
+ */
3976
+ function collectSecretValues(): string[] {
3977
+ const values: string[] = [];
3978
+ for (const item of listSecrets()) {
3979
+ const value = getSecret(item.name);
3980
+ if (value && value.length >= 4) values.push(value);
3981
+ }
3982
+ return values;
3983
+ }
3984
+
3985
+ /** report_bug — отчёт о баге; по умолчанию уходит автору через приёмник F-2. */
3986
+ const reportBugExecute = wrapExecute<ReportBugArgs>(async (args) => {
3987
+ const settings = await loadSettings();
3988
+ const includeLogs = args.includeLogs ?? settings.feedback.includeLogs;
3989
+ const built = await buildBugReportText({
3990
+ description: args.description,
3991
+ taskName: args.taskName,
3992
+ includeLogs,
3993
+ includeAnalytics: args.includeAnalytics,
3994
+ });
3995
+ const secretValues = collectSecretValues();
3996
+ const localText = redactText(built.text, { secrets: secretValues, redactEmails: false });
3997
+
3998
+ const result = await reportFeedback({
3999
+ settings: settings.feedback,
4000
+ destination: args.destination ?? "author",
4001
+ dryRun: args.dryRun,
4002
+ description: args.description,
4003
+ taskName: args.taskName,
4004
+ contactEmail: args.contactEmail ?? settings.feedback.contactEmail,
4005
+ redactedLogs: includeLogs ? built.logs : undefined,
4006
+ metrics: built.metrics,
4007
+ locale: settings.locale,
4008
+ secrets: secretValues,
4009
+ sendLocal: (text) => sendBugReport(text, args.channel),
4010
+ localText,
4011
+ });
4012
+ return {
4013
+ content: JSON.stringify({
4014
+ ...result,
4015
+ message:
4016
+ result.mode === "dryRun"
4017
+ ? t("feedback.dryRun")
4018
+ : result.mode === "sent"
4019
+ ? t("feedback.sent")
4020
+ : result.mode === "outbox"
4021
+ ? t("feedback.outbox")
4022
+ : result.mode === "duplicate"
4023
+ ? t("feedback.duplicate")
4024
+ : t("feedback.local"),
4025
+ }),
4026
+ };
4027
+ });
4028
+
3054
4029
  /** get_dashboard_info — порт дашборда, платформа и активный профиль. */
3055
4030
  const getDashboardInfoExecute = wrapExecute<DashboardInfoArgs>(async () => {
3056
- const port = getDashboardPort();
4031
+ // QA-P3.5: порт из профиля/env может быть «бумажным» (4782), а живой
4032
+ // дашборд слушает 3782. Проверяем маркер и при необходимости находим порт
4033
+ // зондированием стандартных кандидатов, чтобы отчёт совпадал с реальностью.
4034
+ let port = getDashboardPort();
4035
+ let probe = port ? await probeDashboardOn(port) : null;
4036
+ if (!probe?.dashboard) {
4037
+ const discovered = await discoverDashboardPort();
4038
+ if (discovered) {
4039
+ port = discovered;
4040
+ probe = await probeDashboardOn(port);
4041
+ }
4042
+ }
3057
4043
  return {
3058
4044
  content: JSON.stringify({
3059
4045
  success: true,
@@ -3062,6 +4048,7 @@ const getDashboardInfoExecute = wrapExecute<DashboardInfoArgs>(async () => {
3062
4048
  platform: scheduler.platform,
3063
4049
  title: scheduler.title,
3064
4050
  profile: getProfileName(),
4051
+ reachable: probe?.dashboard ?? false,
3065
4052
  }),
3066
4053
  };
3067
4054
  });
@@ -3088,45 +4075,112 @@ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
3088
4075
  };
3089
4076
  });
3090
4077
 
3091
- /** emit_event — запуск задач, подписанных на MCP-событие. */
3092
- const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
3093
- const eventName = args.eventName?.trim();
3094
- if (!eventName) {
3095
- return { content: JSON.stringify({ success: false, error: t("tool.event.nameRequired") }) };
4078
+ /** PL-35: единый обработчик события для агентского инструмента и RPC/GUI. */
4079
+ type EmitEventCode = "no_subscribers" | "start_failed" | "ok";
4080
+ interface EmitEventResult {
4081
+ success: boolean;
4082
+ code: EmitEventCode;
4083
+ event: string;
4084
+ matched: string[];
4085
+ triggered: string[];
4086
+ failed: { name: string; error: string }[];
4087
+ message: string;
4088
+ }
4089
+
4090
+ const DEFAULT_EVENT_PRIORITY = 5;
4091
+
4092
+ /**
4093
+ * QV-3: проверка, что задача подписана на MCP-событие. Источник `server`
4094
+ * сравнивается только когда он передан вызывающим — это сохраняет обратную
4095
+ * совместимость со старыми вызовами emit_event без указания источника.
4096
+ */
4097
+ export function matchesMcpEventSubscription(
4098
+ def: TaskDefinition,
4099
+ event: string,
4100
+ server?: string,
4101
+ payload?: unknown,
4102
+ ): boolean {
4103
+ if ((def.triggerType ?? "cron") !== "mcp-event") return false;
4104
+ // PL-48: definition может хранить алиас `eventName` (PL-42), поэтому матчер
4105
+ // читает нормализованное событие, а не только каноническое поле `event`.
4106
+ const subscription = normalizeMcpEventTrigger(def.mcpEvent);
4107
+ if (subscription?.event.toLowerCase() !== event.toLowerCase()) return false;
4108
+ const expectedServer = server?.trim();
4109
+ if (
4110
+ expectedServer &&
4111
+ subscription.server.toLowerCase() !== expectedServer.toLowerCase()
4112
+ ) {
4113
+ return false;
4114
+ }
4115
+ return matchesEventFilter(subscription.filter, payload);
4116
+ }
4117
+
4118
+ export async function emitEventCore(
4119
+ rawEventName: string | undefined,
4120
+ payload: unknown,
4121
+ server?: string,
4122
+ ): Promise<EmitEventResult> {
4123
+ const event = rawEventName?.trim() ?? "";
4124
+ if (!event) {
4125
+ return {
4126
+ success: false,
4127
+ code: "no_subscribers",
4128
+ event,
4129
+ matched: [],
4130
+ triggered: [],
4131
+ failed: [],
4132
+ message: t("tool.event.nameRequiredShort"),
4133
+ };
3096
4134
  }
3097
- const payload = args.payload ?? {};
4135
+
3098
4136
  const definitions = await loadTaskDefinitions();
3099
4137
  const matched = definitions
3100
- .filter(
3101
- (def) =>
3102
- def.triggerType === "mcp-event" &&
3103
- def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
3104
- matchesEventFilter(def.mcpEvent?.filter, payload),
3105
- )
4138
+ .filter((def) => matchesMcpEventSubscription(def, event, server, payload))
3106
4139
  .sort(
3107
4140
  (a, b) =>
3108
- (normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0),
4141
+ (normalizePriority(b.priority) ?? DEFAULT_EVENT_PRIORITY) -
4142
+ (normalizePriority(a.priority) ?? DEFAULT_EVENT_PRIORITY),
3109
4143
  );
3110
4144
 
3111
4145
  const triggered: string[] = [];
4146
+ const failed: { name: string; error: string }[] = [];
3112
4147
  for (const def of matched) {
3113
4148
  try {
3114
4149
  await runTaskEntry(def.name);
3115
4150
  triggered.push(def.name);
3116
- } catch (err: any) {
3117
- console.error(`[agent-steward] emit_event: не удалось запустить ${def.name}:`, err);
4151
+ } catch (err) {
4152
+ const error = err instanceof Error ? err.message : String(err);
4153
+ failed.push({ name: def.name, error });
4154
+ console.error(`[agent-steward] emit_event: не удалось запустить ${def.name}: ${error}`);
3118
4155
  }
3119
4156
  }
4157
+
4158
+ const code: EmitEventCode =
4159
+ matched.length === 0 ? "no_subscribers" : failed.length > 0 ? "start_failed" : "ok";
4160
+ const message =
4161
+ code === "no_subscribers"
4162
+ ? t("tool.event.none", { event })
4163
+ : code === "start_failed"
4164
+ ? t("tool.event.startFailed", { count: failed.length })
4165
+ : t("tool.event.triggered", { count: triggered.length });
3120
4166
  return {
3121
- content: JSON.stringify({
3122
- success: true,
3123
- message:
3124
- triggered.length > 0
3125
- ? t("tool.event.triggered", { count: triggered.length })
3126
- : t("tool.event.none", { event: eventName }),
3127
- triggered,
3128
- }),
4167
+ success: true,
4168
+ code,
4169
+ event,
4170
+ matched: matched.map((def) => def.name),
4171
+ triggered,
4172
+ failed,
4173
+ message,
3129
4174
  };
4175
+ }
4176
+
4177
+ /** emit_event — запуск задач, подписанных на MCP-событие. */
4178
+ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
4179
+ const result = await emitEventCore(args.eventName, args.payload ?? {}, args.server);
4180
+ if (!result.success) {
4181
+ return { content: JSON.stringify({ ...result, error: result.message }) };
4182
+ }
4183
+ return { content: JSON.stringify(result) };
3130
4184
  });
3131
4185
 
3132
4186
  /** manage_secrets — зашифрованное хранилище секретов. */
@@ -3198,14 +4252,22 @@ const getAuditLogExecute = wrapExecute<AuditLogArgs>(async (args) => {
3198
4252
  function withAudit<A>(
3199
4253
  toolName: string,
3200
4254
  describe: (args: A) => Omit<AuditEntryInput, "actor"> | null,
3201
- execute: (args: A, context: Tool.Context) => Promise<Tool.Result>,
3202
- ): (args: A, context: Tool.Context) => Promise<Tool.Result> {
3203
- return async (args: A, context: Tool.Context) => {
4255
+ execute: (args: A, context: ToolExecuteContext) => Promise<Tool.Result>,
4256
+ ): (args: A, context: ToolExecuteContext) => Promise<Tool.Result> {
4257
+ return async (args: A, context: ToolExecuteContext) => {
3204
4258
  const result = await execute(args, context);
3205
4259
  try {
3206
- const raw = String((result as any)?.content ?? "");
3207
- const parsed = raw ? JSON.parse(raw) : null;
3208
- if (parsed?.success === false) return result;
4260
+ const content = result.content;
4261
+ const raw = typeof content === "string" ? content : "";
4262
+ const parsed: unknown = raw ? JSON.parse(raw) : null;
4263
+ if (
4264
+ typeof parsed === "object" &&
4265
+ parsed !== null &&
4266
+ "success" in parsed &&
4267
+ parsed.success === false
4268
+ ) {
4269
+ return result;
4270
+ }
3209
4271
  const entry = describe(args);
3210
4272
  if (entry) {
3211
4273
  recordAudit({ ...entry, actor: "mcp", source: toolName });
@@ -3217,19 +4279,37 @@ function withAudit<A>(
3217
4279
  };
3218
4280
  }
3219
4281
 
4282
+ /** Поля payload-а GUI-RPC, которые читают правила аудита. */
4283
+ interface RpcAuditInput {
4284
+ name?: string;
4285
+ path?: string;
4286
+ id?: string;
4287
+ runId?: string;
4288
+ eventName?: string;
4289
+ taskName?: string;
4290
+ }
4291
+
4292
+ /** Тип обработчика GUI-RPC: конкретные аргументы известны только вызывающей стороне. */
4293
+ type RpcHandler = (...args: never[]) => unknown;
4294
+
3220
4295
  /** Правила аудита для RPC-методов GUI (Спринт 26). */
3221
4296
  const RPC_AUDIT_RULES: Record<
3222
4297
  string,
3223
4298
  {
3224
4299
  action: string;
3225
4300
  targetType: string;
3226
- target: (input: any) => string;
4301
+ target: (input: RpcAuditInput) => string;
3227
4302
  }
3228
4303
  > = {
3229
4304
  create_task: { action: "task.create", targetType: "task", target: (i) => i.name ?? "" },
3230
4305
  update_task: { action: "task.update", targetType: "task", target: (i) => i.name ?? "" },
3231
4306
  delete_task: { action: "task.delete", targetType: "task", target: (i) => i.name ?? "" },
3232
4307
  run_task: { action: "task.run", targetType: "task", target: (i) => i.name ?? "" },
4308
+ run_mission: {
4309
+ action: "mission.run",
4310
+ targetType: "mission",
4311
+ target: (i) => i.taskName ?? "ad-hoc",
4312
+ },
3233
4313
  pause_task: { action: "task.pause", targetType: "task", target: (i) => i.name ?? "" },
3234
4314
  resume_task: { action: "task.resume", targetType: "task", target: (i) => i.name ?? "" },
3235
4315
  cancel_matrix: { action: "matrix.cancel", targetType: "matrix", target: (i) => i.name ?? "" },
@@ -3302,19 +4382,25 @@ const RPC_AUDIT_RULES: Record<
3302
4382
  * Оборачивает RPC-обработчики GUI: успешные мутации попадают в audit log
3303
4383
  * с actor=gui. Ошибки аудита не влияют на ответ GUI.
3304
4384
  */
3305
- function withRpcAudit<T extends Record<string, (...args: any[]) => any>>(handlers: T): T {
3306
- const wrapped: Record<string, (...args: any[]) => any> = {};
3307
- for (const [name, handler] of Object.entries(handlers)) {
4385
+ function withRpcAudit<T extends Record<string, RpcHandler>>(handlers: T): T {
4386
+ const wrapped: Record<string, RpcHandler> = {};
4387
+ const entries: [string, RpcHandler][] = Object.entries(handlers);
4388
+ for (const [name, handler] of entries) {
3308
4389
  const rule = RPC_AUDIT_RULES[name];
3309
4390
  if (!rule || typeof handler !== "function") {
3310
4391
  wrapped[name] = handler;
3311
4392
  continue;
3312
4393
  }
3313
- wrapped[name] = async (...args: any[]) => {
3314
- const input = args[0] ?? {};
4394
+ wrapped[name] = async (...args: never[]) => {
4395
+ const input = (args[0] ?? {}) as RpcAuditInput;
3315
4396
  const result = await handler(...args);
3316
4397
  try {
3317
- if ((result)?.success !== false) {
4398
+ const failed =
4399
+ typeof result === "object" &&
4400
+ result !== null &&
4401
+ "success" in result &&
4402
+ result.success === false;
4403
+ if (!failed) {
3318
4404
  recordAudit({
3319
4405
  action: rule.action,
3320
4406
  targetType: rule.targetType,
@@ -3354,7 +4440,7 @@ async function refreshTriggers(): Promise<void> {
3354
4440
  if (fileWatcherManager) {
3355
4441
  try {
3356
4442
  await fileWatcherManager.refresh();
3357
- } catch (err: any) {
4443
+ } catch (err) {
3358
4444
  console.error(
3359
4445
  `[agent-steward] Не удалось обновить файловые триггеры: ${
3360
4446
  err instanceof Error ? err.message : String(err)
@@ -3365,7 +4451,7 @@ async function refreshTriggers(): Promise<void> {
3365
4451
  if (gitTriggerManager) {
3366
4452
  try {
3367
4453
  await gitTriggerManager.refresh();
3368
- } catch (err: any) {
4454
+ } catch (err) {
3369
4455
  console.error(
3370
4456
  `[agent-steward] Не удалось обновить git-триггеры: ${
3371
4457
  err instanceof Error ? err.message : String(err)
@@ -3398,7 +4484,27 @@ async function scheduleEventRun(taskName: string, reason: string): Promise<void>
3398
4484
  const state = activeWindowState(now, options);
3399
4485
 
3400
4486
  if (state.active || policy === "run") {
3401
- await runTaskEntry(taskName);
4487
+ const startedAt = now.toISOString();
4488
+ try {
4489
+ await runTaskEntry(taskName);
4490
+ } catch (err) {
4491
+ // PL-53: отказ старта по событийному триггеру раньше уходил только
4492
+ // в console.error хоста и не оставлял следа в истории/журнале.
4493
+ const message = err instanceof Error ? err.message : String(err);
4494
+ const runId = recordRun(taskName, "error", startedAt, 0, message);
4495
+ appendStructuredLog({
4496
+ event: "trigger.start_failed",
4497
+ runId,
4498
+ task: taskName,
4499
+ status: "error",
4500
+ startedAt,
4501
+ finishedAt: new Date().toISOString(),
4502
+ durationMs: 0,
4503
+ error: message,
4504
+ reason,
4505
+ });
4506
+ throw err;
4507
+ }
3402
4508
  console.log(
3403
4509
  `[agent-steward] Запуск задачи "${taskName}" (${reason}).`,
3404
4510
  );
@@ -3430,7 +4536,7 @@ async function scheduleEventRun(taskName: string, reason: string): Promise<void>
3430
4536
  )} мин: ${state.reason ?? "вне окна"}.`,
3431
4537
  );
3432
4538
  const timer = setTimeout(() => {
3433
- void scheduleEventRun(taskName, reason).catch((err: any) => {
4539
+ void scheduleEventRun(taskName, reason).catch((err) => {
3434
4540
  console.error(
3435
4541
  `[agent-steward] Не удалось запустить отложенную задачу "${taskName}": ${
3436
4542
  err instanceof Error ? err.message : String(err)
@@ -3482,7 +4588,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3482
4588
  initDb();
3483
4589
  try {
3484
4590
  await migrateJsonToDb();
3485
- } catch (err: any) {
4591
+ } catch (err) {
3486
4592
  console.error(
3487
4593
  `[migrate] Не удалось мигрировать JSON → SQLite: ${
3488
4594
  err instanceof Error ? err.message : String(err)
@@ -3491,13 +4597,29 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3491
4597
  }
3492
4598
  try {
3493
4599
  recoverInterruptedRuns();
3494
- } catch (err: any) {
4600
+ } catch (err) {
3495
4601
  console.error(
3496
4602
  `[recovery] Не удалось восстановить незавершённые запуски: ${
3497
4603
  err instanceof Error ? err.message : String(err)
3498
4604
  }`,
3499
4605
  );
3500
4606
  }
4607
+ // Деталь 3.8 (F-1.6): повторяем недоставленные отчёты из outbox.
4608
+ // Fire-and-forget: сеть не должна задерживать или ломать старт плагина.
4609
+ void loadSettings()
4610
+ .then((settings) => flushOutbox(settings.feedback))
4611
+ .then((result) => {
4612
+ if (result.sent > 0) {
4613
+ console.log(`[feedback] Из outbox доставлено отчётов: ${result.sent}`);
4614
+ }
4615
+ })
4616
+ .catch((err: unknown) => {
4617
+ console.error(
4618
+ `[feedback] Ошибка повтора outbox: ${
4619
+ err instanceof Error ? err.message : String(err)
4620
+ }`,
4621
+ );
4622
+ });
3501
4623
  // P1-14: pid:-записи fallback'а не переживают перезагрузку. Чистим их и
3502
4624
  // пересоздаём будущие one-shot, иначе после reboot можно убить чужой pid.
3503
4625
  if (scheduler instanceof LinuxScheduler) {
@@ -3510,7 +4632,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3510
4632
  `живо ${report.kept}.`,
3511
4633
  );
3512
4634
  }
3513
- } catch (err: any) {
4635
+ } catch (err) {
3514
4636
  console.error(
3515
4637
  `[scheduler] Не удалось очистить fallback-записи: ${
3516
4638
  err instanceof Error ? err.message : String(err)
@@ -3535,7 +4657,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3535
4657
  );
3536
4658
  }
3537
4659
  })
3538
- .catch((err: any) => {
4660
+ .catch((err) => {
3539
4661
  console.error(
3540
4662
  `[retention] Не удалось очистить историю: ${
3541
4663
  err instanceof Error ? err.message : String(err)
@@ -3545,7 +4667,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3545
4667
 
3546
4668
  // Спринт 19: автопродолжение задач, поставленных на паузу до даты.
3547
4669
  // Проверяем сразу при старте и далее раз в 5 минут, пока плагин жив.
3548
- void resumeExpiredPauses().catch((err: any) => {
4670
+ void resumeExpiredPauses().catch((err) => {
3549
4671
  console.error(
3550
4672
  `[agent-steward] Не удалось проверить автопродолжение: ${
3551
4673
  err instanceof Error ? err.message : String(err)
@@ -3553,7 +4675,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3553
4675
  );
3554
4676
  });
3555
4677
  const pausedUntilTimer = setInterval(() => {
3556
- void resumeExpiredPauses().catch((err: any) => {
4678
+ void resumeExpiredPauses().catch((err) => {
3557
4679
  console.error(
3558
4680
  `[agent-steward] Не удалось проверить автопродолжение: ${
3559
4681
  err instanceof Error ? err.message : String(err)
@@ -3567,7 +4689,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3567
4689
  // старте и далее раз в минуту; таймер не держит процесс Node живым.
3568
4690
  const notificationTimer = setInterval(() => {
3569
4691
  void maybeSendDigest().catch(() => undefined);
3570
- void checkStuckMatrices().catch((err: any) => {
4692
+ void checkStuckMatrices().catch((err) => {
3571
4693
  console.error(
3572
4694
  `[agent-steward] Детектор зависших матриц: ${
3573
4695
  err instanceof Error ? err.message : String(err)
@@ -3623,7 +4745,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3623
4745
  console.log(
3624
4746
  `[agent-steward] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`,
3625
4747
  );
3626
- } catch (err: any) {
4748
+ } catch (err) {
3627
4749
  console.error(
3628
4750
  `[agent-steward] Не удалось восстановить задачу "${def.name}": ${
3629
4751
  err instanceof Error ? err.message : String(err)
@@ -3631,7 +4753,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3631
4753
  );
3632
4754
  }
3633
4755
  }
3634
- } catch (err: any) {
4756
+ } catch (err) {
3635
4757
  console.error(
3636
4758
  `[agent-steward] Catch-up ошибка: ${err instanceof Error ? err.message : String(err)}`,
3637
4759
  );
@@ -3643,7 +4765,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3643
4765
  fileWatcherManager = new FileWatchManager(async (taskName) => {
3644
4766
  try {
3645
4767
  await scheduleEventRun(taskName, "изменение отслеживаемого файла");
3646
- } catch (err: any) {
4768
+ } catch (err) {
3647
4769
  console.error(
3648
4770
  `[agent-steward] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${
3649
4771
  err instanceof Error ? err.message : String(err)
@@ -3657,7 +4779,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3657
4779
  gitTriggerManager = new GitTriggerManager(async (taskName, info) => {
3658
4780
  try {
3659
4781
  await scheduleEventRun(taskName, `новый коммит ${info.head?.slice(0, 7) ?? ""}`);
3660
- } catch (err: any) {
4782
+ } catch (err) {
3661
4783
  console.error(
3662
4784
  `[agent-steward] Не удалось запустить задачу "${taskName}" по git-триггеру: ${
3663
4785
  err instanceof Error ? err.message : String(err)
@@ -3702,6 +4824,9 @@ export interface ToolHandlers {
3702
4824
  get_history: typeof getHistoryExecute;
3703
4825
  get_task_logs: typeof getTaskLogsExecute;
3704
4826
  dry_run: typeof dryRunExecute;
4827
+ pipeline_validate: typeof pipelineValidateExecute;
4828
+ pipeline_apply: typeof pipelineApplyExecute;
4829
+ pipeline_export: typeof pipelineExportExecute;
3705
4830
  manage_workspaces: typeof manageWorkspacesExecute;
3706
4831
  matrix_control: typeof matrixControlExecute;
3707
4832
  get_metrics: typeof getMetricsExecute;
@@ -3713,6 +4838,7 @@ export interface ToolHandlers {
3713
4838
  manage_profiles: typeof manageProfilesExecute;
3714
4839
  transfer_tasks: typeof transferTasksExecute;
3715
4840
  send_notification: typeof sendNotificationExecute;
4841
+ report_bug: typeof reportBugExecute;
3716
4842
  get_dashboard_info: typeof getDashboardInfoExecute;
3717
4843
  cleanup_history: typeof cleanupHistoryExecute;
3718
4844
  emit_event: typeof emitEventExecute;
@@ -3739,6 +4865,9 @@ export function createToolHandlers(_runtime: SchedulerRuntime): ToolHandlers {
3739
4865
  get_history: getHistoryExecute,
3740
4866
  get_task_logs: getTaskLogsExecute,
3741
4867
  dry_run: dryRunExecute,
4868
+ pipeline_validate: pipelineValidateExecute,
4869
+ pipeline_apply: pipelineApplyExecute,
4870
+ pipeline_export: pipelineExportExecute,
3742
4871
  manage_workspaces: manageWorkspacesExecute,
3743
4872
  matrix_control: matrixControlExecute,
3744
4873
  get_metrics: getMetricsExecute,
@@ -3750,6 +4879,7 @@ export function createToolHandlers(_runtime: SchedulerRuntime): ToolHandlers {
3750
4879
  manage_profiles: manageProfilesExecute,
3751
4880
  transfer_tasks: transferTasksExecute,
3752
4881
  send_notification: sendNotificationExecute,
4882
+ report_bug: reportBugExecute,
3753
4883
  get_dashboard_info: getDashboardInfoExecute,
3754
4884
  cleanup_history: cleanupHistoryExecute,
3755
4885
  emit_event: emitEventExecute,
@@ -3805,6 +4935,8 @@ export function createShutdownHandler(
3805
4935
  }
3806
4936
  // Чекпойнт WAL выполняется в closeDb.
3807
4937
  closeDb();
4938
+ // QA/PL-10: выгрузка действительно завершена — запрещаем автосброс ворот.
4939
+ shutdownGate.complete();
3808
4940
  };
3809
4941
  }
3810
4942
 
@@ -3812,13 +4944,28 @@ export function createShutdownHandler(
3812
4944
  * Декларативное описание инструмента: всё, что нужно любому entrypoint'у,
3813
4945
  * чтобы зарегистрировать его в своей версии API.
3814
4946
  */
4947
+ /**
4948
+ * Бивариантные сигнатуры (паттерн `bivarianceHack`). Типизированные
4949
+ * обработчики из `ToolHandlers` принимают конкретные `z.infer`-аргументы,
4950
+ * а реестр хранит их как `unknown`: вход проверен Zod-схемой инструмента
4951
+ * до вызова, поэтому приведение типов здесь не требуется.
4952
+ */
4953
+ type ToolSpecExecute = {
4954
+ bivarianceHack(args: unknown, context: ToolExecuteContext): Promise<Tool.Result>;
4955
+ }["bivarianceHack"];
4956
+ type ToolSpecAudit = {
4957
+ bivarianceHack(args: unknown): Omit<AuditEntryInput, "actor"> | null;
4958
+ }["bivarianceHack"];
4959
+
3815
4960
  export interface ToolSpec {
3816
4961
  name: string;
3817
- input: any;
4962
+ input: z.ZodTypeAny;
4963
+ /** PL-43: схема структурированного output (только V2 Code Mode; V1 использует content). */
4964
+ output?: z.ZodTypeAny;
3818
4965
  description: string;
3819
- execute: (args: any, context: Tool.Context) => Promise<Tool.Result>;
4966
+ execute: ToolSpecExecute;
3820
4967
  /** Правила аудита; null/undefined — операция не пишется в журнал. */
3821
- audit?: (args: any) => Omit<AuditEntryInput, "actor"> | null;
4968
+ audit?: ToolSpecAudit;
3822
4969
  }
3823
4970
 
3824
4971
  /**
@@ -3828,7 +4975,17 @@ export interface ToolSpec {
3828
4975
  * одинаковые имена, схемы, описания и обработчики. Аудит навешивается здесь
3829
4976
  * один раз, чтобы обе линии вели журнал одинаково.
3830
4977
  */
3831
- export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
4978
+ export function createToolSpecs(
4979
+ runtime: SchedulerRuntime,
4980
+ env: NodeJS.ProcessEnv = process.env,
4981
+ ): ToolSpec[] {
4982
+ // QV-8: обёртка задач выставляет маркер дочернего прогона перед `opencode run`.
4983
+ // Такой ребёнок не должен получать инструменты планировщика — иначе он видит
4984
+ // весь surface родителя и может рекурсивно создавать задачи.
4985
+ if (isChildRunMode(env)) {
4986
+ console.log(`[qv8] ${CHILD_RUN_ENV}: инструменты планировщика не регистрируются`);
4987
+ return [];
4988
+ }
3832
4989
  const handlers = createToolHandlers(runtime);
3833
4990
  return [
3834
4991
  {
@@ -3839,15 +4996,16 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3839
4996
  "Every run goes through a timeout + lock-file wrapper, so overlapping runs are skipped. " +
3840
4997
  "Without workingDirectory the task runs in the current project folder, where opencode run picks up the project's opencode.json and MCP servers.",
3841
4998
  audit: (args: ScheduleArgs) => ({ action: "task.create", targetType: "task", target: args.name }),
3842
- execute: handlers.schedule_task as any,
4999
+ execute: handlers.schedule_task,
3843
5000
  },
3844
5001
  {
3845
5002
  name: "list_tasks",
3846
5003
  input: listTasksSchema,
5004
+ output: listTasksOutputSchema,
3847
5005
  description:
3848
5006
  `Lists plugin tasks from the scheduler (${scheduler.title}) with schedule, status, next chained task and working directory. ` +
3849
- "Matrix parents include a per-clone summary.",
3850
- execute: handlers.list_tasks as any,
5007
+ "Matrix parents include a per-clone summary. Returns structured output in Code Mode; content remains a JSON string for V1 compatibility.",
5008
+ execute: handlers.list_tasks,
3851
5009
  },
3852
5010
  {
3853
5011
  name: "update_task",
@@ -3856,7 +5014,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3856
5014
  "Partially updates an existing task: omitted fields keep their current values, empty strings/arrays clear them. " +
3857
5015
  "Matrix changes are synced (clones are diffed, running clones are never touched); pass matrix: null to remove the matrix and its clones.",
3858
5016
  audit: (args: UpdateArgs) => ({ action: "task.update", targetType: "task", target: args.name }),
3859
- execute: handlers.update_task as any,
5017
+ execute: handlers.update_task,
3860
5018
  },
3861
5019
  {
3862
5020
  name: "delete_task",
@@ -3865,7 +5023,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3865
5023
  `Deletes a task from the scheduler (${scheduler.title}) by name. ` +
3866
5024
  "Deleting a matrix parent also deletes its clones and aggregator; deleting a single clone is refused (delete the whole matrix instead).",
3867
5025
  audit: (args: DeleteArgs) => ({ action: "task.delete", targetType: "task", target: args.name }),
3868
- execute: handlers.delete_task as any,
5026
+ execute: handlers.delete_task,
3869
5027
  },
3870
5028
  {
3871
5029
  name: "run_task_now",
@@ -3874,7 +5032,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3874
5032
  `Runs a task immediately in the scheduler (${scheduler.title}) for testing. ` +
3875
5033
  "Runs through the timeout + lock wrapper. For a matrix parent this starts the fan-out instead of the parent itself.",
3876
5034
  audit: (args: RunNowArgs) => ({ action: "task.run", targetType: "task", target: args.name }),
3877
- execute: handlers.run_task_now as any,
5035
+ execute: handlers.run_task_now,
3878
5036
  },
3879
5037
  {
3880
5038
  name: "pause_task",
@@ -3882,7 +5040,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3882
5040
  description:
3883
5041
  "Pauses a task in the OS scheduler. For a matrix parent every clone is paused (the parent itself never runs).",
3884
5042
  audit: (args: PauseArgs) => ({ action: "task.pause", targetType: "task", target: args.name }),
3885
- execute: handlers.pause_task as any,
5043
+ execute: handlers.pause_task,
3886
5044
  },
3887
5045
  {
3888
5046
  name: "resume_task",
@@ -3890,7 +5048,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3890
5048
  description:
3891
5049
  "Resumes a previously paused task. For a matrix parent every clone is resumed.",
3892
5050
  audit: (args: ResumeArgs) => ({ action: "task.resume", targetType: "task", target: args.name }),
3893
- execute: handlers.resume_task as any,
5051
+ execute: handlers.resume_task,
3894
5052
  },
3895
5053
  {
3896
5054
  name: "get_history",
@@ -3898,21 +5056,21 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3898
5056
  description:
3899
5057
  "Returns recent run history (status, duration, tokens, cost, model, Quality Gate and pre/post-flight results). " +
3900
5058
  "Filter by taskName and/or status; newest first.",
3901
- execute: handlers.get_history as any,
5059
+ execute: handlers.get_history,
3902
5060
  },
3903
5061
  {
3904
5062
  name: "get_task_logs",
3905
5063
  input: getTaskLogsSchema,
3906
5064
  description:
3907
5065
  "Returns the tail of a task's log file written by the run wrapper. Use it to diagnose failed runs.",
3908
- execute: handlers.get_task_logs as any,
5066
+ execute: handlers.get_task_logs,
3909
5067
  },
3910
5068
  {
3911
5069
  name: "dry_run",
3912
5070
  input: dryRunSchema,
3913
5071
  description:
3914
5072
  "Simulates a task pipeline (or every task when name is omitted): execution order, DAG dependencies, matrix fan-out, estimated duration/cost and warnings. Nothing is executed.",
3915
- execute: handlers.dry_run as any,
5073
+ execute: handlers.dry_run,
3916
5074
  },
3917
5075
  {
3918
5076
  name: "manage_workspaces",
@@ -3927,7 +5085,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3927
5085
  targetType: "workspace",
3928
5086
  target: args.id || args.name || "",
3929
5087
  },
3930
- execute: handlers.manage_workspaces as any,
5088
+ execute: handlers.manage_workspaces,
3931
5089
  },
3932
5090
  {
3933
5091
  name: "matrix_control",
@@ -3942,29 +5100,31 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3942
5100
  target: args.name || "",
3943
5101
  }
3944
5102
  : null,
3945
- execute: handlers.matrix_control as any,
5103
+ execute: handlers.matrix_control,
3946
5104
  },
3947
5105
  {
3948
5106
  name: "get_metrics",
3949
5107
  input: getMetricsSchema,
3950
5108
  description:
3951
5109
  "Returns aggregate run metrics: total runs, successes and failures across all tasks.",
3952
- execute: handlers.get_metrics as any,
5110
+ execute: handlers.get_metrics,
3953
5111
  },
3954
5112
  {
3955
5113
  name: "get_analytics",
3956
5114
  input: getAnalyticsSchema,
3957
5115
  description:
3958
5116
  "Returns an analytics report for a period: run counts, success rate, duration, tokens and cost, plus top tasks.",
3959
- execute: handlers.get_analytics as any,
5117
+ execute: handlers.get_analytics,
3960
5118
  },
3961
5119
  {
3962
5120
  name: "self_analysis",
3963
5121
  input: selfAnalysisSchema,
3964
5122
  description:
3965
5123
  "Generates a self-analysis report: system health score, anomaly detection, trend analysis and optimization recommendations. " +
3966
- "Helps identify performance issues, cost spikes and reliability problems.",
3967
- execute: handlers.self_analysis as any,
5124
+ "Helps identify performance issues, cost spikes and reliability problems. " +
5125
+ "In health.components, successRate and errorRate are normalized 0..100 scores (higher is better): " +
5126
+ "errorRate = 100 - 100 * error / total, so it is NOT the raw error percentage.",
5127
+ execute: handlers.self_analysis,
3968
5128
  },
3969
5129
  {
3970
5130
  name: "manage_settings",
@@ -3975,7 +5135,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3975
5135
  args.action === "update"
3976
5136
  ? { action: "settings.update", targetType: "settings", target: "global" }
3977
5137
  : null,
3978
- execute: handlers.manage_settings as any,
5138
+ execute: handlers.manage_settings,
3979
5139
  },
3980
5140
  {
3981
5141
  name: "manage_local_ai",
@@ -3988,7 +5148,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3988
5148
  args.action === "update"
3989
5149
  ? { action: "localAi.update", targetType: "settings", target: "triage" }
3990
5150
  : null,
3991
- execute: handlers.manage_local_ai as any,
5151
+ execute: handlers.manage_local_ai,
3992
5152
  },
3993
5153
  {
3994
5154
  name: "manage_templates",
@@ -4003,7 +5163,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
4003
5163
  targetType: "template",
4004
5164
  target: args.id || args.name || "",
4005
5165
  },
4006
- execute: handlers.manage_templates as any,
5166
+ execute: handlers.manage_templates,
4007
5167
  },
4008
5168
  {
4009
5169
  name: "manage_profiles",
@@ -4018,7 +5178,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
4018
5178
  targetType: "profile",
4019
5179
  target: args.name || "",
4020
5180
  },
4021
- execute: handlers.manage_profiles as any,
5181
+ execute: handlers.manage_profiles,
4022
5182
  },
4023
5183
  {
4024
5184
  name: "transfer_tasks",
@@ -4029,21 +5189,28 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
4029
5189
  args.action === "import"
4030
5190
  ? { action: "tasks.import", targetType: "tasks", target: "snapshot" }
4031
5191
  : null,
4032
- execute: handlers.transfer_tasks as any,
5192
+ execute: handlers.transfer_tasks,
4033
5193
  },
4034
5194
  {
4035
5195
  name: "send_notification",
4036
5196
  input: sendNotificationSchema,
4037
5197
  description:
4038
5198
  "Sends a test notification through the configured channel or sends the digest immediately.",
4039
- execute: handlers.send_notification as any,
5199
+ execute: handlers.send_notification,
5200
+ },
5201
+ {
5202
+ name: "report_bug",
5203
+ input: reportBugSchema,
5204
+ description:
5205
+ "Sends a bug report from the plugin user to the developer via configured notification channels (Telegram/webhook/native). Includes optional task logs and recent analytics.",
5206
+ execute: handlers.report_bug,
4040
5207
  },
4041
5208
  {
4042
5209
  name: "get_dashboard_info",
4043
5210
  input: getDashboardInfoSchema,
4044
5211
  description:
4045
5212
  "Returns dashboard port and URL, OS platform, scheduler title and the active profile.",
4046
- execute: handlers.get_dashboard_info as any,
5213
+ execute: handlers.get_dashboard_info,
4047
5214
  },
4048
5215
  {
4049
5216
  name: "cleanup_history",
@@ -4051,7 +5218,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
4051
5218
  description:
4052
5219
  "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
4053
5220
  audit: () => ({ action: "history.cleanup", targetType: "history", target: "runs" }),
4054
- execute: handlers.cleanup_history as any,
5221
+ execute: handlers.cleanup_history,
4055
5222
  },
4056
5223
  {
4057
5224
  name: "manage_secrets",
@@ -4068,7 +5235,7 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
4068
5235
  targetType: "secret",
4069
5236
  target: (args.name ?? "").trim(),
4070
5237
  },
4071
- execute: handlers.manage_secrets as any,
5238
+ execute: handlers.manage_secrets,
4072
5239
  },
4073
5240
  {
4074
5241
  name: "get_audit_log",
@@ -4076,14 +5243,40 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
4076
5243
  description:
4077
5244
  "Returns the audit journal of task and settings mutations: who changed what, when and through which interface (mcp, gui, http). " +
4078
5245
  "Filter by action, target, actor, time range and limit. Secret values are redacted.",
4079
- execute: handlers.get_audit_log as any,
5246
+ execute: handlers.get_audit_log,
5247
+ },
5248
+ {
5249
+ name: "pipeline_validate",
5250
+ input: pipelineValidateSchema,
5251
+ description:
5252
+ "Проверяет opencode.pipeline.yaml (путь к файлу или исходник): валидирует version, шаги, зависимости, циклы, cron-расписание, matrix, модель, окна запуска и другие инварианты конвейера. Не применяет изменения.",
5253
+ execute: handlers.pipeline_validate,
5254
+ },
5255
+ {
5256
+ name: "pipeline_apply",
5257
+ input: pipelineApplySchema,
5258
+ description:
5259
+ "Применяет opencode.pipeline.yaml к текущему набору задач: создаёт новые, обновляет изменённые, пропускает без изменений (идемпотентно). Задачи без маркера pipelineName не трогаются. В режиме dryRun только отчитывает diff.",
5260
+ audit: (args: PipelineApplyArgs) => ({
5261
+ action: "pipeline.apply",
5262
+ targetType: "pipeline",
5263
+ target: args.source ?? args.path ?? "",
5264
+ }),
5265
+ execute: handlers.pipeline_apply,
5266
+ },
5267
+ {
5268
+ name: "pipeline_export",
5269
+ input: pipelineExportSchema,
5270
+ description:
5271
+ "Выгружает задачи указанного конвейера (pipelineName) как opencode.pipeline.yaml: шаги, зависимости, matrix, кастомные настройки шага.",
5272
+ execute: handlers.pipeline_export,
4080
5273
  },
4081
5274
  {
4082
5275
  name: "emit_event",
4083
5276
  input: emitEventSchema,
4084
5277
  description:
4085
5278
  "Emits an MCP event: every task with triggerType 'mcp-event' matching the event name (and filter) is started in priority order.",
4086
- execute: handlers.emit_event as any,
5279
+ execute: handlers.emit_event,
4087
5280
  },
4088
5281
  ];
4089
5282
  }
@@ -4112,6 +5305,14 @@ async function startSchedulerDashboard(): Promise<void> {
4112
5305
  const v2Plugin = Plugin.define({
4113
5306
  id: "opencode-windows-scheduler",
4114
5307
  setup: async (ctx) => {
5308
+ if (isChildRunMode()) {
5309
+ console.log(`[qv8] ${CHILD_RUN_ENV}: дочерний прогон, пропускаю регистрацию плагина`);
5310
+ return async () => undefined;
5311
+ }
5312
+ // PL-45: hot-reload/Code Mode может заново вызвать setup после того, как
5313
+ // хост закрыл и «завершил» ворота, не выгрузив модуль. Открываем их,
5314
+ // иначе все in-process запуски навсегда получают PLUGIN_SHUTTING_DOWN.
5315
+ shutdownGate.reset();
4115
5316
  const runtime = await createRuntime(ctx);
4116
5317
  const registration = await ctx.tool.transform((editor) => {
4117
5318
  // editor.add регистрирует новые инструменты плагина с codemode: true,
@@ -4125,9 +5326,10 @@ const v2Plugin = Plugin.define({
4125
5326
  editor.add({
4126
5327
  name: spec.name,
4127
5328
  input: spec.input,
5329
+ output: spec.output,
4128
5330
  description: spec.description,
4129
5331
  options: { codemode: true },
4130
- execute: execute as any,
5332
+ execute,
4131
5333
  });
4132
5334
  }
4133
5335
  });
@@ -4141,16 +5343,20 @@ const v2Plugin = Plugin.define({
4141
5343
  const skill = loadSchedulerSkill();
4142
5344
  if (skill && ctx.skill?.transform) {
4143
5345
  skillRegistration = await ctx.skill.transform((editor) => {
5346
+ // QA-A2.1: V2 skill API ожидает Effect-брендированные строки
5347
+ // (Skill.ID / Skill.Name / AbsolutePath). Значения приходят из
5348
+ // собственного skill.ts, бренд живёт только на уровне типов —
5349
+ // приведение на границе внешнего API не меняет поведение.
4144
5350
  editor.add({
4145
- id: skill.id as any,
4146
- name: skill.name as any,
5351
+ id: skill.id as Skill.Info["id"],
5352
+ name: skill.name as Skill.Info["name"],
4147
5353
  description: skill.description,
4148
- path: skill.path as any,
5354
+ path: skill.path as Skill.Info["path"],
4149
5355
  content: skill.content,
4150
5356
  });
4151
5357
  });
4152
5358
  }
4153
- } catch (err: any) {
5359
+ } catch (err) {
4154
5360
  console.error(
4155
5361
  `[agent-steward] Не удалось зарегистрировать скилл "${SCHEDULER_SKILL_ID}": ${
4156
5362
  err instanceof Error ? err.message : String(err)
@@ -4172,6 +5378,23 @@ const v2Plugin = Plugin.define({
4172
5378
  },
4173
5379
  create_task: async (input: unknown) => {
4174
5380
  console.log("[agent-steward] create_task input:", input);
5381
+ // QA-P2.1: RPC обходит MCP/Zod — проверяем диапазоны явно.
5382
+ const rangeError = validateTaskInputRanges(input as {
5383
+ prompt?: string;
5384
+ timeoutSeconds?: number;
5385
+ priority?: number;
5386
+ retryCount?: number;
5387
+ retryDelay?: number;
5388
+ watchPath?: string;
5389
+ triggerType?: string;
5390
+ watchGlobs?: string[];
5391
+ watchIgnore?: string[];
5392
+ gitPaths?: string[];
5393
+ gitIgnore?: string[];
5394
+ });
5395
+ if (rangeError) {
5396
+ return { success: false, message: rangeError };
5397
+ }
4175
5398
  const {
4176
5399
  name,
4177
5400
  schedule,
@@ -4203,6 +5426,9 @@ const v2Plugin = Plugin.define({
4203
5426
  sessionMaxRuns,
4204
5427
  runWhenLoggedOff,
4205
5428
  legacyShell,
5429
+ worktree,
5430
+ guards,
5431
+ tokenBudget,
4206
5432
  } = input as {
4207
5433
  name: string;
4208
5434
  schedule?: string;
@@ -4220,7 +5446,7 @@ const v2Plugin = Plugin.define({
4220
5446
  priority?: number;
4221
5447
  beforeScript?: string;
4222
5448
  afterScript?: string;
4223
- mcpEvent?: McpEventTrigger;
5449
+ mcpEvent?: McpEventInput;
4224
5450
  workspaceId?: string;
4225
5451
  allowedTools?: string[];
4226
5452
  deniedTools?: string[];
@@ -4234,6 +5460,9 @@ const v2Plugin = Plugin.define({
4234
5460
  sessionMaxRuns?: number;
4235
5461
  runWhenLoggedOff?: boolean;
4236
5462
  legacyShell?: boolean;
5463
+ worktree?: boolean;
5464
+ guards?: TaskGuards;
5465
+ tokenBudget?: number;
4237
5466
  };
4238
5467
  let effectiveRunAt: string | undefined;
4239
5468
  if (triggerType === "once") {
@@ -4297,6 +5526,10 @@ const v2Plugin = Plugin.define({
4297
5526
  runWhenLoggedOff === true,
4298
5527
  undefined,
4299
5528
  legacyShell === true,
5529
+ worktree === true,
5530
+ guards,
5531
+ // QA-P0.1 (E-2.1): создание через дашборд/RPC сохраняет tokenBudget.
5532
+ tokenBudget,
4300
5533
  );
4301
5534
  const nextRun = computeTaskNextRun({
4302
5535
  schedule: schedule ?? "",
@@ -4312,7 +5545,7 @@ const v2Plugin = Plugin.define({
4312
5545
  nextRun,
4313
5546
  message: t("tool.task.created", { name }),
4314
5547
  };
4315
- } catch (err: any) {
5548
+ } catch (err) {
4316
5549
  const message = err instanceof Error ? err.message : String(err);
4317
5550
  return { success: false, message };
4318
5551
  }
@@ -4331,7 +5564,7 @@ const v2Plugin = Plugin.define({
4331
5564
  })
4332
5565
  : t("tool.task.deleted", { name }),
4333
5566
  };
4334
- } catch (err: any) {
5567
+ } catch (err) {
4335
5568
  return { success: false, message: err instanceof Error ? err.message : String(err) };
4336
5569
  }
4337
5570
  },
@@ -4344,7 +5577,7 @@ const v2Plugin = Plugin.define({
4344
5577
  message: result.message,
4345
5578
  cancelled: result.cancelled,
4346
5579
  };
4347
- } catch (err: any) {
5580
+ } catch (err) {
4348
5581
  return {
4349
5582
  success: false,
4350
5583
  message: err instanceof Error ? err.message : String(err),
@@ -4363,7 +5596,7 @@ const v2Plugin = Plugin.define({
4363
5596
  : t("tool.matrix.orphansNone"),
4364
5597
  removed,
4365
5598
  };
4366
- } catch (err: any) {
5599
+ } catch (err) {
4367
5600
  return {
4368
5601
  success: false,
4369
5602
  message: err instanceof Error ? err.message : String(err),
@@ -4374,10 +5607,30 @@ const v2Plugin = Plugin.define({
4374
5607
  run_task: async (input: unknown) => {
4375
5608
  const { name } = input as { name: string };
4376
5609
  try {
5610
+ const budgetGate = await checkBudgetGate();
5611
+ if (!budgetGate.allowed) {
5612
+ return {
5613
+ success: false,
5614
+ message: formatBudgetSkipMessage(budgetGate),
5615
+ };
5616
+ }
4377
5617
  // Matrix-родитель не выполняется сам: запускаем его клоны (fan-out).
4378
5618
  const definition = (await loadTaskDefinitions()).find(
4379
5619
  (def) => def.name.toLowerCase() === name.trim().toLowerCase(),
4380
5620
  );
5621
+ // E-2.2: тот же персональный токен-гейт, что и в runTaskEntry.
5622
+ if (definition?.tokenBudget) {
5623
+ const taskGate = checkTaskTokenBudgetGate(
5624
+ name,
5625
+ definition.tokenBudget,
5626
+ );
5627
+ if (!taskGate.allowed) {
5628
+ return {
5629
+ success: false,
5630
+ message: formatTaskTokenBudgetSkipMessage(taskGate),
5631
+ };
5632
+ }
5633
+ }
4381
5634
  if (definition?.matrix) {
4382
5635
  const matrixResult = await runMatrix(definition);
4383
5636
  const total = definition.matrix.workspaceIds.length;
@@ -4424,56 +5677,60 @@ const v2Plugin = Plugin.define({
4424
5677
  return { success: true, message: t("tool.task.alreadyRunning", { name }) };
4425
5678
  }
4426
5679
  return { success: true, message: t("tool.task.started", { name }) };
4427
- } catch (err: any) {
5680
+ } catch (err) {
4428
5681
  return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
4429
5682
  }
4430
5683
  },
5684
+ run_mission: async (input: unknown) => {
5685
+ try {
5686
+ const budgetGate = await checkBudgetGate();
5687
+ if (!budgetGate.allowed) {
5688
+ return {
5689
+ success: false,
5690
+ dryRun: false,
5691
+ runId: "",
5692
+ status: "failed",
5693
+ description: "",
5694
+ error: formatBudgetSkipMessage(budgetGate),
5695
+ steps: [],
5696
+ };
5697
+ }
5698
+ const mission = await runMission(input as MissionSpec);
5699
+ return {
5700
+ success: mission.success,
5701
+ dryRun: mission.dryRun,
5702
+ runId: mission.runId ?? "",
5703
+ status: mission.status,
5704
+ description: mission.description,
5705
+ ...(mission.error ? { error: mission.error } : {}),
5706
+ steps: mission.steps.map((step) => ({
5707
+ stepName: step.stepName,
5708
+ taskType: step.taskType,
5709
+ target: step.target,
5710
+ status: step.status,
5711
+ attempt: step.attempt,
5712
+ ...(step.error ? { error: step.error } : {}),
5713
+ })),
5714
+ };
5715
+ } catch (err) {
5716
+ return {
5717
+ success: false,
5718
+ dryRun: false,
5719
+ runId: "",
5720
+ status: "failed",
5721
+ description: "",
5722
+ error: err instanceof Error ? err.message : String(err),
5723
+ steps: [],
5724
+ };
5725
+ }
5726
+ },
4431
5727
  emit_event: async (input: unknown) => {
4432
- const { eventName, payload } = input as {
5728
+ const { eventName, payload, server } = input as {
4433
5729
  eventName?: string;
4434
5730
  payload?: unknown;
5731
+ server?: string;
4435
5732
  };
4436
- const normalized = eventName?.trim();
4437
- if (!normalized) {
4438
- return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
4439
- }
4440
-
4441
- // Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
4442
- const definitions = await loadTaskDefinitions();
4443
- const matched = definitions
4444
- .filter((def) => (def.triggerType ?? "cron") === "mcp-event")
4445
- .filter(
4446
- (def) =>
4447
- def.mcpEvent?.event?.trim().toLowerCase() === normalized.toLowerCase(),
4448
- )
4449
- .filter((def) => matchesEventFilter(def.mcpEvent?.filter, payload))
4450
- .sort(
4451
- (a, b) =>
4452
- (normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5),
4453
- );
4454
-
4455
- const triggered: string[] = [];
4456
- for (const def of matched) {
4457
- try {
4458
- await runTaskEntry(def.name);
4459
- triggered.push(def.name);
4460
- console.log(
4461
- `[agent-steward] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`,
4462
- );
4463
- } catch (err: any) {
4464
- console.error(
4465
- `[agent-steward] Не удалось запустить "${def.name}" по событию "${normalized}": ${
4466
- err instanceof Error ? err.message : String(err)
4467
- }`,
4468
- );
4469
- }
4470
- }
4471
-
4472
- return {
4473
- success: true,
4474
- triggered,
4475
- message: t("tool.event.processed", { event: normalized, count: triggered.length }),
4476
- };
5733
+ return await emitEventCore(eventName, payload, server);
4477
5734
  },
4478
5735
  pause_task: async (input: unknown) => {
4479
5736
  const { name, until } = input as { name: string; until?: string };
@@ -4489,8 +5746,12 @@ const v2Plugin = Plugin.define({
4489
5746
  return await updateTaskFromInput(input as UpdateArgs);
4490
5747
  },
4491
5748
  get_task_logs: async (input: unknown) => {
4492
- const { name } = input as { name: string };
4493
- const result = await getTaskLogs(name);
5749
+ const { name, taskName } = input as { name?: string; taskName?: string };
5750
+ const resolved = name?.trim() || taskName?.trim();
5751
+ if (!resolved) {
5752
+ return { success: false, logs: "", error: "Укажите name или taskName задачи" };
5753
+ }
5754
+ const result = await getTaskLogs(resolved);
4494
5755
  if (result.error) {
4495
5756
  return { success: false, logs: "", error: result.error };
4496
5757
  }
@@ -4511,7 +5772,10 @@ const v2Plugin = Plugin.define({
4511
5772
  return { records };
4512
5773
  },
4513
5774
  get_metrics: async () => {
4514
- return await loadMetrics();
5775
+ const metrics = await loadMetrics();
5776
+ const since = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString();
5777
+ const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
5778
+ return { ...metrics, toolBlocked };
4515
5779
  },
4516
5780
  cleanup_history: async (input: unknown) => {
4517
5781
  const { retentionDays, maxRecords } = input as {
@@ -4539,7 +5803,7 @@ const v2Plugin = Plugin.define({
4539
5803
  maxRecords: report.maxRecords,
4540
5804
  vacuumed: report.vacuumed,
4541
5805
  };
4542
- } catch (err: any) {
5806
+ } catch (err) {
4543
5807
  return {
4544
5808
  success: false,
4545
5809
  message: t("tool.history.cleanFailed", {
@@ -4562,18 +5826,25 @@ const v2Plugin = Plugin.define({
4562
5826
  365,
4563
5827
  Math.max(1, Math.floor(Number(days) || 14)),
4564
5828
  );
4565
- const records = getHistory(null, 20000);
5829
+ const records = getHistoryForAnalytics(windowDays);
4566
5830
  const definitions = await loadTaskDefinitions();
4567
5831
  const report = buildAnalytics(records, {
4568
5832
  days: windowDays,
4569
5833
  topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
4570
- tasks: definitions.map((definition) => ({
5834
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
4571
5835
  name: definition.name,
4572
5836
  matrixParentId: definition.matrixParentId,
5837
+ tokenBudget: definition.tokenBudget,
4573
5838
  })),
4574
5839
  });
4575
- return { success: true, report };
4576
- } catch (err: any) {
5840
+ // Экономика v2 (E-1.1): тот же учёт, что и в агент-инструменте.
5841
+ const settings = await loadSettings();
5842
+ const budgets = buildBudgetReport(records, settings.budgets, new Date());
5843
+ // PL-4.1: та же метрика корректности прав, что и в MCP get_analytics.
5844
+ const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1000).toISOString();
5845
+ const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
5846
+ return { success: true, report: { ...report, budgets, toolBlocked } };
5847
+ } catch (err) {
4577
5848
  return {
4578
5849
  success: false,
4579
5850
  report: null,
@@ -4594,19 +5865,20 @@ const v2Plugin = Plugin.define({
4594
5865
  365,
4595
5866
  Math.max(1, Math.floor(Number(days) || 14)),
4596
5867
  );
4597
- const records = getHistory(null, 20000);
5868
+ const records = getHistoryForAnalytics(windowDays);
4598
5869
  const definitions = await loadTaskDefinitions();
4599
5870
  const report = generateSelfAnalysisReport(records, {
4600
5871
  days: windowDays,
4601
5872
  topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
4602
- tasks: definitions.map((definition) => ({
5873
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
4603
5874
  name: definition.name,
4604
5875
  matrixParentId: definition.matrixParentId,
5876
+ tokenBudget: definition.tokenBudget,
4605
5877
  })),
4606
5878
  });
4607
5879
 
4608
5880
  // Фильтруем секции если нужно
4609
- const result: any = {
5881
+ const result: Partial<typeof report> = {
4610
5882
  generatedAt: report.generatedAt,
4611
5883
  windowDays: report.windowDays,
4612
5884
  health: report.health,
@@ -4625,7 +5897,7 @@ const v2Plugin = Plugin.define({
4625
5897
  }
4626
5898
 
4627
5899
  return { success: true, report: result };
4628
- } catch (err: any) {
5900
+ } catch (err) {
4629
5901
  return {
4630
5902
  success: false,
4631
5903
  report: null,
@@ -4633,6 +5905,72 @@ const v2Plugin = Plugin.define({
4633
5905
  };
4634
5906
  }
4635
5907
  },
5908
+ report_bug: async (input: unknown) => {
5909
+ const {
5910
+ description,
5911
+ taskName,
5912
+ includeLogs,
5913
+ includeAnalytics,
5914
+ channel,
5915
+ destination,
5916
+ contactEmail,
5917
+ dryRun,
5918
+ } = input as {
5919
+ description?: string;
5920
+ taskName?: string;
5921
+ includeLogs?: boolean;
5922
+ includeAnalytics?: boolean;
5923
+ channel?: "all" | "webhook" | "telegram" | "native";
5924
+ destination?: "author" | "local" | "both";
5925
+ contactEmail?: string;
5926
+ dryRun?: boolean;
5927
+ };
5928
+ try {
5929
+ if (!description || !description.trim()) {
5930
+ return { success: false, error: "description is required" };
5931
+ }
5932
+ const settings = await loadSettings();
5933
+ const logsAllowed = includeLogs ?? settings.feedback.includeLogs;
5934
+ const built = await buildBugReportText({
5935
+ description,
5936
+ taskName,
5937
+ includeLogs: logsAllowed,
5938
+ includeAnalytics,
5939
+ });
5940
+ const secretValues = collectSecretValues();
5941
+ const localText = redactText(built.text, {
5942
+ secrets: secretValues,
5943
+ redactEmails: false,
5944
+ });
5945
+ const result = await reportFeedback({
5946
+ settings: settings.feedback,
5947
+ destination: destination ?? "author",
5948
+ dryRun,
5949
+ description,
5950
+ taskName,
5951
+ contactEmail: contactEmail ?? settings.feedback.contactEmail,
5952
+ redactedLogs: logsAllowed ? built.logs : undefined,
5953
+ metrics: built.metrics,
5954
+ locale: settings.locale,
5955
+ secrets: secretValues,
5956
+ sendLocal: (text) => sendBugReport(text, channel),
5957
+ localText,
5958
+ });
5959
+ return {
5960
+ success: result.success,
5961
+ reportId: result.reportId,
5962
+ mode: result.mode,
5963
+ preview: result.preview,
5964
+ error: result.error,
5965
+ author: result.author,
5966
+ };
5967
+ } catch (err) {
5968
+ return {
5969
+ success: false,
5970
+ error: err instanceof Error ? err.message : String(err),
5971
+ };
5972
+ }
5973
+ },
4636
5974
  get_dashboard_port: async () => {
4637
5975
  return { port: getDashboardPort() };
4638
5976
  },
@@ -4644,7 +5982,7 @@ const v2Plugin = Plugin.define({
4644
5982
  try {
4645
5983
  const report = await simulatePipeline(taskName);
4646
5984
  return { ...report };
4647
- } catch (err: any) {
5985
+ } catch (err) {
4648
5986
  return {
4649
5987
  success: false,
4650
5988
  taskName,
@@ -4657,12 +5995,12 @@ const v2Plugin = Plugin.define({
4657
5995
  },
4658
5996
  dry_run_all: async () => {
4659
5997
  const tasks = await loadTaskDefinitions();
4660
- const reports: any[] = [];
5998
+ const reports: (DryRunReport & { error?: string })[] = [];
4661
5999
  let allSuccess = true;
4662
6000
  for (const task of tasks) {
4663
6001
  try {
4664
6002
  reports.push(await simulatePipeline(task.name));
4665
- } catch (err: any) {
6003
+ } catch (err) {
4666
6004
  allSuccess = false;
4667
6005
  reports.push({
4668
6006
  success: false,
@@ -4676,6 +6014,35 @@ const v2Plugin = Plugin.define({
4676
6014
  }
4677
6015
  return { success: allSuccess, reports };
4678
6016
  },
6017
+ pipeline_validate: async (input: unknown) => {
6018
+ const { path, source, dryRun } = input as {
6019
+ path?: string;
6020
+ source?: string;
6021
+ dryRun?: boolean;
6022
+ };
6023
+ const result = await pipelineValidateExecute({ path, source, dryRun } as PipelineValidateArgs, {});
6024
+ const parsed: unknown = JSON.parse(result.content as string);
6025
+ return parsed;
6026
+ },
6027
+ pipeline_apply: async (input: unknown) => {
6028
+ const { path, source, dryRun } = input as {
6029
+ path?: string;
6030
+ source?: string;
6031
+ dryRun?: boolean;
6032
+ };
6033
+ const result = await pipelineApplyExecute({ path, source, dryRun } as PipelineApplyArgs, {});
6034
+ const parsed: unknown = JSON.parse(result.content as string);
6035
+ return parsed;
6036
+ },
6037
+ pipeline_export: async (input: unknown) => {
6038
+ const { pipeline, pipelineName } = input as { pipeline?: string; pipelineName?: string };
6039
+ const result = await pipelineExportExecute(
6040
+ { pipeline: pipeline ?? pipelineName },
6041
+ {},
6042
+ );
6043
+ const parsed: unknown = JSON.parse(result.content as string);
6044
+ return parsed;
6045
+ },
4679
6046
  get_matrix_results: async (input: unknown) => {
4680
6047
  const { parentId } = input as { parentId?: string; name?: string };
4681
6048
  const target = (parentId ?? "").trim();
@@ -4685,7 +6052,7 @@ const v2Plugin = Plugin.define({
4685
6052
  try {
4686
6053
  const report = aggregateMatrixResults(target);
4687
6054
  return { success: true, report };
4688
- } catch (err: any) {
6055
+ } catch (err) {
4689
6056
  return {
4690
6057
  success: false,
4691
6058
  error: err instanceof Error ? err.message : String(err),
@@ -4722,7 +6089,7 @@ const v2Plugin = Plugin.define({
4722
6089
  : null,
4723
6090
  })),
4724
6091
  };
4725
- } catch (err: any) {
6092
+ } catch (err) {
4726
6093
  return {
4727
6094
  success: false,
4728
6095
  clones: [],
@@ -4757,7 +6124,7 @@ const v2Plugin = Plugin.define({
4757
6124
  gitBranch: readGitBranch(workspace.path) ?? null,
4758
6125
  },
4759
6126
  };
4760
- } catch (err: any) {
6127
+ } catch (err) {
4761
6128
  return { success: false, error: err instanceof Error ? err.message : String(err) };
4762
6129
  }
4763
6130
  },
@@ -4785,7 +6152,7 @@ const v2Plugin = Plugin.define({
4785
6152
  gitBranch: readGitBranch(workspace.path) ?? null,
4786
6153
  },
4787
6154
  };
4788
- } catch (err: any) {
6155
+ } catch (err) {
4789
6156
  return { success: false, error: err instanceof Error ? err.message : String(err) };
4790
6157
  }
4791
6158
  },
@@ -4799,7 +6166,7 @@ const v2Plugin = Plugin.define({
4799
6166
  ? t("tool.workspace.deleted")
4800
6167
  : t("tool.workspace.notFound"),
4801
6168
  };
4802
- } catch (err: any) {
6169
+ } catch (err) {
4803
6170
  return { success: false, message: err instanceof Error ? err.message : String(err) };
4804
6171
  }
4805
6172
  },
@@ -4823,7 +6190,7 @@ const v2Plugin = Plugin.define({
4823
6190
  ? t("tool.profile.envVarLong", { name: current })
4824
6191
  : t("tool.profile.active", { name: sanitizeProfileName(name) }),
4825
6192
  };
4826
- } catch (err: any) {
6193
+ } catch (err) {
4827
6194
  return {
4828
6195
  success: false,
4829
6196
  current: getProfileName(),
@@ -4848,7 +6215,7 @@ const v2Plugin = Plugin.define({
4848
6215
  active: meta.name === getProfileName(),
4849
6216
  },
4850
6217
  };
4851
- } catch (err: any) {
6218
+ } catch (err) {
4852
6219
  return {
4853
6220
  success: false,
4854
6221
  error: err instanceof Error ? err.message : String(err),
@@ -4865,7 +6232,7 @@ const v2Plugin = Plugin.define({
4865
6232
  ? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
4866
6233
  : t("tool.profile.notFound"),
4867
6234
  };
4868
- } catch (err: any) {
6235
+ } catch (err) {
4869
6236
  return { success: false, message: err instanceof Error ? err.message : String(err) };
4870
6237
  }
4871
6238
  },
@@ -4873,7 +6240,7 @@ const v2Plugin = Plugin.define({
4873
6240
  return await loadSettings();
4874
6241
  },
4875
6242
  save_settings: async (input: unknown) => {
4876
- const { maxConcurrent, locale, uiLocale, winterMode, notifications, history, integrations, audit, permissions } = input as {
6243
+ const { maxConcurrent, locale, uiLocale, winterMode, notifications, history, integrations, audit, permissions, budgets, feedback } = input as {
4877
6244
  maxConcurrent?: number;
4878
6245
  locale?: LocaleMode;
4879
6246
  uiLocale?: Locale;
@@ -4883,6 +6250,8 @@ const v2Plugin = Plugin.define({
4883
6250
  integrations?: IntegrationSettings;
4884
6251
  audit?: AuditSettings;
4885
6252
  permissions?: PermissionSettings;
6253
+ budgets?: BudgetSettings;
6254
+ feedback?: FeedbackSettings;
4886
6255
  };
4887
6256
  const current = await loadSettings();
4888
6257
  if (
@@ -4894,7 +6263,9 @@ const v2Plugin = Plugin.define({
4894
6263
  history === undefined &&
4895
6264
  integrations === undefined &&
4896
6265
  audit === undefined &&
4897
- permissions === undefined
6266
+ permissions === undefined &&
6267
+ budgets === undefined &&
6268
+ feedback === undefined
4898
6269
  ) {
4899
6270
  return {
4900
6271
  success: false,
@@ -4907,6 +6278,8 @@ const v2Plugin = Plugin.define({
4907
6278
  integrations: current.integrations,
4908
6279
  audit: current.audit,
4909
6280
  permissions: current.permissions,
6281
+ budgets: current.budgets,
6282
+ feedback: current.feedback,
4910
6283
  };
4911
6284
  }
4912
6285
  const settings = await saveSettings({
@@ -4919,6 +6292,8 @@ const v2Plugin = Plugin.define({
4919
6292
  integrations,
4920
6293
  audit,
4921
6294
  permissions,
6295
+ budgets,
6296
+ feedback,
4922
6297
  });
4923
6298
  // Локаль процесса меняется сразу — перезапуск не нужен.
4924
6299
  setLocale(resolveLocale(settings.locale, settings.uiLocale));
@@ -4933,6 +6308,8 @@ const v2Plugin = Plugin.define({
4933
6308
  integrations: settings.integrations,
4934
6309
  audit: settings.audit,
4935
6310
  permissions: settings.permissions,
6311
+ budgets: settings.budgets,
6312
+ feedback: settings.feedback,
4936
6313
  };
4937
6314
  },
4938
6315
  test_notification: async () => {
@@ -5026,7 +6403,7 @@ const v2Plugin = Plugin.define({
5026
6403
  message: t("tool.secret.saved", { name: secret.name }),
5027
6404
  secret,
5028
6405
  };
5029
- } catch (err: any) {
6406
+ } catch (err) {
5030
6407
  return {
5031
6408
  success: false,
5032
6409
  message: err instanceof Error ? err.message : String(err),
@@ -5047,7 +6424,7 @@ const v2Plugin = Plugin.define({
5047
6424
  ? t("tool.secret.deleted", { name })
5048
6425
  : t("tool.secret.notFound", { name }),
5049
6426
  };
5050
- } catch (err: any) {
6427
+ } catch (err) {
5051
6428
  return {
5052
6429
  success: false,
5053
6430
  message: err instanceof Error ? err.message : String(err),
@@ -5063,6 +6440,10 @@ const v2Plugin = Plugin.define({
5063
6440
  until?: string;
5064
6441
  limit?: number;
5065
6442
  };
6443
+ const dateError =
6444
+ auditDateFilterError(source.since, "since") ??
6445
+ auditDateFilterError(source.until, "until");
6446
+ if (dateError) return { success: false, message: dateError };
5066
6447
  const result = readAuditLog({
5067
6448
  action: source.action,
5068
6449
  target: source.target,
@@ -5113,7 +6494,7 @@ const v2Plugin = Plugin.define({
5113
6494
  get_templates: async () => {
5114
6495
  try {
5115
6496
  return { templates: await loadTemplates() };
5116
- } catch (err: any) {
6497
+ } catch (err) {
5117
6498
  console.error("[agent-steward] get_templates error:", err);
5118
6499
  return { templates: [] };
5119
6500
  }
@@ -5144,7 +6525,7 @@ const v2Plugin = Plugin.define({
5144
6525
  : undefined,
5145
6526
  });
5146
6527
  return { success: true, template };
5147
- } catch (err: any) {
6528
+ } catch (err) {
5148
6529
  return {
5149
6530
  success: false,
5150
6531
  error: err instanceof Error ? err.message : String(err),
@@ -5157,9 +6538,15 @@ const v2Plugin = Plugin.define({
5157
6538
  return { success: false, error: t("tool.template.needId") };
5158
6539
  }
5159
6540
  try {
6541
+ // QA-P3.3: принимаем и id, и имя шаблона; отсутствие — явная ошибка.
6542
+ const templates = await loadTemplates();
6543
+ const existed = templates.some((template) => template.id === id || template.name === id);
6544
+ if (!existed) {
6545
+ return { success: false, error: t("tool.template.notFound", { id }) };
6546
+ }
5160
6547
  await deleteTemplate(id);
5161
6548
  return { success: true };
5162
- } catch (err: any) {
6549
+ } catch (err) {
5163
6550
  return {
5164
6551
  success: false,
5165
6552
  error: err instanceof Error ? err.message : String(err),
@@ -5175,7 +6562,7 @@ const v2Plugin = Plugin.define({
5175
6562
  }));
5176
6563
  const { data, count } = await buildExportJson(exportTasks);
5177
6564
  return { success: true, data, count };
5178
- } catch (err: any) {
6565
+ } catch (err) {
5179
6566
  return { success: false, error: err instanceof Error ? err.message : String(err) };
5180
6567
  }
5181
6568
  },
@@ -5245,10 +6632,14 @@ const v2Plugin = Plugin.define({
5245
6632
  def.runWhenLoggedOff === true,
5246
6633
  def.paused === true,
5247
6634
  def.legacyShell === true,
6635
+ def.worktree === true,
6636
+ def.guards,
6637
+ // QA-P0.1 (E-2.1): импорт через RPC сохраняет tokenBudget.
6638
+ def.tokenBudget,
5248
6639
  );
5249
6640
  await saveTaskDefinition(def);
5250
6641
  imported.push(def.name);
5251
- } catch (err: any) {
6642
+ } catch (err) {
5252
6643
  errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
5253
6644
  }
5254
6645
  }
@@ -5258,7 +6649,7 @@ const v2Plugin = Plugin.define({
5258
6649
  imported: imported.length,
5259
6650
  errors: errors.length ? errors : undefined,
5260
6651
  };
5261
- } catch (err: any) {
6652
+ } catch (err) {
5262
6653
  return { success: false, error: err instanceof Error ? err.message : String(err) };
5263
6654
  }
5264
6655
  },
@@ -5271,7 +6662,7 @@ const v2Plugin = Plugin.define({
5271
6662
 
5272
6663
  // Lifecycle матриц (Спринт 16): при старте вычищаем клоны/агрегаторы,
5273
6664
  // чьи родители были удалены в прошлых сессиях.
5274
- void cleanupOrphanedMatrixTasks().catch((err: any) => {
6665
+ void cleanupOrphanedMatrixTasks().catch((err) => {
5275
6666
  console.log(
5276
6667
  `[matrix] Не удалось очистить осиротевшие задачи: ${
5277
6668
  err instanceof Error ? err.message : String(err)
@@ -5293,36 +6684,49 @@ const v2Plugin = Plugin.define({
5293
6684
  * Приводит результат V2-обработчика (`Tool.Result`) к формату V1 (`ToolResult`).
5294
6685
  * V1 ждёт строку или `{ output, metadata }`; V2 отдаёт `{ content }`.
5295
6686
  */
5296
- export function toV1ToolResult(result: any): any {
6687
+ type V1ToolResult = string | { output: string; metadata?: Tool.Result["metadata"] };
6688
+
6689
+ /** Сужает элемент content до текстового блока (остальные типы V2 не нас интересуют). */
6690
+ function isTextContent(part: unknown): part is { type: "text"; text: string } {
6691
+ return (
6692
+ typeof part === "object" &&
6693
+ part !== null &&
6694
+ "type" in part &&
6695
+ part.type === "text" &&
6696
+ "text" in part &&
6697
+ typeof part.text === "string"
6698
+ );
6699
+ }
6700
+
6701
+ export function toV1ToolResult(result: Tool.Result | string): V1ToolResult {
5297
6702
  if (typeof result === "string") return result;
5298
- if (Array.isArray(result?.content)) {
5299
- const text = result.content
5300
- .filter((part: any) => part?.type === "text" && typeof part.text === "string")
5301
- .map((part: any) => part.text)
5302
- .join("\n");
5303
- return { output: text, metadata: result.metadata };
6703
+ const metadata = result.metadata;
6704
+ const content = result.content;
6705
+ if (Array.isArray(content)) {
6706
+ const text = content.filter(isTextContent).map((part) => part.text).join("\n");
6707
+ return { output: text, metadata };
5304
6708
  }
5305
- if (typeof result?.content === "string") {
5306
- return { output: result.content, metadata: result.metadata };
6709
+ if (typeof content === "string") {
6710
+ return { output: content, metadata };
5307
6711
  }
5308
- if (typeof result?.output === "string") {
5309
- return { output: result.output, metadata: result.metadata };
6712
+ if (typeof result.output === "string") {
6713
+ return { output: result.output, metadata };
5310
6714
  }
5311
- return { output: JSON.stringify(result), metadata: result?.metadata };
6715
+ return { output: JSON.stringify(result), metadata };
5312
6716
  }
5313
6717
 
5314
6718
  /**
5315
6719
  * V1 `tool()` принимает `z.ZodRawShape`, а спецификации хранят `z.object(...)`.
5316
6720
  * Возвращаем именно shape, чтобы V1 не получил готовый объект схемы.
5317
6721
  */
5318
- export function toV1ToolArgs(spec: ToolSpec): Record<string, any> {
6722
+ export function toV1ToolArgs(spec: ToolSpec): z.ZodRawShape {
5319
6723
  const shape = (spec.input as { shape?: unknown } | undefined)?.shape;
5320
6724
  if (!shape || typeof shape !== "object") {
5321
6725
  throw new Error(
5322
6726
  `V1-адаптер: схема инструмента "${spec.name}" должна быть z.object(...)`,
5323
6727
  );
5324
6728
  }
5325
- return shape as Record<string, any>;
6729
+ return shape as z.ZodRawShape;
5326
6730
  }
5327
6731
 
5328
6732
  /**
@@ -5330,17 +6734,28 @@ export function toV1ToolArgs(spec: ToolSpec): Record<string, any> {
5330
6734
  * V2, плюс тот же аудит. Отличие одно — у V1 `tool()` нет `codemode`, поэтому
5331
6735
  * флаг не передаётся (см. docs/COMPATIBILITY.md).
5332
6736
  */
5333
- export function createV1Tools(runtime: SchedulerRuntime): Record<string, any> {
5334
- const tools: Record<string, any> = {};
6737
+ /**
6738
+ * Локальное описание V1-реестра. V1-плагин тянет свою копию zod (4.1.8),
6739
+ * поэтому его `ToolDefinition` структурно несовместим с нашим zod (4.6.7).
6740
+ * Приведение типов делается один раз на границе `createV1Hooks`.
6741
+ */
6742
+ interface V1ToolDefinition {
6743
+ description: string;
6744
+ args: z.ZodRawShape;
6745
+ execute(args: unknown, context: unknown): Promise<V1ToolResult>;
6746
+ }
6747
+ type V1ToolRegistry = Record<string, V1ToolDefinition>;
6748
+
6749
+ export function createV1Tools(runtime: SchedulerRuntime): V1ToolRegistry {
6750
+ const tools: V1ToolRegistry = {};
5335
6751
  for (const spec of createToolSpecs(runtime)) {
5336
6752
  const execute = spec.audit
5337
6753
  ? withAudit(spec.name, spec.audit, spec.execute)
5338
6754
  : spec.execute;
5339
6755
  tools[spec.name] = v1Tool({
5340
6756
  description: spec.description,
5341
- args: toV1ToolArgs(spec) as any,
5342
- execute: (async (args: any, context: any) =>
5343
- toV1ToolResult(await execute(args, context))) as any,
6757
+ args: toV1ToolArgs(spec),
6758
+ execute: async (args, context) => toV1ToolResult(await execute(args, context)),
5344
6759
  });
5345
6760
  }
5346
6761
  return tools;
@@ -5357,13 +6772,21 @@ export async function createV1Hooks(
5357
6772
  input: Pick<V1PluginInput, "directory"> = { directory: process.cwd() },
5358
6773
  options: { startDashboard?: boolean } = {},
5359
6774
  ): Promise<V1Hooks> {
6775
+ if (isChildRunMode()) {
6776
+ console.log(`[qv8] ${CHILD_RUN_ENV}: дочерний прогон, пропускаю регистрацию плагина`);
6777
+ return { tool: {}, dispose: async () => undefined };
6778
+ }
6779
+ // PL-45: см. V2 setup — повторная регистрация должна открывать ворота.
6780
+ shutdownGate.reset();
5360
6781
  const runtime = await createRuntime({ location: { directory: input.directory } });
5361
6782
  const tools = createV1Tools(runtime);
5362
6783
  if (options.startDashboard !== false) {
5363
6784
  await startSchedulerDashboard();
5364
6785
  }
5365
6786
  return {
5366
- tool: tools,
6787
+ // QA-A2.1: граница внешнего V1 API — у плагина отдельная копия zod,
6788
+ // типы несовместимы структурно. Значения и поведение не меняются.
6789
+ tool: tools as unknown as V1Hooks["tool"],
5367
6790
  dispose: createShutdownHandler(runtime),
5368
6791
  };
5369
6792
  }
@@ -5472,7 +6895,38 @@ export interface TriggerExtras {
5472
6895
  gitPollSeconds?: number;
5473
6896
  }
5474
6897
 
5475
- async function schedulerCreateTask(
6898
+ /**
6899
+ * PL-42: вход нормализации mcpEvent. `eventName` — алиас `event`, который
6900
+ * присылает `emit_event`; оба поля необязательны, но хотя бы одно нужно
6901
+ * для triggerType=mcp-event (проверяется после нормализации).
6902
+ */
6903
+ interface McpEventInput {
6904
+ server?: string;
6905
+ /** Каноническое имя события. Приоритетнее алиаса. */
6906
+ event?: string;
6907
+ /** Алиас emit_event; используется, только если event пуст. */
6908
+ eventName?: string;
6909
+ filter?: string;
6910
+ }
6911
+
6912
+ /**
6913
+ * PL-42: приводит mcpEvent к каноническому виду `{ server, event, filter? }`.
6914
+ * `event` имеет приоритет: если заданы оба поля и они различаются, alias
6915
+ * `eventName` игнорируется — так поведение старых задач не меняется.
6916
+ */
6917
+ export function normalizeMcpEventTrigger(
6918
+ mcpEvent?: McpEventInput,
6919
+ ): McpEventTrigger | undefined {
6920
+ const rawEvent = mcpEvent?.event?.trim() || mcpEvent?.eventName?.trim();
6921
+ if (!rawEvent) return undefined;
6922
+ return {
6923
+ server: mcpEvent?.server?.trim() || "",
6924
+ event: rawEvent,
6925
+ ...(mcpEvent?.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
6926
+ };
6927
+ }
6928
+
6929
+ export async function schedulerCreateTask(
5476
6930
  name: string,
5477
6931
  schedule: string,
5478
6932
  prompt: string,
@@ -5490,7 +6944,7 @@ async function schedulerCreateTask(
5490
6944
  priority?: number,
5491
6945
  beforeScript?: string,
5492
6946
  afterScript?: string,
5493
- mcpEvent?: McpEventTrigger,
6947
+ mcpEvent?: McpEventInput,
5494
6948
  workspaceId?: string,
5495
6949
  allowedTools?: string[],
5496
6950
  deniedTools?: string[],
@@ -5528,6 +6982,12 @@ async function schedulerCreateTask(
5528
6982
  * true возвращает shell задаче, созданной до обновления поведения.
5529
6983
  */
5530
6984
  legacyShell?: boolean,
6985
+ /** W-1: одноразовый git worktree на каждый запуск. */
6986
+ worktree?: boolean,
6987
+ /** W-3: guard-условия перед запуском opencode. */
6988
+ guards?: TaskGuards,
6989
+ /** Economics v2 (E-2): per-run token budget. 0/omitted = no limit (fail-open). */
6990
+ tokenBudget?: number,
5531
6991
  ): Promise<void> {
5532
6992
  // Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
5533
6993
  // в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
@@ -5593,6 +7053,18 @@ async function schedulerCreateTask(
5593
7053
  const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
5594
7054
  // Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
5595
7055
  const normalizedPaused = paused === true ? true : undefined;
7056
+ // W-1: изоляция запуска в одноразовом git worktree.
7057
+ const normalizedWorktree = worktree === true ? true : undefined;
7058
+ // W-3: guard-условия. Ошибка нормализации — явная ошибка создания задачи,
7059
+ // чтобы опечатка в конфигурации не превратилась в молчаливый пропуск.
7060
+ const guardsResult = normalizeTaskGuards(guards);
7061
+ if (!guardsResult.ok) throw new Error(guardsResult.error);
7062
+ const normalizedGuards = guardsResult.guards;
7063
+ // Economics v2 (E-2): нормализация бюджета токенов. 0/отрицание/NaN = без лимита.
7064
+ const normalizedTokenBudget =
7065
+ Number.isFinite(tokenBudget) && (tokenBudget ?? 0) > 0
7066
+ ? Math.floor(tokenBudget!)
7067
+ : undefined;
5596
7068
  // Спринт 27: дни недели, политика окна и glob/git-фильтры.
5597
7069
  const normalizeGlobList = (raw?: string[]): string[] | undefined => {
5598
7070
  if (!Array.isArray(raw)) return undefined;
@@ -5622,14 +7094,9 @@ async function schedulerCreateTask(
5622
7094
  triggerExtras.gitPollSeconds >= 5
5623
7095
  ? Math.floor(triggerExtras.gitPollSeconds)
5624
7096
  : undefined;
5625
- const normalizedMcpEvent =
5626
- mcpEvent?.event?.trim()
5627
- ? {
5628
- server: mcpEvent.server?.trim() || "",
5629
- event: mcpEvent.event.trim(),
5630
- ...(mcpEvent.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
5631
- }
5632
- : undefined;
7097
+ // PL-42: mcpEvent принимает event и его алиас eventName (emit_event).
7098
+ // event приоритетнее: если оба заданы и различаются, побеждает event.
7099
+ const normalizedMcpEvent = normalizeMcpEventTrigger(mcpEvent);
5633
7100
  let effectiveTriggerType = triggerType ?? "cron";
5634
7101
  // One-shot: нормализуем время до создания файлов и задачи в ОС.
5635
7102
  // Для остальных триггеров runAt не имеет смысла и отбрасывается.
@@ -5789,8 +7256,8 @@ async function schedulerCreateTask(
5789
7256
  // Расширенная грамматика (Спринт 19): диапазоны, списки, шаги,
5790
7257
  // имена месяцев/дней, @every, L и FRI#3.
5791
7258
  parseCron(schedule);
5792
- } catch (err: any) {
5793
- throw new Error(err.message || String(err));
7259
+ } catch (err) {
7260
+ throw new Error(err instanceof Error ? err.message : String(err));
5794
7261
  }
5795
7262
  if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
5796
7263
  throw new Error(
@@ -5902,18 +7369,18 @@ async function schedulerCreateTask(
5902
7369
  if (effectiveWatchPath) {
5903
7370
  try {
5904
7371
  effectiveWatchPath = normalizeWatchPath(effectiveWatchPath, effectiveWorkingDirectory);
5905
- } catch (err: any) {
7372
+ } catch (err) {
5906
7373
  throw new Error(
5907
- t("tool.error.taskReason", { name, error: err.message || String(err) }),
7374
+ t("tool.error.taskReason", { name, error: err instanceof Error ? err.message : String(err) }),
5908
7375
  );
5909
7376
  }
5910
7377
  }
5911
7378
  try {
5912
7379
  validateWatchGlobs(normalizedWatchGlobs);
5913
7380
  validateWatchGlobs(normalizedWatchIgnore);
5914
- } catch (err: any) {
7381
+ } catch (err) {
5915
7382
  throw new Error(
5916
- t("tool.error.taskReason", { name, error: err.message || String(err) }),
7383
+ t("tool.error.taskReason", { name, error: err instanceof Error ? err.message : String(err) }),
5917
7384
  );
5918
7385
  }
5919
7386
 
@@ -5939,11 +7406,16 @@ async function schedulerCreateTask(
5939
7406
  try {
5940
7407
  promptFile = await writePromptFile(sanitized, prompt);
5941
7408
  await fs.mkdir(LOG_DIR, { recursive: true });
5942
- await fs.writeFile(logFile, "", "utf8");
5943
- } catch (err: any) {
7409
+ // Не обнуляем лог: при падении до запуска обёртки (или при отказе модели)
7410
+ // предыдущий диагностический вывод оставался бы единственным, а новый
7411
+ // прогон выглядел бы как «лог пуст». Дописываем маркер ПОДГОТОВКИ —
7412
+ // задача создана, но ещё не запускалась (не путать с реальным Run started,
7413
+ // который пишется обёрткой только при фактическом запуске; QA #8).
7414
+ await fs.appendFile(logFile, formatLogRunMarker("prepare", name), "utf8");
7415
+ } catch (err) {
5944
7416
  throw new Error(
5945
7417
  t("tool.error.prepareFiles", {
5946
- error: err.message || String(err),
7418
+ error: err instanceof Error ? err.message : String(err),
5947
7419
  }),
5948
7420
  );
5949
7421
  }
@@ -5979,12 +7451,15 @@ async function schedulerCreateTask(
5979
7451
  taskEnvFile,
5980
7452
  effectiveSession,
5981
7453
  effectiveSessionId,
5982
- retryCount,
5983
- retryDelay,
5984
7454
  undefined,
5985
7455
  permissionsConfig,
5986
7456
  policyMeta,
5987
7457
  sessionFile,
7458
+ normalizedWorktree,
7459
+ worktreeHelperPath,
7460
+ normalizedGuards,
7461
+ guardHelperPath,
7462
+ gateAllowPathsFromAfterScript(normalizedAfter),
5988
7463
  );
5989
7464
  } else {
5990
7465
  wrapperPath = await writeBashWrapper({
@@ -6010,15 +7485,20 @@ async function schedulerCreateTask(
6010
7485
  sessionMode: effectiveSession,
6011
7486
  sessionId: effectiveSessionId,
6012
7487
  sessionFile,
7488
+ worktree: normalizedWorktree,
7489
+ worktreeHelper: worktreeHelperPath,
7490
+ guards: normalizedGuards,
7491
+ guardHelper: guardHelperPath,
7492
+ gateAllowPaths: gateAllowPathsFromAfterScript(normalizedAfter),
6013
7493
  ...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
6014
7494
  ? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized, getProfileName()) }
6015
7495
  : {}),
6016
7496
  });
6017
7497
  }
6018
- } catch (err: any) {
7498
+ } catch (err) {
6019
7499
  throw new Error(
6020
7500
  t("tool.error.wrapper", {
6021
- error: err.message || String(err),
7501
+ error: err instanceof Error ? err.message : String(err),
6022
7502
  }),
6023
7503
  );
6024
7504
  }
@@ -6052,7 +7532,7 @@ async function schedulerCreateTask(
6052
7532
  notAfter: normalizedNotAfter,
6053
7533
  runWhenLoggedOff: normalizedRunWhenLoggedOff,
6054
7534
  });
6055
- } catch (err: any) {
7535
+ } catch (err) {
6056
7536
  await rollbackArtifacts();
6057
7537
  throw new Error(err instanceof Error ? err.message : String(err));
6058
7538
  }
@@ -6156,6 +7636,9 @@ async function schedulerCreateTask(
6156
7636
  allowedTools: normalizedAllowedTools,
6157
7637
  deniedTools: normalizedDeniedTools,
6158
7638
  legacyShell: legacyShell === true ? true : undefined,
7639
+ worktree: normalizedWorktree,
7640
+ guards: normalizedGuards,
7641
+ tokenBudget: normalizedTokenBudget,
6159
7642
  matrix: normalizedMatrix,
6160
7643
  isMatrixParent: normalizedMatrix ? true : undefined,
6161
7644
  matrixParentId,
@@ -6238,6 +7721,10 @@ async function schedulerCreateTask(
6238
7721
  clone.runWhenLoggedOff,
6239
7722
  clone.paused,
6240
7723
  clone.legacyShell,
7724
+ clone.worktree,
7725
+ clone.guards,
7726
+ // QA-P0.1 (E-2.1): клон матрицы наследует tokenBudget родителя.
7727
+ clone.tokenBudget,
6241
7728
  );
6242
7729
  };
6243
7730
 
@@ -6324,7 +7811,7 @@ async function schedulerCreateTask(
6324
7811
  try {
6325
7812
  await createClone(clone);
6326
7813
  createdInRun.push(clone.name);
6327
- } catch (err: any) {
7814
+ } catch (err) {
6328
7815
  const workspaceLabel = clone.workspaceId
6329
7816
  ? getWorkspace(clone.workspaceId)?.name ?? clone.workspaceId
6330
7817
  : "без workspace";
@@ -6338,7 +7825,7 @@ async function schedulerCreateTask(
6338
7825
  }
6339
7826
  }
6340
7827
  await syncAggregator();
6341
- } catch (err: any) {
7828
+ } catch (err) {
6342
7829
  for (const child of [...createdInRun].reverse()) {
6343
7830
  await removeChild(child);
6344
7831
  }
@@ -6380,7 +7867,7 @@ async function schedulerCreateTask(
6380
7867
  for (const target of pauseTargets) {
6381
7868
  try {
6382
7869
  await scheduler.pauseTask(target);
6383
- } catch (err: any) {
7870
+ } catch (err) {
6384
7871
  console.warn(
6385
7872
  `[agent-steward] Задача "${target}": пауза не восстановлена после пересоздания: ${
6386
7873
  err instanceof Error ? err.message : String(err)
@@ -6451,6 +7938,10 @@ async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<v
6451
7938
  definition.runWhenLoggedOff,
6452
7939
  paused,
6453
7940
  definition.legacyShell,
7941
+ definition.worktree,
7942
+ definition.guards,
7943
+ // QA-P0.1 (E-2.1): откат update не теряет tokenBudget.
7944
+ definition.tokenBudget,
6454
7945
  );
6455
7946
  }
6456
7947
 
@@ -6458,22 +7949,111 @@ async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<v
6458
7949
  * Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
6459
7950
  * на клоны, а не выполняет свой промпт.
6460
7951
  */
7952
+ /** E-1.2: общий гейт бюджета для всех входов запуска задач. */
7953
+ async function checkBudgetGate(now: Date = new Date()): Promise<BudgetGateDecision> {
7954
+ const settings = await loadSettings();
7955
+ // Неделя — widest период бюджетов. Выбираем записи по моменту завершения
7956
+ // (см. getHistoryForBudget), чтобы не зависеть от окна в 20000 запусков.
7957
+ const records = getHistoryForBudget(startOfUtcWeek(now).toISOString());
7958
+ const decision = evaluateBudgetGate(records, settings.budgets, now);
7959
+ if (!decision.allowed) {
7960
+ // E-1.3: алерт не должен задерживать или ломать запуск.
7961
+ void notifyBudgetExceeded(decision).catch((err: unknown) => {
7962
+ console.error(
7963
+ `[agent-steward] Ошибка бюджетного алерта: ${
7964
+ err instanceof Error ? err.message : String(err)
7965
+ }`,
7966
+ );
7967
+ });
7968
+ }
7969
+ return decision;
7970
+ }
7971
+
7972
+ /**
7973
+ * E-2.2: гейт персонального токен-бюджета задачи.
7974
+ *
7975
+ * Зеркалит общий бюджетный гейт E-1.2, но читает лимит из определения задачи
7976
+ * и фильтрует историю по её имени. Fail-open: без лимита запуск не блокируется.
7977
+ */
7978
+ function checkTaskTokenBudgetGate(
7979
+ taskName: string,
7980
+ tokenBudget: number | undefined,
7981
+ now: Date = new Date(),
7982
+ ): TaskTokenBudgetDecision {
7983
+ const records = getHistoryForBudget(startOfUtcWeek(now).toISOString());
7984
+ return evaluateTaskTokenBudgetGate(records, taskName, tokenBudget, now);
7985
+ }
7986
+
7987
+ /**
7988
+ * PL-1.1: структурированная ошибка отказа запуска во время выгрузки плагина.
7989
+ * Текст `message` сохранён дословно для совместимости с существующими
7990
+ * вызывающими; `code` и `hint` дают кнопке повтора/оператору понятный путь.
7991
+ */
7992
+ export class PluginShutdownError extends Error {
7993
+ readonly code = "PLUGIN_SHUTTING_DOWN";
7994
+ readonly hint: string;
7995
+ /** PL-10/QV-2: наблюдаемое состояние ворот в момент отказа. */
7996
+ readonly state: ShutdownGateState;
7997
+ /** PL-45: повтор возможен после перерегистрации плагина. */
7998
+ readonly retryable = true;
7999
+
8000
+ constructor(message: string, hint: string, state: ShutdownGateState) {
8001
+ super(message);
8002
+ this.name = "PluginShutdownError";
8003
+ this.hint = hint;
8004
+ this.state = state;
8005
+ }
8006
+ }
8007
+
6461
8008
  async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }> {
6462
8009
  if (shutdownGate.isShuttingDown()) {
6463
- throw new Error(
8010
+ throw new PluginShutdownError(
6464
8011
  "Плагин выгружается: новые запуски не принимаются. Повторите после перезапуска.",
8012
+ "Повторите запуск после перезапуска плагина. Для once/cron-задач используйте force-маркер locks/<slug>.lock.force + Start-ScheduledTask (schtasks /run) либо отложенный запуск после перезапуска.",
8013
+ shutdownGate.state(),
6465
8014
  );
6466
8015
  }
6467
8016
 
8017
+ const budgetGate = await checkBudgetGate();
8018
+ if (!budgetGate.allowed) {
8019
+ throw new Error(formatBudgetSkipMessage(budgetGate));
8020
+ }
8021
+
6468
8022
  const run = (async () => {
8023
+ const trimmed = name.trim();
6469
8024
  const definition = (await loadTaskDefinitions()).find(
6470
- (def) => def.name.toLowerCase() === name.trim().toLowerCase(),
8025
+ (def) => def.name.toLowerCase() === trimmed.toLowerCase(),
6471
8026
  );
8027
+
8028
+ // E-2.2: остановка задачи при превышении её персонального токен-бюджета.
8029
+ // Пропускаем новые запуски, если завершённый прогон за текущий UTC-день
8030
+ // или неделю уже превысил tokenBudget (fail-open, как и E-1.2).
8031
+ if (definition?.tokenBudget) {
8032
+ const taskGate = checkTaskTokenBudgetGate(trimmed, definition.tokenBudget);
8033
+ if (!taskGate.allowed) {
8034
+ throw new Error(formatTaskTokenBudgetSkipMessage(taskGate));
8035
+ }
8036
+ }
8037
+
6472
8038
  if (definition?.matrix) {
6473
8039
  await runMatrix(definition);
6474
8040
  return { alreadyRunning: false };
6475
8041
  }
6476
8042
 
8043
+ // QA-P3.6: если задачи нет ни в определениях, ни в планировщике ОС,
8044
+ // не дёргаем schtasks /run — он возвращает сырую ошибку ОС. Возвращаем
8045
+ // структурированное «задача не найдена», как и остальные инструменты.
8046
+ // Legacy-задачи, живущие только в ОС (без definition), остаются запускаемыми.
8047
+ if (!definition) {
8048
+ const osTasks = await scheduler.listTasks().catch(() => []);
8049
+ const osExists = osTasks.some(
8050
+ (task) => (task.taskName ?? "").toLowerCase() === trimmed.toLowerCase(),
8051
+ );
8052
+ if (!osExists) {
8053
+ throw new Error(t("tool.error.taskNotFound", { name: trimmed }));
8054
+ }
8055
+ }
8056
+
6477
8057
  // Любой запуск через этот вход — «сейчас», а не «по расписанию»:
6478
8058
  // run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
6479
8059
  // Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
@@ -6697,6 +8277,8 @@ async function collectTasksView() {
6697
8277
  deniedTools: Array.isArray(def?.deniedTools) ? def.deniedTools : null,
6698
8278
  matrix: def?.matrix ?? null,
6699
8279
  matrixParentId: def?.matrixParentId ?? null,
8280
+ /** Экономика v2 (E-2): лимит токенов на запуск для аналитики дашборда. */
8281
+ tokenBudget: def?.tokenBudget ?? null,
6700
8282
  isMatrixParent: Boolean(def?.matrix),
6701
8283
  matrixSummary: matrixAggregate
6702
8284
  ? {