agent-steward 0.0.4 → 0.0.6

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 (279) hide show
  1. package/CHANGELOG.md +309 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +55 -8
  4. package/ROADMAP-STRATEGY.md +22 -19
  5. package/ROADMAP.md +230 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +356 -0
  9. package/dist/core/analytics.d.ts +6 -0
  10. package/dist/core/analytics.d.ts.map +1 -1
  11. package/dist/core/analytics.js +20 -3
  12. package/dist/core/audit.d.ts +6 -0
  13. package/dist/core/audit.d.ts.map +1 -1
  14. package/dist/core/audit.js +24 -0
  15. package/dist/core/budget.d.ts +118 -0
  16. package/dist/core/budget.d.ts.map +1 -0
  17. package/dist/core/budget.js +206 -0
  18. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  19. package/dist/core/cron-to-schtasks.js +38 -0
  20. package/dist/core/dry-run.d.ts +26 -1
  21. package/dist/core/dry-run.d.ts.map +1 -1
  22. package/dist/core/dry-run.js +199 -8
  23. package/dist/core/execution.d.ts +203 -0
  24. package/dist/core/execution.d.ts.map +1 -0
  25. package/dist/core/execution.js +309 -0
  26. package/dist/core/feedback.d.ts +192 -0
  27. package/dist/core/feedback.d.ts.map +1 -0
  28. package/dist/core/feedback.js +426 -0
  29. package/dist/core/gate-integrity.d.ts +71 -0
  30. package/dist/core/gate-integrity.d.ts.map +1 -0
  31. package/dist/core/gate-integrity.js +275 -0
  32. package/dist/core/git-trigger.d.ts.map +1 -1
  33. package/dist/core/git-trigger.js +14 -2
  34. package/dist/core/guard-run.d.ts +4 -0
  35. package/dist/core/guard-run.d.ts.map +1 -0
  36. package/dist/core/guard-run.js +101 -0
  37. package/dist/core/guard.d.ts +52 -0
  38. package/dist/core/guard.d.ts.map +1 -0
  39. package/dist/core/guard.js +362 -0
  40. package/dist/core/local-ai.d.ts.map +1 -1
  41. package/dist/core/local-ai.js +7 -3
  42. package/dist/core/lock.d.ts +41 -0
  43. package/dist/core/lock.d.ts.map +1 -1
  44. package/dist/core/lock.js +141 -29
  45. package/dist/core/matrix.d.ts +8 -0
  46. package/dist/core/matrix.d.ts.map +1 -1
  47. package/dist/core/matrix.js +132 -17
  48. package/dist/core/mission.d.ts +103 -0
  49. package/dist/core/mission.d.ts.map +1 -0
  50. package/dist/core/mission.js +374 -0
  51. package/dist/core/opencode-models.d.ts +2 -2
  52. package/dist/core/opencode-models.d.ts.map +1 -1
  53. package/dist/core/opencode-models.js +28 -21
  54. package/dist/core/opencode-usage.d.ts +35 -0
  55. package/dist/core/opencode-usage.d.ts.map +1 -0
  56. package/dist/core/opencode-usage.js +132 -0
  57. package/dist/core/pipeline-apply.d.ts +38 -0
  58. package/dist/core/pipeline-apply.d.ts.map +1 -0
  59. package/dist/core/pipeline-apply.js +117 -0
  60. package/dist/core/pipeline-io.d.ts +13 -0
  61. package/dist/core/pipeline-io.d.ts.map +1 -0
  62. package/dist/core/pipeline-io.js +78 -0
  63. package/dist/core/pipeline-map.d.ts +52 -0
  64. package/dist/core/pipeline-map.d.ts.map +1 -0
  65. package/dist/core/pipeline-map.js +208 -0
  66. package/dist/core/pipeline-spec.d.ts +109 -0
  67. package/dist/core/pipeline-spec.d.ts.map +1 -0
  68. package/dist/core/pipeline-spec.js +554 -0
  69. package/dist/core/ps-wrapper.d.ts +27 -2
  70. package/dist/core/ps-wrapper.d.ts.map +1 -1
  71. package/dist/core/ps-wrapper.js +424 -65
  72. package/dist/core/record-history.d.ts.map +1 -1
  73. package/dist/core/record-history.js +206 -33
  74. package/dist/core/router/rules.d.ts.map +1 -1
  75. package/dist/core/router/rules.js +6 -0
  76. package/dist/core/run-mode.d.ts +12 -0
  77. package/dist/core/run-mode.d.ts.map +1 -0
  78. package/dist/core/run-mode.js +17 -0
  79. package/dist/core/scheduler/linux.d.ts +8 -1
  80. package/dist/core/scheduler/linux.d.ts.map +1 -1
  81. package/dist/core/scheduler/linux.js +34 -9
  82. package/dist/core/scheduler/logs.d.ts +4 -0
  83. package/dist/core/scheduler/logs.d.ts.map +1 -1
  84. package/dist/core/scheduler/logs.js +25 -1
  85. package/dist/core/scheduler/mac.d.ts +44 -2
  86. package/dist/core/scheduler/mac.d.ts.map +1 -1
  87. package/dist/core/scheduler/mac.js +126 -15
  88. package/dist/core/scheduler/windows.d.ts.map +1 -1
  89. package/dist/core/scheduler/windows.js +15 -12
  90. package/dist/core/secrets.d.ts.map +1 -1
  91. package/dist/core/secrets.js +18 -8
  92. package/dist/core/self-analysis.d.ts +32 -2
  93. package/dist/core/self-analysis.d.ts.map +1 -1
  94. package/dist/core/self-analysis.js +38 -27
  95. package/dist/core/shutdown.d.ts +33 -2
  96. package/dist/core/shutdown.d.ts.map +1 -1
  97. package/dist/core/shutdown.js +58 -2
  98. package/dist/core/structured-log.d.ts +37 -1
  99. package/dist/core/structured-log.d.ts.map +1 -1
  100. package/dist/core/structured-log.js +37 -0
  101. package/dist/core/usage-surface.d.ts +25 -0
  102. package/dist/core/usage-surface.d.ts.map +1 -0
  103. package/dist/core/usage-surface.js +41 -0
  104. package/dist/core/worktree-run.d.ts +4 -0
  105. package/dist/core/worktree-run.d.ts.map +1 -0
  106. package/dist/core/worktree-run.js +164 -0
  107. package/dist/core/worktree.d.ts +115 -0
  108. package/dist/core/worktree.d.ts.map +1 -0
  109. package/dist/core/worktree.js +462 -0
  110. package/dist/core/wrappers/bash.d.ts +19 -0
  111. package/dist/core/wrappers/bash.d.ts.map +1 -1
  112. package/dist/core/wrappers/bash.js +230 -27
  113. package/dist/db/capability-repo.d.ts +43 -2
  114. package/dist/db/capability-repo.d.ts.map +1 -1
  115. package/dist/db/capability-repo.js +96 -11
  116. package/dist/db/history-repo.d.ts +70 -5
  117. package/dist/db/history-repo.d.ts.map +1 -1
  118. package/dist/db/history-repo.js +170 -29
  119. package/dist/db/metrics-repo.d.ts +20 -2
  120. package/dist/db/metrics-repo.d.ts.map +1 -1
  121. package/dist/db/metrics-repo.js +35 -13
  122. package/dist/db/migrate.d.ts.map +1 -1
  123. package/dist/db/migrate.js +37 -17
  124. package/dist/db/recovery.d.ts +3 -1
  125. package/dist/db/recovery.d.ts.map +1 -1
  126. package/dist/db/recovery.js +11 -5
  127. package/dist/db/run-journal.d.ts +33 -5
  128. package/dist/db/run-journal.d.ts.map +1 -1
  129. package/dist/db/run-journal.js +78 -14
  130. package/dist/db/run-resume.d.ts +5 -0
  131. package/dist/db/run-resume.d.ts.map +1 -1
  132. package/dist/db/run-resume.js +9 -2
  133. package/dist/db/runs-repo.d.ts +19 -2
  134. package/dist/db/runs-repo.d.ts.map +1 -1
  135. package/dist/db/runs-repo.js +91 -60
  136. package/dist/db/schema.d.ts +2 -2
  137. package/dist/db/schema.d.ts.map +1 -1
  138. package/dist/db/schema.js +132 -2
  139. package/dist/db/templates-repo.d.ts +2 -2
  140. package/dist/db/templates-repo.d.ts.map +1 -1
  141. package/dist/db/templates-repo.js +5 -3
  142. package/dist/history.d.ts +7 -2
  143. package/dist/history.d.ts.map +1 -1
  144. package/dist/history.js +4 -2
  145. package/dist/hook-output.d.ts +2 -0
  146. package/dist/hook-output.d.ts.map +1 -0
  147. package/dist/hook-output.js +31 -0
  148. package/dist/i18n.d.ts +5 -0
  149. package/dist/i18n.d.ts.map +1 -1
  150. package/dist/i18n.js +11 -4
  151. package/dist/index.d.ts +375 -47
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +1344 -192
  154. package/dist/notifications.d.ts +53 -2
  155. package/dist/notifications.d.ts.map +1 -1
  156. package/dist/notifications.js +168 -21
  157. package/dist/profiles.d.ts.map +1 -1
  158. package/dist/profiles.js +82 -10
  159. package/dist/rpc.d.ts +354 -0
  160. package/dist/rpc.d.ts.map +1 -1
  161. package/dist/rpc.js +145 -0
  162. package/dist/server.d.ts +32 -2
  163. package/dist/server.d.ts.map +1 -1
  164. package/dist/server.js +154 -30
  165. package/dist/settings.d.ts +44 -2
  166. package/dist/settings.d.ts.map +1 -1
  167. package/dist/settings.js +85 -3
  168. package/dist/shared/jobs-view.d.ts +1 -1
  169. package/dist/shared/jobs-view.d.ts.map +1 -1
  170. package/dist/shared/jobs-view.js +2 -0
  171. package/dist/task-transfer.d.ts +21 -0
  172. package/dist/task-transfer.d.ts.map +1 -1
  173. package/dist/task-transfer.js +64 -3
  174. package/dist/templates.d.ts +2 -2
  175. package/dist/templates.d.ts.map +1 -1
  176. package/dist/templates.js +3 -3
  177. package/dist/types.d.ts +22 -2
  178. package/dist/types.d.ts.map +1 -1
  179. package/dist/workspaces.d.ts.map +1 -1
  180. package/dist/workspaces.js +34 -11
  181. package/docs/ARCHITECTURE.md +319 -66
  182. package/docs/COMPATIBILITY.md +2 -2
  183. package/docs/CONCEPT.md +18 -4
  184. package/docs/CROSS_PLATFORM.ru.md +20 -0
  185. package/docs/CROSS_PLATFORM.zh.md +18 -0
  186. package/docs/EXECUTION-LOOP.md +28 -10
  187. package/docs/FEATURES.md +129 -7
  188. package/docs/FEATURES.zh.md +97 -6
  189. package/docs/MIGRATION.md +2 -2
  190. package/docs/PIPELINE.md +293 -0
  191. package/docs/QA-A2-GUI-TUI.md +205 -0
  192. package/docs/README.ru.md +43 -4
  193. package/docs/README.zh.md +44 -4
  194. package/docs/SAFETY.md +23 -3
  195. package/gui-experimental.cjs +9 -8
  196. package/locales/en.json +58 -3
  197. package/locales/ru.json +58 -3
  198. package/locales/zh.json +58 -3
  199. package/opencode.pipeline.yaml +35 -0
  200. package/package.json +36 -4
  201. package/scripts/check-eslint-baseline.mjs +139 -0
  202. package/scripts/gen-test-plan-counters.mjs +117 -0
  203. package/scripts/github-ci-fetch.ps1 +37 -0
  204. package/scripts/pl-commit.ps1 +112 -0
  205. package/scripts/qa-a2-commit.ps1 +104 -0
  206. package/scripts/test-home.mjs +107 -0
  207. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  208. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  209. package/src/cli.ts +417 -0
  210. package/src/core/analytics.ts +27 -4
  211. package/src/core/audit.ts +25 -0
  212. package/src/core/budget.ts +340 -0
  213. package/src/core/cron-to-schtasks.ts +42 -0
  214. package/src/core/dry-run.ts +235 -12
  215. package/src/core/execution.ts +538 -0
  216. package/src/core/feedback.ts +582 -0
  217. package/src/core/file-watcher.ts +2 -2
  218. package/src/core/gate-integrity.ts +330 -0
  219. package/src/core/git-trigger.ts +18 -5
  220. package/src/core/guard-run.ts +119 -0
  221. package/src/core/guard.ts +431 -0
  222. package/src/core/local-ai.ts +7 -3
  223. package/src/core/lock.ts +178 -37
  224. package/src/core/matrix.ts +158 -52
  225. package/src/core/mission.ts +531 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/opencode-models.ts +30 -21
  228. package/src/core/opencode-usage.ts +182 -0
  229. package/src/core/pipeline-apply.ts +158 -0
  230. package/src/core/pipeline-io.ts +96 -0
  231. package/src/core/pipeline-map.ts +283 -0
  232. package/src/core/pipeline-spec.ts +775 -0
  233. package/src/core/ps-wrapper.ts +435 -66
  234. package/src/core/record-history.ts +258 -81
  235. package/src/core/router/rules.ts +6 -0
  236. package/src/core/run-mode.ts +19 -0
  237. package/src/core/schedule-gate.ts +1 -1
  238. package/src/core/scheduler/at-fallback.ts +1 -1
  239. package/src/core/scheduler/linux.ts +40 -11
  240. package/src/core/scheduler/logs.ts +34 -3
  241. package/src/core/scheduler/mac.ts +174 -14
  242. package/src/core/scheduler/registry.ts +2 -2
  243. package/src/core/scheduler/windows.ts +19 -15
  244. package/src/core/secrets.ts +26 -19
  245. package/src/core/self-analysis.ts +75 -29
  246. package/src/core/shutdown.ts +90 -4
  247. package/src/core/structured-log.ts +89 -5
  248. package/src/core/telegram.ts +2 -2
  249. package/src/core/triage-worker.ts +7 -7
  250. package/src/core/triage.ts +2 -2
  251. package/src/core/usage-surface.ts +70 -0
  252. package/src/core/worktree-run.ts +199 -0
  253. package/src/core/worktree.ts +600 -0
  254. package/src/core/wrappers/bash.ts +248 -26
  255. package/src/db/capability-repo.ts +127 -10
  256. package/src/db/history-repo.ts +281 -40
  257. package/src/db/metrics-repo.ts +40 -13
  258. package/src/db/migrate.ts +57 -32
  259. package/src/db/recovery.ts +12 -5
  260. package/src/db/run-journal.ts +100 -13
  261. package/src/db/run-resume.ts +17 -1
  262. package/src/db/runs-repo.ts +147 -65
  263. package/src/db/schema.ts +134 -2
  264. package/src/db/templates-repo.ts +5 -3
  265. package/src/gui.tsx +438 -18
  266. package/src/history.ts +11 -4
  267. package/src/hook-output.ts +39 -0
  268. package/src/i18n.ts +12 -4
  269. package/src/index.ts +1902 -320
  270. package/src/notifications.ts +227 -47
  271. package/src/profiles.ts +88 -10
  272. package/src/rpc.ts +158 -0
  273. package/src/server.ts +201 -41
  274. package/src/settings.ts +125 -5
  275. package/src/shared/jobs-view.ts +3 -1
  276. package/src/task-transfer.ts +90 -6
  277. package/src/templates.ts +3 -3
  278. package/src/types.ts +23 -2
  279. package/src/workspaces.ts +37 -14
