agent-steward 0.0.2 → 0.0.4

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 (263) hide show
  1. package/CHANGELOG.md +45 -2
  2. package/CROSS_PLATFORM.md +11 -9
  3. package/README.md +11 -10
  4. package/ROADMAP-STRATEGY.md +93 -44
  5. package/ROADMAP.md +148 -1017
  6. package/dist/core/cron-to-schtasks.d.ts +0 -8
  7. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  8. package/dist/core/cron-to-schtasks.js +11 -86
  9. package/dist/core/dlq-api.d.ts +44 -0
  10. package/dist/core/dlq-api.d.ts.map +1 -0
  11. package/dist/core/dlq-api.js +68 -0
  12. package/dist/core/dry-run.d.ts.map +1 -1
  13. package/dist/core/dry-run.js +19 -2
  14. package/dist/core/file-watcher.js +9 -9
  15. package/dist/core/git-trigger.js +4 -4
  16. package/dist/core/lock.d.ts +20 -4
  17. package/dist/core/lock.d.ts.map +1 -1
  18. package/dist/core/lock.js +99 -26
  19. package/dist/core/one-shot.d.ts +31 -5
  20. package/dist/core/one-shot.d.ts.map +1 -1
  21. package/dist/core/one-shot.js +78 -10
  22. package/dist/core/opencode-cli.d.ts +28 -0
  23. package/dist/core/opencode-cli.d.ts.map +1 -0
  24. package/dist/core/opencode-cli.js +74 -0
  25. package/dist/core/opencode-models.d.ts +62 -0
  26. package/dist/core/opencode-models.d.ts.map +1 -0
  27. package/dist/core/opencode-models.js +277 -0
  28. package/dist/core/otel.js +2 -2
  29. package/dist/core/ps-wrapper.d.ts +1 -1
  30. package/dist/core/ps-wrapper.d.ts.map +1 -1
  31. package/dist/core/ps-wrapper.js +66 -36
  32. package/dist/core/record-history.d.ts +15 -0
  33. package/dist/core/record-history.d.ts.map +1 -1
  34. package/dist/core/record-history.js +78 -54
  35. package/dist/core/router/dispatch.d.ts +36 -0
  36. package/dist/core/router/dispatch.d.ts.map +1 -0
  37. package/dist/core/router/dispatch.js +59 -0
  38. package/dist/core/router/escalation.d.ts +47 -0
  39. package/dist/core/router/escalation.d.ts.map +1 -0
  40. package/dist/core/router/escalation.js +87 -0
  41. package/dist/core/router/planner.d.ts +53 -0
  42. package/dist/core/router/planner.d.ts.map +1 -0
  43. package/dist/core/router/planner.js +113 -0
  44. package/dist/core/router/rules.d.ts +46 -0
  45. package/dist/core/router/rules.d.ts.map +1 -0
  46. package/dist/core/router/rules.js +85 -0
  47. package/dist/core/run-panel-api.d.ts +94 -0
  48. package/dist/core/run-panel-api.d.ts.map +1 -0
  49. package/dist/core/run-panel-api.js +169 -0
  50. package/dist/core/schedule-gate.js +5 -1
  51. package/dist/core/schedule-v2.d.ts +36 -2
  52. package/dist/core/schedule-v2.d.ts.map +1 -1
  53. package/dist/core/schedule-v2.js +98 -12
  54. package/dist/core/scheduler/at-fallback.d.ts +95 -0
  55. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  56. package/dist/core/scheduler/at-fallback.js +200 -0
  57. package/dist/core/scheduler/linux.d.ts +13 -2
  58. package/dist/core/scheduler/linux.d.ts.map +1 -1
  59. package/dist/core/scheduler/linux.js +67 -13
  60. package/dist/core/scheduler/mac.d.ts +14 -8
  61. package/dist/core/scheduler/mac.d.ts.map +1 -1
  62. package/dist/core/scheduler/mac.js +71 -22
  63. package/dist/core/scheduler/posix.d.ts.map +1 -1
  64. package/dist/core/scheduler/posix.js +37 -2
  65. package/dist/core/scheduler/registry.d.ts +13 -0
  66. package/dist/core/scheduler/registry.d.ts.map +1 -1
  67. package/dist/core/scheduler/registry.js +83 -21
  68. package/dist/core/scheduler/run-now.d.ts +16 -0
  69. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  70. package/dist/core/scheduler/run-now.js +28 -0
  71. package/dist/core/scheduler/windows.d.ts +16 -3
  72. package/dist/core/scheduler/windows.d.ts.map +1 -1
  73. package/dist/core/scheduler/windows.js +249 -96
  74. package/dist/core/secrets.d.ts.map +1 -1
  75. package/dist/core/secrets.js +127 -30
  76. package/dist/core/self-analysis.js +55 -55
  77. package/dist/core/session.d.ts.map +1 -1
  78. package/dist/core/session.js +18 -11
  79. package/dist/core/summary.js +1 -1
  80. package/dist/core/task-name.d.ts +24 -0
  81. package/dist/core/task-name.d.ts.map +1 -0
  82. package/dist/core/task-name.js +40 -0
  83. package/dist/core/triage-chain.js +1 -1
  84. package/dist/core/triage-worker.js +2 -2
  85. package/dist/core/triage.js +1 -1
  86. package/dist/core/wrappers/bash.d.ts.map +1 -1
  87. package/dist/core/wrappers/bash.js +82 -37
  88. package/dist/db/capability-repo.d.ts +83 -0
  89. package/dist/db/capability-repo.d.ts.map +1 -0
  90. package/dist/db/capability-repo.js +182 -0
  91. package/dist/db/history-repo.d.ts +8 -0
  92. package/dist/db/history-repo.d.ts.map +1 -1
  93. package/dist/db/history-repo.js +19 -0
  94. package/dist/db/index.d.ts +6 -0
  95. package/dist/db/index.d.ts.map +1 -1
  96. package/dist/db/index.js +48 -2
  97. package/dist/db/migrate.d.ts.map +1 -1
  98. package/dist/db/migrate.js +3 -1
  99. package/dist/db/run-context.d.ts +103 -0
  100. package/dist/db/run-context.d.ts.map +1 -0
  101. package/dist/db/run-context.js +224 -0
  102. package/dist/db/run-dlq.d.ts +100 -0
  103. package/dist/db/run-dlq.d.ts.map +1 -0
  104. package/dist/db/run-dlq.js +191 -0
  105. package/dist/db/run-journal.d.ts +60 -0
  106. package/dist/db/run-journal.d.ts.map +1 -0
  107. package/dist/db/run-journal.js +143 -0
  108. package/dist/db/run-resume.d.ts +51 -0
  109. package/dist/db/run-resume.d.ts.map +1 -0
  110. package/dist/db/run-resume.js +156 -0
  111. package/dist/db/runs-repo.d.ts +128 -0
  112. package/dist/db/runs-repo.d.ts.map +1 -0
  113. package/dist/db/runs-repo.js +342 -0
  114. package/dist/db/schema.d.ts +16 -2
  115. package/dist/db/schema.d.ts.map +1 -1
  116. package/dist/db/schema.js +342 -35
  117. package/dist/db/settings-repo.d.ts +11 -0
  118. package/dist/db/settings-repo.d.ts.map +1 -1
  119. package/dist/db/settings-repo.js +25 -0
  120. package/dist/db/step-idempotency.d.ts +51 -0
  121. package/dist/db/step-idempotency.d.ts.map +1 -0
  122. package/dist/db/step-idempotency.js +136 -0
  123. package/dist/index.d.ts +5 -5
  124. package/dist/index.d.ts.map +1 -1
  125. package/dist/index.js +168 -40
  126. package/dist/notifications.js +18 -18
  127. package/dist/profiles.d.ts +7 -3
  128. package/dist/profiles.d.ts.map +1 -1
  129. package/dist/profiles.js +85 -7
  130. package/dist/rpc.d.ts +787 -0
  131. package/dist/rpc.d.ts.map +1 -1
  132. package/dist/rpc.js +324 -0
  133. package/dist/server.d.ts +33 -2
  134. package/dist/server.d.ts.map +1 -1
  135. package/dist/server.js +115 -54
  136. package/dist/shared/jobs-view.d.ts.map +1 -1
  137. package/dist/skill.js +1 -1
  138. package/dist/task-transfer.d.ts +1 -1
  139. package/dist/task-transfer.d.ts.map +1 -1
  140. package/dist/task-transfer.js +14 -10
  141. package/dist/types.d.ts +20 -4
  142. package/dist/types.d.ts.map +1 -1
  143. package/dist/types.js +44 -9
  144. package/dist/workspaces.d.ts +25 -3
  145. package/dist/workspaces.d.ts.map +1 -1
  146. package/dist/workspaces.js +44 -9
  147. package/docs/ARCHITECTURE.md +335 -9
  148. package/docs/COMPATIBILITY.md +10 -6
  149. package/docs/CONCEPT.md +183 -91
  150. package/docs/CROSS_PLATFORM.ru.md +11 -9
  151. package/docs/CROSS_PLATFORM.zh.md +11 -9
  152. package/docs/EXECUTION-LOOP.md +196 -0
  153. package/docs/FAQ.md +2 -2
  154. package/docs/FAQ.ru.md +2 -2
  155. package/docs/FAQ.zh.md +2 -2
  156. package/docs/FEATURES.md +5 -4
  157. package/docs/FEATURES.zh.md +5 -4
  158. package/docs/MIGRATION.md +34 -26
  159. package/docs/README.ru.md +27 -8
  160. package/docs/README.zh.md +11 -10
  161. package/docs/SAFETY.md +122 -0
  162. package/docs/SAVINGS.md +29 -0
  163. package/docs/SAVINGS.ru.md +29 -0
  164. package/docs/SAVINGS.zh.md +18 -0
  165. package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
  166. package/gui-experimental.cjs +8 -8
  167. package/index.js +1 -0
  168. package/locales/en.json +68 -0
  169. package/locales/ru.json +68 -0
  170. package/locales/zh.json +68 -0
  171. package/package.json +57 -11
  172. package/scripts/audit-bundle.mjs +215 -0
  173. package/src/core/analytics.ts +2 -2
  174. package/src/core/audit.ts +17 -17
  175. package/src/core/cron-to-schtasks.ts +14 -93
  176. package/src/core/dlq-api.ts +98 -0
  177. package/src/core/dry-run.ts +51 -27
  178. package/src/core/file-watcher.ts +17 -17
  179. package/src/core/git-trigger.ts +9 -9
  180. package/src/core/glob.ts +1 -1
  181. package/src/core/local-ai.ts +2 -2
  182. package/src/core/lock.ts +104 -31
  183. package/src/core/matrix.ts +31 -31
  184. package/src/core/native-notify.ts +2 -2
  185. package/src/core/one-shot.ts +91 -13
  186. package/src/core/opencode-cli.ts +103 -0
  187. package/src/core/opencode-models.ts +315 -0
  188. package/src/core/otel.ts +4 -4
  189. package/src/core/permissions.ts +5 -5
  190. package/src/core/prometheus.ts +17 -17
  191. package/src/core/ps-wrapper.ts +68 -38
  192. package/src/core/record-history.ts +114 -76
  193. package/src/core/retention.ts +3 -3
  194. package/src/core/router/dispatch.ts +94 -0
  195. package/src/core/router/escalation.ts +129 -0
  196. package/src/core/router/planner.ts +166 -0
  197. package/src/core/router/rules.ts +109 -0
  198. package/src/core/run-panel-api.ts +262 -0
  199. package/src/core/savings.ts +1 -1
  200. package/src/core/schedule-gate.ts +17 -13
  201. package/src/core/schedule-v2.ts +138 -29
  202. package/src/core/scheduler/at-fallback.ts +298 -0
  203. package/src/core/scheduler/index.ts +3 -3
  204. package/src/core/scheduler/linux.ts +92 -19
  205. package/src/core/scheduler/logs.ts +1 -1
  206. package/src/core/scheduler/mac.ts +112 -60
  207. package/src/core/scheduler/posix.ts +35 -2
  208. package/src/core/scheduler/registry.ts +109 -26
  209. package/src/core/scheduler/run-now.ts +32 -0
  210. package/src/core/scheduler/windows.ts +295 -125
  211. package/src/core/secrets.ts +139 -39
  212. package/src/core/self-analysis.ts +61 -61
  213. package/src/core/session.ts +26 -13
  214. package/src/core/structured-log.ts +3 -3
  215. package/src/core/summary.ts +25 -25
  216. package/src/core/task-name.ts +67 -0
  217. package/src/core/telegram.ts +16 -16
  218. package/src/core/triage-chain.ts +4 -4
  219. package/src/core/triage-compare.ts +8 -8
  220. package/src/core/triage-rules.ts +4 -4
  221. package/src/core/triage-shadow.ts +7 -7
  222. package/src/core/triage-worker.ts +6 -6
  223. package/src/core/triage.ts +23 -23
  224. package/src/core/watch-paths.ts +1 -1
  225. package/src/core/wrappers/bash.ts +90 -45
  226. package/src/db/capability-repo.ts +285 -0
  227. package/src/db/git-state-repo.ts +1 -1
  228. package/src/db/history-repo.ts +44 -22
  229. package/src/db/index.ts +53 -7
  230. package/src/db/metrics-repo.ts +10 -10
  231. package/src/db/migrate.ts +13 -11
  232. package/src/db/recovery.ts +3 -3
  233. package/src/db/run-context.ts +370 -0
  234. package/src/db/run-dlq.ts +310 -0
  235. package/src/db/run-journal.ts +212 -0
  236. package/src/db/run-resume.ts +256 -0
  237. package/src/db/runs-repo.ts +504 -0
  238. package/src/db/schema.ts +357 -44
  239. package/src/db/settings-repo.ts +33 -2
  240. package/src/db/step-idempotency.ts +185 -0
  241. package/src/db/tasks-repo.ts +10 -10
  242. package/src/db/templates-repo.ts +7 -7
  243. package/src/gui.tsx +516 -1
  244. package/src/history.ts +4 -4
  245. package/src/i18n.ts +7 -7
  246. package/src/index.ts +465 -308
  247. package/src/integrations.ts +6 -6
  248. package/src/notifications.ts +76 -76
  249. package/src/profiles.ts +98 -7
  250. package/src/rpc.ts +347 -1
  251. package/src/schtasks.ts +2 -2
  252. package/src/server.ts +155 -78
  253. package/src/settings.ts +44 -44
  254. package/src/shared/jobs-view.ts +60 -60
  255. package/src/skill.ts +1 -1
  256. package/src/task-transfer.ts +58 -56
  257. package/src/templates.ts +1 -1
  258. package/src/types.ts +54 -10
  259. package/src/workspaces.ts +73 -24
  260. package/dist/core/self-analysis.test.d.ts +0 -2
  261. package/dist/core/self-analysis.test.d.ts.map +0 -1
  262. package/dist/core/self-analysis.test.js +0 -219
  263. package/dist/gui-experimental.cjs +0 -1
