agent-steward 0.0.4 → 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 (190) hide show
  1. package/CHANGELOG.md +134 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +52 -7
  4. package/ROADMAP-STRATEGY.md +21 -18
  5. package/ROADMAP.md +140 -159
  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/execution.d.ts +203 -0
  10. package/dist/core/execution.d.ts.map +1 -0
  11. package/dist/core/execution.js +309 -0
  12. package/dist/core/gate-integrity.d.ts +35 -0
  13. package/dist/core/gate-integrity.d.ts.map +1 -0
  14. package/dist/core/gate-integrity.js +132 -0
  15. package/dist/core/git-trigger.d.ts.map +1 -1
  16. package/dist/core/git-trigger.js +14 -2
  17. package/dist/core/guard-run.d.ts +4 -0
  18. package/dist/core/guard-run.d.ts.map +1 -0
  19. package/dist/core/guard-run.js +101 -0
  20. package/dist/core/guard.d.ts +52 -0
  21. package/dist/core/guard.d.ts.map +1 -0
  22. package/dist/core/guard.js +362 -0
  23. package/dist/core/lock.d.ts +41 -0
  24. package/dist/core/lock.d.ts.map +1 -1
  25. package/dist/core/lock.js +141 -29
  26. package/dist/core/matrix.d.ts.map +1 -1
  27. package/dist/core/matrix.js +75 -15
  28. package/dist/core/mission.d.ts +83 -0
  29. package/dist/core/mission.d.ts.map +1 -0
  30. package/dist/core/mission.js +334 -0
  31. package/dist/core/pipeline-apply.d.ts +38 -0
  32. package/dist/core/pipeline-apply.d.ts.map +1 -0
  33. package/dist/core/pipeline-apply.js +117 -0
  34. package/dist/core/pipeline-io.d.ts +13 -0
  35. package/dist/core/pipeline-io.d.ts.map +1 -0
  36. package/dist/core/pipeline-io.js +64 -0
  37. package/dist/core/pipeline-map.d.ts +46 -0
  38. package/dist/core/pipeline-map.d.ts.map +1 -0
  39. package/dist/core/pipeline-map.js +196 -0
  40. package/dist/core/pipeline-spec.d.ts +109 -0
  41. package/dist/core/pipeline-spec.d.ts.map +1 -0
  42. package/dist/core/pipeline-spec.js +554 -0
  43. package/dist/core/ps-wrapper.d.ts +19 -2
  44. package/dist/core/ps-wrapper.d.ts.map +1 -1
  45. package/dist/core/ps-wrapper.js +250 -62
  46. package/dist/core/record-history.d.ts.map +1 -1
  47. package/dist/core/record-history.js +130 -29
  48. package/dist/core/router/rules.d.ts.map +1 -1
  49. package/dist/core/router/rules.js +6 -0
  50. package/dist/core/scheduler/linux.d.ts +8 -1
  51. package/dist/core/scheduler/linux.d.ts.map +1 -1
  52. package/dist/core/scheduler/linux.js +34 -9
  53. package/dist/core/scheduler/mac.d.ts +44 -2
  54. package/dist/core/scheduler/mac.d.ts.map +1 -1
  55. package/dist/core/scheduler/mac.js +126 -15
  56. package/dist/core/scheduler/windows.d.ts.map +1 -1
  57. package/dist/core/scheduler/windows.js +15 -12
  58. package/dist/core/structured-log.d.ts +7 -1
  59. package/dist/core/structured-log.d.ts.map +1 -1
  60. package/dist/core/worktree-run.d.ts +4 -0
  61. package/dist/core/worktree-run.d.ts.map +1 -0
  62. package/dist/core/worktree-run.js +164 -0
  63. package/dist/core/worktree.d.ts +115 -0
  64. package/dist/core/worktree.d.ts.map +1 -0
  65. package/dist/core/worktree.js +462 -0
  66. package/dist/core/wrappers/bash.d.ts +17 -0
  67. package/dist/core/wrappers/bash.d.ts.map +1 -1
  68. package/dist/core/wrappers/bash.js +175 -24
  69. package/dist/db/capability-repo.d.ts +43 -2
  70. package/dist/db/capability-repo.d.ts.map +1 -1
  71. package/dist/db/capability-repo.js +96 -11
  72. package/dist/db/history-repo.d.ts +38 -5
  73. package/dist/db/history-repo.d.ts.map +1 -1
  74. package/dist/db/history-repo.js +88 -25
  75. package/dist/db/metrics-repo.js +2 -2
  76. package/dist/db/recovery.d.ts.map +1 -1
  77. package/dist/db/recovery.js +5 -4
  78. package/dist/db/run-journal.d.ts +33 -5
  79. package/dist/db/run-journal.d.ts.map +1 -1
  80. package/dist/db/run-journal.js +78 -14
  81. package/dist/db/run-resume.d.ts +5 -0
  82. package/dist/db/run-resume.d.ts.map +1 -1
  83. package/dist/db/run-resume.js +9 -2
  84. package/dist/db/runs-repo.d.ts +19 -2
  85. package/dist/db/runs-repo.d.ts.map +1 -1
  86. package/dist/db/runs-repo.js +22 -6
  87. package/dist/db/schema.d.ts +2 -2
  88. package/dist/db/schema.d.ts.map +1 -1
  89. package/dist/db/schema.js +63 -2
  90. package/dist/history.d.ts +1 -1
  91. package/dist/history.d.ts.map +1 -1
  92. package/dist/i18n.d.ts +5 -0
  93. package/dist/i18n.d.ts.map +1 -1
  94. package/dist/i18n.js +11 -4
  95. package/dist/index.d.ts +136 -2
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +378 -14
  98. package/dist/notifications.d.ts +22 -0
  99. package/dist/notifications.d.ts.map +1 -1
  100. package/dist/notifications.js +36 -8
  101. package/dist/profiles.d.ts.map +1 -1
  102. package/dist/profiles.js +25 -4
  103. package/dist/rpc.d.ts +246 -0
  104. package/dist/rpc.d.ts.map +1 -1
  105. package/dist/rpc.js +117 -0
  106. package/dist/server.d.ts +15 -0
  107. package/dist/server.d.ts.map +1 -1
  108. package/dist/server.js +77 -18
  109. package/dist/settings.d.ts +2 -2
  110. package/dist/settings.d.ts.map +1 -1
  111. package/dist/settings.js +3 -3
  112. package/dist/shared/jobs-view.d.ts +1 -1
  113. package/dist/shared/jobs-view.d.ts.map +1 -1
  114. package/dist/shared/jobs-view.js +2 -0
  115. package/dist/task-transfer.d.ts +16 -0
  116. package/dist/task-transfer.d.ts.map +1 -1
  117. package/dist/task-transfer.js +16 -0
  118. package/docs/ARCHITECTURE.md +281 -65
  119. package/docs/COMPATIBILITY.md +2 -2
  120. package/docs/CONCEPT.md +18 -4
  121. package/docs/CROSS_PLATFORM.ru.md +20 -0
  122. package/docs/CROSS_PLATFORM.zh.md +18 -0
  123. package/docs/EXECUTION-LOOP.md +22 -7
  124. package/docs/FEATURES.md +65 -4
  125. package/docs/FEATURES.zh.md +52 -4
  126. package/docs/MIGRATION.md +2 -2
  127. package/docs/PIPELINE.md +293 -0
  128. package/docs/README.ru.md +42 -3
  129. package/docs/README.zh.md +43 -3
  130. package/docs/SAFETY.md +23 -3
  131. package/gui-experimental.cjs +9 -8
  132. package/locales/en.json +17 -1
  133. package/locales/ru.json +17 -1
  134. package/locales/zh.json +17 -1
  135. package/opencode.pipeline.yaml +35 -0
  136. package/package.json +23 -4
  137. package/scripts/test-home.mjs +83 -0
  138. package/src/cli.ts +412 -0
  139. package/src/core/dry-run.ts +2 -2
  140. package/src/core/execution.ts +538 -0
  141. package/src/core/file-watcher.ts +2 -2
  142. package/src/core/gate-integrity.ts +160 -0
  143. package/src/core/git-trigger.ts +18 -5
  144. package/src/core/guard-run.ts +119 -0
  145. package/src/core/guard.ts +431 -0
  146. package/src/core/lock.ts +178 -37
  147. package/src/core/matrix.ts +95 -50
  148. package/src/core/mission.ts +485 -0
  149. package/src/core/native-notify.ts +1 -1
  150. package/src/core/pipeline-apply.ts +158 -0
  151. package/src/core/pipeline-io.ts +79 -0
  152. package/src/core/pipeline-map.ts +264 -0
  153. package/src/core/pipeline-spec.ts +775 -0
  154. package/src/core/ps-wrapper.ts +263 -63
  155. package/src/core/record-history.ts +164 -77
  156. package/src/core/router/rules.ts +6 -0
  157. package/src/core/schedule-gate.ts +1 -1
  158. package/src/core/scheduler/at-fallback.ts +1 -1
  159. package/src/core/scheduler/linux.ts +40 -11
  160. package/src/core/scheduler/logs.ts +2 -2
  161. package/src/core/scheduler/mac.ts +174 -14
  162. package/src/core/scheduler/registry.ts +2 -2
  163. package/src/core/scheduler/windows.ts +19 -15
  164. package/src/core/secrets.ts +8 -8
  165. package/src/core/structured-log.ts +22 -5
  166. package/src/core/telegram.ts +2 -2
  167. package/src/core/triage-worker.ts +7 -7
  168. package/src/core/triage.ts +2 -2
  169. package/src/core/worktree-run.ts +199 -0
  170. package/src/core/worktree.ts +600 -0
  171. package/src/core/wrappers/bash.ts +190 -23
  172. package/src/db/capability-repo.ts +127 -10
  173. package/src/db/history-repo.ts +129 -22
  174. package/src/db/metrics-repo.ts +2 -2
  175. package/src/db/recovery.ts +5 -4
  176. package/src/db/run-journal.ts +100 -13
  177. package/src/db/run-resume.ts +17 -1
  178. package/src/db/runs-repo.ts +36 -6
  179. package/src/db/schema.ts +65 -2
  180. package/src/gui.tsx +177 -13
  181. package/src/history.ts +1 -1
  182. package/src/i18n.ts +12 -4
  183. package/src/index.ts +524 -4
  184. package/src/notifications.ts +38 -8
  185. package/src/profiles.ts +26 -4
  186. package/src/rpc.ts +128 -0
  187. package/src/server.ts +94 -18
  188. package/src/settings.ts +5 -5
  189. package/src/shared/jobs-view.ts +3 -1
  190. package/src/task-transfer.ts +31 -0
