opencode-windows-scheduler 1.4.0 → 1.5.1

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 (95) hide show
  1. package/CHANGELOG.md +61 -1
  2. package/LICENSE +21 -21
  3. package/README.md +26 -4
  4. package/ROADMAP-STRATEGY.md +43 -24
  5. package/ROADMAP.md +549 -31
  6. package/dist/core/dry-run.d.ts +41 -0
  7. package/dist/core/dry-run.d.ts.map +1 -1
  8. package/dist/core/dry-run.js +165 -16
  9. package/dist/core/file-watcher.d.ts.map +1 -1
  10. package/dist/core/file-watcher.js +53 -10
  11. package/dist/core/git-trigger.d.ts +80 -0
  12. package/dist/core/git-trigger.d.ts.map +1 -0
  13. package/dist/core/git-trigger.js +294 -0
  14. package/dist/core/glob.d.ts +38 -0
  15. package/dist/core/glob.d.ts.map +1 -0
  16. package/dist/core/glob.js +233 -0
  17. package/dist/core/matrix.d.ts.map +1 -1
  18. package/dist/core/matrix.js +48 -22
  19. package/dist/core/ps-wrapper.d.ts.map +1 -1
  20. package/dist/core/ps-wrapper.js +7 -0
  21. package/dist/core/schedule-gate.js +55 -30
  22. package/dist/core/schedule-v2.d.ts +29 -1
  23. package/dist/core/schedule-v2.d.ts.map +1 -1
  24. package/dist/core/schedule-v2.js +107 -17
  25. package/dist/core/scheduler/types.d.ts +7 -1
  26. package/dist/core/scheduler/types.d.ts.map +1 -1
  27. package/dist/core/scheduler/windows.d.ts +6 -2
  28. package/dist/core/scheduler/windows.d.ts.map +1 -1
  29. package/dist/core/scheduler/windows.js +25 -10
  30. package/dist/core/telegram.d.ts.map +1 -1
  31. package/dist/core/telegram.js +13 -10
  32. package/dist/core/wrappers/bash.d.ts.map +1 -1
  33. package/dist/core/wrappers/bash.js +4 -0
  34. package/dist/db/git-state-repo.d.ts +16 -0
  35. package/dist/db/git-state-repo.d.ts.map +1 -0
  36. package/dist/db/git-state-repo.js +38 -0
  37. package/dist/db/schema.d.ts +1 -1
  38. package/dist/db/schema.d.ts.map +1 -1
  39. package/dist/db/schema.js +8 -0
  40. package/dist/i18n.d.ts +52 -0
  41. package/dist/i18n.d.ts.map +1 -0
  42. package/dist/i18n.js +292 -0
  43. package/dist/index.d.ts +50 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +1020 -197
  46. package/dist/notifications.d.ts.map +1 -1
  47. package/dist/notifications.js +74 -40
  48. package/dist/rpc.d.ts +238 -2
  49. package/dist/rpc.d.ts.map +1 -1
  50. package/dist/rpc.js +79 -2
  51. package/dist/server.d.ts.map +1 -1
  52. package/dist/server.js +89 -48
  53. package/dist/settings.d.ts +3 -0
  54. package/dist/settings.d.ts.map +1 -1
  55. package/dist/settings.js +20 -8
  56. package/dist/task-transfer.d.ts +43 -3
  57. package/dist/task-transfer.d.ts.map +1 -1
  58. package/dist/task-transfer.js +94 -6
  59. package/dist/templates.d.ts +1 -1
  60. package/dist/templates.d.ts.map +1 -1
  61. package/dist/types.d.ts +11 -0
  62. package/dist/types.d.ts.map +1 -1
  63. package/dist/types.js +32 -0
  64. package/docs/ARCHITECTURE.md +37 -1
  65. package/docs/FEATURES.md +70 -0
  66. package/docs/README.ru.md +19 -3
  67. package/gui-experimental.cjs +9 -4
  68. package/locales/en.json +695 -0
  69. package/locales/ru.json +695 -0
  70. package/package.json +9 -3
  71. package/scripts/test-locale.mjs +44 -0
  72. package/src/core/dry-run.ts +244 -19
  73. package/src/core/file-watcher.ts +65 -10
  74. package/src/core/git-trigger.ts +373 -0
  75. package/src/core/glob.ts +226 -0
  76. package/src/core/matrix.ts +52 -26
  77. package/src/core/ps-wrapper.ts +7 -0
  78. package/src/core/schedule-gate.ts +67 -33
  79. package/src/core/schedule-v2.ts +152 -17
  80. package/src/core/scheduler/types.ts +7 -1
  81. package/src/core/scheduler/windows.ts +25 -10
  82. package/src/core/telegram.ts +16 -10
  83. package/src/core/wrappers/bash.ts +4 -0
  84. package/src/db/git-state-repo.ts +62 -0
  85. package/src/db/schema.ts +8 -0
  86. package/src/gui.tsx +772 -456
  87. package/src/i18n.ts +339 -0
  88. package/src/index.ts +1274 -212
  89. package/src/notifications.ts +83 -42
  90. package/src/rpc.ts +79 -2
  91. package/src/server.ts +89 -48
  92. package/src/settings.ts +38 -10
  93. package/src/task-transfer.ts +148 -5
  94. package/src/templates.ts +1 -1
  95. package/src/types.ts +37 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-windows-scheduler",