package/src/index.ts CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  type PluginModule as V1PluginModule,
7
7
  } from "@opencode-ai/plugin";
8
8
  import { z } from "zod";
9
- import { Tool } from "@opencode/schema/tool";
9
+ import type { Tool } from "@opencode/schema/tool";
10
10
  import { createRequire } from "node:module";
11
11
  import { existsSync } from "node:fs";
12
12
  import fs from "node:fs/promises";
@@ -19,9 +19,10 @@ import {
19
19
  STALE_LOCK_MAX_AGE_MS,
20
20
  WRAPPER_DIR,
21
21
  sanitizeName,
22
+ validateModelId,
22
23
  validateTaskName,
23
24
  } from "./types.js";
24
- import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
25
+ import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs, assessCronWindowFeasibility, windowFeasibilityReasonText } from "./core/schedule-v2.js";
25
26
  import {
26
27
  buildLaunchdOneShotCleanup,
27
28
  normalizeOneShotRunAt,
@@ -35,9 +36,10 @@ import {
35
36
  type SessionMode,
36
37
  } from "./core/session.js";
37
38
  import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
38
- import { getSchedulerBackend } from "./core/scheduler/index.js";
39
+ import { getSchedulerBackend, LinuxScheduler } from "./core/scheduler/index.js";
39
40
  import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
40
41
  import { getTaskLogs } from "./core/scheduler/logs.js";
42
+ import { findSanitizedNameConflict, sanitizedConflictMessage } from "./core/task-name.js";
41
43
  import { writeBashWrapper } from "./core/wrappers/bash.js";
42
44
  import { simulatePipeline } from "./core/dry-run.js";
43
45
  import {
@@ -77,6 +79,12 @@ import { buildAnalytics } from "./core/analytics.js";
77
79
  import { generateSelfAnalysisReport } from "./core/self-analysis.js";
78
80
  import { getHistory, listRunningRecords } from "./db/history-repo.js";
79
81
  import { getAllMetrics } from "./db/metrics-repo.js";
82
+ import { discardDlq, listDlq, retryDlq } from "./core/dlq-api.js";
83
+ import {
84
+ listRunPanel,
85
+ pauseRunPanel,
86
+ resumeRunPanel,
87
+ } from "./core/run-panel-api.js";
80
88
  import {
81
89
  findStuckMatrixClones,
82
90
  maybeSendDigest,
@@ -172,8 +180,8 @@ const recorderPath = (() => {
172
180
  .replace(/\.ts$/, ".js");
173
181
  if (existsSync(distPath)) return distPath;
174
182
  console.warn(
175
- "[windows-scheduler] Не найден собранный record-history.js: " +
176
- `${distPath}. История/метрики не будут записываться. Выполните npm run build.`
183
+ "[agent-steward] Не найден собранный record-history.js: " +
184
+ `${distPath}. История/метрики не будут записываться. Выполните npm run build.`,
177
185
  );
178
186
  return distPath;
179
187
  })();
@@ -190,8 +198,8 @@ const gatePath = (() => {
190
198
  .replace(/\.ts$/, ".js");
191
199
  if (existsSync(distPath)) return distPath;
192
200
  console.warn(
193
- "[windows-scheduler] Не найден собранный schedule-gate.js: " +
194
- `${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`
201
+ "[agent-steward] Не найден собранный schedule-gate.js: " +
202
+ `${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`,
195
203
  );
196
204
  return distPath;
197
205
  })();
@@ -217,37 +225,37 @@ export const matrixSchema = z.object({
217
225
  .enum(["parallel", "sequential"])
218
226
  .optional()
219
227
  .describe(
220
- "parallel (default) starts all clones at once; sequential starts the next clone only after the previous one finishes."
228
+ "parallel (default) starts all clones at once; sequential starts the next clone only after the previous one finishes.",
221
229
  ),
222
230
  failureMode: z
223
231
  .enum(["continue", "stop"])
224
232
  .optional()
225
233
  .describe(
226
- "continue (default) keeps running the remaining clones after a failure; stop aborts the rest."
234
+ "continue (default) keeps running the remaining clones after a failure; stop aborts the rest.",
227
235
  ),
228
236
  aggregation: z
229
237
  .enum(["summary", "per-task"])
230
238
  .optional()
231
239
  .describe(
232
- "summary (default) writes one aggregate record for the parent; per-task keeps per-clone records."
240
+ "summary (default) writes one aggregate record for the parent; per-task keeps per-clone records.",
233
241
  ),
234
242
  createAggregator: z
235
243
  .boolean()
236
244
  .optional()
237
245
  .describe(
238
- "Also create the <parent>-matrix-complete task depending on every clone."
246
+ "Also create the <parent>-matrix-complete task depending on every clone.",
239
247
  ),
240
248
  concurrency: z
241
249
  .number()
242
250
  .optional()
243
251
  .describe(
244
- "Maximum number of clones running at the same time (>= 1). Ignored for sequential (always 1) and capped by the global maxConcurrent setting."
252
+ "Maximum number of clones running at the same time (>= 1). Ignored for sequential (always 1) and capped by the global maxConcurrent setting.",
245
253
  ),
246
254
  overrides: z
247
255
  .record(z.string(), matrixOverrideSchema)
248
256
  .optional()
249
257
  .describe(
250
- "Per-workspace overrides keyed by workspace id. Keys must be present in workspaceIds."
258
+ "Per-workspace overrides keyed by workspace id. Keys must be present in workspaceIds.",
251
259
  ),
252
260
  });
253
261
 
@@ -256,19 +264,19 @@ export const scheduleTaskSchema = z.object({
256
264
  name: z
257
265
  .string()
258
266
  .describe(
259
- "Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen."
267
+ "Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen.",
260
268
  ),
261
269
  schedule: z
262
270
  .string()
263
271
  .optional()
264
272
  .describe(
265
- "Cron expression (5 fields: minute hour day-of-month month day-of-week). Required for triggerType=cron; ignored for file/mcp-event. Supports ranges, lists, */N steps, month/weekday names, @every 15m|2h|1d, L (last day of month) and FRI#3 (third Friday). Expressions schtasks cannot express are checked every minute inside the wrapper."
273
+ "Cron expression (5 fields: minute hour day-of-month month day-of-week). Required for triggerType=cron; ignored for file/mcp-event. Supports ranges, lists, */N steps, month/weekday names, @every 15m|2h|1d, L (last day of month) and FRI#3 (third Friday). Expressions schtasks cannot express are checked every minute inside the wrapper.",
266
274
  ),
267
275
  runAt: z
268
276
  .string()
269
277
  .optional()
270
278
  .describe(
271
- "Absolute one-shot start time in ISO-8601 (e.g. 2026-12-01T09:00:00Z). Requires triggerType=once; mutually exclusive with delaySeconds (runAt wins)."
279
+ "Absolute one-shot start time in ISO-8601 (e.g. 2026-12-01T09:00:00Z). Requires triggerType=once; mutually exclusive with delaySeconds (runAt wins).",
272
280
  ),
273
281
  delaySeconds: z
274
282
  .number()
@@ -276,13 +284,13 @@ export const scheduleTaskSchema = z.object({
276
284
  .positive()
277
285
  .optional()
278
286
  .describe(
279
- "One-shot delay in seconds from now. Requires triggerType=once. Convenient alternative to runAt."
287
+ "One-shot delay in seconds from now. Requires triggerType=once. Convenient alternative to runAt.",
280
288
  ),
281
289
  session: z
282
290
  .enum(["new", "reuse", "last"])
283
291
  .optional()
284
292
  .describe(
285
- "OpenCode session mode for the task: new (default, fresh session per run), reuse (keep a persistent session stored on the task — sessionId is auto-generated), last (continue the latest session via --continue)."
293
+ "OpenCode session mode for the task: new (default, fresh session per run), reuse (keep a persistent session stored on the task — sessionId is auto-generated), last (continue the latest session via --continue).",
286
294
  ),
287
295
  sessionMaxRuns: z
288
296
  .number()
@@ -291,19 +299,19 @@ export const scheduleTaskSchema = z.object({
291
299
  .max(10000)
292
300
  .optional()
293
301
  .describe(
294
- "Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit."
302
+ "Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit.",
295
303
  ),
296
304
  timezone: z
297
305
  .string()
298
306
  .optional()
299
307
  .describe(
300
- "IANA timezone of the schedule, e.g. Europe/Moscow. Defaults to the system timezone. A zone different from the system one is evaluated by the wrapper (poll mode)."
308
+ "IANA timezone of the schedule, e.g. Europe/Moscow. Defaults to the system timezone. A zone different from the system one is evaluated by the wrapper (poll mode).",
301
309
  ),
302
310
  notBefore: z
303
311
  .string()
304
312
  .optional()
305
313
  .describe(
306
- "Launch window start in HH:MM (24h). Together with notAfter: a run outside the window is postponed to the next window opening, not skipped."
314
+ "Launch window start in HH:MM (24h). Together with notAfter: a run outside the window is postponed to the next window opening, not skipped.",
307
315
  ),
308
316
  notAfter: z
309
317
  .string()
@@ -320,7 +328,7 @@ export const scheduleTaskSchema = z.object({
320
328
  .string()
321
329
  .optional()
322
330
  .describe(
323
- "LLM model in OpenCode format, e.g. anthropic/claude-3-5-sonnet. Defaults to the OpenCode default model."
331
+ "LLM model in OpenCode format, e.g. anthropic/claude-3-5-sonnet. Defaults to the OpenCode default model.",
324
332
  ),
325
333
  priority: z
326
334
  .number()
@@ -330,25 +338,25 @@ export const scheduleTaskSchema = z.object({
330
338
  .string()
331
339
  .optional()
332
340
  .describe(
333
- "Pre-flight shell command executed before the run (e.g. git pull). A non-zero exit code cancels the run."
341
+ "Pre-flight shell command executed before the run (e.g. git pull). A non-zero exit code cancels the run.",
334
342
  ),
335
343
  afterScript: z
336
344
  .string()
337
345
  .optional()
338
346
  .describe(
339
- "Post-flight shell command executed after the run (e.g. git push). Runs even when the task fails."
347
+ "Post-flight shell command executed after the run (e.g. git push). Runs even when the task fails.",
340
348
  ),
341
349
  qualityGate: z
342
350
  .string()
343
351
  .optional()
344
352
  .describe(
345
- "Shell command executed after a successful AI response (e.g. npm test). A non-zero exit code marks the run as a Quality Gate failure."
353
+ "Shell command executed after a successful AI response (e.g. npm test). A non-zero exit code marks the run as a Quality Gate failure.",
346
354
  ),
347
355
  dependsOn: z
348
356
  .array(z.string())
349
357
  .optional()
350
358
  .describe(
351
- "DAG dependencies: tasks that must finish successfully before this task starts."
359
+ "DAG dependencies: tasks that must finish successfully before this task starts.",
352
360
  ),
353
361
  retryCount: z
354
362
  .number()
@@ -370,7 +378,7 @@ export const scheduleTaskSchema = z.object({
370
378
  .enum(["cron", "file", "git", "mcp-event", "once"])
371
379
  .optional()
372
380
  .describe(
373
- "Trigger type: cron (default), file, git (new commits in the task working directory), mcp-event or once (single run at runAt/delaySeconds)."
381
+ "Trigger type: cron (default), file, git (new commits in the task working directory), mcp-event or once (single run at runAt/delaySeconds).",
374
382
  ),
375
383
  mcpEvent: z
376
384
  .object({
@@ -380,37 +388,37 @@ export const scheduleTaskSchema = z.object({
380
388
  })
381
389
  .optional()
382
390
  .describe(
383
- "MCP event trigger: server, event name and an optional filter (key=value or regex)."
391
+ "MCP event trigger: server, event name and an optional filter (key=value or regex).",
384
392
  ),
385
393
  watchPath: z
386
394
  .string()
387
395
  .optional()
388
396
  .describe(
389
- "File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."
397
+ "File or directory to watch when triggerType is \"file\". Can be set here or later via update_task.",
390
398
  ),
391
399
  watchGlobs: z
392
400
  .array(z.string())
393
401
  .optional()
394
402
  .describe(
395
- "Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath."
403
+ "Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath.",
396
404
  ),
397
405
  watchIgnore: z
398
406
  .array(z.string())
399
407
  .optional()
400
408
  .describe(
401
- "Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include."
409
+ "Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include.",
402
410
  ),
403
411
  gitBranch: z
404
412
  .string()
405
413
  .optional()
406
414
  .describe(
407
- "Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch."
415
+ "Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch.",
408
416
  ),
409
417
  gitPaths: z
410
418
  .array(z.string())
411
419
  .optional()
412
420
  .describe(
413
- "Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only)."
421
+ "Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only).",
414
422
  ),
415
423
  gitIgnore: z
416
424
  .array(z.string())
@@ -426,54 +434,54 @@ export const scheduleTaskSchema = z.object({
426
434
  .array(z.number().int().min(0).max(6))
427
435
  .optional()
428
436
  .describe(
429
- "Allowed weekdays 0=Sunday..6=Saturday for cron and event triggers. Empty or all seven means every day."
437
+ "Allowed weekdays 0=Sunday..6=Saturday for cron and event triggers. Empty or all seven means every day.",
430
438
  ),
431
439
  windowPolicy: z
432
440
  .enum(["skip", "postpone", "run"])
433
441
  .optional()
434
442
  .describe(
435
- "Behaviour outside the launch window / active days: postpone (default, wait for the next opening), skip or run anyway."
443
+ "Behaviour outside the launch window / active days: postpone (default, wait for the next opening), skip or run anyway.",
436
444
  ),
437
445
  workingDirectory: z
438
446
  .string()
439
447
  .optional()
440
448
  .describe(
441
- "Working directory of the task. Defaults to the current project folder so opencode run picks up the project's opencode.json with MCP servers."
449
+ "Working directory of the task. Defaults to the current project folder so opencode run picks up the project's opencode.json with MCP servers.",
442
450
  ),
443
451
  workspaceId: z
444
452
  .string()
445
453
  .optional()
446
454
  .describe(
447
- "Multi-repo workspace binding. When set, cwd = workspace path and workingDirectory is ignored."
455
+ "Multi-repo workspace binding. When set, cwd = workspace path and workingDirectory is ignored.",
448
456
  ),
449
457
  allowedTools: z
450
458
  .array(z.string())
451
459
  .optional()
452
460
  .describe(
453
- "Role-scoped tool allow-list, enforced through OPENCODE_CONFIG_CONTENT. A non-empty list also allows actions that the default policy denies (for example shell). An empty array is rejected."
461
+ "Role-scoped tool allow-list, enforced through OPENCODE_CONFIG_CONTENT. A non-empty list also allows actions that the default policy denies (for example shell). An empty array is rejected.",
454
462
  ),
455
463
  deniedTools: z
456
464
  .array(z.string())
457
465
  .optional()
458
466
  .describe(
459
- "Role-scoped tool deny-list (takes precedence over allowedTools and over the default policy). Enforced through OPENCODE_CONFIG_CONTENT."
467
+ "Role-scoped tool deny-list (takes precedence over allowedTools and over the default policy). Enforced through OPENCODE_CONFIG_CONTENT.",
460
468
  ),
461
469
  legacyShell: z
462
470
  .boolean()
463
471
  .optional()
464
472
  .describe(
465
- "Transitional flag (release 1.6): under the hybrid policy, re-enable shell for this task. Prefer listing shell in allowedTools. Ignored by secure/legacy policy."
473
+ "Transitional flag (release 1.6): under the hybrid policy, re-enable shell for this task. Prefer listing shell in allowedTools. Ignored by secure/legacy policy.",
466
474
  ),
467
475
  runWhenLoggedOff: z
468
476
  .boolean()
469
477
  .optional()
470
478
  .describe(
471
- "Windows only: run the task even when no user is logged on (/ru SYSTEM). The task runs in session 0 without the user's profile, mapped drives or saved credentials, so tasks that need the user's environment may fail. Creating such a task usually requires an elevated shell. Default false: interactive only — the task runs only while the user is logged on."
479
+ "Windows only: run the task even when no user is logged on (/ru SYSTEM). The task runs in session 0 without the user's profile, mapped drives or saved credentials, so tasks that need the user's environment may fail. Creating such a task usually requires an elevated shell. Default false: interactive only — the task runs only while the user is logged on.",
472
480
  ),
473
481
  matrix: matrixSchema
474
482
  .optional()
475
483
  .describe(
476
- "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."
484
+ "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.",
477
485
  ),
478
486
  }).superRefine((value, ctx) => {
479
487
  const trigger = value.triggerType ?? "cron";
@@ -531,7 +539,7 @@ export const updateTaskSchema = z.object({
531
539
  .string()
532
540
  .optional()
533
541
  .describe(
534
- "New one-shot time in ISO-8601. Requires triggerType=once. Empty string clears it."
542
+ "New one-shot time in ISO-8601. Requires triggerType=once. Empty string clears it.",
535
543
  ),
536
544
  delaySeconds: z
537
545
  .number()
@@ -539,13 +547,13 @@ export const updateTaskSchema = z.object({
539
547
  .positive()
540
548
  .optional()
541
549
  .describe(
542
- "New one-shot delay in seconds from now. Requires triggerType=once."
550
+ "New one-shot delay in seconds from now. Requires triggerType=once.",
543
551
  ),
544
552
  session: z
545
553
  .enum(["new", "reuse", "last"])
546
554
  .optional()
547
555
  .describe(
548
- "OpenCode session mode for the task: new (fresh session per run), reuse (keep a persistent session stored on the task — sessionId is auto-generated), last (continue the latest session via --continue)."
556
+ "OpenCode session mode for the task: new (fresh session per run), reuse (keep a persistent session stored on the task — sessionId is auto-generated), last (continue the latest session via --continue).",
549
557
  ),
550
558
  sessionMaxRuns: z
551
559
  .number()
@@ -554,7 +562,7 @@ export const updateTaskSchema = z.object({
554
562
  .max(10000)
555
563
  .optional()
556
564
  .describe(
557
- "Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit."
565
+ "Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit.",
558
566
  ),
559
567
  timezone: z
560
568
  .string()
@@ -572,7 +580,7 @@ export const updateTaskSchema = z.object({
572
580
  .array(z.number().int().min(0).max(6))
573
581
  .optional()
574
582
  .describe(
575
- "New allowed weekdays 0=Sunday..6=Saturday. Empty array clears the restriction."
583
+ "New allowed weekdays 0=Sunday..6=Saturday. Empty array clears the restriction.",
576
584
  ),
577
585
  windowPolicy: z
578
586
  .enum(["skip", "postpone", "run"])
@@ -582,7 +590,7 @@ export const updateTaskSchema = z.object({
582
590
  .boolean()
583
591
  .optional()
584
592
  .describe(
585
- "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."
593
+ "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.",
586
594
  ),
587
595
  watchGlobs: z
588
596
  .array(z.string())
@@ -682,13 +690,13 @@ export const updateTaskSchema = z.object({
682
690
  .boolean()
683
691
  .optional()
684
692
  .describe(
685
- "Transitional flag (release 1.6): re-enable shell under the hybrid policy for this task."
693
+ "Transitional flag (release 1.6): re-enable shell under the hybrid policy for this task.",
686
694
  ),
687
695
  matrix: matrixSchema
688
696
  .nullable()
689
697
  .optional()
690
698
  .describe(
691
- "New matrix configuration. Pass null to turn the matrix off (clones and aggregator are removed)."
699
+ "New matrix configuration. Pass null to turn the matrix off (clones and aggregator are removed).",
692
700
  ),
693
701
  }).superRefine((value, ctx) => {
694
702
  if (
@@ -717,7 +725,7 @@ const pauseTaskSchema = z.object({
717
725
  .string()
718
726
  .optional()
719
727
  .describe(
720
- "Optional ISO date/time to resume automatically (e.g. 2026-12-01T09:00:00Z). The plugin re-enables the task at that moment."
728
+ "Optional ISO date/time to resume automatically (e.g. 2026-12-01T09:00:00Z). The plugin re-enables the task at that moment.",
721
729
  ),
722
730
  });
723
731
 
@@ -753,7 +761,7 @@ const dryRunSchema = z.object({
753
761
  .string()
754
762
  .optional()
755
763
  .describe(
756
- "Task name to simulate. When omitted, every task is simulated (pipeline dry run, nothing is executed)."
764
+ "Task name to simulate. When omitted, every task is simulated (pipeline dry run, nothing is executed).",
757
765
  ),
758
766
  });
759
767
 
@@ -770,7 +778,7 @@ const manageWorkspacesSchema = z.object({
770
778
  .nullable()
771
779
  .optional()
772
780
  .describe(
773
- "Workspace environment variables (key → value). Override envFile values; secrets are masked in logs (add/update)."
781
+ "Workspace environment variables (key → value). Override envFile values; secrets are masked in logs (add/update).",
774
782
  ),
775
783
  envFile: z
776
784
  .string()
@@ -783,7 +791,7 @@ export const matrixControlSchema = z.object({
783
791
  action: z
784
792
  .enum(["results", "cancel", "cleanup", "preview"])
785
793
  .describe(
786
- "results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators; preview — dry-expand a matrix config into clone names without creating anything."
794
+ "results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators; preview — dry-expand a matrix config into clone names without creating anything.",
787
795
  ),
788
796
  name: z
789
797
  .string()
@@ -874,7 +882,7 @@ export const manageSettingsSchema = z.object({
874
882
  .enum(["auto", "ru", "en", "zh"])
875
883
  .optional()
876
884
  .describe(
877
- "Interface language: auto (follow OpenCode), ru (default), en or zh. Applies without restart."
885
+ "Interface language: auto (follow OpenCode), ru (default), en or zh. Applies without restart.",
878
886
  ),
879
887
  winterMode: z
880
888
  .boolean()
@@ -895,7 +903,7 @@ export const manageSettingsSchema = z.object({
895
903
  .any()
896
904
  .optional()
897
905
  .describe(
898
- "Integration settings patch (hooks: enabled, token, secret, requireSignature, maxBodyBytes, timestampToleranceSeconds)."
906
+ "Integration settings patch (hooks: enabled, token, secret, requireSignature, maxBodyBytes, timestampToleranceSeconds).",
899
907
  ),
900
908
  audit: z
901
909
  .any()
@@ -907,7 +915,7 @@ export const manageSettingsSchema = z.object({
907
915
  })
908
916
  .optional()
909
917
  .describe(
910
- "Tool permission policy for background tasks: hybrid (default; shell/question denied), secure (read-only), legacy (allow everything, 1.5.x behaviour)."
918
+ "Tool permission policy for background tasks: hybrid (default; shell/question denied), secure (read-only), legacy (allow everything, 1.5.x behaviour).",
911
919
  ),
912
920
  });
913
921
 
@@ -916,20 +924,20 @@ export const manageLocalAiSchema = z.object({
916
924
  action: z
917
925
  .enum(["get", "update", "test"])
918
926
  .describe(
919
- "get — current triage settings and shadow state; update — merge fields and save; test — one classification request against the configured model."
927
+ "get — current triage settings and shadow state; update — merge fields and save; test — one classification request against the configured model.",
920
928
  ),
921
929
  mode: z
922
930
  .enum(["off", "rules", "llm", "auto"])
923
931
  .optional()
924
932
  .describe(
925
- "off — no triage; rules — built-in rules only; llm — model only; auto — model, then rules (default)."
933
+ "off — no triage; rules — built-in rules only; llm — model only; auto — model, then rules (default).",
926
934
  ),
927
935
  baseUrl: z
928
936
  .string()
929
937
  .max(500)
930
938
  .optional()
931
939
  .describe(
932
- "Ollama or OpenAI-compatible base URL, for example http://127.0.0.1:11434. A URL ending with /v1 switches to the OpenAI protocol."
940
+ "Ollama or OpenAI-compatible base URL, for example http://127.0.0.1:11434. A URL ending with /v1 switches to the OpenAI protocol.",
933
941
  ),
934
942
  model: z
935
943
  .string()
@@ -947,7 +955,7 @@ export const manageLocalAiSchema = z.object({
947
955
  .enum(["rules", "notify", "skip"])
948
956
  .optional()
949
957
  .describe(
950
- "When the model fails or is unsure: rules - apply rules (fail-open, default); notify - skip the rules step and deliver the notification; skip - legacy alias for notify."
958
+ "When the model fails or is unsure: rules - apply rules (fail-open, default); notify - skip the rules step and deliver the notification; skip - legacy alias for notify.",
951
959
  ),
952
960
  confidenceThreshold: z
953
961
  .number()
@@ -1110,7 +1118,7 @@ let projectDirectory: string | undefined;
1110
1118
  * Использует Tool.Context из @opencode/schema/tool.
1111
1119
  */
1112
1120
  function wrapExecute<Args>(
1113
- fn: (args: Args, ctx: Tool.Context) => Promise<Tool.Result>
1121
+ fn: (args: Args, ctx: Tool.Context) => Promise<Tool.Result>,
1114
1122
  ): (input: Args, context: Tool.Context) => Promise<Tool.Result> {
1115
1123
  return async (input, context) => {
1116
1124
  try {
@@ -1152,7 +1160,7 @@ function computeTaskNextRun(
1152
1160
  | "pausedUntil"
1153
1161
  >
1154
1162
  | undefined,
1155
- options: { paused?: boolean; now?: Date } = {}
1163
+ options: { paused?: boolean; now?: Date } = {},
1156
1164
  ): string | null {
1157
1165
  if (!def) return null;
1158
1166
  if (options.paused) return null;
@@ -1319,7 +1327,7 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
1319
1327
  // Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
1320
1328
  runWhenLoggedOff === true,
1321
1329
  undefined,
1322
- legacyShell === true
1330
+ legacyShell === true,
1323
1331
  );
1324
1332
  } catch (err: any) {
1325
1333
  return {
@@ -1429,10 +1437,10 @@ const listTasksExecute = wrapExecute<ListArgs>(async () => {
1429
1437
  * чтобы матрицу можно было запустить повторно.
1430
1438
  */
1431
1439
  async function cancelMatrixRun(
1432
- name: string
1440
+ name: string,
1433
1441
  ): Promise<{ cancelled: string[]; running: string[]; message: string; warnings: string[] }> {
1434
1442
  const definition = (await loadTaskDefinitions()).find(
1435
- (def) => def.name.toLowerCase() === name.trim().toLowerCase()
1443
+ (def) => def.name.toLowerCase() === name.trim().toLowerCase(),
1436
1444
  );
1437
1445
  if (!definition?.matrix) {
1438
1446
  throw new Error(t("tool.error.matrixNotMatrix", { name }));
@@ -1443,7 +1451,7 @@ async function cancelMatrixRun(
1443
1451
 
1444
1452
  for (const cloneName of result.running) {
1445
1453
  const clone = (await loadTaskDefinitions()).find(
1446
- (def) => def.name.toLowerCase() === cloneName.toLowerCase()
1454
+ (def) => def.name.toLowerCase() === cloneName.toLowerCase(),
1447
1455
  );
1448
1456
  if (!clone) continue;
1449
1457
 
@@ -1455,7 +1463,7 @@ async function cancelMatrixRun(
1455
1463
  t("tool.matrix.stopFailed", {
1456
1464
  clone: clone.name,
1457
1465
  error: err instanceof Error ? err.message : String(err),
1458
- })
1466
+ }),
1459
1467
  );
1460
1468
  continue;
1461
1469
  }
@@ -1498,14 +1506,14 @@ async function cancelMatrixRun(
1498
1506
  undefined,
1499
1507
  clone.runWhenLoggedOff,
1500
1508
  clone.paused,
1501
- clone.legacyShell
1509
+ clone.legacyShell,
1502
1510
  );
1503
1511
  } catch (err: any) {
1504
1512
  warnings.push(
1505
1513
  t("tool.matrix.recreateFailed", {
1506
1514
  clone: clone.name,
1507
1515
  error: err instanceof Error ? err.message : String(err),
1508
- })
1516
+ }),
1509
1517
  );
1510
1518
  }
1511
1519
  }
@@ -1556,7 +1564,7 @@ async function cleanupOrphanedMatrixTasks(): Promise<string[]> {
1556
1564
 
1557
1565
  if (removed.length > 0) {
1558
1566
  console.log(
1559
- `[matrix] Очищены осиротевшие задачи матриц: ${removed.join(", ")}`
1567
+ `[matrix] Очищены осиротевшие задачи матриц: ${removed.join(", ")}`,
1560
1568
  );
1561
1569
  }
1562
1570
  return removed;
@@ -1647,7 +1655,7 @@ async function garbageCollectTaskArtifacts(): Promise<void> {
1647
1655
  }
1648
1656
 
1649
1657
  async function deleteTaskWithFamily(
1650
- name: string
1658
+ name: string,
1651
1659
  ): Promise<{ removed: string[]; existed: boolean }> {
1652
1660
  const trimmed = name.trim();
1653
1661
  const guard = getMatrixDeletionGuard(trimmed);
@@ -1663,7 +1671,7 @@ async function deleteTaskWithFamily(
1663
1671
  try {
1664
1672
  const osTasks = await scheduler.listTasks();
1665
1673
  existed = osTasks.some(
1666
- (task) => task.taskName.toLowerCase() === trimmed.toLowerCase()
1674
+ (task) => task.taskName.toLowerCase() === trimmed.toLowerCase(),
1667
1675
  );
1668
1676
  } catch {
1669
1677
  // ОС-планировщик недоступен — довольствуемся данными БД.
@@ -1768,7 +1776,7 @@ const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
1768
1776
  */
1769
1777
  function clearableString(
1770
1778
  next: string | undefined,
1771
- current: string | undefined
1779
+ current: string | undefined,
1772
1780
  ): string | undefined {
1773
1781
  if (next === undefined) return current;
1774
1782
  const trimmed = next.trim();
@@ -1777,7 +1785,7 @@ function clearableString(
1777
1785
 
1778
1786
  function clearableList(
1779
1787
  next: string[] | undefined,
1780
- current: string[] | undefined
1788
+ current: string[] | undefined,
1781
1789
  ): string[] | undefined {
1782
1790
  if (next === undefined) return current;
1783
1791
  const cleaned = next.map((value) => value.trim()).filter(Boolean);
@@ -1808,7 +1816,7 @@ async function removeMatrixChildrenFromScheduler(name: string): Promise<string[]
1808
1816
  * Используется инструментом update_task и RPC-методом update_task.
1809
1817
  */
1810
1818
  async function updateTaskFromInput(
1811
- input: UpdateArgs & { newSchedule?: string; newPrompt?: string }
1819
+ input: UpdateArgs & { newSchedule?: string; newPrompt?: string },
1812
1820
  ): Promise<{
1813
1821
  success: boolean;
1814
1822
  message: string;
@@ -1859,8 +1867,8 @@ async function updateTaskFromInput(
1859
1867
  input.runAt !== undefined
1860
1868
  ? input.runAt
1861
1869
  : input.delaySeconds !== undefined
1862
- ? undefined
1863
- : previous.runAt;
1870
+ ? undefined
1871
+ : previous.runAt;
1864
1872
  const normalized = normalizeOneShotRunAt({
1865
1873
  runAt: candidateRunAt,
1866
1874
  delaySeconds: input.delaySeconds,
@@ -1921,7 +1929,7 @@ async function updateTaskFromInput(
1921
1929
  // Спринт 27: параметры триггеров сохраняются, если поле не передано.
1922
1930
  const mergeStringList = (
1923
1931
  next: string[] | undefined,
1924
- prev: string[] | undefined
1932
+ prev: string[] | undefined,
1925
1933
  ): string[] | undefined => {
1926
1934
  if (next === undefined) return prev;
1927
1935
  const cleaned = next
@@ -1950,9 +1958,23 @@ async function updateTaskFromInput(
1950
1958
  // после create — иначе задача молча начинает выполняться по расписанию.
1951
1959
  const wasPaused = Boolean(
1952
1960
  previous.paused === true ||
1953
- (previous.pausedUntil && Date.parse(previous.pausedUntil) > Date.now())
1961
+ (previous.pausedUntil && Date.parse(previous.pausedUntil) > Date.now()),
1954
1962
  );
1955
1963
 
1964
+ const nextModel = clearableString(input.model, previous.model);
1965
+ if (nextModel) {
1966
+ const modelError = validateModelId(nextModel);
1967
+ if (modelError) {
1968
+ return {
1969
+ success: false,
1970
+ message: t("tool.error.modelInvalid", {
1971
+ model: nextModel,
1972
+ error: modelError,
1973
+ }),
1974
+ };
1975
+ }
1976
+ }
1977
+
1956
1978
  let previousDeleted = false;
1957
1979
  try {
1958
1980
  // Обновление = пересоздание в планировщике с сохранением старых значений.
@@ -1972,7 +1994,7 @@ async function updateTaskFromInput(
1972
1994
  triggerType,
1973
1995
  clearableString(input.watchPath, previous.watchPath),
1974
1996
  clearableList(input.dependsOn, previous.dependsOn),
1975
- clearableString(input.model, previous.model),
1997
+ nextModel,
1976
1998
  input.priority ?? previous.priority,
1977
1999
  clearableString(input.beforeScript, previous.beforeScript),
1978
2000
  clearableString(input.afterScript, previous.afterScript),
@@ -1996,7 +2018,7 @@ async function updateTaskFromInput(
1996
2018
  triggerExtras,
1997
2019
  input.runWhenLoggedOff ?? previous.runWhenLoggedOff,
1998
2020
  wasPaused,
1999
- input.legacyShell ?? previous.legacyShell
2021
+ input.legacyShell ?? previous.legacyShell,
2000
2022
  );
2001
2023
 
2002
2024
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
@@ -2109,7 +2131,7 @@ const updateTaskExecute = wrapExecute<UpdateArgs>(async (args) => {
2109
2131
  async function pauseOrResumeTask(
2110
2132
  name: string,
2111
2133
  paused: boolean,
2112
- until?: string
2134
+ until?: string,
2113
2135
  ): Promise<{
2114
2136
  success: boolean;
2115
2137
  message: string;
@@ -2190,7 +2212,7 @@ async function pauseOrResumeTask(
2190
2212
  affected.push(target);
2191
2213
  } catch (err: any) {
2192
2214
  warnings.push(
2193
- `${target}: ${err instanceof Error ? err.message : String(err)}`
2215
+ `${target}: ${err instanceof Error ? err.message : String(err)}`,
2194
2216
  );
2195
2217
  }
2196
2218
  }
@@ -2211,7 +2233,7 @@ async function pauseOrResumeTask(
2211
2233
  warnings.push(
2212
2234
  t("tool.task.autosave", {
2213
2235
  error: err instanceof Error ? err.message : String(err),
2214
- })
2236
+ }),
2215
2237
  );
2216
2238
  }
2217
2239
  }
@@ -2222,20 +2244,20 @@ async function pauseOrResumeTask(
2222
2244
  const verb = paused ? t("tool.task.paused") : t("tool.task.resumed");
2223
2245
  const message = definition.matrix
2224
2246
  ? t("tool.task.matrixPaused", {
2225
- name: trimmed,
2226
- verb,
2227
- until: untilText,
2228
- affected: affected.length,
2229
- total: targets.length,
2230
- }) +
2247
+ name: trimmed,
2248
+ verb,
2249
+ until: untilText,
2250
+ affected: affected.length,
2251
+ total: targets.length,
2252
+ }) +
2231
2253
  (warnings.length > 0
2232
2254
  ? t("tool.task.matrixPauseErrors", { warnings: warnings.join("; ") })
2233
2255
  : "")
2234
2256
  : t("tool.task.pausedText", {
2235
- name: trimmed,
2236
- verb,
2237
- until: untilText,
2238
- }) +
2257
+ name: trimmed,
2258
+ verb,
2259
+ until: untilText,
2260
+ }) +
2239
2261
  (warnings.length > 0
2240
2262
  ? t("tool.task.pauseError", { warnings: warnings.join("; ") })
2241
2263
  : "");
@@ -2304,13 +2326,13 @@ async function resumeExpiredPauses(): Promise<void> {
2304
2326
  paused: false,
2305
2327
  });
2306
2328
  console.log(
2307
- `[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`
2329
+ `[agent-steward] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`,
2308
2330
  );
2309
2331
  } catch (err: any) {
2310
2332
  console.error(
2311
- `[windows-scheduler] Не удалось автопродолжить задачу "${definition.name}": ${
2333
+ `[agent-steward] Не удалось автопродолжить задачу "${definition.name}": ${
2312
2334
  err instanceof Error ? err.message : String(err)
2313
- }`
2335
+ }`,
2314
2336
  );
2315
2337
  }
2316
2338
  }
@@ -2433,8 +2455,17 @@ async function refreshWorkspaceEnvFiles(workspaceId: string): Promise<number> {
2433
2455
  let refreshed = 0;
2434
2456
  for (const task of await loadTaskDefinitions()) {
2435
2457
  if (task.workspaceId !== workspaceId) continue;
2436
- writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
2437
- refreshed += 1;
2458
+ try {
2459
+ writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
2460
+ refreshed += 1;
2461
+ } catch (err: any) {
2462
+ // P2-21: не разрешаем задаче работать с литералом ${secret:...}.
2463
+ console.error(
2464
+ `[workspace] Задача "${task.name}": env-файл не обновлён — ${
2465
+ err instanceof Error ? err.message : String(err)
2466
+ }`,
2467
+ );
2468
+ }
2438
2469
  }
2439
2470
  return refreshed;
2440
2471
  }
@@ -2566,7 +2597,7 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
2566
2597
  failureMode: args.failureMode,
2567
2598
  aggregation: args.aggregation,
2568
2599
  },
2569
- } as any);
2600
+ });
2570
2601
  return {
2571
2602
  content: JSON.stringify({
2572
2603
  success: true,
@@ -2945,7 +2976,7 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
2945
2976
  if (args.action === "export") {
2946
2977
  const tasks = await scheduler.listTasks();
2947
2978
  const { data, count } = await buildExportJson(
2948
- tasks.map((task) => ({ ...task, name: task.taskName || "" }))
2979
+ tasks.map((task) => ({ ...task, name: task.taskName || "" })),
2949
2980
  );
2950
2981
  return { content: JSON.stringify({ success: true, data, count }) };
2951
2982
  }
@@ -2997,7 +3028,7 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
2997
3028
  def.notBefore,
2998
3029
  def.notAfter,
2999
3030
  def.pausedUntil,
3000
- def.runAt
3031
+ def.runAt,
3001
3032
  );
3002
3033
  await saveTaskDefinition(def);
3003
3034
  imported.push(def.name);
@@ -3047,11 +3078,11 @@ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
3047
3078
  message: report.skipped
3048
3079
  ? report.skipped
3049
3080
  : t("tool.history.cleaned", {
3050
- deleted: report.deleted,
3051
- byAge: report.deletedByAge,
3052
- byCount: report.deletedByCount,
3053
- kept: report.kept,
3054
- }),
3081
+ deleted: report.deleted,
3082
+ byAge: report.deletedByAge,
3083
+ byCount: report.deletedByCount,
3084
+ kept: report.kept,
3085
+ }),
3055
3086
  report,
3056
3087
  }),
3057
3088
  };
@@ -3070,11 +3101,11 @@ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
3070
3101
  (def) =>
3071
3102
  def.triggerType === "mcp-event" &&
3072
3103
  def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
3073
- matchesEventFilter(def.mcpEvent?.filter, payload)
3104
+ matchesEventFilter(def.mcpEvent?.filter, payload),
3074
3105
  )
3075
3106
  .sort(
3076
3107
  (a, b) =>
3077
- (normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0)
3108
+ (normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0),
3078
3109
  );
3079
3110
 
3080
3111
  const triggered: string[] = [];
@@ -3083,7 +3114,7 @@ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
3083
3114
  await runTaskEntry(def.name);
3084
3115
  triggered.push(def.name);
3085
3116
  } catch (err: any) {
3086
- console.error(`[windows-scheduler] emit_event: не удалось запустить ${def.name}:`, err);
3117
+ console.error(`[agent-steward] emit_event: не удалось запустить ${def.name}:`, err);
3087
3118
  }
3088
3119
  }
3089
3120
  return {
@@ -3167,7 +3198,7 @@ const getAuditLogExecute = wrapExecute<AuditLogArgs>(async (args) => {
3167
3198
  function withAudit<A>(
3168
3199
  toolName: string,
3169
3200
  describe: (args: A) => Omit<AuditEntryInput, "actor"> | null,
3170
- execute: (args: A, context: Tool.Context) => Promise<Tool.Result>
3201
+ execute: (args: A, context: Tool.Context) => Promise<Tool.Result>,
3171
3202
  ): (args: A, context: Tool.Context) => Promise<Tool.Result> {
3172
3203
  return async (args: A, context: Tool.Context) => {
3173
3204
  const result = await execute(args, context);
@@ -3212,6 +3243,18 @@ const RPC_AUDIT_RULES: Record<
3212
3243
  targetType: "history",
3213
3244
  target: () => "runs",
3214
3245
  },
3246
+ retry_dlq: { action: "dlq.retry", targetType: "dlq", target: (i) => i.id ?? "" },
3247
+ discard_dlq: { action: "dlq.discard", targetType: "dlq", target: (i) => i.id ?? "" },
3248
+ pause_durable_run: {
3249
+ action: "run.pause",
3250
+ targetType: "run",
3251
+ target: (i) => i.runId ?? "",
3252
+ },
3253
+ resume_durable_run: {
3254
+ action: "run.resume",
3255
+ targetType: "run",
3256
+ target: (i) => i.runId ?? "",
3257
+ },
3215
3258
  emit_event: { action: "event.emit", targetType: "event", target: (i) => i.eventName ?? "" },
3216
3259
  add_workspace: {
3217
3260
  action: "workspace.add",
@@ -3271,7 +3314,7 @@ function withRpcAudit<T extends Record<string, (...args: any[]) => any>>(handler
3271
3314
  const input = args[0] ?? {};
3272
3315
  const result = await handler(...args);
3273
3316
  try {
3274
- if ((result as any)?.success !== false) {
3317
+ if ((result)?.success !== false) {
3275
3318
  recordAudit({
3276
3319
  action: rule.action,
3277
3320
  targetType: rule.targetType,
@@ -3313,9 +3356,9 @@ async function refreshTriggers(): Promise<void> {
3313
3356
  await fileWatcherManager.refresh();
3314
3357
  } catch (err: any) {
3315
3358
  console.error(
3316
- `[windows-scheduler] Не удалось обновить файловые триггеры: ${
3359
+ `[agent-steward] Не удалось обновить файловые триггеры: ${
3317
3360
  err instanceof Error ? err.message : String(err)
3318
- }`
3361
+ }`,
3319
3362
  );
3320
3363
  }
3321
3364
  }
@@ -3324,9 +3367,9 @@ async function refreshTriggers(): Promise<void> {
3324
3367
  await gitTriggerManager.refresh();
3325
3368
  } catch (err: any) {
3326
3369
  console.error(
3327
- `[windows-scheduler] Не удалось обновить git-триггеры: ${
3370
+ `[agent-steward] Не удалось обновить git-триггеры: ${
3328
3371
  err instanceof Error ? err.message : String(err)
3329
- }`
3372
+ }`,
3330
3373
  );
3331
3374
  }
3332
3375
  }
@@ -3357,16 +3400,16 @@ async function scheduleEventRun(taskName: string, reason: string): Promise<void>
3357
3400
  if (state.active || policy === "run") {
3358
3401
  await runTaskEntry(taskName);
3359
3402
  console.log(
3360
- `[windows-scheduler] Запуск задачи "${taskName}" (${reason}).`
3403
+ `[agent-steward] Запуск задачи "${taskName}" (${reason}).`,
3361
3404
  );
3362
3405
  return;
3363
3406
  }
3364
3407
 
3365
3408
  if (policy === "skip") {
3366
3409
  console.log(
3367
- `[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${
3410
+ `[agent-steward] Задача "${taskName}" не запущена (${reason}): ${
3368
3411
  state.reason ?? "вне окна"
3369
- } — политика skip.`
3412
+ } — политика skip.`,
3370
3413
  );
3371
3414
  return;
3372
3415
  }
@@ -3374,24 +3417,24 @@ async function scheduleEventRun(taskName: string, reason: string): Promise<void>
3374
3417
  const delay = nextWindowOpenDelayMs(now, options);
3375
3418
  if (delay <= 0 || delay > EVENT_POSTPONE_MAX_MS) {
3376
3419
  console.log(
3377
- `[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${
3420
+ `[agent-steward] Задача "${taskName}" не запущена (${reason}): ${
3378
3421
  state.reason ?? "вне окна"
3379
- } — до открытия окна больше 12 ч.`
3422
+ } — до открытия окна больше 12 ч.`,
3380
3423
  );
3381
3424
  return;
3382
3425
  }
3383
3426
 
3384
3427
  console.log(
3385
- `[windows-scheduler] Задача "${taskName}" (${reason}) отложена на ~${Math.round(
3386
- delay / 60000
3387
- )} мин: ${state.reason ?? "вне окна"}.`
3428
+ `[agent-steward] Задача "${taskName}" (${reason}) отложена на ~${Math.round(
3429
+ delay / 60000,
3430
+ )} мин: ${state.reason ?? "вне окна"}.`,
3388
3431
  );
3389
3432
  const timer = setTimeout(() => {
3390
3433
  void scheduleEventRun(taskName, reason).catch((err: any) => {
3391
3434
  console.error(
3392
- `[windows-scheduler] Не удалось запустить отложенную задачу "${taskName}": ${
3435
+ `[agent-steward] Не удалось запустить отложенную задачу "${taskName}": ${
3393
3436
  err instanceof Error ? err.message : String(err)
3394
- }`
3437
+ }`,
3395
3438
  );
3396
3439
  });
3397
3440
  }, delay);
@@ -3443,7 +3486,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3443
3486
  console.error(
3444
3487
  `[migrate] Не удалось мигрировать JSON → SQLite: ${
3445
3488
  err instanceof Error ? err.message : String(err)
3446
- }`
3489
+ }`,
3447
3490
  );
3448
3491
  }
3449
3492
  try {
@@ -3452,9 +3495,29 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3452
3495
  console.error(
3453
3496
  `[recovery] Не удалось восстановить незавершённые запуски: ${
3454
3497
  err instanceof Error ? err.message : String(err)
3455
- }`
3498
+ }`,
3456
3499
  );
3457
3500
  }
3501
+ // P1-14: pid:-записи fallback'а не переживают перезагрузку. Чистим их и
3502
+ // пересоздаём будущие one-shot, иначе после reboot можно убить чужой pid.
3503
+ if (scheduler instanceof LinuxScheduler) {
3504
+ try {
3505
+ const report = await scheduler.pruneStaleFallbacks();
3506
+ if (report.removed || report.rescheduled || report.missed) {
3507
+ console.log(
3508
+ `[scheduler] Fallback one-shot: удалено ${report.removed}, ` +
3509
+ `пересоздано ${report.rescheduled}, пропущено ${report.missed}, ` +
3510
+ `живо ${report.kept}.`,
3511
+ );
3512
+ }
3513
+ } catch (err: any) {
3514
+ console.error(
3515
+ `[scheduler] Не удалось очистить fallback-записи: ${
3516
+ err instanceof Error ? err.message : String(err)
3517
+ }`,
3518
+ );
3519
+ }
3520
+ }
3458
3521
  checkJsonBackups();
3459
3522
  void garbageCollectTaskArtifacts().catch((err) => {
3460
3523
  console.log(`[gc] Не удалось вычистить мусорные файлы: ${err instanceof Error ? err.message : String(err)}`);
@@ -3468,7 +3531,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3468
3531
  console.log(
3469
3532
  `[retention] Удалено ${report.deleted} записей истории ` +
3470
3533
  `(по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}); ` +
3471
- `осталось ${report.kept}.`
3534
+ `осталось ${report.kept}.`,
3472
3535
  );
3473
3536
  }
3474
3537
  })
@@ -3476,7 +3539,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3476
3539
  console.error(
3477
3540
  `[retention] Не удалось очистить историю: ${
3478
3541
  err instanceof Error ? err.message : String(err)
3479
- }`
3542
+ }`,
3480
3543
  );
3481
3544
  });
3482
3545
 
@@ -3484,17 +3547,17 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3484
3547
  // Проверяем сразу при старте и далее раз в 5 минут, пока плагин жив.
3485
3548
  void resumeExpiredPauses().catch((err: any) => {
3486
3549
  console.error(
3487
- `[windows-scheduler] Не удалось проверить автопродолжение: ${
3550
+ `[agent-steward] Не удалось проверить автопродолжение: ${
3488
3551
  err instanceof Error ? err.message : String(err)
3489
- }`
3552
+ }`,
3490
3553
  );
3491
3554
  });
3492
3555
  const pausedUntilTimer = setInterval(() => {
3493
3556
  void resumeExpiredPauses().catch((err: any) => {
3494
3557
  console.error(
3495
- `[windows-scheduler] Не удалось проверить автопродолжение: ${
3558
+ `[agent-steward] Не удалось проверить автопродолжение: ${
3496
3559
  err instanceof Error ? err.message : String(err)
3497
- }`
3560
+ }`,
3498
3561
  );
3499
3562
  });
3500
3563
  }, PAUSED_UNTIL_CHECK_MS);
@@ -3506,9 +3569,9 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3506
3569
  void maybeSendDigest().catch(() => undefined);
3507
3570
  void checkStuckMatrices().catch((err: any) => {
3508
3571
  console.error(
3509
- `[windows-scheduler] Детектор зависших матриц: ${
3572
+ `[agent-steward] Детектор зависших матриц: ${
3510
3573
  err instanceof Error ? err.message : String(err)
3511
- }`
3574
+ }`,
3512
3575
  );
3513
3576
  });
3514
3577
  }, NOTIFICATION_CHECK_MS);
@@ -3532,7 +3595,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3532
3595
 
3533
3596
  // Сначала запускаем задачи с более высоким приоритетом (10 — максимум).
3534
3597
  const prioritized = [...definitions].sort(
3535
- (a, b) => (normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5)
3598
+ (a, b) => (normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5),
3536
3599
  );
3537
3600
 
3538
3601
  for (const def of prioritized) {
@@ -3550,7 +3613,7 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3550
3613
  const ranAfter = history.some(
3551
3614
  (r) =>
3552
3615
  r.taskName.toLowerCase() === def.name.toLowerCase() &&
3553
- new Date(r.startedAt).getTime() >= prev.getTime()
3616
+ new Date(r.startedAt).getTime() >= prev.getTime(),
3554
3617
  );
3555
3618
  if (ranAfter) continue;
3556
3619
 
@@ -3558,19 +3621,19 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3558
3621
  try {
3559
3622
  await runTaskEntry(def.name);
3560
3623
  console.log(
3561
- `[windows-scheduler] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`
3624
+ `[agent-steward] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`,
3562
3625
  );
3563
3626
  } catch (err: any) {
3564
3627
  console.error(
3565
- `[windows-scheduler] Не удалось восстановить задачу "${def.name}": ${
3628
+ `[agent-steward] Не удалось восстановить задачу "${def.name}": ${
3566
3629
  err instanceof Error ? err.message : String(err)
3567
- }`
3630
+ }`,
3568
3631
  );
3569
3632
  }
3570
3633
  }
3571
3634
  } catch (err: any) {
3572
3635
  console.error(
3573
- `[windows-scheduler] Catch-up ошибка: ${err instanceof Error ? err.message : String(err)}`
3636
+ `[agent-steward] Catch-up ошибка: ${err instanceof Error ? err.message : String(err)}`,
3574
3637
  );
3575
3638
  }
3576
3639
  })();
@@ -3582,9 +3645,9 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3582
3645
  await scheduleEventRun(taskName, "изменение отслеживаемого файла");
3583
3646
  } catch (err: any) {
3584
3647
  console.error(
3585
- `[windows-scheduler] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${
3648
+ `[agent-steward] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${
3586
3649
  err instanceof Error ? err.message : String(err)
3587
- }`
3650
+ }`,
3588
3651
  );
3589
3652
  }
3590
3653
  });
@@ -3596,9 +3659,9 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3596
3659
  await scheduleEventRun(taskName, `новый коммит ${info.head?.slice(0, 7) ?? ""}`);
3597
3660
  } catch (err: any) {
3598
3661
  console.error(
3599
- `[windows-scheduler] Не удалось запустить задачу "${taskName}" по git-триггеру: ${
3662
+ `[agent-steward] Не удалось запустить задачу "${taskName}" по git-триггеру: ${
3600
3663
  err instanceof Error ? err.message : String(err)
3601
- }`
3664
+ }`,
3602
3665
  );
3603
3666
  }
3604
3667
  });
@@ -3710,7 +3773,7 @@ export interface ShutdownResource {
3710
3773
  export function createShutdownHandler(
3711
3774
  runtime: SchedulerRuntime,
3712
3775
  registrations: ShutdownResource[] = [],
3713
- options: { waitMs?: number } = {}
3776
+ options: { waitMs?: number } = {},
3714
3777
  ): () => Promise<void> {
3715
3778
  const waitMs = options.waitMs ?? SHUTDOWN_WAIT_MS;
3716
3779
 
@@ -3722,9 +3785,9 @@ export function createShutdownHandler(
3722
3785
  await registration.dispose();
3723
3786
  } catch (err) {
3724
3787
  console.warn(
3725
- `[windows-scheduler] Выгрузка: ошибка освобождения регистрации — ${
3788
+ `[agent-steward] Выгрузка: ошибка освобождения регистрации — ${
3726
3789
  err instanceof Error ? err.message : String(err)
3727
- }`
3790
+ }`,
3728
3791
  );
3729
3792
  }
3730
3793
  }
@@ -3737,7 +3800,7 @@ export function createShutdownHandler(
3737
3800
  const wait = await shutdownGate.waitForIdle(waitMs);
3738
3801
  if (wait.timedOut) {
3739
3802
  console.warn(
3740
- `[windows-scheduler] Выгрузка: ${wait.remaining} запуск(ов) не завершились за ${waitMs} мс — закрываем БД.`
3803
+ `[agent-steward] Выгрузка: ${wait.remaining} запуск(ов) не завершились за ${waitMs} мс — закрываем БД.`,
3741
3804
  );
3742
3805
  }
3743
3806
  // Чекпойнт WAL выполняется в closeDb.
@@ -3860,10 +3923,10 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3860
3923
  args.action === "list"
3861
3924
  ? null
3862
3925
  : {
3863
- action: `workspace.${args.action}`,
3864
- targetType: "workspace",
3865
- target: args.id || args.name || "",
3866
- },
3926
+ action: `workspace.${args.action}`,
3927
+ targetType: "workspace",
3928
+ target: args.id || args.name || "",
3929
+ },
3867
3930
  execute: handlers.manage_workspaces as any,
3868
3931
  },
3869
3932
  {
@@ -3874,10 +3937,10 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3874
3937
  audit: (args: MatrixControlArgs) =>
3875
3938
  args.action === "cancel" || args.action === "cleanup"
3876
3939
  ? {
3877
- action: `matrix.${args.action}`,
3878
- targetType: "matrix",
3879
- target: args.name || "",
3880
- }
3940
+ action: `matrix.${args.action}`,
3941
+ targetType: "matrix",
3942
+ target: args.name || "",
3943
+ }
3881
3944
  : null,
3882
3945
  execute: handlers.matrix_control as any,
3883
3946
  },
@@ -3936,10 +3999,10 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3936
3999
  args.action === "list"
3937
4000
  ? null
3938
4001
  : {
3939
- action: `template.${args.action}`,
3940
- targetType: "template",
3941
- target: args.id || args.name || "",
3942
- },
4002
+ action: `template.${args.action}`,
4003
+ targetType: "template",
4004
+ target: args.id || args.name || "",
4005
+ },
3943
4006
  execute: handlers.manage_templates as any,
3944
4007
  },
3945
4008
  {
@@ -3951,10 +4014,10 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
3951
4014
  args.action === "list"
3952
4015
  ? null
3953
4016
  : {
3954
- action: `profile.${args.action}`,
3955
- targetType: "profile",
3956
- target: args.name || "",
3957
- },
4017
+ action: `profile.${args.action}`,
4018
+ targetType: "profile",
4019
+ target: args.name || "",
4020
+ },
3958
4021
  execute: handlers.manage_profiles as any,
3959
4022
  },
3960
4023
  {
@@ -4001,10 +4064,10 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
4001
4064
  args.action === "list"
4002
4065
  ? null
4003
4066
  : {
4004
- action: `secret.${args.action}`,
4005
- targetType: "secret",
4006
- target: (args.name ?? "").trim(),
4007
- },
4067
+ action: `secret.${args.action}`,
4068
+ targetType: "secret",
4069
+ target: (args.name ?? "").trim(),
4070
+ },
4008
4071
  execute: handlers.manage_secrets as any,
4009
4072
  },
4010
4073
  {
@@ -4041,7 +4104,7 @@ async function startSchedulerDashboard(): Promise<void> {
4041
4104
  });
4042
4105
  if (dashboard) {
4043
4106
  console.log(
4044
- `[windows-scheduler] Открыть дашборд в браузере: http://localhost:${dashboard.port}`
4107
+ `[agent-steward] Открыть дашборд в браузере: http://localhost:${dashboard.port}`,
4045
4108
  );
4046
4109
  }
4047
4110
  }
@@ -4089,9 +4152,9 @@ const v2Plugin = Plugin.define({
4089
4152
  }
4090
4153
  } catch (err: any) {
4091
4154
  console.error(
4092
- `[windows-scheduler] Не удалось зарегистрировать скилл "${SCHEDULER_SKILL_ID}": ${
4155
+ `[agent-steward] Не удалось зарегистрировать скилл "${SCHEDULER_SKILL_ID}": ${
4093
4156
  err instanceof Error ? err.message : String(err)
4094
- }`
4157
+ }`,
4095
4158
  );
4096
4159
  }
4097
4160
 
@@ -4108,7 +4171,7 @@ const v2Plugin = Plugin.define({
4108
4171
  };
4109
4172
  },
4110
4173
  create_task: async (input: unknown) => {
4111
- console.log("[windows-scheduler] create_task input:", input);
4174
+ console.log("[agent-steward] create_task input:", input);
4112
4175
  const {
4113
4176
  name,
4114
4177
  schedule,
@@ -4233,7 +4296,7 @@ const v2Plugin = Plugin.define({
4233
4296
  undefined,
4234
4297
  runWhenLoggedOff === true,
4235
4298
  undefined,
4236
- legacyShell === true
4299
+ legacyShell === true,
4237
4300
  );
4238
4301
  const nextRun = computeTaskNextRun({
4239
4302
  schedule: schedule ?? "",
@@ -4263,9 +4326,9 @@ const v2Plugin = Plugin.define({
4263
4326
  message:
4264
4327
  removed.length > 0
4265
4328
  ? t("tool.task.matrixDeletedCount", {
4266
- name,
4267
- count: removed.length,
4268
- })
4329
+ name,
4330
+ count: removed.length,
4331
+ })
4269
4332
  : t("tool.task.deleted", { name }),
4270
4333
  };
4271
4334
  } catch (err: any) {
@@ -4313,7 +4376,7 @@ const v2Plugin = Plugin.define({
4313
4376
  try {
4314
4377
  // Matrix-родитель не выполняется сам: запускаем его клоны (fan-out).
4315
4378
  const definition = (await loadTaskDefinitions()).find(
4316
- (def) => def.name.toLowerCase() === name.trim().toLowerCase()
4379
+ (def) => def.name.toLowerCase() === name.trim().toLowerCase(),
4317
4380
  );
4318
4381
  if (definition?.matrix) {
4319
4382
  const matrixResult = await runMatrix(definition);
@@ -4326,13 +4389,13 @@ const v2Plugin = Plugin.define({
4326
4389
  }) +
4327
4390
  (matrixResult.skipped.length
4328
4391
  ? t("tool.matrix.startedSkipped", {
4329
- count: matrixResult.skipped.length,
4330
- })
4392
+ count: matrixResult.skipped.length,
4393
+ })
4331
4394
  : "") +
4332
4395
  (matrixResult.errors.length
4333
4396
  ? t("tool.matrix.startedErrors", {
4334
- errors: matrixResult.errors.join("; "),
4335
- })
4397
+ errors: matrixResult.errors.join("; "),
4398
+ })
4336
4399
  : ".");
4337
4400
  return { success: matrixResult.success, message };
4338
4401
  }
@@ -4342,7 +4405,7 @@ const v2Plugin = Plugin.define({
4342
4405
  if (settings.maxConcurrent > 0) {
4343
4406
  const allTasks = await scheduler.listTasks();
4344
4407
  const runningCount = allTasks.filter((t) =>
4345
- /running|выполняется/i.test(t.status ?? "")
4408
+ /running|выполняется/i.test(t.status ?? ""),
4346
4409
  ).length;
4347
4410
  if (runningCount >= settings.maxConcurrent) {
4348
4411
  return {
@@ -4381,12 +4444,12 @@ const v2Plugin = Plugin.define({
4381
4444
  .filter((def) => (def.triggerType ?? "cron") === "mcp-event")
4382
4445
  .filter(
4383
4446
  (def) =>
4384
- def.mcpEvent?.event?.trim().toLowerCase() === normalized.toLowerCase()
4447
+ def.mcpEvent?.event?.trim().toLowerCase() === normalized.toLowerCase(),
4385
4448
  )
4386
4449
  .filter((def) => matchesEventFilter(def.mcpEvent?.filter, payload))
4387
4450
  .sort(
4388
4451
  (a, b) =>
4389
- (normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5)
4452
+ (normalizePriority(b.priority) ?? 5) - (normalizePriority(a.priority) ?? 5),
4390
4453
  );
4391
4454
 
4392
4455
  const triggered: string[] = [];
@@ -4395,13 +4458,13 @@ const v2Plugin = Plugin.define({
4395
4458
  await runTaskEntry(def.name);
4396
4459
  triggered.push(def.name);
4397
4460
  console.log(
4398
- `[windows-scheduler] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`
4461
+ `[agent-steward] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`,
4399
4462
  );
4400
4463
  } catch (err: any) {
4401
4464
  console.error(
4402
- `[windows-scheduler] Не удалось запустить "${def.name}" по событию "${normalized}": ${
4465
+ `[agent-steward] Не удалось запустить "${def.name}" по событию "${normalized}": ${
4403
4466
  err instanceof Error ? err.message : String(err)
4404
- }`
4467
+ }`,
4405
4468
  );
4406
4469
  }
4407
4470
  }
@@ -4460,11 +4523,11 @@ const v2Plugin = Plugin.define({
4460
4523
  const message = report.skipped
4461
4524
  ? report.skipped
4462
4525
  : t("tool.history.cleaned", {
4463
- deleted: report.deleted,
4464
- byAge: report.deletedByAge,
4465
- byCount: report.deletedByCount,
4466
- kept: report.kept,
4467
- });
4526
+ deleted: report.deleted,
4527
+ byAge: report.deletedByAge,
4528
+ byCount: report.deletedByCount,
4529
+ kept: report.kept,
4530
+ });
4468
4531
  return {
4469
4532
  success: true,
4470
4533
  message,
@@ -4497,7 +4560,7 @@ const v2Plugin = Plugin.define({
4497
4560
  try {
4498
4561
  const windowDays = Math.min(
4499
4562
  365,
4500
- Math.max(1, Math.floor(Number(days) || 14))
4563
+ Math.max(1, Math.floor(Number(days) || 14)),
4501
4564
  );
4502
4565
  const records = getHistory(null, 20000);
4503
4566
  const definitions = await loadTaskDefinitions();
@@ -4529,7 +4592,7 @@ const v2Plugin = Plugin.define({
4529
4592
  try {
4530
4593
  const windowDays = Math.min(
4531
4594
  365,
4532
- Math.max(1, Math.floor(Number(days) || 14))
4595
+ Math.max(1, Math.floor(Number(days) || 14)),
4533
4596
  );
4534
4597
  const records = getHistory(null, 20000);
4535
4598
  const definitions = await loadTaskDefinitions();
@@ -5010,11 +5073,48 @@ const v2Plugin = Plugin.define({
5010
5073
  });
5011
5074
  return { success: true, ...result };
5012
5075
  },
5076
+ list_dlq: async (input: unknown) => {
5077
+ const source = (input ?? {}) as { status?: string; limit?: number };
5078
+ return listDlq({ status: source.status, limit: source.limit });
5079
+ },
5080
+ retry_dlq: async (input: unknown) => {
5081
+ const source = (input ?? {}) as { id?: string };
5082
+ if (!source.id) return { success: false, error: "id is required" };
5083
+ return retryDlq(source.id);
5084
+ },
5085
+ discard_dlq: async (input: unknown) => {
5086
+ const source = (input ?? {}) as { id?: string; resolution?: string };
5087
+ if (!source.id) return { success: false, error: "id is required" };
5088
+ return discardDlq(source.id, source.resolution);
5089
+ },
5090
+ list_durable_runs: async (input: unknown) => {
5091
+ const source = (input ?? {}) as { filter?: string; limit?: number };
5092
+ return listRunPanel({ filter: source.filter, limit: source.limit });
5093
+ },
5094
+ pause_durable_run: async (input: unknown) => {
5095
+ const source = (input ?? {}) as {
5096
+ runId?: string;
5097
+ stepName?: string;
5098
+ comment?: string;
5099
+ author?: string;
5100
+ };
5101
+ if (!source.runId) return { success: false, error: "runId is required" };
5102
+ return pauseRunPanel(source.runId, {
5103
+ stepName: source.stepName,
5104
+ comment: source.comment,
5105
+ author: source.author,
5106
+ });
5107
+ },
5108
+ resume_durable_run: async (input: unknown) => {
5109
+ const source = (input ?? {}) as { runId?: string };
5110
+ if (!source.runId) return { success: false, error: "runId is required" };
5111
+ return resumeRunPanel(source.runId);
5112
+ },
5013
5113
  get_templates: async () => {
5014
5114
  try {
5015
5115
  return { templates: await loadTemplates() };
5016
5116
  } catch (err: any) {
5017
- console.error("[windows-scheduler] get_templates error:", err);
5117
+ console.error("[agent-steward] get_templates error:", err);
5018
5118
  return { templates: [] };
5019
5119
  }
5020
5120
  },
@@ -5038,10 +5138,10 @@ const v2Plugin = Plugin.define({
5038
5138
  source.triggerType === "file"
5039
5139
  ? "file"
5040
5140
  : source.triggerType === "mcp-event"
5041
- ? "mcp-event"
5042
- : source.triggerType
5043
- ? "cron"
5044
- : undefined,
5141
+ ? "mcp-event"
5142
+ : source.triggerType
5143
+ ? "cron"
5144
+ : undefined,
5045
5145
  });
5046
5146
  return { success: true, template };
5047
5147
  } catch (err: any) {
@@ -5144,7 +5244,7 @@ const v2Plugin = Plugin.define({
5144
5244
  },
5145
5245
  def.runWhenLoggedOff === true,
5146
5246
  def.paused === true,
5147
- def.legacyShell === true
5247
+ def.legacyShell === true,
5148
5248
  );
5149
5249
  await saveTaskDefinition(def);
5150
5250
  imported.push(def.name);
@@ -5166,7 +5266,7 @@ const v2Plugin = Plugin.define({
5166
5266
 
5167
5267
  const rpcRegistration = await ctx.rpc.register(
5168
5268
  SchedulerRpc,
5169
- withRpcAudit(rpcHandlers) as typeof rpcHandlers
5269
+ withRpcAudit(rpcHandlers),
5170
5270
  );
5171
5271
 
5172
5272
  // Lifecycle матриц (Спринт 16): при старте вычищаем клоны/агрегаторы,
@@ -5175,7 +5275,7 @@ const v2Plugin = Plugin.define({
5175
5275
  console.log(
5176
5276
  `[matrix] Не удалось очистить осиротевшие задачи: ${
5177
5277
  err instanceof Error ? err.message : String(err)
5178
- }`
5278
+ }`,
5179
5279
  );
5180
5280
  });
5181
5281
 
@@ -5219,7 +5319,7 @@ export function toV1ToolArgs(spec: ToolSpec): Record<string, any> {
5219
5319
  const shape = (spec.input as { shape?: unknown } | undefined)?.shape;
5220
5320
  if (!shape || typeof shape !== "object") {
5221
5321
  throw new Error(
5222
- `V1-адаптер: схема инструмента "${spec.name}" должна быть z.object(...)`
5322
+ `V1-адаптер: схема инструмента "${spec.name}" должна быть z.object(...)`,
5223
5323
  );
5224
5324
  }
5225
5325
  return shape as Record<string, any>;
@@ -5255,7 +5355,7 @@ export function createV1Tools(runtime: SchedulerRuntime): Record<string, any> {
5255
5355
  */
5256
5356
  export async function createV1Hooks(
5257
5357
  input: Pick<V1PluginInput, "directory"> = { directory: process.cwd() },
5258
- options: { startDashboard?: boolean } = {}
5358
+ options: { startDashboard?: boolean } = {},
5259
5359
  ): Promise<V1Hooks> {
5260
5360
  const runtime = await createRuntime({ location: { directory: input.directory } });
5261
5361
  const tools = createV1Tools(runtime);
@@ -5286,7 +5386,7 @@ export default { ...v2Plugin, ...v1Plugin };
5286
5386
  function resolveMatrixExtraConfig(
5287
5387
  name: string,
5288
5388
  matrix: MatrixConfig,
5289
- ids: string[]
5389
+ ids: string[],
5290
5390
  ): { concurrency?: number; overrides?: Record<string, MatrixWorkspaceOverride> } {
5291
5391
  const extra: {
5292
5392
  concurrency?: number;
@@ -5300,7 +5400,7 @@ function resolveMatrixExtraConfig(
5300
5400
  matrix.concurrency < 1
5301
5401
  ) {
5302
5402
  throw new Error(
5303
- t("tool.error.matrixConcurrency", { task: name })
5403
+ t("tool.error.matrixConcurrency", { task: name }),
5304
5404
  );
5305
5405
  }
5306
5406
  extra.concurrency = Math.floor(matrix.concurrency);
@@ -5316,7 +5416,7 @@ function resolveMatrixExtraConfig(
5316
5416
  t("tool.error.matrixOverride", {
5317
5417
  task: name,
5318
5418
  workspace: workspaceKey,
5319
- })
5419
+ }),
5320
5420
  );
5321
5421
  }
5322
5422
  if (!value || typeof value !== "object") continue;
@@ -5329,7 +5429,21 @@ function resolveMatrixExtraConfig(
5329
5429
  "afterScript",
5330
5430
  ] as const) {
5331
5431
  const raw = (value as Record<string, unknown>)[field];
5332
- if (typeof raw === "string" && raw.trim()) override[field] = raw.trim();
5432
+ if (typeof raw === "string" && raw.trim()) {
5433
+ const trimmed = raw.trim();
5434
+ if (field === "model") {
5435
+ const modelError = validateModelId(trimmed);
5436
+ if (modelError) {
5437
+ throw new Error(
5438
+ t("tool.error.modelInvalid", {
5439
+ model: trimmed,
5440
+ error: modelError,
5441
+ }),
5442
+ );
5443
+ }
5444
+ }
5445
+ override[field] = trimmed;
5446
+ }
5333
5447
  }
5334
5448
  if (Object.keys(override).length > 0) overrides[workspaceKey] = override;
5335
5449
  }
@@ -5413,7 +5527,7 @@ async function schedulerCreateTask(
5413
5527
  * Спринт 32 / релиз 1.6: переходный флаг для гибридной политики.
5414
5528
  * true возвращает shell задаче, созданной до обновления поведения.
5415
5529
  */
5416
- legacyShell?: boolean
5530
+ legacyShell?: boolean,
5417
5531
  ): Promise<void> {
5418
5532
  // Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
5419
5533
  // в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
@@ -5432,22 +5546,42 @@ async function schedulerCreateTask(
5432
5546
  if (process.platform === "win32") {
5433
5547
  if (prompt.length > 30000) {
5434
5548
  throw new Error(
5435
- `Промпт задачи "${normalizedName}" слишком длинный для командной строки Windows: ${prompt.length} символов (максимум 30000). Сократите промпт или вынесите инструкции в файл.`
5549
+ `Промпт задачи "${normalizedName}" слишком длинный для командной строки Windows: ${prompt.length} символов (максимум 30000). Сократите промпт или вынесите инструкции в файл.`,
5436
5550
  );
5437
5551
  }
5438
5552
  } else {
5439
5553
  const promptBytes = Buffer.byteLength(prompt, "utf8");
5440
5554
  if (promptBytes > POSIX_MAX_PROMPT_BYTES) {
5441
5555
  throw new Error(
5442
- `Промпт задачи "${normalizedName}" слишком длинный для командной строки POSIX: ${promptBytes} байт (максимум ${POSIX_MAX_PROMPT_BYTES}). Сократите промпт или вынесите инструкции в файл.`
5556
+ `Промпт задачи "${normalizedName}" слишком длинный для командной строки POSIX: ${promptBytes} байт (максимум ${POSIX_MAX_PROMPT_BYTES}). Сократите промпт или вынесите инструкции в файл.`,
5443
5557
  );
5444
5558
  }
5445
5559
  }
5446
5560
  // Для отката файлов: при обновлении существующей задачи файлы переиспользуются,
5447
5561
  // удалять их при сбое нельзя — в БД остаётся прежнее определение.
5448
5562
  const definitionExisted = Boolean(getTask(normalizedName));
5563
+ // P1-10: при создании проверяем, что sanitized-имя не занято другой задачей
5564
+ // или её оставшимися файлами. Иначе «my task» и «my-task» делят
5565
+ // wrapper/prompt/lock/log, а вторая задача перезаписывает первую.
5566
+ if (!definitionExisted) {
5567
+ const conflict = findSanitizedNameConflict(
5568
+ normalizedName,
5569
+ listTaskDefinitions().map((def) => def.name),
5570
+ );
5571
+ if (conflict) {
5572
+ throw new Error(sanitizedConflictMessage(normalizedName, conflict));
5573
+ }
5574
+ }
5449
5575
 
5450
5576
  const normalizedModel = model?.trim() || undefined;
5577
+ if (normalizedModel) {
5578
+ const modelError = validateModelId(normalizedModel);
5579
+ if (modelError) {
5580
+ throw new Error(
5581
+ t("tool.error.modelInvalid", { model: normalizedModel, error: modelError }),
5582
+ );
5583
+ }
5584
+ }
5451
5585
  const normalizedPriority = normalizePriority(priority);
5452
5586
  const normalizedBefore = beforeScript?.trim() || undefined;
5453
5587
  const normalizedAfter = afterScript?.trim() || undefined;
@@ -5467,8 +5601,8 @@ async function schedulerCreateTask(
5467
5601
  raw
5468
5602
  .filter((item): item is string => typeof item === "string")
5469
5603
  .map((item) => item.trim())
5470
- .filter(Boolean)
5471
- )
5604
+ .filter(Boolean),
5605
+ ),
5472
5606
  );
5473
5607
  return cleaned.length > 0 ? cleaned : undefined;
5474
5608
  };
@@ -5489,12 +5623,12 @@ async function schedulerCreateTask(
5489
5623
  ? Math.floor(triggerExtras.gitPollSeconds)
5490
5624
  : undefined;
5491
5625
  const normalizedMcpEvent =
5492
- mcpEvent && mcpEvent.event?.trim()
5626
+ mcpEvent?.event?.trim()
5493
5627
  ? {
5494
- server: mcpEvent.server?.trim() || "",
5495
- event: mcpEvent.event.trim(),
5496
- ...(mcpEvent.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
5497
- }
5628
+ server: mcpEvent.server?.trim() || "",
5629
+ event: mcpEvent.event.trim(),
5630
+ ...(mcpEvent.filter?.trim() ? { filter: mcpEvent.filter.trim() } : {}),
5631
+ }
5498
5632
  : undefined;
5499
5633
  let effectiveTriggerType = triggerType ?? "cron";
5500
5634
  // One-shot: нормализуем время до создания файлов и задачи в ОС.
@@ -5515,11 +5649,11 @@ async function schedulerCreateTask(
5515
5649
  const normalizedSession = normalizeSessionMode(session);
5516
5650
  if (!normalizedSession) {
5517
5651
  throw new Error(
5518
- t("tool.error.sessionUnknown", {
5519
- name,
5520
- session: String(session),
5521
- })
5522
- );
5652
+ t("tool.error.sessionUnknown", {
5653
+ name,
5654
+ session: String(session),
5655
+ }),
5656
+ );
5523
5657
  }
5524
5658
  effectiveSession = normalizedSession;
5525
5659
  }
@@ -5537,14 +5671,14 @@ async function schedulerCreateTask(
5537
5671
  .filter((t): t is string => typeof t === "string")
5538
5672
  .map((t) => t.trim())
5539
5673
  .filter(Boolean)
5540
- .map((t) => [t.toLowerCase(), t] as const)
5541
- ).values()
5674
+ .map((t) => [t.toLowerCase(), t] as const),
5675
+ ).values(),
5542
5676
  );
5543
5677
  return cleaned.length > 0 ? cleaned : undefined;
5544
5678
  };
5545
5679
  if (Array.isArray(allowedTools) && allowedTools.filter((t) => typeof t === "string" && t.trim()).length === 0) {
5546
5680
  throw new Error(
5547
- t("tool.error.allowedToolsEmpty", { task: name })
5681
+ t("tool.error.allowedToolsEmpty", { task: name }),
5548
5682
  );
5549
5683
  }
5550
5684
  const normalizedAllowedTools = normalizeToolList(allowedTools);
@@ -5577,7 +5711,7 @@ async function schedulerCreateTask(
5577
5711
  if (matrix) {
5578
5712
  if (workspaceId?.trim()) {
5579
5713
  throw new Error(
5580
- t("tool.error.workspaceIdConflict", { task: name })
5714
+ t("tool.error.workspaceIdConflict", { task: name }),
5581
5715
  );
5582
5716
  }
5583
5717
  const ids = Array.from(
@@ -5585,19 +5719,19 @@ async function schedulerCreateTask(
5585
5719
  (Array.isArray(matrix.workspaceIds) ? matrix.workspaceIds : [])
5586
5720
  .filter((id): id is string => typeof id === "string")
5587
5721
  .map((id) => id.trim())
5588
- .filter(Boolean)
5589
- )
5722
+ .filter(Boolean),
5723
+ ),
5590
5724
  );
5591
5725
  if (ids.length === 0) {
5592
5726
  throw new Error(
5593
- t("tool.error.workspaceIdsEmpty", { task: name })
5727
+ t("tool.error.workspaceIdsEmpty", { task: name }),
5594
5728
  );
5595
5729
  }
5596
5730
  for (const id of ids) {
5597
5731
  const ws = getWorkspace(id);
5598
5732
  if (!ws) {
5599
5733
  throw new Error(
5600
- t("tool.error.workspaceMissing", { task: name, id })
5734
+ t("tool.error.workspaceMissing", { task: name, id }),
5601
5735
  );
5602
5736
  }
5603
5737
  try {
@@ -5608,7 +5742,7 @@ async function schedulerCreateTask(
5608
5742
  task: name,
5609
5743
  workspace: ws.name,
5610
5744
  path: ws.path,
5611
- })
5745
+ }),
5612
5746
  );
5613
5747
  }
5614
5748
  }
@@ -5639,12 +5773,12 @@ async function schedulerCreateTask(
5639
5773
  : workingDirectory?.trim() || projectDirectory || process.cwd();
5640
5774
  if (!gitCwd) {
5641
5775
  throw new Error(
5642
- t("tool.error.gitCwdRequired", { task: name })
5776
+ t("tool.error.gitCwdRequired", { task: name }),
5643
5777
  );
5644
5778
  }
5645
5779
  if (!readGitBranch(gitCwd)) {
5646
5780
  throw new Error(
5647
- t("tool.error.gitNoRepo", { task: name, path: gitCwd })
5781
+ t("tool.error.gitNoRepo", { task: name, path: gitCwd }),
5648
5782
  );
5649
5783
  }
5650
5784
  }
@@ -5663,16 +5797,39 @@ async function schedulerCreateTask(
5663
5797
  t("tool.error.timezone", {
5664
5798
  task: name,
5665
5799
  timezone: normalizedTz,
5666
- })
5800
+ }),
5667
5801
  );
5668
5802
  }
5669
5803
  const windowError = validateLaunchWindow(
5670
5804
  normalizedNotBefore,
5671
- normalizedNotAfter
5805
+ normalizedNotAfter,
5672
5806
  );
5673
5807
  if (windowError) {
5674
5808
  throw new Error(t("tool.error.window", { task: name, error: windowError }));
5675
5809
  }
5810
+ // P2-24: cron может быть валидным, но никогда не попадать в окно запуска
5811
+ // (например, daily 09:00 при окне 22:00–06:00). Предупреждаем сразу при
5812
+ // создании: иначе задача молча не выполняется из-за лимита переноса 12 ч.
5813
+ if (normalizedNotBefore || normalizedNotAfter || normalizedActiveDays) {
5814
+ const feasibility = assessCronWindowFeasibility(
5815
+ schedule,
5816
+ {
5817
+ notBefore: normalizedNotBefore,
5818
+ notAfter: normalizedNotAfter,
5819
+ days: normalizedActiveDays,
5820
+ timeZone: normalizedTz || undefined,
5821
+ },
5822
+ normalizedWindowPolicy,
5823
+ );
5824
+ if (!feasibility.feasible) {
5825
+ console.warn(
5826
+ `[scheduler] Задача "${name}": ${t("dryRun.window.unreachable", {
5827
+ cron: schedule,
5828
+ reason: windowFeasibilityReasonText(feasibility.reason),
5829
+ })}`,
5830
+ );
5831
+ }
5832
+ }
5676
5833
  }
5677
5834
  // Спринт 27: окно и дни недели применимы и к событийным триггерам
5678
5835
  // (file/git/mcp-event/once) — проверяем корректность до создания задачи.
@@ -5691,21 +5848,21 @@ async function schedulerCreateTask(
5691
5848
  const gate =
5692
5849
  effectiveTriggerType === "cron"
5693
5850
  ? buildScheduleGate(
5694
- schedule,
5695
- normalizedTz,
5696
- normalizedNotBefore,
5697
- normalizedNotAfter,
5698
- normalizedActiveDays,
5699
- normalizedWindowPolicy
5700
- )
5851
+ schedule,
5852
+ normalizedTz,
5853
+ normalizedNotBefore,
5854
+ normalizedNotAfter,
5855
+ normalizedActiveDays,
5856
+ normalizedWindowPolicy,
5857
+ )
5701
5858
  : undefined;
5702
5859
  const wrapperGate = gate
5703
5860
  ? {
5704
- ...gate,
5705
- gateFile: gatePath,
5706
- deferFile: `${lockFile}.defer`,
5707
- forceFile: `${lockFile}.force`,
5708
- }
5861
+ ...gate,
5862
+ gateFile: gatePath,
5863
+ deferFile: `${lockFile}.defer`,
5864
+ forceFile: `${lockFile}.force`,
5865
+ }
5709
5866
  : undefined;
5710
5867
  // Workspace имеет приоритет над workingDirectory: одна задача = один repo
5711
5868
  // = один cwd. Мы не угадываем, куда мержить, и не смешиваем контексты.
@@ -5715,7 +5872,7 @@ async function schedulerCreateTask(
5715
5872
  throw new Error(
5716
5873
  t("tool.error.workspaceIdMissing", {
5717
5874
  id: normalizedWorkspaceId,
5718
- })
5875
+ }),
5719
5876
  );
5720
5877
  }
5721
5878
  if (workspace) {
@@ -5726,13 +5883,13 @@ async function schedulerCreateTask(
5726
5883
  t("tool.error.workspacePathMissing", {
5727
5884
  name: workspace.name,
5728
5885
  path: workspace.path,
5729
- })
5886
+ }),
5730
5887
  );
5731
5888
  }
5732
5889
  if (workingDirectory?.trim() && workingDirectory.trim() !== workspace.path) {
5733
5890
  console.warn(
5734
5891
  `[workspace] Задача "${name}": workingDirectory "${workingDirectory.trim()}" ` +
5735
- `игнорируется, cwd = workspace "${workspace.name}" (${workspace.path}).`
5892
+ `игнорируется, cwd = workspace "${workspace.name}" (${workspace.path}).`,
5736
5893
  );
5737
5894
  }
5738
5895
  }
@@ -5747,7 +5904,7 @@ async function schedulerCreateTask(
5747
5904
  effectiveWatchPath = normalizeWatchPath(effectiveWatchPath, effectiveWorkingDirectory);
5748
5905
  } catch (err: any) {
5749
5906
  throw new Error(
5750
- t("tool.error.taskReason", { name, error: err.message || String(err) })
5907
+ t("tool.error.taskReason", { name, error: err.message || String(err) }),
5751
5908
  );
5752
5909
  }
5753
5910
  }
@@ -5756,7 +5913,7 @@ async function schedulerCreateTask(
5756
5913
  validateWatchGlobs(normalizedWatchIgnore);
5757
5914
  } catch (err: any) {
5758
5915
  throw new Error(
5759
- t("tool.error.taskReason", { name, error: err.message || String(err) })
5916
+ t("tool.error.taskReason", { name, error: err.message || String(err) }),
5760
5917
  );
5761
5918
  }
5762
5919
 
@@ -5766,13 +5923,13 @@ async function schedulerCreateTask(
5766
5923
  prompt,
5767
5924
  beforeScript,
5768
5925
  afterScript,
5769
- qualityGate
5926
+ qualityGate,
5770
5927
  );
5771
5928
  const taskEnvFile = writeWorkspaceEnvFile(
5772
5929
  workspace,
5773
5930
  PLUGIN_DIR,
5774
5931
  sanitized,
5775
- usedSecretNames
5932
+ usedSecretNames,
5776
5933
  );
5777
5934
  if (taskEnvFile) {
5778
5935
  console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
@@ -5787,7 +5944,7 @@ async function schedulerCreateTask(
5787
5944
  throw new Error(
5788
5945
  t("tool.error.prepareFiles", {
5789
5946
  error: err.message || String(err),
5790
- })
5947
+ }),
5791
5948
  );
5792
5949
  }
5793
5950
 
@@ -5827,7 +5984,7 @@ async function schedulerCreateTask(
5827
5984
  undefined,
5828
5985
  permissionsConfig,
5829
5986
  policyMeta,
5830
- sessionFile
5987
+ sessionFile,
5831
5988
  );
5832
5989
  } else {
5833
5990
  wrapperPath = await writeBashWrapper({
@@ -5862,7 +6019,7 @@ async function schedulerCreateTask(
5862
6019
  throw new Error(
5863
6020
  t("tool.error.wrapper", {
5864
6021
  error: err.message || String(err),
5865
- })
6022
+ }),
5866
6023
  );
5867
6024
  }
5868
6025
 
@@ -5872,8 +6029,8 @@ async function schedulerCreateTask(
5872
6029
  if (definitionExisted) return;
5873
6030
  await Promise.all(
5874
6031
  [wrapperPath, promptFile, logFile, taskEnvFile].map((file) =>
5875
- file ? fs.unlink(file).catch(() => undefined) : Promise.resolve()
5876
- )
6032
+ file ? fs.unlink(file).catch(() => undefined) : Promise.resolve(),
6033
+ ),
5877
6034
  );
5878
6035
  };
5879
6036
 
@@ -5904,7 +6061,7 @@ async function schedulerCreateTask(
5904
6061
  // 200 мс. Это ловит случай, когда ОС/обёртка вернула код 0, но задачи нет.
5905
6062
  const isListed = (tasks: Awaited<ReturnType<typeof scheduler.listTasks>>): boolean =>
5906
6063
  tasks.some(
5907
- (task) => (task.taskName || "").trim().toLowerCase() === name.toLowerCase()
6064
+ (task) => (task.taskName || "").trim().toLowerCase() === name.toLowerCase(),
5908
6065
  );
5909
6066
  let listedTasks: Awaited<ReturnType<typeof scheduler.listTasks>> | undefined;
5910
6067
  let verifyQueryError: unknown;
@@ -5929,16 +6086,16 @@ async function schedulerCreateTask(
5929
6086
  " " +
5930
6087
  (definitionExisted
5931
6088
  ? t("tool.error.schedulerKeptFiles")
5932
- : t("tool.error.schedulerRemovedFiles"))
6089
+ : t("tool.error.schedulerRemovedFiles")),
5933
6090
  );
5934
6091
  }
5935
6092
  if (!listedTasks && verifyQueryError) {
5936
6093
  // Список получить не удалось — не удаляем возможно созданную задачу,
5937
6094
  // но явно предупреждаем: проверка наличия не выполнена.
5938
6095
  console.warn(
5939
- `[windows-scheduler] Задача "${name}" создана, но проверить её в планировщике не удалось: ${
6096
+ `[agent-steward] Задача "${name}" создана, но проверить её в планировщике не удалось: ${
5940
6097
  verifyQueryError instanceof Error ? verifyQueryError.message : String(verifyQueryError)
5941
- }`
6098
+ }`,
5942
6099
  );
5943
6100
  }
5944
6101
 
@@ -5976,7 +6133,7 @@ async function schedulerCreateTask(
5976
6133
  sessionRunCount: preservedSessionRunCount(
5977
6134
  previousDefinition,
5978
6135
  effectiveSession,
5979
- effectiveSessionId
6136
+ effectiveSessionId,
5980
6137
  ),
5981
6138
  watchPath: normalizedMatrix ? undefined : effectiveWatchPath,
5982
6139
  timezone: normalizedTz,
@@ -6009,13 +6166,13 @@ async function schedulerCreateTask(
6009
6166
  dependsOn:
6010
6167
  Array.isArray(dependsOn) && dependsOn.length > 0
6011
6168
  ? Array.from(
6012
- new Set(
6013
- dependsOn
6014
- .filter((dep): dep is string => typeof dep === "string")
6015
- .map((dep) => dep.trim())
6016
- .filter(Boolean)
6017
- )
6018
- )
6169
+ new Set(
6170
+ dependsOn
6171
+ .filter((dep): dep is string => typeof dep === "string")
6172
+ .map((dep) => dep.trim())
6173
+ .filter(Boolean),
6174
+ ),
6175
+ )
6019
6176
  : undefined,
6020
6177
  };
6021
6178
  try {
@@ -6028,7 +6185,7 @@ async function schedulerCreateTask(
6028
6185
  "system",
6029
6186
  "policy",
6030
6187
  globalPolicy,
6031
- legacyShell === true
6188
+ legacyShell === true,
6032
6189
  );
6033
6190
  } catch {
6034
6191
  // Не критично — основная задача уже создана.
@@ -6080,7 +6237,7 @@ async function schedulerCreateTask(
6080
6237
  undefined,
6081
6238
  clone.runWhenLoggedOff,
6082
6239
  clone.paused,
6083
- clone.legacyShell
6240
+ clone.legacyShell,
6084
6241
  );
6085
6242
  };
6086
6243
 
@@ -6126,7 +6283,7 @@ async function schedulerCreateTask(
6126
6283
  undefined,
6127
6284
  cloneNames,
6128
6285
  normalizedModel,
6129
- normalizedPriority
6286
+ normalizedPriority,
6130
6287
  );
6131
6288
  return aggregatorName;
6132
6289
  };
@@ -6149,7 +6306,7 @@ async function schedulerCreateTask(
6149
6306
  console.log(
6150
6307
  `[matrix] ${name}: синхронизация — создано ${syncResult.created.length}, ` +
6151
6308
  `обновлено ${syncResult.updated.length}, удалено ${syncResult.removed.length}, ` +
6152
- `занято ${syncResult.running.length}`
6309
+ `занято ${syncResult.running.length}`,
6153
6310
  );
6154
6311
  }
6155
6312
  } else {
@@ -6176,7 +6333,7 @@ async function schedulerCreateTask(
6176
6333
  clone: clone.name,
6177
6334
  workspace: workspaceLabel,
6178
6335
  error: err instanceof Error ? err.message : String(err),
6179
- })
6336
+ }),
6180
6337
  );
6181
6338
  }
6182
6339
  }
@@ -6208,7 +6365,7 @@ async function schedulerCreateTask(
6208
6365
  t("tool.error.matrixExpandRuntime", {
6209
6366
  name,
6210
6367
  error: err instanceof Error ? err.message : String(err),
6211
- })
6368
+ }),
6212
6369
  );
6213
6370
  }
6214
6371
  }
@@ -6225,9 +6382,9 @@ async function schedulerCreateTask(
6225
6382
  await scheduler.pauseTask(target);
6226
6383
  } catch (err: any) {
6227
6384
  console.warn(
6228
- `[windows-scheduler] Задача "${target}": пауза не восстановлена после пересоздания: ${
6385
+ `[agent-steward] Задача "${target}": пауза не восстановлена после пересоздания: ${
6229
6386
  err instanceof Error ? err.message : String(err)
6230
- }`
6387
+ }`,
6231
6388
  );
6232
6389
  }
6233
6390
  }
@@ -6246,7 +6403,7 @@ async function schedulerCreateTask(
6246
6403
  async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<void> {
6247
6404
  const paused = Boolean(
6248
6405
  definition.paused === true ||
6249
- (definition.pausedUntil && Date.parse(definition.pausedUntil) > Date.now())
6406
+ (definition.pausedUntil && Date.parse(definition.pausedUntil) > Date.now()),
6250
6407
  );
6251
6408
  await schedulerCreateTask(
6252
6409
  definition.name,
@@ -6293,7 +6450,7 @@ async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<v
6293
6450
  },
6294
6451
  definition.runWhenLoggedOff,
6295
6452
  paused,
6296
- definition.legacyShell
6453
+ definition.legacyShell,
6297
6454
  );
6298
6455
  }
6299
6456
 
@@ -6304,13 +6461,13 @@ async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<v
6304
6461
  async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }> {
6305
6462
  if (shutdownGate.isShuttingDown()) {
6306
6463
  throw new Error(
6307
- "Плагин выгружается: новые запуски не принимаются. Повторите после перезапуска."
6464
+ "Плагин выгружается: новые запуски не принимаются. Повторите после перезапуска.",
6308
6465
  );
6309
6466
  }
6310
6467
 
6311
6468
  const run = (async () => {
6312
6469
  const definition = (await loadTaskDefinitions()).find(
6313
- (def) => def.name.toLowerCase() === name.trim().toLowerCase()
6470
+ (def) => def.name.toLowerCase() === name.trim().toLowerCase(),
6314
6471
  );
6315
6472
  if (definition?.matrix) {
6316
6473
  await runMatrix(definition);
@@ -6347,7 +6504,7 @@ async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }>
6347
6504
  */
6348
6505
  async function readOsTasksWithRetry(
6349
6506
  expectNonEmpty: boolean,
6350
- delayMs = 300
6507
+ delayMs = 300,
6351
6508
  ): Promise<{
6352
6509
  tasks: Awaited<ReturnType<typeof scheduler.listTasks>>;
6353
6510
  osAvailable: boolean;
@@ -6398,7 +6555,7 @@ async function collectTasksView() {
6398
6555
  // (накопительные итоги, не зависят от retention истории). Для задач, у
6399
6556
  // которых метрик ещё нет, считаем по загруженной истории.
6400
6557
  const metricsByName = new Map(
6401
- getAllMetrics(true).map((row) => [row.taskName.toLowerCase(), row])
6558
+ getAllMetrics(true).map((row) => [row.taskName.toLowerCase(), row]),
6402
6559
  );
6403
6560
  const historyCounts = new Map<
6404
6561
  string,
@@ -6427,10 +6584,10 @@ async function collectTasksView() {
6427
6584
  const orphanNames = defs
6428
6585
  .filter((def) => !osNames.has(def.name.toLowerCase()))
6429
6586
  .map((def) => def.name);
6430
- const sources: Array<{ task: (typeof tasks)[number]; orphaned: boolean }> = [
6587
+ const sources: { task: (typeof tasks)[number]; orphaned: boolean }[] = [
6431
6588
  ...tasks.map((task) => ({ task, orphaned: false })),
6432
6589
  ...orphanNames.map((name) => ({
6433
- task: { taskName: name } as (typeof tasks)[number],
6590
+ task: { taskName: name },
6434
6591
  orphaned: true,
6435
6592
  })),
6436
6593
  ];
@@ -6466,17 +6623,17 @@ async function collectTasksView() {
6466
6623
  const metricsRow = metricsByName.get(name.toLowerCase());
6467
6624
  const counts = metricsRow
6468
6625
  ? {
6469
- total: metricsRow.total,
6470
- success: metricsRow.success,
6471
- error: metricsRow.error,
6472
- partial: metricsRow.partial,
6473
- }
6626
+ total: metricsRow.total,
6627
+ success: metricsRow.success,
6628
+ error: metricsRow.error,
6629
+ partial: metricsRow.partial,
6630
+ }
6474
6631
  : historyCounts.get(name.toLowerCase()) ?? {
6475
- total: 0,
6476
- success: 0,
6477
- error: 0,
6478
- partial: 0,
6479
- };
6632
+ total: 0,
6633
+ success: 0,
6634
+ error: 0,
6635
+ partial: 0,
6636
+ };
6480
6637
 
6481
6638
  // Спринт 27.5.2: пауза учитывает и флаг ОС, и активный pausedUntil.
6482
6639
  // nextRun считаем из определения — schtasks после мутации отдаёт
@@ -6543,13 +6700,13 @@ async function collectTasksView() {
6543
6700
  isMatrixParent: Boolean(def?.matrix),
6544
6701
  matrixSummary: matrixAggregate
6545
6702
  ? {
6546
- totalCount: matrixAggregate.totalCount,
6547
- successCount: matrixAggregate.successCount,
6548
- errorCount: matrixAggregate.errorCount,
6549
- pendingCount: matrixAggregate.pendingCount,
6550
- status: matrixAggregate.status,
6551
- message: matrixAggregate.message,
6552
- }
6703
+ totalCount: matrixAggregate.totalCount,
6704
+ successCount: matrixAggregate.successCount,
6705
+ errorCount: matrixAggregate.errorCount,
6706
+ pendingCount: matrixAggregate.pendingCount,
6707
+ status: matrixAggregate.status,
6708
+ message: matrixAggregate.message,
6709
+ }
6553
6710
  : null,
6554
6711
  prompt: def?.prompt ?? "",
6555
6712
  };