agent-steward 0.0.2 → 0.0.3

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 (180) hide show
  1. package/CHANGELOG.md +25 -2
  2. package/CROSS_PLATFORM.md +11 -9
  3. package/README.md +9 -8
  4. package/ROADMAP-STRATEGY.md +93 -44
  5. package/ROADMAP.md +114 -999
  6. package/dist/core/cron-to-schtasks.d.ts +0 -8
  7. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  8. package/dist/core/cron-to-schtasks.js +11 -86
  9. package/dist/core/dry-run.js +1 -1
  10. package/dist/core/file-watcher.js +9 -9
  11. package/dist/core/git-trigger.js +4 -4
  12. package/dist/core/lock.js +2 -4
  13. package/dist/core/one-shot.d.ts +27 -5
  14. package/dist/core/one-shot.d.ts.map +1 -1
  15. package/dist/core/one-shot.js +53 -10
  16. package/dist/core/otel.js +2 -2
  17. package/dist/core/ps-wrapper.d.ts +1 -1
  18. package/dist/core/ps-wrapper.d.ts.map +1 -1
  19. package/dist/core/ps-wrapper.js +55 -35
  20. package/dist/core/record-history.js +22 -22
  21. package/dist/core/schedule-v2.d.ts +2 -2
  22. package/dist/core/schedule-v2.d.ts.map +1 -1
  23. package/dist/core/schedule-v2.js +7 -7
  24. package/dist/core/scheduler/at-fallback.d.ts +42 -0
  25. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  26. package/dist/core/scheduler/at-fallback.js +70 -0
  27. package/dist/core/scheduler/linux.d.ts +3 -1
  28. package/dist/core/scheduler/linux.d.ts.map +1 -1
  29. package/dist/core/scheduler/linux.js +43 -7
  30. package/dist/core/scheduler/mac.d.ts +14 -8
  31. package/dist/core/scheduler/mac.d.ts.map +1 -1
  32. package/dist/core/scheduler/mac.js +71 -22
  33. package/dist/core/scheduler/posix.d.ts.map +1 -1
  34. package/dist/core/scheduler/posix.js +12 -1
  35. package/dist/core/scheduler/registry.d.ts +2 -0
  36. package/dist/core/scheduler/registry.d.ts.map +1 -1
  37. package/dist/core/scheduler/windows.d.ts +16 -3
  38. package/dist/core/scheduler/windows.d.ts.map +1 -1
  39. package/dist/core/scheduler/windows.js +249 -96
  40. package/dist/core/secrets.js +2 -2
  41. package/dist/core/self-analysis.js +55 -55
  42. package/dist/core/summary.js +1 -1
  43. package/dist/core/triage-chain.js +1 -1
  44. package/dist/core/triage-worker.js +2 -2
  45. package/dist/core/triage.js +1 -1
  46. package/dist/core/wrappers/bash.js +33 -33
  47. package/dist/db/index.d.ts +2 -0
  48. package/dist/db/index.d.ts.map +1 -1
  49. package/dist/db/index.js +9 -1
  50. package/dist/db/run-journal.d.ts +60 -0
  51. package/dist/db/run-journal.d.ts.map +1 -0
  52. package/dist/db/run-journal.js +143 -0
  53. package/dist/db/run-resume.d.ts +48 -0
  54. package/dist/db/run-resume.d.ts.map +1 -0
  55. package/dist/db/run-resume.js +137 -0
  56. package/dist/db/runs-repo.d.ts +120 -0
  57. package/dist/db/runs-repo.d.ts.map +1 -0
  58. package/dist/db/runs-repo.js +319 -0
  59. package/dist/db/schema.d.ts +16 -2
  60. package/dist/db/schema.d.ts.map +1 -1
  61. package/dist/db/schema.js +190 -35
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +66 -36
  65. package/dist/notifications.js +18 -18
  66. package/dist/profiles.d.ts +7 -3
  67. package/dist/profiles.d.ts.map +1 -1
  68. package/dist/profiles.js +85 -7
  69. package/dist/rpc.d.ts +109 -0
  70. package/dist/rpc.d.ts.map +1 -1
  71. package/dist/rpc.js +89 -0
  72. package/dist/server.d.ts +2 -2
  73. package/dist/server.d.ts.map +1 -1
  74. package/dist/server.js +20 -19
  75. package/dist/shared/jobs-view.d.ts.map +1 -1
  76. package/dist/skill.js +1 -1
  77. package/dist/task-transfer.d.ts +1 -1
  78. package/dist/task-transfer.d.ts.map +1 -1
  79. package/dist/task-transfer.js +14 -10
  80. package/dist/types.d.ts +20 -4
  81. package/dist/types.d.ts.map +1 -1
  82. package/dist/types.js +37 -9
  83. package/dist/workspaces.js +1 -1
  84. package/docs/ARCHITECTURE.md +110 -8
  85. package/docs/COMPATIBILITY.md +10 -6
  86. package/docs/CONCEPT.md +15 -3
  87. package/docs/CROSS_PLATFORM.ru.md +11 -9
  88. package/docs/CROSS_PLATFORM.zh.md +11 -9
  89. package/docs/FAQ.md +2 -2
  90. package/docs/FAQ.ru.md +2 -2
  91. package/docs/FAQ.zh.md +2 -2
  92. package/docs/FEATURES.md +5 -4
  93. package/docs/FEATURES.zh.md +5 -4
  94. package/docs/MIGRATION.md +34 -26
  95. package/docs/README.ru.md +26 -7
  96. package/docs/README.zh.md +9 -8
  97. package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
  98. package/gui-experimental.cjs +8 -8
  99. package/index.js +1 -0
  100. package/locales/en.json +1 -0
  101. package/locales/ru.json +1 -0
  102. package/locales/zh.json +1 -0
  103. package/package.json +31 -10
  104. package/src/core/analytics.ts +2 -2
  105. package/src/core/audit.ts +17 -17
  106. package/src/core/cron-to-schtasks.ts +14 -93
  107. package/src/core/dry-run.ts +26 -26
  108. package/src/core/file-watcher.ts +17 -17
  109. package/src/core/git-trigger.ts +9 -9
  110. package/src/core/glob.ts +1 -1
  111. package/src/core/local-ai.ts +2 -2
  112. package/src/core/lock.ts +9 -9
  113. package/src/core/matrix.ts +31 -31
  114. package/src/core/native-notify.ts +2 -2
  115. package/src/core/one-shot.ts +63 -13
  116. package/src/core/otel.ts +4 -4
  117. package/src/core/permissions.ts +5 -5
  118. package/src/core/prometheus.ts +17 -17
  119. package/src/core/ps-wrapper.ts +57 -37
  120. package/src/core/record-history.ts +40 -40
  121. package/src/core/retention.ts +3 -3
  122. package/src/core/savings.ts +1 -1
  123. package/src/core/schedule-gate.ts +12 -12
  124. package/src/core/schedule-v2.ts +24 -24
  125. package/src/core/scheduler/at-fallback.ts +113 -0
  126. package/src/core/scheduler/index.ts +3 -3
  127. package/src/core/scheduler/linux.ts +64 -13
  128. package/src/core/scheduler/logs.ts +1 -1
  129. package/src/core/scheduler/mac.ts +112 -60
  130. package/src/core/scheduler/posix.ts +15 -1
  131. package/src/core/scheduler/registry.ts +6 -4
  132. package/src/core/scheduler/windows.ts +295 -125
  133. package/src/core/secrets.ts +13 -13
  134. package/src/core/self-analysis.ts +61 -61
  135. package/src/core/session.ts +3 -3
  136. package/src/core/structured-log.ts +3 -3
  137. package/src/core/summary.ts +25 -25
  138. package/src/core/telegram.ts +16 -16
  139. package/src/core/triage-chain.ts +4 -4
  140. package/src/core/triage-compare.ts +8 -8
  141. package/src/core/triage-rules.ts +4 -4
  142. package/src/core/triage-shadow.ts +7 -7
  143. package/src/core/triage-worker.ts +6 -6
  144. package/src/core/triage.ts +23 -23
  145. package/src/core/watch-paths.ts +1 -1
  146. package/src/core/wrappers/bash.ts +41 -41
  147. package/src/db/git-state-repo.ts +1 -1
  148. package/src/db/history-repo.ts +22 -22
  149. package/src/db/index.ts +16 -6
  150. package/src/db/metrics-repo.ts +10 -10
  151. package/src/db/migrate.ts +10 -10
  152. package/src/db/recovery.ts +3 -3
  153. package/src/db/run-journal.ts +212 -0
  154. package/src/db/run-resume.ts +220 -0
  155. package/src/db/runs-repo.ts +481 -0
  156. package/src/db/schema.ts +205 -44
  157. package/src/db/settings-repo.ts +2 -2
  158. package/src/db/tasks-repo.ts +10 -10
  159. package/src/db/templates-repo.ts +7 -7
  160. package/src/gui.tsx +1 -1
  161. package/src/history.ts +4 -4
  162. package/src/i18n.ts +7 -7
  163. package/src/index.ts +341 -304
  164. package/src/integrations.ts +6 -6
  165. package/src/notifications.ts +76 -76
  166. package/src/profiles.ts +98 -7
  167. package/src/rpc.ts +96 -1
  168. package/src/schtasks.ts +2 -2
  169. package/src/server.ts +43 -42
  170. package/src/settings.ts +44 -44
  171. package/src/shared/jobs-view.ts +60 -60
  172. package/src/skill.ts +1 -1
  173. package/src/task-transfer.ts +58 -56
  174. package/src/templates.ts +1 -1
  175. package/src/types.ts +45 -10
  176. package/src/workspaces.ts +16 -16
  177. package/dist/core/self-analysis.test.d.ts +0 -2
  178. package/dist/core/self-analysis.test.d.ts.map +0 -1
  179. package/dist/core/self-analysis.test.js +0 -219
  180. package/dist/gui-experimental.cjs +0 -1
