agent-steward 0.0.3 → 0.0.5

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 (287) hide show
  1. package/CHANGELOG.md +154 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +54 -9
  4. package/ROADMAP-STRATEGY.md +23 -20
  5. package/ROADMAP.md +140 -143
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +351 -0
  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 +18 -1
  14. package/dist/core/execution.d.ts +203 -0
  15. package/dist/core/execution.d.ts.map +1 -0
  16. package/dist/core/execution.js +309 -0
  17. package/dist/core/gate-integrity.d.ts +35 -0
  18. package/dist/core/gate-integrity.d.ts.map +1 -0
  19. package/dist/core/gate-integrity.js +132 -0
  20. package/dist/core/git-trigger.d.ts.map +1 -1
  21. package/dist/core/git-trigger.js +14 -2
  22. package/dist/core/guard-run.d.ts +4 -0
  23. package/dist/core/guard-run.d.ts.map +1 -0
  24. package/dist/core/guard-run.js +101 -0
  25. package/dist/core/guard.d.ts +52 -0
  26. package/dist/core/guard.d.ts.map +1 -0
  27. package/dist/core/guard.js +362 -0
  28. package/dist/core/lock.d.ts +61 -4
  29. package/dist/core/lock.d.ts.map +1 -1
  30. package/dist/core/lock.js +213 -26
  31. package/dist/core/matrix.d.ts.map +1 -1
  32. package/dist/core/matrix.js +75 -15
  33. package/dist/core/mission.d.ts +83 -0
  34. package/dist/core/mission.d.ts.map +1 -0
  35. package/dist/core/mission.js +334 -0
  36. package/dist/core/one-shot.d.ts +5 -1
  37. package/dist/core/one-shot.d.ts.map +1 -1
  38. package/dist/core/one-shot.js +33 -8
  39. package/dist/core/opencode-cli.d.ts +28 -0
  40. package/dist/core/opencode-cli.d.ts.map +1 -0
  41. package/dist/core/opencode-cli.js +74 -0
  42. package/dist/core/opencode-models.d.ts +62 -0
  43. package/dist/core/opencode-models.d.ts.map +1 -0
  44. package/dist/core/opencode-models.js +277 -0
  45. package/dist/core/pipeline-apply.d.ts +38 -0
  46. package/dist/core/pipeline-apply.d.ts.map +1 -0
  47. package/dist/core/pipeline-apply.js +117 -0
  48. package/dist/core/pipeline-io.d.ts +13 -0
  49. package/dist/core/pipeline-io.d.ts.map +1 -0
  50. package/dist/core/pipeline-io.js +64 -0
  51. package/dist/core/pipeline-map.d.ts +46 -0
  52. package/dist/core/pipeline-map.d.ts.map +1 -0
  53. package/dist/core/pipeline-map.js +196 -0
  54. package/dist/core/pipeline-spec.d.ts +109 -0
  55. package/dist/core/pipeline-spec.d.ts.map +1 -0
  56. package/dist/core/pipeline-spec.js +554 -0
  57. package/dist/core/ps-wrapper.d.ts +19 -2
  58. package/dist/core/ps-wrapper.d.ts.map +1 -1
  59. package/dist/core/ps-wrapper.js +261 -63
  60. package/dist/core/record-history.d.ts +15 -0
  61. package/dist/core/record-history.d.ts.map +1 -1
  62. package/dist/core/record-history.js +183 -58
  63. package/dist/core/router/dispatch.d.ts +36 -0
  64. package/dist/core/router/dispatch.d.ts.map +1 -0
  65. package/dist/core/router/dispatch.js +59 -0
  66. package/dist/core/router/escalation.d.ts +47 -0
  67. package/dist/core/router/escalation.d.ts.map +1 -0
  68. package/dist/core/router/escalation.js +87 -0
  69. package/dist/core/router/planner.d.ts +53 -0
  70. package/dist/core/router/planner.d.ts.map +1 -0
  71. package/dist/core/router/planner.js +113 -0
  72. package/dist/core/router/rules.d.ts +46 -0
  73. package/dist/core/router/rules.d.ts.map +1 -0
  74. package/dist/core/router/rules.js +91 -0
  75. package/dist/core/run-panel-api.d.ts +94 -0
  76. package/dist/core/run-panel-api.d.ts.map +1 -0
  77. package/dist/core/run-panel-api.js +169 -0
  78. package/dist/core/schedule-gate.js +5 -1
  79. package/dist/core/schedule-v2.d.ts +34 -0
  80. package/dist/core/schedule-v2.d.ts.map +1 -1
  81. package/dist/core/schedule-v2.js +91 -5
  82. package/dist/core/scheduler/at-fallback.d.ts +55 -2
  83. package/dist/core/scheduler/at-fallback.d.ts.map +1 -1
  84. package/dist/core/scheduler/at-fallback.js +135 -5
  85. package/dist/core/scheduler/linux.d.ts +18 -2
  86. package/dist/core/scheduler/linux.d.ts.map +1 -1
  87. package/dist/core/scheduler/linux.js +63 -20
  88. package/dist/core/scheduler/mac.d.ts +44 -2
  89. package/dist/core/scheduler/mac.d.ts.map +1 -1
  90. package/dist/core/scheduler/mac.js +126 -15
  91. package/dist/core/scheduler/posix.d.ts.map +1 -1
  92. package/dist/core/scheduler/posix.js +25 -1
  93. package/dist/core/scheduler/registry.d.ts +11 -0
  94. package/dist/core/scheduler/registry.d.ts.map +1 -1
  95. package/dist/core/scheduler/registry.js +83 -21
  96. package/dist/core/scheduler/run-now.d.ts +16 -0
  97. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  98. package/dist/core/scheduler/run-now.js +28 -0
  99. package/dist/core/scheduler/windows.d.ts.map +1 -1
  100. package/dist/core/scheduler/windows.js +15 -12
  101. package/dist/core/secrets.d.ts.map +1 -1
  102. package/dist/core/secrets.js +125 -28
  103. package/dist/core/session.d.ts.map +1 -1
  104. package/dist/core/session.js +18 -11
  105. package/dist/core/structured-log.d.ts +7 -1
  106. package/dist/core/structured-log.d.ts.map +1 -1
  107. package/dist/core/task-name.d.ts +24 -0
  108. package/dist/core/task-name.d.ts.map +1 -0
  109. package/dist/core/task-name.js +40 -0
  110. package/dist/core/worktree-run.d.ts +4 -0
  111. package/dist/core/worktree-run.d.ts.map +1 -0
  112. package/dist/core/worktree-run.js +164 -0
  113. package/dist/core/worktree.d.ts +115 -0
  114. package/dist/core/worktree.d.ts.map +1 -0
  115. package/dist/core/worktree.js +462 -0
  116. package/dist/core/wrappers/bash.d.ts +17 -0
  117. package/dist/core/wrappers/bash.d.ts.map +1 -1
  118. package/dist/core/wrappers/bash.js +224 -28
  119. package/dist/db/capability-repo.d.ts +124 -0
  120. package/dist/db/capability-repo.d.ts.map +1 -0
  121. package/dist/db/capability-repo.js +267 -0
  122. package/dist/db/history-repo.d.ts +46 -5
  123. package/dist/db/history-repo.d.ts.map +1 -1
  124. package/dist/db/history-repo.js +107 -25
  125. package/dist/db/index.d.ts +4 -0
  126. package/dist/db/index.d.ts.map +1 -1
  127. package/dist/db/index.js +39 -1
  128. package/dist/db/metrics-repo.js +2 -2
  129. package/dist/db/migrate.d.ts.map +1 -1
  130. package/dist/db/migrate.js +3 -1
  131. package/dist/db/recovery.d.ts.map +1 -1
  132. package/dist/db/recovery.js +5 -4
  133. package/dist/db/run-context.d.ts +103 -0
  134. package/dist/db/run-context.d.ts.map +1 -0
  135. package/dist/db/run-context.js +224 -0
  136. package/dist/db/run-dlq.d.ts +100 -0
  137. package/dist/db/run-dlq.d.ts.map +1 -0
  138. package/dist/db/run-dlq.js +191 -0
  139. package/dist/db/run-journal.d.ts +33 -5
  140. package/dist/db/run-journal.d.ts.map +1 -1
  141. package/dist/db/run-journal.js +78 -14
  142. package/dist/db/run-resume.d.ts +10 -2
  143. package/dist/db/run-resume.d.ts.map +1 -1
  144. package/dist/db/run-resume.js +39 -13
  145. package/dist/db/runs-repo.d.ts +32 -7
  146. package/dist/db/runs-repo.d.ts.map +1 -1
  147. package/dist/db/runs-repo.js +50 -11
  148. package/dist/db/schema.d.ts +2 -2
  149. package/dist/db/schema.d.ts.map +1 -1
  150. package/dist/db/schema.js +216 -3
  151. package/dist/db/settings-repo.d.ts +11 -0
  152. package/dist/db/settings-repo.d.ts.map +1 -1
  153. package/dist/db/settings-repo.js +25 -0
  154. package/dist/db/step-idempotency.d.ts +51 -0
  155. package/dist/db/step-idempotency.d.ts.map +1 -0
  156. package/dist/db/step-idempotency.js +136 -0
  157. package/dist/history.d.ts +1 -1
  158. package/dist/history.d.ts.map +1 -1
  159. package/dist/i18n.d.ts +5 -0
  160. package/dist/i18n.d.ts.map +1 -1
  161. package/dist/i18n.js +11 -4
  162. package/dist/index.d.ts +140 -6
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +480 -18
  165. package/dist/notifications.d.ts +22 -0
  166. package/dist/notifications.d.ts.map +1 -1
  167. package/dist/notifications.js +36 -8
  168. package/dist/profiles.d.ts.map +1 -1
  169. package/dist/profiles.js +25 -4
  170. package/dist/rpc.d.ts +924 -0
  171. package/dist/rpc.d.ts.map +1 -1
  172. package/dist/rpc.js +352 -0
  173. package/dist/server.d.ts +46 -0
  174. package/dist/server.d.ts.map +1 -1
  175. package/dist/server.js +172 -53
  176. package/dist/settings.d.ts +2 -2
  177. package/dist/settings.d.ts.map +1 -1
  178. package/dist/settings.js +3 -3
  179. package/dist/shared/jobs-view.d.ts +1 -1
  180. package/dist/shared/jobs-view.d.ts.map +1 -1
  181. package/dist/shared/jobs-view.js +2 -0
  182. package/dist/task-transfer.d.ts +16 -0
  183. package/dist/task-transfer.d.ts.map +1 -1
  184. package/dist/task-transfer.js +16 -0
  185. package/dist/types.d.ts.map +1 -1
  186. package/dist/types.js +7 -0
  187. package/dist/workspaces.d.ts +25 -3
  188. package/dist/workspaces.d.ts.map +1 -1
  189. package/dist/workspaces.js +43 -8
  190. package/docs/ARCHITECTURE.md +498 -58
  191. package/docs/COMPATIBILITY.md +2 -2
  192. package/docs/CONCEPT.md +185 -91
  193. package/docs/CROSS_PLATFORM.ru.md +20 -0
  194. package/docs/CROSS_PLATFORM.zh.md +18 -0
  195. package/docs/EXECUTION-LOOP.md +211 -0
  196. package/docs/FEATURES.md +65 -4
  197. package/docs/FEATURES.zh.md +52 -4
  198. package/docs/MIGRATION.md +2 -2
  199. package/docs/PIPELINE.md +293 -0
  200. package/docs/README.ru.md +44 -5
  201. package/docs/README.zh.md +46 -6
  202. package/docs/SAFETY.md +142 -0
  203. package/docs/SAVINGS.md +29 -0
  204. package/docs/SAVINGS.ru.md +29 -0
  205. package/docs/SAVINGS.zh.md +18 -0
  206. package/gui-experimental.cjs +9 -8
  207. package/locales/en.json +84 -1
  208. package/locales/ru.json +84 -1
  209. package/locales/zh.json +84 -1
  210. package/opencode.pipeline.yaml +35 -0
  211. package/package.json +46 -2
  212. package/scripts/audit-bundle.mjs +215 -0
  213. package/scripts/test-home.mjs +83 -0
  214. package/src/cli.ts +412 -0
  215. package/src/core/dlq-api.ts +98 -0
  216. package/src/core/dry-run.ts +27 -3
  217. package/src/core/execution.ts +538 -0
  218. package/src/core/file-watcher.ts +2 -2
  219. package/src/core/gate-integrity.ts +160 -0
  220. package/src/core/git-trigger.ts +18 -5
  221. package/src/core/guard-run.ts +119 -0
  222. package/src/core/guard.ts +431 -0
  223. package/src/core/lock.ts +244 -30
  224. package/src/core/matrix.ts +95 -50
  225. package/src/core/mission.ts +485 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/one-shot.ts +36 -8
  228. package/src/core/opencode-cli.ts +103 -0
  229. package/src/core/opencode-models.ts +315 -0
  230. package/src/core/pipeline-apply.ts +158 -0
  231. package/src/core/pipeline-io.ts +79 -0
  232. package/src/core/pipeline-map.ts +264 -0
  233. package/src/core/pipeline-spec.ts +775 -0
  234. package/src/core/ps-wrapper.ts +274 -64
  235. package/src/core/record-history.ts +229 -104
  236. package/src/core/router/dispatch.ts +94 -0
  237. package/src/core/router/escalation.ts +129 -0
  238. package/src/core/router/planner.ts +166 -0
  239. package/src/core/router/rules.ts +115 -0
  240. package/src/core/run-panel-api.ts +262 -0
  241. package/src/core/schedule-gate.ts +7 -3
  242. package/src/core/schedule-v2.ts +114 -5
  243. package/src/core/scheduler/at-fallback.ts +190 -5
  244. package/src/core/scheduler/linux.ts +72 -21
  245. package/src/core/scheduler/logs.ts +2 -2
  246. package/src/core/scheduler/mac.ts +174 -14
  247. package/src/core/scheduler/posix.ts +20 -1
  248. package/src/core/scheduler/registry.ts +107 -26
  249. package/src/core/scheduler/run-now.ts +32 -0
  250. package/src/core/scheduler/windows.ts +19 -15
  251. package/src/core/secrets.ts +131 -31
  252. package/src/core/session.ts +23 -10
  253. package/src/core/structured-log.ts +22 -5
  254. package/src/core/task-name.ts +67 -0
  255. package/src/core/telegram.ts +2 -2
  256. package/src/core/triage-worker.ts +7 -7
  257. package/src/core/triage.ts +2 -2
  258. package/src/core/worktree-run.ts +199 -0
  259. package/src/core/worktree.ts +600 -0
  260. package/src/core/wrappers/bash.ts +239 -27
  261. package/src/db/capability-repo.ts +402 -0
  262. package/src/db/history-repo.ts +151 -22
  263. package/src/db/index.ts +37 -1
  264. package/src/db/metrics-repo.ts +2 -2
  265. package/src/db/migrate.ts +3 -1
  266. package/src/db/recovery.ts +5 -4
  267. package/src/db/run-context.ts +370 -0
  268. package/src/db/run-dlq.ts +310 -0
  269. package/src/db/run-journal.ts +100 -13
  270. package/src/db/run-resume.ts +65 -13
  271. package/src/db/runs-repo.ts +66 -13
  272. package/src/db/schema.ts +218 -3
  273. package/src/db/settings-repo.ts +31 -0
  274. package/src/db/step-idempotency.ts +185 -0
  275. package/src/gui.tsx +692 -13
  276. package/src/history.ts +1 -1
  277. package/src/i18n.ts +12 -4
  278. package/src/index.ts +648 -8
  279. package/src/notifications.ts +38 -8
  280. package/src/profiles.ts +26 -4
  281. package/src/rpc.ts +379 -0
  282. package/src/server.ts +206 -54
  283. package/src/settings.ts +5 -5
  284. package/src/shared/jobs-view.ts +3 -1
  285. package/src/task-transfer.ts +31 -0
  286. package/src/types.ts +9 -0
  287. package/src/workspaces.ts +58 -9