package/dist/index.js CHANGED
@@ -16,14 +16,20 @@ import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
16
16
  import { getTaskLogs } from "./core/scheduler/logs.js";
17
17
  import { findSanitizedNameConflict, sanitizedConflictMessage } from "./core/task-name.js";
18
18
  import { writeBashWrapper } from "./core/wrappers/bash.js";
19
+ import { normalizeTaskGuards } from "./core/guard.js";
19
20
  import { simulatePipeline } from "./core/dry-run.js";
20
21
  import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, findOrphanedMatrixTasks, getMatrixDeletionGuard, matrixCompleteName, planMatrixFamilyDelete, removeMatrixChildren, runMatrix, syncMatrixFamily, } from "./core/matrix.js";
21
22
  import { normalizeWatchPath, validateWatchGlobs } from "./core/watch-paths.js";
22
23
  import { createShutdownGate } from "./core/shutdown.js";
23
24
  import { SchedulerRpc } from "./rpc.js";
25
+ import { loadPipelineFile, parsePipelineYaml, } from "./core/pipeline-io.js";
26
+ import { planPipelineApply, } from "./core/pipeline-apply.js";
27
+ import { tasksToPipelineSpec } from "./core/pipeline-map.js";
28
+ import { stringify as yamlStringify } from "yaml";
24
29
  import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
