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/dist/index.js CHANGED
@@ -1,5 +1,9 @@
1
1
  import { Plugin } from "@opencode/plugin";
2
- import { tool as v1Tool, } from "@opencode-ai/plugin";
2
+ // V1 `tool()` — тривиальная identity-функция (`input => input`). Инлайним её,
3
+ // чтобы точка входа V2 не импортировала devDependency @opencode-ai/plugin:
4
+ // у пользователя OpenCode 2 этот пакет не установлен, и статический импорт
5
+ // ломал загрузку плагина целиком (ERR_MODULE_NOT_FOUND).
6
+ const v1Tool = (input) => input;
3
7
  import { z } from "zod";
4
8
  import { createRequire } from "node:module";
5
9
  import { existsSync } from "node:fs";
@@ -10,29 +14,39 @@ import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, STALE_LOCK_MAX_AGE_MS, WRAPPER_DIR, sani
10
14
  import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs, assessCronWindowFeasibility, windowFeasibilityReasonText } from "./core/schedule-v2.js";
11
15
  import { buildLaunchdOneShotCleanup, normalizeOneShotRunAt, } from "./core/one-shot.js";
12
16
  import { generateSessionId, normalizeSessionMode, preservedSessionRunCount, sessionStatePath, writeSessionStateFile, } from "./core/session.js";
13
- import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
17
+ import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun, gateAllowPathsFromAfterScript } from "./core/ps-wrapper.js";
14
18
  import { getSchedulerBackend, LinuxScheduler } from "./core/scheduler/index.js";
15
19
  import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
16
20
  import { getTaskLogs } from "./core/scheduler/logs.js";
17
21
  import { findSanitizedNameConflict, sanitizedConflictMessage } from "./core/task-name.js";
18
22
  import { writeBashWrapper } from "./core/wrappers/bash.js";
19
- import { simulatePipeline } from "./core/dry-run.js";
20
- import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, findOrphanedMatrixTasks, getMatrixDeletionGuard, matrixCompleteName, planMatrixFamilyDelete, removeMatrixChildren, runMatrix, syncMatrixFamily, } from "./core/matrix.js";
23
+ import { normalizeTaskGuards } from "./core/guard.js";
24
+ import { simulatePipeline, workingDirectoryDriftWarning, } from "./core/dry-run.js";
25
+ import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, findOrphanedMatrixTasks, getMatrixDeletionGuard, isKnownMatrix, matrixCompleteName, planMatrixFamilyDelete, removeMatrixChildren, runMatrix, syncMatrixFamily, } from "./core/matrix.js";
21
26
  import { normalizeWatchPath, validateWatchGlobs } from "./core/watch-paths.js";
22
27
  import { createShutdownGate } from "./core/shutdown.js";
28
+ import { CHILD_RUN_ENV, isChildRunMode } from "./core/run-mode.js";
23
29
  import { SchedulerRpc } from "./rpc.js";
30
+ import { loadPipelineFile, parsePipelineYaml, } from "./core/pipeline-io.js";
31
+ import { planPipelineApply, } from "./core/pipeline-apply.js";
32
+ import { pipelineExportLookupError, tasksToPipelineSpec, } from "./core/pipeline-map.js";
33
+ import { stringify as yamlStringify } from "yaml";
24
34
  import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
25
- import { defaultNotifications, loadSettings, saveSettings } from "./settings.js";
35
+ import { defaultNotifications, loadSettings, saveSettings, } from "./settings.js";
26
36
  import { resolveLocale, setLocale, t } from "./i18n.js";
37
+ import { formatLogRunMarker, runMission } from "./core/mission.js";
27
38
  import { DEFAULT_PERMISSION_POLICY, buildOpencodeConfig, resolvePermissions, } from "./core/permissions.js";
28
39
  import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
29
40
  import { buildAnalytics } from "./core/analytics.js";
41
+ import { buildBudgetReport, evaluateBudgetGate, evaluateTaskTokenBudgetGate, formatBudgetSkipMessage, formatTaskTokenBudgetSkipMessage, startOfUtcWeek, } from "./core/budget.js";
30
42
  import { generateSelfAnalysisReport } from "./core/self-analysis.js";
31
- import { getHistory, listRunningRecords } from "./db/history-repo.js";
43
+ import { getHistoryForAnalytics, getHistoryForBudget, listRunningRecords, recordRun, } from "./db/history-repo.js";
44
+ import { appendStructuredLog } from "./core/structured-log.js";
32
45
  import { getAllMetrics } from "./db/metrics-repo.js";
33
46
  import { discardDlq, listDlq, retryDlq } from "./core/dlq-api.js";
34
47
  import { listRunPanel, pauseRunPanel, resumeRunPanel, } from "./core/run-panel-api.js";
35
- import { findStuckMatrixClones, maybeSendDigest, notifyStuckMatrix, sendDigestNow, sendTestNotification, } from "./notifications.js";
48
+ import { findStuckMatrixClones, maybeSendDigest, notifyBudgetExceeded, notifyStuckMatrix, sendBugReport, sendDigestNow, sendTestNotification, } from "./notifications.js";
49
+ import { FEEDBACK_LIMITS, flushOutbox, redactText, reportFeedback, } from "./core/feedback.js";
36
50
  import { shadowReport, resetShadowDecisions, } from "./core/triage-shadow.js";
37
51
  import { compareTriage } from "./core/triage-compare.js";
38
52
  import { applyLocalAiPatch, summarizeLocalAi } from "./core/local-ai.js";
@@ -41,15 +55,15 @@ import { loadTaskDefinitions, saveTaskDefinition, removeTaskDefinition, buildExp
41
55
  import { FileWatchManager } from "./core/file-watcher.js";
42
56
  import { GitTriggerManager } from "./core/git-trigger.js";
43
57
  import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
44
- import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
58
+ import { startDashboardServer, closeDashboardServer, getDashboardPort, probeDashboardOn, discoverDashboardPort, } from "./server.js";
45
59
  import { DEFAULT_PROFILE, createProfile, deleteProfile, getProfileDir, getProfileName, isProfilePinnedByEnv, listProfiles, sanitizeProfileName, setActiveProfile, } from "./profiles.js";
46
60
  import { closeDb, initDb } from "./db/index.js";
47
61
  import { migrateJsonToDb } from "./db/migrate.js";
48
62
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
49
63
  import { getTask, listMatrixClones, listTasks as listTaskDefinitions, saveTask } from "./db/tasks-repo.js";
50
64
  import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
51
- import { deleteSecret, collectSecretNames, hasSecret, listSecrets, setSecret, } from "./core/secrets.js";
52
- import { readAuditLog, recordAudit, recordTaskToolBlocks, } from "./core/audit.js";
65
+ import { deleteSecret, collectSecretNames, getSecret, hasSecret, listSecrets, setSecret, } from "./core/secrets.js";
66
+ import { auditDateFilterError, readAuditLog, recordAudit, recordTaskToolBlocks, } from "./core/audit.js";
53
67
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
54
68
  const require = createRequire(import.meta.url);
55
69
  const resolvedRecorder = require.resolve("./core/record-history.js");
@@ -91,6 +105,39 @@ const gatePath = (() => {
91
105
  `${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`);
92
106
  return distPath;
93
107
  })();
108
+ /**
109
+ * W-1: путь к помощнику создания одноразового git worktree
110
+ * (dist/core/worktree-run.js). Обёртка вызывает его перед opencode.
111
+ */
112
+ const worktreeHelperPath = (() => {
113
+ const resolved = require.resolve("./core/worktree-run.js");
114
+ if (!resolved.endsWith(".ts"))
115
+ return resolved;
116
+ const distPath = resolved
117
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
118
+ .replace(/\.ts$/, ".js");
119
+ if (existsSync(distPath))
120
+ return distPath;
121
+ console.warn("[agent-steward] Не найден собранный worktree-run.js: " +
122
+ `${distPath}. Изоляция в git worktree не будет работать. Выполните npm run build.`);
123
+ return distPath;
124
+ })();
125
+ /**
126
+ * W-3: путь к CLI-помощнику guard-условий (dist/core/guard-run.js).
127
+ */
128
+ const guardHelperPath = (() => {
129
+ const resolved = require.resolve("./core/guard-run.js");
130
+ if (!resolved.endsWith(".ts"))
131
+ return resolved;
132
+ const distPath = resolved
133
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
134
+ .replace(/\.ts$/, ".js");
135
+ if (existsSync(distPath))
136
+ return distPath;
137
+ console.warn("[agent-steward] Не найден собранный guard-run.js: " +
138
+ `${distPath}. Guard-условия не будут проверяться. Выполните npm run build.`);
139
+ return distPath;
140
+ })();
94
141
  /** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
95
142
  const scheduler = getSchedulerBackend();
96
143
  /** Per-workspace overrides for matrix clones (Sprint 17). */
@@ -131,11 +178,100 @@ export const matrixSchema = z.object({
131
178
  .optional()
132
179
  .describe("Per-workspace overrides keyed by workspace id. Keys must be present in workspaceIds."),
133
180
  });
181
+ /** W-3: guard-условия задачи. */
182
+ export const guardsSchema = z.object({
183
+ command: z
184
+ .string()
185
+ .max(4000)
186
+ .optional()
187
+ .describe("Shell command evaluated before the run. Exit 0 runs the task; any other code skips it."),
188
+ timeoutSeconds: z
189
+ .number()
190
+ .int()
191
+ .min(1)
192
+ .max(3600)
193
+ .optional()
194
+ .describe("Shell guard timeout in seconds (default 60)."),
195
+ semantic: z
196
+ .object({
197
+ filesExist: z.array(z.string()).max(200).optional().describe("Paths that must exist."),
198
+ filesMissing: z.array(z.string()).max(200).optional().describe("Paths that must not exist."),
199
+ branch: z.string().max(200).optional().describe("Glob for the current git branch, e.g. feature/*."),
200
+ changedPaths: z
201
+ .array(z.string())
202
+ .max(200)
203
+ .optional()
204
+ .describe("Globs of changed paths; at least one must match."),
205
+ changedSince: z
206
+ .string()
207
+ .max(100)
208
+ .optional()
209
+ .describe("Git ref to diff against (default HEAD~1)."),
210
+ })
211
+ .optional()
212
+ .describe("Semantic pre-run checks inside the working directory."),
213
+ }).describe("W-3: guard conditions. If a check fails, the run is skipped before opencode starts.");
214
+ /**
215
+ * QA-P2.1: маска glob не может быть пустой или содержать пробелы.
216
+ * Пробел в `** /*.md` молча сужает совпадение до файлов с пробелом в имени.
217
+ */
218
+ const globMaskSchema = z.string().min(1).refine((mask) => !/\s/.test(mask), {
219
+ message: "Glob mask must be non-empty and contain no whitespace.",
220
+ });
221
+ /**
222
+ * QA-P2.1: единая проверка диапазонов для MCP и RPC.
223
+ * Zod-схемы защищают только MCP-путь; RPC (create_task/update_task) принимает
224
+ * сырой JSON и вызывает эту функцию явно, до normalizePriority(), который
225
+ * молча обрезает priority до 0..10.
226
+ * Возвращает текст ошибки или null.
227
+ */
228
+ export function validateTaskInputRanges(input) {
229
+ if (input.prompt !== undefined && !input.prompt.trim()) {
230
+ return "prompt must be a non-empty string.";
231
+ }
232
+ if (input.timeoutSeconds !== undefined &&
233
+ (!Number.isInteger(input.timeoutSeconds) || input.timeoutSeconds <= 0)) {
234
+ return "timeoutSeconds must be a positive integer.";
235
+ }
236
+ if (input.priority !== undefined &&
237
+ (!Number.isInteger(input.priority) || input.priority < 0 || input.priority > 10)) {
238
+ return "priority must be an integer between 0 and 10.";
239
+ }
240
+ if (input.retryCount !== undefined &&
241
+ (!Number.isInteger(input.retryCount) || input.retryCount < 0)) {
242
+ return "retryCount must be a non-negative integer.";
243
+ }
244
+ if (input.retryDelay !== undefined &&
245
+ (!Number.isInteger(input.retryDelay) || input.retryDelay < 0)) {
246
+ return "retryDelay must be a non-negative integer.";
247
+ }
248
+ const globFields = [
249
+ ["watchGlobs", input.watchGlobs],
250
+ ["watchIgnore", input.watchIgnore],
251
+ ["gitPaths", input.gitPaths],
252
+ ["gitIgnore", input.gitIgnore],
253
+ ];
254
+ for (const [field, masks] of globFields) {
255
+ if (!Array.isArray(masks))
256
+ continue;
257
+ for (const mask of masks) {
258
+ if (typeof mask !== "string" || !mask.trim() || /\s/.test(mask)) {
259
+ return `${field} masks must be non-empty strings without whitespace.`;
260
+ }
261
+ }
262
+ }
263
+ if (input.triggerType === "file" &&
264
+ input.watchPath !== undefined &&
265
+ !input.watchPath.trim()) {
266
+ return "watchPath must be a non-empty path when triggerType is file.";
267
+ }
268
+ return null;
269
+ }
134
270
  /** Zod-схема аргументов schedule_task */