@@ -39,7 +39,7 @@ export class FileWatchManager {
39
39
 
40
40
  constructor(
41
41
  private readonly handler: FileTriggerHandler,
42
- private readonly debounceMs: number = FILE_TRIGGER_DEBOUNCE_MS
42
+ private readonly debounceMs: number = FILE_TRIGGER_DEBOUNCE_MS,
43
43
  ) {}
44
44
 
45
45
  /** Сколько задач сейчас отслеживается. */
@@ -61,7 +61,7 @@ export class FileWatchManager {
61
61
  (d) =>
62
62
  d.triggerType === "file" &&
63
63
  typeof d.watchPath === "string" &&
64
- d.watchPath.trim().length > 0
64
+ d.watchPath.trim().length > 0,
65
65
  )
66
66
  .map((d) => ({
67
67
  name: d.name.trim(),
@@ -79,13 +79,13 @@ export class FileWatchManager {
79
79
  // watcher на путях с управляющими символами или выходом через `..`.
80
80
  if (hasPathControlChars(d.path)) {
81
81
  console.error(
82
- `[windows-scheduler] Задача "${d.name}": путь наблюдения содержит управляющие символы — пропущен.`
82
+ `[agent-steward] Задача "${d.name}": путь наблюдения содержит управляющие символы — пропущен.`,
83
83
  );
84
84
  return false;
85
85
  }
86
86
  if (!isAbsolute(d.path) && d.path.split(/[\\/]/).includes("..")) {
87
87
  console.error(
88
- `[windows-scheduler] Задача "${d.name}": относительный путь наблюдения выходит за рабочую директорию — пропущен.`
88
+ `[agent-steward] Задача "${d.name}": относительный путь наблюдения выходит за рабочую директорию — пропущен.`,
89
89
  );
90
90
  return false;
91
91
  }
@@ -130,7 +130,7 @@ export class FileWatchManager {
130
130
  name: string,
131
131
  watchPath: string,
132
132
  globs: string[] = [],
133
- ignore: string[] = []
133
+ ignore: string[] = [],
134
134
  ): void {
135
135
  // Спринт 27: маски с "**" требуют рекурсивного обхода директории.
136
136
  const needsRecursive = globs.some((g) => g.includes("**"));
@@ -148,9 +148,9 @@ export class FileWatchManager {
148
148
  });
149
149
  } catch (err: any) {
150
150
  console.error(
151
- `[windows-scheduler] Не удалось начать отслеживание "${watchPath}" для задачи "${name}": ${
151
+ `[agent-steward] Не удалось начать отслеживание "${watchPath}" для задачи "${name}": ${
152
152
  err instanceof Error ? err.message : String(err)
153
- }`
153
+ }`,
154
154
  );
155
155
  return;
156
156
  }
@@ -174,7 +174,7 @@ export class FileWatchManager {
174
174
  const rel = relativeTo(watchPath, changedPath);
175
175
  const candidates = rel ? [rel, changedPath] : [changedPath];
176
176
  return candidates.some(
177
- (candidate) => filterPaths([candidate], globs, ignore).length > 0
177
+ (candidate) => filterPaths([candidate], globs, ignore).length > 0,
178
178
  );
179
179
  };
180
180
 
@@ -187,20 +187,20 @@ export class FileWatchManager {
187
187
  if (this.stopped) return;
188
188
  try {
189
189
  const result = this.handler(name, changedPath);
190
- if (result && typeof (result as Promise<void>).catch === "function") {
191
- (result as Promise<void>).catch((err: any) => {
190
+ if (result && typeof (result).catch === "function") {
191
+ (result).catch((err: any) => {
192
192
  console.error(
193
- `[windows-scheduler] Ошибка запуска задачи "${name}" по изменению файла: ${
193
+ `[agent-steward] Ошибка запуска задачи "${name}" по изменению файла: ${
194
194
  err instanceof Error ? err.message : String(err)
195
- }`
195
+ }`,
196
196
  );
197
197
  });
198
198
  }
199
199
  } catch (err: any) {
200
200
  console.error(
201
- `[windows-scheduler] Ошибка запуска задачи "${name}" по изменению файла: ${
201
+ `[agent-steward] Ошибка запуска задачи "${name}" по изменению файла: ${
202
202
  err instanceof Error ? err.message : String(err)
203
- }`
203
+ }`,
204
204
  );
205
205
  }
206
206
  }, this.debounceMs);
@@ -216,15 +216,15 @@ export class FileWatchManager {
216
216
 
217
217
  watcher.on("error", (err) => {
218
218
  console.error(
219
- `[windows-scheduler] Ошибка наблюдения за "${watchPath}" (задача "${name}"): ${
219
+ `[agent-steward] Ошибка наблюдения за "${watchPath}" (задача "${name}"): ${
220
220
  (err as any)?.message ?? String(err)
221
- }`
221
+ }`,
222
222
  );
223
223
  });
224
224
 
225
225
  this.entries.set(name.toLowerCase(), entry);
226
226
  console.log(
227
- `[windows-scheduler] Слежу за "${watchPath}" — задача "${name}" запускается при изменении файла.`
227
+ `[agent-steward] Слежу за "${watchPath}" — задача "${name}" запускается при изменении файла.`,
228
228
  );
229
229
  }
230
230
 
@@ -70,11 +70,11 @@ const defaultRunner: GitRunner = (cwd, args) =>
70
70
  { timeout: GIT_COMMAND_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 * 1024 * 1024 },
71
71
  (err, stdout) => {
72
72
  if (err) {
73
- reject(err);
73
+ reject(err instanceof Error ? err : new Error(String(err)));
74
74
  return;
75
75
  }
76
76
  resolve(String(stdout ?? ""));
77
- }
77
+ },
78
78
  );
79
79
  });
80
80
 
@@ -113,7 +113,7 @@ export async function gitChangedFiles(
113
113
  cwd: string,
114
114
  from: string | null,
115
115
  to: string,
116
- run: GitRunner = defaultRunner
116
+ run: GitRunner = defaultRunner,
117
117
  ): Promise<string[]> {
118
118
  const args = from
119
119
  ? ["diff", "--name-only", `${from}..${to}`]
@@ -126,7 +126,7 @@ export async function gitChangedFiles(
126
126
  }
127
127
 
128
128
  function branchMatches(branch: string | null, pattern?: string): boolean {
129
- if (!pattern || !pattern.trim()) return true;
129
+ if (!pattern?.trim()) return true;
130
130
  if (!branch) return false;
131
131
  const normalize = (value: string) =>
132
132
  process.platform === "win32" ? value.toLowerCase() : value;
@@ -151,7 +151,7 @@ function branchMatches(branch: string | null, pattern?: string): boolean {
151
151
  */
152
152
  export async function checkGitTrigger(
153
153
  task: GitTriggerTask,
154
- options: { run?: GitRunner; persist?: boolean } = {}
154
+ options: { run?: GitRunner; persist?: boolean } = {},
155
155
  ): Promise<GitCheckResult> {
156
156
  const run = options.run ?? defaultRunner;
157
157
  const persist = options.persist !== false;
@@ -328,7 +328,7 @@ export class GitTriggerManager {
328
328
  return checkGitTrigger(this.taskSpec(managed.def), { run: this.run });
329
329
  }
330
330
  const def = (await loadTaskDefinitions()).find(
331
- (d) => d.triggerType === "git" && d.name.toLowerCase() === taskName.toLowerCase()
331
+ (d) => d.triggerType === "git" && d.name.toLowerCase() === taskName.toLowerCase(),
332
332
  );
333
333
  if (!def) return null;
334
334
  return checkGitTrigger(this.taskSpec(def), { run: this.run });
@@ -354,13 +354,13 @@ export class GitTriggerManager {
354
354
  if (result.status === "changed") {
355
355
  await this.handler(managed.def.name, { ...result, cwd: cwdOf(managed.def) });
356
356
  } else if (result.status === "error") {
357
- console.error(`[windows-scheduler] git-триггер «${managed.def.name}»: ${result.message}`);
357
+ console.error(`[agent-steward] git-триггер «${managed.def.name}»: ${result.message}`);
358
358
  }
359
359
  } catch (err: any) {
360
360
  console.error(
361
- `[windows-scheduler] git-триггер «${managed.def.name}»: ${
361
+ `[agent-steward] git-триггер «${managed.def.name}»: ${
362
362
  err instanceof Error ? err.message : String(err)
363
- }`
363
+ }`,
364
364
  );
365
365
  } finally {
366
366
  managed.busy = false;
package/src/core/glob.ts CHANGED
@@ -196,7 +196,7 @@ export function isIgnored(path: unknown, ignore: unknown): boolean {
196
196
  export function filterPaths(
197
197
  files: string[],
198
198
  include?: string[] | null,
199
- ignore?: string[] | null
199
+ ignore?: string[] | null,
200
200
  ): string[] {
201
201
  const list = Array.isArray(files) ? files : [];
202
202
  const includes = Array.isArray(include) ? include.filter(Boolean) : [];
@@ -70,7 +70,7 @@ export function protocolFor(baseUrl: string): "openai" | "ollama" {
70
70
  */
71
71
  export function applyLocalAiPatch(
72
72
  current: TriageSettings,
73
- patch: LocalAiPatch
73
+ patch: LocalAiPatch,
74
74
  ): { settings: TriageSettings; changed: string[] } {
75
75
  const next: TriageSettings = { ...current, shadow: { ...current.shadow } as TriageShadowSettings };
76
76
  const changed: string[] = [];
@@ -98,7 +98,7 @@ export function applyLocalAiPatch(
98
98
  patch.timeoutMs,
99
99
  LOCAL_AI_TIMEOUT_MIN,
100
100
  LOCAL_AI_TIMEOUT_MAX,
101
- current.timeoutMs
101
+ current.timeoutMs,
102
102
  );
103
103
  if (timeoutMs !== current.timeoutMs) {
104
104
  next.timeoutMs = timeoutMs;
package/src/core/lock.ts CHANGED
@@ -72,11 +72,11 @@ export class LockManager {
72
72
  continue;
73
73
  }
74
74
  await fs.rm(stalePath, { recursive: true, force: true }).catch(() => {});
75
- // eslint-disable-next-line no-console
75
+
76
76
  console.log(
77
- `[windows-scheduler] Вытеснен зависший lock: ${file} (возраст ${Math.round(
78
- age / 1000
79
- )} с)`
77
+ `[agent-steward] Вытеснен зависший lock: ${file} (возраст ${Math.round(
78
+ age / 1000,
79
+ )} с)`,
80
80
  );
81
81
  }
82
82
  } catch {
@@ -142,13 +142,13 @@ export class LockManager {
142
142
  export async function withLock<T>(
143
143
  lockManager: LockManager,
144
144
  taskName: string,
145
- fn: () => Promise<T>
145
+ fn: () => Promise<T>,
146
146
  ): Promise<T | null> {
147
147
  const acquired = await lockManager.acquire(taskName);
148
148
  if (!acquired) {
149
- // eslint-disable-next-line no-console
149
+
150
150
  console.log(
151
- `[windows-scheduler] Запуск задачи "${taskName}" пропущен: удерживается активная блокировка.`
151
+ `[agent-steward] Запуск задачи "${taskName}" пропущен: удерживается активная блокировка.`,
152
152
  );
153
153
  return null;
154
154
  }
@@ -171,7 +171,7 @@ export async function withLockWait<T>(
171
171
  lockManager: LockManager,
172
172
  taskName: string,
173
173
  fn: () => Promise<T>,
174
- options: { timeoutMs?: number; retryDelayMs?: number; staleMs?: number } = {}
174
+ options: { timeoutMs?: number; retryDelayMs?: number; staleMs?: number } = {},
175
175
  ): Promise<T> {
176
176
  const timeoutMs = options.timeoutMs ?? 15000;
177
177
  const retryDelayMs = options.retryDelayMs ?? 50;
@@ -205,7 +205,7 @@ export async function withLockWait<T>(
205
205
 
206
206
  if (Date.now() >= deadline) {
207
207
  throw new Error(
208
- `Не удалось получить блокировку "${taskName}" за ${timeoutMs} мс.`
208
+ `Не удалось получить блокировку "${taskName}" за ${timeoutMs} мс.`,
209
209
  );
210
210
  }
211
211
  await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
@@ -56,7 +56,7 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
56
56
  const matrix = task.matrix;
57
57
  if (!matrix || !Array.isArray(matrix.workspaceIds) || matrix.workspaceIds.length === 0) {
58
58
  throw new Error(
59
- t("matrix.error.workspaceIdsEmpty", { task: task.name })
59
+ t("matrix.error.workspaceIdsEmpty", { task: task.name }),
60
60
  );
61
61
  }
62
62
 
@@ -70,13 +70,13 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
70
70
  t("matrix.error.workspaceMissing", {
71
71
  task: task.name,
72
72
  workspace: workspaceId,
73
- })
73
+ }),
74
74
  );
75
75
  }
76
76
  const name = matrixCloneName(task.name, workspace.name);
77
77
  if (usedNames.has(name.toLowerCase())) {
78
78
  throw new Error(
79
- t("matrix.error.duplicateCloneName", { task: task.name, name })
79
+ t("matrix.error.duplicateCloneName", { task: task.name, name }),
80
80
  );
81
81
  }
82
82
  usedNames.add(name.toLowerCase());
@@ -123,7 +123,7 @@ export function expandMatrixTask(task: TaskDefinition): TaskDefinition[] {
123
123
 
124
124
  if (clones.length === 0) {
125
125
  throw new Error(
126
- t("matrix.error.cloneCreation", { task: task.name })
126
+ t("matrix.error.cloneCreation", { task: task.name }),
127
127
  );
128
128
  }
129
129
  return clones;
@@ -189,7 +189,7 @@ export function aggregateMatrixResults(parentId: string): MatrixAggregate {
189
189
  const successCount = results.filter((r) => r.status === "success").length;
190
190
  const errorCount = results.filter((r) => r.status === "error").length;
191
191
  const pendingCount = results.filter(
192
- (r) => r.status !== "success" && r.status !== "error" && r.status !== "partial"
192
+ (r) => r.status !== "success" && r.status !== "error" && r.status !== "partial",
193
193
  ).length;
194
194
 
195
195
  let status: MatrixAggregate["status"];
@@ -217,9 +217,9 @@ export function aggregateMatrixResults(parentId: string): MatrixAggregate {
217
217
  }) +
218
218
  (firstError?.error
219
219
  ? t("matrix.aggregate.stoppedFirst", {
220
- name: firstError.name,
221
- error: firstError.error,
222
- })
220
+ name: firstError.name,
221
+ error: firstError.error,
222
+ })
223
223
  : "");
224
224
  } else {
225
225
  status = "partial";
@@ -256,7 +256,7 @@ export interface MatrixRunResult {
256
256
  /** Эффективный лимит одновременных клонов матрицы (Спринт 17). */
257
257
  export function resolveMatrixConcurrency(
258
258
  matrix: MatrixConfig | undefined,
259
- totalClones: number
259
+ totalClones: number,
260
260
  ): number {
261
261
  const total = Math.max(1, totalClones);
262
262
  if (!matrix) return total;
@@ -336,14 +336,14 @@ export async function runMatrix(task: TaskDefinition): Promise<MatrixRunResult>
336
336
  console.log(
337
337
  `[matrix] ${task.name}: не удалось сохранить очередь: ${
338
338
  err instanceof Error ? err.message : String(err)
339
- }`
339
+ }`,
340
340
  );
341
341
  }
342
342
 
343
343
  console.log(
344
344
  `[matrix] ${task.name}: strategy=${strategy}, failureMode=${failureMode}, ` +
345
345
  `concurrency=${concurrency}, started=${started.length}, skipped=${skipped.length}, ` +
346
- `queued=${queueToSave.length}, errors=${errors.length}`
346
+ `queued=${queueToSave.length}, errors=${errors.length}`,
347
347
  );
348
348
 
349
349
  return {
@@ -363,7 +363,7 @@ export async function runMatrix(task: TaskDefinition): Promise<MatrixRunResult>
363
363
  * Возвращает имя запущенного клона или undefined.
364
364
  */
365
365
  export async function advanceSequentialMatrix(
366
- cloneName: string
366
+ cloneName: string,
367
367
  ): Promise<string | undefined> {
368
368
  const clone = getTask(cloneName);
369
369
  if (!clone?.matrixParentId) return undefined;
@@ -415,7 +415,7 @@ export async function advanceSequentialMatrix(
415
415
  * Возвращает имена запущенных клонов.
416
416
  */
417
417
  export async function advanceMatrixAfterClone(
418
- cloneName: string
418
+ cloneName: string,
419
419
  ): Promise<string[]> {
420
420
  const sequentialNext = await advanceSequentialMatrix(cloneName);
421
421
  if (sequentialNext) return [sequentialNext];
@@ -433,7 +433,7 @@ export async function advanceMatrixAfterClone(
433
433
  const clones = listMatrixClones(parent.name);
434
434
  const concurrency = resolveMatrixConcurrency(parent.matrix, clones.length);
435
435
  const running = clones.filter(
436
- (item) => latestCloneStatus(item.name).status === "running"
436
+ (item) => latestCloneStatus(item.name).status === "running",
437
437
  ).length;
438
438
  let slots = Math.max(0, concurrency - running);
439
439
  if (slots === 0) return [];
@@ -453,7 +453,7 @@ export async function advanceMatrixAfterClone(
453
453
  } catch (err: any) {
454
454
  const message = err instanceof Error ? err.message : String(err);
455
455
  console.log(
456
- `[matrix] ${parent.name}: не удалось запустить из очереди ${nextName}: ${message}`
456
+ `[matrix] ${parent.name}: не удалось запустить из очереди ${nextName}: ${message}`,
457
457
  );
458
458
  // Попытка запуска «съедает» слот: иначе при недоступном бэкенде
459
459
  // цикл уйдёт по всей очереди, проигнорировав лимит.
@@ -471,7 +471,7 @@ export async function advanceMatrixAfterClone(
471
471
  console.log(
472
472
  `[matrix] ${parent.name}: не удалось сохранить очередь: ${
473
473
  err instanceof Error ? err.message : String(err)
474
- }`
474
+ }`,
475
475
  );
476
476
  }
477
477
 
@@ -578,7 +578,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
578
578
  const desired = expandMatrixTask(parent);
579
579
  const existing = listMatrixClones(parent.name);
580
580
  const byName = new Map(
581
- existing.map((definition) => [definition.name.toLowerCase(), definition])
581
+ existing.map((definition) => [definition.name.toLowerCase(), definition]),
582
582
  );
583
583
  const desiredNames = new Set(desired.map((definition) => definition.name.toLowerCase()));
584
584
 
@@ -601,7 +601,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
601
601
  running.push(current.name);
602
602
  if (cloneSignature(current) !== cloneSignature(wanted)) {
603
603
  warnings.push(
604
- t("matrix.clone.runningChanges", { name: current.name })
604
+ t("matrix.clone.runningChanges", { name: current.name }),
605
605
  );
606
606
  }
607
607
  continue;
@@ -617,7 +617,7 @@ export function planMatrixSync(parent: TaskDefinition): MatrixSyncPlan {
617
617
  if (latest.status === "running") {
618
618
  running.push(current.name);
619
619
  warnings.push(
620
- t("matrix.clone.runningDeletion", { name: current.name })
620
+ t("matrix.clone.runningDeletion", { name: current.name }),
621
621
  );
622
622
  continue;
623
623
  }
@@ -652,7 +652,7 @@ export interface MatrixSyncResult {
652
652
  */
653
653
  export async function syncMatrixFamily(
654
654
  parent: TaskDefinition,
655
- hooks: MatrixSyncHooks = {}
655
+ hooks: MatrixSyncHooks = {},
656
656
  ): Promise<MatrixSyncResult> {
657
657
  const plan = planMatrixSync(parent);
658
658
 
@@ -680,7 +680,7 @@ export async function syncMatrixFamily(
680
680
 
681
681
  /** Имя родителя по имени агрегатора (`<parent>-matrix-complete`). */
682
682
  export function matrixParentOfCompleteTask(
683
- taskName: string
683
+ taskName: string,
684
684
  ): string | undefined {
685
685
  const trimmed = taskName.trim();
686
686
  if (!isMatrixCompleteName(trimmed)) return undefined;
@@ -698,7 +698,7 @@ export interface MatrixFamilyPlan {
698
698
  }
699
699
 
700
700
  export function planMatrixFamilyDelete(
701
- taskName: string
701
+ taskName: string,
702
702
  ): MatrixFamilyPlan | undefined {
703
703
  const definition = getTask(taskName);
704
704
  if (!definition?.matrix) return undefined;
@@ -715,7 +715,7 @@ export function planMatrixFamilyDelete(
715
715
  * Возвращает текст ошибки или undefined, если удаление разрешено.
716
716
  */
717
717
  export function getMatrixDeletionGuard(
718
- taskName: string
718
+ taskName: string,
719
719
  ): string | undefined {
720
720
  const definition = getTask(taskName);
721
721
  const parentId = definition?.matrixParentId?.trim();
@@ -773,7 +773,7 @@ export interface MatrixCancelResult {
773
773
  */
774
774
  export async function cancelPendingMatrixClones(
775
775
  parentName: string,
776
- reason = t("matrix.cancel.defaultReason")
776
+ reason = t("matrix.cancel.defaultReason"),
777
777
  ): Promise<MatrixCancelResult> {
778
778
  const parent = getTask(parentName);
779
779
  if (!parent?.matrix) {
@@ -793,7 +793,7 @@ export async function cancelPendingMatrixClones(
793
793
  console.log(
794
794
  `[matrix] ${parent.name}: не удалось очистить очередь: ${
795
795
  err instanceof Error ? err.message : String(err)
796
- }`
796
+ }`,
797
797
  );
798
798
  }
799
799
  }
@@ -824,14 +824,14 @@ export async function cancelPendingMatrixClones(
824
824
  undefined,
825
825
  clone.model ?? undefined,
826
826
  "skipped",
827
- "skipped"
827
+ "skipped",
828
828
  );
829
829
  cancelled.push(clone.name);
830
830
  } catch (err: any) {
831
831
  console.log(
832
832
  `[matrix] ${parent.name}: не удалось записать отмену клона ${clone.name}: ${
833
833
  err instanceof Error ? err.message : String(err)
834
- }`
834
+ }`,
835
835
  );
836
836
  }
837
837
  }
@@ -860,7 +860,7 @@ export function cloneFileKey(cloneName: string): string {
860
860
  * success/error/partial) и запускает matrix-complete, если он создан.
861
861
  */
862
862
  export async function finalizeMatrixIfComplete(
863
- cloneName: string
863
+ cloneName: string,
864
864
  ): Promise<MatrixAggregate | undefined> {
865
865
  const clone = getTask(cloneName);
866
866
  const parentId = clone?.matrixParentId?.trim();
@@ -908,7 +908,7 @@ export async function finalizeMatrixIfComplete(
908
908
  undefined,
909
909
  parent.model ?? undefined,
910
910
  "skipped",
911
- "skipped"
911
+ "skipped",
912
912
  );
913
913
  // Спринт 20: уведомление о завершении матрицы (partial / все упали / успех).
914
914
  void notifyMatrixCompletion({
@@ -923,7 +923,7 @@ export async function finalizeMatrixIfComplete(
923
923
  console.log(
924
924
  `[matrix] ${parent.name}: не удалось записать агрегат: ${
925
925
  err instanceof Error ? err.message : String(err)
926
- }`
926
+ }`,
927
927
  );
928
928
  }
929
929
 
@@ -937,7 +937,7 @@ export async function finalizeMatrixIfComplete(
937
937
  console.log(
938
938
  `[matrix] ${parent.name}: не удалось запустить агрегатор: ${
939
939
  err instanceof Error ? err.message : String(err)
940
- }`
940
+ }`,
941
941
  );
942
942
  }
943
943
  }
@@ -52,7 +52,7 @@ $appId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\power
52
52
  */
53
53
  export function buildNativeNotificationCommand(
54
54
  platform: NodeJS.Platform,
55
- message: NativeNotificationMessage
55
+ message: NativeNotificationMessage,
56
56
  ): NativeCommand {
57
57
  const title = (message.title ?? "OpenCode Scheduler").trim() || "OpenCode Scheduler";
58
58
  const body = String(message.body ?? "");
@@ -129,7 +129,7 @@ export interface NativeSendResult {
129
129
  */
130
130
  export async function sendNativeNotification(
131
131
  message: NativeNotificationMessage,
132
- options: SendNativeOptions = {}
132
+ options: SendNativeOptions = {},
133
133
  ): Promise<NativeSendResult> {
134
134
  const platform = options.platform ?? process.platform;
135
135
  const command = buildNativeNotificationCommand(platform, message);
@@ -52,7 +52,7 @@ function asDelaySeconds(value: unknown): number | undefined | "invalid" {
52
52
  */
53
53
  export function normalizeOneShotRunAt(
54
54
  input: OneShotInput,
55
- nowMs: number = Date.now()
55
+ nowMs: number = Date.now(),
56
56
  ): OneShotNormalization {
57
57
  const rawRunAt =
58
58
  typeof input.runAt === "string" ? input.runAt.trim() : undefined;
@@ -73,7 +73,7 @@ export function normalizeOneShotRunAt(
73
73
  return {
74
74
  ok: false,
75
75
  error:
76
- `runAt должен быть датой в формате ISO-8601, например ` +
76
+ "runAt должен быть датой в формате ISO-8601, например " +
77
77
  `2026-12-01T09:00:00Z (получено «${rawRunAt}»).`,
78
78
  };
79
79
  }
@@ -82,7 +82,7 @@ export function normalizeOneShotRunAt(
82
82
  ok: false,
83
83
  error:
84
84
  `runAt должен быть в будущем (получено «${rawRunAt}»). ` +
85
- `Для запуска сразу используйте run_task_now.`,
85
+ "Для запуска сразу используйте run_task_now.",
86
86
  };
87
87
  }
88
88
  return {
@@ -114,24 +114,48 @@ function pad(value: number): string {
114
114
  /**
115
115
  * Формат даты/времени для schtasks /sd и /st.
116
116
  *
117
- * Windows Task Scheduler ожидает дату в формате текущей локали. Плагин уже
118
- * использует DD.MM.YYYY для ONCE-заглушки, поэтому сохраняем этот формат
119
- * для совместимости с русской локалью (основной сценарий проекта).
117
+ * Windows Task Scheduler ожидает дату в формате текущей локали. На русской
118
+ * Windows — DD.MM.YYYY, на английской — M/d/yyyy и т.д. Жёсткий DD.MM.YYYY
119
+ * ломает создание one-shot и file/git/mcp-задач на не-RU Windows (P1-8).
120
+ * Вызывающий код (windows.ts) передаёт `dateFormat`, полученный из системной
121
+ * локали через PowerShell `(Get-Culture).DateTimeFormat.ShortDatePattern`.
122
+ *
123
+ * @param runAt — ISO-8601 время запуска.
124
+ * @param dateFormat — шаблон даты локали (например, "dd.MM.yyyy" или "M/d/yyyy").
125
+ * Если не задан — используется DD.MM.YYYY (по умолчанию RU).
120
126
  */
121
127
  export function buildWindowsOneShotFlags(
122
- runAt: string
128
+ runAt: string,
129
+ dateFormat?: string,
123
130
  ): ["/sc", "ONCE", "/sd", string, "/st", string] {
124
131
  const date = new Date(runAt);
132
+ const sd = dateFormat ? formatDateByLocalePattern(date, dateFormat) : `${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${date.getFullYear()}`;
125
133
  return [
126
134
  "/sc",
127
135
  "ONCE",
128
136
  "/sd",
129
- `${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${date.getFullYear()}`,
137
+ sd,
130
138
  "/st",
131
139
  `${pad(date.getHours())}:${pad(date.getMinutes())}`,
132
140
  ];
133
141
  }
134
142
 
143
+ /**
144
+ * Форматирует Date по шаблону локали Windows (.NET-формат, как возвращает
145
+ * (Get-Culture).DateTimeFormat.ShortDatePattern). Поддерживает d/dd, M/MM,
146
+ * y/yy/yyyy. Неизвестные символы копируются как есть.
147
+ */
148
+ export function formatDateByLocalePattern(date: Date, pattern: string): string {
149
+ const pad2 = (v: number) => String(v).padStart(2, "0");
150
+ return pattern
151
+ .replace(/yyyy/g, String(date.getFullYear()))
152
+ .replace(/yy/g, String(date.getFullYear()).slice(-2))
153
+ .replace(/MM/g, pad2(date.getMonth() + 1))
154
+ .replace(/M/g, String(date.getMonth() + 1))
155
+ .replace(/dd/g, pad2(date.getDate()))
156
+ .replace(/d/g, String(date.getDate()));
157
+ }
158
+
135
159
  /** Формат `at -t`: YYYYMMDDHHMM в локальном времени системы. */
136
160
  export function buildAtTimestamp(runAt: string): string {
137
161
  const date = new Date(runAt);
@@ -144,9 +168,35 @@ export function buildAtTimestamp(runAt: string): string {
144
168
  );
145
169
  }
146
170
 
171
+ /**
172
+ * Bash-команда для one-shot в launchd.
173
+ *
174
+ * StartCalendarInterval не поддерживает год: без защиты задача с runAt
175
+ * дальше чем через год сработала бы в ближайшую годовщину, а после
176
+ * выполнения — повторно через год. Гейт сравнивает now с runAt и ставит
177
+ * маркер, привязанный ко времени запуска.
178
+ */
179
+ export function buildOneShotGuardCommand(
180
+ command: string,
181
+ runAt: string,
182
+ stampPath: string,
183
+ ): string {
184
+ const epoch = Math.floor(new Date(runAt).getTime() / 1000);
185
+ const quote = (value: string) => `'${value.replace(/'/g, "'\\''")}'`;
186
+ return [
187
+ `stamp=${quote(stampPath)}`,
188
+ "[ -f \"$stamp\" ] && exit 0",
189
+ `[ "$(date +%s)" -lt ${epoch} ] && exit 0`,
190
+ "mkdir -p \"$(dirname \"$stamp\")\" 2>/dev/null || true",
191
+ ": > \"$stamp\" 2>/dev/null || true",
192
+ command,
193
+ ].join("; ");
194
+ }
195
+
147
196
  /**
148
197
  * StartCalendarInterval для launchd. launchd не поддерживает год, поэтому
149
- * плагин дополнительно выгружает plist после первого запуска (см. обёртку).
198
+ * обёртка дополнительно проверяет runAt и ставит маркер выполнения
199
+ * (см. buildOneShotGuardCommand).
150
200
  */
151
201
  export function buildLaunchdCalendar(runAt: string): {
152
202
  Month: number;
@@ -166,13 +216,13 @@ export function buildLaunchdCalendar(runAt: string): {
166
216
  /** Команда самоочистки launchd-агента после единственного запуска. */
167
217
  export function buildLaunchdOneShotCleanup(
168
218
  sanitizedName: string,
169
- profile: string = "default"
219
+ profile = "default",
170
220
  ): string {
171
221
  const label = launchdLabel(sanitizedName, profile);
172
222
  return (
173
- `launchctl bootout "gui/$(id -u)" ` +
223
+ "launchctl bootout \"gui/$(id -u)\" " +
174
224
  `"$HOME/Library/LaunchAgents/${label}.plist" ` +
175
- `>/dev/null 2>&1 || true`
225
+ ">/dev/null 2>&1 || true"
176
226
  );
177
227
  }
178
228
 
@@ -181,7 +231,7 @@ export function buildLaunchdOneShotCleanup(
181
231
  * `com.opencode.scheduler.<name>`; у не-default профиля свой префикс, чтобы
182
232
  * одноимённые задачи разных профилей не затирали plist друг друга.
183
233
  */
184
- export function launchdLabel(sanitizedName: string, profile: string = "default"): string {
234
+ export function launchdLabel(sanitizedName: string, profile = "default"): string {
185
235
  const base = `com.opencode.scheduler.${sanitizedName}`;
186
236
  if (profile === "default") return base;
187
237
  const scope = profile.replace(/[^A-Za-z0-9_.-]/g, "-");