package/src/index.ts CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  validateModelId,
23
23
  validateTaskName,
24
24
  } from "./types.js";
25
- 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";
26
26
  import {
27
27
  buildLaunchdOneShotCleanup,
28
28
  normalizeOneShotRunAt,
@@ -36,10 +36,12 @@ import {
36
36
  type SessionMode,
37
37
  } from "./core/session.js";
38
38
  import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
39
- import { getSchedulerBackend } from "./core/scheduler/index.js";
39
+ import { getSchedulerBackend, LinuxScheduler } from "./core/scheduler/index.js";
40
40
  import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
41
41
  import { getTaskLogs } from "./core/scheduler/logs.js";
42
+ import { findSanitizedNameConflict, sanitizedConflictMessage } from "./core/task-name.js";
42
43
  import { writeBashWrapper } from "./core/wrappers/bash.js";
44
+ import { normalizeTaskGuards, type TaskGuards } from "./core/guard.js";
43
45
  import { simulatePipeline } from "./core/dry-run.js";
44
46
  import {
45
47
  aggregateMatrixResults,
@@ -56,6 +58,22 @@ import {
56
58
  import { normalizeWatchPath, validateWatchGlobs } from "./core/watch-paths.js";
57
59
  import { createShutdownGate } from "./core/shutdown.js";
58
60
  import { SchedulerRpc } from "./rpc.js";
61
+ import {
62
+ validatePipelineSpec,
63
+ type PipelineValidationResult,
64
+ } from "./core/pipeline-spec.js";
65
+ import {
66
+ loadPipelineFile,
67
+ parsePipelineYaml,
68
+ type PipelineParseResult,
69
+ } from "./core/pipeline-io.js";
70
+ import {
71
+ planPipelineApply,
72
+ executePipelineApply,
73
+ type PipelineApplyPlan,
74
+ } from "./core/pipeline-apply.js";
75
+ import { pipelineSpecToTasks, tasksToPipelineSpec } from "./core/pipeline-map.js";
76
+ import { stringify as yamlStringify } from "yaml";
59
77
  import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
60
78
  import { defaultNotifications, loadSettings, saveSettings } from "./settings.js";
61
79
  import { resolveLocale, setLocale, t, type Locale, type LocaleMode } from "./i18n.js";
@@ -67,6 +85,7 @@ import type {
67
85
  PermissionSettings,
68
86
  TriageSettings,
69
87
  } from "./settings.js";
88
+ import { runMission, type MissionSpec } from "./core/mission.js";
70
89
  import {
71
90
  DEFAULT_PERMISSION_POLICY,
72
91
  buildOpencodeConfig,
@@ -78,6 +97,12 @@ import { buildAnalytics } from "./core/analytics.js";
78
97
  import { generateSelfAnalysisReport } from "./core/self-analysis.js";
79
98
  import { getHistory, listRunningRecords } from "./db/history-repo.js";
80
99
  import { getAllMetrics } from "./db/metrics-repo.js";
100
+ import { discardDlq, listDlq, retryDlq } from "./core/dlq-api.js";
101
+ import {
102
+ listRunPanel,
103
+ pauseRunPanel,
104
+ resumeRunPanel,
105
+ } from "./core/run-panel-api.js";
81
106
  import {
82
107
  findStuckMatrixClones,
83
108
  maybeSendDigest,
@@ -197,6 +222,41 @@ const gatePath = (() => {
197
222
  return distPath;
198
223
  })();
199
224
 
225
+ /**
226
+ * W-1: путь к помощнику создания одноразового git worktree
227
+ * (dist/core/worktree-run.js). Обёртка вызывает его перед opencode.
228
+ */
229
+ const worktreeHelperPath = (() => {
230
+ const resolved = require.resolve("./core/worktree-run.js");
231
+ if (!resolved.endsWith(".ts")) return resolved;
232
+ const distPath = resolved
233
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
234
+ .replace(/\.ts$/, ".js");
235
+ if (existsSync(distPath)) return distPath;
236
+ console.warn(
237
+ "[agent-steward] Не найден собранный worktree-run.js: " +
238
+ `${distPath}. Изоляция в git worktree не будет работать. Выполните npm run build.`,
239
+ );
240
+ return distPath;
241
+ })();
242
+
243
+ /**
244
+ * W-3: путь к CLI-помощнику guard-условий (dist/core/guard-run.js).
245
+ */
246
+ const guardHelperPath = (() => {
247
+ const resolved = require.resolve("./core/guard-run.js");
248
+ if (!resolved.endsWith(".ts")) return resolved;
249
+ const distPath = resolved
250
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
251
+ .replace(/\.ts$/, ".js");
252
+ if (existsSync(distPath)) return distPath;
253
+ console.warn(
254
+ "[agent-steward] Не найден собранный guard-run.js: " +
255
+ `${distPath}. Guard-условия не будут проверяться. Выполните npm run build.`,
256
+ );
257
+ return distPath;
258
+ })();
259
+
200
260
  /** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
201
261
  const scheduler = getSchedulerBackend();
202
262
 
@@ -252,6 +312,40 @@ export const matrixSchema = z.object({
252
312
  ),
253
313
  });
254
314
 
315
+ /** W-3: guard-условия задачи. */
316
+ export const guardsSchema = z.object({
317
+ command: z
318
+ .string()
319
+ .max(4000)
320
+ .optional()
321
+ .describe("Shell command evaluated before the run. Exit 0 runs the task; any other code skips it."),
322
+ timeoutSeconds: z
323
+ .number()
324
+ .int()
325
+ .min(1)
326
+ .max(3600)
327
+ .optional()
328
+ .describe("Shell guard timeout in seconds (default 60)."),
329
+ semantic: z
330
+ .object({
331
+ filesExist: z.array(z.string()).max(200).optional().describe("Paths that must exist."),
332
+ filesMissing: z.array(z.string()).max(200).optional().describe("Paths that must not exist."),
333
+ branch: z.string().max(200).optional().describe("Glob for the current git branch, e.g. feature/*."),
334
+ changedPaths: z
335
+ .array(z.string())
336
+ .max(200)
337
+ .optional()
338
+ .describe("Globs of changed paths; at least one must match."),
339
+ changedSince: z
340
+ .string()
341
+ .max(100)
342
+ .optional()
343
+ .describe("Git ref to diff against (default HEAD~1)."),
344
+ })
345
+ .optional()
346
+ .describe("Semantic pre-run checks inside the working directory."),
347
+ }).describe("W-3: guard conditions. If a check fails, the run is skipped before opencode starts.");
348
+
255
349
  /** Zod-схема аргументов schedule_task */
256
350
  export const scheduleTaskSchema = z.object({
257
351
  name: z
@@ -471,6 +565,17 @@ export const scheduleTaskSchema = z.object({
471
565
  .describe(
472
566
  "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.",
473
567
  ),
568
+ worktree: z
569
+ .boolean()
570
+ .optional()
571
+ .describe(
572
+ "W-1: run each tick in a one-off git worktree created from HEAD of workingDirectory. Keeps fan-out runs isolated from each other and from the main checkout. Requires a git repository; creation failure fails the run closed. Default false.",
573
+ ),
574
+ guards: guardsSchema
575
+ .optional()
576
+ .describe(
577
+ "W-3: pre-run guard conditions. If a semantic check or shell command fails, the run is skipped (no opencode, no side effects). Combined with worktree: checks run inside the fresh worktree.",
578
+ ),
474
579
  matrix: matrixSchema
475
580
  .optional()
476
581
  .describe(
@@ -685,6 +790,15 @@ export const updateTaskSchema = z.object({
685
790
  .describe(
686
791
  "Transitional flag (release 1.6): re-enable shell under the hybrid policy for this task.",
687
792
  ),
793
+ worktree: z
794
+ .boolean()
795
+ .optional()
796
+ .describe(
797
+ "W-1: run each tick in a one-off git worktree created from HEAD of workingDirectory. Default false.",
798
+ ),
799
+ guards: guardsSchema
800
+ .optional()
801
+ .describe("W-3: pre-run guard conditions; a failed check skips the run."),
688
802
  matrix: matrixSchema
689
803
  .nullable()
690
804
  .optional()
@@ -758,6 +872,33 @@ const dryRunSchema = z.object({
758
872
  ),
759
873
  });
760
874
 
875
+ /** pipeline_validate — проверить опencode.pipeline.yaml (путь или исходник). */
876
+ export const pipelineValidateSchema = z.object({
877
+ path: z.string().optional().describe("Путь к файлу opencode.pipeline.yaml."),
878
+ source: z.string().optional().describe("Исходное содержимое YAML."),
879
+ dryRun: z
880
+ .boolean()
881
+ .optional()
882
+ .default(true)
883
+ .describe("Если true — только валидация без применения (по умолчанию true)."),
884
+ });
885
+
886
+ /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
887
+ export const pipelineApplySchema = z.object({
888
+ path: z.string().optional().describe("Путь к файлу opencode.pipeline.yaml."),
889
+ source: z.string().optional().describe("Исходное содержимое YAML."),
890
+ dryRun: z
891
+ .boolean()
892
+ .optional()
893
+ .default(false)
894
+ .describe("Если true — прогон diff'а без применения изменений (по умолчанию false)."),
895
+ });
896
+
897
+ /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
898
+ export const pipelineExportSchema = z.object({
899
+ pipeline: z.string().describe("Имя конвейера (pipelineName)."),
900
+ });
901
+
761
902
  const manageWorkspacesSchema = z.object({
762
903
  action: z
763
904
  .enum(["list", "add", "update", "delete"])
@@ -875,7 +1016,7 @@ export const manageSettingsSchema = z.object({
875
1016
  .enum(["auto", "ru", "en", "zh"])
876
1017
  .optional()
877
1018
  .describe(
878
- "Interface language: auto (follow OpenCode), ru (default), en or zh. Applies without restart.",
1019
+ "Interface language: auto (default, follows OpenCode), ru, en or zh. Applies without restart.",
879
1020
  ),
880
1021
  winterMode: z
881
1022
  .boolean()
@@ -1098,6 +1239,9 @@ type CleanupHistoryArgs = z.infer<typeof cleanupHistorySchema>;
1098
1239
  type EmitEventArgs = z.infer<typeof emitEventSchema>;
1099
1240
  type SecretsArgs = z.infer<typeof manageSecretsSchema>;
1100
1241
  type AuditLogArgs = z.infer<typeof getAuditLogSchema>;
1242
+ type PipelineValidateArgs = z.infer<typeof pipelineValidateSchema>;
1243
+ type PipelineApplyArgs = z.infer<typeof pipelineApplySchema>;
1244
+ type PipelineExportArgs = z.infer<typeof pipelineExportSchema>;
1101
1245
 
1102
1246
  /**
1103
1247
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
@@ -1253,6 +1397,8 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
1253
1397
  gitPollSeconds,
1254
1398
  runWhenLoggedOff,
1255
1399
  legacyShell,
1400
+ worktree,
1401
+ guards,
1256
1402
  } = args;
1257
1403
 
1258
1404
  let effectiveRunAt: string | undefined;
@@ -1321,6 +1467,8 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
1321
1467
  runWhenLoggedOff === true,
1322
1468
  undefined,
1323
1469
  legacyShell === true,
1470
+ worktree === true,
1471
+ guards,
1324
1472
  );
1325
1473
  } catch (err: any) {
1326
1474
  return {
@@ -1387,6 +1535,8 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
1387
1535
  workspaceId: workspace?.id ?? null,
1388
1536
  workspaceName: workspace?.name ?? null,
1389
1537
  matrix: matrix ?? null,
1538
+ worktree: worktree === true,
1539
+ guards: guards ?? null,
1390
1540
  },
1391
1541
  }),
1392
1542
  };
@@ -1500,6 +1650,8 @@ async function cancelMatrixRun(
1500
1650
  clone.runWhenLoggedOff,
1501
1651
  clone.paused,
1502
1652
  clone.legacyShell,
1653
+ clone.worktree,
1654
+ clone.guards,
1503
1655
  );
1504
1656
  } catch (err: any) {
1505
1657
  warnings.push(
@@ -2012,6 +2164,8 @@ async function updateTaskFromInput(
2012
2164
  input.runWhenLoggedOff ?? previous.runWhenLoggedOff,
2013
2165
  wasPaused,
2014
2166
  input.legacyShell ?? previous.legacyShell,
2167
+ input.worktree ?? previous.worktree,
2168
+ input.guards ?? previous.guards,
2015
2169
  );
2016
2170
 
2017
2171
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
@@ -2438,6 +2592,239 @@ const dryRunExecute = wrapExecute<DryRunArgs>(async (args) => {
2438
2592
  };
2439
2593
  });
2440
2594
 
2595
+ /** pipeline_validate — проверить opencode.pipeline.yaml (путь или исходник). */
2596
+ const pipelineValidateExecute = wrapExecute<PipelineValidateArgs>(async (args) => {
2597
+ const path = args.path ?? args.source ? undefined : undefined;
2598
+ if (args.path === undefined && args.source === undefined) {
2599
+ return {
2600
+ content: JSON.stringify({
2601
+ success: false,
2602
+ pipeline: null,
2603
+ errors: ["Укажите path к файлу или source с содержимым YAML"],
2604
+ warnings: [],
2605
+ }),
2606
+ };
2607
+ }
2608
+ const parsed =
2609
+ args.source !== undefined
2610
+ ? validatePipelineSpecFromSource(args.source)
2611
+ : await loadPipelineFile(args.path!);
2612
+ if (!parsed.ok) {
2613
+ return {
2614
+ content: JSON.stringify({
2615
+ success: false,
2616
+ pipeline: null,
2617
+ errors: parsed.errors,
2618
+ warnings: parsed.warnings,
2619
+ }),
2620
+ };
2621
+ }
2622
+ const spec = parsed.spec!;
2623
+ return {
2624
+ content: JSON.stringify({
2625
+ success: true,
2626
+ pipeline: spec.name,
2627
+ steps: spec.steps.length,
2628
+ errors: [],
2629
+ warnings: parsed.warnings,
2630
+ }),
2631
+ };
2632
+ });
2633
+
2634
+ function validatePipelineSpecFromSource(source: string): PipelineParseResult {
2635
+ const parsed = parsePipelineYaml(source);
2636
+ return parsed;
2637
+ }
2638
+
2639
+ /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
2640
+ const pipelineApplyExecute = wrapExecute<PipelineApplyArgs>(async (args) => {
2641
+ const dryRun = args.dryRun !== false;
2642
+ const parsed =
2643
+ args.source !== undefined
2644
+ ? validatePipelineSpecFromSource(args.source)
2645
+ : await loadPipelineFile(args.path!);
2646
+ if (!parsed.ok) {
2647
+ return {
2648
+ content: JSON.stringify({
2649
+ success: false,
2650
+ pipeline: null,
2651
+ errors: parsed.errors,
2652
+ warnings: parsed.warnings,
2653
+ }),
2654
+ };
2655
+ }
2656
+
2657
+ const spec = parsed.spec!;
2658
+ const existing = await listTaskDefinitions();
2659
+ const plan = planPipelineApply(spec, existing, {
2660
+ resolveWorkspaceId: (nameOrId: string) => {
2661
+ const ws = getWorkspace(nameOrId);
2662
+ return ws ? ws.id : undefined;
2663
+ },
2664
+ });
2665
+
2666
+ let created = 0;
2667
+ let updated = 0;
2668
+ const errors: string[] = [];
2669
+
2670
+ if (!dryRun) {
2671
+ for (const task of plan.creates) {
2672
+ try {
2673
+ await schedulerCreateTask(
2674
+ task.name,
2675
+ task.schedule,
2676
+ task.prompt,
2677
+ task.timeoutSeconds,
2678
+ task.workingDirectory ?? task.workdir ?? undefined,
2679
+ task.retryCount,
2680
+ task.retryDelay,
2681
+ task.qualityGate,
2682
+ task.nextTaskOnSuccess,
2683
+ task.nextTaskOnError,
2684
+ task.triggerType ?? "cron",
2685
+ task.watchPath,
2686
+ task.dependsOn,
2687
+ task.model,
2688
+ task.priority,
2689
+ task.beforeScript,
2690
+ task.afterScript,
2691
+ task.mcpEvent,
2692
+ task.workspaceId,
2693
+ task.allowedTools,
2694
+ task.deniedTools,
2695
+ task.matrix,
2696
+ task.matrixParentId,
2697
+ "create",
2698
+ task.timezone,
2699
+ task.notBefore,
2700
+ task.notAfter,
2701
+ task.pausedUntil,
2702
+ task.runAt,
2703
+ task.session,
2704
+ task.sessionId,
2705
+ task.sessionMaxRuns,
2706
+ {
2707
+ activeDays: task.activeDays,
2708
+ windowPolicy: task.windowPolicy,
2709
+ watchGlobs: task.watchGlobs ?? [],
2710
+ watchIgnore: task.watchIgnore ?? [],
2711
+ gitBranch: task.gitBranch,
2712
+ gitPaths: task.gitPaths,
2713
+ gitIgnore: task.gitIgnore,
2714
+ gitPollSeconds: task.gitPollSeconds,
2715
+ },
2716
+ task.runWhenLoggedOff ?? false,
2717
+ task.paused ?? false,
2718
+ task.legacyShell ?? false,
2719
+ task.worktree ?? false,
2720
+ task.guards,
2721
+ );
2722
+ await saveTaskDefinition(task);
2723
+ created++;
2724
+ } catch (err: any) {
2725
+ errors.push(`create ${task.name}: ${err instanceof Error ? err.message : String(err)}`);
2726
+ }
2727
+ }
2728
+ for (const item of plan.updates) {
2729
+ try {
2730
+ await schedulerCreateTask(
2731
+ item.task.name,
2732
+ item.task.schedule,
2733
+ item.task.prompt,
2734
+ item.task.timeoutSeconds,
2735
+ item.task.workingDirectory ?? item.task.workdir ?? undefined,
2736
+ item.task.retryCount,
2737
+ item.task.retryDelay,
2738
+ item.task.qualityGate,
2739
+ item.task.nextTaskOnSuccess,
2740
+ item.task.nextTaskOnError,
2741
+ item.task.triggerType ?? "cron",
2742
+ item.task.watchPath,
2743
+ item.task.dependsOn,
2744
+ item.task.model,
2745
+ item.task.priority,
2746
+ item.task.beforeScript,
2747
+ item.task.afterScript,
2748
+ item.task.mcpEvent,
2749
+ item.task.workspaceId,
2750
+ item.task.allowedTools,
2751
+ item.task.deniedTools,
2752
+ item.task.matrix,
2753
+ item.task.matrixParentId,
2754
+ "sync",
2755
+ item.task.timezone,
2756
+ item.task.notBefore,
2757
+ item.task.notAfter,
2758
+ item.task.pausedUntil,
2759
+ item.task.runAt,
2760
+ item.task.session,
2761
+ item.task.sessionId,
2762
+ item.task.sessionMaxRuns,
2763
+ {
2764
+ activeDays: item.task.activeDays,
2765
+ windowPolicy: item.task.windowPolicy,
2766
+ watchGlobs: item.task.watchGlobs ?? [],
2767
+ watchIgnore: item.task.watchIgnore ?? [],
2768
+ gitBranch: item.task.gitBranch,
2769
+ gitPaths: item.task.gitPaths,
2770
+ gitIgnore: item.task.gitIgnore,
2771
+ gitPollSeconds: item.task.gitPollSeconds,
2772
+ },
2773
+ item.task.runWhenLoggedOff ?? false,
2774
+ item.task.paused ?? false,
2775
+ item.task.legacyShell ?? false,
2776
+ item.task.worktree ?? false,
2777
+ item.task.guards,
2778
+ );
2779
+ await saveTaskDefinition(item.task);
2780
+ updated++;
2781
+ } catch (err: any) {
2782
+ errors.push(`update ${item.task.name}: ${err instanceof Error ? err.message : String(err)}`);
2783
+ }
2784
+ }
2785
+ refreshTriggers();
2786
+ }
2787
+
2788
+ return {
2789
+ content: JSON.stringify({
2790
+ success: errors.length === 0,
2791
+ pipeline: spec.name,
2792
+ dryRun,
2793
+ created,
2794
+ updated,
2795
+ unchanged: plan.unchanged.length,
2796
+ stale: plan.stale.length,
2797
+ warnings: [...plan.warnings, ...errors],
2798
+ errors,
2799
+ }),
2800
+ };
2801
+ });
2802
+
2803
+ /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
2804
+ const pipelineExportExecute = wrapExecute<PipelineExportArgs>(async (args) => {
2805
+ const allTasks = await listTaskDefinitions();
2806
+ const result = tasksToPipelineSpec(allTasks, args.pipeline);
2807
+ if (!result.spec) {
2808
+ return {
2809
+ content: JSON.stringify({
2810
+ success: false,
2811
+ error: `Конвейер "${args.pipeline}" не найден (не найдены задачи с pipelineName=${args.pipeline} и pipelineStepId).`,
2812
+ warnings: result.warnings,
2813
+ }),
2814
+ };
2815
+ }
2816
+ const yamlText = yamlStringify(result.spec, { lineWidth: 0 });
2817
+ return {
2818
+ content: JSON.stringify({
2819
+ success: true,
2820
+ pipeline: args.pipeline,
2821
+ steps: result.spec.steps.length,
2822
+ yaml: yamlText,
2823
+ warnings: result.warnings,
2824
+ }),
2825
+ };
2826
+ });
2827
+
2441
2828
  /**
2442
2829
  * Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
2443
2830
  * Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
@@ -2448,8 +2835,17 @@ async function refreshWorkspaceEnvFiles(workspaceId: string): Promise<number> {
2448
2835
  let refreshed = 0;
2449
2836
  for (const task of await loadTaskDefinitions()) {
2450
2837
  if (task.workspaceId !== workspaceId) continue;
2451
- writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
2452
- refreshed += 1;
2838
+ try {
2839
+ writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
2840
+ refreshed += 1;
2841
+ } catch (err: any) {
2842
+ // P2-21: не разрешаем задаче работать с литералом ${secret:...}.
2843
+ console.error(
2844
+ `[workspace] Задача "${task.name}": env-файл не обновлён — ${
2845
+ err instanceof Error ? err.message : String(err)
2846
+ }`,
2847
+ );
2848
+ }
2453
2849
  }
2454
2850
  return refreshed;
2455
2851
  }
@@ -3013,6 +3409,24 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
3013
3409
  def.notAfter,
3014
3410
  def.pausedUntil,
3015
3411
  def.runAt,
3412
+ def.session,
3413
+ def.sessionId,
3414
+ def.sessionMaxRuns,
3415
+ {
3416
+ activeDays: def.activeDays,
3417
+ windowPolicy: def.windowPolicy,
3418
+ watchGlobs: def.watchGlobs,
3419
+ watchIgnore: def.watchIgnore,
3420
+ gitBranch: def.gitBranch,
3421
+ gitPaths: def.gitPaths,
3422
+ gitIgnore: def.gitIgnore,
3423
+ gitPollSeconds: def.gitPollSeconds,
3424
+ },
3425
+ def.runWhenLoggedOff,
3426
+ def.paused,
3427
+ def.legacyShell,
3428
+ def.worktree,
3429
+ def.guards,
3016
3430
  );
3017
3431
  await saveTaskDefinition(def);
3018
3432
  imported.push(def.name);
@@ -3214,6 +3628,11 @@ const RPC_AUDIT_RULES: Record<
3214
3628
  update_task: { action: "task.update", targetType: "task", target: (i) => i.name ?? "" },
3215
3629
  delete_task: { action: "task.delete", targetType: "task", target: (i) => i.name ?? "" },
3216
3630
  run_task: { action: "task.run", targetType: "task", target: (i) => i.name ?? "" },
3631
+ run_mission: {
3632
+ action: "mission.run",
3633
+ targetType: "mission",
3634
+ target: (i) => i.taskName ?? "ad-hoc",
3635
+ },
3217
3636
  pause_task: { action: "task.pause", targetType: "task", target: (i) => i.name ?? "" },
3218
3637
  resume_task: { action: "task.resume", targetType: "task", target: (i) => i.name ?? "" },
3219
3638
  cancel_matrix: { action: "matrix.cancel", targetType: "matrix", target: (i) => i.name ?? "" },
@@ -3227,6 +3646,18 @@ const RPC_AUDIT_RULES: Record<
3227
3646
  targetType: "history",
3228
3647
  target: () => "runs",
3229
3648
  },
3649
+ retry_dlq: { action: "dlq.retry", targetType: "dlq", target: (i) => i.id ?? "" },
3650
+ discard_dlq: { action: "dlq.discard", targetType: "dlq", target: (i) => i.id ?? "" },
3651
+ pause_durable_run: {
3652
+ action: "run.pause",
3653
+ targetType: "run",
3654
+ target: (i) => i.runId ?? "",
3655
+ },
3656
+ resume_durable_run: {
3657
+ action: "run.resume",
3658
+ targetType: "run",
3659
+ target: (i) => i.runId ?? "",
3660
+ },
3230
3661
  emit_event: { action: "event.emit", targetType: "event", target: (i) => i.eventName ?? "" },
3231
3662
  add_workspace: {
3232
3663
  action: "workspace.add",
@@ -3470,6 +3901,26 @@ export async function createRuntime(ctxLike: RuntimeContextLike): Promise<Schedu
3470
3901
  }`,
3471
3902
  );
3472
3903
  }
3904
+ // P1-14: pid:-записи fallback'а не переживают перезагрузку. Чистим их и
3905
+ // пересоздаём будущие one-shot, иначе после reboot можно убить чужой pid.
3906
+ if (scheduler instanceof LinuxScheduler) {
3907
+ try {
3908
+ const report = await scheduler.pruneStaleFallbacks();
3909
+ if (report.removed || report.rescheduled || report.missed) {
3910
+ console.log(
3911
+ `[scheduler] Fallback one-shot: удалено ${report.removed}, ` +
3912
+ `пересоздано ${report.rescheduled}, пропущено ${report.missed}, ` +
3913
+ `живо ${report.kept}.`,
3914
+ );
3915
+ }
3916
+ } catch (err: any) {
3917
+ console.error(
3918
+ `[scheduler] Не удалось очистить fallback-записи: ${
3919
+ err instanceof Error ? err.message : String(err)
3920
+ }`,
3921
+ );
3922
+ }
3923
+ }
3473
3924
  checkJsonBackups();
3474
3925
  void garbageCollectTaskArtifacts().catch((err) => {
3475
3926
  console.log(`[gc] Не удалось вычистить мусорные файлы: ${err instanceof Error ? err.message : String(err)}`);
@@ -3654,6 +4105,9 @@ export interface ToolHandlers {
3654
4105
  get_history: typeof getHistoryExecute;
3655
4106
  get_task_logs: typeof getTaskLogsExecute;
3656
4107
  dry_run: typeof dryRunExecute;
4108
+ pipeline_validate: typeof pipelineValidateExecute;
4109
+ pipeline_apply: typeof pipelineApplyExecute;
4110
+ pipeline_export: typeof pipelineExportExecute;
3657
4111
  manage_workspaces: typeof manageWorkspacesExecute;
3658
4112
  matrix_control: typeof matrixControlExecute;
3659
4113
  get_metrics: typeof getMetricsExecute;
@@ -3691,6 +4145,9 @@ export function createToolHandlers(_runtime: SchedulerRuntime): ToolHandlers {
3691
4145
  get_history: getHistoryExecute,
3692
4146
  get_task_logs: getTaskLogsExecute,
3693
4147
  dry_run: dryRunExecute,
4148
+ pipeline_validate: pipelineValidateExecute,
4149
+ pipeline_apply: pipelineApplyExecute,
4150
+ pipeline_export: pipelineExportExecute,
3694
4151
  manage_workspaces: manageWorkspacesExecute,
3695
4152
  matrix_control: matrixControlExecute,
3696
4153
  get_metrics: getMetricsExecute,
@@ -4030,6 +4487,32 @@ export function createToolSpecs(runtime: SchedulerRuntime): ToolSpec[] {
4030
4487
  "Filter by action, target, actor, time range and limit. Secret values are redacted.",
4031
4488
  execute: handlers.get_audit_log as any,
4032
4489
  },
4490
+ {
4491
+ name: "pipeline_validate",
4492
+ input: pipelineValidateSchema,
4493
+ description:
4494
+ "Проверяет opencode.pipeline.yaml (путь к файлу или исходник): валидирует version, шаги, зависимости, циклы, cron-расписание, matrix, модель, окна запуска и другие инварианты конвейера. Не применяет изменения.",
4495
+ execute: handlers.pipeline_validate as any,
4496
+ },
4497
+ {
4498
+ name: "pipeline_apply",
4499
+ input: pipelineApplySchema,
4500
+ description:
4501
+ "Применяет opencode.pipeline.yaml к текущему набору задач: создаёт новые, обновляет изменённые, пропускает без изменений (идемпотентно). Задачи без маркера pipelineName не трогаются. В режиме dryRun только отчитывает diff.",
4502
+ audit: (args: PipelineApplyArgs) => ({
4503
+ action: "pipeline.apply",
4504
+ targetType: "pipeline",
4505
+ target: args.source ?? args.path ?? "",
4506
+ }),
4507
+ execute: handlers.pipeline_apply as any,
4508
+ },
4509
+ {
4510
+ name: "pipeline_export",
4511
+ input: pipelineExportSchema,
4512
+ description:
4513
+ "Выгружает задачи указанного конвейера (pipelineName) как opencode.pipeline.yaml: шаги, зависимости, matrix, кастомные настройки шага.",
4514
+ execute: handlers.pipeline_export as any,
4515
+ },
4033
4516
  {
4034
4517
  name: "emit_event",
4035
4518
  input: emitEventSchema,
@@ -4155,6 +4638,8 @@ const v2Plugin = Plugin.define({
4155
4638
  sessionMaxRuns,
4156
4639
  runWhenLoggedOff,
4157
4640
  legacyShell,
4641
+ worktree,
4642
+ guards,
4158
4643
  } = input as {
4159
4644
  name: string;
4160
4645
  schedule?: string;
@@ -4186,6 +4671,8 @@ const v2Plugin = Plugin.define({
4186
4671
  sessionMaxRuns?: number;
4187
4672
  runWhenLoggedOff?: boolean;
4188
4673
  legacyShell?: boolean;
4674
+ worktree?: boolean;
4675
+ guards?: TaskGuards;
4189
4676
  };
4190
4677
  let effectiveRunAt: string | undefined;
4191
4678
  if (triggerType === "once") {
@@ -4249,6 +4736,8 @@ const v2Plugin = Plugin.define({
4249
4736
  runWhenLoggedOff === true,
4250
4737
  undefined,
4251
4738
  legacyShell === true,
4739
+ worktree === true,
4740
+ guards,
4252
4741
  );
4253
4742
  const nextRun = computeTaskNextRun({
4254
4743
  schedule: schedule ?? "",
@@ -4380,6 +4869,37 @@ const v2Plugin = Plugin.define({
4380
4869
  return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
4381
4870
  }
4382
4871
  },
4872
+ run_mission: async (input: unknown) => {
4873
+ try {
4874
+ const mission = await runMission(input as MissionSpec);
4875
+ return {
4876
+ success: mission.success,
4877
+ dryRun: mission.dryRun,
4878
+ runId: mission.runId ?? "",
4879
+ status: mission.status,
4880
+ description: mission.description,
4881
+ ...(mission.error ? { error: mission.error } : {}),
4882
+ steps: mission.steps.map((step) => ({
4883
+ stepName: step.stepName,
4884
+ taskType: step.taskType,
4885
+ target: step.target,
4886
+ status: step.status,
4887
+ attempt: step.attempt,
4888
+ ...(step.error ? { error: step.error } : {}),
4889
+ })),
4890
+ };
4891
+ } catch (err: any) {
4892
+ return {
4893
+ success: false,
4894
+ dryRun: false,
4895
+ runId: "",
4896
+ status: "failed",
4897
+ description: "",
4898
+ error: err instanceof Error ? err.message : String(err),
4899
+ steps: [],
4900
+ };
4901
+ }
4902
+ },
4383
4903
  emit_event: async (input: unknown) => {
4384
4904
  const { eventName, payload } = input as {
4385
4905
  eventName?: string;
@@ -4628,6 +5148,29 @@ const v2Plugin = Plugin.define({
4628
5148
  }
4629
5149
  return { success: allSuccess, reports };
4630
5150
  },
5151
+ pipeline_validate: async (input: unknown) => {
5152
+ const { path, source, dryRun } = input as {
5153
+ path?: string;
5154
+ source?: string;
5155
+ dryRun?: boolean;
5156
+ };
5157
+ const result = await pipelineValidateExecute({ path, source, dryRun } as PipelineValidateArgs, {} as Tool.Context);
5158
+ return JSON.parse(result.content as string);
5159
+ },
5160
+ pipeline_apply: async (input: unknown) => {
5161
+ const { path, source, dryRun } = input as {
5162
+ path?: string;
5163
+ source?: string;
5164
+ dryRun?: boolean;
5165
+ };
5166
+ const result = await pipelineApplyExecute({ path, source, dryRun } as PipelineApplyArgs, {} as Tool.Context);
5167
+ return JSON.parse(result.content as string);
5168
+ },
5169
+ pipeline_export: async (input: unknown) => {
5170
+ const { pipeline } = input as { pipeline?: string };
5171
+ const result = await pipelineExportExecute({ pipeline } as PipelineExportArgs, {} as Tool.Context);
5172
+ return JSON.parse(result.content as string);
5173
+ },
4631
5174
  get_matrix_results: async (input: unknown) => {
4632
5175
  const { parentId } = input as { parentId?: string; name?: string };
4633
5176
  const target = (parentId ?? "").trim();
@@ -5025,6 +5568,43 @@ const v2Plugin = Plugin.define({
5025
5568
  });
5026
5569
  return { success: true, ...result };
5027
5570
  },
5571
+ list_dlq: async (input: unknown) => {
5572
+ const source = (input ?? {}) as { status?: string; limit?: number };
5573
+ return listDlq({ status: source.status, limit: source.limit });
5574
+ },
5575
+ retry_dlq: async (input: unknown) => {
5576
+ const source = (input ?? {}) as { id?: string };
5577
+ if (!source.id) return { success: false, error: "id is required" };
5578
+ return retryDlq(source.id);
5579
+ },
5580
+ discard_dlq: async (input: unknown) => {
5581
+ const source = (input ?? {}) as { id?: string; resolution?: string };
5582
+ if (!source.id) return { success: false, error: "id is required" };
5583
+ return discardDlq(source.id, source.resolution);
5584
+ },
5585
+ list_durable_runs: async (input: unknown) => {
5586
+ const source = (input ?? {}) as { filter?: string; limit?: number };
5587
+ return listRunPanel({ filter: source.filter, limit: source.limit });
5588
+ },
5589
+ pause_durable_run: async (input: unknown) => {
5590
+ const source = (input ?? {}) as {
5591
+ runId?: string;
5592
+ stepName?: string;
5593
+ comment?: string;
5594
+ author?: string;
5595
+ };
5596
+ if (!source.runId) return { success: false, error: "runId is required" };
5597
+ return pauseRunPanel(source.runId, {
5598
+ stepName: source.stepName,
5599
+ comment: source.comment,
5600
+ author: source.author,
5601
+ });
5602
+ },
5603
+ resume_durable_run: async (input: unknown) => {
5604
+ const source = (input ?? {}) as { runId?: string };
5605
+ if (!source.runId) return { success: false, error: "runId is required" };
5606
+ return resumeRunPanel(source.runId);
5607
+ },
5028
5608
  get_templates: async () => {
5029
5609
  try {
5030
5610
  return { templates: await loadTemplates() };
@@ -5160,6 +5740,8 @@ const v2Plugin = Plugin.define({
5160
5740
  def.runWhenLoggedOff === true,
5161
5741
  def.paused === true,
5162
5742
  def.legacyShell === true,
5743
+ def.worktree === true,
5744
+ def.guards,
5163
5745
  );
5164
5746
  await saveTaskDefinition(def);
5165
5747
  imported.push(def.name);
@@ -5387,7 +5969,7 @@ export interface TriggerExtras {
5387
5969
  gitPollSeconds?: number;
5388
5970
  }
5389
5971
 
5390
- async function schedulerCreateTask(
5972
+ export async function schedulerCreateTask(
5391
5973
  name: string,
5392
5974
  schedule: string,
5393
5975
  prompt: string,
@@ -5443,6 +6025,10 @@ async function schedulerCreateTask(
5443
6025
  * true возвращает shell задаче, созданной до обновления поведения.
5444
6026
  */
5445
6027
  legacyShell?: boolean,
6028
+ /** W-1: одноразовый git worktree на каждый запуск. */
6029
+ worktree?: boolean,
6030
+ /** W-3: guard-условия перед запуском opencode. */
6031
+ guards?: TaskGuards,
5446
6032
  ): Promise<void> {
5447
6033
  // Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
5448
6034
  // в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
@@ -5475,6 +6061,18 @@ async function schedulerCreateTask(
5475
6061
  // Для отката файлов: при обновлении существующей задачи файлы переиспользуются,
5476
6062
  // удалять их при сбое нельзя — в БД остаётся прежнее определение.
5477
6063
  const definitionExisted = Boolean(getTask(normalizedName));
6064
+ // P1-10: при создании проверяем, что sanitized-имя не занято другой задачей
6065
+ // или её оставшимися файлами. Иначе «my task» и «my-task» делят
6066
+ // wrapper/prompt/lock/log, а вторая задача перезаписывает первую.
6067
+ if (!definitionExisted) {
6068
+ const conflict = findSanitizedNameConflict(
6069
+ normalizedName,
6070
+ listTaskDefinitions().map((def) => def.name),
6071
+ );
6072
+ if (conflict) {
6073
+ throw new Error(sanitizedConflictMessage(normalizedName, conflict));
6074
+ }
6075
+ }
5478
6076
 
5479
6077
  const normalizedModel = model?.trim() || undefined;
5480
6078
  if (normalizedModel) {
@@ -5496,6 +6094,13 @@ async function schedulerCreateTask(
5496
6094
  const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
5497
6095
  // Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
5498
6096
  const normalizedPaused = paused === true ? true : undefined;
6097
+ // W-1: изоляция запуска в одноразовом git worktree.
6098
+ const normalizedWorktree = worktree === true ? true : undefined;
6099
+ // W-3: guard-условия. Ошибка нормализации — явная ошибка создания задачи,
6100
+ // чтобы опечатка в конфигурации не превратилась в молчаливый пропуск.
6101
+ const guardsResult = normalizeTaskGuards(guards);
6102
+ if (!guardsResult.ok) throw new Error(guardsResult.error);
6103
+ const normalizedGuards = guardsResult.guards;
5499
6104
  // Спринт 27: дни недели, политика окна и glob/git-фильтры.
5500
6105
  const normalizeGlobList = (raw?: string[]): string[] | undefined => {
5501
6106
  if (!Array.isArray(raw)) return undefined;
@@ -5710,6 +6315,29 @@ async function schedulerCreateTask(
5710
6315
  if (windowError) {
5711
6316
  throw new Error(t("tool.error.window", { task: name, error: windowError }));
5712
6317
  }
6318
+ // P2-24: cron может быть валидным, но никогда не попадать в окно запуска
6319
+ // (например, daily 09:00 при окне 22:00–06:00). Предупреждаем сразу при
6320
+ // создании: иначе задача молча не выполняется из-за лимита переноса 12 ч.
6321
+ if (normalizedNotBefore || normalizedNotAfter || normalizedActiveDays) {
6322
+ const feasibility = assessCronWindowFeasibility(
6323
+ schedule,
6324
+ {
6325
+ notBefore: normalizedNotBefore,
6326
+ notAfter: normalizedNotAfter,
6327
+ days: normalizedActiveDays,
6328
+ timeZone: normalizedTz || undefined,
6329
+ },
6330
+ normalizedWindowPolicy,
6331
+ );
6332
+ if (!feasibility.feasible) {
6333
+ console.warn(
6334
+ `[scheduler] Задача "${name}": ${t("dryRun.window.unreachable", {
6335
+ cron: schedule,
6336
+ reason: windowFeasibilityReasonText(feasibility.reason),
6337
+ })}`,
6338
+ );
6339
+ }
6340
+ }
5713
6341
  }
5714
6342
  // Спринт 27: окно и дни недели применимы и к событийным триггерам
5715
6343
  // (file/git/mcp-event/once) — проверяем корректность до создания задачи.
@@ -5859,12 +6487,14 @@ async function schedulerCreateTask(
5859
6487
  taskEnvFile,
5860
6488
  effectiveSession,
5861
6489
  effectiveSessionId,
5862
- retryCount,
5863
- retryDelay,
5864
6490
  undefined,
5865
6491
  permissionsConfig,
5866
6492
  policyMeta,
5867
6493
  sessionFile,
6494
+ normalizedWorktree,
6495
+ worktreeHelperPath,
6496
+ normalizedGuards,
6497
+ guardHelperPath,
5868
6498
  );
5869
6499
  } else {
5870
6500
  wrapperPath = await writeBashWrapper({
@@ -5890,6 +6520,10 @@ async function schedulerCreateTask(
5890
6520
  sessionMode: effectiveSession,
5891
6521
  sessionId: effectiveSessionId,
5892
6522
  sessionFile,
6523
+ worktree: normalizedWorktree,
6524
+ worktreeHelper: worktreeHelperPath,
6525
+ guards: normalizedGuards,
6526
+ guardHelper: guardHelperPath,
5893
6527
  ...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
5894
6528
  ? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized, getProfileName()) }
5895
6529
  : {}),
@@ -6036,6 +6670,8 @@ async function schedulerCreateTask(
6036
6670
  allowedTools: normalizedAllowedTools,
6037
6671
  deniedTools: normalizedDeniedTools,
6038
6672
  legacyShell: legacyShell === true ? true : undefined,
6673
+ worktree: normalizedWorktree,
6674
+ guards: normalizedGuards,
6039
6675
  matrix: normalizedMatrix,
6040
6676
  isMatrixParent: normalizedMatrix ? true : undefined,
6041
6677
  matrixParentId,
@@ -6118,6 +6754,8 @@ async function schedulerCreateTask(
6118
6754
  clone.runWhenLoggedOff,
6119
6755
  clone.paused,
6120
6756
  clone.legacyShell,
6757
+ clone.worktree,
6758
+ clone.guards,
6121
6759
  );
6122
6760
  };
6123
6761
 
@@ -6331,6 +6969,8 @@ async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<v
6331
6969
  definition.runWhenLoggedOff,
6332
6970
  paused,
6333
6971
  definition.legacyShell,
6972
+ definition.worktree,
6973
+ definition.guards,
6334
6974
  );
6335
6975
  }
6336
6976