3
- "version": "1.4.0",
3
+ "version": "1.5.1",
4
4
  "description": "OpenCode v2 plugin for scheduling and orchestrating AI agent jobs: cron, one-shot runs, DAG pipelines, matrix builds, quality gates, SQLite history, metrics and a local web dashboard. Windows, macOS and Linux. Free and open source (MIT).",
5
5
  "license": "MIT",
6
6
  "author": "opencode-windows-scheduler contributors",
@@ -48,6 +48,7 @@
48
48
  "index.js",
49
49
  "gui-experimental.cjs",
50
50
  "skills",
51
+ "locales",
51
52
  "scripts",
52
53
  "docs",
53
54
  "README.md",
@@ -69,7 +70,7 @@
69
70
  "demo": "node scripts/demo-dashboard.mjs",
70
71
  "prepare": "npm run build",
71
72
  "prepublishOnly": "npm run build && npm run build:gui",
72
- "test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-v3.mjs && node test-secrets.mjs && node test-audit.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs",
73
+ "test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-v3.mjs && node test-secrets.mjs && node test-audit.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs && node test-glob.mjs && node test-git-trigger.mjs && node test-window-v3.mjs && node test-i18n.mjs",
73
74
  "test:sqlite": "node test-sqlite.mjs",
74
75
  "test:crash": "node test-crash-recovery.mjs",
75
76
  "test:workspaces": "node test-workspaces.mjs",
@@ -98,7 +99,12 @@
98
99
  "test:dashboard": "node test-dashboard.mjs",
99
100
  "test:dashboard-dag": "node test-dashboard-dag.mjs",
100
101
  "test:dashboard-json": "node test-dashboard-json.mjs",
101
- "test:docs": "node test-docs.mjs"
102
+ "test:docs": "node test-docs.mjs",
103
+ "test:glob": "node test-glob.mjs",
104
+ "test:git-trigger": "node test-git-trigger.mjs",
105
+ "test:window-v3": "node test-window-v3.mjs",
106
+ "test:i18n": "node test-i18n.mjs",
107
+ "test:en": "node scripts/test-locale.mjs en"
102
108
  },
