opencode-windows-scheduler 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/CROSS_PLATFORM.md +113 -0
  3. package/LICENSE +21 -0
  4. package/README.md +173 -2
  5. package/README.ru.md +131 -0
  6. package/ROADMAP-STRATEGY.md +217 -0
  7. package/ROADMAP.md +87 -0
  8. package/dist/core/cron-to-schtasks.d.ts +20 -0
  9. package/dist/core/cron-to-schtasks.d.ts.map +1 -0
  10. package/dist/core/cron-to-schtasks.js +233 -0
  11. package/dist/core/dry-run.d.ts +44 -0
  12. package/dist/core/dry-run.d.ts.map +1 -0
  13. package/dist/core/dry-run.js +252 -0
  14. package/dist/core/file-watcher.d.ts +31 -0
  15. package/dist/core/file-watcher.d.ts.map +1 -0
  16. package/dist/core/file-watcher.js +128 -0
  17. package/dist/core/lock.d.ts +43 -0
  18. package/dist/core/lock.d.ts.map +1 -0
  19. package/dist/core/lock.js +118 -0
  20. package/dist/core/matrix.d.ts +167 -0
  21. package/dist/core/matrix.d.ts.map +1 -0
  22. package/dist/core/matrix.js +687 -0
  23. package/dist/core/ps-wrapper.d.ts +60 -0
  24. package/dist/core/ps-wrapper.d.ts.map +1 -0
  25. package/dist/core/ps-wrapper.js +538 -0
  26. package/dist/core/record-history.d.ts +14 -0
  27. package/dist/core/record-history.d.ts.map +1 -0
  28. package/dist/core/record-history.js +360 -0
  29. package/dist/core/scheduler/index.d.ts +20 -0
  30. package/dist/core/scheduler/index.d.ts.map +1 -0
  31. package/dist/core/scheduler/index.js +32 -0
  32. package/dist/core/scheduler/linux.d.ts +32 -0
  33. package/dist/core/scheduler/linux.d.ts.map +1 -0
  34. package/dist/core/scheduler/linux.js +115 -0
  35. package/dist/core/scheduler/logs.d.ts +11 -0
  36. package/dist/core/scheduler/logs.d.ts.map +1 -0
  37. package/dist/core/scheduler/logs.js +34 -0
  38. package/dist/core/scheduler/mac.d.ts +39 -0
  39. package/dist/core/scheduler/mac.d.ts.map +1 -0
  40. package/dist/core/scheduler/mac.js +175 -0
  41. package/dist/core/scheduler/posix.d.ts +40 -0
  42. package/dist/core/scheduler/posix.d.ts.map +1 -0
  43. package/dist/core/scheduler/posix.js +86 -0
  44. package/dist/core/scheduler/registry.d.ts +36 -0
  45. package/dist/core/scheduler/registry.d.ts.map +1 -0
  46. package/dist/core/scheduler/registry.js +56 -0
  47. package/dist/core/scheduler/types.d.ts +63 -0
  48. package/dist/core/scheduler/types.d.ts.map +1 -0
  49. package/dist/core/scheduler/types.js +1 -0
  50. package/dist/core/scheduler/windows.d.ts +47 -0
  51. package/dist/core/scheduler/windows.d.ts.map +1 -0
  52. package/dist/core/scheduler/windows.js +375 -0
  53. package/dist/core/wrappers/bash.d.ts +58 -0
  54. package/dist/core/wrappers/bash.d.ts.map +1 -0
  55. package/dist/core/wrappers/bash.js +223 -0
  56. package/dist/db/history-repo.d.ts +69 -0
  57. package/dist/db/history-repo.d.ts.map +1 -0
  58. package/dist/db/history-repo.js +150 -0
  59. package/dist/db/index.d.ts +47 -0
  60. package/dist/db/index.d.ts.map +1 -0
  61. package/dist/db/index.js +120 -0
  62. package/dist/db/metrics-repo.d.ts +43 -0
  63. package/dist/db/metrics-repo.d.ts.map +1 -0
  64. package/dist/db/metrics-repo.js +95 -0
  65. package/dist/db/migrate.d.ts +24 -0
  66. package/dist/db/migrate.d.ts.map +1 -0
  67. package/dist/db/migrate.js +237 -0
  68. package/dist/db/recovery.d.ts +11 -0
  69. package/dist/db/recovery.d.ts.map +1 -0
  70. package/dist/db/recovery.js +38 -0
  71. package/dist/db/schema.d.ts +24 -0
  72. package/dist/db/schema.d.ts.map +1 -0
  73. package/dist/db/schema.js +97 -0
  74. package/dist/db/settings-repo.d.ts +8 -0
  75. package/dist/db/settings-repo.d.ts.map +1 -0
  76. package/dist/db/settings-repo.js +27 -0
  77. package/dist/db/tasks-repo.d.ts +26 -0
  78. package/dist/db/tasks-repo.d.ts.map +1 -0
  79. package/dist/db/tasks-repo.js +120 -0
  80. package/dist/db/templates-repo.d.ts +17 -0
  81. package/dist/db/templates-repo.d.ts.map +1 -0
  82. package/dist/db/templates-repo.js +57 -0
  83. package/dist/gui-experimental.cjs +1 -0
  84. package/dist/history.d.ts +53 -0
  85. package/dist/history.d.ts.map +1 -0
  86. package/dist/history.js +57 -0
  87. package/dist/index.d.ts +156 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +2077 -0
  90. package/dist/notifications.d.ts +45 -0
  91. package/dist/notifications.d.ts.map +1 -0
  92. package/dist/notifications.js +135 -0
  93. package/dist/rpc.d.ts +2052 -0
  94. package/dist/rpc.d.ts.map +1 -0
  95. package/dist/rpc.js +863 -0
  96. package/dist/schtasks.d.ts +32 -0
  97. package/dist/schtasks.d.ts.map +1 -0
  98. package/dist/schtasks.js +45 -0
  99. package/dist/server.d.ts +106 -0
  100. package/dist/server.d.ts.map +1 -0
  101. package/dist/server.js +1478 -0
  102. package/dist/settings.d.ts +43 -0
  103. package/dist/settings.d.ts.map +1 -0
  104. package/dist/settings.js +96 -0
  105. package/dist/shared/jobs-view.d.ts +21 -0
  106. package/dist/shared/jobs-view.d.ts.map +1 -0
  107. package/dist/shared/jobs-view.js +28 -0
  108. package/dist/skill.d.ts +15 -0
  109. package/dist/skill.d.ts.map +1 -0
  110. package/dist/skill.js +93 -0
  111. package/dist/task-transfer.d.ts +176 -0
  112. package/dist/task-transfer.d.ts.map +1 -0
  113. package/dist/task-transfer.js +442 -0
  114. package/dist/templates.d.ts +57 -0
  115. package/dist/templates.d.ts.map +1 -0
  116. package/dist/templates.js +16 -0
  117. package/dist/types.d.ts +78 -0
  118. package/dist/types.d.ts.map +1 -0
  119. package/dist/types.js +88 -0
  120. package/dist/workspaces.d.ts +55 -0
  121. package/dist/workspaces.d.ts.map +1 -0
  122. package/dist/workspaces.js +183 -0
  123. package/docs/ARCHITECTURE.md +302 -0
  124. package/docs/FEATURES.md +288 -0
  125. package/docs/MIGRATION.md +266 -0
  126. package/docs/dashboard.png +0 -0
  127. package/gui-experimental.cjs +2 -0
  128. package/index.js +1 -0
  129. package/package.json +92 -4
  130. package/scripts/demo-dashboard.mjs +199 -0
  131. package/skills/scheduled-job-best-practices/SKILL.md +155 -0
  132. package/skills/scheduled-job-best-practices/references/recipes.md +123 -0
  133. package/src/core/cron-to-schtasks.ts +269 -0
  134. package/src/core/dry-run.ts +315 -0
  135. package/src/core/file-watcher.ts +171 -0
  136. package/src/core/lock.ts +134 -0
  137. package/src/core/matrix.ts +907 -0
  138. package/src/core/ps-wrapper.ts +572 -0
  139. package/src/core/record-history.ts +493 -0
  140. package/src/core/scheduler/index.ts +44 -0
  141. package/src/core/scheduler/linux.ts +125 -0
  142. package/src/core/scheduler/logs.ts +37 -0
  143. package/src/core/scheduler/mac.ts +222 -0
  144. package/src/core/scheduler/posix.ts +111 -0
  145. package/src/core/scheduler/registry.ts +93 -0
  146. package/src/core/scheduler/types.ts +67 -0
  147. package/src/core/scheduler/windows.ts +469 -0
  148. package/src/core/wrappers/bash.ts +282 -0
  149. package/src/db/history-repo.ts +303 -0
  150. package/src/db/index.ts +166 -0
  151. package/src/db/metrics-repo.ts +158 -0
  152. package/src/db/migrate.ts +322 -0
  153. package/src/db/recovery.ts +46 -0
  154. package/src/db/schema.ts +109 -0
  155. package/src/db/settings-repo.ts +31 -0
  156. package/src/db/tasks-repo.ts +162 -0
  157. package/src/db/templates-repo.ts +77 -0
  158. package/src/gui.tsx +2725 -0
  159. package/src/history.ts +107 -0
  160. package/src/index.ts +2672 -0
  161. package/src/notifications.ts +174 -0
  162. package/src/rpc.ts +933 -0
  163. package/src/schtasks.ts +75 -0
  164. package/src/server.ts +1663 -0
  165. package/src/settings.ts +157 -0
  166. package/src/shared/jobs-view.ts +38 -0
  167. package/src/skill.ts +113 -0
  168. package/src/task-transfer.ts +648 -0
  169. package/src/templates.ts +67 -0
  170. package/src/tui.tsx +46 -0
  171. package/src/types.ts +145 -0
  172. package/src/workspaces.ts +236 -0
