opencode-windows-scheduler 1.3.0 → 1.5.0

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 (85) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/README.md +11 -5
  3. package/ROADMAP-STRATEGY.md +45 -26
  4. package/ROADMAP.md +279 -35
  5. package/dist/core/audit.d.ts +68 -0
  6. package/dist/core/audit.d.ts.map +1 -0
  7. package/dist/core/audit.js +206 -0
  8. package/dist/core/dry-run.d.ts +31 -0
  9. package/dist/core/dry-run.d.ts.map +1 -1
  10. package/dist/core/dry-run.js +129 -1
  11. package/dist/core/file-watcher.d.ts.map +1 -1
  12. package/dist/core/file-watcher.js +53 -10
  13. package/dist/core/git-trigger.d.ts +80 -0
  14. package/dist/core/git-trigger.d.ts.map +1 -0
  15. package/dist/core/git-trigger.js +288 -0
  16. package/dist/core/glob.d.ts +38 -0
  17. package/dist/core/glob.d.ts.map +1 -0
  18. package/dist/core/glob.js +233 -0
  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 +81 -3
  25. package/dist/core/scheduler/types.d.ts +1 -1
  26. package/dist/core/scheduler/types.d.ts.map +1 -1
  27. package/dist/core/secrets.d.ts +57 -0
  28. package/dist/core/secrets.d.ts.map +1 -0
  29. package/dist/core/secrets.js +331 -0
  30. package/dist/core/structured-log.d.ts.map +1 -1
  31. package/dist/core/structured-log.js +9 -0
  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 +23 -0
  40. package/dist/index.d.ts +68 -4
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +589 -45
  43. package/dist/rpc.d.ts +623 -0
  44. package/dist/rpc.d.ts.map +1 -1
  45. package/dist/rpc.js +219 -0
  46. package/dist/server.d.ts.map +1 -1
  47. package/dist/server.js +67 -0
  48. package/dist/settings.d.ts +16 -0
  49. package/dist/settings.d.ts.map +1 -1
  50. package/dist/settings.js +29 -0
  51. package/dist/task-transfer.d.ts +30 -3
  52. package/dist/task-transfer.d.ts.map +1 -1
  53. package/dist/task-transfer.js +83 -6
  54. package/dist/templates.d.ts +1 -1
  55. package/dist/templates.d.ts.map +1 -1
  56. package/dist/workspaces.d.ts +8 -2
  57. package/dist/workspaces.d.ts.map +1 -1
  58. package/dist/workspaces.js +21 -4
  59. package/docs/ARCHITECTURE.md +14 -5
  60. package/docs/FEATURES.md +80 -1
  61. package/docs/README.ru.md +15 -5
  62. package/gui-experimental.cjs +9 -4
  63. package/package.json +8 -3
  64. package/src/core/audit.ts +291 -0
  65. package/src/core/dry-run.ts +188 -1
  66. package/src/core/file-watcher.ts +65 -10
  67. package/src/core/git-trigger.ts +367 -0
  68. package/src/core/glob.ts +226 -0
  69. package/src/core/ps-wrapper.ts +7 -0
  70. package/src/core/schedule-gate.ts +67 -33
  71. package/src/core/schedule-v2.ts +108 -3
  72. package/src/core/scheduler/types.ts +1 -1
  73. package/src/core/secrets.ts +385 -0
  74. package/src/core/structured-log.ts +9 -0
  75. package/src/core/wrappers/bash.ts +4 -0
  76. package/src/db/git-state-repo.ts +62 -0
  77. package/src/db/schema.ts +23 -0
  78. package/src/gui.tsx +548 -4
  79. package/src/index.ts +790 -47
  80. package/src/rpc.ts +230 -0
  81. package/src/server.ts +67 -0
  82. package/src/settings.ts +51 -0
  83. package/src/task-transfer.ts +124 -5
  84. package/src/templates.ts +1 -1
  85. package/src/workspaces.ts +22 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-windows-scheduler",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
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",
@@ -69,7 +69,7 @@
69
69
  "demo": "node scripts/demo-dashboard.mjs",
70
70
  "prepare": "npm run build",
71
71
  "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-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",
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 && node test-glob.mjs && node test-git-trigger.mjs && node test-window-v3.mjs",
73
73
  "test:sqlite": "node test-sqlite.mjs",
74
74
  "test:crash": "node test-crash-recovery.mjs",
75
75
  "test:workspaces": "node test-workspaces.mjs",