25
30
  import { defaultNotifications, loadSettings, saveSettings } from "./settings.js";
26
31
  import { resolveLocale, setLocale, t } from "./i18n.js";
32
+ import { runMission } from "./core/mission.js";
27
33
  import { DEFAULT_PERMISSION_POLICY, buildOpencodeConfig, resolvePermissions, } from "./core/permissions.js";
28
34
  import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
29
35
  import { buildAnalytics } from "./core/analytics.js";
@@ -91,6 +97,39 @@ const gatePath = (() => {
91
97
  `${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`);
92
98
  return distPath;
93
99
  })();
100
+ /**
101
+ * W-1: путь к помощнику создания одноразового git worktree
102
+ * (dist/core/worktree-run.js). Обёртка вызывает его перед opencode.
103
+ */
104
+ const worktreeHelperPath = (() => {
105
+ const resolved = require.resolve("./core/worktree-run.js");
106
+ if (!resolved.endsWith(".ts"))
107
+ return resolved;
108
+ const distPath = resolved
109
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
110
+ .replace(/\.ts$/, ".js");
111
+ if (existsSync(distPath))
112
+ return distPath;
113
+ console.warn("[agent-steward] Не найден собранный worktree-run.js: " +
114
+ `${distPath}. Изоляция в git worktree не будет работать. Выполните npm run build.`);
115
+ return distPath;
116
+ })();
117
+ /**
118
+ * W-3: путь к CLI-помощнику guard-условий (dist/core/guard-run.js).
119
+ */
120
+ const guardHelperPath = (() => {
121
+ const resolved = require.resolve("./core/guard-run.js");
122
+ if (!resolved.endsWith(".ts"))
123
+ return resolved;
124
+ const distPath = resolved
125
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
126
+ .replace(/\.ts$/, ".js");
127
+ if (existsSync(distPath))
128
+ return distPath;
129
+ console.warn("[agent-steward] Не найден собранный guard-run.js: " +
130
+ `${distPath}. Guard-условия не будут проверяться. Выполните npm run build.`);
131
+ return distPath;
132
+ })();
94
133
  /** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
95
134
  const scheduler = getSchedulerBackend();
96
135
  /** Per-workspace overrides for matrix clones (Sprint 17). */
@@ -131,6 +170,39 @@ export const matrixSchema = z.object({
131
170
  .optional()
132
171
  .describe("Per-workspace overrides keyed by workspace id. Keys must be present in workspaceIds."),
133
172
  });
173
+ /** W-3: guard-условия задачи. */
174
+ export const guardsSchema = z.object({
175
+ command: z
176
+ .string()
177
+ .max(4000)
178
+ .optional()
179
+ .describe("Shell command evaluated before the run. Exit 0 runs the task; any other code skips it."),
180
+ timeoutSeconds: z
181
+ .number()
182
+ .int()
183
+ .min(1)
184
+ .max(3600)
185
+ .optional()
186
+ .describe("Shell guard timeout in seconds (default 60)."),
187
+ semantic: z
188
+ .object({
189
+ filesExist: z.array(z.string()).max(200).optional().describe("Paths that must exist."),
190
+ filesMissing: z.array(z.string()).max(200).optional().describe("Paths that must not exist."),
191
+ branch: z.string().max(200).optional().describe("Glob for the current git branch, e.g. feature/*."),
192
+ changedPaths: z
193
+ .array(z.string())
194
+ .max(200)
195
+ .optional()
196
+ .describe("Globs of changed paths; at least one must match."),
197
+ changedSince: z
198
+ .string()
199
+ .max(100)
200
+ .optional()
201
+ .describe("Git ref to diff against (default HEAD~1)."),
202
+ })
203
+ .optional()
204
+ .describe("Semantic pre-run checks inside the working directory."),
205
+ }).describe("W-3: guard conditions. If a check fails, the run is skipped before opencode starts.");
134
206
  /** Zod-схема аргументов schedule_task */
