agent-steward 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/CHANGELOG.md +154 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +54 -9
  4. package/ROADMAP-STRATEGY.md +23 -20
  5. package/ROADMAP.md +140 -143
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +351 -0
  9. package/dist/core/dlq-api.d.ts +44 -0
  10. package/dist/core/dlq-api.d.ts.map +1 -0
  11. package/dist/core/dlq-api.js +68 -0
  12. package/dist/core/dry-run.d.ts.map +1 -1
  13. package/dist/core/dry-run.js +18 -1
  14. package/dist/core/execution.d.ts +203 -0
  15. package/dist/core/execution.d.ts.map +1 -0
  16. package/dist/core/execution.js +309 -0
  17. package/dist/core/gate-integrity.d.ts +35 -0
  18. package/dist/core/gate-integrity.d.ts.map +1 -0
  19. package/dist/core/gate-integrity.js +132 -0
  20. package/dist/core/git-trigger.d.ts.map +1 -1
  21. package/dist/core/git-trigger.js +14 -2
  22. package/dist/core/guard-run.d.ts +4 -0
  23. package/dist/core/guard-run.d.ts.map +1 -0
  24. package/dist/core/guard-run.js +101 -0
  25. package/dist/core/guard.d.ts +52 -0
  26. package/dist/core/guard.d.ts.map +1 -0
  27. package/dist/core/guard.js +362 -0
  28. package/dist/core/lock.d.ts +61 -4
  29. package/dist/core/lock.d.ts.map +1 -1
  30. package/dist/core/lock.js +213 -26
  31. package/dist/core/matrix.d.ts.map +1 -1
  32. package/dist/core/matrix.js +75 -15
  33. package/dist/core/mission.d.ts +83 -0
  34. package/dist/core/mission.d.ts.map +1 -0
  35. package/dist/core/mission.js +334 -0
  36. package/dist/core/one-shot.d.ts +5 -1
  37. package/dist/core/one-shot.d.ts.map +1 -1
  38. package/dist/core/one-shot.js +33 -8
  39. package/dist/core/opencode-cli.d.ts +28 -0
  40. package/dist/core/opencode-cli.d.ts.map +1 -0
  41. package/dist/core/opencode-cli.js +74 -0
  42. package/dist/core/opencode-models.d.ts +62 -0
  43. package/dist/core/opencode-models.d.ts.map +1 -0
  44. package/dist/core/opencode-models.js +277 -0
  45. package/dist/core/pipeline-apply.d.ts +38 -0
  46. package/dist/core/pipeline-apply.d.ts.map +1 -0
  47. package/dist/core/pipeline-apply.js +117 -0
  48. package/dist/core/pipeline-io.d.ts +13 -0
  49. package/dist/core/pipeline-io.d.ts.map +1 -0
  50. package/dist/core/pipeline-io.js +64 -0
  51. package/dist/core/pipeline-map.d.ts +46 -0
  52. package/dist/core/pipeline-map.d.ts.map +1 -0
  53. package/dist/core/pipeline-map.js +196 -0
  54. package/dist/core/pipeline-spec.d.ts +109 -0
  55. package/dist/core/pipeline-spec.d.ts.map +1 -0
  56. package/dist/core/pipeline-spec.js +554 -0
  57. package/dist/core/ps-wrapper.d.ts +19 -2
  58. package/dist/core/ps-wrapper.d.ts.map +1 -1
  59. package/dist/core/ps-wrapper.js +261 -63
  60. package/dist/core/record-history.d.ts +15 -0
  61. package/dist/core/record-history.d.ts.map +1 -1
  62. package/dist/core/record-history.js +183 -58
  63. package/dist/core/router/dispatch.d.ts +36 -0
  64. package/dist/core/router/dispatch.d.ts.map +1 -0
  65. package/dist/core/router/dispatch.js +59 -0
  66. package/dist/core/router/escalation.d.ts +47 -0
  67. package/dist/core/router/escalation.d.ts.map +1 -0
  68. package/dist/core/router/escalation.js +87 -0
  69. package/dist/core/router/planner.d.ts +53 -0
  70. package/dist/core/router/planner.d.ts.map +1 -0
  71. package/dist/core/router/planner.js +113 -0
  72. package/dist/core/router/rules.d.ts +46 -0
  73. package/dist/core/router/rules.d.ts.map +1 -0
  74. package/dist/core/router/rules.js +91 -0
  75. package/dist/core/run-panel-api.d.ts +94 -0
  76. package/dist/core/run-panel-api.d.ts.map +1 -0
  77. package/dist/core/run-panel-api.js +169 -0
  78. package/dist/core/schedule-gate.js +5 -1
  79. package/dist/core/schedule-v2.d.ts +34 -0
  80. package/dist/core/schedule-v2.d.ts.map +1 -1
  81. package/dist/core/schedule-v2.js +91 -5
  82. package/dist/core/scheduler/at-fallback.d.ts +55 -2
  83. package/dist/core/scheduler/at-fallback.d.ts.map +1 -1
  84. package/dist/core/scheduler/at-fallback.js +135 -5
  85. package/dist/core/scheduler/linux.d.ts +18 -2
  86. package/dist/core/scheduler/linux.d.ts.map +1 -1
  87. package/dist/core/scheduler/linux.js +63 -20
  88. package/dist/core/scheduler/mac.d.ts +44 -2
  89. package/dist/core/scheduler/mac.d.ts.map +1 -1
  90. package/dist/core/scheduler/mac.js +126 -15
  91. package/dist/core/scheduler/posix.d.ts.map +1 -1
  92. package/dist/core/scheduler/posix.js +25 -1
  93. package/dist/core/scheduler/registry.d.ts +11 -0
  94. package/dist/core/scheduler/registry.d.ts.map +1 -1
  95. package/dist/core/scheduler/registry.js +83 -21
  96. package/dist/core/scheduler/run-now.d.ts +16 -0
  97. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  98. package/dist/core/scheduler/run-now.js +28 -0
  99. package/dist/core/scheduler/windows.d.ts.map +1 -1
  100. package/dist/core/scheduler/windows.js +15 -12
  101. package/dist/core/secrets.d.ts.map +1 -1
  102. package/dist/core/secrets.js +125 -28
  103. package/dist/core/session.d.ts.map +1 -1
  104. package/dist/core/session.js +18 -11
  105. package/dist/core/structured-log.d.ts +7 -1
  106. package/dist/core/structured-log.d.ts.map +1 -1
  107. package/dist/core/task-name.d.ts +24 -0
  108. package/dist/core/task-name.d.ts.map +1 -0
  109. package/dist/core/task-name.js +40 -0
  110. package/dist/core/worktree-run.d.ts +4 -0
  111. package/dist/core/worktree-run.d.ts.map +1 -0
  112. package/dist/core/worktree-run.js +164 -0
  113. package/dist/core/worktree.d.ts +115 -0
  114. package/dist/core/worktree.d.ts.map +1 -0
  115. package/dist/core/worktree.js +462 -0
  116. package/dist/core/wrappers/bash.d.ts +17 -0
  117. package/dist/core/wrappers/bash.d.ts.map +1 -1
  118. package/dist/core/wrappers/bash.js +224 -28
  119. package/dist/db/capability-repo.d.ts +124 -0
  120. package/dist/db/capability-repo.d.ts.map +1 -0
  121. package/dist/db/capability-repo.js +267 -0
  122. package/dist/db/history-repo.d.ts +46 -5
  123. package/dist/db/history-repo.d.ts.map +1 -1
  124. package/dist/db/history-repo.js +107 -25
  125. package/dist/db/index.d.ts +4 -0
  126. package/dist/db/index.d.ts.map +1 -1
  127. package/dist/db/index.js +39 -1
  128. package/dist/db/metrics-repo.js +2 -2
  129. package/dist/db/migrate.d.ts.map +1 -1
  130. package/dist/db/migrate.js +3 -1
  131. package/dist/db/recovery.d.ts.map +1 -1
  132. package/dist/db/recovery.js +5 -4
  133. package/dist/db/run-context.d.ts +103 -0
  134. package/dist/db/run-context.d.ts.map +1 -0
  135. package/dist/db/run-context.js +224 -0
  136. package/dist/db/run-dlq.d.ts +100 -0
  137. package/dist/db/run-dlq.d.ts.map +1 -0
  138. package/dist/db/run-dlq.js +191 -0
  139. package/dist/db/run-journal.d.ts +33 -5
  140. package/dist/db/run-journal.d.ts.map +1 -1
  141. package/dist/db/run-journal.js +78 -14
  142. package/dist/db/run-resume.d.ts +10 -2
  143. package/dist/db/run-resume.d.ts.map +1 -1
  144. package/dist/db/run-resume.js +39 -13
  145. package/dist/db/runs-repo.d.ts +32 -7
  146. package/dist/db/runs-repo.d.ts.map +1 -1
  147. package/dist/db/runs-repo.js +50 -11
  148. package/dist/db/schema.d.ts +2 -2
  149. package/dist/db/schema.d.ts.map +1 -1
  150. package/dist/db/schema.js +216 -3
  151. package/dist/db/settings-repo.d.ts +11 -0
  152. package/dist/db/settings-repo.d.ts.map +1 -1
  153. package/dist/db/settings-repo.js +25 -0
  154. package/dist/db/step-idempotency.d.ts +51 -0
  155. package/dist/db/step-idempotency.d.ts.map +1 -0
  156. package/dist/db/step-idempotency.js +136 -0
  157. package/dist/history.d.ts +1 -1
  158. package/dist/history.d.ts.map +1 -1
  159. package/dist/i18n.d.ts +5 -0
  160. package/dist/i18n.d.ts.map +1 -1
  161. package/dist/i18n.js +11 -4
  162. package/dist/index.d.ts +140 -6
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +480 -18
  165. package/dist/notifications.d.ts +22 -0
  166. package/dist/notifications.d.ts.map +1 -1
  167. package/dist/notifications.js +36 -8
  168. package/dist/profiles.d.ts.map +1 -1
  169. package/dist/profiles.js +25 -4
  170. package/dist/rpc.d.ts +924 -0
  171. package/dist/rpc.d.ts.map +1 -1
  172. package/dist/rpc.js +352 -0
  173. package/dist/server.d.ts +46 -0
  174. package/dist/server.d.ts.map +1 -1
  175. package/dist/server.js +172 -53
  176. package/dist/settings.d.ts +2 -2
  177. package/dist/settings.d.ts.map +1 -1
  178. package/dist/settings.js +3 -3
  179. package/dist/shared/jobs-view.d.ts +1 -1
  180. package/dist/shared/jobs-view.d.ts.map +1 -1
  181. package/dist/shared/jobs-view.js +2 -0
  182. package/dist/task-transfer.d.ts +16 -0
  183. package/dist/task-transfer.d.ts.map +1 -1
  184. package/dist/task-transfer.js +16 -0
  185. package/dist/types.d.ts.map +1 -1
  186. package/dist/types.js +7 -0
  187. package/dist/workspaces.d.ts +25 -3
  188. package/dist/workspaces.d.ts.map +1 -1
  189. package/dist/workspaces.js +43 -8
  190. package/docs/ARCHITECTURE.md +498 -58
  191. package/docs/COMPATIBILITY.md +2 -2
  192. package/docs/CONCEPT.md +185 -91
  193. package/docs/CROSS_PLATFORM.ru.md +20 -0
  194. package/docs/CROSS_PLATFORM.zh.md +18 -0
  195. package/docs/EXECUTION-LOOP.md +211 -0
  196. package/docs/FEATURES.md +65 -4
  197. package/docs/FEATURES.zh.md +52 -4
  198. package/docs/MIGRATION.md +2 -2
  199. package/docs/PIPELINE.md +293 -0
  200. package/docs/README.ru.md +44 -5
  201. package/docs/README.zh.md +46 -6
  202. package/docs/SAFETY.md +142 -0
  203. package/docs/SAVINGS.md +29 -0
  204. package/docs/SAVINGS.ru.md +29 -0
  205. package/docs/SAVINGS.zh.md +18 -0
  206. package/gui-experimental.cjs +9 -8
  207. package/locales/en.json +84 -1
  208. package/locales/ru.json +84 -1
  209. package/locales/zh.json +84 -1
  210. package/opencode.pipeline.yaml +35 -0
  211. package/package.json +46 -2
  212. package/scripts/audit-bundle.mjs +215 -0
  213. package/scripts/test-home.mjs +83 -0
  214. package/src/cli.ts +412 -0
  215. package/src/core/dlq-api.ts +98 -0
  216. package/src/core/dry-run.ts +27 -3
  217. package/src/core/execution.ts +538 -0
  218. package/src/core/file-watcher.ts +2 -2
  219. package/src/core/gate-integrity.ts +160 -0
  220. package/src/core/git-trigger.ts +18 -5
  221. package/src/core/guard-run.ts +119 -0
  222. package/src/core/guard.ts +431 -0
  223. package/src/core/lock.ts +244 -30
  224. package/src/core/matrix.ts +95 -50
  225. package/src/core/mission.ts +485 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/one-shot.ts +36 -8
  228. package/src/core/opencode-cli.ts +103 -0
  229. package/src/core/opencode-models.ts +315 -0
  230. package/src/core/pipeline-apply.ts +158 -0
  231. package/src/core/pipeline-io.ts +79 -0
  232. package/src/core/pipeline-map.ts +264 -0
  233. package/src/core/pipeline-spec.ts +775 -0
  234. package/src/core/ps-wrapper.ts +274 -64
  235. package/src/core/record-history.ts +229 -104
  236. package/src/core/router/dispatch.ts +94 -0
  237. package/src/core/router/escalation.ts +129 -0
  238. package/src/core/router/planner.ts +166 -0
  239. package/src/core/router/rules.ts +115 -0
  240. package/src/core/run-panel-api.ts +262 -0
  241. package/src/core/schedule-gate.ts +7 -3
  242. package/src/core/schedule-v2.ts +114 -5
  243. package/src/core/scheduler/at-fallback.ts +190 -5
  244. package/src/core/scheduler/linux.ts +72 -21
  245. package/src/core/scheduler/logs.ts +2 -2
  246. package/src/core/scheduler/mac.ts +174 -14
  247. package/src/core/scheduler/posix.ts +20 -1
  248. package/src/core/scheduler/registry.ts +107 -26
  249. package/src/core/scheduler/run-now.ts +32 -0
  250. package/src/core/scheduler/windows.ts +19 -15
  251. package/src/core/secrets.ts +131 -31
  252. package/src/core/session.ts +23 -10
  253. package/src/core/structured-log.ts +22 -5
  254. package/src/core/task-name.ts +67 -0
  255. package/src/core/telegram.ts +2 -2
  256. package/src/core/triage-worker.ts +7 -7
  257. package/src/core/triage.ts +2 -2
  258. package/src/core/worktree-run.ts +199 -0
  259. package/src/core/worktree.ts +600 -0
  260. package/src/core/wrappers/bash.ts +239 -27
  261. package/src/db/capability-repo.ts +402 -0
  262. package/src/db/history-repo.ts +151 -22
  263. package/src/db/index.ts +37 -1
  264. package/src/db/metrics-repo.ts +2 -2
  265. package/src/db/migrate.ts +3 -1
  266. package/src/db/recovery.ts +5 -4
  267. package/src/db/run-context.ts +370 -0
  268. package/src/db/run-dlq.ts +310 -0
  269. package/src/db/run-journal.ts +100 -13
  270. package/src/db/run-resume.ts +65 -13
  271. package/src/db/runs-repo.ts +66 -13
  272. package/src/db/schema.ts +218 -3
  273. package/src/db/settings-repo.ts +31 -0
  274. package/src/db/step-idempotency.ts +185 -0
  275. package/src/gui.tsx +692 -13
  276. package/src/history.ts +1 -1
  277. package/src/i18n.ts +12 -4
  278. package/src/index.ts +648 -8
  279. package/src/notifications.ts +38 -8
  280. package/src/profiles.ts +26 -4
  281. package/src/rpc.ts +379 -0
  282. package/src/server.ts +206 -54
  283. package/src/settings.ts +5 -5
  284. package/src/shared/jobs-view.ts +3 -1
  285. package/src/task-transfer.ts +31 -0
  286. package/src/types.ts +9 -0
  287. package/src/workspaces.ts +58 -9
