opencode-windows-scheduler 0.0.0-stage → 1.1.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 (183) hide show
  1. package/CHANGELOG.md +52 -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 +90 -0
  8. package/dist/core/analytics.d.ts +119 -0
  9. package/dist/core/analytics.d.ts.map +1 -0
  10. package/dist/core/analytics.js +265 -0
  11. package/dist/core/cron-to-schtasks.d.ts +20 -0
  12. package/dist/core/cron-to-schtasks.d.ts.map +1 -0
  13. package/dist/core/cron-to-schtasks.js +233 -0
  14. package/dist/core/dry-run.d.ts +44 -0
  15. package/dist/core/dry-run.d.ts.map +1 -0
  16. package/dist/core/dry-run.js +252 -0
  17. package/dist/core/file-watcher.d.ts +31 -0
  18. package/dist/core/file-watcher.d.ts.map +1 -0
  19. package/dist/core/file-watcher.js +128 -0
  20. package/dist/core/lock.d.ts +43 -0
  21. package/dist/core/lock.d.ts.map +1 -0
  22. package/dist/core/lock.js +118 -0
  23. package/dist/core/matrix.d.ts +167 -0
  24. package/dist/core/matrix.d.ts.map +1 -0
  25. package/dist/core/matrix.js +687 -0
  26. package/dist/core/ps-wrapper.d.ts +60 -0
  27. package/dist/core/ps-wrapper.d.ts.map +1 -0
  28. package/dist/core/ps-wrapper.js +538 -0
  29. package/dist/core/record-history.d.ts +14 -0
  30. package/dist/core/record-history.d.ts.map +1 -0
  31. package/dist/core/record-history.js +360 -0
  32. package/dist/core/retention.d.ts +29 -0
  33. package/dist/core/retention.d.ts.map +1 -0
  34. package/dist/core/retention.js +98 -0
  35. package/dist/core/scheduler/index.d.ts +20 -0
  36. package/dist/core/scheduler/index.d.ts.map +1 -0
  37. package/dist/core/scheduler/index.js +32 -0
  38. package/dist/core/scheduler/linux.d.ts +32 -0
  39. package/dist/core/scheduler/linux.d.ts.map +1 -0
  40. package/dist/core/scheduler/linux.js +115 -0
  41. package/dist/core/scheduler/logs.d.ts +11 -0
  42. package/dist/core/scheduler/logs.d.ts.map +1 -0
  43. package/dist/core/scheduler/logs.js +34 -0
  44. package/dist/core/scheduler/mac.d.ts +39 -0
  45. package/dist/core/scheduler/mac.d.ts.map +1 -0
  46. package/dist/core/scheduler/mac.js +175 -0
  47. package/dist/core/scheduler/posix.d.ts +40 -0
  48. package/dist/core/scheduler/posix.d.ts.map +1 -0
  49. package/dist/core/scheduler/posix.js +86 -0
  50. package/dist/core/scheduler/registry.d.ts +36 -0
  51. package/dist/core/scheduler/registry.d.ts.map +1 -0
  52. package/dist/core/scheduler/registry.js +56 -0
  53. package/dist/core/scheduler/types.d.ts +63 -0
  54. package/dist/core/scheduler/types.d.ts.map +1 -0
  55. package/dist/core/scheduler/types.js +1 -0
  56. package/dist/core/scheduler/windows.d.ts +47 -0
  57. package/dist/core/scheduler/windows.d.ts.map +1 -0
  58. package/dist/core/scheduler/windows.js +375 -0
  59. package/dist/core/wrappers/bash.d.ts +58 -0
  60. package/dist/core/wrappers/bash.d.ts.map +1 -0
  61. package/dist/core/wrappers/bash.js +223 -0
  62. package/dist/db/history-repo.d.ts +102 -0
  63. package/dist/db/history-repo.d.ts.map +1 -0
  64. package/dist/db/history-repo.js +215 -0
  65. package/dist/db/index.d.ts +47 -0
  66. package/dist/db/index.d.ts.map +1 -0
  67. package/dist/db/index.js +120 -0
  68. package/dist/db/metrics-repo.d.ts +43 -0
  69. package/dist/db/metrics-repo.d.ts.map +1 -0
  70. package/dist/db/metrics-repo.js +95 -0
  71. package/dist/db/migrate.d.ts +24 -0
  72. package/dist/db/migrate.d.ts.map +1 -0
  73. package/dist/db/migrate.js +237 -0
  74. package/dist/db/recovery.d.ts +11 -0
  75. package/dist/db/recovery.d.ts.map +1 -0
  76. package/dist/db/recovery.js +38 -0
  77. package/dist/db/schema.d.ts +24 -0
  78. package/dist/db/schema.d.ts.map +1 -0
  79. package/dist/db/schema.js +97 -0
  80. package/dist/db/settings-repo.d.ts +8 -0
  81. package/dist/db/settings-repo.d.ts.map +1 -0
  82. package/dist/db/settings-repo.js +27 -0
  83. package/dist/db/tasks-repo.d.ts +26 -0
  84. package/dist/db/tasks-repo.d.ts.map +1 -0
  85. package/dist/db/tasks-repo.js +120 -0
  86. package/dist/db/templates-repo.d.ts +17 -0
  87. package/dist/db/templates-repo.d.ts.map +1 -0
  88. package/dist/db/templates-repo.js +57 -0
  89. package/dist/history.d.ts +53 -0
  90. package/dist/history.d.ts.map +1 -0
  91. package/dist/history.js +57 -0
  92. package/dist/index.d.ts +156 -0
  93. package/dist/index.d.ts.map +1 -0
  94. package/dist/index.js +2159 -0
  95. package/dist/notifications.d.ts +45 -0
  96. package/dist/notifications.d.ts.map +1 -0
  97. package/dist/notifications.js +135 -0
  98. package/dist/rpc.d.ts +2186 -0
  99. package/dist/rpc.d.ts.map +1 -0
  100. package/dist/rpc.js +924 -0
  101. package/dist/schtasks.d.ts +32 -0
  102. package/dist/schtasks.d.ts.map +1 -0
  103. package/dist/schtasks.js +45 -0
  104. package/dist/server.d.ts +106 -0
  105. package/dist/server.d.ts.map +1 -0
  106. package/dist/server.js +1668 -0
  107. package/dist/settings.d.ts +66 -0
  108. package/dist/settings.d.ts.map +1 -0
  109. package/dist/settings.js +137 -0
  110. package/dist/shared/jobs-view.d.ts +21 -0
  111. package/dist/shared/jobs-view.d.ts.map +1 -0
  112. package/dist/shared/jobs-view.js +28 -0
  113. package/dist/skill.d.ts +15 -0
  114. package/dist/skill.d.ts.map +1 -0
  115. package/dist/skill.js +93 -0
  116. package/dist/task-transfer.d.ts +176 -0
  117. package/dist/task-transfer.d.ts.map +1 -0
  118. package/dist/task-transfer.js +442 -0
  119. package/dist/templates.d.ts +57 -0
  120. package/dist/templates.d.ts.map +1 -0
  121. package/dist/templates.js +16 -0
  122. package/dist/types.d.ts +78 -0
  123. package/dist/types.d.ts.map +1 -0
  124. package/dist/types.js +88 -0
  125. package/dist/version.d.ts +8 -0
  126. package/dist/version.d.ts.map +1 -0
  127. package/dist/version.js +27 -0
  128. package/dist/workspaces.d.ts +55 -0
  129. package/dist/workspaces.d.ts.map +1 -0
  130. package/dist/workspaces.js +183 -0
  131. package/docs/ARCHITECTURE.md +314 -0
  132. package/docs/FEATURES.md +300 -0
  133. package/docs/MIGRATION.md +266 -0
  134. package/docs/dashboard.png +0 -0
  135. package/gui-experimental.cjs +2 -0
  136. package/index.js +1 -0
  137. package/package.json +94 -4
  138. package/scripts/demo-dashboard.mjs +199 -0
  139. package/skills/scheduled-job-best-practices/SKILL.md +155 -0
  140. package/skills/scheduled-job-best-practices/references/recipes.md +123 -0
  141. package/src/core/analytics.ts +378 -0
  142. package/src/core/cron-to-schtasks.ts +269 -0
  143. package/src/core/dry-run.ts +315 -0
  144. package/src/core/file-watcher.ts +171 -0
  145. package/src/core/lock.ts +134 -0
  146. package/src/core/matrix.ts +907 -0
  147. package/src/core/ps-wrapper.ts +572 -0
  148. package/src/core/record-history.ts +493 -0
  149. package/src/core/retention.ts +141 -0
  150. package/src/core/scheduler/index.ts +44 -0
  151. package/src/core/scheduler/linux.ts +125 -0
  152. package/src/core/scheduler/logs.ts +37 -0
  153. package/src/core/scheduler/mac.ts +222 -0
  154. package/src/core/scheduler/posix.ts +111 -0
  155. package/src/core/scheduler/registry.ts +93 -0
  156. package/src/core/scheduler/types.ts +67 -0
  157. package/src/core/scheduler/windows.ts +469 -0
  158. package/src/core/wrappers/bash.ts +282 -0
  159. package/src/db/history-repo.ts +396 -0
  160. package/src/db/index.ts +166 -0
  161. package/src/db/metrics-repo.ts +158 -0
  162. package/src/db/migrate.ts +322 -0
  163. package/src/db/recovery.ts +46 -0
  164. package/src/db/schema.ts +109 -0
  165. package/src/db/settings-repo.ts +31 -0
  166. package/src/db/tasks-repo.ts +162 -0
  167. package/src/db/templates-repo.ts +77 -0
  168. package/src/gui.tsx +2868 -0
  169. package/src/history.ts +107 -0
  170. package/src/index.ts +2768 -0
  171. package/src/notifications.ts +174 -0
  172. package/src/rpc.ts +999 -0
  173. package/src/schtasks.ts +75 -0
  174. package/src/server.ts +1879 -0
  175. package/src/settings.ts +228 -0
  176. package/src/shared/jobs-view.ts +38 -0
  177. package/src/skill.ts +113 -0
  178. package/src/task-transfer.ts +648 -0
  179. package/src/templates.ts +67 -0
  180. package/src/tui.tsx +46 -0
  181. package/src/types.ts +145 -0
  182. package/src/version.ts +27 -0
  183. package/src/workspaces.ts +236 -0