135
207
  export const scheduleTaskSchema = z.object({
136
208
  name: z
@@ -294,6 +366,13 @@ export const scheduleTaskSchema = z.object({
294
366
  .boolean()
295
367
  .optional()
296
368
  .describe("Windows only: run the task even when no user is logged on (/ru SYSTEM). The task runs in session 0 without the user's profile, mapped drives or saved credentials, so tasks that need the user's environment may fail. Creating such a task usually requires an elevated shell. Default false: interactive only — the task runs only while the user is logged on."),
369
+ worktree: z
370
+ .boolean()
371
+ .optional()
372
+ .describe("W-1: run each tick in a one-off git worktree created from HEAD of workingDirectory. Keeps fan-out runs isolated from each other and from the main checkout. Requires a git repository; creation failure fails the run closed. Default false."),
373
+ guards: guardsSchema
374
+ .optional()
375
+ .describe("W-3: pre-run guard conditions. If a semantic check or shell command fails, the run is skipped (no opencode, no side effects). Combined with worktree: checks run inside the fresh worktree."),
297
376
  matrix: matrixSchema
298
377
  .optional()
299
378
  .describe("Matrix fan-out: the task becomes a template that is expanded into clones, one per workspace. The parent never runs itself. Cannot be combined with workspaceId."),
@@ -486,6 +565,13 @@ export const updateTaskSchema = z.object({
486
565
  .boolean()
487
566
  .optional()
488
567
  .describe("Transitional flag (release 1.6): re-enable shell under the hybrid policy for this task."),
568
+ worktree: z
569
+ .boolean()
570
+ .optional()
571
+ .describe("W-1: run each tick in a one-off git worktree created from HEAD of workingDirectory. Default false."),
572
+ guards: guardsSchema
573
+ .optional()
574
+ .describe("W-3: pre-run guard conditions; a failed check skips the run."),
489
575
  matrix: matrixSchema
490
576
  .nullable()
491
577
  .optional()
@@ -545,6 +631,30 @@ const dryRunSchema = z.object({
545
631
  .optional()
546
632
  .describe("Task name to simulate. When omitted, every task is simulated (pipeline dry run, nothing is executed)."),
547
633
  });
634
+ /** pipeline_validate — проверить опencode.pipeline.yaml (путь или исходник). */
635
+ export const pipelineValidateSchema = z.object({
636
+ path: z.string().optional().describe("Путь к файлу opencode.pipeline.yaml."),
637
+ source: z.string().optional().describe("Исходное содержимое YAML."),
638
+ dryRun: z
639
+ .boolean()
640
+ .optional()
641
+ .default(true)
642
+ .describe("Если true — только валидация без применения (по умолчанию true)."),
643
+ });
644
+ /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
645
+ export const pipelineApplySchema = z.object({
646
+ path: z.string().optional().describe("Путь к файлу opencode.pipeline.yaml."),
647
+ source: z.string().optional().describe("Исходное содержимое YAML."),
648
+ dryRun: z
649
+ .boolean()
650
+ .optional()
651
+ .default(false)
652
+ .describe("Если true — прогон diff'а без применения изменений (по умолчанию false)."),
653
+ });
654
+ /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
655
+ export const pipelineExportSchema = z.object({
656
+ pipeline: z.string().describe("Имя конвейера (pipelineName)."),
657
+ });
548
658
  const manageWorkspacesSchema = z.object({
549
659
  action: z
550
660
  .enum(["list", "add", "update", "delete"])
@@ -652,7 +762,7 @@ export const manageSettingsSchema = z.object({
652
762
  locale: z
653
763
  .enum(["auto", "ru", "en", "zh"])
654
764
  .optional()
655
- .describe("Interface language: auto (follow OpenCode), ru (default), en or zh. Applies without restart."),
765
+ .describe("Interface language: auto (default, follows OpenCode), ru, en or zh. Applies without restart."),
656
766
  winterMode: z
657
767
  .boolean()
658
768
  .optional()
@@ -919,7 +1029,7 @@ function computeTaskNextRun(def, options = {}) {
919
1029
  }
920
1030
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
921
1031
  const scheduleTaskExecute = wrapExecute(async (args) => {
922
- const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, runWhenLoggedOff, legacyShell, } = args;
1032
+ const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, runWhenLoggedOff, legacyShell, worktree, guards, } = args;
923
1033
  let effectiveRunAt;
924
1034
  if ((triggerType ?? "cron") === "once") {
925
1035
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
@@ -946,7 +1056,7 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
946
1056
  gitPollSeconds,
947
1057
  },
948
1058
  // Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
949
- runWhenLoggedOff === true, undefined, legacyShell === true);
1059
+ runWhenLoggedOff === true, undefined, legacyShell === true, worktree === true, guards);
950
1060
  }
951
1061
  catch (err) {
952
1062
  return {
@@ -1010,6 +1120,8 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
1010
1120
  workspaceId: workspace?.id ?? null,
1011
1121
  workspaceName: workspace?.name ?? null,
1012
1122
  matrix: matrix ?? null,
1123
+ worktree: worktree === true,
1124
+ guards: guards ?? null,
1013
1125
  },
1014
1126
  }),
1015
1127
  };
@@ -1072,7 +1184,7 @@ async function cancelMatrixRun(name) {
1072
1184
  }
1073
1185
  // Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
1074
1186
  try {
1075
- await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell);
1187
+ await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell, clone.worktree, clone.guards);
1076
1188
  }
1077
1189
  catch (err) {
1078
1190
  warnings.push(t("tool.matrix.recreateFailed", {
@@ -1499,7 +1611,7 @@ async function updateTaskFromInput(input) {
1499
1611
  await schedulerCreateTask(name, schedule ?? "", prompt, input.timeoutSeconds ?? previous.timeoutSeconds, clearableString(input.workingDirectory, previous.workingDirectory), input.retryCount ?? previous.retryCount, input.retryDelay ?? previous.retryDelay, clearableString(input.qualityGate, previous.qualityGate), clearableString(input.nextTaskOnSuccess, previous.nextTaskOnSuccess), clearableString(input.nextTaskOnError, previous.nextTaskOnError), triggerType, clearableString(input.watchPath, previous.watchPath), clearableList(input.dependsOn, previous.dependsOn), nextModel, input.priority ?? previous.priority, clearableString(input.beforeScript, previous.beforeScript), clearableString(input.afterScript, previous.afterScript), input.mcpEvent ?? previous.mcpEvent, clearableString(input.workspaceId, previous.workspaceId), clearableList(input.allowedTools, previous.allowedTools), clearableList(input.deniedTools, previous.deniedTools), matrixNext, undefined,
1500
1612
  // Если задача была матрицей — синхронизируем клонов, а не
1501
1613
  // пересоздаём их с нуля (Спринт 17).
1502
- matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras, input.runWhenLoggedOff ?? previous.runWhenLoggedOff, wasPaused, input.legacyShell ?? previous.legacyShell);
1614
+ matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras, input.runWhenLoggedOff ?? previous.runWhenLoggedOff, wasPaused, input.legacyShell ?? previous.legacyShell, input.worktree ?? previous.worktree, input.guards ?? previous.guards);
1503
1615
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
1504
1616
  if (matrixWas && !matrixNext) {
1505
1617
  await removeMatrixChildrenFromScheduler(name);
@@ -1886,6 +1998,153 @@ const dryRunExecute = wrapExecute(async (args) => {
1886
1998
  }),
1887
1999
  };
1888
2000
  });
2001
+ /** pipeline_validate — проверить opencode.pipeline.yaml (путь или исходник). */
2002
+ const pipelineValidateExecute = wrapExecute(async (args) => {
2003
+ const path = args.path ?? args.source ? undefined : undefined;
2004
+ if (args.path === undefined && args.source === undefined) {
2005
+ return {
2006
+ content: JSON.stringify({
2007
+ success: false,
2008
+ pipeline: null,
2009
+ errors: ["Укажите path к файлу или source с содержимым YAML"],
2010
+ warnings: [],
2011
+ }),
2012
+ };
2013
+ }
2014
+ const parsed = args.source !== undefined
2015
+ ? validatePipelineSpecFromSource(args.source)
2016
+ : await loadPipelineFile(args.path);
2017
+ if (!parsed.ok) {
2018
+ return {
2019
+ content: JSON.stringify({
2020
+ success: false,
2021
+ pipeline: null,
2022
+ errors: parsed.errors,
2023
+ warnings: parsed.warnings,
2024
+ }),
2025
+ };
2026
+ }
2027
+ const spec = parsed.spec;
2028
+ return {
2029
+ content: JSON.stringify({
2030
+ success: true,
2031
+ pipeline: spec.name,
2032
+ steps: spec.steps.length,
2033
+ errors: [],
2034
+ warnings: parsed.warnings,
2035
+ }),
2036
+ };
2037
+ });
2038
+ function validatePipelineSpecFromSource(source) {
2039
+ const parsed = parsePipelineYaml(source);
2040
+ return parsed;
2041
+ }
2042
+ /** pipeline_apply — применить opencode.pipeline.yaml к текущему набору задач. */
2043
+ const pipelineApplyExecute = wrapExecute(async (args) => {
2044
+ const dryRun = args.dryRun !== false;
2045
+ const parsed = args.source !== undefined
2046
+ ? validatePipelineSpecFromSource(args.source)
2047
+ : await loadPipelineFile(args.path);
2048
+ if (!parsed.ok) {
2049
+ return {
2050
+ content: JSON.stringify({
2051
+ success: false,
2052
+ pipeline: null,
2053
+ errors: parsed.errors,
2054
+ warnings: parsed.warnings,
2055
+ }),
2056
+ };
2057
+ }
2058
+ const spec = parsed.spec;
2059
+ const existing = await listTaskDefinitions();
2060
+ const plan = planPipelineApply(spec, existing, {
2061
+ resolveWorkspaceId: (nameOrId) => {
2062
+ const ws = getWorkspace(nameOrId);
2063
+ return ws ? ws.id : undefined;
2064
+ },
2065
+ });
2066
+ let created = 0;
2067
+ let updated = 0;
2068
+ const errors = [];
2069
+ if (!dryRun) {
2070
+ for (const task of plan.creates) {
2071
+ try {
2072
+ await schedulerCreateTask(task.name, task.schedule, task.prompt, task.timeoutSeconds, task.workingDirectory ?? task.workdir ?? undefined, task.retryCount, task.retryDelay, task.qualityGate, task.nextTaskOnSuccess, task.nextTaskOnError, task.triggerType ?? "cron", task.watchPath, task.dependsOn, task.model, task.priority, task.beforeScript, task.afterScript, task.mcpEvent, task.workspaceId, task.allowedTools, task.deniedTools, task.matrix, task.matrixParentId, "create", task.timezone, task.notBefore, task.notAfter, task.pausedUntil, task.runAt, task.session, task.sessionId, task.sessionMaxRuns, {
2073
+ activeDays: task.activeDays,
2074
+ windowPolicy: task.windowPolicy,
2075
+ watchGlobs: task.watchGlobs ?? [],
2076
+ watchIgnore: task.watchIgnore ?? [],
2077
+ gitBranch: task.gitBranch,
2078
+ gitPaths: task.gitPaths,
2079
+ gitIgnore: task.gitIgnore,
2080
+ gitPollSeconds: task.gitPollSeconds,
2081
+ }, task.runWhenLoggedOff ?? false, task.paused ?? false, task.legacyShell ?? false, task.worktree ?? false, task.guards);
2082
+ await saveTaskDefinition(task);
2083
+ created++;
2084
+ }
2085
+ catch (err) {
2086
+ errors.push(`create ${task.name}: ${err instanceof Error ? err.message : String(err)}`);
2087
+ }
2088
+ }
2089
+ for (const item of plan.updates) {
2090
+ try {
2091
+ await schedulerCreateTask(item.task.name, item.task.schedule, item.task.prompt, item.task.timeoutSeconds, item.task.workingDirectory ?? item.task.workdir ?? undefined, item.task.retryCount, item.task.retryDelay, item.task.qualityGate, item.task.nextTaskOnSuccess, item.task.nextTaskOnError, item.task.triggerType ?? "cron", item.task.watchPath, item.task.dependsOn, item.task.model, item.task.priority, item.task.beforeScript, item.task.afterScript, item.task.mcpEvent, item.task.workspaceId, item.task.allowedTools, item.task.deniedTools, item.task.matrix, item.task.matrixParentId, "sync", item.task.timezone, item.task.notBefore, item.task.notAfter, item.task.pausedUntil, item.task.runAt, item.task.session, item.task.sessionId, item.task.sessionMaxRuns, {
2092
+ activeDays: item.task.activeDays,
2093
+ windowPolicy: item.task.windowPolicy,
2094
+ watchGlobs: item.task.watchGlobs ?? [],
2095
+ watchIgnore: item.task.watchIgnore ?? [],
2096
+ gitBranch: item.task.gitBranch,
2097
+ gitPaths: item.task.gitPaths,
2098
+ gitIgnore: item.task.gitIgnore,
2099
+ gitPollSeconds: item.task.gitPollSeconds,
2100
+ }, item.task.runWhenLoggedOff ?? false, item.task.paused ?? false, item.task.legacyShell ?? false, item.task.worktree ?? false, item.task.guards);
2101
+ await saveTaskDefinition(item.task);
2102
+ updated++;
2103
+ }
2104
+ catch (err) {
2105
+ errors.push(`update ${item.task.name}: ${err instanceof Error ? err.message : String(err)}`);
2106
+ }
2107
+ }
2108
+ refreshTriggers();
2109
+ }
2110
+ return {
2111
+ content: JSON.stringify({
2112
+ success: errors.length === 0,
2113
+ pipeline: spec.name,
2114
+ dryRun,
2115
+ created,
2116
+ updated,
2117
+ unchanged: plan.unchanged.length,
2118
+ stale: plan.stale.length,
2119
+ warnings: [...plan.warnings, ...errors],
2120
+ errors,
2121
+ }),
2122
+ };
2123
+ });
2124
+ /** pipeline_export — выгрузить задачи конвейера как opencode.pipeline.yaml. */
2125
+ const pipelineExportExecute = wrapExecute(async (args) => {
2126
+ const allTasks = await listTaskDefinitions();
2127
+ const result = tasksToPipelineSpec(allTasks, args.pipeline);
2128
+ if (!result.spec) {
2129
+ return {
2130
+ content: JSON.stringify({
2131
+ success: false,
2132
+ error: `Конвейер "${args.pipeline}" не найден (не найдены задачи с pipelineName=${args.pipeline} и pipelineStepId).`,
2133
+ warnings: result.warnings,
2134
+ }),
2135
+ };
2136
+ }
2137
+ const yamlText = yamlStringify(result.spec, { lineWidth: 0 });
2138
+ return {
2139
+ content: JSON.stringify({
2140
+ success: true,
2141
+ pipeline: args.pipeline,
2142
+ steps: result.spec.steps.length,
2143
+ yaml: yamlText,
2144
+ warnings: result.warnings,
2145
+ }),
2146
+ };
2147
+ });
1889
2148
  /**
1890
2149
  * Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
1891
2150
  * Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
@@ -2399,7 +2658,16 @@ const transferTasksExecute = wrapExecute(async (args) => {
2399
2658
  const errors = [...parsed.errors];
2400
2659
  for (const def of parsed.tasks) {
2401
2660
  try {
2402
- await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt);
2661
+ await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt, def.session, def.sessionId, def.sessionMaxRuns, {
2662
+ activeDays: def.activeDays,
2663
+ windowPolicy: def.windowPolicy,
2664
+ watchGlobs: def.watchGlobs,
2665
+ watchIgnore: def.watchIgnore,
2666
+ gitBranch: def.gitBranch,
2667
+ gitPaths: def.gitPaths,
2668
+ gitIgnore: def.gitIgnore,
2669
+ gitPollSeconds: def.gitPollSeconds,
2670
+ }, def.runWhenLoggedOff, def.paused, def.legacyShell, def.worktree, def.guards);
2403
2671
  await saveTaskDefinition(def);
2404
2672
  imported.push(def.name);
2405
2673
  }
@@ -2572,6 +2840,11 @@ const RPC_AUDIT_RULES = {
2572
2840
  update_task: { action: "task.update", targetType: "task", target: (i) => i.name ?? "" },
2573
2841
  delete_task: { action: "task.delete", targetType: "task", target: (i) => i.name ?? "" },
2574
2842
  run_task: { action: "task.run", targetType: "task", target: (i) => i.name ?? "" },
2843
+ run_mission: {
2844
+ action: "mission.run",
2845
+ targetType: "mission",
2846
+ target: (i) => i.taskName ?? "ad-hoc",
2847
+ },
2575
2848
  pause_task: { action: "task.pause", targetType: "task", target: (i) => i.name ?? "" },
2576
2849
  resume_task: { action: "task.resume", targetType: "task", target: (i) => i.name ?? "" },
2577
2850
  cancel_matrix: { action: "matrix.cancel", targetType: "matrix", target: (i) => i.name ?? "" },
@@ -2936,6 +3209,9 @@ export function createToolHandlers(_runtime) {
2936
3209
  get_history: getHistoryExecute,
2937
3210
  get_task_logs: getTaskLogsExecute,
2938
3211
  dry_run: dryRunExecute,
3212
+ pipeline_validate: pipelineValidateExecute,
3213
+ pipeline_apply: pipelineApplyExecute,
3214
+ pipeline_export: pipelineExportExecute,
2939
3215
  manage_workspaces: manageWorkspacesExecute,
2940
3216
  matrix_control: matrixControlExecute,
2941
3217
  get_metrics: getMetricsExecute,
@@ -3202,6 +3478,29 @@ export function createToolSpecs(runtime) {
3202
3478
  "Filter by action, target, actor, time range and limit. Secret values are redacted.",
3203
3479
  execute: handlers.get_audit_log,
3204
3480
  },
3481
+ {
3482
+ name: "pipeline_validate",
3483
+ input: pipelineValidateSchema,
3484
+ description: "Проверяет opencode.pipeline.yaml (путь к файлу или исходник): валидирует version, шаги, зависимости, циклы, cron-расписание, matrix, модель, окна запуска и другие инварианты конвейера. Не применяет изменения.",
3485
+ execute: handlers.pipeline_validate,
3486
+ },
3487
+ {
3488
+ name: "pipeline_apply",
3489
+ input: pipelineApplySchema,
3490
+ description: "Применяет opencode.pipeline.yaml к текущему набору задач: создаёт новые, обновляет изменённые, пропускает без изменений (идемпотентно). Задачи без маркера pipelineName не трогаются. В режиме dryRun только отчитывает diff.",
3491
+ audit: (args) => ({
3492
+ action: "pipeline.apply",
3493
+ targetType: "pipeline",
3494
+ target: args.source ?? args.path ?? "",
3495
+ }),
3496
+ execute: handlers.pipeline_apply,
3497
+ },
3498
+ {
3499
+ name: "pipeline_export",
3500
+ input: pipelineExportSchema,
3501
+ description: "Выгружает задачи указанного конвейера (pipelineName) как opencode.pipeline.yaml: шаги, зависимости, matrix, кастомные настройки шага.",
3502
+ execute: handlers.pipeline_export,
3503
+ },
3205
3504
  {
3206
3505
  name: "emit_event",
3207
3506
  input: emitEventSchema,
@@ -3286,7 +3585,7 @@ const v2Plugin = Plugin.define({
3286
3585
  },
3287
3586
  create_task: async (input) => {
3288
3587
  console.log("[agent-steward] create_task input:", input);
3289
- const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, runWhenLoggedOff, legacyShell, } = input;
3588
+ const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, runWhenLoggedOff, legacyShell, worktree, guards, } = input;
3290
3589
  let effectiveRunAt;
3291
3590
  if (triggerType === "once") {
3292
3591
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
@@ -3309,7 +3608,7 @@ const v2Plugin = Plugin.define({
3309
3608
  }
3310
3609
  const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
3311
3610
  try {
3312
- await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, undefined, runWhenLoggedOff === true, undefined, legacyShell === true);
3611
+ await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, undefined, runWhenLoggedOff === true, undefined, legacyShell === true, worktree === true, guards);
3313
3612
  const nextRun = computeTaskNextRun({
3314
3613
  schedule: schedule ?? "",
3315
3614
  triggerType: triggerType ?? "cron",
@@ -3436,6 +3735,38 @@ const v2Plugin = Plugin.define({
3436
3735
  return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
3437
3736
  }
3438
3737
  },
3738
+ run_mission: async (input) => {
3739
+ try {
3740
+ const mission = await runMission(input);
3741
+ return {
3742
+ success: mission.success,
3743
+ dryRun: mission.dryRun,
3744
+ runId: mission.runId ?? "",
3745
+ status: mission.status,
3746
+ description: mission.description,
3747
+ ...(mission.error ? { error: mission.error } : {}),
3748
+ steps: mission.steps.map((step) => ({
3749
+ stepName: step.stepName,
3750
+ taskType: step.taskType,
3751
+ target: step.target,
3752
+ status: step.status,
3753
+ attempt: step.attempt,
3754
+ ...(step.error ? { error: step.error } : {}),
3755
+ })),
3756
+ };
3757
+ }
3758
+ catch (err) {
3759
+ return {
3760
+ success: false,
3761
+ dryRun: false,
3762
+ runId: "",
3763
+ status: "failed",
3764
+ description: "",
3765
+ error: err instanceof Error ? err.message : String(err),
3766
+ steps: [],
3767
+ };
3768
+ }
3769
+ },
3439
3770
  emit_event: async (input) => {
3440
3771
  const { eventName, payload } = input;
3441
3772
  const normalized = eventName?.trim();
@@ -3650,6 +3981,21 @@ const v2Plugin = Plugin.define({
3650
3981
  }
3651
3982
  return { success: allSuccess, reports };
3652
3983
  },
3984
+ pipeline_validate: async (input) => {
3985
+ const { path, source, dryRun } = input;
3986
+ const result = await pipelineValidateExecute({ path, source, dryRun }, {});
3987
+ return JSON.parse(result.content);
3988
+ },
3989
+ pipeline_apply: async (input) => {
3990
+ const { path, source, dryRun } = input;
3991
+ const result = await pipelineApplyExecute({ path, source, dryRun }, {});
3992
+ return JSON.parse(result.content);
3993
+ },
3994
+ pipeline_export: async (input) => {
3995
+ const { pipeline } = input;
3996
+ const result = await pipelineExportExecute({ pipeline }, {});
3997
+ return JSON.parse(result.content);
3998
+ },
3653
3999
  get_matrix_results: async (input) => {
3654
4000
  const { parentId } = input;
3655
4001
  const target = (parentId ?? "").trim();
@@ -4138,7 +4484,7 @@ const v2Plugin = Plugin.define({
4138
4484
  gitPaths: def.gitPaths,
4139
4485
  gitIgnore: def.gitIgnore,
4140
4486
  gitPollSeconds: def.gitPollSeconds,
4141
- }, def.runWhenLoggedOff === true, def.paused === true, def.legacyShell === true);
4487
+ }, def.runWhenLoggedOff === true, def.paused === true, def.legacyShell === true, def.worktree === true, def.guards);
4142
4488
  await saveTaskDefinition(def);
4143
4489
  imported.push(def.name);
4144
4490
  }
@@ -4308,7 +4654,7 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
4308
4654
  }
4309
4655
  return extra;
4310
4656
  }
4311
- async function schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, matrixParentId,
4657
+ export async function schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, matrixParentId,
4312
4658
  /** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
4313
4659
  matrixMode = "create",
4314
4660
  /** IANA-зона задачи (Спринт 19). Не системная зона → poll-режим шлюза. */
@@ -4340,7 +4686,11 @@ paused,
4340
4686
  * Спринт 32 / релиз 1.6: переходный флаг для гибридной политики.
4341
4687
  * true возвращает shell задаче, созданной до обновления поведения.
4342
4688
  */
4343
- legacyShell) {
4689
+ legacyShell,
4690
+ /** W-1: одноразовый git worktree на каждый запуск. */
4691
+ worktree,
4692
+ /** W-3: guard-условия перед запуском opencode. */
4693
+ guards) {
4344
4694
  // Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
4345
4695
  // в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
4346
4696
  // schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
@@ -4396,6 +4746,14 @@ legacyShell) {
4396
4746
  const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
4397
4747
  // Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
4398
4748
  const normalizedPaused = paused === true ? true : undefined;
4749
+ // W-1: изоляция запуска в одноразовом git worktree.
4750
+ const normalizedWorktree = worktree === true ? true : undefined;
4751
+ // W-3: guard-условия. Ошибка нормализации — явная ошибка создания задачи,
4752
+ // чтобы опечатка в конфигурации не превратилась в молчаливый пропуск.
4753
+ const guardsResult = normalizeTaskGuards(guards);
4754
+ if (!guardsResult.ok)
4755
+ throw new Error(guardsResult.error);
4756
+ const normalizedGuards = guardsResult.guards;
4399
4757
  // Спринт 27: дни недели, политика окна и glob/git-фильтры.
4400
4758
  const normalizeGlobList = (raw) => {
4401
4759
  if (!Array.isArray(raw))
@@ -4687,7 +5045,7 @@ legacyShell) {
4687
5045
  try {
4688
5046
  if (scheduler.platform === "win32") {
4689
5047
  await ensureWrapper();
4690
- wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile, effectiveSession, effectiveSessionId, retryCount, retryDelay, undefined, permissionsConfig, policyMeta, sessionFile);
5048
+ wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile, effectiveSession, effectiveSessionId, undefined, permissionsConfig, policyMeta, sessionFile, normalizedWorktree, worktreeHelperPath, normalizedGuards, guardHelperPath);
4691
5049
  }
4692
5050
  else {
4693
5051
  wrapperPath = await writeBashWrapper({
@@ -4713,6 +5071,10 @@ legacyShell) {
4713
5071
  sessionMode: effectiveSession,
4714
5072
  sessionId: effectiveSessionId,
4715
5073
  sessionFile,
5074
+ worktree: normalizedWorktree,
5075
+ worktreeHelper: worktreeHelperPath,
5076
+ guards: normalizedGuards,
5077
+ guardHelper: guardHelperPath,
4716
5078
  ...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
4717
5079
  ? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized, getProfileName()) }
4718
5080
  : {}),
@@ -4840,6 +5202,8 @@ legacyShell) {
4840
5202
  allowedTools: normalizedAllowedTools,
4841
5203
  deniedTools: normalizedDeniedTools,
4842
5204
  legacyShell: legacyShell === true ? true : undefined,
5205
+ worktree: normalizedWorktree,
5206
+ guards: normalizedGuards,
4843
5207
  matrix: normalizedMatrix,
4844
5208
  isMatrixParent: normalizedMatrix ? true : undefined,
4845
5209
  matrixParentId,
@@ -4871,7 +5235,7 @@ legacyShell) {
4871
5235
  // с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
4872
5236
  if (normalizedMatrix) {
4873
5237
  const createClone = async (clone) => {
4874
- await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell);
5238
+ await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused, clone.legacyShell, clone.worktree, clone.guards);
4875
5239
  };
4876
5240
  const removeChild = async (child) => {
4877
5241
  try {
@@ -5022,7 +5386,7 @@ async function recreateTaskFromDefinition(definition) {
5022
5386
  gitPaths: definition.gitPaths,
5023
5387
  gitIgnore: definition.gitIgnore,
5024
5388
  gitPollSeconds: definition.gitPollSeconds,
5025
- }, definition.runWhenLoggedOff, paused, definition.legacyShell);
5389
+ }, definition.runWhenLoggedOff, paused, definition.legacyShell, definition.worktree, definition.guards);
5026
5390
  }
5027
5391
  /**
5028
5392
  * Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
@@ -114,6 +114,28 @@ export interface DedupRecord {
114
114
  lastAt: string;
115
115
  windowMinutes: number;
116
116
  }
117
+ /**
118
+ * Простой токенизатор: слова, цифры, нижний регистр.
119
+ *
120
+ * B14: CJK-блоки больше не вырезаются. Иероглифы не разделены пробелами,
121
+ * поэтому слово режется на перекрывающиеся биграммы («任务失败» → «任务»,
122
+ * «务失», «失败»); одиночный иероглиф остаётся униграммой. Это даёт
123
+ * ненулевой вектор для `zh`/`ja`/`ko` и работает без словарей и
124
+ * `Intl.Segmenter`, одинаково на всех платформах.
125
+ */
126
+ export declare function tokenize(text: string): string[];
127
+ /**
128
+ * Вектор сообщения: feature hashing в фиксированную размерность.
129
+ *
130
+ * Раньше длина вектора равнялась числу уникальных слов, а индекс — порядку
131
+ * первого появления. Такие векторы нельзя сравнивать позиционно: один и тот
132
+ * же текст с другим порядком слов давал сходство < 1, а векторы разной длины
133
+ * вообще пропускались. Теперь каждый токен детерминированно проецируется
134
+ * в [0, EMBEDDING_DIMENSION), поэтому косинус корректен для любых двух текстов.
135
+ * Вес — 1 + log(tf), L2-нормализация; знак из старшего бита хеша снижает
136
+ * влияние коллизий.
137
+ */
138
+ export declare function textToVector(text: string): number[];
117
139
  export declare function notifyTaskCompletion(taskName: string, status: NotificationStatus, durationMs: number, error?: string | null, tokens?: number | null, costUsd?: number | null, options?: NotifyTaskOptions): Promise<void>;
118
140
  /**
119
141
  * Уведомляет о завершении матрицы (Спринт 20).