@@ -89,19 +89,27 @@ export class LinuxScheduler extends PosixSchedulerBase {
89
89
  maxBuffer: 10 * 1024 * 1024,
90
90
  });
91
91
  return stdout;
92
- } catch (err: any) {
93
- const stderr = String(err?.stderr ?? "");
92
+ } catch (err: unknown) {
93
+ const stderrRaw = (err as { stderr?: unknown } | undefined)?.stderr;
94
+ const stderr = typeof stderrRaw === "string" ? stderrRaw : String(stderrRaw ?? "");
94
95
  // "no crontab for user" — это нормальное состояние. Любую другую ошибку
95
96
  // (нет доступа, сбой crontab) нельзя превращать в пустой crontab: иначе
96
97
  // последующая запись затрёт пользовательские задания.
97
- if (/no crontab/i.test(stderr) || /no crontab/i.test(String(err?.message ?? ""))) {
98
+ if (/no crontab/i.test(stderr) || /no crontab/i.test(String((err as Error | undefined)?.message ?? ""))) {
98
99
  return "";
99
100
  }
100
- throw new Error(`Не удалось прочитать crontab: ${stderr.trim() || err?.message || err}`);
101
+ throw new Error(`Не удалось прочитать crontab: ${stderr.trim() || (err as Error | undefined)?.message || String(err)}`);
101
102
  }
102
103
  }