@@ -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
  }
@@ -48,8 +48,27 @@ export abstract class PosixSchedulerBase implements SchedulerBackend {
48
48
  ...(options.timezone ? { timezone: options.timezone } : {}),
49
49
  };
50
50
 
51
+ // P2-17: запись нужна в реестре ДО installEntry — Linux пересобирает crontab
52
+ // из реестра. Но если установка упала, запись-призрак останется навсегда,
53
+ // поэтому откатываем реестр к предыдущему состоянию.
54
+ const previous = await this.registry.find(entry.name);
51
55
  await this.registry.upsert(entry);
52
- await this.installEntry(entry);
56
+ try {
57
+ await this.installEntry(entry);
58
+ } catch (err) {
59
+ try {
60
+ if (previous) await this.registry.upsert(previous);
61
+ else await this.registry.remove(entry.name);
62
+ } catch {
63
+ // Не маскируем исходную ошибку установки ошибкой отката.
64
+ }
65
+ try {
66
+ await this.uninstallEntry(entry);
67
+ } catch {
68
+ // Частичная установка могла не создать запись — это не ошибка отката.
69
+ }
70
+ throw err;
71
+ }
53
72
  // installEntry может записать atJobId для Linux one-shot.
54
73
  await this.registry.upsert(entry);
55
74
  }
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { getProfileDir, getProfileName } from "../../profiles.js";
4
+ import { LockManager, withLockWait } from "../lock.js";
4
5
  import type { TriggerType } from "./types.js";