package/dist/types.js ADDED
@@ -0,0 +1,88 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import { z } from "zod";
4
+ /** Префикс всех задач плагина (историческое имя, сохраняется для совместимости). */
5
+ export const TASK_PREFIX = "OpenCode\\windows-scheduler";
6
+ /** Папка задач плагина в планировщике ОС (Windows). */
7
+ export const TASK_FOLDER = "OpenCode";
8
+ export const TASK_FOLDER_NAME = "windows-scheduler";
9
+ /**
10
+ * Директория для хранения файлов плагина (обёртки, логи, блокировки, история).
11
+ *
12
+ * Windows: %APPDATA%\opencode\windows-scheduler (как раньше — без миграции).
13
+ * macOS/Linux: $XDG_CONFIG_HOME/opencode/windows-scheduler или
14
+ * ~/.config/opencode/windows-scheduler.
15
+ */
16
+ function resolvePluginDir() {
17
+ // Explicit override (tests, custom installations). Takes precedence on every platform.
18
+ const custom = process.env.OPENCODE_SCHEDULER_HOME?.trim();
19
+ if (custom)
20
+ return path.resolve(custom);
21
+ if (process.platform === "win32") {
22
+ const base = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
23
+ return path.join(base, "opencode", TASK_FOLDER_NAME);
24
+ }
25
+ const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
26
+ return path.join(configHome, "opencode", TASK_FOLDER_NAME);
27
+ }
28
+ export const PLUGIN_DIR = resolvePluginDir();
29
+ export const LOCK_DIR = path.join(PLUGIN_DIR, "locks");
30
+ export const LOG_DIR = path.join(PLUGIN_DIR, "logs");
31
+ export const WRAPPER_DIR = path.join(PLUGIN_DIR, "wrappers");
32
+ /** true, если плагин запущен на Windows. */
33
+ export const IS_WINDOWS = process.platform === "win32";
34
+ /** Порог возраста lock-файла, после которого он считается зависшим (24 часа). */
35
+ export const STALE_LOCK_MAX_AGE_MS = 24 * 60 * 60 * 1000;
36
+ /**
37
+ * Приводит имя задачи к безопасному виду для имён файлов (обёртка, промпт, lock, лог).
38
+ * Кириллица транслитерируется, прочие спецсимволы заменяются на дефис.
39
+ * Используется единообразно при создании задачи (index.ts) и при чтении логов (schtasks.ts).
40
+ */
41
+ export function sanitizeName(name) {
42
+ const translit = {
43
+ а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e",
44
+ ж: "zh", з: "z", и: "i", й: "y", к: "k", л: "l", м: "m",
45
+ н: "n", о: "o", п: "p", р: "r", с: "s", т: "t", у: "u",
46
+ ф: "f", х: "h", ц: "ts", ч: "ch", ш: "sh", щ: "sch",
47
+ ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya",
48
+ };
49
+ let result = name.toLowerCase();
50
+ result = result.split("").map((c) => translit[c] || c).join("");
51
+ result = result.replace(/[^a-z0-9_\-]/g, "-");
52
+ result = result.replace(/-+/g, "-").replace(/^-+|-+$/g, "");
53
+ return result || "task";
54
+ }
55
+ /**
56
+ * Схема аргументов для schedule_job.
57
+ * schedule принимает только 5-полевые cron-выражения.
58
+ */
59
+ export const ScheduleJobArgs = z.object({
60
+ name: z
61
+ .string()
62
+ .min(1)
63
+ .regex(/^[A-Za-z0-9_\-]+$/, "Имя задачи должно содержать только буквы, цифры, подчёркивание и дефис")
64
+ .describe("Имя задачи (уникально в рамках префикса OpenCode\\windows-scheduler)"),
65
+ schedule: z
66
+ .string()
67
+ .min(1)
68
+ .describe("5-полевое cron-выражение (минута час день_месяца месяц день_недели)"),
69
+ prompt: z.string().min(1).describe("Промпт, который передаётся в opencode run при запуске задачи"),
70
+ timeoutSeconds: z
71
+ .number()
72
+ .int()
73
+ .positive()
74
+ .optional()
75
+ .default(3600)
76
+ .describe("Таймаут выполнения задачи в секундах (по умолчанию 3600)"),
77
+ workdir: z
78
+ .string()
79
+ .optional()
80
+ .describe("Рабочая директория для выполнения opencode run (по умолчанию текущая)"),
81
+ });
82
+ export const DeleteJobArgs = z.object({
83
+ name: z.string().min(1).describe("Имя задачи для удаления"),
84
+ });
85
+ export const RunJobNowArgs = z.object({
86
+ name: z.string().min(1).describe("Имя задачи для немедленного запуска"),
87
+ });
88
+ export const ListJobsArgs = z.object({});
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Multi-repo workspaces.
3
+ *
4
+ * Одна задача = один workspace = один cwd. Workspace — это просто
5
+ * зарегистрированный путь к репозиторию; плагин никогда не «угадывает»,
6
+ * куда мержить и не выполняет cross-repo операции самостоятельно.
7
+ */
8
+ export interface Workspace {
9
+ id: string;
10
+ name: string;
11
+ path: string;
12
+ gitRemote?: string;
13
+ color?: string;
14
+ createdAt: string;
15
+ }
16
+ export interface AddWorkspaceInput {
17
+ name?: string;
18
+ path: string;
19
+ color?: string;
20
+ }
21
+ export interface UpdateWorkspacePatch {
22
+ name?: string;
23
+ path?: string;
24
+ color?: string;
25
+ gitRemote?: string | null;
26
+ }
27
+ /** Палитра цветных маркеров для GUI/дашборда. */
28
+ export declare const WORKSPACE_COLORS: string[];
29
+ /** Проверяет, что путь существует и является директорией. */
30
+ export declare function validateWorkspacePath(workspacePath: string): void;
31
+ /**
32
+ * Читает git remote origin. Если путь не git-репозиторий или remote не
33
+ * настроен — возвращает undefined (это не ошибка).
34
+ */
35
+ export declare function readGitRemote(workspacePath: string): string | undefined;
36
+ /** Текущая git-ветка (для dry-run preview); undefined вне git-репозитория. */
37
+ export declare function readGitBranch(workspacePath: string): string | undefined;
38
+ /** Все workspace (по имени). */
39
+ export declare function listWorkspaces(): Workspace[];
40
+ /** Workspace по id. */
41
+ export declare function getWorkspace(id: string): Workspace | undefined;
42
+ /** Workspace по пути (без учёта регистра, как в Windows). */
43
+ export declare function getWorkspaceByPath(workspacePath: string): Workspace | undefined;
44
+ /** Регистрирует новый workspace. Путь должен существовать. */
45
+ export declare function addWorkspace(input: AddWorkspaceInput): Workspace;
46
+ /** Обновляет имя/путь/цвет workspace. */
47
+ export declare function updateWorkspace(id: string, patch: UpdateWorkspacePatch): Workspace;
48
+ /**
49
+ * Удаляет workspace. Задачи не удаляются — у них просто очищается
50
+ * workspaceId (с предупреждением в логе).
51
+ */
52
+ export declare function deleteWorkspace(id: string): boolean;
53
+ /** Количество workspace (для сводок и тестов). */
54
+ export declare function countWorkspaces(): number;
55
+ //# sourceMappingURL=workspaces.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspaces.d.ts","sourceRoot":"","sources":["../src/workspaces.ts"],"names":[],"mappings":"AAOA;;;;;;GAMG;AACH,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,oBAAoB;IACnC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED,iDAAiD;AACjD,eAAO,MAAM,gBAAgB,UAO5B,CAAC;AAiBF,6DAA6D;AAC7D,wBAAgB,qBAAqB,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI,CAOjE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAavE;AAED,8EAA8E;AAC9E,wBAAgB,aAAa,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAavE;AAED,gCAAgC;AAChC,wBAAgB,cAAc,IAAI,SAAS,EAAE,CAK5C;AAED,uBAAuB;AACvB,wBAAgB,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAI9D;AAED,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAM/E;AAED,8DAA8D;AAC9D,wBAAgB,YAAY,CAAC,KAAK,EAAE,iBAAiB,GAAG,SAAS,CAgChE;AAED,yCAAyC;AACzC,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,oBAAoB,GAAG,SAAS,CA0ClF;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAenD;AAED,kDAAkD;AAClD,wBAAgB,eAAe,IAAI,MAAM,CAGxC"}
@@ -0,0 +1,183 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { statSync } from "node:fs";
3
+ import { basename, resolve } from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { getDb } from "./db/index.js";
6
+ import { clearWorkspaceAssignments } from "./db/tasks-repo.js";
7
+ /** Палитра цветных маркеров для GUI/дашборда. */
8
+ export const WORKSPACE_COLORS = [
9
+ "#5b8def",
10
+ "#2fb67c",
11
+ "#e0a03a",
12
+ "#d15c8a",
13
+ "#8b6fe8",
14
+ "#3aa8b8",
15
+ ];
16
+ function rowToWorkspace(row) {
17
+ return {
18
+ id: String(row.id),
19
+ name: String(row.name),
20
+ path: String(row.path),
21
+ gitRemote: row.git_remote == null ? undefined : String(row.git_remote),
22
+ color: row.color == null ? undefined : String(row.color),
23
+ createdAt: String(row.created_at),
24
+ };
25
+ }
26
+ function normalizePath(value) {
27
+ return resolve(value.trim());
28
+ }
29
+ /** Проверяет, что путь существует и является директорией. */
30
+ export function validateWorkspacePath(workspacePath) {
31
+ try {
32
+ const stat = statSync(workspacePath);
33
+ if (!stat.isDirectory())
34
+ throw new Error("not a directory");
35
+ }
36
+ catch {
37
+ throw new Error(`Путь workspace недоступен: ${workspacePath}`);
38
+ }
39
+ }
40
+ /**
41
+ * Читает git remote origin. Если путь не git-репозиторий или remote не
42
+ * настроен — возвращает undefined (это не ошибка).
43
+ */
44
+ export function readGitRemote(workspacePath) {
45
+ try {
46
+ const result = spawnSync("git", ["-C", workspacePath, "remote", "get-url", "origin"], {
47
+ encoding: "utf8",
48
+ timeout: 5000,
49
+ windowsHide: true,
50
+ });
51
+ if (result.status !== 0)
52
+ return undefined;
53
+ const remote = String(result.stdout || "").trim();
54
+ return remote || undefined;
55
+ }
56
+ catch {
57
+ return undefined;
58
+ }
59
+ }
60
+ /** Текущая git-ветка (для dry-run preview); undefined вне git-репозитория. */
61
+ export function readGitBranch(workspacePath) {
62
+ try {
63
+ const result = spawnSync("git", ["-C", workspacePath, "rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8", timeout: 5000, windowsHide: true });
64
+ if (result.status !== 0)
65
+ return undefined;
66
+ const branch = String(result.stdout || "").trim();
67
+ return branch || undefined;
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ }
73
+ /** Все workspace (по имени). */
74
+ export function listWorkspaces() {
75
+ const rows = getDb()
76
+ .prepare("SELECT * FROM workspaces ORDER BY name COLLATE NOCASE ASC")
77
+ .all();
78
+ return rows.map(rowToWorkspace);
79
+ }
80
+ /** Workspace по id. */
81
+ export function getWorkspace(id) {
82
+ if (!id)
83
+ return undefined;
84
+ const row = getDb().prepare("SELECT * FROM workspaces WHERE id = ?").get(id);
85
+ return row ? rowToWorkspace(row) : undefined;
86
+ }
87
+ /** Workspace по пути (без учёта регистра, как в Windows). */
88
+ export function getWorkspaceByPath(workspacePath) {
89
+ const normalized = normalizePath(workspacePath);
90
+ const row = getDb()
91
+ .prepare("SELECT * FROM workspaces WHERE lower(path) = lower(?) LIMIT 1")
92
+ .get(normalized);
93
+ return row ? rowToWorkspace(row) : undefined;
94
+ }
95
+ /** Регистрирует новый workspace. Путь должен существовать. */
96
+ export function addWorkspace(input) {
97
+ const workspacePath = normalizePath(input.path || "");
98
+ if (!workspacePath) {
99
+ throw new Error("Путь workspace не может быть пустым.");
100
+ }
101
+ const name = (input.name || basename(workspacePath) || workspacePath).trim();
102
+ try {
103
+ validateWorkspacePath(workspacePath);
104
+ }
105
+ catch {
106
+ throw new Error(`Workspace '${name}' недоступен по пути '${workspacePath}'`);
107
+ }
108
+ const existing = getWorkspaceByPath(workspacePath);
109
+ if (existing) {
110
+ throw new Error(`Workspace с путём '${workspacePath}' уже существует.`);
111
+ }
112
+ const id = randomUUID();
113
+ const color = input.color?.trim() ||
114
+ WORKSPACE_COLORS[listWorkspaces().length % WORKSPACE_COLORS.length];
115
+ const createdAt = new Date().toISOString();
116
+ const gitRemote = readGitRemote(workspacePath);
117
+ getDb()
118
+ .prepare(`INSERT INTO workspaces (id, name, path, git_remote, color, created_at)
119
+ VALUES (?, ?, ?, ?, ?, ?)`)
120
+ .run(id, name, workspacePath, gitRemote ?? null, color, createdAt);
121
+ return { id, name, path: workspacePath, gitRemote, color, createdAt };
122
+ }
123
+ /** Обновляет имя/путь/цвет workspace. */
124
+ export function updateWorkspace(id, patch) {
125
+ const existing = getWorkspace(id);
126
+ if (!existing)
127
+ throw new Error(`Workspace '${id}' не найден.`);
128
+ const nextName = patch.name?.trim() || existing.name;
129
+ const nextPath = patch.path?.trim() ? normalizePath(patch.path) : existing.path;
130
+ if (nextPath !== existing.path) {
131
+ try {
132
+ validateWorkspacePath(nextPath);
133
+ }
134
+ catch {
135
+ throw new Error(`Workspace '${nextName}' недоступен по пути '${nextPath}'`);
136
+ }
137
+ const duplicate = getWorkspaceByPath(nextPath);
138
+ if (duplicate && duplicate.id !== id) {
139
+ throw new Error(`Workspace с путём '${nextPath}' уже существует.`);
140
+ }
141
+ }
142
+ const nextColor = patch.color?.trim() || existing.color;
143
+ const nextRemote = patch.gitRemote === null
144
+ ? undefined
145
+ : patch.gitRemote !== undefined
146
+ ? patch.gitRemote.trim() || undefined
147
+ : nextPath !== existing.path
148
+ ? readGitRemote(nextPath)
149
+ : existing.gitRemote;
150
+ getDb()
151
+ .prepare("UPDATE workspaces SET name = ?, path = ?, git_remote = ?, color = ? WHERE id = ?")
152
+ .run(nextName, nextPath, nextRemote ?? null, nextColor ?? null, id);
153
+ return {
154
+ id,
155
+ name: nextName,
156
+ path: nextPath,
157
+ gitRemote: nextRemote,
158
+ color: nextColor,
159
+ createdAt: existing.createdAt,
160
+ };
161
+ }
162
+ /**
163
+ * Удаляет workspace. Задачи не удаляются — у них просто очищается
164
+ * workspaceId (с предупреждением в логе).
165
+ */
166
+ export function deleteWorkspace(id) {
167
+ const workspace = getWorkspace(id);
168
+ if (!workspace)
169
+ return false;
170
+ const affected = clearWorkspaceAssignments(id);
171
+ if (affected.length > 0) {
172
+ console.warn(`[workspace] Удалён workspace '${workspace.name}'. ` +
173
+ `Отвязано задач: ${affected.length} (${affected.join(", ")}). ` +
174
+ `Задачи не удалены, workspaceId очищен.`);
175
+ }
176
+ const result = getDb().prepare("DELETE FROM workspaces WHERE id = ?").run(id);
177
+ return Number(result.changes) > 0;
178
+ }
179
+ /** Количество workspace (для сводок и тестов). */
180
+ export function countWorkspaces() {
181
+ const row = getDb().prepare("SELECT COUNT(*) AS count FROM workspaces").get();
182
+ return Number(row?.count) || 0;
183
+ }
@@ -0,0 +1,302 @@
1
+ # Architecture
2
+
3
+ This document explains how `opencode-windows-scheduler` is put together: the process
4
+ model, the modules, the data model and the extension points.
5
+
6
+ - [Design principles](#design-principles)
7
+ - [Process model](#process-model)
8
+ - [Data flow](#data-flow)
9
+ - [Modules](#modules)
10
+ - [Scheduling backends](#scheduling-backends)
11
+ - [Run wrapper](#run-wrapper)
12
+ - [History, metrics and recovery](#history-metrics-and-recovery)
13
+ - [Chains, retries and DAG](#chains-retries-and-dag)
14
+ - [Matrix builds](#matrix-builds)
15
+ - [Workspaces](#workspaces)
16
+ - [Triggers](#triggers)
17
+ - [Storage](#storage)
18
+ - [Interfaces](#interfaces)
19
+ - [Security model](#security-model)
20
+ - [Extension points](#extension-points)
21
+
22
+ ## Design principles
23
+
24
+ 1. **The OS scheduler owns time.** The plugin never keeps a timer in memory for cron
25
+ jobs. Every recurring task becomes a real OS entry (Task Scheduler, launchd,
26
+ crontab), so jobs survive reboots and closed editor windows.
27
+ 2. **The host process owns the UI.** Agent tools, the sidebar GUI, the RPC layer and the
28
+ dashboard live inside the OpenCode plugin host. They are stateless wrappers around
29
+ the database and the OS scheduler.
30
+ 3. **Runs are independent processes.** A job executes `opencode run` through a wrapper
31
+ that enforces timeout, single-instance locking, pre/post hooks and a Quality Gate.
32
+ The wrapper reports the result back to the database, not to the plugin host.
33
+ 4. **One source of truth for definitions is SQLite.** OS entries are derived artifacts:
34
+ they can always be recreated from the database with export/import.
35
+ 5. **Local first.** No network services, no telemetry, no accounts. The dashboard binds
36
+ to localhost only.
37
+
38
+ ## Process model
39
+
40
+ ```
41
+ ┌─────────────────────────────┐
42
+ │ OpenCode (plugin host) │
43
+ │ • agent tools (12) │
44
+ │ • sidebar GUI (gui.tsx) │
45
+ │ • RPC ↔ sidebar │
46
+ │ • dashboard HTTP server │
47
+ │ • chokidar file watcher │
48
+ └──────────┬──────────────────┘
49
+ │ creates / updates
50
+ ▼
51
+ ┌─────────────────────────────┐ ┌──────────────────────────────┐
52
+ │ OS scheduler │ │ SQLite (scheduler.db) │
53
+ │ Windows Task Scheduler │ │ tasks, history, metrics, │
54
+ │ launchd / crontab │ │ templates, settings, │
55
+ └──────────┬──────────────────┘ │ workspaces │
56
+ │ fires │ └──────────────────────────────┘
57
+ ▼ │ ▲
58
+ ┌─────────────────────────────┐ │ │ writes
59
+ │ Run wrapper (.cmd / .sh) │ │ │
60
+ │ • lock │ │ ┌─────────┴──────────────┐
61
+ │ • timeout │ └──│ recorder process │
62
+ │ • pre-flight hook │ │ core/record-history.js │
63
+ │ • opencode run ... │────────▶│ • history / metrics │
64
+ │ • Quality Gate │ │ • retries, chains │
65
+ │ • post-flight hook │ │ • DAG dependents │
66
+ └─────────────────────────────┘ │ • matrix continuation │
67
+ └────────────────────────┘
68
+ ```
69
+
70
+ There are four kinds of processes:
71
+
72
+ | Process | Lifetime | Responsibility |
73
+ | --- | --- | --- |
74
+ | Plugin host | OpenCode session | Register tools/skill, create OS entries, serve RPC and dashboard, watch files |
75
+ | OS scheduler | Always | Fire jobs on schedule or on demand |
76
+ | Run wrapper | Per run | Lock, timeout, hooks, Quality Gate, invoke `opencode run`, call the recorder |
77
+ | Recorder | Per run (short) | Persist history/metrics, schedule retries, trigger chains and dependents, continue matrices |
78
+
79
+ Because the recorder is a separate short-lived process, it cannot rely on in-memory
80
+ state of the plugin host. Everything it needs (definitions, retry state, matrix queue)
81
+ is read from the database or from files under the plugin directory.
82
+
83
+ ## Data flow
84
+
85
+ **Create a task**
86
+
87
+ 1. Agent tool / GUI / import calls `schedulerCreateTask(...)`.
88
+ 2. Definitions are validated (cron, workspace path, matrix rules), a prompt file and a
89
+ wrapper script are written under the plugin directory.
90
+ 3. An OS entry is created through the platform backend.
91
+ 4. The definition is stored in `tasks.definition_json`.
92
+
93
+ **Run a task**
94
+
95
+ 1. The OS scheduler starts the wrapper.
96
+ 2. The wrapper acquires the lock (`locks/<task>.lock`), writes the log
97
+ (`logs/<task>.log`), runs the pre-flight hook and starts `opencode run` with the
98
+ prompt file. Output is streamed to the log.
99
+ 3. When the process ends, the wrapper enforces the timeout result, runs the Quality
100
+ Gate and the post-flight hook.
101
+ 4. The wrapper calls `node dist/core/record-history.js --finish ...` with status,
102
+ duration, tokens, cost, model and hook results.
103
+ 5. The recorder writes `history` and updates `metrics`, then evaluates retries, task
104
+ chains, DAG dependents and matrix continuation.
105
+
106
+ **Read state**
107
+
108
+ `collectTasksView()` (shared by tools, RPC and GUI) merges definitions, the latest
109
+ history record and metrics into a `TaskItem`. Matrix parents get an aggregated status
110
+ from their clones instead of their own last run.
111
+
112
+ ## Modules
113
+
114
+ | Path | Role |
115
+ | --- | --- |
116
+ | `src/index.ts` | Plugin lifecycle, 12 agent tools, RPC handlers, task CRUD, view assembly |
117
+ | `src/rpc.ts` | JSON-schema contracts for every RPC method |
118
+ | `src/gui.tsx` | OpenCode sidebar panel (SolidJS, built to `gui-experimental.cjs`) |
119
+ | `src/server.ts` | Local web dashboard HTTP server and HTML rendering |
120
+ | `src/skill.ts` | Loads and registers the bundled agent skill |
121
+ | `src/task-transfer.ts` | Export/import, validation, `MatrixConfig` types |
122
+ | `src/workspaces.ts` | Workspace registry and path validation |
123
+ | `src/templates.ts` | Reusable task templates |
124
+ | `src/settings.ts` | Plugin settings and notification config |
125
+ | `src/notifications.ts` | Webhook notifications |
126
+ | `src/history.ts` | History model and status types |
127
+ | `src/core/scheduler/` | Platform backends, registry, logs |
128
+ | `src/core/ps-wrapper.ts` | PowerShell wrapper template and `.cmd` generation |
129
+ | `src/core/wrappers/bash.ts` | POSIX wrapper template |
130
+ | `src/core/record-history.ts` | Recorder: history, retries, chains, DAG, matrix continuation |
131
+ | `src/core/matrix.ts` | Fan-out, aggregation, sync, cancel, orphan cleanup |
132
+ | `src/core/dry-run.ts` | Pipeline simulation (no execution) |
133
+ | `src/core/lock.ts` | Single-instance lock manager |
134
+ | `src/core/file-watcher.ts` | chokidar-based file triggers |
135
+ | `src/core/cron-to-schtasks.ts` | Cron → Task Scheduler translation |
136
+ | `src/db/` | SQLite access: schema, migrations, repositories, recovery |
137
+ | `src/shared/jobs-view.ts` | Task view shared by the GUI and dashboard |
138
+
139
+ ## Scheduling backends
140
+
141
+ `scheduler/registry.ts` keeps the mapping between a task name and its OS entry.
142
+ `scheduler/index.ts` picks a backend from `process.platform`.
143
+
144
+ | Platform | Backend | Notes |
145
+ | --- | --- | --- |
146
+ | Windows | `schtasks.exe` | Cron is translated to `MINUTE/HOURLY/DAILY/WEEKLY/MONTHLY` flags; non-cron triggers are registered as `ONCE` at `31.12.2099` |
147
+ | Linux | `crontab` | Task lines with the plugin marker are rewritten via `crontab -` |
148
+ | macOS | `launchd` | `StartCalendarInterval` plists |
149
+ | POSIX fallback | `crontab` | Used when launchd is unavailable |
150
+
151
+ File and MCP triggers are not time-based. They are still registered as a far-future
152
+ one-shot entry so that `runMatrix`, DAG dependencies and manual runs can start them,
153
+ while the OS never fires them on its own. File triggers are additionally watched by
154
+ chokidar inside the plugin host.
155
+
156
+ ## Run wrapper
157
+
158
+ The wrapper is generated per task and is the only place where execution policy is
159
+ enforced:
160
+
161
+ | Concern | Implementation |
162
+ | --- | --- |
163
+ | Working directory | Task `workingDirectory`, or the workspace path, or the plugin directory |
164
+ | Prompt | Written to a prompt file, passed to `opencode run` |
165
+ | Timeout | `timeoutSeconds`; on expiry the child process tree is stopped and the run is marked `timeout` |
166
+ | No overlap | Lock file per task; a second start exits immediately and records `skipped` |
167
+ | Pre-flight | `beforeScript`; non-zero exit marks `preFlight` as failed |
168
+ | Quality Gate | `qualityGate` after a successful run; non-zero exit turns the run into an error |
169
+ | Post-flight | `afterScript`; non-zero exit is reported but does not rewrite a success |
170
+ | Logging | Append-only log per task under `logs/` |
171
+ | History | Calls the recorder with `--start` and `--finish` |
172
+
173
+ Windows uses PowerShell and `.cmd` shims; POSIX uses bash. Both wrappers are generated
174
+ from templates so the policy stays identical across platforms.
175
+
176
+ ## History, metrics and recovery
177
+
178
+ `history` stores one row per run: status (`running`, `success`, `error`, `timeout`,
179
+ `partial`), start/finish timestamps, duration, error text, tokens, cost, model,
180
+ pre/post-flight results, the chained next task, workspace and tool restrictions.
181
+ `metrics` holds per-task counters and totals.
182
+
183
+ If the host or the machine dies mid-run, the row stays in `running`. On the next
184
+ plugin activation, `db/recovery.ts` marks stale `running` rows as `error`, so the UI
185
+ never shows a permanently running task.
186
+
187
+ ## Chains, retries and DAG
188
+
189
+ All three are evaluated by the recorder after a run finishes:
190
+
191
+ - **Retries** — `retryCount`/`retryDelay` with a retry-state file so a crash cannot
192
+ loop forever. Retries are attempted before chains and dependents.
193
+ - **Chains** — `nextTaskOnSuccess` / `nextTaskOnError` start exactly one follow-up task.
194
+ - **DAG** — `dependsOn` is satisfied only when every dependency's latest run is
195
+ successful. For a matrix dependency, all clones must be successful; the parent's own
196
+ aggregate record is not enough.
197
+
198
+ `selectDependentsToTrigger(taskName, definitions, history)` is a pure function, which
199
+ keeps the rules testable.
200
+
201
+ ## Matrix builds
202
+
203
+ A matrix task is a template, not a runnable job:
204
+
205
+ 1. `expandMatrixTask(parent)` produces one clone per workspace:
206
+ `<parent>-matrix-<workspace>`, each with its own `workspaceId`, `matrixParentId`,
207
+ a file trigger and per-workspace overrides applied.
208
+ 2. `runMatrix(parent)` starts clones according to `strategy` (`parallel`/`sequential`)
209
+ and `concurrency`; extra clones wait in `matrixQueue` persisted on the parent.
210
+ 3. On each clone completion, the recorder calls `advanceMatrixAfterClone` (drain the
211
+ queue or start the next sequential clone) and `finalizeMatrixIfComplete`.
212
+ 4. `aggregateMatrixResults(parent)` derives `success` / `error` / `partial` / `running` /
213
+ `empty` from clone history.
214
+ 5. `syncMatrixFamily(parent)` diffs existing clones against a fresh expansion on update:
215
+ missing clones are created, changed clones are updated, extra clones are removed.
216
+ Clones whose latest run is `running` are never touched.
217
+
218
+ The parent is registered in the OS scheduler as a far-future one-shot entry only so it
219
+ can be addressed by name; it never fires on its own.
220
+
221
+ ## Workspaces
222
+
223
+ A workspace is a named directory (usually a git repository) with an id, path, optional
224
+ remote and color. Workspaces provide:
225
+
226
+ - the working directory for a task (`workspaceId` instead of `workingDirectory`);
227
+ - matrix targets (`matrix.workspaceIds`);
228
+ - per-workspace overrides (`matrix.overrides`);
229
+ - dashboard grouping.
230
+
231
+ Paths are validated on creation, update and import: a workspace must point to an
232
+ existing directory.
233
+
234
+ ## Triggers
235
+
236
+ | Trigger | How it fires |
237
+ | --- | --- |
238
+ | `cron` | OS scheduler on the translated schedule |
239
+ | `file` | chokidar watches `watchPath`; debounced change starts the task |
240
+ | `mcp-event` | `emit_event` RPC/tool matches server + event and starts subscribers |
241
+
242
+ Cron expressions are standard 5-field. The Windows backend supports the subset that
243
+ `schtasks` can express; unsupported shapes are rejected at creation time with a clear
244
+ error instead of silently drifting.
245
+
246
+ ## Storage
247
+
248
+ Everything lives under the plugin directory:
249
+
250
+ | Platform | Path |
251
+ | --- | --- |
252
+ | Windows | `%APPDATA%\opencode\windows-scheduler` |
253
+ | macOS/Linux | `$XDG_CONFIG_HOME/opencode/windows-scheduler` (default `~/.config/...`) |
254
+
255
+ ```
256
+ scheduler.db SQLite database (WAL)
257
+ logs/ per-task run logs
258
+ locks/ lock files
259
+ wrappers/ generated .cmd / .sh wrappers
260
+ prompts/ prompt files
261
+ ```
262
+
263
+ Override the database location with `OPENCODE_SCHEDULER_DB` (used by tests). Override
264
+ the whole plugin directory (database, logs, locks, wrappers, prompts) with
265
+ `OPENCODE_SCHEDULER_HOME` on any platform.
266
+
267
+ Schema evolution is additive: `applySchema` runs `CREATE TABLE IF NOT EXISTS` on every
268
+ connection and adds missing columns after `PRAGMA table_info`, so upgrading the plugin
269
+ never requires a manual migration.
270
+
271
+ ## Interfaces
272
+
273
+ | Interface | Audience | Entry point |
274
+ | --- | --- | --- |
275
+ | Agent tools | AI agent | 12 tools registered via `ctx.tool.transform` |
276
+ | Agent skill | AI agent | `skills/scheduled-job-best-practices` |
277
+ | RPC | Sidebar GUI | `src/rpc.ts` contracts, ~30 methods |
278
+ | Sidebar GUI | Human | `gui-experimental.cjs` |
279
+ | Web dashboard | Human | `startDashboardServer` (localhost, random/fixed port) |
280
+
281
+ ## Security model
282
+
283
+ - The dashboard has **no authentication** and binds to localhost. Do not expose it.
284
+ - A job definition is **code**: prompts, hooks, Quality Gates and wrappers all execute
285
+ with your user privileges. Treat task creation like granting shell access.
286
+ - `allowedTools` / `deniedTools` are **metadata passed to the run**, not a sandbox.
287
+ They are recorded in history for audit, but they do not constrain `opencode` at the
288
+ OS level.
289
+ - Secrets are stored in plain text in the SQLite database and in wrapper files. Use
290
+ environment variables or a secret manager for anything sensitive.
291
+ - Workspace paths are validated, but hooks are not sandboxed: only schedule jobs from
292
+ repositories you trust.
293
+
294
+ ## Extension points
295
+
296
+ | Goal | Where to start |
297
+ | --- | --- |
298
+ | New OS backend | Implement `SchedulerBackend` in `src/core/scheduler/`, register it in `index.ts` |
299
+ | New trigger type | Add a `triggerType` branch in `schedulerCreateTask` and in the wrapper |
300
+ | New agent tool | Add a zod schema + execute function, register in `ctx.tool.transform`, add an RPC contract |
301
+ | New dashboard panel | Extend `server.ts` routes and the HTML template |
302
+ | New matrix policy | Extend `MatrixConfig` in `task-transfer.ts` and the logic in `core/matrix.ts` |