135
271
  export const scheduleTaskSchema = z.object({
136
272
  name: z
137
273
  .string()
138
- .describe("Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen."),
274
+ .describe("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'."),
139
275
  schedule: z
140
276
  .string()
141
277
  .optional()
@@ -175,9 +311,13 @@ export const scheduleTaskSchema = z.object({
175
311
  .describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
176
312
  prompt: z
177
313
  .string()
314
+ .min(1, "prompt must be a non-empty string.")
315
+ .refine((value) => value.trim().length > 0, "prompt must be a non-empty string.")
178
316
  .describe("Prompt passed to the agent on every run."),
179
317
  timeoutSeconds: z
180
318
  .number()
319
+ .int()
320
+ .positive()
181
321
  .optional()
182
322
  .describe("Run timeout in seconds (default 3600)."),
183
323
  model: z
@@ -186,6 +326,9 @@ export const scheduleTaskSchema = z.object({
186
326
  .describe("LLM model in OpenCode format, e.g. anthropic/claude-3-5-sonnet. Defaults to the OpenCode default model."),
187
327
  priority: z
188
328
  .number()
329
+ .int()
330
+ .min(0)
331
+ .max(10)
189
332
  .optional()
190
333
  .describe("Task priority 0..10 (10 is the highest). Default 5 (normal)."),
191
334
  beforeScript: z
@@ -206,10 +349,14 @@ export const scheduleTaskSchema = z.object({
206
349
  .describe("DAG dependencies: tasks that must finish successfully before this task starts."),
207
350
  retryCount: z
208
351
  .number()
352
+ .int()
353
+ .nonnegative()
209
354
  .optional()
210
355
  .describe("How many times to retry a failed run (default 0)."),
211
356
  retryDelay: z
212
357
  .number()
358
+ .int()
359
+ .nonnegative()
213
360
  .optional()
214
361
  .describe("Delay between retries in seconds (default 60)."),
215
362
  nextTaskOnSuccess: z
@@ -227,21 +374,28 @@ export const scheduleTaskSchema = z.object({
227
374
  mcpEvent: z
228
375
  .object({
229
376
  server: z.string(),
230
- event: z.string(),
377
+ event: z
378
+ .string()
379
+ .optional()
380
+ .describe("event or eventName (alias); eventName is accepted for emit_event compatibility"),
381
+ eventName: z
382
+ .string()
383
+ .optional()
384
+ .describe("event or eventName (alias); eventName is accepted for emit_event compatibility"),
231
385
  filter: z.string().optional(),
232
386
  })
233
387
  .optional()
234
- .describe("MCP event trigger: server, event name and an optional filter (key=value or regex)."),
388
+ .describe("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."),
235
389
  watchPath: z
236
390
  .string()
237
391
  .optional()
238
392
  .describe("File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."),
239
393
  watchGlobs: z
240
- .array(z.string())
394
+ .array(globMaskSchema)
241
395
  .optional()
242
396
  .describe("Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath."),
243
397
  watchIgnore: z
244
- .array(z.string())
398
+ .array(globMaskSchema)
245
399
  .optional()
246
400
  .describe("Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include."),
247
401
  gitBranch: z
@@ -249,11 +403,11 @@ export const scheduleTaskSchema = z.object({
249
403
  .optional()
250
404
  .describe("Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch."),
251
405
  gitPaths: z
252
- .array(z.string())
406
+ .array(globMaskSchema)
253
407
  .optional()
254
408
  .describe("Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only)."),
255
409
  gitIgnore: z
256
- .array(z.string())
410
+ .array(globMaskSchema)
257
411
  .optional()
258
412
  .describe("Only for triggerType=git: glob masks of changed files to ignore."),
259
413
  gitPollSeconds: z
@@ -294,6 +448,20 @@ export const scheduleTaskSchema = z.object({
294
448
  .boolean()
295
449
  .optional()
296
450
  .describe("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."),
451
+ worktree: z
452
+ .boolean()
453
+ .optional()
454
+ .describe("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."),
455
+ guards: guardsSchema
456
+ .optional()
457
+ .describe("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."),
458
+ tokenBudget: z
459
+ .number()
460
+ .int()
461
+ .min(0)
462
+ .max(10000000)
463
+ .optional()
464
+ .describe("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."),
297
465
  matrix: matrixSchema
298
466
  .optional()
299
467
  .describe("Matrix fan-out: the task becomes a template that is expanded into clones, one per workspace. The parent never runs itself. Cannot be combined with workspaceId."),
@@ -329,13 +497,31 @@ export const scheduleTaskSchema = z.object({
329
497
  message: t("tool.error.onceFields"),
330
498
  });
331
499
  }
500
+ // QA-P2.1: явная пустая строка watchPath при file-триггере бессмысленна.
501
+ if (trigger === "file" && value.watchPath !== undefined && !value.watchPath.trim()) {
502
+ ctx.addIssue({
503
+ code: z.ZodIssueCode.custom,
504
+ path: ["watchPath"],
505
+ message: "watchPath must be a non-empty path when triggerType is file.",
506
+ });
507
+ }
332
508
  });
333
509
  const listTasksSchema = z.object({});
510
+ /** PL-43: структурированный ответ list_tasks для Code Mode (V2). */
511
+ const listTasksOutputSchema = z.object({
512
+ success: z.boolean(),
513
+ message: z.string(),
514
+ tasks: z.array(z.unknown()),
515
+ osAvailable: z.boolean(),
516
+ osError: z.string().optional(),
517
+ });
334
518
  const deleteTaskSchema = z.object({
335
519
  name: z.string().describe("Task name to delete."),
336
520
  });
337
521
  const runTaskNowSchema = z.object({
338
- name: z.string().describe("Task name to run immediately."),
522
+ name: z
523
+ .string()
524
+ .describe("Task name to run immediately. While the plugin unloads the tool returns a structured PLUGIN_SHUTTING_DOWN error (message + retry hint)."),
339
525
  });
340
526
  export const updateTaskSchema = z.object({
341
527
  name: z.string().describe("Name of the task to update."),
@@ -389,11 +575,11 @@ export const updateTaskSchema = z.object({
389
575
  .optional()
390
576
  .describe("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."),
391
577
  watchGlobs: z
392
- .array(z.string())
578
+ .array(globMaskSchema)
393
579
  .optional()
394
580
  .describe("New glob masks for a file trigger. Empty array clears them."),
395
581
  watchIgnore: z
396
- .array(z.string())
582
+ .array(globMaskSchema)
397
583
  .optional()
398
584
  .describe("New ignore masks for a file trigger. Empty array clears them."),
399
585
  gitBranch: z
@@ -401,11 +587,11 @@ export const updateTaskSchema = z.object({
401
587
  .optional()
402
588
  .describe("New git branch filter (glob, comma-separated). Empty string clears it."),
403
589
  gitPaths: z
404
- .array(z.string())
590
+ .array(globMaskSchema)
405
591
  .optional()
406
592
  .describe("New changed-file masks for a git trigger. Empty array clears them."),
407
593
  gitIgnore: z
408
- .array(z.string())
594
+ .array(globMaskSchema)
409
595
  .optional()
410
596
  .describe("New ignored changed-file masks for a git trigger. Empty array clears them."),
411
597
  gitPollSeconds: z
@@ -416,14 +602,26 @@ export const updateTaskSchema = z.object({
416
602
  .describe("New git polling interval in seconds."),
417
603
  prompt: z
418
604
  .string()
605
+ .refine((value) => value.trim().length > 0, "prompt must be a non-empty string.")
419
606
  .optional()
420
607
  .describe("New prompt. Keeps the current value when omitted."),
421
- timeoutSeconds: z.number().optional().describe("New run timeout in seconds."),
608
+ timeoutSeconds: z
609
+ .number()
610
+ .int()
611
+ .positive()
612
+ .optional()
613
+ .describe("New run timeout in seconds."),
422
614
  model: z
423
615
  .string()
424
616
  .optional()
425
617
  .describe("New model in OpenCode format. Empty string clears it (default model)."),
426
- priority: z.number().optional().describe("New priority 0..10."),
618
+ priority: z
619
+ .number()
620
+ .int()
621
+ .min(0)
622
+ .max(10)
623
+ .optional()
624
+ .describe("New priority 0..10."),
427
625
  beforeScript: z
428
626
  .string()
429
627
  .optional()
@@ -440,8 +638,8 @@ export const updateTaskSchema = z.object({
440
638
  .array(z.string())
441
639
  .optional()
442
640
  .describe("New DAG dependencies. Empty array clears them."),
443
- retryCount: z.number().optional().describe("New retry count."),
444
- retryDelay: z.number().optional().describe("New retry delay in seconds."),
641
+ retryCount: z.number().int().nonnegative().optional().describe("New retry count."),
642
+ retryDelay: z.number().int().nonnegative().optional().describe("New retry delay in seconds."),
445
643
  nextTaskOnSuccess: z
446
644
  .string()
447
645
  .optional()
@@ -457,11 +655,18 @@ export const updateTaskSchema = z.object({
457
655
  mcpEvent: z
458
656
  .object({
459
657
  server: z.string(),
460
- event: z.string(),
658
+ event: z
659
+ .string()
660
+ .optional()
661
+ .describe("event or eventName (alias); eventName is accepted for emit_event compatibility"),
662
+ eventName: z
663
+ .string()
664
+ .optional()
665
+ .describe("event or eventName (alias); eventName is accepted for emit_event compatibility"),
461
666
  filter: z.string().optional(),
462
667
  })
463
668
  .optional()
464
- .describe("New MCP event trigger."),
669
+ .describe("New MCP event trigger: event (or its alias eventName); at least one of them is required for triggerType=mcp-event."),
465
670
  watchPath: z
466
671
  .string()
467
672
  .optional()
@@ -486,6 +691,20 @@ export const updateTaskSchema = z.object({
486
691
  .boolean()
487
692
  .optional()
488
693
  .describe("Transitional flag (release 1.6): re-enable shell under the hybrid policy for this task."),
694
+ worktree: z
695
+ .boolean()
696
+ .optional()
697
+ .describe("W-1: run each tick in a one-off git worktree created from HEAD of workingDirectory. Default false."),
698
+ guards: guardsSchema
699
+ .optional()
700
+ .describe("W-3: pre-run guard conditions; a failed check skips the run."),
701
+ tokenBudget: z
702
+ .number()
703
+ .int()
704
+ .min(0)
705
+ .max(10000000)
706
+ .optional()
707
+ .describe("Economics v2 (E-2): per-run token budget. 0 or omitted = no task limit (fail-open). Pass 0 to clear a previous limit."),
489
708
  matrix: matrixSchema
490
709
  .nullable()
491
710
  .optional()
@@ -507,6 +726,16 @@ export const updateTaskSchema = z.object({
507
726
  message: t("tool.error.onceMatrixUpdate"),
508
727
  });
509
728
  }
729
+ // QA-P2.1: пустой watchPath допустим только для очистки не-file триггера.
730
+ if (value.triggerType === "file" &&
731
+ value.watchPath !== undefined &&
732
+ !value.watchPath.trim()) {
733
+ ctx.addIssue({
734
+ code: z.ZodIssueCode.custom,
735
+ path: ["watchPath"],
736
+ message: "watchPath must be a non-empty path when triggerType is file.",
737
+ });
738
+ }
510
739
  });
511
740
  const pauseTaskSchema = z.object({
512
741
  name: z.string().describe("Task name to pause."),
@@ -532,8 +761,9 @@ const getHistorySchema = z.object({
532
761
  .optional()
533
762
  .describe("Maximum number of records to return (default 20, max 200)."),
534
763
  });
535
- const getTaskLogsSchema = z.object({
536
- name: z.string().describe("Task name to read logs for."),
764
+ export const getTaskLogsSchema = z.object({
765
+ name: z.string().optional().describe("Task name to read logs for (alias: taskName)."),
766
+ taskName: z.string().optional().describe("Alias for name; both spellings are accepted."),
537
767
  lines: z
538
768
  .number()
539
769
  .optional()
@@ -545,6 +775,58 @@ const dryRunSchema = z.object({
545
775
  .optional()
546
776
  .describe("Task name to simulate. When omitted, every task is simulated (pipeline dry run, nothing is executed)."),
547
777
  });
778
+ /** pipeline_validate — проверить опencode.pipeline.yaml (путь или исходник). */
779
+ export const pipelineValidateSchema = z.object({
780
+ path: z
781
+ .string()
782
+ .optional()
783
+ .describe("Путь к файлу opencode.pipeline.yaml (относительный резолвится против cwd) или source."),
784
+ source: z.string().optional().describe("Исходное содержимое YAML (альтернатива path)."),
785
+ workingDirectory: z
786
+ .string()
787
+ .optional()
788
+ .describe("База для относительного path (по умолчанию cwd процесса, затем подсказки окружения)."),
789
+ dryRun: z
790
+ .boolean()
791
+ .optional()
792
+ .default(true)
793
+ .describe("Если true — только валидация без применения (по умолчанию true)."),
794
+ });
795
+ /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
796
+ export const pipelineApplySchema = z.object({
797
+ path: z
798
+ .string()
799
+ .optional()
800
+ .describe("Путь к файлу opencode.pipeline.yaml (относительный резолвится против cwd) или source."),
801
+ source: z.string().optional().describe("Исходное содержимое YAML (альтернатива path)."),
802
+ workingDirectory: z
803
+ .string()
804
+ .optional()
805
+ .describe("База для относительного path (по умолчанию cwd процесса, затем подсказки окружения)."),
806
+ dryRun: z
807
+ .boolean()
808
+ .optional()
809
+ .default(false)
810
+ .describe("Если true — прогон diff'а без применения изменений (по умолчанию false)."),
811
+ });
812
+ /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
813
+ export const pipelineExportSchema = z
814
+ .object({
815
+ pipeline: z.string().optional().describe("Имя конвейера (pipelineName)."),
816
+ pipelineName: z.string().optional().describe("Алиас параметра pipeline — имя конвейера."),
817
+ })
818
+ .superRefine((value, ctx) => {
819
+ // QA-P3.2: разные имена в двух полях — ошибка, а не молчаливый приоритет pipeline.
820
+ const explicit = value.pipeline?.trim();
821
+ const alias = value.pipelineName?.trim();
822
+ if (explicit && alias && explicit.toLowerCase() !== alias.toLowerCase()) {
823
+ ctx.addIssue({
824
+ code: z.ZodIssueCode.custom,
825
+ path: ["pipelineName"],
826
+ message: "Конфликт параметров: pipeline и pipelineName задают разные имена конвейера.",
827
+ });
828
+ }
829
+ });
548
830
  const manageWorkspacesSchema = z.object({
549
831
  action: z
550
832
  .enum(["list", "add", "update", "delete"])
@@ -640,8 +922,8 @@ export const selfAnalysisSchema = z.object({
640
922
  /** manage_settings — глобальные настройки планировщика. */
641
923
  export const manageSettingsSchema = z.object({
642
924
  action: z
643
- .enum(["get", "update"])
644
- .describe("get — current settings; update — merge the provided fields and save."),
925
+ .enum(["get", "list", "update"])
926
+ .describe("get - current settings; list - same as get (agent-friendly alias); update - merge the provided fields and save."),
645
927
  maxConcurrent: z
646
928
  .number()
647
929
  .int()
@@ -652,7 +934,7 @@ export const manageSettingsSchema = z.object({
652
934
  locale: z
653
935
  .enum(["auto", "ru", "en", "zh"])
654
936
  .optional()
655
- .describe("Interface language: auto (follow OpenCode), ru (default), en or zh. Applies without restart."),
937
+ .describe("Interface language: auto (default, follows OpenCode), ru, en or zh. Applies without restart."),
656
938
  winterMode: z
657
939
  .boolean()
658
940
  .optional()
@@ -682,6 +964,24 @@ export const manageSettingsSchema = z.object({
682
964
  })
683
965
  .optional()
684
966
  .describe("Tool permission policy for background tasks: hybrid (default; shell/question denied), secure (read-only), legacy (allow everything, 1.5.x behaviour)."),
967
+ budgets: z
968
+ .object({
969
+ enabled: z.boolean().optional(),
970
+ dailyUsd: z.number().min(0).max(1000000).optional(),
971
+ weeklyUsd: z.number().min(0).max(1000000).optional(),
972
+ })
973
+ .optional()
974
+ .describe("Daily/weekly USD budgets (0 = no limit). Accounting is exposed by get_analytics as report.budgets."),
975
+ feedback: z
976
+ .object({
977
+ enabled: z.boolean().optional(),
978
+ endpoint: z.string().max(2048).optional(),
979
+ includeLogs: z.boolean().optional(),
980
+ contactEmail: z.string().max(254).optional(),
981
+ maxPerHour: z.number().int().min(1).max(100).optional(),
982
+ })
983
+ .optional()
984
+ .describe("Author feedback (bug reports → GitHub Issues). disabled by default; endpoint must be https (http only for localhost)."),
685
985
  });
686
986
  /** manage_local_ai — настройки локального ассистента и триажа (Спринт 30.7). */
687
987
  export const manageLocalAiSchema = z.object({
@@ -736,8 +1036,8 @@ export const manageLocalAiSchema = z.object({
736
1036
  export const manageTemplatesSchema = z.object({
737
1037
  action: z
738
1038
  .enum(["list", "save", "delete"])
739
- .describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
740
- id: z.string().optional().describe("Template id for update/delete."),
1039
+ .describe("list — all templates; save — create or update (id omitted = create); delete — remove by id or name."),
1040
+ id: z.string().optional().describe("Template id for update; for delete an id or a template name is accepted."),
741
1041
  name: z.string().optional().describe("Template name."),
742
1042
  prompt: z.string().optional().describe("Prompt text stored in the template."),
743
1043
  schedule: z.string().optional().describe("Cron expression."),
@@ -756,10 +1056,18 @@ export const manageTemplatesSchema = z.object({
756
1056
  mcpEvent: z
757
1057
  .object({
758
1058
  server: z.string(),
759
- event: z.string(),
1059
+ event: z
1060
+ .string()
1061
+ .optional()
1062
+ .describe("event or eventName (alias); eventName is accepted for emit_event compatibility"),
1063
+ eventName: z
1064
+ .string()
1065
+ .optional()
1066
+ .describe("event or eventName (alias); eventName is accepted for emit_event compatibility"),
760
1067
  filter: z.string().optional(),
761
1068
  })
762
- .optional(),
1069
+ .optional()
1070
+ .describe("MCP event trigger: event (or its alias eventName); at least one of them is required for triggerType=mcp-event."),
763
1071
  watchPath: z.string().optional(),
764
1072
  workingDirectory: z.string().optional(),
765
1073
  allowedTools: z.array(z.string()).optional(),
@@ -788,6 +1096,21 @@ export const sendNotificationSchema = z.object({
788
1096
  .optional()
789
1097
  .describe("For action=test: which channel to check (default all enabled)."),
790
1098
  });
1099
+ /** report_bug — отчёт о баге; по умолчанию уходит автору через приёмник F-2 (Деталь 3.8). */
1100
+ export const reportBugSchema = z.object({
1101
+ description: z.string().min(1).max(FEEDBACK_LIMITS.description).describe("Описание бага от пользователя (обязательно)."),
1102
+ taskName: z.string().max(FEEDBACK_LIMITS.taskName).optional().describe("Имя задачи, к которой относится баг (для прикрепления логов)."),
1103
+ /** Приватность: по умолчанию логи НЕ прикладываются (F-1.3). */
1104
+ includeLogs: z.boolean().optional().default(false).describe("Включить логи задачи (по умолчанию false)."),
1105
+ includeAnalytics: z.boolean().optional().default(true).describe("Включить метрики и аналитику за последние 7 дней."),
1106
+ /** Канал локальных уведомлений (для destination local/both). */
1107
+ channel: z.enum(["all", "webhook", "telegram", "native"]).optional().describe("Канал локального уведомления."),
1108
+ /** Направление: автор (по умолчанию), локальные каналы или оба (F-1.5). */
1109
+ destination: z.enum(["author", "local", "both"]).optional().default("author").describe("Куда отправить отчёт."),
1110
+ contactEmail: z.string().max(FEEDBACK_LIMITS.contactEmail).optional().describe("Обратный адрес (опционально)."),
1111
+ /** Показать точный payload без отправки (F-3.1). */
1112
+ dryRun: z.boolean().optional().default(false).describe("Предпросмотр без отправки."),
1113
+ });
791
1114
  /** get_dashboard_info — сведения о панели управления. */
792
1115
  export const getDashboardInfoSchema = z.object({});
793
1116
  /** cleanup_history — удаление старой истории. */
@@ -799,6 +1122,10 @@ export const cleanupHistorySchema = z.object({
799
1122
  export const emitEventSchema = z.object({
800
1123
  eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
801
1124
  payload: z.any().optional().describe("Event payload passed to trigger filters."),
1125
+ server: z
1126
+ .string()
1127
+ .optional()
1128
+ .describe("Optional MCP source/server name (e.g. 'github'). When set, only tasks with the same mcpEvent.server are triggered."),
802
1129
  });
803
1130
  /** manage_secrets — зашифрованное хранилище секретов (Спринт 26). */
804
1131
  export const manageSecretsSchema = z.object({
@@ -831,7 +1158,6 @@ export const getAuditLogSchema = z.object({
831
1158
  let projectDirectory;
832
1159
  /**
833
1160
  * Обёртка execute-функции: ловит ошибки и возвращает Tool.Result с content.
834
- * Использует Tool.Context из @opencode/schema/tool.
835
1161
  */
836
1162
  function wrapExecute(fn) {
837
1163
  return async (input, context) => {
@@ -839,11 +1165,24 @@ function wrapExecute(fn) {
839
1165
  return await fn(input, context);
840
1166
  }
841
1167
  catch (err) {
1168
+ const shutdown = err instanceof PluginShutdownError
1169
+ ? {
1170
+ code: err.code,
1171
+ hint: err.hint,
1172
+ retryable: err.retryable,
1173
+ shutdownState: err.state,
1174
+ }
1175
+ : {};
1176
+ // PL-43: тот же payload отдаём и структурированным output, и строкой
1177
+ // content — V1-адаптер по-прежнему читает content.
1178
+ const output = {
1179
+ success: false,
1180
+ error: err instanceof Error ? err.message : String(err),
1181
+ ...shutdown,
1182
+ };
842
1183
  return {
843
- content: JSON.stringify({
844
- success: false,
845
- error: err instanceof Error ? err.message : String(err),
846
- }),
1184
+ output,
1185
+ content: JSON.stringify(output),
847
1186
  };
848
1187
  }
849
1188
  };
@@ -919,7 +1258,11 @@ function computeTaskNextRun(def, options = {}) {
919
1258
  }
920
1259
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
921
1260
  const scheduleTaskExecute = wrapExecute(async (args) => {
922
- const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, runWhenLoggedOff, legacyShell, } = args;
1261
+ // QA-P2.1: RPC-путь не проходит Zod — проверяем диапазоны явно.
1262
+ const rangeError = validateTaskInputRanges(args);
1263
+ if (rangeError)
1264
+ throw new Error(rangeError);
1265
+ const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, runWhenLoggedOff, legacyShell, worktree, guards, tokenBudget, } = args;
923
1266
  let effectiveRunAt;
924
1267
  if ((triggerType ?? "cron") === "once") {
925
1268
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
@@ -946,7 +1289,7 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
946
1289
  gitPollSeconds,
947
1290
  },
948
1291
  // Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
949
- runWhenLoggedOff === true, undefined, legacyShell === true);
1292
+ runWhenLoggedOff === true, undefined, legacyShell === true, worktree === true, guards, tokenBudget);
950
1293
  }
951
1294
  catch (err) {
952
1295
  return {
@@ -1010,6 +1353,8 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
1010
1353
  workspaceId: workspace?.id ?? null,
1011
1354
  workspaceName: workspace?.name ?? null,
1012
1355
  matrix: matrix ?? null,
1356
+ worktree: worktree === true,
1357
+ guards: guards ?? null,
1013
1358
  },
1014
1359
  }),
1015
1360
  };
@@ -1018,29 +1363,27 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
1018
1363
  const listTasksExecute = wrapExecute(async () => {
1019
1364
  const { tasks, osAvailable, osError } = await collectTasksView();
1020
1365
  if (tasks.length === 0) {
1021
- return {
1022
- content: JSON.stringify({
1023
- success: true,
1024
- message: osAvailable
1025
- ? t("tool.task.listEmpty")
1026
- : t("tool.task.listOsUnavailable"),
1027
- tasks: [],
1028
- osAvailable,
1029
- ...(osError ? { osError } : {}),
1030
- }),
1031
- };
1032
- }
1033
- return {
1034
- content: JSON.stringify({
1366
+ const output = {
1035
1367
  success: true,
1036
1368
  message: osAvailable
1037
- ? t("tool.task.found", { count: tasks.length })
1038
- : t("tool.task.foundOsUnavailable", { count: tasks.length }),
1039
- tasks,
1369
+ ? t("tool.task.listEmpty")
1370
+ : t("tool.task.listOsUnavailable"),
1371
+ tasks: [],
1040
1372
  osAvailable,
1041
1373
  ...(osError ? { osError } : {}),
1042
- }),
1374
+ };
1375
+ return { output, content: JSON.stringify(output) };
1376
+ }
1377
+ const output = {
1378
+ success: true,
1379
+ message: osAvailable
1380
+ ? t("tool.task.found", { count: tasks.length })
1381
+ : t("tool.task.foundOsUnavailable", { count: tasks.length }),
1382
+ tasks,
1383
+ osAvailable,
1384
+ ...(osError ? { osError } : {}),
1043
1385
  };
1386
+ return { output, content: JSON.stringify(output) };
1044
1387
  });
1045
1388
  /**
1046
1389
  * Отмена выполняющейся матрицы: незавершённые клоны помечаются отменой
@@ -1072,7 +1415,9 @@ async function cancelMatrixRun(name) {
1072
1415
  }
1073
1416
  // Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
1074
1417
  try {
1075
- await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell);
1418
+ await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell, clone.worktree, clone.guards,
1419
+ // QA-P0.1 (E-2.1): клон матрицы наследует tokenBudget родителя.
1420
+ clone.tokenBudget);
1076
1421
  }
1077
1422
  catch (err) {
1078
1423
  warnings.push(t("tool.matrix.recreateFailed", {
@@ -1293,7 +1638,7 @@ const deleteTaskExecute = wrapExecute(async (args) => {
1293
1638
  return {
1294
1639
  content: JSON.stringify({
1295
1640
  success: false,
1296
- error: err.message || String(err),
1641
+ error: err instanceof Error ? err.message : String(err),
1297
1642
  }),
1298
1643
  };
1299
1644
  }
@@ -1301,6 +1646,11 @@ const deleteTaskExecute = wrapExecute(async (args) => {
1301
1646
  /** run_task_now — немедленный запуск задачи */
1302
1647
  const runTaskNowExecute = wrapExecute(async (args) => {
1303
1648
  const { name } = args;
1649
+ // PL-8.1: тот же дрейф HEAD, что и в dry_run, показываем при ручном старте.
1650
+ const definition = getTask(name);
1651
+ const warning = definition?.workingDirectory && definition.createdAt
1652
+ ? workingDirectoryDriftWarning(definition, definition.workingDirectory)
1653
+ : null;
1304
1654
  let alreadyRunning = false;
1305
1655
  try {
1306
1656
  const result = await runTaskEntry(name);
@@ -1310,7 +1660,7 @@ const runTaskNowExecute = wrapExecute(async (args) => {
1310
1660
  return {
1311
1661
  content: JSON.stringify({
1312
1662
  success: false,
1313
- error: err.message || String(err),
1663
+ error: err instanceof Error ? err.message : String(err),
1314
1664
  }),
1315
1665
  };
1316
1666
  }
@@ -1320,6 +1670,7 @@ const runTaskNowExecute = wrapExecute(async (args) => {
1320
1670
  message: alreadyRunning
1321
1671
  ? t("tool.task.alreadyRunning", { name })
1322
1672
  : t("tool.task.started", { name }),
1673
+ ...(warning ? { warning } : {}),
1323
1674
  }),
1324
1675
  };
1325
1676
  });
@@ -1368,6 +1719,11 @@ async function updateTaskFromInput(input) {
1368
1719
  if (!name) {
1369
1720
  return { success: false, message: t("tool.error.taskNameMissing") };
1370
1721
  }
1722
+ // QA-P2.1: RPC не проходит Zod — проверяем диапазоны явно.
1723
+ const rangeError = validateTaskInputRanges(input);
1724
+ if (rangeError) {
1725
+ return { success: false, message: rangeError };
1726
+ }
1371
1727
  const previous = getTask(name);
1372
1728
  if (!previous) {
1373
1729
  return { success: false, message: t("tool.error.taskNotFound", { name }) };
@@ -1499,7 +1855,9 @@ async function updateTaskFromInput(input) {
1499
1855
  await schedulerCreateTask(name, schedule ?? "", prompt, input.timeoutSeconds ?? previous.timeoutSeconds, clearableString(input.workingDirectory, previous.workingDirectory), input.retryCount ?? previous.retryCount, input.retryDelay ?? previous.retryDelay, clearableString(input.qualityGate, previous.qualityGate), clearableString(input.nextTaskOnSuccess, previous.nextTaskOnSuccess), clearableString(input.nextTaskOnError, previous.nextTaskOnError), triggerType, clearableString(input.watchPath, previous.watchPath), clearableList(input.dependsOn, previous.dependsOn), nextModel, input.priority ?? previous.priority, clearableString(input.beforeScript, previous.beforeScript), clearableString(input.afterScript, previous.afterScript), input.mcpEvent ?? previous.mcpEvent, clearableString(input.workspaceId, previous.workspaceId), clearableList(input.allowedTools, previous.allowedTools), clearableList(input.deniedTools, previous.deniedTools), matrixNext, undefined,
1500
1856
  // Если задача была матрицей — синхронизируем клонов, а не
1501
1857
  // пересоздаём их с нуля (Спринт 17).
1502
- matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras, input.runWhenLoggedOff ?? previous.runWhenLoggedOff, wasPaused, input.legacyShell ?? previous.legacyShell);
1858
+ matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras, input.runWhenLoggedOff ?? previous.runWhenLoggedOff, wasPaused, input.legacyShell ?? previous.legacyShell, input.worktree ?? previous.worktree, input.guards ?? previous.guards,
1859
+ // QA-P0.1 (E-2.1): budget переживает пересоздание задачи. 0 очищает лимит.
1860
+ input.tokenBudget ?? previous.tokenBudget);
1503
1861
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
1504
1862
  if (matrixWas && !matrixNext) {
1505
1863
  await removeMatrixChildrenFromScheduler(name);
@@ -1612,7 +1970,10 @@ async function pauseOrResumeTask(name, paused, until) {
1612
1970
  message: t("tool.error.taskNotFound", { name: trimmed }),
1613
1971
  affected: [],
1614
1972
  warnings: [],
1615
- paused,
1973
+ // QA-P3.8: в ошибке `paused` должен отражать реальное состояние,
1974
+ // а не запрошенное действие (иначе resume про несуществующей задаче
1975
+ // сообщает paused:false, а pause — paused:true).
1976
+ paused: false,
1616
1977
  nextRun: null,
1617
1978
  pausedUntil: null,
1618
1979
  };
@@ -1627,7 +1988,7 @@ async function pauseOrResumeTask(name, paused, until) {
1627
1988
  message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
1628
1989
  affected: [],
1629
1990
  warnings: [],
1630
- paused,
1991
+ paused: definition.paused ?? false,
1631
1992
  nextRun: null,
1632
1993
  pausedUntil: definition.pausedUntil ?? null,
1633
1994
  };
@@ -1638,7 +1999,7 @@ async function pauseOrResumeTask(name, paused, until) {
1638
1999
  message: t("tool.error.pauseDatePast", { name: trimmed }),
1639
2000
  affected: [],
1640
2001
  warnings: [],
1641
- paused,
2002
+ paused: definition.paused ?? false,
1642
2003
  nextRun: null,
1643
2004
  pausedUntil: definition.pausedUntil ?? null,
1644
2005
  };
@@ -1654,7 +2015,7 @@ async function pauseOrResumeTask(name, paused, until) {
1654
2015
  message: t("tool.error.matrixNoClones", { name: trimmed }),
1655
2016
  affected: [],
1656
2017
  warnings: [],
1657
- paused,
2018
+ paused: definition.paused ?? false,
1658
2019
  nextRun: null,
1659
2020
  pausedUntil: definition.pausedUntil ?? null,
1660
2021
  };
@@ -1829,6 +2190,9 @@ async function checkStuckMatrices() {
1829
2190
  /** get_history — история запусков с фильтрами по задаче и статусу. */
1830
2191
  const getHistoryExecute = wrapExecute(async (args) => {
1831
2192
  const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
2193
+ // PL-46: зависшие записи (schtasks /End) должны закрываться не только при
2194
+ // setup, но и при наблюдении истории — иначе остаются running навсегда.
2195
+ recoverInterruptedRuns();
1832
2196
  const records = await loadHistory(args.taskName, limit, args.status);
1833
2197
  return {
1834
2198
  content: JSON.stringify({
@@ -1840,7 +2204,14 @@ const getHistoryExecute = wrapExecute(async (args) => {
1840
2204
  });
1841
2205
  /** get_task_logs — последние строки лога задачи. */
1842
2206
  const getTaskLogsExecute = wrapExecute(async (args) => {
1843
- const result = await getTaskLogs(args.name, args.lines ?? 200);
2207
+ // PL-19: MCP-клиенты передают и name, и taskName — принимаем оба написания.
2208
+ const taskName = args.name?.trim() || args.taskName?.trim();
2209
+ if (!taskName) {
2210
+ return {
2211
+ content: JSON.stringify({ success: false, logs: "", error: "Укажите name или taskName задачи" }),
2212
+ };
2213
+ }
2214
+ const result = await getTaskLogs(taskName, args.lines ?? 200);
1844
2215
  if (result.error) {
1845
2216
  return {
1846
2217
  content: JSON.stringify({ success: false, logs: "", error: result.error }),
@@ -1886,6 +2257,184 @@ const dryRunExecute = wrapExecute(async (args) => {
1886
2257
  }),
1887
2258
  };
1888
2259
  });
2260
+ /** pipeline_validate — проверить opencode.pipeline.yaml (путь или исходник). */
2261
+ const pipelineValidateExecute = wrapExecute(async (args) => {
2262
+ if (args.path === undefined && args.source === undefined) {
2263
+ return {
2264
+ content: JSON.stringify({
2265
+ success: false,
2266
+ pipeline: null,
2267
+ errors: ["Укажите path к файлу или source с содержимым YAML"],
2268
+ warnings: [],
2269
+ }),
2270
+ };
2271
+ }
2272
+ const parsed = args.source !== undefined
2273
+ ? validatePipelineSpecFromSource(args.source)
2274
+ : await loadPipelineFile(args.path, args.workingDirectory);
2275
+ if (!parsed.ok) {
2276
+ return {
2277
+ content: JSON.stringify({
2278
+ success: false,
2279
+ pipeline: null,
2280
+ errors: parsed.errors,
2281
+ warnings: parsed.warnings,
2282
+ }),
2283
+ };
2284
+ }
2285
+ const spec = parsed.spec;
2286
+ return {
2287
+ content: JSON.stringify({
2288
+ success: true,
2289
+ pipeline: spec.name,
2290
+ steps: spec.steps.length,
2291
+ errors: [],
2292
+ warnings: parsed.warnings,
2293
+ }),
2294
+ };
2295
+ });
2296
+ function validatePipelineSpecFromSource(source) {
2297
+ const parsed = parsePipelineYaml(source);
2298
+ return parsed;
2299
+ }
2300
+ /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
2301
+ const pipelineApplyExecute = wrapExecute(async (args) => {
2302
+ const dryRun = args.dryRun !== false;
2303
+ if (args.path === undefined && args.source === undefined) {
2304
+ return {
2305
+ content: JSON.stringify({
2306
+ success: false,
2307
+ pipeline: null,
2308
+ errors: ["Укажите path к файлу или source с содержимым YAML"],
2309
+ warnings: [],
2310
+ }),
2311
+ };
2312
+ }
2313
+ const parsed = args.source !== undefined
2314
+ ? validatePipelineSpecFromSource(args.source)
2315
+ : await loadPipelineFile(args.path, args.workingDirectory);
2316
+ if (!parsed.ok) {
2317
+ return {
2318
+ content: JSON.stringify({
2319
+ success: false,
2320
+ pipeline: null,
2321
+ errors: parsed.errors,
2322
+ warnings: parsed.warnings,
2323
+ }),
2324
+ };
2325
+ }
2326
+ const spec = parsed.spec;
2327
+ const existing = await listTaskDefinitions();
2328
+ const plan = planPipelineApply(spec, existing, {
2329
+ resolveWorkspaceId: (nameOrId) => {
2330
+ const ws = getWorkspace(nameOrId);
2331
+ return ws ? ws.id : undefined;
2332
+ },
2333
+ });
2334
+ let created = 0;
2335
+ let updated = 0;
2336
+ const errors = [];
2337
+ if (!dryRun) {
2338
+ for (const task of plan.creates) {
2339
+ try {
2340
+ await schedulerCreateTask(task.name, task.schedule, task.prompt, task.timeoutSeconds, task.workingDirectory ?? task.workdir ?? undefined, task.retryCount, task.retryDelay, task.qualityGate, task.nextTaskOnSuccess, task.nextTaskOnError, task.triggerType ?? "cron", task.watchPath, task.dependsOn, task.model, task.priority, task.beforeScript, task.afterScript, task.mcpEvent, task.workspaceId, task.allowedTools, task.deniedTools, task.matrix, task.matrixParentId, "create", task.timezone, task.notBefore, task.notAfter, task.pausedUntil, task.runAt, task.session, task.sessionId, task.sessionMaxRuns, {
2341
+ activeDays: task.activeDays,
2342
+ windowPolicy: task.windowPolicy,
2343
+ watchGlobs: task.watchGlobs ?? [],
2344
+ watchIgnore: task.watchIgnore ?? [],
2345
+ gitBranch: task.gitBranch,
2346
+ gitPaths: task.gitPaths,
2347
+ gitIgnore: task.gitIgnore,
2348
+ gitPollSeconds: task.gitPollSeconds,
2349
+ }, task.runWhenLoggedOff ?? false, task.paused ?? false, task.legacyShell ?? false, task.worktree ?? false, task.guards);
2350
+ await saveTaskDefinition(task);
2351
+ created++;
2352
+ }
2353
+ catch (err) {
2354
+ errors.push(`create ${task.name}: ${err instanceof Error ? err.message : String(err)}`);
2355
+ }
2356
+ }
2357
+ for (const item of plan.updates) {
2358
+ try {
2359
+ await schedulerCreateTask(item.task.name, item.task.schedule, item.task.prompt, item.task.timeoutSeconds, item.task.workingDirectory ?? item.task.workdir ?? undefined, item.task.retryCount, item.task.retryDelay, item.task.qualityGate, item.task.nextTaskOnSuccess, item.task.nextTaskOnError, item.task.triggerType ?? "cron", item.task.watchPath, item.task.dependsOn, item.task.model, item.task.priority, item.task.beforeScript, item.task.afterScript, item.task.mcpEvent, item.task.workspaceId, item.task.allowedTools, item.task.deniedTools, item.task.matrix, item.task.matrixParentId, "sync", item.task.timezone, item.task.notBefore, item.task.notAfter, item.task.pausedUntil, item.task.runAt, item.task.session, item.task.sessionId, item.task.sessionMaxRuns, {
2360
+ activeDays: item.task.activeDays,
2361
+ windowPolicy: item.task.windowPolicy,
2362
+ watchGlobs: item.task.watchGlobs ?? [],
2363
+ watchIgnore: item.task.watchIgnore ?? [],
2364
+ gitBranch: item.task.gitBranch,
2365
+ gitPaths: item.task.gitPaths,
2366
+ gitIgnore: item.task.gitIgnore,
2367
+ gitPollSeconds: item.task.gitPollSeconds,
2368
+ }, item.task.runWhenLoggedOff ?? false, item.task.paused ?? false, item.task.legacyShell ?? false, item.task.worktree ?? false, item.task.guards);
2369
+ await saveTaskDefinition(item.task);
2370
+ updated++;
2371
+ }
2372
+ catch (err) {
2373
+ errors.push(`update ${item.task.name}: ${err instanceof Error ? err.message : String(err)}`);
2374
+ }
2375
+ }
2376
+ refreshTriggers();
2377
+ }
2378
+ return {
2379
+ content: JSON.stringify({
2380
+ success: errors.length === 0,
2381
+ pipeline: spec.name,
2382
+ dryRun,
2383
+ created,
2384
+ updated,
2385
+ unchanged: plan.unchanged.length,
2386
+ stale: plan.stale.length,
2387
+ warnings: [...plan.warnings, ...errors],
2388
+ errors,
2389
+ }),
2390
+ };
2391
+ });
2392
+ /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
2393
+ const pipelineExportExecute = wrapExecute(async (args) => {
2394
+ const allTasks = await listTaskDefinitions();
2395
+ // QA-P3.2: два имени — это ошибка, а не молчаливый выбор первого.
2396
+ const explicit = args.pipeline?.trim();
2397
+ const alias = args.pipelineName?.trim();
2398
+ if (explicit && alias && explicit.toLowerCase() !== alias.toLowerCase()) {
2399
+ return {
2400
+ content: JSON.stringify({
2401
+ success: false,
2402
+ error: "Конфликт параметров: pipeline и pipelineName задают разные имена конвейера.",
2403
+ }),
2404
+ };
2405
+ }
2406
+ const pipelineName = explicit || alias;
2407
+ if (!pipelineName) {
2408
+ return {
2409
+ content: JSON.stringify({
2410
+ success: false,
2411
+ error: "Не задано имя конвейера: укажите pipeline или pipelineName.",
2412
+ }),
2413
+ };
2414
+ }
2415
+ const result = tasksToPipelineSpec(allTasks, pipelineName);
2416
+ // QA-P3.2: spec всегда создаётся, поэтому «не найден» проверяем по шагам.
2417
+ const lookupError = pipelineExportLookupError(allTasks, pipelineName);
2418
+ if (!result.spec || lookupError) {
2419
+ return {
2420
+ content: JSON.stringify({
2421
+ success: false,
2422
+ error: lookupError ?? `Конвейер "${pipelineName}" не найден.`,
2423
+ warnings: result.warnings,
2424
+ }),
2425
+ };
2426
+ }
2427
+ const yamlText = yamlStringify(result.spec, { lineWidth: 0 });
2428
+ return {
2429
+ content: JSON.stringify({
2430
+ success: true,
2431
+ pipeline: pipelineName,
2432
+ steps: result.spec.steps.length,
2433
+ yaml: yamlText,
2434
+ warnings: result.warnings,
2435
+ }),
2436
+ };
2437
+ });
1889
2438
  /**
1890
2439
  * Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
1891
2440
  * Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
@@ -2089,6 +2638,17 @@ const matrixControlExecute = wrapExecute(async (args) => {
2089
2638
  };
2090
2639
  }
2091
2640
  }
2641
+ // QA-P3.7: `results` должен так же проверять тип задачи, как `cancel`.
2642
+ // Иначе неизвестное имя даёт success:true с пустым отчётом вместо
2643
+ // внятной ошибки «задача не является матрицей».
2644
+ if (!isKnownMatrix(name)) {
2645
+ return {
2646
+ content: JSON.stringify({
2647
+ success: false,
2648
+ error: t("tool.error.matrixNotMatrix", { name }),
2649
+ }),
2650
+ };
2651
+ }
2092
2652
  try {
2093
2653
  const report = aggregateMatrixResults(name);
2094
2654
  return { content: JSON.stringify({ success: true, report }) };
@@ -2105,34 +2665,52 @@ const matrixControlExecute = wrapExecute(async (args) => {
2105
2665
  /** get_metrics — суммарная статистика запусков. */
2106
2666
  const getMetricsExecute = wrapExecute(async () => {
2107
2667
  const metrics = await loadMetrics();
2108
- return { content: JSON.stringify({ success: true, metrics }) };
2668
+ // PL-4.1: блокировки инструментов — показатель корректности hybrid-политики.
2669
+ const since = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString();
2670
+ const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
2671
+ return { content: JSON.stringify({ success: true, metrics: { ...metrics, toolBlocked } }) };
2109
2672
  });
2110
2673
  /** get_analytics — аналитика запусков и стоимости за период. */
2111
2674
  const getAnalyticsExecute = wrapExecute(async (args) => {
2112
2675
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
2113
- const records = getHistory(null, 20000);
2676
+ const records = getHistoryForAnalytics(windowDays);
2114
2677
  const definitions = await loadTaskDefinitions();
2115
2678
  const report = buildAnalytics(records, {
2116
2679
  days: windowDays,
2117
2680
  topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
2118
- tasks: definitions.map((definition) => ({
2681
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
2119
2682
  name: definition.name,
2120
2683
  matrixParentId: definition.matrixParentId,
2684
+ tokenBudget: definition.tokenBudget,
2121
2685
  })),
2122
2686
  });
2123
- return { content: JSON.stringify({ success: true, report }) };
2687
+ // Экономика v2 (E-1.1): учёт расхода за день/неделю рядом с аналитикой.
2688
+ const settings = await loadSettings();
2689
+ const budgets = buildBudgetReport(records, settings.budgets, new Date());
2690
+ // PL-4.1: tool.blocked — метрика корректности прав политики, а не ошибка
2691
+ // запуска. Считаем за то же окно, что и аналитику; readAuditLog отдаёт total
2692
+ // независимо от limit, поэтому одной строки выборки достаточно для счётчика.
2693
+ const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1000).toISOString();
2694
+ const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
2695
+ return {
2696
+ content: JSON.stringify({
2697
+ success: true,
2698
+ report: { ...report, budgets, toolBlocked },
2699
+ }),
2700
+ };
2124
2701
  });
2125
2702
  /** self_analysis — система самоанализа: здоровье, аномалии, тренды, рекомендации. */
2126
2703
  const selfAnalysisExecute = wrapExecute(async (args) => {
2127
2704
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
2128
- const records = getHistory(null, 20000);
2705
+ const records = getHistoryForAnalytics(windowDays);
2129
2706
  const definitions = await loadTaskDefinitions();
2130
2707
  const report = generateSelfAnalysisReport(records, {
2131
2708
  days: windowDays,
2132
2709
  topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
2133
- tasks: definitions.map((definition) => ({
2710
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
2134
2711
  name: definition.name,
2135
2712
  matrixParentId: definition.matrixParentId,
2713
+ tokenBudget: definition.tokenBudget,
2136
2714
  })),
2137
2715
  });
2138
2716
  // Фильтруем секции если нужно
@@ -2157,7 +2735,7 @@ const selfAnalysisExecute = wrapExecute(async (args) => {
2157
2735
  /** manage_settings — чтение и изменение глобальных настроек. */
2158
2736
  const manageSettingsExecute = wrapExecute(async (args) => {
2159
2737
  const current = await loadSettings();
2160
- if (args.action === "get") {
2738
+ if (args.action === "get" || args.action === "list") {
2161
2739
  return { content: JSON.stringify({ success: true, settings: current }) };
2162
2740
  }
2163
2741
  if (args.maxConcurrent === undefined &&
@@ -2167,7 +2745,9 @@ const manageSettingsExecute = wrapExecute(async (args) => {
2167
2745
  args.history === undefined &&
2168
2746
  args.integrations === undefined &&
2169
2747
  args.audit === undefined &&
2170
- args.permissions === undefined) {
2748
+ args.permissions === undefined &&
2749
+ args.budgets === undefined &&
2750
+ args.feedback === undefined) {
2171
2751
  return {
2172
2752
  content: JSON.stringify({
2173
2753
  success: false,
@@ -2185,6 +2765,8 @@ const manageSettingsExecute = wrapExecute(async (args) => {
2185
2765
  integrations: args.integrations,
2186
2766
  audit: args.audit,
2187
2767
  permissions: args.permissions,
2768
+ budgets: args.budgets,
2769
+ feedback: args.feedback,
2188
2770
  });
2189
2771
  // Локаль процесса меняется сразу — перезапуск плагина не нужен.
2190
2772
  setLocale(resolveLocale(settings.locale, settings.uiLocale));
@@ -2285,12 +2867,14 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
2285
2867
  return { content: JSON.stringify({ success: true, templates: await loadTemplates() }) };
2286
2868
  }
2287
2869
  if (args.action === "delete") {
2288
- const id = args.id?.trim();
2870
+ // PL-17/PL-28/PL-32: name — такой же алиас id, как и в репозитории.
2871
+ const id = args.id?.trim() || args.name?.trim();
2289
2872
  if (!id) {
2290
2873
  return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
2291
2874
  }
2292
2875
  const before = await loadTemplates();
2293
- const existed = before.some((template) => template.id === id);
2876
+ // QA-P3.3: name является алиасом id при удалении.
2877
+ const existed = before.some((template) => template.id === id || template.name === id);
2294
2878
  await deleteTemplate(id);
2295
2879
  return {
2296
2880
  content: JSON.stringify({
@@ -2399,7 +2983,18 @@ const transferTasksExecute = wrapExecute(async (args) => {
2399
2983
  const errors = [...parsed.errors];
2400
2984
  for (const def of parsed.tasks) {
2401
2985
  try {
2402
- await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt);
2986
+ await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt, def.session, def.sessionId, def.sessionMaxRuns, {
2987
+ activeDays: def.activeDays,
2988
+ windowPolicy: def.windowPolicy,
2989
+ watchGlobs: def.watchGlobs,
2990
+ watchIgnore: def.watchIgnore,
2991
+ gitBranch: def.gitBranch,
2992
+ gitPaths: def.gitPaths,
2993
+ gitIgnore: def.gitIgnore,
2994
+ gitPollSeconds: def.gitPollSeconds,
2995
+ }, def.runWhenLoggedOff, def.paused, def.legacyShell, def.worktree, def.guards,
2996
+ // QA-P0.1 (E-2.1): импорт через transfer_tasks сохраняет tokenBudget.
2997
+ def.tokenBudget);
2403
2998
  await saveTaskDefinition(def);
2404
2999
  imported.push(def.name);
2405
3000
  }
@@ -2419,9 +3014,151 @@ const sendNotificationExecute = wrapExecute(async (args) => {
2419
3014
  : await sendDigestNow({ updateLastSentAt: false });
2420
3015
  return { content: JSON.stringify(result) };
2421
3016
  });
3017
+ /**
3018
+ * Общий сборщик текста баг-репорта (устраняет дублирование между MCP-тулом
3019
+ * и RPC-хендлером — QA-находка 3.8). Возвращает также сырые логи и метрики
3020
+ * для структурированного payload (F-1.1).
3021
+ */
3022
+ async function buildBugReportText(input) {
3023
+ const lines = [];
3024
+ lines.push("🐛 *Bug report — agent-steward plugin*");
3025
+ lines.push(`Время: ${new Date().toISOString()}`);
3026
+ lines.push(`Описание: ${input.description}`);
3027
+ let logs;
3028
+ if (input.taskName) {
3029
+ lines.push(`Задача: ${input.taskName}`);
3030
+ if (input.includeLogs) {
3031
+ try {
3032
+ const taskLogs = await getTaskLogs(input.taskName);
3033
+ if (taskLogs.logs) {
3034
+ logs = String(taskLogs.logs).slice(0, 2000);
3035
+ lines.push(`\n--- Логи задачи ${input.taskName} ---`);
3036
+ lines.push(logs);
3037
+ }
3038
+ }
3039
+ catch (err) {
3040
+ lines.push(`\n--- Логи задачи ${input.taskName}: ошибка чтения ---`);
3041
+ lines.push(err instanceof Error ? err.message : String(err));
3042
+ }
3043
+ }
3044
+ }
3045
+ let metrics;
3046
+ if (input.includeAnalytics !== false) {
3047
+ try {
3048
+ const raw = await loadMetrics();
3049
+ metrics = {
3050
+ total: raw.total,
3051
+ success: raw.success,
3052
+ error: raw.error,
3053
+ partial: raw.partial ?? 0,
3054
+ };
3055
+ lines.push("\n--- Метрики ---");
3056
+ lines.push(`Всего запусков: ${metrics.total}`);
3057
+ lines.push(`Успех: ${metrics.success}`);
3058
+ lines.push(`Ошибок: ${metrics.error}`);
3059
+ if (metrics.partial)
3060
+ lines.push(`Частично: ${metrics.partial}`);
3061
+ }
3062
+ catch (err) {
3063
+ lines.push(`\n--- Метрики: ошибка чтения: ${err instanceof Error ? err.message : String(err)} ---`);
3064
+ }
3065
+ try {
3066
+ const records = getHistoryForAnalytics(7);
3067
+ const definitions = await loadTaskDefinitions();
3068
+ const report = buildAnalytics(records, {
3069
+ days: 7,
3070
+ topLimit: 10,
3071
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
3072
+ name: definition.name,
3073
+ matrixParentId: definition.matrixParentId,
3074
+ tokenBudget: definition.tokenBudget,
3075
+ })),
3076
+ });
3077
+ lines.push("\n--- Аналитика (7 дней) ---");
3078
+ lines.push(`Всего запусков: ${report.totals.total}`);
3079
+ lines.push(`Успех: ${report.totals.success}`);
3080
+ lines.push(`Ошибок: ${report.totals.error}`);
3081
+ if (report.totals.partial)
3082
+ lines.push(`Частично: ${report.totals.partial}`);
3083
+ const errorTasks = report.tasks.filter((task) => task.error > 0).slice(0, 5);
3084
+ if (errorTasks.length > 0) {
3085
+ lines.push(`Задачи с ошибками: ${errorTasks.map((task) => `${task.taskName} (${task.error})`).join(", ")}`);
3086
+ }
3087
+ }
3088
+ catch (err) {
3089
+ lines.push(`\n--- Аналитика: ошибка чтения: ${err instanceof Error ? err.message : String(err)} ---`);
3090
+ }
3091
+ }
3092
+ return { text: lines.join("\n"), logs, metrics };
3093
+ }
3094
+ /**
3095
+ * Значения всех секретов из manage_secrets — используются только для
3096
+ * редактирования текста (F-1.4). Ни одно значение не попадает в payload.
3097
+ */
3098
+ function collectSecretValues() {
3099
+ const values = [];
3100
+ for (const item of listSecrets()) {
3101
+ const value = getSecret(item.name);
3102
+ if (value && value.length >= 4)
3103
+ values.push(value);
3104
+ }
3105
+ return values;
3106
+ }
3107
+ /** report_bug — отчёт о баге; по умолчанию уходит автору через приёмник F-2. */
3108
+ const reportBugExecute = wrapExecute(async (args) => {
3109
+ const settings = await loadSettings();
3110
+ const includeLogs = args.includeLogs ?? settings.feedback.includeLogs;
3111
+ const built = await buildBugReportText({
3112
+ description: args.description,
3113
+ taskName: args.taskName,
3114
+ includeLogs,
3115
+ includeAnalytics: args.includeAnalytics,
3116
+ });
3117
+ const secretValues = collectSecretValues();
3118
+ const localText = redactText(built.text, { secrets: secretValues, redactEmails: false });
3119
+ const result = await reportFeedback({
3120
+ settings: settings.feedback,
3121
+ destination: args.destination ?? "author",
3122
+ dryRun: args.dryRun,
3123
+ description: args.description,
3124
+ taskName: args.taskName,
3125
+ contactEmail: args.contactEmail ?? settings.feedback.contactEmail,
3126
+ redactedLogs: includeLogs ? built.logs : undefined,
3127
+ metrics: built.metrics,
3128
+ locale: settings.locale,
3129
+ secrets: secretValues,
3130
+ sendLocal: (text) => sendBugReport(text, args.channel),
3131
+ localText,
3132
+ });
3133
+ return {
3134
+ content: JSON.stringify({
3135
+ ...result,
3136
+ message: result.mode === "dryRun"
3137
+ ? t("feedback.dryRun")
3138
+ : result.mode === "sent"
3139
+ ? t("feedback.sent")
3140
+ : result.mode === "outbox"
3141
+ ? t("feedback.outbox")
3142
+ : result.mode === "duplicate"
3143
+ ? t("feedback.duplicate")
3144
+ : t("feedback.local"),
3145
+ }),
3146
+ };
3147
+ });
2422
3148
  /** get_dashboard_info — порт дашборда, платформа и активный профиль. */
2423
3149
  const getDashboardInfoExecute = wrapExecute(async () => {
2424
- const port = getDashboardPort();
3150
+ // QA-P3.5: порт из профиля/env может быть «бумажным» (4782), а живой
3151
+ // дашборд слушает 3782. Проверяем маркер и при необходимости находим порт
3152
+ // зондированием стандартных кандидатов, чтобы отчёт совпадал с реальностью.
3153
+ let port = getDashboardPort();
3154
+ let probe = port ? await probeDashboardOn(port) : null;
3155
+ if (!probe?.dashboard) {
3156
+ const discovered = await discoverDashboardPort();
3157
+ if (discovered) {
3158
+ port = discovered;
3159
+ probe = await probeDashboardOn(port);
3160
+ }
3161
+ }
2425
3162
  return {
2426
3163
  content: JSON.stringify({
2427
3164
  success: true,
@@ -2430,6 +3167,7 @@ const getDashboardInfoExecute = wrapExecute(async () => {
2430
3167
  platform: scheduler.platform,
2431
3168
  title: scheduler.title,
2432
3169
  profile: getProfileName(),
3170
+ reachable: probe?.dashboard ?? false,
2433
3171
  }),
2434
3172
  };
2435
3173
  });
@@ -2454,38 +3192,81 @@ const cleanupHistoryExecute = wrapExecute(async (args) => {
2454
3192
  }),
2455
3193
  };
2456
3194
  });
2457
- /** emit_event — запуск задач, подписанных на MCP-событие. */
2458
- const emitEventExecute = wrapExecute(async (args) => {
2459
- const eventName = args.eventName?.trim();
2460
- if (!eventName) {
2461
- return { content: JSON.stringify({ success: false, error: t("tool.event.nameRequired") }) };
3195
+ const DEFAULT_EVENT_PRIORITY = 5;
3196
+ /**
3197
+ * QV-3: проверка, что задача подписана на MCP-событие. Источник `server`
3198
+ * сравнивается только когда он передан вызывающим — это сохраняет обратную
3199
+ * совместимость со старыми вызовами emit_event без указания источника.
3200
+ */
3201
+ export function matchesMcpEventSubscription(def, event, server, payload) {
3202
+ if ((def.triggerType ?? "cron") !== "mcp-event")
3203
+ return false;
3204
+ // PL-48: definition может хранить алиас `eventName` (PL-42), поэтому матчер
3205
+ // читает нормализованное событие, а не только каноническое поле `event`.
3206
+ const subscription = normalizeMcpEventTrigger(def.mcpEvent);
3207
+ if (subscription?.event.toLowerCase() !== event.toLowerCase())
3208
+ return false;
3209
+ const expectedServer = server?.trim();
3210
+ if (expectedServer &&
3211
+ subscription.server.toLowerCase() !== expectedServer.toLowerCase()) {
3212
+ return false;
3213
+ }
3214
+ return matchesEventFilter(subscription.filter, payload);
3215
+ }
3216
+ export async function emitEventCore(rawEventName, payload, server) {
3217
+ const event = rawEventName?.trim() ?? "";
3218
+ if (!event) {
3219
+ return {
3220
+ success: false,
3221
+ code: "no_subscribers",
3222
+ event,
3223
+ matched: [],
3224
+ triggered: [],
3225
+ failed: [],
3226
+ message: t("tool.event.nameRequiredShort"),
3227
+ };
2462
3228
  }
2463
- const payload = args.payload ?? {};
2464
3229
  const definitions = await loadTaskDefinitions();
2465
3230
  const matched = definitions
2466
- .filter((def) => def.triggerType === "mcp-event" &&
2467
- def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
2468
- matchesEventFilter(def.mcpEvent?.filter, payload))
2469
- .sort((a, b) => (normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0));
3231
+ .filter((def) => matchesMcpEventSubscription(def, event, server, payload))
3232
+ .sort((a, b) => (normalizePriority(b.priority) ?? DEFAULT_EVENT_PRIORITY) -
3233
+ (normalizePriority(a.priority) ?? DEFAULT_EVENT_PRIORITY));
2470
3234
  const triggered = [];
3235
+ const failed = [];
2471
3236
  for (const def of matched) {
2472
3237
  try {
2473
3238
  await runTaskEntry(def.name);
2474
3239
  triggered.push(def.name);
2475
3240
  }
2476
3241
  catch (err) {
2477
- console.error(`[agent-steward] emit_event: не удалось запустить ${def.name}:`, err);
3242
+ const error = err instanceof Error ? err.message : String(err);
3243
+ failed.push({ name: def.name, error });
3244
+ console.error(`[agent-steward] emit_event: не удалось запустить ${def.name}: ${error}`);
2478
3245
  }
2479
3246
  }
3247
+ const code = matched.length === 0 ? "no_subscribers" : failed.length > 0 ? "start_failed" : "ok";
3248
+ const message = code === "no_subscribers"
3249
+ ? t("tool.event.none", { event })
3250
+ : code === "start_failed"
3251
+ ? t("tool.event.startFailed", { count: failed.length })
3252
+ : t("tool.event.triggered", { count: triggered.length });
2480
3253
  return {
2481
- content: JSON.stringify({
2482
- success: true,
2483
- message: triggered.length > 0
2484
- ? t("tool.event.triggered", { count: triggered.length })
2485
- : t("tool.event.none", { event: eventName }),
2486
- triggered,
2487
- }),
3254
+ success: true,
3255
+ code,
3256
+ event,
3257
+ matched: matched.map((def) => def.name),
3258
+ triggered,
3259
+ failed,
3260
+ message,
2488
3261
  };
3262
+ }
3263
+ /** emit_event — запуск задач, подписанных на MCP-событие. */
3264
+ const emitEventExecute = wrapExecute(async (args) => {
3265
+ const result = await emitEventCore(args.eventName, args.payload ?? {}, args.server);
3266
+ if (!result.success) {
3267
+ return { content: JSON.stringify({ ...result, error: result.message }) };
3268
+ }
3269
+ return { content: JSON.stringify(result) };
2489
3270
  });
2490
3271
  /** manage_secrets — зашифрованное хранилище секретов. */
2491
3272
  const manageSecretsExecute = wrapExecute(async (args) => {
@@ -2551,10 +3332,15 @@ function withAudit(toolName, describe, execute) {
2551
3332
  return async (args, context) => {
2552
3333
  const result = await execute(args, context);
2553
3334
  try {
2554
- const raw = String(result?.content ?? "");
3335
+ const content = result.content;
3336
+ const raw = typeof content === "string" ? content : "";
2555
3337
  const parsed = raw ? JSON.parse(raw) : null;
2556
- if (parsed?.success === false)
3338
+ if (typeof parsed === "object" &&
3339
+ parsed !== null &&
3340
+ "success" in parsed &&
3341
+ parsed.success === false) {
2557
3342
  return result;
3343
+ }
2558
3344
  const entry = describe(args);
2559
3345
  if (entry) {
2560
3346
  recordAudit({ ...entry, actor: "mcp", source: toolName });
@@ -2572,6 +3358,11 @@ const RPC_AUDIT_RULES = {
2572
3358
  update_task: { action: "task.update", targetType: "task", target: (i) => i.name ?? "" },
2573
3359
  delete_task: { action: "task.delete", targetType: "task", target: (i) => i.name ?? "" },
2574
3360
  run_task: { action: "task.run", targetType: "task", target: (i) => i.name ?? "" },
3361
+ run_mission: {
3362
+ action: "mission.run",
3363
+ targetType: "mission",
3364
+ target: (i) => i.taskName ?? "ad-hoc",
3365
+ },
2575
3366
  pause_task: { action: "task.pause", targetType: "task", target: (i) => i.name ?? "" },
2576
3367
  resume_task: { action: "task.resume", targetType: "task", target: (i) => i.name ?? "" },
2577
3368
  cancel_matrix: { action: "matrix.cancel", targetType: "matrix", target: (i) => i.name ?? "" },
@@ -2645,17 +3436,22 @@ const RPC_AUDIT_RULES = {
2645
3436
  */
2646
3437
  function withRpcAudit(handlers) {
2647
3438
  const wrapped = {};
2648
- for (const [name, handler] of Object.entries(handlers)) {
3439
+ const entries = Object.entries(handlers);
3440
+ for (const [name, handler] of entries) {
2649
3441
  const rule = RPC_AUDIT_RULES[name];
2650
3442
  if (!rule || typeof handler !== "function") {
2651
3443
  wrapped[name] = handler;
2652
3444
  continue;
2653
3445
  }
2654
3446
  wrapped[name] = async (...args) => {
2655
- const input = args[0] ?? {};
3447
+ const input = (args[0] ?? {});
2656
3448
  const result = await handler(...args);
2657
3449
  try {
2658
- if ((result)?.success !== false) {
3450
+ const failed = typeof result === "object" &&
3451
+ result !== null &&
3452
+ "success" in result &&
3453
+ result.success === false;
3454
+ if (!failed) {
2659
3455
  recordAudit({
2660
3456
  action: rule.action,
2661
3457
  targetType: rule.targetType,
@@ -2728,7 +3524,28 @@ async function scheduleEventRun(taskName, reason) {
2728
3524
  const now = new Date();
2729
3525
  const state = activeWindowState(now, options);
2730
3526
  if (state.active || policy === "run") {
2731
- await runTaskEntry(taskName);
3527
+ const startedAt = now.toISOString();
3528
+ try {
3529
+ await runTaskEntry(taskName);
3530
+ }
3531
+ catch (err) {
3532
+ // PL-53: отказ старта по событийному триггеру раньше уходил только
3533
+ // в console.error хоста и не оставлял следа в истории/журнале.
3534
+ const message = err instanceof Error ? err.message : String(err);
3535
+ const runId = recordRun(taskName, "error", startedAt, 0, message);
3536
+ appendStructuredLog({
3537
+ event: "trigger.start_failed",
3538
+ runId,
3539
+ task: taskName,
3540
+ status: "error",
3541
+ startedAt,
3542
+ finishedAt: new Date().toISOString(),
3543
+ durationMs: 0,
3544
+ error: message,
3545
+ reason,
3546
+ });
3547
+ throw err;
3548
+ }
2732
3549
  console.log(`[agent-steward] Запуск задачи "${taskName}" (${reason}).`);
2733
3550
  return;
2734
3551
  }
@@ -2778,6 +3595,18 @@ export async function createRuntime(ctxLike) {
2778
3595
  catch (err) {
2779
3596
  console.error(`[recovery] Не удалось восстановить незавершённые запуски: ${err instanceof Error ? err.message : String(err)}`);
2780
3597
  }
3598
+ // Деталь 3.8 (F-1.6): повторяем недоставленные отчёты из outbox.
3599
+ // Fire-and-forget: сеть не должна задерживать или ломать старт плагина.
3600
+ void loadSettings()
3601
+ .then((settings) => flushOutbox(settings.feedback))
3602
+ .then((result) => {
3603
+ if (result.sent > 0) {
3604
+ console.log(`[feedback] Из outbox доставлено отчётов: ${result.sent}`);
3605
+ }
3606
+ })
3607
+ .catch((err) => {
3608
+ console.error(`[feedback] Ошибка повтора outbox: ${err instanceof Error ? err.message : String(err)}`);
3609
+ });
2781
3610
  // P1-14: pid:-записи fallback'а не переживают перезагрузку. Чистим их и
2782
3611
  // пересоздаём будущие one-shot, иначе после reboot можно убить чужой pid.
2783
3612
  if (scheduler instanceof LinuxScheduler) {
@@ -2936,6 +3765,9 @@ export function createToolHandlers(_runtime) {
2936
3765
  get_history: getHistoryExecute,
2937
3766
  get_task_logs: getTaskLogsExecute,
2938
3767
  dry_run: dryRunExecute,
3768
+ pipeline_validate: pipelineValidateExecute,
3769
+ pipeline_apply: pipelineApplyExecute,
3770
+ pipeline_export: pipelineExportExecute,
2939
3771
  manage_workspaces: manageWorkspacesExecute,
2940
3772
  matrix_control: matrixControlExecute,
2941
3773
  get_metrics: getMetricsExecute,
@@ -2947,6 +3779,7 @@ export function createToolHandlers(_runtime) {
2947
3779
  manage_profiles: manageProfilesExecute,
2948
3780
  transfer_tasks: transferTasksExecute,
2949
3781
  send_notification: sendNotificationExecute,
3782
+ report_bug: reportBugExecute,
2950
3783
  get_dashboard_info: getDashboardInfoExecute,
2951
3784
  cleanup_history: cleanupHistoryExecute,
2952
3785
  emit_event: emitEventExecute,
@@ -2976,6 +3809,8 @@ export function createShutdownHandler(runtime, registrations = [], options = {})
2976
3809
  }
2977
3810
  // Чекпойнт WAL выполняется в closeDb.
2978
3811
  closeDb();
3812
+ // QA/PL-10: выгрузка действительно завершена — запрещаем автосброс ворот.
3813
+ shutdownGate.complete();
2979
3814
  };
2980
3815
  }
2981
3816
  /**
@@ -2985,7 +3820,14 @@ export function createShutdownHandler(runtime, registrations = [], options = {})
2985
3820
  * одинаковые имена, схемы, описания и обработчики. Аудит навешивается здесь
2986
3821
  * один раз, чтобы обе линии вели журнал одинаково.
2987
3822
  */
2988
- export function createToolSpecs(runtime) {
3823
+ export function createToolSpecs(runtime, env = process.env) {
3824
+ // QV-8: обёртка задач выставляет маркер дочернего прогона перед `opencode run`.
3825
+ // Такой ребёнок не должен получать инструменты планировщика — иначе он видит
3826
+ // весь surface родителя и может рекурсивно создавать задачи.
3827
+ if (isChildRunMode(env)) {
3828
+ console.log(`[qv8] ${CHILD_RUN_ENV}: инструменты планировщика не регистрируются`);
3829
+ return [];
3830
+ }
2989
3831
  const handlers = createToolHandlers(runtime);
2990
3832
  return [
2991
3833
  {
@@ -3000,8 +3842,9 @@ export function createToolSpecs(runtime) {
3000
3842
  {
3001
3843
  name: "list_tasks",
3002
3844
  input: listTasksSchema,
3845
+ output: listTasksOutputSchema,
3003
3846
  description: `Lists plugin tasks from the scheduler (${scheduler.title}) with schedule, status, next chained task and working directory. ` +
3004
- "Matrix parents include a per-clone summary.",
3847
+ "Matrix parents include a per-clone summary. Returns structured output in Code Mode; content remains a JSON string for V1 compatibility.",
3005
3848
  execute: handlers.list_tasks,
3006
3849
  },
3007
3850
  {
@@ -3103,7 +3946,9 @@ export function createToolSpecs(runtime) {
3103
3946
  name: "self_analysis",
3104
3947
  input: selfAnalysisSchema,
3105
3948
  description: "Generates a self-analysis report: system health score, anomaly detection, trend analysis and optimization recommendations. " +
3106
- "Helps identify performance issues, cost spikes and reliability problems.",
3949
+ "Helps identify performance issues, cost spikes and reliability problems. " +
3950
+ "In health.components, successRate and errorRate are normalized 0..100 scores (higher is better): " +
3951
+ "errorRate = 100 - 100 * error / total, so it is NOT the raw error percentage.",
3107
3952
  execute: handlers.self_analysis,
3108
3953
  },
3109
3954
  {
@@ -3167,6 +4012,12 @@ export function createToolSpecs(runtime) {
3167
4012
  description: "Sends a test notification through the configured channel or sends the digest immediately.",
3168
4013
  execute: handlers.send_notification,
3169
4014
  },
4015
+ {
4016
+ name: "report_bug",
4017
+ input: reportBugSchema,
4018
+ description: "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.",
4019
+ execute: handlers.report_bug,
4020
+ },
3170
4021
  {
3171
4022
  name: "get_dashboard_info",
3172
4023
  input: getDashboardInfoSchema,
@@ -3202,6 +4053,29 @@ export function createToolSpecs(runtime) {
3202
4053
  "Filter by action, target, actor, time range and limit. Secret values are redacted.",
3203
4054
  execute: handlers.get_audit_log,
3204
4055
  },
4056
+ {
4057
+ name: "pipeline_validate",
4058
+ input: pipelineValidateSchema,
4059
+ description: "Проверяет opencode.pipeline.yaml (путь к файлу или исходник): валидирует version, шаги, зависимости, циклы, cron-расписание, matrix, модель, окна запуска и другие инварианты конвейера. Не применяет изменения.",
4060
+ execute: handlers.pipeline_validate,
4061
+ },
4062
+ {
4063
+ name: "pipeline_apply",
4064
+ input: pipelineApplySchema,
4065
+ description: "Применяет opencode.pipeline.yaml к текущему набору задач: создаёт новые, обновляет изменённые, пропускает без изменений (идемпотентно). Задачи без маркера pipelineName не трогаются. В режиме dryRun только отчитывает diff.",
4066
+ audit: (args) => ({
4067
+ action: "pipeline.apply",
4068
+ targetType: "pipeline",
4069
+ target: args.source ?? args.path ?? "",
4070
+ }),
4071
+ execute: handlers.pipeline_apply,
4072
+ },
4073
+ {
4074
+ name: "pipeline_export",
4075
+ input: pipelineExportSchema,
4076
+ description: "Выгружает задачи указанного конвейера (pipelineName) как opencode.pipeline.yaml: шаги, зависимости, matrix, кастомные настройки шага.",
4077
+ execute: handlers.pipeline_export,
4078
+ },
3205
4079
  {
3206
4080
  name: "emit_event",
3207
4081
  input: emitEventSchema,
@@ -3231,6 +4105,14 @@ async function startSchedulerDashboard() {
3231
4105
  const v2Plugin = Plugin.define({
3232
4106
  id: "opencode-windows-scheduler",
3233
4107
  setup: async (ctx) => {
4108
+ if (isChildRunMode()) {
4109
+ console.log(`[qv8] ${CHILD_RUN_ENV}: дочерний прогон, пропускаю регистрацию плагина`);
4110
+ return async () => undefined;
4111
+ }
4112
+ // PL-45: hot-reload/Code Mode может заново вызвать setup после того, как
4113
+ // хост закрыл и «завершил» ворота, не выгрузив модуль. Открываем их,
4114
+ // иначе все in-process запуски навсегда получают PLUGIN_SHUTTING_DOWN.
4115
+ shutdownGate.reset();
3234
4116
  const runtime = await createRuntime(ctx);
3235
4117
  const registration = await ctx.tool.transform((editor) => {
3236
4118
  // editor.add регистрирует новые инструменты плагина с codemode: true,
@@ -3244,9 +4126,10 @@ const v2Plugin = Plugin.define({
3244
4126
  editor.add({
3245
4127
  name: spec.name,
3246
4128
  input: spec.input,
4129
+ output: spec.output,
3247
4130
  description: spec.description,
3248
4131
  options: { codemode: true },
3249
- execute: execute,
4132
+ execute,
3250
4133
  });
3251
4134
  }
3252
4135
  });
@@ -3259,6 +4142,10 @@ const v2Plugin = Plugin.define({
3259
4142
  const skill = loadSchedulerSkill();
3260
4143
  if (skill && ctx.skill?.transform) {
3261
4144
  skillRegistration = await ctx.skill.transform((editor) => {
4145
+ // QA-A2.1: V2 skill API ожидает Effect-брендированные строки
4146
+ // (Skill.ID / Skill.Name / AbsolutePath). Значения приходят из
4147
+ // собственного skill.ts, бренд живёт только на уровне типов —
4148
+ // приведение на границе внешнего API не меняет поведение.
3262
4149
  editor.add({
3263
4150
  id: skill.id,
3264
4151
  name: skill.name,
@@ -3286,7 +4173,12 @@ const v2Plugin = Plugin.define({
3286
4173
  },
3287
4174
  create_task: async (input) => {
3288
4175
  console.log("[agent-steward] create_task input:", input);
3289
- const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, runWhenLoggedOff, legacyShell, } = input;
4176
+ // QA-P2.1: RPC обходит MCP/Zod — проверяем диапазоны явно.
4177
+ const rangeError = validateTaskInputRanges(input);
4178
+ if (rangeError) {
4179
+ return { success: false, message: rangeError };
4180
+ }
4181
+ const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, runWhenLoggedOff, legacyShell, worktree, guards, tokenBudget, } = input;
3290
4182
  let effectiveRunAt;
3291
4183
  if (triggerType === "once") {
3292
4184
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
@@ -3309,7 +4201,9 @@ const v2Plugin = Plugin.define({
3309
4201
  }
3310
4202
  const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
3311
4203
  try {
3312
- await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, undefined, runWhenLoggedOff === true, undefined, legacyShell === true);
4204
+ await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, undefined, runWhenLoggedOff === true, undefined, legacyShell === true, worktree === true, guards,
4205
+ // QA-P0.1 (E-2.1): создание через дашборд/RPC сохраняет tokenBudget.
4206
+ tokenBudget);
3313
4207
  const nextRun = computeTaskNextRun({
3314
4208
  schedule: schedule ?? "",
3315
4209
  triggerType: triggerType ?? "cron",
@@ -3388,8 +4282,25 @@ const v2Plugin = Plugin.define({
3388
4282
  run_task: async (input) => {
3389
4283
  const { name } = input;
3390
4284
  try {
4285
+ const budgetGate = await checkBudgetGate();
4286
+ if (!budgetGate.allowed) {
4287
+ return {
4288
+ success: false,
4289
+ message: formatBudgetSkipMessage(budgetGate),
4290
+ };
4291
+ }
3391
4292
  // Matrix-родитель не выполняется сам: запускаем его клоны (fan-out).
3392
4293
  const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === name.trim().toLowerCase());
4294
+ // E-2.2: тот же персональный токен-гейт, что и в runTaskEntry.
4295
+ if (definition?.tokenBudget) {
4296
+ const taskGate = checkTaskTokenBudgetGate(name, definition.tokenBudget);
4297
+ if (!taskGate.allowed) {
4298
+ return {
4299
+ success: false,
4300
+ message: formatTaskTokenBudgetSkipMessage(taskGate),
4301
+ };
4302
+ }
4303
+ }
3393
4304
  if (definition?.matrix) {
3394
4305
  const matrixResult = await runMatrix(definition);
3395
4306
  const total = definition.matrix.workspaceIds.length;
@@ -3436,35 +4347,53 @@ const v2Plugin = Plugin.define({
3436
4347
  return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
3437
4348
  }
3438
4349
  },
3439
- emit_event: async (input) => {
3440
- const { eventName, payload } = input;
3441
- const normalized = eventName?.trim();
3442
- if (!normalized) {
3443
- return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
3444
- }
3445
- // Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
3446
- const definitions = await loadTaskDefinitions();
3447
- const matched = definitions
3448
- .filter((def) => (def.triggerType ?? "cron") === "mcp-event")
3449
- .filter((def) => def.mcpEvent?.event?.trim().toLowerCase() === normalized.toLowerCase())
3450
- .filter((def) => matchesEventFilter(def.mcpEvent?.filter, payload))
3451
- .sort((a, b) => (normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5));
3452
- const triggered = [];
3453
- for (const def of matched) {
3454
- try {
3455
- await runTaskEntry(def.name);
3456
- triggered.push(def.name);
3457
- console.log(`[agent-steward] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`);
3458
- }
3459
- catch (err) {
3460
- console.error(`[agent-steward] Не удалось запустить "${def.name}" по событию "${normalized}": ${err instanceof Error ? err.message : String(err)}`);
4350
+ run_mission: async (input) => {
4351
+ try {
4352
+ const budgetGate = await checkBudgetGate();
4353
+ if (!budgetGate.allowed) {
4354
+ return {
4355
+ success: false,
4356
+ dryRun: false,
4357
+ runId: "",
4358
+ status: "failed",
4359
+ description: "",
4360
+ error: formatBudgetSkipMessage(budgetGate),
4361
+ steps: [],
4362
+ };
3461
4363
  }
4364
+ const mission = await runMission(input);
4365
+ return {
4366
+ success: mission.success,
4367
+ dryRun: mission.dryRun,
4368
+ runId: mission.runId ?? "",
4369
+ status: mission.status,
4370
+ description: mission.description,
4371
+ ...(mission.error ? { error: mission.error } : {}),
4372
+ steps: mission.steps.map((step) => ({
4373
+ stepName: step.stepName,
4374
+ taskType: step.taskType,
4375
+ target: step.target,
4376
+ status: step.status,
4377
+ attempt: step.attempt,
4378
+ ...(step.error ? { error: step.error } : {}),
4379
+ })),
4380
+ };
4381
+ }
4382
+ catch (err) {
4383
+ return {
4384
+ success: false,
4385
+ dryRun: false,
4386
+ runId: "",
4387
+ status: "failed",
4388
+ description: "",
4389
+ error: err instanceof Error ? err.message : String(err),
4390
+ steps: [],
4391
+ };
3462
4392
  }
3463
- return {
3464
- success: true,
3465
- triggered,
3466
- message: t("tool.event.processed", { event: normalized, count: triggered.length }),
3467
- };
4393
+ },
4394
+ emit_event: async (input) => {
4395
+ const { eventName, payload, server } = input;
4396
+ return await emitEventCore(eventName, payload, server);
3468
4397
  },
3469
4398
  pause_task: async (input) => {
3470
4399
  const { name, until } = input;
@@ -3480,8 +4409,12 @@ const v2Plugin = Plugin.define({
3480
4409
  return await updateTaskFromInput(input);
3481
4410
  },
3482
4411
  get_task_logs: async (input) => {
3483
- const { name } = input;
3484
- const result = await getTaskLogs(name);
4412
+ const { name, taskName } = input;
4413
+ const resolved = name?.trim() || taskName?.trim();
4414
+ if (!resolved) {
4415
+ return { success: false, logs: "", error: "Укажите name или taskName задачи" };
4416
+ }
4417
+ const result = await getTaskLogs(resolved);
3485
4418
  if (result.error) {
3486
4419
  return { success: false, logs: "", error: result.error };
3487
4420
  }
@@ -3498,7 +4431,10 @@ const v2Plugin = Plugin.define({
3498
4431
  return { records };
3499
4432
  },
3500
4433
  get_metrics: async () => {
3501
- return await loadMetrics();
4434
+ const metrics = await loadMetrics();
4435
+ const since = new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString();
4436
+ const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
4437
+ return { ...metrics, toolBlocked };
3502
4438
  },
3503
4439
  cleanup_history: async (input) => {
3504
4440
  const { retentionDays, maxRecords } = input;
@@ -3544,17 +4480,24 @@ const v2Plugin = Plugin.define({
3544
4480
  const { days, topLimit } = input;
3545
4481
  try {
3546
4482
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(days) || 14)));
3547
- const records = getHistory(null, 20000);
4483
+ const records = getHistoryForAnalytics(windowDays);
3548
4484
  const definitions = await loadTaskDefinitions();
3549
4485
  const report = buildAnalytics(records, {
3550
4486
  days: windowDays,
3551
4487
  topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
3552
- tasks: definitions.map((definition) => ({
4488
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
3553
4489
  name: definition.name,
3554
4490
  matrixParentId: definition.matrixParentId,
4491
+ tokenBudget: definition.tokenBudget,
3555
4492
  })),
3556
4493
  });
3557
- return { success: true, report };
4494
+ // Экономика v2 (E-1.1): тот же учёт, что и в агент-инструменте.
4495
+ const settings = await loadSettings();
4496
+ const budgets = buildBudgetReport(records, settings.budgets, new Date());
4497
+ // PL-4.1: та же метрика корректности прав, что и в MCP get_analytics.
4498
+ const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1000).toISOString();
4499
+ const toolBlocked = readAuditLog({ action: "tool.blocked", since, limit: 1 }).total;
4500
+ return { success: true, report: { ...report, budgets, toolBlocked } };
3558
4501
  }
3559
4502
  catch (err) {
3560
4503
  return {
@@ -3568,14 +4511,15 @@ const v2Plugin = Plugin.define({
3568
4511
  const { days, topLimit, includeAnomalies, includeTrends, includeRecommendations } = input;
3569
4512
  try {
3570
4513
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(days) || 14)));
3571
- const records = getHistory(null, 20000);
4514
+ const records = getHistoryForAnalytics(windowDays);
3572
4515
  const definitions = await loadTaskDefinitions();
3573
4516
  const report = generateSelfAnalysisReport(records, {
3574
4517
  days: windowDays,
3575
4518
  topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
3576
- tasks: definitions.map((definition) => ({
4519
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
3577
4520
  name: definition.name,
3578
4521
  matrixParentId: definition.matrixParentId,
4522
+ tokenBudget: definition.tokenBudget,
3579
4523
  })),
3580
4524
  });
3581
4525
  // Фильтруем секции если нужно
@@ -3605,6 +4549,55 @@ const v2Plugin = Plugin.define({
3605
4549
  };
3606
4550
  }
3607
4551
  },
4552
+ report_bug: async (input) => {
4553
+ const { description, taskName, includeLogs, includeAnalytics, channel, destination, contactEmail, dryRun, } = input;
4554
+ try {
4555
+ if (!description || !description.trim()) {
4556
+ return { success: false, error: "description is required" };
4557
+ }
4558
+ const settings = await loadSettings();
4559
+ const logsAllowed = includeLogs ?? settings.feedback.includeLogs;
4560
+ const built = await buildBugReportText({
4561
+ description,
4562
+ taskName,
4563
+ includeLogs: logsAllowed,
4564
+ includeAnalytics,
4565
+ });
4566
+ const secretValues = collectSecretValues();
4567
+ const localText = redactText(built.text, {
4568
+ secrets: secretValues,
4569
+ redactEmails: false,
4570
+ });
4571
+ const result = await reportFeedback({
4572
+ settings: settings.feedback,
4573
+ destination: destination ?? "author",
4574
+ dryRun,
4575
+ description,
4576
+ taskName,
4577
+ contactEmail: contactEmail ?? settings.feedback.contactEmail,
4578
+ redactedLogs: logsAllowed ? built.logs : undefined,
4579
+ metrics: built.metrics,
4580
+ locale: settings.locale,
4581
+ secrets: secretValues,
4582
+ sendLocal: (text) => sendBugReport(text, channel),
4583
+ localText,
4584
+ });
4585
+ return {
4586
+ success: result.success,
4587
+ reportId: result.reportId,
4588
+ mode: result.mode,
4589
+ preview: result.preview,
4590
+ error: result.error,
4591
+ author: result.author,
4592
+ };
4593
+ }
4594
+ catch (err) {
4595
+ return {
4596
+ success: false,
4597
+ error: err instanceof Error ? err.message : String(err),
4598
+ };
4599
+ }
4600
+ },
3608
4601
  get_dashboard_port: async () => {
3609
4602
  return { port: getDashboardPort() };
3610
4603
  },
@@ -3650,6 +4643,24 @@ const v2Plugin = Plugin.define({
3650
4643
  }
3651
4644
  return { success: allSuccess, reports };
3652
4645
  },
4646
+ pipeline_validate: async (input) => {
4647
+ const { path, source, dryRun } = input;
4648
+ const result = await pipelineValidateExecute({ path, source, dryRun }, {});
4649
+ const parsed = JSON.parse(result.content);
4650
+ return parsed;
4651
+ },
4652
+ pipeline_apply: async (input) => {
4653
+ const { path, source, dryRun } = input;
4654
+ const result = await pipelineApplyExecute({ path, source, dryRun }, {});
4655
+ const parsed = JSON.parse(result.content);
4656
+ return parsed;
4657
+ },
4658
+ pipeline_export: async (input) => {
4659
+ const { pipeline, pipelineName } = input;
4660
+ const result = await pipelineExportExecute({ pipeline: pipeline ?? pipelineName }, {});
4661
+ const parsed = JSON.parse(result.content);
4662
+ return parsed;
4663
+ },
3653
4664
  get_matrix_results: async (input) => {
3654
4665
  const { parentId } = input;
3655
4666
  const target = (parentId ?? "").trim();
@@ -3836,7 +4847,7 @@ const v2Plugin = Plugin.define({
3836
4847
  return await loadSettings();
3837
4848
  },
3838
4849
  save_settings: async (input) => {
3839
- const { maxConcurrent, locale, uiLocale, winterMode, notifications, history, integrations, audit, permissions } = input;
4850
+ const { maxConcurrent, locale, uiLocale, winterMode, notifications, history, integrations, audit, permissions, budgets, feedback } = input;
3840
4851
  const current = await loadSettings();
3841
4852
  if (maxConcurrent === undefined &&
3842
4853
  locale === undefined &&
@@ -3846,7 +4857,9 @@ const v2Plugin = Plugin.define({
3846
4857
  history === undefined &&
3847
4858
  integrations === undefined &&
3848
4859
  audit === undefined &&
3849
- permissions === undefined) {
4860
+ permissions === undefined &&
4861
+ budgets === undefined &&
4862
+ feedback === undefined) {
3850
4863
  return {
3851
4864
  success: false,
3852
4865
  maxConcurrent: current.maxConcurrent,
@@ -3858,6 +4871,8 @@ const v2Plugin = Plugin.define({
3858
4871
  integrations: current.integrations,
3859
4872
  audit: current.audit,
3860
4873
  permissions: current.permissions,
4874
+ budgets: current.budgets,
4875
+ feedback: current.feedback,
3861
4876
  };
3862
4877
  }
3863
4878
  const settings = await saveSettings({
@@ -3870,6 +4885,8 @@ const v2Plugin = Plugin.define({
3870
4885
  integrations,
3871
4886
  audit,
3872
4887
  permissions,
4888
+ budgets,
4889
+ feedback,
3873
4890
  });
3874
4891
  // Локаль процесса меняется сразу — перезапуск не нужен.
3875
4892
  setLocale(resolveLocale(settings.locale, settings.uiLocale));
@@ -3884,6 +4901,8 @@ const v2Plugin = Plugin.define({
3884
4901
  integrations: settings.integrations,
3885
4902
  audit: settings.audit,
3886
4903
  permissions: settings.permissions,
4904
+ budgets: settings.budgets,
4905
+ feedback: settings.feedback,
3887
4906
  };
3888
4907
  },
3889
4908
  test_notification: async () => {
@@ -3996,6 +5015,10 @@ const v2Plugin = Plugin.define({
3996
5015
  },
3997
5016
  get_audit: async (input) => {
3998
5017
  const source = (input ?? {});
5018
+ const dateError = auditDateFilterError(source.since, "since") ??
5019
+ auditDateFilterError(source.until, "until");
5020
+ if (dateError)
5021
+ return { success: false, message: dateError };
3999
5022
  const result = readAuditLog({
4000
5023
  action: source.action,
4001
5024
  target: source.target,
@@ -4087,6 +5110,12 @@ const v2Plugin = Plugin.define({
4087
5110
  return { success: false, error: t("tool.template.needId") };
4088
5111
  }
4089
5112
  try {
5113
+ // QA-P3.3: принимаем и id, и имя шаблона; отсутствие — явная ошибка.
5114
+ const templates = await loadTemplates();
5115
+ const existed = templates.some((template) => template.id === id || template.name === id);
5116
+ if (!existed) {
5117
+ return { success: false, error: t("tool.template.notFound", { id }) };
5118
+ }
4090
5119
  await deleteTemplate(id);
4091
5120
  return { success: true };
4092
5121
  }
@@ -4138,7 +5167,9 @@ const v2Plugin = Plugin.define({
4138
5167
  gitPaths: def.gitPaths,
4139
5168
  gitIgnore: def.gitIgnore,
4140
5169
  gitPollSeconds: def.gitPollSeconds,
4141
- }, def.runWhenLoggedOff === true, def.paused === true, def.legacyShell === true);
5170
+ }, def.runWhenLoggedOff === true, def.paused === true, def.legacyShell === true, def.worktree === true, def.guards,
5171
+ // QA-P0.1 (E-2.1): импорт через RPC сохраняет tokenBudget.
5172
+ def.tokenBudget);
4142
5173
  await saveTaskDefinition(def);
4143
5174
  imported.push(def.name);
4144
5175
  }
@@ -4171,27 +5202,31 @@ const v2Plugin = Plugin.define({
4171
5202
  ]);
4172
5203
  },
4173
5204
  });
4174
- /**
4175
- * Приводит результат V2-обработчика (`Tool.Result`) к формату V1 (`ToolResult`).
4176
- * V1 ждёт строку или `{ output, metadata }`; V2 отдаёт `{ content }`.
4177
- */
5205
+ /** Сужает элемент content до текстового блока (остальные типы V2 не нас интересуют). */
5206
+ function isTextContent(part) {
5207
+ return (typeof part === "object" &&
5208
+ part !== null &&
5209
+ "type" in part &&
5210
+ part.type === "text" &&
5211
+ "text" in part &&
5212
+ typeof part.text === "string");
5213
+ }
4178
5214
  export function toV1ToolResult(result) {
4179
5215
  if (typeof result === "string")
4180
5216
  return result;
4181
- if (Array.isArray(result?.content)) {
4182
- const text = result.content
4183
- .filter((part) => part?.type === "text" && typeof part.text === "string")
4184
- .map((part) => part.text)
4185
- .join("\n");
4186
- return { output: text, metadata: result.metadata };
5217
+ const metadata = result.metadata;
5218
+ const content = result.content;
5219
+ if (Array.isArray(content)) {
5220
+ const text = content.filter(isTextContent).map((part) => part.text).join("\n");
5221
+ return { output: text, metadata };
4187
5222
  }
4188
- if (typeof result?.content === "string") {
4189
- return { output: result.content, metadata: result.metadata };
5223
+ if (typeof content === "string") {
5224
+ return { output: content, metadata };
4190
5225
  }
4191
- if (typeof result?.output === "string") {
4192
- return { output: result.output, metadata: result.metadata };
5226
+ if (typeof result.output === "string") {
5227
+ return { output: result.output, metadata };
4193
5228
  }
4194
- return { output: JSON.stringify(result), metadata: result?.metadata };
5229
+ return { output: JSON.stringify(result), metadata };
4195
5230
  }
4196
5231
  /**
4197
5232
  * V1 `tool()` принимает `z.ZodRawShape`, а спецификации хранят `z.object(...)`.
@@ -4204,11 +5239,6 @@ export function toV1ToolArgs(spec) {
4204
5239
  }
4205
5240
  return shape;
4206
5241
  }
4207
- /**
4208
- * V1-реестр инструментов: те же имена, описания, схемы и обработчики, что в
4209
- * V2, плюс тот же аудит. Отличие одно — у V1 `tool()` нет `codemode`, поэтому
4210
- * флаг не передаётся (см. docs/COMPATIBILITY.md).
4211
- */
4212
5242
  export function createV1Tools(runtime) {
4213
5243
  const tools = {};
4214
5244
  for (const spec of createToolSpecs(runtime)) {
@@ -4218,7 +5248,7 @@ export function createV1Tools(runtime) {
4218
5248
  tools[spec.name] = v1Tool({
4219
5249
  description: spec.description,
4220
5250
  args: toV1ToolArgs(spec),
4221
- execute: (async (args, context) => toV1ToolResult(await execute(args, context))),
5251
+ execute: async (args, context) => toV1ToolResult(await execute(args, context)),
4222
5252
  });
4223
5253
  }
4224
5254
  return tools;
@@ -4231,12 +5261,20 @@ export function createV1Tools(runtime) {
4231
5261
  * `createShutdownHandler`. GUI/RPC/скиллы — только V2, здесь их нет.
4232
5262
  */
4233
5263
  export async function createV1Hooks(input = { directory: process.cwd() }, options = {}) {
5264
+ if (isChildRunMode()) {
5265
+ console.log(`[qv8] ${CHILD_RUN_ENV}: дочерний прогон, пропускаю регистрацию плагина`);
5266
+ return { tool: {}, dispose: async () => undefined };
5267
+ }
5268
+ // PL-45: см. V2 setup — повторная регистрация должна открывать ворота.
5269
+ shutdownGate.reset();
4234
5270
  const runtime = await createRuntime({ location: { directory: input.directory } });
4235
5271
  const tools = createV1Tools(runtime);
4236
5272
  if (options.startDashboard !== false) {
4237
5273
  await startSchedulerDashboard();
4238
5274
  }
4239
5275
  return {
5276
+ // QA-A2.1: граница внешнего V1 API — у плагина отдельная копия zod,
5277
+ // типы несовместимы структурно. Значения и поведение не меняются.
4240
5278
  tool: tools,
4241
5279
  dispose: createShutdownHandler(runtime),
4242
5280
  };
@@ -4308,7 +5346,22 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
4308
5346
  }
4309
5347
  return extra;
4310
5348
  }
4311
- async function schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, matrixParentId,
5349
+ /**
5350
+ * PL-42: приводит mcpEvent к каноническому виду `{ server, event, filter? }`.
5351
+ * `event` имеет приоритет: если заданы оба поля и они различаются, alias
5352
+ * `eventName` игнорируется — так поведение старых задач не меняется.
5353
+ */
5354
+ export function normalizeMcpEventTrigger(mcpEvent) {
5355
+ const rawEvent = mcpEvent?.event?.trim() || mcpEvent?.eventName?.trim();
5356
+ if (!rawEvent)
5357
+ return undefined;
5358
+ return {
5359
+ server: mcpEvent?.server?.trim() || "",
5360
+ event: rawEvent,
5361
+ ...(mcpEvent?.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
5362
+ };
5363
+ }
5364
+ export async function schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, matrixParentId,
4312
5365
  /** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
4313
5366
  matrixMode = "create",
4314
5367
  /** IANA-зона задачи (Спринт 19). Не системная зона → poll-режим шлюза. */
@@ -4340,7 +5393,13 @@ paused,
4340
5393
  * Спринт 32 / релиз 1.6: переходный флаг для гибридной политики.
4341
5394
  * true возвращает shell задаче, созданной до обновления поведения.
4342
5395
  */
4343
- legacyShell) {
5396
+ legacyShell,
5397
+ /** W-1: одноразовый git worktree на каждый запуск. */
5398
+ worktree,
5399
+ /** W-3: guard-условия перед запуском opencode. */
5400
+ guards,
5401
+ /** Economics v2 (E-2): per-run token budget. 0/omitted = no limit (fail-open). */
5402
+ tokenBudget) {
4344
5403
  // Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
4345
5404
  // в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
4346
5405
  // schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
@@ -4396,6 +5455,18 @@ legacyShell) {
4396
5455
  const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
4397
5456
  // Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
4398
5457
  const normalizedPaused = paused === true ? true : undefined;
5458
+ // W-1: изоляция запуска в одноразовом git worktree.
5459
+ const normalizedWorktree = worktree === true ? true : undefined;
5460
+ // W-3: guard-условия. Ошибка нормализации — явная ошибка создания задачи,
5461
+ // чтобы опечатка в конфигурации не превратилась в молчаливый пропуск.
5462
+ const guardsResult = normalizeTaskGuards(guards);
5463
+ if (!guardsResult.ok)
5464
+ throw new Error(guardsResult.error);
5465
+ const normalizedGuards = guardsResult.guards;
5466
+ // Economics v2 (E-2): нормализация бюджета токенов. 0/отрицание/NaN = без лимита.
5467
+ const normalizedTokenBudget = Number.isFinite(tokenBudget) && (tokenBudget ?? 0) > 0
5468
+ ? Math.floor(tokenBudget)
5469
+ : undefined;
4399
5470
  // Спринт 27: дни недели, политика окна и glob/git-фильтры.
4400
5471
  const normalizeGlobList = (raw) => {
4401
5472
  if (!Array.isArray(raw))
@@ -4420,13 +5491,9 @@ legacyShell) {
4420
5491
  triggerExtras.gitPollSeconds >= 5
4421
5492
  ? Math.floor(triggerExtras.gitPollSeconds)
4422
5493
  : undefined;
4423
- const normalizedMcpEvent = mcpEvent?.event?.trim()
4424
- ? {
4425
- server: mcpEvent.server?.trim() || "",
4426
- event: mcpEvent.event.trim(),
4427
- ...(mcpEvent.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
4428
- }
4429
- : undefined;
5494
+ // PL-42: mcpEvent принимает event и его алиас eventName (emit_event).
5495
+ // event приоритетнее: если оба заданы и различаются, побеждает event.
5496
+ const normalizedMcpEvent = normalizeMcpEventTrigger(mcpEvent);
4430
5497
  let effectiveTriggerType = triggerType ?? "cron";
4431
5498
  // One-shot: нормализуем время до создания файлов и задачи в ОС.
4432
5499
  // Для остальных триггеров runAt не имеет смысла и отбрасывается.
@@ -4562,7 +5629,7 @@ legacyShell) {
4562
5629
  parseCron(schedule);
4563
5630
  }
4564
5631
  catch (err) {
4565
- throw new Error(err.message || String(err));
5632
+ throw new Error(err instanceof Error ? err.message : String(err));
4566
5633
  }
4567
5634
  if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
4568
5635
  throw new Error(t("tool.error.timezone", {
@@ -4649,7 +5716,7 @@ legacyShell) {
4649
5716
  effectiveWatchPath = normalizeWatchPath(effectiveWatchPath, effectiveWorkingDirectory);
4650
5717
  }
4651
5718
  catch (err) {
4652
- throw new Error(t("tool.error.taskReason", { name, error: err.message || String(err) }));
5719
+ throw new Error(t("tool.error.taskReason", { name, error: err instanceof Error ? err.message : String(err) }));
4653
5720
  }
4654
5721
  }
4655
5722
  try {
@@ -4657,7 +5724,7 @@ legacyShell) {
4657
5724
  validateWatchGlobs(normalizedWatchIgnore);
4658
5725
  }
4659
5726
  catch (err) {
4660
- throw new Error(t("tool.error.taskReason", { name, error: err.message || String(err) }));
5727
+ throw new Error(t("tool.error.taskReason", { name, error: err instanceof Error ? err.message : String(err) }));
4661
5728
  }
4662
5729
  // Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
4663
5730
  // Спринт 29.3: инжектит в env только реально используемые секреты (scoped-инъекция).
@@ -4670,11 +5737,16 @@ legacyShell) {
4670
5737
  try {
4671
5738
  promptFile = await writePromptFile(sanitized, prompt);
4672
5739
  await fs.mkdir(LOG_DIR, { recursive: true });
4673
- await fs.writeFile(logFile, "", "utf8");
5740
+ // Не обнуляем лог: при падении до запуска обёртки (или при отказе модели)
5741
+ // предыдущий диагностический вывод оставался бы единственным, а новый
5742
+ // прогон выглядел бы как «лог пуст». Дописываем маркер ПОДГОТОВКИ —
5743
+ // задача создана, но ещё не запускалась (не путать с реальным Run started,
5744
+ // который пишется обёрткой только при фактическом запуске; QA #8).
5745
+ await fs.appendFile(logFile, formatLogRunMarker("prepare", name), "utf8");
4674
5746
  }
4675
5747
  catch (err) {
4676
5748
  throw new Error(t("tool.error.prepareFiles", {
4677
- error: err.message || String(err),
5749
+ error: err instanceof Error ? err.message : String(err),
4678
5750
  }));
4679
5751
  }
4680
5752
  // Обёртка зависит от платформы:
@@ -4687,7 +5759,7 @@ legacyShell) {
4687
5759
  try {
4688
5760
  if (scheduler.platform === "win32") {
4689
5761
  await ensureWrapper();
4690
- wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile, effectiveSession, effectiveSessionId, retryCount, retryDelay, undefined, permissionsConfig, policyMeta, sessionFile);
5762
+ wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile, effectiveSession, effectiveSessionId, undefined, permissionsConfig, policyMeta, sessionFile, normalizedWorktree, worktreeHelperPath, normalizedGuards, guardHelperPath, gateAllowPathsFromAfterScript(normalizedAfter));
4691
5763
  }
4692
5764
  else {
4693
5765
  wrapperPath = await writeBashWrapper({
@@ -4713,6 +5785,11 @@ legacyShell) {
4713
5785
  sessionMode: effectiveSession,
4714
5786
  sessionId: effectiveSessionId,
4715
5787
  sessionFile,
5788
+ worktree: normalizedWorktree,
5789
+ worktreeHelper: worktreeHelperPath,
5790
+ guards: normalizedGuards,
5791
+ guardHelper: guardHelperPath,
5792
+ gateAllowPaths: gateAllowPathsFromAfterScript(normalizedAfter),
4716
5793
  ...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
4717
5794
  ? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized, getProfileName()) }
4718
5795
  : {}),
@@ -4721,7 +5798,7 @@ legacyShell) {
4721
5798
  }
4722
5799
  catch (err) {
4723
5800
  throw new Error(t("tool.error.wrapper", {
4724
- error: err.message || String(err),
5801
+ error: err instanceof Error ? err.message : String(err),
4725
5802
  }));
4726
5803
  }
4727
5804
  // 27.5.5.3: при сбое создания новой задачи убираем подготовленные файлы.
@@ -4840,6 +5917,9 @@ legacyShell) {
4840
5917
  allowedTools: normalizedAllowedTools,
4841
5918
  deniedTools: normalizedDeniedTools,
4842
5919
  legacyShell: legacyShell === true ? true : undefined,
5920
+ worktree: normalizedWorktree,
5921
+ guards: normalizedGuards,
5922
+ tokenBudget: normalizedTokenBudget,
4843
5923
  matrix: normalizedMatrix,
4844
5924
  isMatrixParent: normalizedMatrix ? true : undefined,
4845
5925
  matrixParentId,
@@ -4871,7 +5951,9 @@ legacyShell) {
4871
5951
  // с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
4872
5952
  if (normalizedMatrix) {
4873
5953
  const createClone = async (clone) => {
4874
- await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell);
5954
+ await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell, clone.worktree, clone.guards,
5955
+ // QA-P0.1 (E-2.1): клон матрицы наследует tokenBudget родителя.
5956
+ clone.tokenBudget);
4875
5957
  };
4876
5958
  const removeChild = async (child) => {
4877
5959
  try {
@@ -5022,22 +6104,90 @@ async function recreateTaskFromDefinition(definition) {
5022
6104
  gitPaths: definition.gitPaths,
5023
6105
  gitIgnore: definition.gitIgnore,
5024
6106
  gitPollSeconds: definition.gitPollSeconds,
5025
- }, definition.runWhenLoggedOff, paused, definition.legacyShell);
6107
+ }, definition.runWhenLoggedOff, paused, definition.legacyShell, definition.worktree, definition.guards,
6108
+ // QA-P0.1 (E-2.1): откат update не теряет tokenBudget.
6109
+ definition.tokenBudget);
5026
6110
  }
5027
6111
  /**
5028
6112
  * Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
5029
6113
  * на клоны, а не выполняет свой промпт.
5030
6114
  */
6115
+ /** E-1.2: общий гейт бюджета для всех входов запуска задач. */
6116
+ async function checkBudgetGate(now = new Date()) {
6117
+ const settings = await loadSettings();
6118
+ // Неделя — widest период бюджетов. Выбираем записи по моменту завершения
6119
+ // (см. getHistoryForBudget), чтобы не зависеть от окна в 20000 запусков.
6120
+ const records = getHistoryForBudget(startOfUtcWeek(now).toISOString());
6121
+ const decision = evaluateBudgetGate(records, settings.budgets, now);
6122
+ if (!decision.allowed) {
6123
+ // E-1.3: алерт не должен задерживать или ломать запуск.
6124
+ void notifyBudgetExceeded(decision).catch((err) => {
6125
+ console.error(`[agent-steward] Ошибка бюджетного алерта: ${err instanceof Error ? err.message : String(err)}`);
6126
+ });
6127
+ }
6128
+ return decision;
6129
+ }
6130
+ /**
6131
+ * E-2.2: гейт персонального токен-бюджета задачи.
6132
+ *
6133
+ * Зеркалит общий бюджетный гейт E-1.2, но читает лимит из определения задачи
6134
+ * и фильтрует историю по её имени. Fail-open: без лимита запуск не блокируется.
6135
+ */
6136
+ function checkTaskTokenBudgetGate(taskName, tokenBudget, now = new Date()) {
6137
+ const records = getHistoryForBudget(startOfUtcWeek(now).toISOString());
6138
+ return evaluateTaskTokenBudgetGate(records, taskName, tokenBudget, now);
6139
+ }
6140
+ /**
6141
+ * PL-1.1: структурированная ошибка отказа запуска во время выгрузки плагина.
6142
+ * Текст `message` сохранён дословно для совместимости с существующими
6143
+ * вызывающими; `code` и `hint` дают кнопке повтора/оператору понятный путь.
6144
+ */
6145
+ export class PluginShutdownError extends Error {
6146
+ constructor(message, hint, state) {
6147
+ super(message);
6148
+ this.code = "PLUGIN_SHUTTING_DOWN";
6149
+ /** PL-45: повтор возможен после перерегистрации плагина. */
6150
+ this.retryable = true;
6151
+ this.name = "PluginShutdownError";
6152
+ this.hint = hint;
6153
+ this.state = state;
6154
+ }
6155
+ }
5031
6156
  async function runTaskEntry(name) {
5032
6157
  if (shutdownGate.isShuttingDown()) {
5033
- throw new Error("Плагин выгружается: новые запуски не принимаются. Повторите после перезапуска.");
6158
+ throw new PluginShutdownError("Плагин выгружается: новые запуски не принимаются. Повторите после перезапуска.", "Повторите запуск после перезапуска плагина. Для once/cron-задач используйте force-маркер locks/<slug>.lock.force + Start-ScheduledTask (schtasks /run) либо отложенный запуск после перезапуска.", shutdownGate.state());
6159
+ }
6160
+ const budgetGate = await checkBudgetGate();
6161
+ if (!budgetGate.allowed) {
6162
+ throw new Error(formatBudgetSkipMessage(budgetGate));
5034
6163
  }
5035
6164
  const run = (async () => {
5036
- const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === name.trim().toLowerCase());
6165
+ const trimmed = name.trim();
6166
+ const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === trimmed.toLowerCase());
6167
+ // E-2.2: остановка задачи при превышении её персонального токен-бюджета.
6168
+ // Пропускаем новые запуски, если завершённый прогон за текущий UTC-день
6169
+ // или неделю уже превысил tokenBudget (fail-open, как и E-1.2).
6170
+ if (definition?.tokenBudget) {
6171
+ const taskGate = checkTaskTokenBudgetGate(trimmed, definition.tokenBudget);
6172
+ if (!taskGate.allowed) {
6173
+ throw new Error(formatTaskTokenBudgetSkipMessage(taskGate));
6174
+ }
6175
+ }
5037
6176
  if (definition?.matrix) {
5038
6177
  await runMatrix(definition);
5039
6178
  return { alreadyRunning: false };
5040
6179
  }
6180
+ // QA-P3.6: если задачи нет ни в определениях, ни в планировщике ОС,
6181
+ // не дёргаем schtasks /run — он возвращает сырую ошибку ОС. Возвращаем
6182
+ // структурированное «задача не найдена», как и остальные инструменты.
6183
+ // Legacy-задачи, живущие только в ОС (без definition), остаются запускаемыми.
6184
+ if (!definition) {
6185
+ const osTasks = await scheduler.listTasks().catch(() => []);
6186
+ const osExists = osTasks.some((task) => (task.taskName ?? "").toLowerCase() === trimmed.toLowerCase());
6187
+ if (!osExists) {
6188
+ throw new Error(t("tool.error.taskNotFound", { name: trimmed }));
6189
+ }
6190
+ }
5041
6191
  // Любой запуск через этот вход — «сейчас», а не «по расписанию»:
5042
6192
  // run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
5043
6193
  // Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
@@ -5241,6 +6391,8 @@ async function collectTasksView() {
5241
6391
  deniedTools: Array.isArray(def?.deniedTools) ? def.deniedTools : null,
5242
6392
  matrix: def?.matrix ?? null,
5243
6393
  matrixParentId: def?.matrixParentId ?? null,
6394
+ /** Экономика v2 (E-2): лимит токенов на запуск для аналитики дашборда. */
6395
+ tokenBudget: def?.tokenBudget ?? null,
5244
6396
  isMatrixParent: Boolean(def?.matrix),
5245
6397
  matrixSummary: matrixAggregate
5246
6398
  ? {