5
6
 
6
7
  /**
@@ -35,10 +36,16 @@ export interface RegistryEntry {
35
36
  export class TaskRegistry {
36
37
  private readonly file: string;
37
38
  private readonly dir: string;
39
+ private readonly backendId: string;
40
+ private readonly lock: LockManager;
38
41
 
39
42
  constructor(backendId: string, profile: string = getProfileName()) {
43
+ this.backendId = backendId;
40
44
  this.dir = getProfileDir(profile);
41
45
  this.file = path.join(this.dir, `scheduler-${backendId}.json`);
46
+ // P2-16: мутации реестра — read-modify-write. Лок сериализует их между
47
+ // процессами (хост OpenCode, CLI, detached record-history).
48
+ this.lock = new LockManager(path.join(this.dir, "locks"));
42
49
  }
43
50
 
44
51
  /** Путь к файлу реестра (для диагностики). */
@@ -46,18 +53,69 @@ export class TaskRegistry {
46
53
  return this.file;
47
54
  }
48
55
 
56
+ /** Маркер того, что реестр был повреждён и перемещён в карантин. */
57
+ private get blockedPath(): string {
58
+ return `${this.file}.blocked`;
59
+ }
60
+
49
61
  async load(): Promise<RegistryEntry[]> {
62
+ let raw: string;
50
63
  try {
51
- const raw = await fs.readFile(this.file, "utf8");
52
- const parsed = JSON.parse(raw);
53
- if (!Array.isArray(parsed)) return [];
54
- return parsed.filter(
55
- (entry): entry is RegistryEntry =>
56
- entry && typeof entry.name === "string" && typeof entry.command === "string",
64
+ raw = await fs.readFile(this.file, "utf8");
65
+ } catch (err: unknown) {
66
+ if ((err as NodeJS.ErrnoException | undefined)?.code === "ENOENT") {
67
+ // Карантин уже переместил файл. Пустой реестр нельзя выдавать за
68
+ // «задач нет»: rebuildCrontab вычистил бы все cron-строки плагина.
69
+ const blocked = await fs.readFile(this.blockedPath, "utf8").catch(() => null);
70
+ if (blocked) {
71
+ throw new Error(
72
+ `Реестр задач повреждён (карантин: ${blocked.trim()}). ` +
73
+ `Восстановите ${this.file} вручную или удалите маркер ${this.blockedPath}.`,
74
+ );
75
+ }
76
+ return [];
77
+ }
78
+ throw err;
79
+ }
80
+
81
+ let parsed: unknown;
82
+ try {
83
+ parsed = JSON.parse(raw);
84
+ } catch (err) {
85
+ return this.quarantineCorrupt(err);
86
+ }
87
+ if (!Array.isArray(parsed)) {
88
+ return this.quarantineCorrupt(new Error("expected an array of registry entries"));
89
+ }
90
+ return parsed.filter(
91
+ (entry): entry is RegistryEntry =>
92
+ entry && typeof entry.name === "string" && typeof entry.command === "string",
93
+ );
94
+ }
95
+
96
+ /** Перемещает повреждённый файл в карантин и блокирует дальнейшие записи. */
97
+ private async quarantineCorrupt(err: unknown): Promise<never> {
98
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
99
+ const target = `${this.file}.corrupt-${stamp}`;
100
+ let moved = "";
101
+ try {
102
+ await fs.rename(this.file, target);
103
+ await fs.writeFile(this.blockedPath, target, "utf8");
104
+ moved = ` Файл перемещён в ${target}.`;
105
+ console.warn(
106
+ `[scheduler] Реестр ${path.basename(this.file)} повреждён и перемещён в ${target}. ` +
107
+ `Запись заблокирована маркером ${this.blockedPath}.`,
108
+ err,
109
+ );
110
+ } catch (renameErr) {
111
+ console.error(
112
+ `[scheduler] Не удалось переместить повреждённый реестр ${this.file} в ${target}.`,
113
+ renameErr,
57
114
  );
58
- } catch {
59
- return [];
60
115
  }
116
+ throw new Error(
117
+ `Реестр задач повреждён.${moved} Восстановите ${this.file} вручную или удалите маркер ${this.blockedPath}.`,
118
+ );
61
119
  }
62
120
 
63
121
  async save(entries: RegistryEntry[]): Promise<void> {
@@ -65,6 +123,28 @@ export class TaskRegistry {
65
123
  const tmp = `${this.file}.tmp`;
66
124
  await fs.writeFile(tmp, JSON.stringify(entries, null, 2), "utf8");
67
125
  await fs.rename(tmp, this.file);
126
+ await fs.rm(this.blockedPath, { force: true }).catch(() => {
127
+ /* маркера могло не быть */
128
+ });
129
+ }
130
+
131
+ /**
132
+ * Read-modify-write под межпроцессной блокировкой: два процесса на одном
133
+ * профиле не должны терять чужие записи (P2-16).
134
+ */
135
+ private async mutate<T>(fn: (entries: RegistryEntry[]) => T | Promise<T>): Promise<T> {
136
+ await this.lock.initialize();
137
+ return withLockWait(
138
+ this.lock,
139
+ `registry-${this.backendId}`,
140
+ async () => {
141
+ const entries = await this.load();
142
+ const result = await fn(entries);
143
+ await this.save(entries);
144
+ return result;
145
+ },
146
+ { timeoutMs: 15000, staleMs: 60000 },
147
+ );
68
148
  }
69
149
 
70
150
  async find(name: string): Promise<RegistryEntry | undefined> {
@@ -73,29 +153,30 @@ export class TaskRegistry {
73
153
  }
74
154
 
75
155
  async upsert(entry: RegistryEntry): Promise<void> {
76
- const entries = await this.load();
77
- const index = entries.findIndex(
78
- (e) => e.name.toLowerCase() === entry.name.toLowerCase(),
79
- );
80
- if (index === -1) entries.push(entry);
81
- else entries[index] = entry;
82
- await this.save(entries);
156
+ await this.mutate((entries) => {
157
+ const index = entries.findIndex(
158
+ (e) => e.name.toLowerCase() === entry.name.toLowerCase(),
159
+ );
160
+ if (index === -1) entries.push(entry);
161
+ else entries[index] = entry;
162
+ });
83
163
  }
84
164
 
85
165
  async remove(name: string): Promise<void> {
86
- const entries = await this.load();
87
- await this.save(
88
- entries.filter((e) => e.name.toLowerCase() !== name.toLowerCase()),
89
- );
166
+ await this.mutate((entries) => {
167
+ const index = entries.findIndex(
168
+ (e) => e.name.toLowerCase() === name.toLowerCase(),
169
+ );
170
+ if (index !== -1) entries.splice(index, 1);
171
+ });
90
172
  }
91
173
 
92
174
  async setPaused(name: string, paused: boolean): Promise<void> {
93
- const entries = await this.load();
94
- const entry = entries.find(
95
- (e) => e.name.toLowerCase() === name.toLowerCase(),
96
- );
97
- if (!entry) return;
98
- entry.paused = paused;
99
- await this.save(entries);
175
+ await this.mutate((entries) => {
176
+ const entry = entries.find(
177
+ (e) => e.name.toLowerCase() === name.toLowerCase(),
178
+ );
179
+ if (entry) entry.paused = paused;
180
+ });
100
181
  }
101
182
  }
@@ -0,0 +1,32 @@
1
+ import fs from "node:fs/promises";
2
+ import { requestImmediateRun } from "../ps-wrapper.js";
3
+ import { createSchedulerBackend } from "./index.js";
4
+ import type { RunTaskResult, SchedulerBackend } from "./types.js";
5
+
6
+ /**
7
+ * Немедленный запуск задачи в обход schedule-gate.
8
+ *
9
+ * Зачем: для poll-режима (расширенный cron / чужая IANA-таймзона / окно
10
+ * запуска) обёртка всегда прогоняет schedule-gate, и запуск вне cron-окна
11
+ * молча завершается с exit 3. Это касается не только `run_task_now`, но и
12
+ * цепочек (nextTaskOnSuccess / nextTaskOnError), DAG-зависимостей и retry:
13
+ * они тоже запускают задачу «сейчас», а не «по расписанию».
14
+ *
15
+ * Маркер `requestImmediateRun` снимает проверку расписания внутри обёртки.
16
+ * Если планировщик не принял запуск, маркер удаляется, чтобы он не «разрешил»
17
+ * следующий плановый тик в обход расписания.
18
+ */
19
+ export async function runTaskNow(
20
+ taskName: string,
21
+ backend: SchedulerBackend = createSchedulerBackend(),
22
+ ): Promise<RunTaskResult> {
23
+ const forceFile = await requestImmediateRun(taskName);
24
+ try {
25
+ return await backend.runTask(taskName);
26
+ } catch (err) {
27
+ await fs.unlink(forceFile).catch(() => {
28
+ /* маркер мог быть уже поглощён gate'ом или удалён по TTL */
29
+ });
30
+ throw err;
31
+ }
32
+ }
@@ -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-триггеров) в формате локали. */