agent-steward 0.0.5 → 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 (191) hide show
  1. package/CHANGELOG.md +176 -1
  2. package/README.md +9 -7
  3. package/ROADMAP-STRATEGY.md +5 -5
  4. package/ROADMAP.md +107 -17
  5. package/dist/cli.js +5 -0
  6. package/dist/core/analytics.d.ts +6 -0
  7. package/dist/core/analytics.d.ts.map +1 -1
  8. package/dist/core/analytics.js +20 -3
  9. package/dist/core/audit.d.ts +6 -0
  10. package/dist/core/audit.d.ts.map +1 -1
  11. package/dist/core/audit.js +24 -0
  12. package/dist/core/budget.d.ts +118 -0
  13. package/dist/core/budget.d.ts.map +1 -0
  14. package/dist/core/budget.js +206 -0
  15. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  16. package/dist/core/cron-to-schtasks.js +38 -0
  17. package/dist/core/dry-run.d.ts +26 -1
  18. package/dist/core/dry-run.d.ts.map +1 -1
  19. package/dist/core/dry-run.js +199 -8
  20. package/dist/core/feedback.d.ts +192 -0
  21. package/dist/core/feedback.d.ts.map +1 -0
  22. package/dist/core/feedback.js +426 -0
  23. package/dist/core/gate-integrity.d.ts +36 -0
  24. package/dist/core/gate-integrity.d.ts.map +1 -1
  25. package/dist/core/gate-integrity.js +144 -1
  26. package/dist/core/local-ai.d.ts.map +1 -1
  27. package/dist/core/local-ai.js +7 -3
  28. package/dist/core/matrix.d.ts +8 -0
  29. package/dist/core/matrix.d.ts.map +1 -1
  30. package/dist/core/matrix.js +57 -2
  31. package/dist/core/mission.d.ts +20 -0
  32. package/dist/core/mission.d.ts.map +1 -1
  33. package/dist/core/mission.js +45 -5
  34. package/dist/core/opencode-models.d.ts +2 -2
  35. package/dist/core/opencode-models.d.ts.map +1 -1
  36. package/dist/core/opencode-models.js +28 -21
  37. package/dist/core/opencode-usage.d.ts +35 -0
  38. package/dist/core/opencode-usage.d.ts.map +1 -0
  39. package/dist/core/opencode-usage.js +132 -0
  40. package/dist/core/pipeline-io.d.ts +1 -1
  41. package/dist/core/pipeline-io.d.ts.map +1 -1
  42. package/dist/core/pipeline-io.js +26 -12
  43. package/dist/core/pipeline-map.d.ts +6 -0
  44. package/dist/core/pipeline-map.d.ts.map +1 -1
  45. package/dist/core/pipeline-map.js +12 -0
  46. package/dist/core/ps-wrapper.d.ts +10 -2
  47. package/dist/core/ps-wrapper.d.ts.map +1 -1
  48. package/dist/core/ps-wrapper.js +176 -5
  49. package/dist/core/record-history.d.ts.map +1 -1
  50. package/dist/core/record-history.js +76 -4
  51. package/dist/core/run-mode.d.ts +12 -0
  52. package/dist/core/run-mode.d.ts.map +1 -0
  53. package/dist/core/run-mode.js +17 -0
  54. package/dist/core/scheduler/logs.d.ts +4 -0
  55. package/dist/core/scheduler/logs.d.ts.map +1 -1
  56. package/dist/core/scheduler/logs.js +25 -1
  57. package/dist/core/secrets.d.ts.map +1 -1
  58. package/dist/core/secrets.js +18 -8
  59. package/dist/core/self-analysis.d.ts +32 -2
  60. package/dist/core/self-analysis.d.ts.map +1 -1
  61. package/dist/core/self-analysis.js +38 -27
  62. package/dist/core/shutdown.d.ts +33 -2
  63. package/dist/core/shutdown.d.ts.map +1 -1
  64. package/dist/core/shutdown.js +58 -2
  65. package/dist/core/structured-log.d.ts +30 -0
  66. package/dist/core/structured-log.d.ts.map +1 -1
  67. package/dist/core/structured-log.js +37 -0
  68. package/dist/core/usage-surface.d.ts +25 -0
  69. package/dist/core/usage-surface.d.ts.map +1 -0
  70. package/dist/core/usage-surface.js +41 -0
  71. package/dist/core/wrappers/bash.d.ts +2 -0
  72. package/dist/core/wrappers/bash.d.ts.map +1 -1
  73. package/dist/core/wrappers/bash.js +58 -6
  74. package/dist/db/history-repo.d.ts +32 -0
  75. package/dist/db/history-repo.d.ts.map +1 -1
  76. package/dist/db/history-repo.js +85 -7
  77. package/dist/db/metrics-repo.d.ts +20 -2
  78. package/dist/db/metrics-repo.d.ts.map +1 -1
  79. package/dist/db/metrics-repo.js +33 -11
  80. package/dist/db/migrate.d.ts.map +1 -1
  81. package/dist/db/migrate.js +37 -17
  82. package/dist/db/recovery.d.ts +3 -1
  83. package/dist/db/recovery.d.ts.map +1 -1
  84. package/dist/db/recovery.js +9 -4
  85. package/dist/db/runs-repo.d.ts.map +1 -1
  86. package/dist/db/runs-repo.js +71 -56
  87. package/dist/db/schema.d.ts +2 -2
  88. package/dist/db/schema.d.ts.map +1 -1
  89. package/dist/db/schema.js +70 -1
  90. package/dist/db/templates-repo.d.ts +2 -2
  91. package/dist/db/templates-repo.d.ts.map +1 -1
  92. package/dist/db/templates-repo.js +5 -3
  93. package/dist/history.d.ts +6 -1
  94. package/dist/history.d.ts.map +1 -1
  95. package/dist/history.js +4 -2
  96. package/dist/hook-output.d.ts +2 -0
  97. package/dist/hook-output.d.ts.map +1 -0
  98. package/dist/hook-output.js +31 -0
  99. package/dist/index.d.ts +247 -53
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +999 -211
  102. package/dist/notifications.d.ts +31 -2
  103. package/dist/notifications.d.ts.map +1 -1
  104. package/dist/notifications.js +132 -13
  105. package/dist/profiles.d.ts.map +1 -1
  106. package/dist/profiles.js +66 -15
  107. package/dist/rpc.d.ts +108 -0
  108. package/dist/rpc.d.ts.map +1 -1
  109. package/dist/rpc.js +28 -0
  110. package/dist/server.d.ts +17 -2
  111. package/dist/server.d.ts.map +1 -1
  112. package/dist/server.js +77 -12
  113. package/dist/settings.d.ts +42 -0
  114. package/dist/settings.d.ts.map +1 -1
  115. package/dist/settings.js +82 -0
  116. package/dist/task-transfer.d.ts +5 -0
  117. package/dist/task-transfer.d.ts.map +1 -1
  118. package/dist/task-transfer.js +48 -3
  119. package/dist/templates.d.ts +2 -2
  120. package/dist/templates.d.ts.map +1 -1
  121. package/dist/templates.js +3 -3
  122. package/dist/types.d.ts +22 -2
  123. package/dist/types.d.ts.map +1 -1
  124. package/dist/workspaces.d.ts.map +1 -1
  125. package/dist/workspaces.js +34 -11
  126. package/docs/ARCHITECTURE.md +49 -12
  127. package/docs/COMPATIBILITY.md +2 -2
  128. package/docs/EXECUTION-LOOP.md +6 -3
  129. package/docs/FEATURES.md +65 -4
  130. package/docs/FEATURES.zh.md +45 -2
  131. package/docs/QA-A2-GUI-TUI.md +205 -0
  132. package/docs/README.ru.md +3 -3
  133. package/docs/README.zh.md +2 -2
  134. package/gui-experimental.cjs +9 -9
  135. package/locales/en.json +42 -3
  136. package/locales/ru.json +42 -3
  137. package/locales/zh.json +42 -3
  138. package/package.json +15 -2
  139. package/scripts/check-eslint-baseline.mjs +139 -0
  140. package/scripts/gen-test-plan-counters.mjs +117 -0
  141. package/scripts/github-ci-fetch.ps1 +37 -0
  142. package/scripts/pl-commit.ps1 +112 -0
  143. package/scripts/qa-a2-commit.ps1 +104 -0
  144. package/scripts/test-home.mjs +26 -2
  145. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  146. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  147. package/src/cli.ts +5 -0
  148. package/src/core/analytics.ts +27 -4
  149. package/src/core/audit.ts +25 -0
  150. package/src/core/budget.ts +340 -0
  151. package/src/core/cron-to-schtasks.ts +42 -0
  152. package/src/core/dry-run.ts +233 -10
  153. package/src/core/feedback.ts +582 -0
  154. package/src/core/gate-integrity.ts +171 -1
  155. package/src/core/local-ai.ts +7 -3
  156. package/src/core/matrix.ts +63 -2
  157. package/src/core/mission.ts +51 -5
  158. package/src/core/opencode-models.ts +30 -21
  159. package/src/core/opencode-usage.ts +182 -0
  160. package/src/core/pipeline-io.ts +28 -11
  161. package/src/core/pipeline-map.ts +19 -0
  162. package/src/core/ps-wrapper.ts +173 -4
  163. package/src/core/record-history.ts +94 -4
  164. package/src/core/run-mode.ts +19 -0
  165. package/src/core/scheduler/logs.ts +32 -1
  166. package/src/core/secrets.ts +18 -11
  167. package/src/core/self-analysis.ts +75 -29
  168. package/src/core/shutdown.ts +90 -4
  169. package/src/core/structured-log.ts +67 -0
  170. package/src/core/usage-surface.ts +70 -0
  171. package/src/core/wrappers/bash.ts +60 -5
  172. package/src/db/history-repo.ts +153 -19
  173. package/src/db/metrics-repo.ts +38 -11
  174. package/src/db/migrate.ts +57 -32
  175. package/src/db/recovery.ts +10 -4
  176. package/src/db/runs-repo.ts +113 -61
  177. package/src/db/schema.ts +70 -1
  178. package/src/db/templates-repo.ts +5 -3
  179. package/src/gui.tsx +261 -5
  180. package/src/history.ts +10 -3
  181. package/src/hook-output.ts +39 -0
  182. package/src/index.ts +1407 -345
  183. package/src/notifications.ts +189 -39
  184. package/src/profiles.ts +72 -16
  185. package/src/rpc.ts +30 -0
  186. package/src/server.ts +107 -23
  187. package/src/settings.ts +120 -0
  188. package/src/task-transfer.ts +59 -6
  189. package/src/templates.ts +3 -3
  190. package/src/types.ts +23 -2
  191. 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,35 +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