@@ -0,0 +1,314 @@
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: notifications and history retention |
125
+ | `src/notifications.ts` | Webhook notifications |
126
+ | `src/history.ts` | History model and status types |
127
+ | `src/version.ts` | Runtime plugin version (reads package.json) |
128
+ | `src/core/retention.ts` | Daily history prune and incremental vacuum |
129
+ | `src/core/analytics.ts` | Pure 14-day analytics and CSV export |
130
+ | `src/core/scheduler/` | Platform backends, registry, logs |
131
+ | `src/core/ps-wrapper.ts` | PowerShell wrapper template and `.cmd` generation |
132
+ | `src/core/wrappers/bash.ts` | POSIX wrapper template |
133
+ | `src/core/record-history.ts` | Recorder: history, retries, chains, DAG, matrix continuation |
134
+ | `src/core/matrix.ts` | Fan-out, aggregation, sync, cancel, orphan cleanup |
135
+ | `src/core/dry-run.ts` | Pipeline simulation (no execution) |
136
+ | `src/core/lock.ts` | Single-instance lock manager |
137
+ | `src/core/file-watcher.ts` | chokidar-based file triggers |
138
+ | `src/core/cron-to-schtasks.ts` | Cron → Task Scheduler translation |
139
+ | `src/db/` | SQLite access: schema, migrations, repositories, recovery |
140
+ | `src/shared/jobs-view.ts` | Task view shared by the GUI and dashboard |
141
+
142
+ ## Scheduling backends
143
+
144
+ `scheduler/registry.ts` keeps the mapping between a task name and its OS entry.
145
+ `scheduler/index.ts` picks a backend from `process.platform`.
146
+
147
+ | Platform | Backend | Notes |
148
+ | --- | --- | --- |
149
+ | Windows | `schtasks.exe` | Cron is translated to `MINUTE/HOURLY/DAILY/WEEKLY/MONTHLY` flags; non-cron triggers are registered as `ONCE` at `31.12.2099` |
150
+ | Linux | `crontab` | Task lines with the plugin marker are rewritten via `crontab -` |
151
+ | macOS | `launchd` | `StartCalendarInterval` plists |
152
+ | POSIX fallback | `crontab` | Used when launchd is unavailable |
153
+
154
+ File and MCP triggers are not time-based. They are still registered as a far-future
155
+ one-shot entry so that `runMatrix`, DAG dependencies and manual runs can start them,
156
+ while the OS never fires them on its own. File triggers are additionally watched by
157
+ chokidar inside the plugin host.
158
+
159
+ ## Run wrapper
160
+
161
+ The wrapper is generated per task and is the only place where execution policy is
162
+ enforced:
163
+
164
+ | Concern | Implementation |
165
+ | --- | --- |
166
+ | Working directory | Task `workingDirectory`, or the workspace path, or the plugin directory |
167
+ | Prompt | Written to a prompt file, passed to `opencode run` |
168
+ | Timeout | `timeoutSeconds`; on expiry the child process tree is stopped and the run is marked `timeout` |
169
+ | No overlap | Lock file per task; a second start exits immediately and records `skipped` |
170
+ | Pre-flight | `beforeScript`; non-zero exit marks `preFlight` as failed |
171
+ | Quality Gate | `qualityGate` after a successful run; non-zero exit turns the run into an error |
172
+ | Post-flight | `afterScript`; non-zero exit is reported but does not rewrite a success |
173
+ | Logging | Append-only log per task under `logs/` |
174
+ | History | Calls the recorder with `--start` and `--finish` |
175
+
176
+ Windows uses PowerShell and `.cmd` shims; POSIX uses bash. Both wrappers are generated
177
+ from templates so the policy stays identical across platforms.
178
+
179
+ ## History, metrics and recovery
180
+
181
+ `history` stores one row per run: status (`running`, `success`, `error`, `timeout`,
182
+ `partial`), start/finish timestamps, duration, error text, tokens, cost, model,
183
+ pre/post-flight results, the chained next task, workspace and tool restrictions.
184
+ `metrics` holds per-task counters and totals.
185
+
186
+ If the host or the machine dies mid-run, the row stays in `running`. On the next
187
+ plugin activation, `db/recovery.ts` marks stale `running` rows as `error`, so the UI
188
+ never shows a permanently running task.
189
+
190
+ History is bounded by retention: `settings.json` carries `history.retentionDays` and
191
+ `history.maxRecords` (defaults 30 / 5000, `0` disables). Cleanup runs at most once a
192
+ day on plugin start (`core/retention.ts`), prunes only finished rows via
193
+ `pruneHistory` in `db/history-repo.ts`, then `PRAGMA incremental_vacuum` frees space.
194
+ Aggregates in `metrics` are never pruned. Period analytics (per-day buckets, success
195
+ rate, tokens, cost, matrix/model breakdowns) are computed by `core/analytics.ts` and
196
+ exposed as `get_analytics` / `GET /api/analytics`; the dashboard renders a 14-day
197
+ block and `GET /api/history/export` serves CSV/JSON.
198
+
199
+ ## Chains, retries and DAG
200
+
201
+ All three are evaluated by the recorder after a run finishes:
202
+
203
+ - **Retries** — `retryCount`/`retryDelay` with a retry-state file so a crash cannot
204
+ loop forever. Retries are attempted before chains and dependents.
205
+ - **Chains** — `nextTaskOnSuccess` / `nextTaskOnError` start exactly one follow-up task.
206
+ - **DAG** — `dependsOn` is satisfied only when every dependency's latest run is
207
+ successful. For a matrix dependency, all clones must be successful; the parent's own
208
+ aggregate record is not enough.
209
+
210
+ `selectDependentsToTrigger(taskName, definitions, history)` is a pure function, which
211
+ keeps the rules testable.
212
+
213
+ ## Matrix builds
214
+
215
+ A matrix task is a template, not a runnable job:
216
+
217
+ 1. `expandMatrixTask(parent)` produces one clone per workspace:
218
+ `<parent>-matrix-<workspace>`, each with its own `workspaceId`, `matrixParentId`,
219
+ a file trigger and per-workspace overrides applied.
220
+ 2. `runMatrix(parent)` starts clones according to `strategy` (`parallel`/`sequential`)
221
+ and `concurrency`; extra clones wait in `matrixQueue` persisted on the parent.
222
+ 3. On each clone completion, the recorder calls `advanceMatrixAfterClone` (drain the
223
+ queue or start the next sequential clone) and `finalizeMatrixIfComplete`.
224
+ 4. `aggregateMatrixResults(parent)` derives `success` / `error` / `partial` / `running` /
225
+ `empty` from clone history.
226
+ 5. `syncMatrixFamily(parent)` diffs existing clones against a fresh expansion on update:
227
+ missing clones are created, changed clones are updated, extra clones are removed.
228
+ Clones whose latest run is `running` are never touched.
229
+
230
+ The parent is registered in the OS scheduler as a far-future one-shot entry only so it
231
+ can be addressed by name; it never fires on its own.
232
+
233
+ ## Workspaces
234
+
235
+ A workspace is a named directory (usually a git repository) with an id, path, optional
236
+ remote and color. Workspaces provide:
237
+
238
+ - the working directory for a task (`workspaceId` instead of `workingDirectory`);
239
+ - matrix targets (`matrix.workspaceIds`);
240
+ - per-workspace overrides (`matrix.overrides`);
241
+ - dashboard grouping.
242
+
243
+ Paths are validated on creation, update and import: a workspace must point to an
244
+ existing directory.
245
+
246
+ ## Triggers
247
+
248
+ | Trigger | How it fires |
249
+ | --- | --- |
250
+ | `cron` | OS scheduler on the translated schedule |
251
+ | `file` | chokidar watches `watchPath`; debounced change starts the task |
252
+ | `mcp-event` | `emit_event` RPC/tool matches server + event and starts subscribers |
253
+
254
+ Cron expressions are standard 5-field. The Windows backend supports the subset that
255
+ `schtasks` can express; unsupported shapes are rejected at creation time with a clear
256
+ error instead of silently drifting.
257
+
258
+ ## Storage
259
+
260
+ Everything lives under the plugin directory:
261
+
262
+ | Platform | Path |
263
+ | --- | --- |
264
+ | Windows | `%APPDATA%\opencode\windows-scheduler` |
265
+ | macOS/Linux | `$XDG_CONFIG_HOME/opencode/windows-scheduler` (default `~/.config/...`) |
266
+
267
+ ```
268
+ scheduler.db SQLite database (WAL)
269
+ logs/ per-task run logs
270
+ locks/ lock files
271
+ wrappers/ generated .cmd / .sh wrappers
272
+ prompts/ prompt files
273
+ ```
274
+
275
+ Override the database location with `OPENCODE_SCHEDULER_DB` (used by tests). Override
276
+ the whole plugin directory (database, logs, locks, wrappers, prompts) with
277
+ `OPENCODE_SCHEDULER_HOME` on any platform.
278
+
279
+ Schema evolution is additive: `applySchema` runs `CREATE TABLE IF NOT EXISTS` on every
280
+ connection and adds missing columns after `PRAGMA table_info`, so upgrading the plugin
281
+ never requires a manual migration.
282
+
283
+ ## Interfaces
284
+
285
+ | Interface | Audience | Entry point |
286
+ | --- | --- | --- |
287
+ | Agent tools | AI agent | 12 tools registered via `ctx.tool.transform` |
288
+ | Agent skill | AI agent | `skills/scheduled-job-best-practices` |
289
+ | RPC | Sidebar GUI | `src/rpc.ts` contracts, ~30 methods |
290
+ | Sidebar GUI | Human | `gui-experimental.cjs` |
291
+ | Web dashboard | Human | `startDashboardServer` (localhost, random/fixed port) |
292
+
293
+ ## Security model
294
+
295
+ - The dashboard has **no authentication** and binds to localhost. Do not expose it.
296
+ - A job definition is **code**: prompts, hooks, Quality Gates and wrappers all execute
297
+ with your user privileges. Treat task creation like granting shell access.
298
+ - `allowedTools` / `deniedTools` are **metadata passed to the run**, not a sandbox.
299
+ They are recorded in history for audit, but they do not constrain `opencode` at the
300
+ OS level.
301
+ - Secrets are stored in plain text in the SQLite database and in wrapper files. Use
302
+ environment variables or a secret manager for anything sensitive.
303
+ - Workspace paths are validated, but hooks are not sandboxed: only schedule jobs from
304
+ repositories you trust.
305
+
306
+ ## Extension points
307
+
308
+ | Goal | Where to start |
309
+ | --- | --- |
310
+ | New OS backend | Implement `SchedulerBackend` in `src/core/scheduler/`, register it in `index.ts` |
311
+ | New trigger type | Add a `triggerType` branch in `schedulerCreateTask` and in the wrapper |
312
+ | New agent tool | Add a zod schema + execute function, register in `ctx.tool.transform`, add an RPC contract |
313
+ | New dashboard panel | Extend `server.ts` routes and the HTML template |
314
+ | New matrix policy | Extend `MatrixConfig` in `task-transfer.ts` and the logic in `core/matrix.ts` |
@@ -0,0 +1,300 @@
1
+ # Features
2
+
3
+ A complete catalog of what the scheduler can do, with examples and the caveats that
4
+ matter in practice.
5
+
6
+ - [Scheduling](#scheduling)
7
+ - [Execution policy](#execution-policy)
8
+ - [Orchestration](#orchestration)
9
+ - [Multi-repository workspaces](#multi-repository-workspaces)
10
+ - [Observability](#observability)
11
+ - [Management](#management)
12
+ - [Agent interface](#agent-interface)
13
+ - [Platform support](#platform-support)
14
+ - [Limits and non-goals](#limits-and-non-goals)
15
+
16
+ ## Scheduling
17
+
18
+ ### Cron schedules
19
+
20
+ Five-field cron: `minute hour day-of-month month day-of-week`.
21
+
22
+ | Pattern | Example | Meaning |
23
+ | --- | --- | --- |
24
+ | Every N minutes | `*/15 * * * *` | Every 15 minutes |
25
+ | Fixed time | `0 9 * * *` | Daily at 09:00 |
26
+ | Weekdays | `30 8 * * 1-5` | 08:30 Monday to Friday |
27
+ | Monthly | `0 3 1 * *` | 03:00 on the 1st |
28
+
29
+ The Windows backend translates cron to native Task Scheduler triggers. Expressions
30
+ that `schtasks` cannot express are rejected at creation time with an explicit error
31
+ instead of being silently approximated.
32
+
33
+ ### File triggers
34
+
35
+ ```json
36
+ {
37
+ "name": "regen-api-client",
38
+ "triggerType": "file",
39
+ "watchPath": "C:\\projects\\api\\openapi.yaml",
40
+ "prompt": "Regenerate the API client from openapi.yaml and run contract tests."
41
+ }
42
+ ```
43
+
44
+ The file is watched with chokidar in the plugin host, changes are debounced. File
45
+ triggers ignore `schedule`.
46
+
47
+ ### MCP event triggers
48
+
49
+ ```json
50
+ {
51
+ "name": "on-pr-opened",
52
+ "triggerType": "mcp-event",
53
+ "mcpEvent": { "server": "github", "event": "pull_request.opened", "filter": "repo=acme/api" },
54
+ "prompt": "Review the newly opened pull request."
55
+ }
56
+ ```
57
+
58
+ Events are emitted through the `emit_event` RPC method.
59
+
60
+ ### Manual runs and pause
61
+
62
+ - `run_task_now` starts a task immediately, through the same wrapper (timeout, lock,
63
+ hooks, Quality Gate).
64
+ - `pause_task` / `resume_task` disable and re-enable the OS entry. For a matrix parent
65
+ every clone is paused.
66
+
67
+ ## Execution policy
68
+
69
+ ### Timeout and no-overlap
70
+
71
+ Every run has `timeoutSeconds` (default 3600). On expiry the process tree is stopped
72
+ and the run is recorded as `timeout`. A lock file prevents two runs of the same task
73
+ from overlapping; the second start exits immediately and is recorded as `skipped`.
74
+
75
+ ### Pre-flight, Quality Gate, post-flight
76
+
77
+ ```json
78
+ {
79
+ "name": "nightly-deps",
80
+ "schedule": "0 2 * * *",
81
+ "beforeScript": "git pull --ff-only",
82
+ "prompt": "Update dependencies, fix breaking changes, keep the diff minimal.",
83
+ "qualityGate": "npm test",
84
+ "afterScript": "git push",
85
+ "timeoutSeconds": 2400
86
+ }
87
+ ```
88
+
89
+ | Hook | When | Effect of non-zero exit |
90
+ | --- | --- | --- |
91
+ | `beforeScript` | before the agent starts | run is cancelled, pre-flight marked failed |
92
+ | `qualityGate` | after a successful response | run is marked as a Quality Gate failure (error) |
93
+ | `afterScript` | after the run, even on failure | reported in history, does not rewrite a success |
94
+
95
+ ### Retries
96
+
97
+ `retryCount` and `retryDelay` (seconds) retry a failed run. Retry state is persisted,
98
+ so a crash cannot produce an infinite retry loop. Retries happen before chains and
99
+ dependents.
100
+
101
+ ### Model and priority
102
+
103
+ `model` selects an OpenCode model (for example `anthropic/claude-3-5-sonnet`);
104
+ omitting it uses the OpenCode default. `priority` is `0..10` and is passed through to
105
+ the scheduler entry.
106
+
107
+ ### Tool restrictions
108
+
109
+ `allowedTools` and `deniedTools` declare the intended role of the job. They are
110
+ recorded in history for audit. They are **metadata, not a sandbox**: they do not
111
+ restrict `opencode` at runtime today.
112
+
113
+ ## Orchestration
114
+
115
+ ### Chains
116
+
117
+ ```json
118
+ { "name": "build", "nextTaskOnSuccess": "deploy", "nextTaskOnError": "notify-failure" }
119
+ ```
120
+
121
+ Exactly one follow-up task is started after a run.
122
+
123
+ ### DAG dependencies
124
+
125
+ ```json
126
+ { "name": "smoke-tests", "dependsOn": ["deploy"], "schedule": "0 * * * *" }
127
+ ```
128
+
129
+ A dependent starts only when every dependency's latest run is successful. If a
130
+ dependency is a matrix, **all clones** must be successful — a `partial` matrix blocks
131
+ dependents.
132
+
133
+ ### Matrix builds (fan-out)
134
+
135
+ One definition, one clone per workspace:
136
+
137
+ ```json
138
+ {
139
+ "name": "deploy",
140
+ "schedule": "0 3 * * *",
141
+ "prompt": "Build, test and deploy this repository. Report what changed.",
142
+ "matrix": {
143
+ "workspaceIds": ["ws-frontend", "ws-backend", "ws-mobile"],
144
+ "strategy": "parallel",
145
+ "failureMode": "continue",
146
+ "concurrency": 2,
147
+ "overrides": {
148
+ "ws-mobile": { "qualityGate": "flutter test", "prompt": "Use the Flutter toolchain." }
149
+ }
150
+ }
151
+ }
152
+ ```
153
+
154
+ | Field | Default | Meaning |
155
+ | --- | --- | --- |
156
+ | `strategy` | `parallel` | `sequential` starts the next clone only after the previous one finishes |
157
+ | `failureMode` | `continue` | `stop` aborts the remaining clones after the first failure |
158
+ | `concurrency` | unlimited | Maximum clones running at once (ignored for `sequential`) |
159
+ | `aggregation` | `summary` | `summary` writes one aggregate record for the parent |
160
+ | `createAggregator` | `false` | Also create `<parent>-matrix-complete` depending on every clone |
161
+ | `overrides` | none | Per-workspace prompt/model/Quality Gate/hooks |
162
+
163
+ Behavior worth knowing:
164
+
165
+ - Clones are named `<parent>-matrix-<workspace>`, inherit the parent definition and get
166
+ their own working directory.
167
+ - The parent never runs itself; its status is the aggregate: `success`, `error`,
168
+ `partial` (some clones failed under `continue`), or `running`.
169
+ - Editing the parent (workspaces, prompt, overrides, concurrency) **syncs** the clone
170
+ set: missing clones are created, changed ones updated, removed ones deleted. Clones
171
+ with a running job are never touched.
172
+ - Cancelling a matrix (`matrix_control` with `action: "cancel"`) marks pending clones
173
+ as cancelled and stops running ones. Deleting a parent deletes its whole family.
174
+ - `matrix_control` with `action: "cleanup"` removes orphaned clones whose parent is
175
+ gone; the same cleanup also runs at plugin startup.
176
+
177
+ ## Multi-repository workspaces
178
+
179
+ A workspace is a named directory: id, name, path, optional git remote and color.
180
+
181
+ ```json
182
+ { "id": "ws-api", "name": "API", "path": "C:\\projects\\api", "color": "#3b82f6" }
183
+ ```
184
+
185
+ Use `workspaceId` instead of `workingDirectory` to run a task in a workspace. Paths are
186
+ validated on add/update/import, and the dashboard groups tasks and runs by workspace.
187
+ Workspaces are the unit that matrix builds fan out to.
188
+
189
+ ## Observability
190
+
191
+ ### History
192
+
193
+ Every run becomes a row: status, start/finish, duration, error, tokens, cost, model,
194
+ pre/post-flight results, next chained task, workspace and tool restrictions. Statuses:
195
+
196
+ | Status | Meaning |
197
+ | --- | --- |
198
+ | `running` | started, not finished |
199
+ | `success` | finished, no Quality Gate failure |
200
+ | `error` | agent error, hook failure or Quality Gate failure |
201
+ | `timeout` | killed by the timeout |
202
+ | `partial` | matrix aggregate with both successes and failures |
203
+
204
+ ### Metrics
205
+
206
+ Per-task counters and totals: runs, successes, errors, tokens, cost. Available through
207
+ `get_history`, the RPC layer and the dashboard header. A 14-day analytics slice —
208
+ per-day buckets (UTC), success rate, token-based cost estimate, top tasks by cost,
209
+ matrix and model breakdowns — is available through `get_analytics` /
210
+ `GET /api/analytics` and the dashboard's «📊 Аналитика за период» block. History is
211
+ pruned automatically (age and size limits, see Settings) and can be exported as
212
+ CSV/JSON (`GET /api/history/export`).
213
+
214
+ ### Logs
215
+
216
+ Each run appends to `logs/<task>.log` — pre/post hooks, Quality Gate output and the
217
+ agent's stdout/stderr. `get_task_logs` returns the tail (1–1000 lines).
218
+
219
+ ### Dry run
220
+
221
+ `dry_run` simulates one task or every task: execution order, DAG prerequisites, matrix
222
+ fan-out and estimated time. Nothing is executed and nothing is created.
223
+
224
+ ### Dashboard
225
+
226
+ A local web dashboard shows tasks, matrix tabs, per-workspace summaries, DAG markers,
227
+ metrics, a 14-day analytics block (KPIs, daily bar chart, top tasks by cost, matrices),
228
+ recent runs and CSV/JSON history export. It binds to localhost and has no authentication
229
+ — do not expose it. `GET /api/health` reports plugin version, scheduler backend, queue
230
+ depth and database status for external monitoring.
231
+
232
+ ## Management
233
+
234
+ ### Templates
235
+
236
+ Save a definition as a reusable template, then create tasks from it with one click or
237
+ one tool call.
238
+
239
+ ### Export and import
240
+
241
+ `export_tasks` produces a versioned JSON document with definitions, including matrix
242
+ configuration and `matrixParentId`. `import_tasks` validates every record and reports
243
+ per-record errors instead of failing the whole batch. Unknown workspaces and invalid
244
+ matrix combinations are rejected explicitly.
245
+
246
+ ### Notifications
247
+
248
+ Webhook notifications on run completion, configurable in settings and testable with
249
+ `test_notification`.
250
+
251
+ ### Crash recovery
252
+
253
+ Runs left in `running` after a crash are marked `error` on the next plugin start, so
254
+ the timeline never lies. Orphaned matrix clones are cleaned up at startup as well.
255
+
256
+ ### Settings
257
+
258
+ Global defaults (timeout, concurrency, notifications, history retention) live in
259
+ `settings.json` and are editable from the GUI/RPC layer. History retention keeps the
260
+ raw run log bounded: `history.retentionDays` (default 30) and `history.maxRecords`
261
+ (default 5000); `0` disables the respective limit. Cleanup runs at most once a day on
262
+ plugin start, records `lastCleanupAt` / `lastCleanupDeleted`, and is also available as
263
+ the `cleanup_history` RPC and the GUI's «Очистить сейчас» button. Aggregates in
264
+ `metrics.json` are not affected by retention.
265
+
266
+ ## Agent interface
267
+
268
+ Twelve tools: `schedule_task`, `list_tasks`, `update_task`, `delete_task`,
269
+ `run_task_now`, `pause_task`, `resume_task`, `get_history`, `get_task_logs`, `dry_run`,
270
+ `manage_workspaces`, `matrix_control`.
271
+
272
+ A bundled skill, `scheduled-job-best-practices`, teaches the agent safe defaults:
273
+ least privilege, Quality Gates, timeout, matrix concurrency, DAG rules and a
274
+ create → dry-run → run-now → inspect loop. It is registered automatically by the
275
+ plugin, no installation step required.
276
+
277
+ ## Platform support
278
+
279
+ | Capability | Windows | Linux | macOS |
280
+ | --- | --- | --- | --- |
281
+ | Cron scheduling | Task Scheduler | crontab | launchd |
282
+ | Fallback | — | — | crontab |
283
+ | Timeout and lock | PowerShell wrapper | bash wrapper | bash wrapper |
284
+ | File triggers | chokidar | chokidar | chokidar |
285
+ | History, metrics, dashboard | yes | yes | yes |
286
+ | Agent tools and skill | yes | yes | yes |
287
+
288
+ ## Limits and non-goals
289
+
290
+ - **No one-shot scheduling yet.** Only cron, file and MCP-event triggers exist; use
291
+ `run_task_now` for immediate runs. A one-shot trigger is on the roadmap.
292
+ - **No session continuity.** Every run starts a fresh `opencode run` session.
293
+ - **No sandbox.** Hooks, Quality Gates and prompts run with your user privileges.
294
+ - **No authentication on the dashboard.** Localhost only by design.
295
+ - **Secrets are not encrypted.** Use environment variables or an external secret
296
+ manager.
297
+ - **`allowedTools` / `deniedTools` are advisory.** They document intent and are
298
+ recorded in history; enforcement is not implemented.
299
+ - **Matrix clones are separate tasks.** They appear in the task list (grouped under the
300
+ parent) and consume global concurrency slots like any other run.