103
109
  "dependencies": {
104
110
  "@opencode/plugin": "^2.2.7",
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Прогоняет тот же набор сюит, что `npm test`, с заданной локалью.
3
+ *
4
+ * Локаль задаётся переменной `OPENCODE_SCHEDULER_LOCALE`, которую читает
5
+ * `src/i18n.ts` при загрузке: так один и тот же код проверяется в ru и en
6
+ * без правки settings.json.
7
+ *
8
+ * Запуск: node scripts/test-locale.mjs en
9
+ */
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { spawnSync } from "node:child_process";
13
+ import { fileURLToPath } from "node:url";
14
+
15
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
16
+ const locale = process.argv[2] ?? "en";
17
+
18
+ if (locale !== "ru" && locale !== "en") {
19
+ console.error(`Неизвестная локаль: ${locale}. Ожидается ru или en.`);
20
+ process.exit(2);
21
+ }
22
+
23
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
24
+ const suites = pkg.scripts.test
25
+ .split("&&")
26
+ .map((part) => part.trim().replace(/^node\s+/, ""))
27
+ .filter(Boolean);
28
+
29
+ const failed = [];
30
+ for (const suite of suites) {
31
+ const result = spawnSync(process.execPath, [suite], {
32
+ cwd: root,
33
+ env: { ...process.env, OPENCODE_SCHEDULER_LOCALE: locale },
34
+ stdio: "inherit",
35
+ });
36
+ if (result.status !== 0) failed.push(suite);
37
+ }
38
+
39
+ if (failed.length > 0) {
40
+ console.error(`\n${locale}: провалено ${failed.length} из ${suites.length}: ${failed.join(", ")}`);
41
+ process.exit(1);
42
+ }
43
+
44
+ console.log(`\n${locale}: все ${suites.length} сюит зелёные.`);
@@ -10,7 +10,9 @@ import { loadTaskDefinitions } from "../task-transfer.js";
10
10
  import { getHistory } from "../db/history-repo.js";
11
11
  import { getWorkspace } from "../workspaces.js";
12
12
  import { expandMatrixTask } from "./matrix.js";
13
- import { nextRun } from "./schedule-v2.js";
13
+ import { nextRun, activeWindowState } from "./schedule-v2.js";
14
+ import { checkGitTrigger } from "./git-trigger.js";
15
+ import { t } from "../i18n.js";
14
16
  import type { TaskDefinition } from "../task-transfer.js";
15
17
 
16
18
  export interface DryRunRoleScoped {
@@ -18,6 +20,36 @@ export interface DryRunRoleScoped {
18
20
  denied?: string[];
19
21
  }
20
22
 
23
+ /**
24
+ * Детали триггера (Спринт 27): чем задача запускается и не будет ли запуск
25
+ * пропущен из-за окна/дней недели. Для git-триггера — состояние репозитория.
26
+ */
27
+ export interface DryRunTriggerDetails {
28
+ type: "manual" | "cron" | "file" | "git" | "mcp-event" | "once";
29
+ /** Человекочитаемое объяснение условия запуска. */
30
+ explanation: string;
31
+ /** Состояние окна запуска и разрешённых дней недели (если заданы). */
32
+ activeWindow?: {
33
+ active: boolean;
34
+ reason?: string;
35
+ nextOpenAt: string | null;
36
+ };
37
+ /** Состояние git-триггера на момент dry-run. */
38
+ git?: {
39
+ branch: string | null;
40
+ head: string | null;
41
+ lastCommit: string | null;
42
+ changedFiles: string[];
43
+ matched: string[];
44
+ };
45
+ /** Настройки файлового триггера. */
46
+ file?: {
47
+ watchPath: string | null;
48
+ globs: string[];
49
+ ignore: string[];
50
+ };
51
+ }
52
+
21
53
  export interface DryRunTaskItem {
22
54
  name: string;
23
55
  order: number;
@@ -38,6 +70,16 @@ export interface DryRunTaskItem {
38
70
  session?: string | null;
39
71
  /** Идентификатор переиспользуемой сессии (только для session=reuse). */
40
72
  sessionId?: string | null;
73
+ /**
74
+ * Windows-режим входа (Спринт 27.5.4): false — задача интерактивная и идёт
75
+ * только при активном входе пользователя (Interactive only); true — запуск
76
+ * без входа через `/ru SYSTEM` (session 0, без профиля пользователя).
77
+ * На Linux/macOS поле всегда false: cron работает без входа, launchd-агент —
78
+ * только при входе.
79
+ */
80
+ runWhenLoggedOff?: boolean;
81
+ /** Человекочитаемое пояснение к режиму входа (для отчёта dry-run). */
82
+ logonMode?: string | null;
41
83
  /**
42
84
  * Эффективное расписание cron-задачи (Спринт 19): пояс, окно запуска и
43
85
  * ближайшие срабатывания с учётом часового пояса. Позволяет проверить
@@ -51,6 +93,8 @@ export interface DryRunTaskItem {
51
93
  pausedUntil: string | null;
52
94
  nextRuns: string[];
53
95
  };
96
+ /** Детали триггера и причина возможного пропуска (Спринт 27). */
97
+ triggerDetails?: DryRunTriggerDetails;
54
98
  }
55
99
 
56
100
  export interface DryRunTotals {
@@ -73,12 +117,177 @@ const ESTIMATE_SAMPLE = 10;
73
117
  /** Средняя цена за 1K токенов (должна совпадать с dashboards/server.ts). */
74
118
  export const ESTIMATED_COST_PER_1K_TOKENS_USD = 0.003;
75
119
 
76
- /** Опасные паттерны, о которых обязательно предупреждаем. */
77
- const DANGEROUS_PATTERNS: Array<{ test: RegExp; message: string }> = [
78
- { test: /rm\s+-rf\s+\/(?:\s|$)/, message: "возможна рекурсивная очистка корня файловой системы (`rm -rf /`)" },
79
- { test: /git\s+push\s+.*--force(?:\s|$)/, message: "принудительный push в git (`git push --force`)" },
120
+ /** Опасные паттерны, о которых обязательно предупреждаем (ключи каталога). */
121
+ const DANGEROUS_PATTERNS: Array<{ test: RegExp; messageKey: string }> = [
122
+ { test: /rm\s+-rf\s+\/(?:\s|$)/, messageKey: "dryRun.danger.rmRoot" },
123
+ { test: /git\s+push\s+.*--force(?:\s|$)/, messageKey: "dryRun.danger.forcePush" },
80
124
  ];
81
125
 
126
+ /**
127
+ * Свойства для описания триггера задачи в dry-run (Спринт 27).
128
+ */
129
+ interface DescribeTriggerOptions {
130
+ /** Задание задачи (может содержать новые поля Спринта 27). */
131
+ def: TaskDefinition;
132
+ /** Эффективная рабочая директория задачи. */
133
+ cwd: string;
134
+ /** Вычисляемый тип триггера для поля `trigger`. */
135
+ triggerType: string;
136
+ /** Куда накапливать предупреждения (префикс [task] добавится в цикле). */
137
+ warnings: string[];
138
+ }
139
+
140
+ /**
141
+ * Описывает триггер задачи: что запускает задачу, не будет ли запуск
142
+ * пропущен из-за окна/дней недели, и (для git) состояние репозитория.
143
+ * Не имеет побочных эффектов (для git используется persist: false).
144
+ */
145
+ async function describeTrigger(opts: DescribeTriggerOptions): Promise<DryRunTriggerDetails> {
146
+ const { def, cwd, triggerType, warnings } = opts;
147
+ const policy: "skip" | "postpone" | "run" = def.windowPolicy ?? "postpone";
148
+
149
+ const base: DryRunTriggerDetails = {
150
+ type: triggerType as DryRunTriggerDetails["type"],
151
+ explanation: "",
152
+ };
153
+
154
+ const hasWindow = Boolean((def.notBefore ?? "").trim() || (def.notAfter ?? "").trim());
155
+ const hasDays = Array.isArray(def.activeDays) && def.activeDays.length > 0;
156
+
157
+ switch (triggerType) {
158
+ case "git": {
159
+ try {
160
+ const result = await checkGitTrigger(
161
+ {
162
+ name: def.name,
163
+ cwd,
164
+ branch: def.gitBranch ?? undefined,
165
+ paths: def.gitPaths ?? undefined,
166
+ ignore: def.gitIgnore ?? undefined,
167
+ },
168
+ { persist: false }
169
+ );
170
+ base.git = {
171
+ branch: result.branch ?? null,
172
+ head: result.head ?? null,
173
+ lastCommit: result.from ?? null,
174
+ changedFiles: result.files,
175
+ matched: result.matched,
176
+ };
177
+ base.explanation = result.message;
178
+
179
+ if (result.status === "no-repo") {
180
+ warnings.push(t("dryRun.git.notRepo"));
181
+ } else if (result.status === "branch-mismatch") {
182
+ warnings.push(
183
+ t("dryRun.git.branchMismatch", { branch: def.gitBranch ?? "" })
184
+ );
185
+ }
186
+ } catch (err: any) {
187
+ base.explanation = t("dryRun.git.checkError", {
188
+ error: err instanceof Error ? err.message : String(err),
189
+ });
190
+ warnings.push(base.explanation);
191
+ }
192
+ break;
193
+ }
194
+
195
+ case "file": {
196
+ base.file = {
197
+ watchPath: def.watchPath ?? null,
198
+ globs: Array.isArray(def.watchGlobs) ? def.watchGlobs : [],
199
+ ignore: Array.isArray(def.watchIgnore) ? def.watchIgnore : [],
200
+ };
201
+ const parts: string[] = [];
202
+ if (def.watchPath) parts.push(`«${def.watchPath}»`);
203
+ if (def.watchGlobs?.length)
204
+ parts.push(t("dryRun.file.globs", { count: def.watchGlobs.length }));
205
+ if (def.watchIgnore?.length)
206
+ parts.push(t("dryRun.file.ignore", { count: def.watchIgnore.length }));
207
+ base.explanation =
208
+ parts.length > 0
209
+ ? t("dryRun.file.trigger", { parts: parts.join("; ") })
210
+ : t("dryRun.file.any");
211
+ break;
212
+ }
213
+
214
+ case "mcp-event": {
215
+ const ev = def.mcpEvent;
216
+ base.explanation = ev && ev.event
217
+ ? t("dryRun.mcp.event", {
218
+ server: ev.server,
219
+ event: ev.event,
220
+ filter: ev.filter
221
+ ? t("dryRun.mcp.filter", { filter: ev.filter })
222
+ : "",
223
+ })
224
+ : t("dryRun.mcp.missing");
225
+ break;
226
+ }
227
+
228
+ case "cron": {
229
+ base.explanation = def.timezone
230
+ ? t("dryRun.cronTimezone", {
231
+ schedule: def.schedule,
232
+ timezone: def.timezone,
233
+ })
234
+ : t("dryRun.cron", { schedule: def.schedule });
235
+ break;
236
+ }
237
+
238
+ case "once": {
239
+ base.explanation = def.runAt
240
+ ? t("dryRun.once.at", { runAt: def.runAt })
241
+ : t("dryRun.once");
242
+ break;
243
+ }
244
+
245
+ case "manual":
246
+ default: {
247
+ base.explanation = t("dryRun.manual");
248
+ break;
249
+ }
250
+ }
251
+
252
+ // Окно запуска и дни недели (если заданы).
253
+ if (hasWindow || hasDays) {
254
+ const state = activeWindowState(new Date(), {
255
+ notBefore: def.notBefore ?? undefined,
256
+ notAfter: def.notAfter ?? undefined,
257
+ days: def.activeDays ?? undefined,
258
+ timeZone: def.timezone ?? undefined,
259
+ });
260
+ base.activeWindow = {
261
+ active: state.active,
262
+ ...(state.reason ? { reason: state.reason } : {}),
263
+ nextOpenAt: state.nextOpenAt ? state.nextOpenAt.toISOString() : null,
264
+ };
265
+
266
+ if (!state.active && policy !== "run") {
267
+ const reason = state.reason ?? t("dryRun.window.outside");
268
+ if (policy === "skip") {
269
+ warnings.push(t("dryRun.window.skip", { reason }));
270
+ } else {
271
+ // postpone — переносим на ближайшее открытие.
272
+ const iso = base.activeWindow.nextOpenAt ?? null;
273
+ warnings.push(
274
+ iso
275
+ ? t("dryRun.window.postpone", { reason, nextOpenAt: iso })
276
+ : t("dryRun.window.noOpening", { reason })
277
+ );
278
+ }
279
+ } else if (!state.active && policy === "run") {
280
+ warnings.push(
281
+ t("dryRun.window.run", {
282
+ reason: state.reason ?? t("dryRun.window.outside"),
283
+ })
284
+ );
285
+ }
286
+ }
287
+
288
+ return base;
289
+ }
290
+
82
291
  /**
83
292
  * Симулирует конвейер задачи: сама задача + все зависимости (dependsOn)
84
293
  * в топологическом порядке. Возвращает отчёт без реального запуска.
@@ -90,7 +299,7 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
90
299
  const rootLower = taskName.trim().toLowerCase();
91
300
  const root = allDefs.find((d) => d.name.toLowerCase() === rootLower);
92
301
  if (!root) {
93
- throw new Error(`Задача "${taskName}" не найдена.`);
302
+ throw new Error(t("dryRun.taskNotFound", { task: taskName }));
94
303
  }
95
304
 
96
305
  // Собираем подграф зависимостей рекурсивно, обнаруживая циклы.
@@ -102,7 +311,7 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
102
311
  const collect = (lowerName: string): TaskDefinition | undefined => {
103
312
  if (visiting.has(lowerName)) {
104
313
  const list = warningsPerTask.get(lowerName) ?? [];
105
- list.push(`Обнаружена циклическая зависимость вокруг задачи "${lowerName}" — конвейер разорван на этом узле.`);
314
+ list.push(t("dryRun.cycle", { task: lowerName }));
106
315
  warningsPerTask.set(lowerName, list);
107
316
  return undefined;
108
317
  }
@@ -111,7 +320,7 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
111
320
  const def = byLower.get(lowerName);
112
321
  if (!def) {
113
322
  const list = warningsPerTask.get(lowerName) ?? [];
114
- list.push(`Зависимость "${lowerName}" не найдена среди задач — узел пропущен.`);
323
+ list.push(t("dryRun.dependencyMissing", { task: lowerName }));
115
324
  warningsPerTask.set(lowerName, list);
116
325
  return undefined;
117
326
  }
@@ -173,15 +382,15 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
173
382
  try {
174
383
  const clones = expandMatrixTask(def);
175
384
  warnings.push(
176
- `[${def.name}] Родитель матрицы не выполняется сам — показаны ${clones.length} клон(а/ов) по workspace.`
385
+ t("dryRun.matrix.parent", { name: def.name, count: clones.length })
177
386
  );
178
387
  for (const clone of clones) units.push({ def: clone, matrixParent: def.name });
179
388
  } catch (err: any) {
180
389
  const list = warningsPerTask.get(def.name.toLowerCase()) ?? [];
181
390
  list.push(
182
- `Матрица не может быть развёрнута: ${
183
- err instanceof Error ? err.message : String(err)
184
- }`
391
+ t("dryRun.matrix.expandError", {
392
+ error: err instanceof Error ? err.message : String(err),
393
+ })
185
394
  );
186
395
  warningsPerTask.set(def.name.toLowerCase(), list);
187
396
  warnings.push(`[${def.name}] ${list[list.length - 1]}`);
@@ -208,15 +417,15 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
208
417
  const workspace = def.workspaceId ? getWorkspace(def.workspaceId) : undefined;
209
418
  const cwd = workspace?.path || def.workingDirectory || def.workdir || "";
210
419
  if (!cwd) {
211
- taskWarnings.push("Рабочая директория не задана явно — будет использована папка текущего проекта.");
420
+ taskWarnings.push(t("dryRun.cwdImplicit"));
212
421
  } else {
213
422
  try {
214
423
  const stat = fs.statSync(cwd);
215
424
  if (!stat.isDirectory()) {
216
- taskWarnings.push(`Путь "${cwd}" существует, но не является директорией.`);
425
+ taskWarnings.push(t("dryRun.cwdNotDir", { path: cwd }));
217
426
  }
218
427
  } catch {
219
- taskWarnings.push(`Рабочая директория "${cwd}" не существует на диске.`);
428
+ taskWarnings.push(t("dryRun.cwdMissing", { path: cwd }));
220
429
  }
221
430
  }
222
431
 
@@ -230,6 +439,14 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
230
439
  ? "manual"
231
440
  : "dag";
232
441
 
442
+ // Детали триггера (Спринт 27): состояние окна/дней недели, git-статус.
443
+ const triggerDetails = await describeTrigger({
444
+ def,
445
+ cwd,
446
+ triggerType,
447
+ warnings: taskWarnings,
448
+ });
449
+
233
450
  // Команда, которую выполнит обёртка.
234
451
  const modelArg = def.model ? ` --model ${def.model}` : "";
235
452
  const promptPreview = (def.prompt ?? "").replace(/\s+/g, " ").trim();
@@ -241,7 +458,7 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
241
458
  let estimatedCostUsd: number | null = null;
242
459
  let estimatedTokens: number | null = null;
243
460
  if (records.length === 0) {
244
- taskWarnings.push("Нет успешных запусков в истории — оценка длительности/токенов/стоимости недоступна.");
461
+ taskWarnings.push(t("dryRun.noHistory"));
245
462
  } else {
246
463
  const sample = records.slice(0, ESTIMATE_SAMPLE);
247
464
  const avg = (pick: (r: (typeof sample)[number]) => number | null | undefined) => {
@@ -261,9 +478,11 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
261
478
  .filter((s): s is string => typeof s === "string")
262
479
  .join("\n")
263
480
  .toLowerCase();
264
- for (const { test, message } of DANGEROUS_PATTERNS) {
481
+ for (const { test, messageKey } of DANGEROUS_PATTERNS) {
265
482
  if (test.test(scanned)) {
266
- taskWarnings.push(`Опасный паттерн: ${message}.`);
483
+ taskWarnings.push(
484
+ t("dryRun.dangerPattern", { message: t(messageKey) })
485
+ );
267
486
  }
268
487
  }
269
488
 
@@ -299,7 +518,9 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
299
518
  cursor = next;
300
519
  }
301
520
  } catch {
302
- taskWarnings.push(`Не удалось разобрать cron "${def.schedule}" для расчёта ближайших запусков.`);
521
+ taskWarnings.push(
522
+ t("dryRun.cronParseError", { schedule: def.schedule })
523
+ );
303
524
  }
304
525
  scheduleDetails = {
305
526
  cron: def.schedule,
@@ -317,6 +538,9 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
317
538
  trigger,
318
539
  session: def.session ?? "new",
319
540
  sessionId: def.session === "reuse" ? def.sessionId ?? null : null,
541
+ // Спринт 27.5.4: показываем режим входа до регистрации в ОС.
542
+ runWhenLoggedOff: def.runWhenLoggedOff === true,
543
+ logonMode: def.runWhenLoggedOff === true ? "background" : "interactive",
320
544
  cwd,
321
545
  command,
322
546
  workspace: workspace ? { name: workspace.name, path: workspace.path } : undefined,
@@ -329,6 +553,7 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
329
553
  estimatedTokens: estimatedTokens != null ? Math.round(estimatedTokens) : null,
330
554
  ...(matrixParent ? { matrixParent } : {}),
331
555
  ...(scheduleDetails ? { scheduleDetails } : {}),
556
+ ...(triggerDetails ? { triggerDetails } : {}),
332
557
  });
333
558
 
334
559
  if (taskWarnings.length > 0) {
@@ -1,5 +1,6 @@
1
1
  import { watch, type FSWatcher } from "chokidar";
2
2
  import { loadTaskDefinitions } from "../task-transfer.js";
3
+ import { filterPaths, relativeTo } from "./glob.js";
3
4
 
4
5
  /**
5
6
  * Задержка между последним изменением файла и запуском задачи.
@@ -18,6 +19,9 @@ interface WatchedTask {
18
19
  name: string;
19
20
  /** Нормализованный путь, который отслеживаем. */
20
21
  path: string;
22
+ /** Спринт 27: glob-маски и ignore-список (пусто — любое изменение). */
23
+ globs: string[];
24
+ ignore: string[];
21
25
  watcher: FSWatcher;
22
26
  /** Таймер дебаунса (одна задача = один отложенный запуск). */
23
27
  timer: NodeJS.Timeout | null;
@@ -57,15 +61,30 @@ export class FileWatchManager {
57
61
  typeof d.watchPath === "string" &&
58
62
  d.watchPath.trim().length > 0
59
63
  )
60
- .map((d) => ({ name: d.name.trim(), path: d.watchPath!.trim() }))
64
+ .map((d) => ({
65
+ name: d.name.trim(),
66
+ path: d.watchPath!.trim(),
67
+ globs: Array.isArray(d.watchGlobs)
68
+ ? d.watchGlobs.filter((g): g is string => typeof g === "string" && g.trim().length > 0)
69
+ : [],
70
+ ignore: Array.isArray(d.watchIgnore)
71
+ ? d.watchIgnore.filter((g): g is string => typeof g === "string" && g.trim().length > 0)
72
+ : [],
73
+ }))
61
74
  .filter((d) => d.name.length > 0);
62
75
 
63
76
  const wantedKeys = new Set(wanted.map((d) => d.name.toLowerCase()));
64
77
 
65
- // Убираем watcher'ы для задач, которых больше нет или у которых сменился путь.
78
+ // Убираем watcher'ы для задач, которых больше нет или у которых сменился
79
+ // путь/маски (Спринт 27).
66
80
  for (const [key, entry] of Array.from(this.entries.entries())) {
67
81
  const target = wanted.find((d) => d.name.toLowerCase() === key);
68
- if (!target || target.path !== entry.path) {
82
+ if (
83
+ !target ||
84
+ target.path !== entry.path ||
85
+ target.globs.join("\u0000") !== entry.globs.join("\u0000") ||
86
+ target.ignore.join("\u0000") !== entry.ignore.join("\u0000")
87
+ ) {
69
88
  await this.remove(key);
70
89
  }
71
90
  }
@@ -74,7 +93,7 @@ export class FileWatchManager {
74
93
  for (const item of wanted) {
75
94
  const key = item.name.toLowerCase();
76
95
  if (this.entries.has(key) || !wantedKeys.has(key)) continue;
77
- this.add(item.name, item.path);
96
+ this.add(item.name, item.path, item.globs, item.ignore);
78
97
  }
79
98
 
80
99
  return this.entries.size;
@@ -88,14 +107,22 @@ export class FileWatchManager {
88
107
  }
89
108
  }
90
109
 
91
- private add(name: string, watchPath: string): void {
110
+ private add(
111
+ name: string,
112
+ watchPath: string,
113
+ globs: string[] = [],
114
+ ignore: string[] = []
115
+ ): void {
116
+ // Спринт 27: маски с "**" требуют рекурсивного обхода директории.
117
+ const needsRecursive = globs.some((g) => g.includes("**"));
92
118
  let watcher: FSWatcher;
93
119
  try {
94
120
  watcher = watch(watchPath, {
95
121
  // Не считаем уже существующий файл «изменением» при старте.
96
122
  ignoreInitial: true,
97
- // Следим за одним файлом/папкой, без рекурсии в глубину.
98
- depth: 0,
123
+ // Следим за одним файлом/папкой, без рекурсии в глубину, если маски
124
+ // этого не требуют.
125
+ depth: needsRecursive ? undefined : 0,
99
126
  // Файлы могут быть большими: дождёмся, пока запись успокоится.
100
127
  awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 },
101
128
  ignorePermissionErrors: true,
@@ -109,10 +136,32 @@ export class FileWatchManager {
109
136
  return;
110
137
  }
111
138
 
112
- const entry: WatchedTask = { name, path: watchPath, watcher, timer: null };
139
+ const entry: WatchedTask = {
140
+ name,
141
+ path: watchPath,
142
+ globs,
143
+ ignore,
144
+ watcher,
145
+ timer: null,
146
+ };
147
+
148
+ /** Спринт 27: маски применяются к пути относительно watchPath. */
149
+ const accepts = (changedPath: string): boolean => {
150
+ if (globs.length === 0 && ignore.length === 0) return true;
151
+ if (globs.length === 0) {
152
+ const rel = relativeTo(watchPath, changedPath) ?? changedPath;
153
+ return filterPaths([rel], undefined, ignore).length > 0;
154
+ }
155
+ const rel = relativeTo(watchPath, changedPath);
156
+ const candidates = rel ? [rel, changedPath] : [changedPath];
157
+ return candidates.some(
158
+ (candidate) => filterPaths([candidate], globs, ignore).length > 0
159
+ );
160
+ };
113
161
 
114
- watcher.on("change", (changedPath: string) => {
162
+ const onChange = (changedPath: string) => {
115
163
  if (this.stopped) return;
164
+ if (!accepts(changedPath)) return;
116
165
  if (entry.timer) clearTimeout(entry.timer);
117
166
  entry.timer = setTimeout(() => {
118
167
  entry.timer = null;
@@ -138,7 +187,13 @@ export class FileWatchManager {
138
187
  }, this.debounceMs);
139
188
  // Таймер не должен удерживать процесс, если хост завершается.
140
189
  if (typeof entry.timer.unref === "function") entry.timer.unref();
141
- });
190
+ };
191
+
192
+ // Спринт 27: переименование/удаление файла тоже считается изменением —
193
+ // иначе mac/win-редакторы, пишущие через rename, «пропадали» бы.
194
+ watcher.on("change", onChange);
195
+ watcher.on("add", onChange);
196
+ watcher.on("unlink", onChange);
142
197
 
143
198
  watcher.on("error", (err) => {
144
199
  console.error(