23
  import { normalizeTaskGuards } from "./core/guard.js";
20
- import { simulatePipeline } from "./core/dry-run.js";
21
- import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, findOrphanedMatrixTasks, getMatrixDeletionGuard, matrixCompleteName, planMatrixFamilyDelete, removeMatrixChildren, runMatrix, syncMatrixFamily, } from "./core/matrix.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";
22
26
  import { normalizeWatchPath, validateWatchGlobs } from "./core/watch-paths.js";
23
27
  import { createShutdownGate } from "./core/shutdown.js";
28
+ import { CHILD_RUN_ENV, isChildRunMode } from "./core/run-mode.js";
24
29
  import { SchedulerRpc } from "./rpc.js";
25
30
  import { loadPipelineFile, parsePipelineYaml, } from "./core/pipeline-io.js";
26
31
  import { planPipelineApply, } from "./core/pipeline-apply.js";
27
- import { tasksToPipelineSpec } from "./core/pipeline-map.js";
32
+ import { pipelineExportLookupError, tasksToPipelineSpec, } from "./core/pipeline-map.js";
28
33
  import { stringify as yamlStringify } from "yaml";
29
34
  import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
30
- import { defaultNotifications, loadSettings, saveSettings } from "./settings.js";
35
+ import { defaultNotifications, loadSettings, saveSettings, } from "./settings.js";
31
36
  import { resolveLocale, setLocale, t } from "./i18n.js";
32
- import { runMission } from "./core/mission.js";
37
+ import { formatLogRunMarker, runMission } from "./core/mission.js";
33
38
  import { DEFAULT_PERMISSION_POLICY, buildOpencodeConfig, resolvePermissions, } from "./core/permissions.js";
34
39
  import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
35
40
  import { buildAnalytics } from "./core/analytics.js";
41
+ import { buildBudgetReport, evaluateBudgetGate, evaluateTaskTokenBudgetGate, formatBudgetSkipMessage, formatTaskTokenBudgetSkipMessage, startOfUtcWeek, } from "./core/budget.js";
36
42
  import { generateSelfAnalysisReport } from "./core/self-analysis.js";
37
- 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";
38
45
  import { getAllMetrics } from "./db/metrics-repo.js";
39
46
  import { discardDlq, listDlq, retryDlq } from "./core/dlq-api.js";
40
47
  import { listRunPanel, pauseRunPanel, resumeRunPanel, } from "./core/run-panel-api.js";
41
- 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";
42
50
  import { shadowReport, resetShadowDecisions, } from "./core/triage-shadow.js";
43
51
  import { compareTriage } from "./core/triage-compare.js";
44
52
  import { applyLocalAiPatch, summarizeLocalAi } from "./core/local-ai.js";