103
104
 
104
- /** Убирает управляемый блок плагина из текста crontab. */
105
+ /**
106
+ * Убирает управляемый блок плагина из текста crontab.
107
+ *
108
+ * B9: удаляются только строки между парными маркерами. Незакрытый блок
109
+ * (маркер начала без конца) — fail-closed: бросаем ошибку, чтобы вызывающий
110
+ * не записал crontab и пользовательские задания после маркера не пропали.
111
+ * Строки вне маркеров сохраняются байт-в-байт, включая пустые.
112
+ */
105
113
  private stripBlock(content: string): string {
106
114
  // Совместимость: до появления профилей блок назывался без суффикса.
107
115
  // Он принадлежит профилю default; другие профили его не трогают.
@@ -119,18 +127,36 @@ export class LinuxScheduler extends PosixSchedulerBase {
119
127
  const lines = content.split(/\r?\n/);
120
128
  const result: string[] = [];
121
129
  let inside = false;
122
- for (const line of lines) {
123
- if (isBegin(line.trim())) {
130
+ let openAt = 0;
131
+ for (let index = 0; index < lines.length; index += 1) {
132
+ const line = lines[index];
133
+ const trimmed = line.trim();
134
+ if (isBegin(trimmed)) {
135
+ if (inside) {
136
+ throw new Error(
137
+ `crontab: вложенный маркер начала блока на строке ${index + 1} ` +
138
+ `(предыдущий блок открыт на строке ${openAt}). Файл не изменён.`,
139
+ );
140
+ }
124
141
  inside = true;
142
+ openAt = index + 1;
125
143
  continue;
126
144
  }
127
- if (isEnd(line.trim())) {
145
+ if (inside && isEnd(trimmed)) {
128
146
  inside = false;
129
147
  continue;
130
148
  }
149
+ // Строки внутри блока удаляются; всё остальное (включая «сиротский»
150
+ // маркер конца) остаётся без изменений.
131
151
  if (!inside) result.push(line);
132
152
  }
133
- return result.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd();
153
+ if (inside) {
154
+ throw new Error(
155
+ `crontab: незакрытый блок плагина с строки ${openAt} — ` +
156
+ "маркер конца не найден. Файл не изменён.",
157
+ );
158
+ }
159
+ return result.join("\n");
134
160
  }
135
161
 
136
162
  /** Записывает crontab через stdin: `crontab -`. */
@@ -165,7 +191,10 @@ export class LinuxScheduler extends PosixSchedulerBase {
165
191
  async () => {
166
192
  const entries = await this.registry.load();
167
193
  const current = await this.readCrontab();
168
- const base = this.stripBlock(current);
194
+ // B9: stripBlock сохраняет содержимое вне маркеров. Отрезаем только
195
+ // хвостовые переводы строк, чтобы повторные rebuild не копили пустые
196
+ // строки; одна финальная добавляется ниже.
197
+ const base = this.stripBlock(current).replace(/\n+$/, "");
169
198
  const block = this.renderBlock(entries);
170
199
 
171
200
  // Пустой блок (нет задач) не пишем, чтобы не оставлять мусор в crontab.
@@ -173,7 +202,7 @@ export class LinuxScheduler extends PosixSchedulerBase {
173
202
  .split("\n")
174
203
  .some((line) => line.trim().startsWith("# task:"));
175
204
  const next = [base, hasTasks ? block : ""].filter(Boolean).join("\n");
176
- await this.writeCrontab(next);
205
+ await this.writeCrontab(next ? `${next}\n` : "");
177
206
  },
178
207
  { timeoutMs: 15000, staleMs: 60000 },
179
208
  );
@@ -1,6 +1,36 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { LOG_DIR, sanitizeName } from "../../types.js";
4
+ import { extractLastRunLog } from "../mission.js";
5
+
6
+ /** Codes returned by Windows/PowerShell while a log file is still held by the writer. */
7
+ export function isRetriableLogReadError(code: unknown): boolean {
8
+ return code === "EBUSY" || code === "EPERM" || code === "EACCES";
9
+ }
10
+
11
+ /** Retry fs.readFile while the writer still holds the log (emit_event / immediate get_task_logs race). */
12
+ export async function readLogWithRetry(
13
+ logPath: string,
14
+ attempts = 6,
15
+ delayMs = 50,
16
+ ): Promise<string> {
17
+ let lastErr: unknown;
18
+ for (let i = 0; i < attempts; i++) {
19
+ try {
20
+ return await fs.readFile(logPath, "utf8");
21
+ } catch (err: unknown) {
22
+ lastErr = err;
23
+ if (
24
+ !isRetriableLogReadError((err as NodeJS.ErrnoException).code) ||
25
+ i === attempts - 1
26
+ ) {
27
+ throw err;
28
+ }
29
+ await new Promise((resolve) => setTimeout(resolve, delayMs * (i + 1)));
30
+ }
31
+ }
32
+ throw lastErr;
33
+ }
4
34
 
5
35
  /**
6
36
  * Читает файл лога задачи и возвращает последние 50 строк.
@@ -15,7 +45,8 @@ export async function getTaskLogs(
15
45
  const logPath = path.join(LOG_DIR, `${sanitizeName(name)}.log`);
16
46
  try {
17
47
  // PowerShell 5.1 пишет UTF-8 с BOM — убираем его, чтобы GUI не показывал мусор.
18
- const content = (await fs.readFile(logPath, "utf8")).replace(/^\uFEFF/, "");
48
+ // Лог дописывается между запусками: показываем только последний прогон.
49
+ const content = extractLastRunLog(await readLogWithRetry(logPath));
19
50
  const lines = content.split(/\r?\n/).filter((line) => line.trim());
20
51
  if (lines.length === 0) {
21
52
  return {
@@ -25,8 +56,8 @@ export async function getTaskLogs(
25
56
  }
26
57
  const last = lines.slice(-Math.max(1, Math.min(limit, 1000)));
27
58
  return { logs: last.join("\n") };
28
- } catch (err: any) {
29
- if (err.code === "ENOENT") {
59
+ } catch (err: unknown) {
60
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
30
61
  return {
31
62
  logs: "",
32
63
  error: `Лог задачи "${name}" не найден по пути ${logPath} (задача ещё не запускалась).`,
@@ -16,6 +16,12 @@ import type { RegistryEntry } from "./registry.js";
16
16
 
17
17
  const execFileAsync = promisify(execFile);
18
18
 
19
+ /** O-2: неудачная уборка temp/plist не проглатывается молча. */
20
+ function warnCleanupFailure(target: string, error: unknown): void {
21
+ const reason = error instanceof Error ? error.message : String(error);
22
+ console.warn(`[agent-steward] Не удалось удалить plist «${target}»: ${reason}`);
23
+ }
24
+
19
25
  /** Папка пользовательских LaunchAgents. */
20
26
  const LAUNCH_AGENTS_DIR = path.join(os.homedir(), "Library", "LaunchAgents");
21
27
 
@@ -247,12 +253,147 @@ function buildPlist(label: string, entry: RegistryEntry): string {
247
253
  ].join("\n");
248
254
  }
249
255
 
256
+ /** Ошибка запуска launchctl с командой, кодом выхода и stderr. */
257
+ export function describeLaunchctlError(args: string[], err: unknown): string {
258
+ const error = err as {
259
+ code?: number | string;
260
+ signal?: string;
261
+ stderr?: string | Buffer;
262
+ stdout?: string | Buffer;
263
+ message?: string;
264
+ };
265
+ const stderr = String(error.stderr ?? "").trim();
266
+ const stdout = String(error.stdout ?? "").trim();
267
+ const detail = stderr || stdout || error.message || "вывод пуст";
268
+ const status =
269
+ error.code !== undefined
270
+ ? `код ${String(error.code)}`
271
+ : error.signal
272
+ ? `сигнал ${error.signal}`
273
+ : "без кода выхода";
274
+ return `launchctl ${args.join(" ")}: ${status}: ${detail}`;
275
+ }
276
+
277
+ /**
278
+ * Запускает launchctl и либо пробрасывает ошибку с stderr/exit code,
279
+ * либо глотает её (unload незагруженного агента — штатная ситуация).
280
+ */
281
+ export async function runLaunchctl(
282
+ runner: (args: string[]) => Promise<unknown>,
283
+ args: string[],
284
+ options: { tolerateFailure?: boolean } = {},
285
+ ): Promise<void> {
286
+ try {
287
+ await runner(args);
288
+ } catch (err) {
289
+ if (options.tolerateFailure) return;
290
+ const failure = new Error(describeLaunchctlError(args, err)) as Error & {
291
+ cause?: unknown;
292
+ };
293
+ // target/lib проекта не включает ErrorOptions, поэтому cause ставим вручную.
294
+ failure.cause = err;
295
+ throw failure;
296
+ }
297
+ }
298
+
299
+ /** Команды launchctl при установке записи. */
300
+ export interface LaunchctlInstallPlan {
301
+ /** unload перед перезаписью plist (best effort: агент мог быть не загружен). */
302
+ beforeWrite: string[];
303
+ /** load после записи; null — задача на паузе, загружать её нельзя. */
304
+ afterWrite: string[] | null;
305
+ }
306
+
307
+ /**
308
+ * B5: `load -w` не только загружает агент, но и снимает Disabled,
309
+ * поэтому для приостановленной задачи его вызывать нельзя — иначе
310
+ * установка молча возобновляет задачу. Вместо этого `unload -w`
311
+ * фиксирует Disabled, чтобы launchd не загрузил агент при следующем входе.
312
+ */
313
+ export function planLaunchctlInstall(
314
+ paused: boolean,
315
+ plistPath: string,
316
+ ): LaunchctlInstallPlan {
317
+ if (paused) {
318
+ return {
319
+ beforeWrite: ["unload", "-w", plistPath],
320
+ afterWrite: null,
321
+ };
322
+ }
323
+ return {
324
+ beforeWrite: ["unload", plistPath],
325
+ afterWrite: ["load", "-w", plistPath],
326
+ };
327
+ }
328
+
329
+ /**
330
+ * ML-1: macOS 13 (Darwin 22) заменяет `load`/`unload` на `bootstrap`/`bootout`
331
+ * с явным доменом `gui/<uid>`. `-w` у legacy-команды здесь не нужен: bootstrap
332
+ * сам регистрирует агент, а bootout — снимает регистрацию.
333
+ */
334
+ export function modernLaunchctlArgs(args: string[], uid: number = process.getuid?.() ?? 501): string[] {
335
+ const [command, ...rest] = args;
336
+ if (command !== "load" && command !== "unload") return args;
337
+ const plist = rest.filter((part) => part !== "-w");
338
+ return [command === "load" ? "bootstrap" : "bootout", `gui/${uid}`, ...plist];
339
+ }
340
+
341
+ /** Современные команды доступны на macOS 13+ (Darwin 22+). */
342
+ export function supportsModernLaunchctl(
343
+ platform: NodeJS.Platform = process.platform,
344
+ release: string = os.release(),
345
+ ): boolean {
346
+ if (platform !== "darwin") return true;
347
+ const darwinMajor = Number.parseInt(release.split(".")[0] ?? "", 10);
348
+ return Number.isFinite(darwinMajor) ? darwinMajor >= 22 : true;
349
+ }
350
+
351
+ /** Признак того, что launchctl не знает bootstrap/bootout (максимально старая macOS). */
352
+ function needsLegacyLaunchctlFallback(error: unknown): boolean {
353
+ const source = error as { message?: unknown; stderr?: unknown } | null;
354
+ const text = `${String(source?.message ?? "")}\n${String(source?.stderr ?? "")}`;
355
+ return /unrecognized subcommand|unknown subcommand|invalid subcommand|unrecognized option|Usage:/i.test(
356
+ text,
357
+ );
358
+ }
359
+
360
+ /**
361
+ * Выполняет launchctl через современные команды; при отсутствии поддержки
362
+ * (macOS < 13 или «unrecognized subcommand») повторяет legacy-аргументы.
363
+ */
364
+ export async function runLaunchctlModern(
365
+ runner: (args: string[]) => Promise<unknown>,
366
+ args: string[],
367
+ options: { tolerateFailure?: boolean } = {},
368
+ ): Promise<void> {
369
+ const modern = supportsModernLaunchctl() ? modernLaunchctlArgs(args) : args;
370
+ await runLaunchctl(
371
+ async (call) => {
372
+ try {
373
+ await runner(call);
374
+ } catch (err) {
375
+ if (modern !== args && needsLegacyLaunchctlFallback(err)) {
376
+ await runner(args);
377
+ return;
378
+ }
379
+ throw err;
380
+ }
381
+ },
382
+ modern,
383
+ options,
384
+ );
385
+ }
386
+
250
387
  /**
251
388
  * Бэкенд планировщика macOS на основе launchd.
252
389
  *
253
390
  * Каждая задача — отдельный LaunchAgent:
254
391
  * ~/Library/LaunchAgents/com.opencode.scheduler.<name>.plist
255
- * Управление — через launchctl load/unload -w.
392
+ * Управление — через `launchctl bootstrap/bootout` (macOS ≥13), с фолбэком
393
+ * на legacy `load/unload -w` для более старых систем. `planLaunchctlInstall`
394
+ * намеренно остаётся на legacy-командах: обратная совместимость контракта.
395
+ * Ошибки загрузки не глотаются: битый plist должен вернуть ошибку установки,
396
+ * а не оставить задачу молча незапланированной.
256
397
  */
257
398
  export class MacScheduler extends PosixSchedulerBase {
258
399
  readonly platform: NodeJS.Platform = "darwin";
@@ -288,34 +429,53 @@ export class MacScheduler extends PosixSchedulerBase {
288
429
  return path.join(LAUNCH_AGENTS_DIR, `${this.label(name)}.plist`);
289
430
  }
290
431
 
291
- /** Выполняет launchctl, не считая ошибку фатальной (unload несуществующего). */
292
- private async launchctl(args: string[]): Promise<void> {
293
- try {
294
- await execFileAsync("launchctl", args, { maxBuffer: 1024 * 1024 });
295
- } catch {
296
- // launchctl возвращает ошибку, если агент ещё не загружен — это нормально.
297
- }
432
+ /** Выполняет launchctl; tolerateFailure оставлен только для bootout/unload. */
433
+ private async launchctl(
434
+ args: string[],
435
+ options: { tolerateFailure?: boolean } = {},
436
+ ): Promise<void> {
437
+ await runLaunchctlModern(
438
+ (call) => execFileAsync("launchctl", call, { maxBuffer: 1024 * 1024 }),
439
+ args,
440
+ options,
441
+ );
298
442
  }
299
443
 
300
444
  protected async installEntry(entry: RegistryEntry): Promise<void> {
301
445
  await fs.mkdir(LAUNCH_AGENTS_DIR, { recursive: true });
302
446
  const plistPath = this.plistPath(entry.name);
303
- await this.launchctl(["unload", plistPath]);
304
- await fs.writeFile(plistPath, buildPlist(this.label(entry.name), entry), "utf8");
305
- await this.launchctl(["load", "-w", plistPath]);
447
+ const plan = planLaunchctlInstall(entry.paused, plistPath);
448
+ // Агент мог быть не загружен — это не ошибка.
449
+ await this.launchctl(plan.beforeWrite, { tolerateFailure: true });
450
+ // Пишем в уникальный temp и переименовываем: launchctl не должен увидеть
451
+ // полузаписанный plist, если процесс упадёт посреди записи.
452
+ const tmpPath = `${plistPath}.${process.pid}.${Date.now()}.tmp`;
453
+ try {
454
+ await fs.writeFile(tmpPath, buildPlist(this.label(entry.name), entry), "utf8");
455
+ await fs.rename(tmpPath, plistPath);
456
+ } catch (error) {
457
+ await fs.rm(tmpPath, { force: true }).catch((cleanupError: unknown) =>
458
+ warnCleanupFailure(tmpPath, cleanupError),
459
+ );
460
+ throw error;
461
+ }
462
+ if (plan.afterWrite) {
463
+ await this.launchctl(plan.afterWrite);
464
+ }
306
465
  }
307
466
 
308
467
  protected async uninstallEntry(entry: RegistryEntry): Promise<void> {
309
468
  const plistPath = this.plistPath(entry.name);
310
- await this.launchctl(["unload", "-w", plistPath]);
311
- await fs.unlink(plistPath).catch(() => {});
469
+ await this.launchctl(["unload", "-w", plistPath], { tolerateFailure: true });
470
+ await fs.unlink(plistPath).catch((error: unknown) => warnCleanupFailure(plistPath, error));
312
471
  }
313
472
 
314
473
  protected async applyPause(entry: RegistryEntry, paused: boolean): Promise<void> {
315
474
  const plistPath = this.plistPath(entry.name);
316
475
  if (paused) {
317
- await this.launchctl(["unload", "-w", plistPath]);
476
+ await this.launchctl(["unload", "-w", plistPath], { tolerateFailure: true });
318
477
  } else {
478
+ // Возобновление не должно «удаваться» молча при битом plist.
319
479
  await this.launchctl(["load", "-w", plistPath]);
320
480
  }
321
481
  }
@@ -62,8 +62,8 @@ export class TaskRegistry {
62
62
  let raw: string;
63
63
  try {
64
64
  raw = await fs.readFile(this.file, "utf8");
65
- } catch (err: any) {
66
- if (err?.code === "ENOENT") {
65
+ } catch (err: unknown) {
66
+ if ((err as NodeJS.ErrnoException | undefined)?.code === "ENOENT") {
67
67
  // Карантин уже переместил файл. Пустой реестр нельзя выдавать за
68
68
  // «задач нет»: rebuildCrontab вычистил бы все cron-строки плагина.
69
69
  const blocked = await fs.readFile(this.blockedPath, "utf8").catch(() => null);
@@ -15,25 +15,29 @@ import type {
15
15
 
16
16
  const execFileAsync = promisify(execFile);
17
17
 
18
- /** Кэш формата даты локали Windows (ShortDatePattern), полученного через PowerShell. */
19
- let windowsDateFormatCache: string | null = null;
18
+ /** Кэш формата даты локали Windows (ShortDatePattern), полученного через PowerShell.
19
+ * Храним промис, а не готовую строку: параллельные вызовы ждут один и тот же
20
+ * результат и не запускают PowerShell по несколько раз (гонка при await). */
21
+ let windowsDateFormatCache: Promise<string> | null = null;
20
22
 
21
23
  /** Определяет формат даты системной локали через PowerShell (P1-8). */
22
24
  async function getWindowsDateFormat(): Promise<string> {
23
- if (windowsDateFormatCache !== null) return windowsDateFormatCache;
24
- try {
25
- const { stdout } = await execFileAsync(
26
- "powershell.exe",
27
- ["-NoProfile", "-Command", "(Get-Culture).DateTimeFormat.ShortDatePattern"],
28
- { maxBuffer: MAX_OUTPUT_BUFFER },
29
- );
30
- const pattern = String(stdout).trim();
31
- windowsDateFormatCache = pattern || "dd.MM.yyyy";
32
- return windowsDateFormatCache;
33
- } catch {
34
- windowsDateFormatCache = "dd.MM.yyyy";
35
- return windowsDateFormatCache;
25
+ if (windowsDateFormatCache === null) {
26
+ windowsDateFormatCache = (async () => {
27
+ try {
28
+ const { stdout } = await execFileAsync(
29
+ "powershell.exe",
30
+ ["-NoProfile", "-Command", "(Get-Culture).DateTimeFormat.ShortDatePattern"],
31
+ { maxBuffer: MAX_OUTPUT_BUFFER },
32
+ );
33
+ const pattern = String(stdout).trim();
34
+ return pattern || "dd.MM.yyyy";
35
+ } catch {
36
+ return "dd.MM.yyyy";
37
+ }
38
+ })();
36
39
  }
40
+ return windowsDateFormatCache;
37
41
  }
38
42
 
39
43
  /** Форматирует дату «никогда» (заглушка для file/git/mcp-триггеров) в формате локали. */
@@ -36,8 +36,9 @@ const KEY_BYTES = 32;
36
36
  * используется из CLI/GUI/плагина, переписывать его на async нельзя.
37
37
  */
38
38
  const SECRETS_LOCK_FILE = `${SECRETS_FILE}.lock`;
39
- const SECRETS_LOCK_STALE_MS = 10_000;
40
- const SECRETS_LOCK_TIMEOUT_MS = 5_000;
39
+ // icacls на Windows под параллельной нагрузкой CI может занять секунды;
40
+ // 5 с приводило к ложным «Не удалось получить блокировку» даже без краша.
41
+ const SECRETS_LOCK_TIMEOUT_MS = 30_000;
41
42
  let secretsLockDepth = 0;
42
43
 
43
44
  function sleepSync(ms: number): void {
@@ -67,20 +68,26 @@ function withSecretsLock<T>(fn: () => T): T {
67
68
  }
68
69
  secretsLockDepth = 1;
69
70
  break;
70
- } catch (err: any) {
71
- if (err?.code !== "EEXIST") throw err;
71
+ } catch (err: unknown) {
72
+ if ((err as NodeJS.ErrnoException | undefined)?.code !== "EEXIST") throw err;
72
73
  try {
73
74
  const stat = fs.statSync(SECRETS_LOCK_FILE);
74
- if (Date.now() - stat.mtimeMs > SECRETS_LOCK_STALE_MS) {
75
- const owner = Number.parseInt(
76
- fs.readFileSync(SECRETS_LOCK_FILE, "utf8").trim(),
77
- 10,
78
- );
79
- if (!Number.isInteger(owner) || !isProcessAlive(owner)) {
80
- fs.rmSync(SECRETS_LOCK_FILE, { force: true });
81
- continue;
82
- }
75
+ const rawOwner = fs.readFileSync(SECRETS_LOCK_FILE, "utf8").trim();
76
+ const owner = /^\d+$/.test(rawOwner) ? Number(rawOwner) : NaN;
77
+ // Мёртвый владелец — лок осиротел. PID проверяем независимо от времени
78
+ // жизни файла: свежий лок упавшего процесса раньше блокировал запись
79
+ // на 10 с (stale) + 5 с (timeout) и ложно падал на загруженном CI.
80
+ if (Number.isInteger(owner) && owner > 0 && !isProcessAlive(owner)) {
81
+ fs.rmSync(SECRETS_LOCK_FILE, { force: true });
82
+ continue;
83
83
  }
84
+ // Пустой/битый лок с только что созданным mtime может ещё не содержать
85
+ // PID — даём процессу-создателю окно, прежде чем считать его осиротевшим.
86
+ if (Date.now() - stat.mtimeMs > 1_000 && !Number.isInteger(owner)) {
87
+ fs.rmSync(SECRETS_LOCK_FILE, { force: true });
88
+ continue;
89
+ }
90
+ // Лок с живым владельцем не крадём, даже если он создан давно.
84
91
  } catch {
85
92
  // Лок исчез между stat и read — повторяем попытку.
86
93
  }
@@ -239,8 +246,8 @@ function loadKey(): Buffer {
239
246
  chmodPrivate(SECRETS_KEY_FILE);
240
247
  keyCache = { stamp, key: raw };
241
248
  return raw;
242
- } catch (err: any) {
243
- if (err?.code !== "ENOENT") throw err;
249
+ } catch (err: unknown) {
250
+ if ((err as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") throw err;
244
251
  // Два процесса могли одновременно не найти ключ и сгенерировать разный.
245
252
  // Под локом перечитываем файл: побеждает первый, остальные используют его ключ.
246
253
  return withSecretsLock(() => {
@@ -254,8 +261,8 @@ function loadKey(): Buffer {
254
261
  key: raw,
255
262
  };
256
263
  return raw;
257
- } catch (readErr: any) {
258
- if (readErr?.code !== "ENOENT") throw readErr;
264
+ } catch (readErr: unknown) {
265
+ if ((readErr as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") throw readErr;
259
266
  }
260
267
  const key = crypto.randomBytes(KEY_BYTES);
261
268
  fs.writeFileSync(SECRETS_KEY_FILE, key, { mode: 0o600 });
@@ -337,8 +344,8 @@ function readFileSafe(): SecretsFile {
337
344
  const file: SecretsFile = { version: 1, secrets };
338
345
  cache = { stamp, file };
339
346
  return file;
340
- } catch (err: any) {
341
- if (err?.code === "ENOENT") return emptyFile();
347
+ } catch (err: unknown) {
348
+ if ((err as NodeJS.ErrnoException | undefined)?.code === "ENOENT") return emptyFile();
342
349
  // Не глотаем повреждение молча: иначе setSecret запишет пустой файл поверх.
343
350
  quarantineCorruptStore(err);
344
351
  return emptyFile();