@@ -83,6 +83,8 @@
83
83
  "test:schedule-v2": "node test-schedule-v2.mjs",
84
84
  "test:notifications-v2": "node test-notifications-v2.mjs",
85
85
  "test:notifications-v3": "node test-notifications-v3.mjs",
86
+ "test:secrets": "node test-secrets.mjs",
87
+ "test:audit": "node test-audit.mjs",
86
88
  "test:profiles": "node test-profiles.mjs",
87
89
  "test:env": "node test-env.mjs",
88
90
  "test:agent": "node test-agent-tools.mjs",
@@ -96,7 +98,10 @@
96
98
  "test:dashboard": "node test-dashboard.mjs",
97
99
  "test:dashboard-dag": "node test-dashboard-dag.mjs",
98
100
  "test:dashboard-json": "node test-dashboard-json.mjs",
99
- "test:docs": "node test-docs.mjs"
101
+ "test:docs": "node test-docs.mjs",
102
+ "test:glob": "node test-glob.mjs",
103
+ "test:git-trigger": "node test-git-trigger.mjs",
104
+ "test:window-v3": "node test-window-v3.mjs"
100
105
  },
101
106
  "dependencies": {
102
107
  "@opencode/plugin": "^2.2.7",
@@ -0,0 +1,291 @@
1
+ import { getDb } from "../db/index.js";
2
+ import { redactSecretsInText } from "./secrets.js";
3
+
4
+ /**
5
+ * Журнал аудита мутаций (Спринт 26).
6
+ *
7
+ * Фиксирует кто, когда и через какой интерфейс создал / изменил / запустил /
8
+ * удалил задачу или настройки. Записи лежат в SQLite рядом с историей, поэтому
9
+ * аудит не зависит от файловых логов и переживает перезапуск. Любая ошибка
10
+ * записи проглатывается: аудит не должен ломать основную операцию.
11
+ */
12
+
13
+ export type AuditActor = "mcp" | "gui" | "http" | "system" | string;
14
+
15
+ export interface AuditEntryInput {
16
+ action: string;
17
+ targetType?: string | null;
18
+ target?: string | null;
19
+ actor: AuditActor;
20
+ /** Конкретный инструмент / RPC-метод / HTTP-маршрут. */
21
+ source?: string | null;
22
+ details?: unknown;
23
+ remote?: string | null;
24
+ /** Время события (ISO). По умолчанию — сейчас. */
25
+ ts?: string;
26
+ }
27
+
28
+ export interface AuditRecord {
29
+ id: number;
30
+ ts: string;
31
+ action: string;
32
+ targetType: string | null;
33
+ target: string | null;
34
+ actor: string;
35
+ source: string | null;
36
+ details: unknown;
37
+ remote: string | null;
38
+ }
39
+
40
+ export interface ReadAuditFilter {
41
+ action?: string;
42
+ target?: string;
43
+ actor?: string;
44
+ since?: string;
45
+ until?: string;
46
+ limit?: number;
47
+ }
48
+
49
+ export interface ReadAuditResult {
50
+ records: AuditRecord[];
51
+ total: number;
52
+ }
53
+
54
+ export const DEFAULT_AUDIT_RETENTION_DAYS = 90;
55
+ export const DEFAULT_AUDIT_MAX_RECORDS = 10_000;
56
+
57
+ const SENSITIVE_KEY_RE = /(TOKEN|SECRET|PASS|PASSWORD|PASSWD|API_?KEY|CREDENTIAL|AUTH)/i;
58
+ const PURE_SECRET_REF_RE = /^\$\{secret:[A-Za-z0-9_.-]{1,64}\}$/;
59
+
60
+ function looksLikeSecretRef(value: string): boolean {
61
+ return PURE_SECRET_REF_RE.test(value.trim());
62
+ }
63
+
64
+ /** Рекурсивно вычищает секреты из произвольной структуры details. */
65
+ export function redactAuditDetails(value: unknown, depth = 0): unknown {
66
+ if (depth > 8) return "[truncated]";
67
+ if (typeof value === "string") return redactSecretsInText(value);
68
+ if (value == null || typeof value !== "object") return value;
69
+ if (Array.isArray(value)) {
70
+ return value.slice(0, 200).map((item) => redactAuditDetails(item, depth + 1));
71
+ }
72
+ const result: Record<string, unknown> = {};
73
+ for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
74
+ if (
75
+ typeof item === "string" &&
76
+ SENSITIVE_KEY_RE.test(key) &&
77
+ !looksLikeSecretRef(item)
78
+ ) {
79
+ result[key] = "***";
80
+ } else {
81
+ result[key] = redactAuditDetails(item, depth + 1);
82
+ }
83
+ }
84
+ return result;
85
+ }
86
+
87
+ function safeJson(value: unknown): string | null {
88
+ if (value === undefined || value === null) return null;
89
+ try {
90
+ return JSON.stringify(redactAuditDetails(value));
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ let lastCleanupAt = 0;
97
+
98
+ /**
99
+ * Записывает событие аудита. Никогда не бросает исключение.
100
+ * Возвращает id записи или null при ошибке.
101
+ */
102
+ export function recordAudit(entry: AuditEntryInput): number | null {
103
+ try {
104
+ const ts = entry.ts ?? new Date().toISOString();
105
+ const result = getDb()
106
+ .prepare(
107
+ `INSERT INTO audit_log
108
+ (ts, action, target_type, target, actor, source, details_json, remote)
109
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
110
+ )
111
+ .run(
112
+ ts,
113
+ String(entry.action || "unknown").slice(0, 128),
114
+ entry.targetType == null ? null : String(entry.targetType).slice(0, 64),
115
+ entry.target == null ? null : String(entry.target).slice(0, 256),
116
+ String(entry.actor || "system").slice(0, 32),
117
+ entry.source == null ? null : String(entry.source).slice(0, 128),
118
+ safeJson(entry.details),
119
+ entry.remote == null ? null : String(entry.remote).slice(0, 128)
120
+ );
121
+ maybeCleanup();
122
+ return Number(result.lastInsertRowid) || null;
123
+ } catch (err) {
124
+ try {
125
+ console.warn(
126
+ `[audit] не удалось записать событие: ${
127
+ err instanceof Error ? err.message : String(err)
128
+ }`
129
+ );
130
+ } catch {
131
+ // console недоступен — молча игнорируем.
132
+ }
133
+ return null;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Ленивая ротация: не чаще раза в час, лимиты по умолчанию. Точные лимиты из
139
+ * settings применяются в cleanupHistory / manage_settings.
140
+ */
141
+ function maybeCleanup(): void {
142
+ const now = Date.now();
143
+ if (now - lastCleanupAt < 60 * 60 * 1000) return;
144
+ lastCleanupAt = now;
145
+ try {
146
+ cleanupAuditLog({
147
+ retentionDays: DEFAULT_AUDIT_RETENTION_DAYS,
148
+ maxRecords: DEFAULT_AUDIT_MAX_RECORDS,
149
+ });
150
+ } catch {
151
+ // очистка не критична
152
+ }
153
+ }
154
+
155
+ function rowToRecord(row: any): AuditRecord {
156
+ let details: unknown = null;
157
+ if (row.details_json) {
158
+ try {
159
+ details = JSON.parse(String(row.details_json));
160
+ } catch {
161
+ details = String(row.details_json);
162
+ }
163
+ }
164
+ return {
165
+ id: Number(row.id),
166
+ ts: String(row.ts),
167
+ action: String(row.action),
168
+ targetType: row.target_type == null ? null : String(row.target_type),
169
+ target: row.target == null ? null : String(row.target),
170
+ actor: String(row.actor ?? "system"),
171
+ source: row.source == null ? null : String(row.source),
172
+ details,
173
+ remote: row.remote == null ? null : String(row.remote),
174
+ };
175
+ }
176
+
177
+ /** Читает журнал аудита (новые сверху). */
178
+ export function readAuditLog(filter: ReadAuditFilter = {}): ReadAuditResult {
179
+ const limit = Math.max(1, Math.min(5000, Math.floor(filter.limit ?? 200) || 200));
180
+ const where: string[] = [];
181
+ const params: unknown[] = [];
182
+ if (filter.action?.trim()) {
183
+ where.push("action = ?");
184
+ params.push(filter.action.trim());
185
+ }
186
+ if (filter.target?.trim()) {
187
+ where.push("target = ?");
188
+ params.push(filter.target.trim());
189
+ }
190
+ if (filter.actor?.trim()) {
191
+ where.push("actor = ?");
192
+ params.push(filter.actor.trim());
193
+ }
194
+ if (filter.since?.trim()) {
195
+ where.push("ts >= ?");
196
+ params.push(filter.since.trim());
197
+ }
198
+ if (filter.until?.trim()) {
199
+ where.push("ts <= ?");
200
+ params.push(filter.until.trim());
201
+ }
202
+ const clause = where.length ? `WHERE ${where.join(" AND ")}` : "";
203
+ try {
204
+ const db = getDb();
205
+ const totalRow = db
206
+ .prepare(`SELECT COUNT(*) AS count FROM audit_log ${clause}`)
207
+ .get(...params) as any;
208
+ const rows = db
209
+ .prepare(`SELECT * FROM audit_log ${clause} ORDER BY ts DESC, id DESC LIMIT ?`)
210
+ .all(...params, limit) as any[];
211
+ return { records: rows.map(rowToRecord), total: Number(totalRow?.count) || 0 };
212
+ } catch (err) {
213
+ try {
214
+ console.warn(
215
+ `[audit] не удалось прочитать журнал: ${
216
+ err instanceof Error ? err.message : String(err)
217
+ }`
218
+ );
219
+ } catch {
220
+ // ignore
221
+ }
222
+ return { records: [], total: 0 };
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Удаляет старые записи и лишние сверх maxRecords.
228
+ * Возвращает количество удалённых строк.
229
+ */
230
+ export function cleanupAuditLog(options: {
231
+ retentionDays?: number;
232
+ maxRecords?: number;
233
+ } = {}): number {
234
+ const retentionDays = Math.max(
235
+ 0,
236
+ Math.floor(options.retentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS) || 0
237
+ );
238
+ const maxRecords = Math.max(
239
+ 100,
240
+ Math.floor(options.maxRecords ?? DEFAULT_AUDIT_MAX_RECORDS) || DEFAULT_AUDIT_MAX_RECORDS
241
+ );
242
+ let deleted = 0;
243
+ try {
244
+ const db = getDb();
245
+ if (retentionDays > 0) {
246
+ const cutoff = new Date(
247
+ Date.now() - retentionDays * 24 * 60 * 60 * 1000
248
+ ).toISOString();
249
+ const result = db.prepare("DELETE FROM audit_log WHERE ts < ?").run(cutoff);
250
+ deleted += Number(result.changes) || 0;
251
+ }
252
+ const countRow = db.prepare("SELECT COUNT(*) AS count FROM audit_log").get() as any;
253
+ const count = Number(countRow?.count) || 0;
254
+ if (count > maxRecords) {
255
+ const excess = count - maxRecords;
256
+ const result = db
257
+ .prepare(
258
+ `DELETE FROM audit_log WHERE id IN (
259
+ SELECT id FROM audit_log ORDER BY ts ASC, id ASC LIMIT ?
260
+ )`
261
+ )
262
+ .run(excess);
263
+ deleted += Number(result.changes) || 0;
264
+ }
265
+ } catch (err) {
266
+ try {
267
+ console.warn(
268
+ `[audit] не удалось очистить журнал: ${
269
+ err instanceof Error ? err.message : String(err)
270
+ }`
271
+ );
272
+ } catch {
273
+ // ignore
274
+ }
275
+ }
276
+ return deleted;
277
+ }
278
+
279
+ /** Удаляет все записи (тесты / обслуживание). */
280
+ export function clearAuditLog(): void {
281
+ try {
282
+ getDb().exec("DELETE FROM audit_log");
283
+ } catch {
284
+ // ignore
285
+ }
286
+ }
287
+
288
+ /** Сбрасывает троттлинг очистки (для тестов). */
289
+ export function resetAuditCleanupThrottle(): void {
290
+ lastCleanupAt = 0;
291
+ }
@@ -10,7 +10,8 @@ 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";
14
15
  import type { TaskDefinition } from "../task-transfer.js";
15
16
 
16
17
  export interface DryRunRoleScoped {
@@ -18,6 +19,36 @@ export interface DryRunRoleScoped {
18
19
  denied?: string[];
19
20
  }
20
21
 
22
+ /**
23
+ * Детали триггера (Спринт 27): чем задача запускается и не будет ли запуск
24
+ * пропущен из-за окна/дней недели. Для git-триггера — состояние репозитория.
25
+ */
26
+ export interface DryRunTriggerDetails {
27
+ type: "manual" | "cron" | "file" | "git" | "mcp-event" | "once";
28
+ /** Человекочитаемое объяснение условия запуска. */
29
+ explanation: string;
30
+ /** Состояние окна запуска и разрешённых дней недели (если заданы). */
31
+ activeWindow?: {
32
+ active: boolean;
33
+ reason?: string;
34
+ nextOpenAt: string | null;
35
+ };
36
+ /** Состояние git-триггера на момент dry-run. */
37
+ git?: {
38
+ branch: string | null;
39
+ head: string | null;
40
+ lastCommit: string | null;
41
+ changedFiles: string[];
42
+ matched: string[];
43
+ };
44
+ /** Настройки файлового триггера. */
45
+ file?: {
46
+ watchPath: string | null;
47
+ globs: string[];
48
+ ignore: string[];
49
+ };
50
+ }
51
+
21
52
  export interface DryRunTaskItem {
22
53
  name: string;
23
54
  order: number;
@@ -51,6 +82,8 @@ export interface DryRunTaskItem {
51
82
  pausedUntil: string | null;
52
83
  nextRuns: string[];
53
84
  };
85
+ /** Детали триггера и причина возможного пропуска (Спринт 27). */
86
+ triggerDetails?: DryRunTriggerDetails;
54
87
  }
55
88
 
56
89
  export interface DryRunTotals {
@@ -79,6 +112,151 @@ const DANGEROUS_PATTERNS: Array<{ test: RegExp; message: string }> = [
79
112
  { test: /git\s+push\s+.*--force(?:\s|$)/, message: "принудительный push в git (`git push --force`)" },
80
113
  ];
81
114
 
115
+ /**
116
+ * Свойства для описания триггера задачи в dry-run (Спринт 27).
117
+ */
118
+ interface DescribeTriggerOptions {
119
+ /** Задание задачи (может содержать новые поля Спринта 27). */
120
+ def: TaskDefinition;
121
+ /** Эффективная рабочая директория задачи. */
122
+ cwd: string;
123
+ /** Вычисляемый тип триггера для поля `trigger`. */
124
+ triggerType: string;
125
+ /** Куда накапливать предупреждения (префикс [task] добавится в цикле). */
126
+ warnings: string[];
127
+ }
128
+
129
+ /**
130
+ * Описывает триггер задачи: что запускает задачу, не будет ли запуск
131
+ * пропущен из-за окна/дней недели, и (для git) состояние репозитория.
132
+ * Не имеет побочных эффектов (для git используется persist: false).
133
+ */
134
+ async function describeTrigger(opts: DescribeTriggerOptions): Promise<DryRunTriggerDetails> {
135
+ const { def, cwd, triggerType, warnings } = opts;
136
+ const policy: "skip" | "postpone" | "run" = def.windowPolicy ?? "postpone";
137
+
138
+ const base: DryRunTriggerDetails = {
139
+ type: triggerType as DryRunTriggerDetails["type"],
140
+ explanation: "",
141
+ };
142
+
143
+ const hasWindow = Boolean((def.notBefore ?? "").trim() || (def.notAfter ?? "").trim());
144
+ const hasDays = Array.isArray(def.activeDays) && def.activeDays.length > 0;
145
+
146
+ switch (triggerType) {
147
+ case "git": {
148
+ try {
149
+ const result = await checkGitTrigger(
150
+ {
151
+ name: def.name,
152
+ cwd,
153
+ branch: def.gitBranch ?? undefined,
154
+ paths: def.gitPaths ?? undefined,
155
+ ignore: def.gitIgnore ?? undefined,
156
+ },
157
+ { persist: false }
158
+ );
159
+ base.git = {
160
+ branch: result.branch ?? null,
161
+ head: result.head ?? null,
162
+ lastCommit: result.from ?? null,
163
+ changedFiles: result.files,
164
+ matched: result.matched,
165
+ };
166
+ base.explanation = result.message;
167
+
168
+ if (result.status === "no-repo") {
169
+ warnings.push("Задача с git-триггером, но рабочая директория не является git-репозиторием.");
170
+ } else if (result.status === "branch-mismatch") {
171
+ warnings.push(`Ветка не подходит под фильтр «${def.gitBranch ?? ""}».`);
172
+ }
173
+ } catch (err: any) {
174
+ base.explanation = `Git-триггер: ошибка проверки — ${err instanceof Error ? err.message : String(err)}.`;
175
+ warnings.push(base.explanation);
176
+ }
177
+ break;
178
+ }
179
+
180
+ case "file": {
181
+ base.file = {
182
+ watchPath: def.watchPath ?? null,
183
+ globs: Array.isArray(def.watchGlobs) ? def.watchGlobs : [],
184
+ ignore: Array.isArray(def.watchIgnore) ? def.watchIgnore : [],
185
+ };
186
+ const parts: string[] = [];
187
+ if (def.watchPath) parts.push(`«${def.watchPath}»`);
188
+ if (def.watchGlobs?.length) parts.push(`маски: ${def.watchGlobs.length}`);
189
+ if (def.watchIgnore?.length) parts.push(`исключения: ${def.watchIgnore.length}`);
190
+ base.explanation =
191
+ parts.length > 0
192
+ ? `Файловый триггер: ${parts.join("; ")}.`
193
+ : "Файловый триггер: любое изменение подходит.";
194
+ break;
195
+ }
196
+
197
+ case "mcp-event": {
198
+ const ev = def.mcpEvent;
199
+ base.explanation = ev && ev.event
200
+ ? `MCP-событие ${ev.server}:${ev.event}${ev.filter ? ` (фильтр «${ev.filter}»)` : ""}.`
201
+ : "MCP-событие (параметры не заданы).";
202
+ break;
203
+ }
204
+
205
+ case "cron": {
206
+ let text = `По расписанию «${def.schedule}»`;
207
+ if (def.timezone) text += ` (${def.timezone})`;
208
+ base.explanation = text + ".";
209
+ break;
210
+ }
211
+
212
+ case "once": {
213
+ base.explanation = def.runAt ? `Однократно в ${def.runAt}.` : "Однократный запуск.";
214
+ break;
215
+ }
216
+
217
+ case "manual":
218
+ default: {
219
+ base.explanation = "Запуск вручную (в составе конвейера).";
220
+ break;
221
+ }
222
+ }
223
+
224
+ // Окно запуска и дни недели (если заданы).
225
+ if (hasWindow || hasDays) {
226
+ const state = activeWindowState(new Date(), {
227
+ notBefore: def.notBefore ?? undefined,
228
+ notAfter: def.notAfter ?? undefined,
229
+ days: def.activeDays ?? undefined,
230
+ timeZone: def.timezone ?? undefined,
231
+ });
232
+ base.activeWindow = {
233
+ active: state.active,
234
+ ...(state.reason ? { reason: state.reason } : {}),
235
+ nextOpenAt: state.nextOpenAt ? state.nextOpenAt.toISOString() : null,
236
+ };
237
+
238
+ if (!state.active && policy !== "run") {
239
+ if (policy === "skip") {
240
+ warnings.push(
241
+ `Сейчас ${state.reason ?? "вне окна"}: при политике skip запуск будет пропущен.`
242
+ );
243
+ } else {
244
+ // postpone — переносим на ближайшее открытие.
245
+ const iso = base.activeWindow.nextOpenAt ?? null;
246
+ warnings.push(
247
+ iso
248
+ ? `Сейчас ${state.reason ?? "вне окна"}: запуск будет перенесён на ${iso}.`
249
+ : `Сейчас ${state.reason ?? "вне окна"}: открытие окна не найдено, запуск пропущен.`
250
+ );
251
+ }
252
+ } else if (!state.active && policy === "run") {
253
+ warnings.push(`Сейчас ${state.reason ?? "вне окна"}: политика run — задача выполнится всё равно.`);
254
+ }
255
+ }
256
+
257
+ return base;
258
+ }
259
+
82
260
  /**
83
261
  * Симулирует конвейер задачи: сама задача + все зависимости (dependsOn)
84
262
  * в топологическом порядке. Возвращает отчёт без реального запуска.
@@ -230,6 +408,14 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
230
408
  ? "manual"
231
409
  : "dag";
232
410
 
411
+ // Детали триггера (Спринт 27): состояние окна/дней недели, git-статус.
412
+ const triggerDetails = await describeTrigger({
413
+ def,
414
+ cwd,
415
+ triggerType,
416
+ warnings: taskWarnings,
417
+ });
418
+
233
419
  // Команда, которую выполнит обёртка.
234
420
  const modelArg = def.model ? ` --model ${def.model}` : "";
235
421
  const promptPreview = (def.prompt ?? "").replace(/\s+/g, " ").trim();
@@ -329,6 +515,7 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
329
515
  estimatedTokens: estimatedTokens != null ? Math.round(estimatedTokens) : null,
330
516
  ...(matrixParent ? { matrixParent } : {}),
331
517
  ...(scheduleDetails ? { scheduleDetails } : {}),
518
+ ...(triggerDetails ? { triggerDetails } : {}),
332
519
  });
333
520
 
334
521
  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(