@@ -47,15 +55,15 @@ import { loadTaskDefinitions, saveTaskDefinition, removeTaskDefinition, buildExp
47
55
  import { FileWatchManager } from "./core/file-watcher.js";
48
56
  import { GitTriggerManager } from "./core/git-trigger.js";
49
57
  import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
50
- import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
58
+ import { startDashboardServer, closeDashboardServer, getDashboardPort, probeDashboardOn, discoverDashboardPort, } from "./server.js";
51
59
  import { DEFAULT_PROFILE, createProfile, deleteProfile, getProfileDir, getProfileName, isProfilePinnedByEnv, listProfiles, sanitizeProfileName, setActiveProfile, } from "./profiles.js";
52
60
  import { closeDb, initDb } from "./db/index.js";
53
61
  import { migrateJsonToDb } from "./db/migrate.js";
54
62
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
55
63
  import { getTask, listMatrixClones, listTasks as listTaskDefinitions, saveTask } from "./db/tasks-repo.js";
56
64
  import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
57
- import { deleteSecret, collectSecretNames, hasSecret, listSecrets, setSecret, } from "./core/secrets.js";
58
- 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";
59
67
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
60
68
  const require = createRequire(import.meta.url);
61
69
  const resolvedRecorder = require.resolve("./core/record-history.js");
@@ -203,11 +211,67 @@ export const guardsSchema = z.object({
203
211
  .optional()
204
212
  .describe("Semantic pre-run checks inside the working directory."),
205
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
+ }
206
270
  /** Zod-схема аргументов schedule_task */
207
271
  export const scheduleTaskSchema = z.object({
208
272
  name: z
209
273
  .string()
210
- .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'."),
211
275
  schedule: z
212
276
  .string()
213
277
  .optional()
@@ -247,9 +311,13 @@ export const scheduleTaskSchema = z.object({
247
311
  .describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
248
312
  prompt: z
249
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.")
250
316
  .describe("Prompt passed to the agent on every run."),
251
317
  timeoutSeconds: z
252
318
  .number()
319
+ .int()
320
+ .positive()
253
321
  .optional()
254
322
  .describe("Run timeout in seconds (default 3600)."),
255
323
  model: z
@@ -258,6 +326,9 @@ export const scheduleTaskSchema = z.object({
258
326
  .describe("LLM model in OpenCode format, e.g. anthropic/claude-3-5-sonnet. Defaults to the OpenCode default model."),
259
327
  priority: z
260
328
  .number()
329
+ .int()
330
+ .min(0)
331
+ .max(10)
261
332
  .optional()
262
333
  .describe("Task priority 0..10 (10 is the highest). Default 5 (normal)."),
263
334
  beforeScript: z
@@ -278,10 +349,14 @@ export const scheduleTaskSchema = z.object({
278
349
  .describe("DAG dependencies: tasks that must finish successfully before this task starts."),
279
350
  retryCount: z
280
351
  .number()
352
+ .int()
353
+ .nonnegative()
281
354
  .optional()
282
355
  .describe("How many times to retry a failed run (default 0)."),
283
356
  retryDelay: z
284
357
  .number()
358
+ .int()
359
+ .nonnegative()
285
360
  .optional()
286
361
  .describe("Delay between retries in seconds (default 60)."),
287
362
  nextTaskOnSuccess: z
@@ -299,21 +374,28 @@ export const scheduleTaskSchema = z.object({
299
374
  mcpEvent: z
300
375
  .object({
301
376
  server: z.string(),
302
- 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"),
303
385
  filter: z.string().optional(),
304
386
  })
305
387
  .optional()
306
- .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."),
307
389
  watchPath: z
308
390
  .string()
309
391
  .optional()
310
392
  .describe("File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."),
311
393
  watchGlobs: z
312
- .array(z.string())
394
+ .array(globMaskSchema)
313
395
  .optional()
314
396
  .describe("Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath."),
315
397
  watchIgnore: z
316
- .array(z.string())
398
+ .array(globMaskSchema)
317
399
  .optional()
318
400
  .describe("Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include."),
319
401
  gitBranch: z
@@ -321,11 +403,11 @@ export const scheduleTaskSchema = z.object({
321
403
  .optional()
322
404
  .describe("Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch."),
323
405
  gitPaths: z
324
- .array(z.string())
406
+ .array(globMaskSchema)
325
407
  .optional()
326
408
  .describe("Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only)."),
327
409
  gitIgnore: z
328
- .array(z.string())
410
+ .array(globMaskSchema)
329
411
  .optional()
330
412
  .describe("Only for triggerType=git: glob masks of changed files to ignore."),
331
413
  gitPollSeconds: z
@@ -373,6 +455,13 @@ export const scheduleTaskSchema = z.object({
373
455
  guards: guardsSchema
374
456
  .optional()
375
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."),
376
465
  matrix: matrixSchema
377
466
  .optional()
378
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."),
@@ -408,13 +497,31 @@ export const scheduleTaskSchema = z.object({
408
497
  message: t("tool.error.onceFields"),
409
498
  });
410
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
+ }
411
508
  });
412
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
+ });
413
518
  const deleteTaskSchema = z.object({
414
519
  name: z.string().describe("Task name to delete."),
415
520
  });
416
521
  const runTaskNowSchema = z.object({
417
- 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)."),
418
525
  });
419
526
  export const updateTaskSchema = z.object({
420
527
  name: z.string().describe("Name of the task to update."),
@@ -468,11 +575,11 @@ export const updateTaskSchema = z.object({
468
575
  .optional()
469
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."),
470
577
  watchGlobs: z
471
- .array(z.string())
578
+ .array(globMaskSchema)
472
579
  .optional()
473
580
  .describe("New glob masks for a file trigger. Empty array clears them."),
474
581
  watchIgnore: z
475
- .array(z.string())
582
+ .array(globMaskSchema)
476
583
  .optional()
477
584
  .describe("New ignore masks for a file trigger. Empty array clears them."),
478
585
  gitBranch: z
@@ -480,11 +587,11 @@ export const updateTaskSchema = z.object({
480
587
  .optional()
481
588
  .describe("New git branch filter (glob, comma-separated). Empty string clears it."),
482
589
  gitPaths: z
483
- .array(z.string())
590
+ .array(globMaskSchema)
484
591
  .optional()
485
592
  .describe("New changed-file masks for a git trigger. Empty array clears them."),
486
593
  gitIgnore: z
487
- .array(z.string())
594
+ .array(globMaskSchema)
488
595
  .optional()
489
596
  .describe("New ignored changed-file masks for a git trigger. Empty array clears them."),
490
597
  gitPollSeconds: z
@@ -495,14 +602,26 @@ export const updateTaskSchema = z.object({
495
602
  .describe("New git polling interval in seconds."),
496
603
  prompt: z
497
604
  .string()
605
+ .refine((value) => value.trim().length > 0, "prompt must be a non-empty string.")
498
606
  .optional()
499
607
  .describe("New prompt. Keeps the current value when omitted."),
500
- 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."),
501
614
  model: z
502
615
  .string()
503
616
  .optional()
504
617
  .describe("New model in OpenCode format. Empty string clears it (default model)."),
505
- 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."),
506
625
  beforeScript: z
507
626
  .string()
508
627
  .optional()
@@ -519,8 +638,8 @@ export const updateTaskSchema = z.object({
519
638
  .array(z.string())
520
639
  .optional()
521
640
  .describe("New DAG dependencies. Empty array clears them."),
522
- retryCount: z.number().optional().describe("New retry count."),
523
- 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."),
524
643
  nextTaskOnSuccess: z
525
644
  .string()
526
645
  .optional()
@@ -536,11 +655,18 @@ export const updateTaskSchema = z.object({
536
655
  mcpEvent: z
537
656
  .object({
538
657
  server: z.string(),
539
- 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"),
540
666
  filter: z.string().optional(),
541
667
  })
542
668
  .optional()
543
- .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."),
544
670
  watchPath: z
545
671
  .string()
546
672
  .optional()
@@ -572,6 +698,13 @@ export const updateTaskSchema = z.object({
572
698
  guards: guardsSchema
573
699
  .optional()
574
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."),
575
708
  matrix: matrixSchema
576
709
  .nullable()
577
710
  .optional()
@@ -593,6 +726,16 @@ export const updateTaskSchema = z.object({
593
726
  message: t("tool.error.onceMatrixUpdate"),
594
727
  });
595
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
+ }
596
739
  });
597
740
  const pauseTaskSchema = z.object({
598
741
  name: z.string().describe("Task name to pause."),
@@ -618,8 +761,9 @@ const getHistorySchema = z.object({
618
761
  .optional()
619
762
  .describe("Maximum number of records to return (default 20, max 200)."),
620
763
  });
621
- const getTaskLogsSchema = z.object({
622
- 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."),
623
767
  lines: z
624
768
  .number()
625
769
  .optional()
@@ -633,8 +777,15 @@ const dryRunSchema = z.object({
633
777
  });
634
778
  /** pipeline_validate — проверить опencode.pipeline.yaml (путь или исходник). */
635
779
  export const pipelineValidateSchema = z.object({
636
- path: z.string().optional().describe("Путь к файлу opencode.pipeline.yaml."),
637
- source: z.string().optional().describe("Исходное содержимое YAML."),
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 процесса, затем подсказки окружения)."),
638
789
  dryRun: z
639
790
  .boolean()
640
791
  .optional()
@@ -643,8 +794,15 @@ export const pipelineValidateSchema = z.object({
643
794
  });
644
795
  /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
645
796
  export const pipelineApplySchema = z.object({
646
- path: z.string().optional().describe("Путь к файлу opencode.pipeline.yaml."),
647
- source: z.string().optional().describe("Исходное содержимое YAML."),
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 процесса, затем подсказки окружения)."),
648
806
  dryRun: z
649
807
  .boolean()
650
808
  .optional()
@@ -652,8 +810,22 @@ export const pipelineApplySchema = z.object({
652
810
  .describe("Если true — прогон diff'а без применения изменений (по умолчанию false)."),
653
811
  });
654
812
  /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
655
- export const pipelineExportSchema = z.object({
656
- pipeline: z.string().describe("Имя конвейера (pipelineName)."),
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
+ }
657
829
  });
658
830
  const manageWorkspacesSchema = z.object({
659
831
  action: z
@@ -750,8 +922,8 @@ export const selfAnalysisSchema = z.object({
750
922
  /** manage_settings — глобальные настройки планировщика. */
751
923
  export const manageSettingsSchema = z.object({
752
924
  action: z
753
- .enum(["get", "update"])
754
- .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."),
755
927
  maxConcurrent: z
756
928
  .number()
757
929
  .int()
@@ -792,6 +964,24 @@ export const manageSettingsSchema = z.object({
792
964
  })
793
965
  .optional()
794
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)."),
795
985
  });
796
986
  /** manage_local_ai — настройки локального ассистента и триажа (Спринт 30.7). */
797
987
  export const manageLocalAiSchema = z.object({
@@ -846,8 +1036,8 @@ export const manageLocalAiSchema = z.object({
846
1036
  export const manageTemplatesSchema = z.object({
847
1037
  action: z
848
1038
  .enum(["list", "save", "delete"])
849
- .describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
850
- 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."),
851
1041
  name: z.string().optional().describe("Template name."),
852
1042
  prompt: z.string().optional().describe("Prompt text stored in the template."),
853
1043
  schedule: z.string().optional().describe("Cron expression."),
@@ -866,10 +1056,18 @@ export const manageTemplatesSchema = z.object({
866
1056
  mcpEvent: z
867
1057
  .object({
868
1058
  server: z.string(),
869
- 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"),
870
1067
  filter: z.string().optional(),
871
1068
  })
872
- .optional(),
1069
+ .optional()
1070
+ .describe("MCP event trigger: event (or its alias eventName); at least one of them is required for triggerType=mcp-event."),
873
1071
  watchPath: z.string().optional(),
874
1072
  workingDirectory: z.string().optional(),
875
1073
  allowedTools: z.array(z.string()).optional(),
@@ -898,6 +1096,21 @@ export const sendNotificationSchema = z.object({
898
1096
  .optional()
899
1097
  .describe("For action=test: which channel to check (default all enabled)."),
900
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
+ });
901
1114
  /** get_dashboard_info — сведения о панели управления. */
902
1115
  export const getDashboardInfoSchema = z.object({});
903
1116
  /** cleanup_history — удаление старой истории. */
@@ -909,6 +1122,10 @@ export const cleanupHistorySchema = z.object({
909
1122
  export const emitEventSchema = z.object({
910
1123
  eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
911
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."),
912
1129
  });
913
1130
  /** manage_secrets — зашифрованное хранилище секретов (Спринт 26). */
914
1131
  export const manageSecretsSchema = z.object({
@@ -941,7 +1158,6 @@ export const getAuditLogSchema = z.object({
941
1158
  let projectDirectory;
942
1159
  /**
943
1160
  * Обёртка execute-функции: ловит ошибки и возвращает Tool.Result с content.
944
- * Использует Tool.Context из @opencode/schema/tool.
945
1161
  */
946
1162
  function wrapExecute(fn) {
947
1163
  return async (input, context) => {
@@ -949,11 +1165,24 @@ function wrapExecute(fn) {
949
1165
  return await fn(input, context);
950
1166
  }
951
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
+ };
952
1183
  return {
953
- content: JSON.stringify({
954
- success: false,
955
- error: err instanceof Error ? err.message : String(err),
956
- }),
1184
+ output,
1185
+ content: JSON.stringify(output),
957
1186
  };
958
1187
  }
959
1188
  };
@@ -1029,7 +1258,11 @@ function computeTaskNextRun(def, options = {}) {
1029
1258
  }
1030
1259
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
1031
1260
  const scheduleTaskExecute = wrapExecute(async (args) => {
1032
- 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, } = 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;
1033
1266
  let effectiveRunAt;
1034
1267
  if ((triggerType ?? "cron") === "once") {
1035
1268
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
@@ -1056,7 +1289,7 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
1056
1289
  gitPollSeconds,
1057
1290
  },
1058
1291
  // Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
1059
- runWhenLoggedOff === true, undefined, legacyShell === true, worktree === true, guards);
1292
+ runWhenLoggedOff === true, undefined, legacyShell === true, worktree === true, guards, tokenBudget);
1060
1293
  }
1061
1294
  catch (err) {
1062
1295
  return {
@@ -1130,29 +1363,27 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
1130
1363
  const listTasksExecute = wrapExecute(async () => {
1131
1364
  const { tasks, osAvailable, osError } = await collectTasksView();
1132
1365
  if (tasks.length === 0) {
1133
- return {
1134
- content: JSON.stringify({
1135
- success: true,
1136
- message: osAvailable
1137
- ? t("tool.task.listEmpty")
1138
- : t("tool.task.listOsUnavailable"),
1139
- tasks: [],
1140
- osAvailable,
1141
- ...(osError ? { osError } : {}),
1142
- }),
1143
- };
1144
- }
1145
- return {
1146
- content: JSON.stringify({
1366
+ const output = {
1147
1367
  success: true,
1148
1368
  message: osAvailable
1149
- ? t("tool.task.found", { count: tasks.length })
1150
- : t("tool.task.foundOsUnavailable", { count: tasks.length }),
1151
- tasks,
1369
+ ? t("tool.task.listEmpty")
1370
+ : t("tool.task.listOsUnavailable"),
1371
+ tasks: [],
1152
1372
  osAvailable,
1153
1373
  ...(osError ? { osError } : {}),
1154
- }),
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 } : {}),
1155
1385
  };
1386
+ return { output, content: JSON.stringify(output) };
1156
1387
  });
1157
1388
  /**
1158
1389
  * Отмена выполняющейся матрицы: незавершённые клоны помечаются отменой
@@ -1184,7 +1415,9 @@ async function cancelMatrixRun(name) {
1184
1415
  }
1185
1416
  // Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
1186
1417
  try {
1187
- 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);
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);
1188
1421
  }
1189
1422
  catch (err) {
1190
1423
  warnings.push(t("tool.matrix.recreateFailed", {
@@ -1405,7 +1638,7 @@ const deleteTaskExecute = wrapExecute(async (args) => {
1405
1638
  return {
1406
1639
  content: JSON.stringify({
1407
1640
  success: false,
1408
- error: err.message || String(err),
1641
+ error: err instanceof Error ? err.message : String(err),
1409
1642
  }),
1410
1643
  };
1411
1644
  }
@@ -1413,6 +1646,11 @@ const deleteTaskExecute = wrapExecute(async (args) => {
1413
1646
  /** run_task_now — немедленный запуск задачи */
1414
1647
  const runTaskNowExecute = wrapExecute(async (args) => {
1415
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;
1416
1654
  let alreadyRunning = false;
1417
1655
  try {
1418
1656
  const result = await runTaskEntry(name);
@@ -1422,7 +1660,7 @@ const runTaskNowExecute = wrapExecute(async (args) => {
1422
1660
  return {
1423
1661
  content: JSON.stringify({
1424
1662
  success: false,
1425
- error: err.message || String(err),
1663
+ error: err instanceof Error ? err.message : String(err),
1426
1664
  }),
1427
1665
  };
1428
1666
  }
@@ -1432,6 +1670,7 @@ const runTaskNowExecute = wrapExecute(async (args) => {
1432
1670
  message: alreadyRunning
1433
1671
  ? t("tool.task.alreadyRunning", { name })
1434
1672
  : t("tool.task.started", { name }),
1673
+ ...(warning ? { warning } : {}),
1435
1674
  }),
1436
1675
  };
1437
1676
  });
@@ -1480,6 +1719,11 @@ async function updateTaskFromInput(input) {
1480
1719
  if (!name) {
1481
1720
  return { success: false, message: t("tool.error.taskNameMissing") };
1482
1721
  }
1722
+ // QA-P2.1: RPC не проходит Zod — проверяем диапазоны явно.
1723
+ const rangeError = validateTaskInputRanges(input);
1724
+ if (rangeError) {
1725
+ return { success: false, message: rangeError };
1726
+ }
1483
1727
  const previous = getTask(name);
1484
1728
  if (!previous) {
1485
1729
  return { success: false, message: t("tool.error.taskNotFound", { name }) };
@@ -1611,7 +1855,9 @@ async function updateTaskFromInput(input) {
1611
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,
1612
1856
  // Если задача была матрицей — синхронизируем клонов, а не
1613
1857
  // пересоздаём их с нуля (Спринт 17).
1614
- 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);
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);
1615
1861
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
1616
1862
  if (matrixWas && !matrixNext) {
1617
1863
  await removeMatrixChildrenFromScheduler(name);
@@ -1724,7 +1970,10 @@ async function pauseOrResumeTask(name, paused, until) {
1724
1970
  message: t("tool.error.taskNotFound", { name: trimmed }),
1725
1971
  affected: [],
1726
1972
  warnings: [],
1727
- paused,
1973
+ // QA-P3.8: в ошибке `paused` должен отражать реальное состояние,
1974
+ // а не запрошенное действие (иначе resume про несуществующей задаче
1975
+ // сообщает paused:false, а pause — paused:true).
1976
+ paused: false,
1728
1977
  nextRun: null,
1729
1978
  pausedUntil: null,
1730
1979
  };
@@ -1739,7 +1988,7 @@ async function pauseOrResumeTask(name, paused, until) {
1739
1988
  message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
1740
1989
  affected: [],
1741
1990
  warnings: [],
1742
- paused,
1991
+ paused: definition.paused ?? false,
1743
1992
  nextRun: null,
1744
1993
  pausedUntil: definition.pausedUntil ?? null,
1745
1994
  };
@@ -1750,7 +1999,7 @@ async function pauseOrResumeTask(name, paused, until) {
1750
1999
  message: t("tool.error.pauseDatePast", { name: trimmed }),
1751
2000
  affected: [],
1752
2001
  warnings: [],
1753
- paused,
2002
+ paused: definition.paused ?? false,
1754
2003
  nextRun: null,
1755
2004
  pausedUntil: definition.pausedUntil ?? null,
1756
2005
  };
@@ -1766,7 +2015,7 @@ async function pauseOrResumeTask(name, paused, until) {
1766
2015
  message: t("tool.error.matrixNoClones", { name: trimmed }),
1767
2016
  affected: [],
1768
2017
  warnings: [],
1769
- paused,
2018
+ paused: definition.paused ?? false,
1770
2019
  nextRun: null,
1771
2020
  pausedUntil: definition.pausedUntil ?? null,
1772
2021
  };
@@ -1941,6 +2190,9 @@ async function checkStuckMatrices() {
1941
2190
  /** get_history — история запусков с фильтрами по задаче и статусу. */
1942
2191
  const getHistoryExecute = wrapExecute(async (args) => {
1943
2192
  const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
2193
+ // PL-46: зависшие записи (schtasks /End) должны закрываться не только при
2194
+ // setup, но и при наблюдении истории — иначе остаются running навсегда.
2195
+ recoverInterruptedRuns();
1944
2196
  const records = await loadHistory(args.taskName, limit, args.status);
1945
2197
  return {
1946
2198
  content: JSON.stringify({
@@ -1952,7 +2204,14 @@ const getHistoryExecute = wrapExecute(async (args) => {
1952
2204
  });
1953
2205
  /** get_task_logs — последние строки лога задачи. */
1954
2206
  const getTaskLogsExecute = wrapExecute(async (args) => {
1955
- 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);
1956
2215
  if (result.error) {
1957
2216
  return {
1958
2217
  content: JSON.stringify({ success: false, logs: "", error: result.error }),
@@ -2000,7 +2259,6 @@ const dryRunExecute = wrapExecute(async (args) => {
2000
2259
  });
2001
2260
  /** pipeline_validate — проверить opencode.pipeline.yaml (путь или исходник). */
2002
2261
  const pipelineValidateExecute = wrapExecute(async (args) => {
2003
- const path = args.path ?? args.source ? undefined : undefined;
2004
2262
  if (args.path === undefined && args.source === undefined) {
2005
2263
  return {
2006
2264
  content: JSON.stringify({
@@ -2013,7 +2271,7 @@ const pipelineValidateExecute = wrapExecute(async (args) => {
2013
2271
  }
2014
2272
  const parsed = args.source !== undefined
2015
2273
  ? validatePipelineSpecFromSource(args.source)
2016
- : await loadPipelineFile(args.path);
2274
+ : await loadPipelineFile(args.path, args.workingDirectory);
2017
2275
  if (!parsed.ok) {
2018
2276
  return {
2019
2277
  content: JSON.stringify({
@@ -2042,9 +2300,19 @@ function validatePipelineSpecFromSource(source) {
2042
2300
  /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
2043
2301
  const pipelineApplyExecute = wrapExecute(async (args) => {
2044
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
+ }
2045
2313
  const parsed = args.source !== undefined
2046
2314
  ? validatePipelineSpecFromSource(args.source)
2047
- : await loadPipelineFile(args.path);
2315
+ : await loadPipelineFile(args.path, args.workingDirectory);
2048
2316
  if (!parsed.ok) {
2049
2317
  return {
2050
2318
  content: JSON.stringify({
@@ -2124,12 +2392,34 @@ const pipelineApplyExecute = wrapExecute(async (args) => {
2124
2392
  /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
2125
2393
  const pipelineExportExecute = wrapExecute(async (args) => {
2126
2394
  const allTasks = await listTaskDefinitions();
2127
- const result = tasksToPipelineSpec(allTasks, args.pipeline);
2128
- if (!result.spec) {
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) {
2129
2408
  return {
2130
2409
  content: JSON.stringify({
2131
2410
  success: false,
2132
- error: `Конвейер "${args.pipeline}" не найден (не найдены задачи с pipelineName=${args.pipeline} и pipelineStepId).`,
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}" не найден.`,
2133
2423
  warnings: result.warnings,
2134
2424
  }),
2135
2425
  };
@@ -2138,7 +2428,7 @@ const pipelineExportExecute = wrapExecute(async (args) => {
2138
2428
  return {
2139
2429
  content: JSON.stringify({
2140
2430
  success: true,
2141
- pipeline: args.pipeline,
2431
+ pipeline: pipelineName,
2142
2432
  steps: result.spec.steps.length,
2143
2433
  yaml: yamlText,
2144
2434
  warnings: result.warnings,
@@ -2348,6 +2638,17 @@ const matrixControlExecute = wrapExecute(async (args) => {
2348
2638
  };
2349
2639
  }
2350
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
+ }
2351
2652
  try {
2352
2653
  const report = aggregateMatrixResults(name);
2353
2654
  return { content: JSON.stringify({ success: true, report }) };
@@ -2364,34 +2665,52 @@ const matrixControlExecute = wrapExecute(async (args) => {
2364
2665
  /** get_metrics — суммарная статистика запусков. */
2365
2666
  const getMetricsExecute = wrapExecute(async () => {
2366
2667
  const metrics = await loadMetrics();
2367
- 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 } }) };
2368
2672
  });
2369
2673
  /** get_analytics — аналитика запусков и стоимости за период. */
2370
2674
  const getAnalyticsExecute = wrapExecute(async (args) => {
2371
2675
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
2372
- const records = getHistory(null, 20000);
2676
+ const records = getHistoryForAnalytics(windowDays);
2373
2677
  const definitions = await loadTaskDefinitions();
2374
2678
  const report = buildAnalytics(records, {
2375
2679
  days: windowDays,
2376
2680
  topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
2377
- tasks: definitions.map((definition) => ({
2681
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
2378
2682
  name: definition.name,
2379
2683
  matrixParentId: definition.matrixParentId,
2684
+ tokenBudget: definition.tokenBudget,
2380
2685
  })),
2381
2686
  });
2382
- 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
+ };
2383
2701
  });
2384
2702
  /** self_analysis — система самоанализа: здоровье, аномалии, тренды, рекомендации. */
2385
2703
  const selfAnalysisExecute = wrapExecute(async (args) => {
2386
2704
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
2387
- const records = getHistory(null, 20000);
2705
+ const records = getHistoryForAnalytics(windowDays);
2388
2706
  const definitions = await loadTaskDefinitions();
2389
2707
  const report = generateSelfAnalysisReport(records, {
2390
2708
  days: windowDays,
2391
2709
  topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
2392
- tasks: definitions.map((definition) => ({
2710
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
2393
2711
  name: definition.name,
2394
2712
  matrixParentId: definition.matrixParentId,
2713
+ tokenBudget: definition.tokenBudget,
2395
2714
  })),
2396
2715
  });
2397
2716
  // Фильтруем секции если нужно
@@ -2416,7 +2735,7 @@ const selfAnalysisExecute = wrapExecute(async (args) => {
2416
2735
  /** manage_settings — чтение и изменение глобальных настроек. */
2417
2736
  const manageSettingsExecute = wrapExecute(async (args) => {
2418
2737
  const current = await loadSettings();
2419
- if (args.action === "get") {
2738
+ if (args.action === "get" || args.action === "list") {
2420
2739
  return { content: JSON.stringify({ success: true, settings: current }) };
2421
2740
  }
2422
2741
  if (args.maxConcurrent === undefined &&
@@ -2426,7 +2745,9 @@ const manageSettingsExecute = wrapExecute(async (args) => {
2426
2745
  args.history === undefined &&
2427
2746
  args.integrations === undefined &&
2428
2747
  args.audit === undefined &&
2429
- args.permissions === undefined) {
2748
+ args.permissions === undefined &&
2749
+ args.budgets === undefined &&
2750
+ args.feedback === undefined) {
2430
2751
  return {
2431
2752
  content: JSON.stringify({
2432
2753
  success: false,
@@ -2444,6 +2765,8 @@ const manageSettingsExecute = wrapExecute(async (args) => {
2444
2765
  integrations: args.integrations,
2445
2766
  audit: args.audit,
2446
2767
  permissions: args.permissions,
2768
+ budgets: args.budgets,
2769
+ feedback: args.feedback,
2447
2770
  });
2448
2771
  // Локаль процесса меняется сразу — перезапуск плагина не нужен.
2449
2772
  setLocale(resolveLocale(settings.locale, settings.uiLocale));
@@ -2544,12 +2867,14 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
2544
2867
  return { content: JSON.stringify({ success: true, templates: await loadTemplates() }) };
2545
2868
  }
2546
2869
  if (args.action === "delete") {
2547
- const id = args.id?.trim();
2870
+ // PL-17/PL-28/PL-32: name — такой же алиас id, как и в репозитории.
2871
+ const id = args.id?.trim() || args.name?.trim();
2548
2872
  if (!id) {
2549
2873
  return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
2550
2874
  }
2551
2875
  const before = await loadTemplates();
2552
- 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);
2553
2878
  await deleteTemplate(id);
2554
2879
  return {
2555
2880
  content: JSON.stringify({
@@ -2667,7 +2992,9 @@ const transferTasksExecute = wrapExecute(async (args) => {
2667
2992
  gitPaths: def.gitPaths,
2668
2993
  gitIgnore: def.gitIgnore,
2669
2994
  gitPollSeconds: def.gitPollSeconds,
2670
- }, def.runWhenLoggedOff, def.paused, def.legacyShell, def.worktree, def.guards);
2995
+ }, def.runWhenLoggedOff, def.paused, def.legacyShell, def.worktree, def.guards,
2996
+ // QA-P0.1 (E-2.1): импорт через transfer_tasks сохраняет tokenBudget.
2997
+ def.tokenBudget);
2671
2998
  await saveTaskDefinition(def);
2672
2999
  imported.push(def.name);
2673
3000
  }
@@ -2687,9 +3014,151 @@ const sendNotificationExecute = wrapExecute(async (args) => {
2687
3014
  : await sendDigestNow({ updateLastSentAt: false });
2688
3015
  return { content: JSON.stringify(result) };
2689
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
+ });
2690
3148
  /** get_dashboard_info — порт дашборда, платформа и активный профиль. */
2691
3149
  const getDashboardInfoExecute = wrapExecute(async () => {
2692
- 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
+ }
2693
3162
  return {
2694
3163
  content: JSON.stringify({
2695
3164
  success: true,
@@ -2698,6 +3167,7 @@ const getDashboardInfoExecute = wrapExecute(async () => {
2698
3167
  platform: scheduler.platform,
2699
3168
  title: scheduler.title,
2700
3169
  profile: getProfileName(),
3170
+ reachable: probe?.dashboard ?? false,
2701
3171
  }),
2702
3172
  };
2703
3173
  });
@@ -2722,38 +3192,81 @@ const cleanupHistoryExecute = wrapExecute(async (args) => {
2722
3192
  }),
2723
3193
  };
2724
3194
  });
2725
- /** emit_event — запуск задач, подписанных на MCP-событие. */
2726
- const emitEventExecute = wrapExecute(async (args) => {
2727
- const eventName = args.eventName?.trim();
2728
- if (!eventName) {
2729
- 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
+ };
2730
3228
  }
2731
- const payload = args.payload ?? {};
2732
3229
  const definitions = await loadTaskDefinitions();
2733
3230
  const matched = definitions
2734
- .filter((def) => def.triggerType === "mcp-event" &&
2735
- def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
2736
- matchesEventFilter(def.mcpEvent?.filter, payload))
2737
- .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));
2738
3234
  const triggered = [];
3235
+ const failed = [];
2739
3236
  for (const def of matched) {
2740
3237
  try {
2741
3238
  await runTaskEntry(def.name);
2742
3239
  triggered.push(def.name);
2743
3240
  }
2744
3241
  catch (err) {
2745
- 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}`);
2746
3245
  }
2747
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 });
2748
3253
  return {
2749
- content: JSON.stringify({
2750
- success: true,
2751
- message: triggered.length > 0
2752
- ? t("tool.event.triggered", { count: triggered.length })
2753
- : t("tool.event.none", { event: eventName }),
2754
- triggered,
2755
- }),
3254
+ success: true,
3255
+ code,
3256
+ event,
3257
+ matched: matched.map((def) => def.name),
3258
+ triggered,
3259
+ failed,
3260
+ message,
2756
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) };
2757
3270
  });
2758
3271
  /** manage_secrets — зашифрованное хранилище секретов. */
2759
3272
  const manageSecretsExecute = wrapExecute(async (args) => {
@@ -2819,10 +3332,15 @@ function withAudit(toolName, describe, execute) {
2819
3332
  return async (args, context) => {
2820
3333
  const result = await execute(args, context);
2821
3334
  try {
2822
- const raw = String(result?.content ?? "");
3335
+ const content = result.content;
3336
+ const raw = typeof content === "string" ? content : "";
2823
3337
  const parsed = raw ? JSON.parse(raw) : null;
2824
- if (parsed?.success === false)
3338
+ if (typeof parsed === "object" &&
3339
+ parsed !== null &&
3340
+ "success" in parsed &&
3341
+ parsed.success === false) {
2825
3342
  return result;
3343
+ }
2826
3344
  const entry = describe(args);
2827
3345
  if (entry) {
2828
3346
  recordAudit({ ...entry, actor: "mcp", source: toolName });
@@ -2918,17 +3436,22 @@ const RPC_AUDIT_RULES = {
2918
3436
  */
2919
3437
  function withRpcAudit(handlers) {
2920
3438
  const wrapped = {};
2921
- for (const [name, handler] of Object.entries(handlers)) {
3439
+ const entries = Object.entries(handlers);
3440
+ for (const [name, handler] of entries) {
2922
3441
  const rule = RPC_AUDIT_RULES[name];
2923
3442
  if (!rule || typeof handler !== "function") {
2924
3443
  wrapped[name] = handler;
2925
3444
  continue;
2926
3445
  }
2927
3446
  wrapped[name] = async (...args) => {
2928
- const input = args[0] ?? {};
3447
+ const input = (args[0] ?? {});
2929
3448
  const result = await handler(...args);
2930
3449
  try {
2931
- if ((result)?.success !== false) {
3450
+ const failed = typeof result === "object" &&
3451
+ result !== null &&
3452
+ "success" in result &&
3453
+ result.success === false;
3454
+ if (!failed) {
2932
3455
  recordAudit({
2933
3456
  action: rule.action,
2934
3457
  targetType: rule.targetType,
@@ -3001,7 +3524,28 @@ async function scheduleEventRun(taskName, reason) {
3001
3524
  const now = new Date();
3002
3525
  const state = activeWindowState(now, options);
3003
3526
  if (state.active || policy === "run") {
3004
- 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
+ }
3005
3549
  console.log(`[agent-steward] Запуск задачи "${taskName}" (${reason}).`);
3006
3550
  return;
3007
3551
  }
@@ -3051,6 +3595,18 @@ export async function createRuntime(ctxLike) {
3051
3595
  catch (err) {
3052
3596
  console.error(`[recovery] Не удалось восстановить незавершённые запуски: ${err instanceof Error ? err.message : String(err)}`);
3053
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
+ });
3054
3610
  // P1-14: pid:-записи fallback'а не переживают перезагрузку. Чистим их и
3055
3611
  // пересоздаём будущие one-shot, иначе после reboot можно убить чужой pid.
3056
3612
  if (scheduler instanceof LinuxScheduler) {
@@ -3223,6 +3779,7 @@ export function createToolHandlers(_runtime) {
3223
3779
  manage_profiles: manageProfilesExecute,
3224
3780
  transfer_tasks: transferTasksExecute,
3225
3781
  send_notification: sendNotificationExecute,
3782
+ report_bug: reportBugExecute,
3226
3783
  get_dashboard_info: getDashboardInfoExecute,
3227
3784
  cleanup_history: cleanupHistoryExecute,
3228
3785
  emit_event: emitEventExecute,
@@ -3252,6 +3809,8 @@ export function createShutdownHandler(runtime, registrations = [], options = {})
3252
3809
  }
3253
3810
  // Чекпойнт WAL выполняется в closeDb.
3254
3811
  closeDb();
3812
+ // QA/PL-10: выгрузка действительно завершена — запрещаем автосброс ворот.
3813
+ shutdownGate.complete();
3255
3814
  };
3256
3815
  }
3257
3816
  /**
@@ -3261,7 +3820,14 @@ export function createShutdownHandler(runtime, registrations = [], options = {})
3261
3820
  * одинаковые имена, схемы, описания и обработчики. Аудит навешивается здесь
3262
3821
  * один раз, чтобы обе линии вели журнал одинаково.
3263
3822
  */
3264
- 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
+ }
3265
3831
  const handlers = createToolHandlers(runtime);
3266
3832
  return [
3267
3833
  {
@@ -3276,8 +3842,9 @@ export function createToolSpecs(runtime) {
3276
3842
  {
3277
3843
  name: "list_tasks",
3278
3844
  input: listTasksSchema,
3845
+ output: listTasksOutputSchema,
3279
3846
  description: `Lists plugin tasks from the scheduler (${scheduler.title}) with schedule, status, next chained task and working directory. ` +
3280
- "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.",
3281
3848
  execute: handlers.list_tasks,
3282
3849
  },
3283
3850
  {
@@ -3379,7 +3946,9 @@ export function createToolSpecs(runtime) {
3379
3946
  name: "self_analysis",
3380
3947
  input: selfAnalysisSchema,
3381
3948
  description: "Generates a self-analysis report: system health score, anomaly detection, trend analysis and optimization recommendations. " +
3382
- "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.",
3383
3952
  execute: handlers.self_analysis,
3384
3953
  },
3385
3954
  {
@@ -3443,6 +4012,12 @@ export function createToolSpecs(runtime) {
3443
4012
  description: "Sends a test notification through the configured channel or sends the digest immediately.",
3444
4013
  execute: handlers.send_notification,
3445
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
+ },
3446
4021
  {
3447
4022
  name: "get_dashboard_info",
3448
4023
  input: getDashboardInfoSchema,
@@ -3530,6 +4105,14 @@ async function startSchedulerDashboard() {
3530
4105
  const v2Plugin = Plugin.define({
3531
4106
  id: "opencode-windows-scheduler",
3532
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();
3533
4116
  const runtime = await createRuntime(ctx);
3534
4117
  const registration = await ctx.tool.transform((editor) => {
3535
4118
  // editor.add регистрирует новые инструменты плагина с codemode: true,
@@ -3543,9 +4126,10 @@ const v2Plugin = Plugin.define({
3543
4126
  editor.add({
3544
4127
  name: spec.name,
3545
4128
  input: spec.input,
4129
+ output: spec.output,
3546
4130
  description: spec.description,
3547
4131
  options: { codemode: true },
3548
- execute: execute,
4132
+ execute,
3549
4133
  });
3550
4134
  }
3551
4135
  });
@@ -3558,6 +4142,10 @@ const v2Plugin = Plugin.define({
3558
4142
  const skill = loadSchedulerSkill();
3559
4143
  if (skill && ctx.skill?.transform) {
3560
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 не меняет поведение.
3561
4149
  editor.add({
3562
4150
  id: skill.id,
3563
4151
  name: skill.name,
@@ -3585,7 +4173,12 @@ const v2Plugin = Plugin.define({
3585
4173
  },
3586
4174
  create_task: async (input) => {
3587
4175
  console.log("[agent-steward] create_task input:", input);
3588
- 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, } = 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;
3589
4182
  let effectiveRunAt;
3590
4183
  if (triggerType === "once") {
3591
4184
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
@@ -3608,7 +4201,9 @@ const v2Plugin = Plugin.define({
3608
4201
  }
3609
4202
  const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
3610
4203
  try {
3611
- 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);
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);
3612
4207
  const nextRun = computeTaskNextRun({
3613
4208
  schedule: schedule ?? "",
3614
4209
  triggerType: triggerType ?? "cron",
@@ -3687,8 +4282,25 @@ const v2Plugin = Plugin.define({
3687
4282
  run_task: async (input) => {
3688
4283
  const { name } = input;
3689
4284
  try {
4285
+ const budgetGate = await checkBudgetGate();
4286
+ if (!budgetGate.allowed) {
4287
+ return {
4288
+ success: false,
4289
+ message: formatBudgetSkipMessage(budgetGate),
4290
+ };
4291
+ }
3690
4292
  // Matrix-родитель не выполняется сам: запускаем его клоны (fan-out).
3691
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
+ }
3692
4304
  if (definition?.matrix) {
3693
4305
  const matrixResult = await runMatrix(definition);
3694
4306
  const total = definition.matrix.workspaceIds.length;
@@ -3737,6 +4349,18 @@ const v2Plugin = Plugin.define({
3737
4349
  },
3738
4350
  run_mission: async (input) => {
3739
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
+ };
4363
+ }
3740
4364
  const mission = await runMission(input);
3741
4365
  return {
3742
4366
  success: mission.success,
@@ -3768,34 +4392,8 @@ const v2Plugin = Plugin.define({
3768
4392
  }
3769
4393
  },
3770
4394
  emit_event: async (input) => {
3771
- const { eventName, payload } = input;
3772
- const normalized = eventName?.trim();
3773
- if (!normalized) {
3774
- return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
3775
- }
3776
- // Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
3777
- const definitions = await loadTaskDefinitions();
3778
- const matched = definitions
3779
- .filter((def) => (def.triggerType ?? "cron") === "mcp-event")
3780
- .filter((def) => def.mcpEvent?.event?.trim().toLowerCase() === normalized.toLowerCase())
3781
- .filter((def) => matchesEventFilter(def.mcpEvent?.filter, payload))
3782
- .sort((a, b) => (normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5));
3783
- const triggered = [];
3784
- for (const def of matched) {
3785
- try {
3786
- await runTaskEntry(def.name);
3787
- triggered.push(def.name);
3788
- console.log(`[agent-steward] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`);
3789
- }
3790
- catch (err) {
3791
- console.error(`[agent-steward] Не удалось запустить "${def.name}" по событию "${normalized}": ${err instanceof Error ? err.message : String(err)}`);
3792
- }
3793
- }
3794
- return {
3795
- success: true,
3796
- triggered,
3797
- message: t("tool.event.processed", { event: normalized, count: triggered.length }),
3798
- };
4395
+ const { eventName, payload, server } = input;
4396
+ return await emitEventCore(eventName, payload, server);
3799
4397
  },
3800
4398
  pause_task: async (input) => {
3801
4399
  const { name, until } = input;
@@ -3811,8 +4409,12 @@ const v2Plugin = Plugin.define({
3811
4409
  return await updateTaskFromInput(input);
3812
4410
  },
3813
4411
  get_task_logs: async (input) => {
3814
- const { name } = input;
3815
- 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);
3816
4418
  if (result.error) {
3817
4419
  return { success: false, logs: "", error: result.error };
3818
4420
  }
@@ -3829,7 +4431,10 @@ const v2Plugin = Plugin.define({
3829
4431
  return { records };
3830
4432
  },
3831
4433
  get_metrics: async () => {
3832
- 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 };
3833
4438
  },
3834
4439
  cleanup_history: async (input) => {
3835
4440
  const { retentionDays, maxRecords } = input;
@@ -3875,17 +4480,24 @@ const v2Plugin = Plugin.define({
3875
4480
  const { days, topLimit } = input;
3876
4481
  try {
3877
4482
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(days) || 14)));
3878
- const records = getHistory(null, 20000);
4483
+ const records = getHistoryForAnalytics(windowDays);
3879
4484
  const definitions = await loadTaskDefinitions();
3880
4485
  const report = buildAnalytics(records, {
3881
4486
  days: windowDays,
3882
4487
  topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
3883
- tasks: definitions.map((definition) => ({
4488
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
3884
4489
  name: definition.name,
3885
4490
  matrixParentId: definition.matrixParentId,
4491
+ tokenBudget: definition.tokenBudget,
3886
4492
  })),
3887
4493
  });
3888
- 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 } };
3889
4501
  }
3890
4502
  catch (err) {
3891
4503
  return {
@@ -3899,14 +4511,15 @@ const v2Plugin = Plugin.define({
3899
4511
  const { days, topLimit, includeAnomalies, includeTrends, includeRecommendations } = input;
3900
4512
  try {
3901
4513
  const windowDays = Math.min(365, Math.max(1, Math.floor(Number(days) || 14)));
3902
- const records = getHistory(null, 20000);
4514
+ const records = getHistoryForAnalytics(windowDays);
3903
4515
  const definitions = await loadTaskDefinitions();
3904
4516
  const report = generateSelfAnalysisReport(records, {
3905
4517
  days: windowDays,
3906
4518
  topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
3907
- tasks: definitions.map((definition) => ({
4519
+ tasks: definitions.filter((d) => !d.name.startsWith("__")).map((definition) => ({
3908
4520
  name: definition.name,
3909
4521
  matrixParentId: definition.matrixParentId,
4522
+ tokenBudget: definition.tokenBudget,
3910
4523
  })),
3911
4524
  });
3912
4525
  // Фильтруем секции если нужно
@@ -3936,6 +4549,55 @@ const v2Plugin = Plugin.define({
3936
4549
  };
3937
4550
  }
3938
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
+ },
3939
4601
  get_dashboard_port: async () => {
3940
4602
  return { port: getDashboardPort() };
3941
4603
  },
@@ -3984,17 +4646,20 @@ const v2Plugin = Plugin.define({
3984
4646
  pipeline_validate: async (input) => {
3985
4647
  const { path, source, dryRun } = input;
3986
4648
  const result = await pipelineValidateExecute({ path, source, dryRun }, {});
3987
- return JSON.parse(result.content);
4649
+ const parsed = JSON.parse(result.content);
4650
+ return parsed;
3988
4651
  },
3989
4652
  pipeline_apply: async (input) => {
3990
4653
  const { path, source, dryRun } = input;
3991
4654
  const result = await pipelineApplyExecute({ path, source, dryRun }, {});
3992
- return JSON.parse(result.content);
4655
+ const parsed = JSON.parse(result.content);
4656
+ return parsed;
3993
4657
  },
3994
4658
  pipeline_export: async (input) => {
3995
- const { pipeline } = input;
3996
- const result = await pipelineExportExecute({ pipeline }, {});
3997
- return JSON.parse(result.content);
4659
+ const { pipeline, pipelineName } = input;
4660
+ const result = await pipelineExportExecute({ pipeline: pipeline ?? pipelineName }, {});
4661
+ const parsed = JSON.parse(result.content);
4662
+ return parsed;
3998
4663
  },
3999
4664
  get_matrix_results: async (input) => {
4000
4665
  const { parentId } = input;
@@ -4182,7 +4847,7 @@ const v2Plugin = Plugin.define({
4182
4847
  return await loadSettings();
4183
4848
  },
4184
4849
  save_settings: async (input) => {
4185
- 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;
4186
4851
  const current = await loadSettings();
4187
4852
  if (maxConcurrent === undefined &&
4188
4853
  locale === undefined &&
@@ -4192,7 +4857,9 @@ const v2Plugin = Plugin.define({
4192
4857
  history === undefined &&
4193
4858
  integrations === undefined &&
4194
4859
  audit === undefined &&
4195
- permissions === undefined) {
4860
+ permissions === undefined &&
4861
+ budgets === undefined &&
4862
+ feedback === undefined) {
4196
4863
  return {
4197
4864
  success: false,
4198
4865
  maxConcurrent: current.maxConcurrent,
@@ -4204,6 +4871,8 @@ const v2Plugin = Plugin.define({
4204
4871
  integrations: current.integrations,
4205
4872
  audit: current.audit,
4206
4873
  permissions: current.permissions,
4874
+ budgets: current.budgets,
4875
+ feedback: current.feedback,
4207
4876
  };
4208
4877
  }
4209
4878
  const settings = await saveSettings({
@@ -4216,6 +4885,8 @@ const v2Plugin = Plugin.define({
4216
4885
  integrations,
4217
4886
  audit,
4218
4887
  permissions,
4888
+ budgets,
4889
+ feedback,
4219
4890
  });
4220
4891
  // Локаль процесса меняется сразу — перезапуск не нужен.
4221
4892
  setLocale(resolveLocale(settings.locale, settings.uiLocale));
@@ -4230,6 +4901,8 @@ const v2Plugin = Plugin.define({
4230
4901
  integrations: settings.integrations,
4231
4902
  audit: settings.audit,
4232
4903
  permissions: settings.permissions,
4904
+ budgets: settings.budgets,
4905
+ feedback: settings.feedback,
4233
4906
  };
4234
4907
  },
4235
4908
  test_notification: async () => {
@@ -4342,6 +5015,10 @@ const v2Plugin = Plugin.define({
4342
5015
  },
4343
5016
  get_audit: async (input) => {
4344
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 };
4345
5022
  const result = readAuditLog({
4346
5023
  action: source.action,
4347
5024
  target: source.target,
@@ -4433,6 +5110,12 @@ const v2Plugin = Plugin.define({
4433
5110
  return { success: false, error: t("tool.template.needId") };
4434
5111
  }
4435
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
+ }
4436
5119
  await deleteTemplate(id);
4437
5120
  return { success: true };
4438
5121
  }
@@ -4484,7 +5167,9 @@ const v2Plugin = Plugin.define({
4484
5167
  gitPaths: def.gitPaths,
4485
5168
  gitIgnore: def.gitIgnore,
4486
5169
  gitPollSeconds: def.gitPollSeconds,
4487
- }, def.runWhenLoggedOff === true, def.paused === true, def.legacyShell === true, def.worktree === true, def.guards);
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);
4488
5173
  await saveTaskDefinition(def);
4489
5174
  imported.push(def.name);
4490
5175
  }
@@ -4517,27 +5202,31 @@ const v2Plugin = Plugin.define({
4517
5202
  ]);
4518
5203
  },
4519
5204
  });
4520
- /**
4521
- * Приводит результат V2-обработчика (`Tool.Result`) к формату V1 (`ToolResult`).
4522
- * V1 ждёт строку или `{ output, metadata }`; V2 отдаёт `{ content }`.
4523
- */
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
+ }
4524
5214
  export function toV1ToolResult(result) {
4525
5215
  if (typeof result === "string")
4526
5216
  return result;
4527
- if (Array.isArray(result?.content)) {
4528
- const text = result.content
4529
- .filter((part) => part?.type === "text" && typeof part.text === "string")
4530
- .map((part) => part.text)
4531
- .join("\n");
4532
- 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 };
4533
5222
  }
4534
- if (typeof result?.content === "string") {
4535
- return { output: result.content, metadata: result.metadata };
5223
+ if (typeof content === "string") {
5224
+ return { output: content, metadata };
4536
5225
  }
4537
- if (typeof result?.output === "string") {
4538
- return { output: result.output, metadata: result.metadata };
5226
+ if (typeof result.output === "string") {
5227
+ return { output: result.output, metadata };
4539
5228
  }
4540
- return { output: JSON.stringify(result), metadata: result?.metadata };
5229
+ return { output: JSON.stringify(result), metadata };
4541
5230
  }
4542
5231
  /**
4543
5232
  * V1 `tool()` принимает `z.ZodRawShape`, а спецификации хранят `z.object(...)`.
@@ -4550,11 +5239,6 @@ export function toV1ToolArgs(spec) {
4550
5239
  }
4551
5240
  return shape;
4552
5241
  }
4553
- /**
4554
- * V1-реестр инструментов: те же имена, описания, схемы и обработчики, что в
4555
- * V2, плюс тот же аудит. Отличие одно — у V1 `tool()` нет `codemode`, поэтому
4556
- * флаг не передаётся (см. docs/COMPATIBILITY.md).
4557
- */
4558
5242
  export function createV1Tools(runtime) {
4559
5243
  const tools = {};
4560
5244
  for (const spec of createToolSpecs(runtime)) {
@@ -4564,7 +5248,7 @@ export function createV1Tools(runtime) {
4564
5248
  tools[spec.name] = v1Tool({
4565
5249
  description: spec.description,
4566
5250
  args: toV1ToolArgs(spec),
4567
- execute: (async (args, context) => toV1ToolResult(await execute(args, context))),
5251
+ execute: async (args, context) => toV1ToolResult(await execute(args, context)),
4568
5252
  });
4569
5253
  }
4570
5254
  return tools;
@@ -4577,12 +5261,20 @@ export function createV1Tools(runtime) {
4577
5261
  * `createShutdownHandler`. GUI/RPC/скиллы — только V2, здесь их нет.
4578
5262
  */
4579
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();
4580
5270
  const runtime = await createRuntime({ location: { directory: input.directory } });
4581
5271
  const tools = createV1Tools(runtime);
4582
5272
  if (options.startDashboard !== false) {
4583
5273
  await startSchedulerDashboard();
4584
5274
  }
4585
5275
  return {
5276
+ // QA-A2.1: граница внешнего V1 API — у плагина отдельная копия zod,
5277
+ // типы несовместимы структурно. Значения и поведение не меняются.
4586
5278
  tool: tools,
4587
5279
  dispose: createShutdownHandler(runtime),
4588
5280
  };
@@ -4654,6 +5346,21 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
4654
5346
  }
4655
5347
  return extra;
4656
5348
  }
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
+ }
4657
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,
4658
5365
  /** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
4659
5366
  matrixMode = "create",
@@ -4690,7 +5397,9 @@ legacyShell,
4690
5397
  /** W-1: одноразовый git worktree на каждый запуск. */
4691
5398
  worktree,
4692
5399
  /** W-3: guard-условия перед запуском opencode. */
4693
- guards) {
5400
+ guards,
5401
+ /** Economics v2 (E-2): per-run token budget. 0/omitted = no limit (fail-open). */
5402
+ tokenBudget) {
4694
5403
  // Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
4695
5404
  // в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
4696
5405
  // schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
@@ -4754,6 +5463,10 @@ guards) {
4754
5463
  if (!guardsResult.ok)
4755
5464
  throw new Error(guardsResult.error);
4756
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;
4757
5470
  // Спринт 27: дни недели, политика окна и glob/git-фильтры.
4758
5471
  const normalizeGlobList = (raw) => {
4759
5472
  if (!Array.isArray(raw))
@@ -4778,13 +5491,9 @@ guards) {
4778
5491
  triggerExtras.gitPollSeconds >= 5
4779
5492
  ? Math.floor(triggerExtras.gitPollSeconds)
4780
5493
  : undefined;
4781
- const normalizedMcpEvent = mcpEvent?.event?.trim()
4782
- ? {
4783
- server: mcpEvent.server?.trim() || "",
4784
- event: mcpEvent.event.trim(),
4785
- ...(mcpEvent.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
4786
- }
4787
- : undefined;
5494
+ // PL-42: mcpEvent принимает event и его алиас eventName (emit_event).
5495
+ // event приоритетнее: если оба заданы и различаются, побеждает event.
5496
+ const normalizedMcpEvent = normalizeMcpEventTrigger(mcpEvent);
4788
5497
  let effectiveTriggerType = triggerType ?? "cron";
4789
5498
  // One-shot: нормализуем время до создания файлов и задачи в ОС.
4790
5499
  // Для остальных триггеров runAt не имеет смысла и отбрасывается.
@@ -4920,7 +5629,7 @@ guards) {
4920
5629
  parseCron(schedule);
4921
5630
  }
4922
5631
  catch (err) {
4923
- throw new Error(err.message || String(err));
5632
+ throw new Error(err instanceof Error ? err.message : String(err));
4924
5633
  }
4925
5634
  if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
4926
5635
  throw new Error(t("tool.error.timezone", {
@@ -5007,7 +5716,7 @@ guards) {
5007
5716
  effectiveWatchPath = normalizeWatchPath(effectiveWatchPath, effectiveWorkingDirectory);
5008
5717
  }
5009
5718
  catch (err) {
5010
- 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) }));
5011
5720
  }
5012
5721
  }
5013
5722
  try {
@@ -5015,7 +5724,7 @@ guards) {
5015
5724
  validateWatchGlobs(normalizedWatchIgnore);
5016
5725
  }
5017
5726
  catch (err) {
5018
- 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) }));
5019
5728
  }
5020
5729
  // Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
5021
5730
  // Спринт 29.3: инжектит в env только реально используемые секреты (scoped-инъекция).
@@ -5028,11 +5737,16 @@ guards) {
5028
5737
  try {
5029
5738
  promptFile = await writePromptFile(sanitized, prompt);
5030
5739
  await fs.mkdir(LOG_DIR, { recursive: true });
5031
- await fs.writeFile(logFile, "", "utf8");
5740
+ // Не обнуляем лог: при падении до запуска обёртки (или при отказе модели)
5741
+ // предыдущий диагностический вывод оставался бы единственным, а новый
5742
+ // прогон выглядел бы как «лог пуст». Дописываем маркер ПОДГОТОВКИ —
5743
+ // задача создана, но ещё не запускалась (не путать с реальным Run started,
5744
+ // который пишется обёрткой только при фактическом запуске; QA #8).
5745
+ await fs.appendFile(logFile, formatLogRunMarker("prepare", name), "utf8");
5032
5746
  }
5033
5747
  catch (err) {
5034
5748
  throw new Error(t("tool.error.prepareFiles", {
5035
- error: err.message || String(err),
5749
+ error: err instanceof Error ? err.message : String(err),
5036
5750
  }));
5037
5751
  }
5038
5752
  // Обёртка зависит от платформы:
@@ -5045,7 +5759,7 @@ guards) {
5045
5759
  try {
5046
5760
  if (scheduler.platform === "win32") {
5047
5761
  await ensureWrapper();
5048
- 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);
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));
5049
5763
  }
5050
5764
  else {
5051
5765
  wrapperPath = await writeBashWrapper({
@@ -5075,6 +5789,7 @@ guards) {
5075
5789
  worktreeHelper: worktreeHelperPath,
5076
5790
  guards: normalizedGuards,
5077
5791
  guardHelper: guardHelperPath,
5792
+ gateAllowPaths: gateAllowPathsFromAfterScript(normalizedAfter),
5078
5793
  ...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
5079
5794
  ? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized, getProfileName()) }
5080
5795
  : {}),
@@ -5083,7 +5798,7 @@ guards) {
5083
5798
  }
5084
5799
  catch (err) {
5085
5800
  throw new Error(t("tool.error.wrapper", {
5086
- error: err.message || String(err),
5801
+ error: err instanceof Error ? err.message : String(err),
5087
5802
  }));
5088
5803
  }
5089
5804
  // 27.5.5.3: при сбое создания новой задачи убираем подготовленные файлы.
@@ -5204,6 +5919,7 @@ guards) {
5204
5919
  legacyShell: legacyShell === true ? true : undefined,
5205
5920
  worktree: normalizedWorktree,
5206
5921
  guards: normalizedGuards,
5922
+ tokenBudget: normalizedTokenBudget,
5207
5923
  matrix: normalizedMatrix,
5208
5924
  isMatrixParent: normalizedMatrix ? true : undefined,
5209
5925
  matrixParentId,
@@ -5235,7 +5951,9 @@ guards) {
5235
5951
  // с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
5236
5952
  if (normalizedMatrix) {
5237
5953
  const createClone = async (clone) => {
5238
- 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);
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);
5239
5957
  };
5240
5958
  const removeChild = async (child) => {
5241
5959
  try {
@@ -5386,22 +6104,90 @@ async function recreateTaskFromDefinition(definition) {
5386
6104
  gitPaths: definition.gitPaths,
5387
6105
  gitIgnore: definition.gitIgnore,
5388
6106
  gitPollSeconds: definition.gitPollSeconds,
5389
- }, definition.runWhenLoggedOff, paused, definition.legacyShell, definition.worktree, definition.guards);
6107
+ }, definition.runWhenLoggedOff, paused, definition.legacyShell, definition.worktree, definition.guards,
6108
+ // QA-P0.1 (E-2.1): откат update не теряет tokenBudget.
6109
+ definition.tokenBudget);
5390
6110
  }
5391
6111
  /**
5392
6112
  * Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
5393
6113
  * на клоны, а не выполняет свой промпт.
5394
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
+ }
5395
6156
  async function runTaskEntry(name) {
5396
6157
  if (shutdownGate.isShuttingDown()) {
5397
- 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));
5398
6163
  }
5399
6164
  const run = (async () => {
5400
- 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
+ }
5401
6176
  if (definition?.matrix) {
5402
6177
  await runMatrix(definition);
5403
6178
  return { alreadyRunning: false };
5404
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
+ }
5405
6191
  // Любой запуск через этот вход — «сейчас», а не «по расписанию»:
5406
6192
  // run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
5407
6193
  // Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
@@ -5605,6 +6391,8 @@ async function collectTasksView() {
5605
6391
  deniedTools: Array.isArray(def?.deniedTools) ? def.deniedTools : null,
5606
6392
  matrix: def?.matrix ?? null,
5607
6393
  matrixParentId: def?.matrixParentId ?? null,
6394
+ /** Экономика v2 (E-2): лимит токенов на запуск для аналитики дашборда. */
6395
+ tokenBudget: def?.tokenBudget ?? null,
5608
6396
  isMatrixParent: Boolean(def?.matrix),
5609
6397
  matrixSummary: matrixAggregate
5610
6398
  ? {