agent-steward 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (345) hide show
  1. package/CHANGELOG.md +399 -0
  2. package/CROSS_PLATFORM.md +151 -0
  3. package/README.md +307 -15
  4. package/ROADMAP-STRATEGY.md +196 -0
  5. package/ROADMAP.md +184 -0
  6. package/dist/core/analytics.d.ts +132 -0
  7. package/dist/core/analytics.d.ts.map +1 -0
  8. package/dist/core/analytics.js +290 -0
  9. package/dist/core/audit.d.ts +96 -0
  10. package/dist/core/audit.d.ts.map +1 -0
  11. package/dist/core/audit.js +297 -0
  12. package/dist/core/cron-to-schtasks.d.ts +12 -0
  13. package/dist/core/cron-to-schtasks.d.ts.map +1 -0
  14. package/dist/core/cron-to-schtasks.js +175 -0
  15. package/dist/core/dry-run.d.ts +102 -0
  16. package/dist/core/dry-run.d.ts.map +1 -0
  17. package/dist/core/dry-run.js +447 -0
  18. package/dist/core/file-watcher.d.ts +31 -0
  19. package/dist/core/file-watcher.d.ts.map +1 -0
  20. package/dist/core/file-watcher.js +186 -0
  21. package/dist/core/git-trigger.d.ts +82 -0
  22. package/dist/core/git-trigger.d.ts.map +1 -0
  23. package/dist/core/git-trigger.js +312 -0
  24. package/dist/core/glob.d.ts +38 -0
  25. package/dist/core/glob.d.ts.map +1 -0
  26. package/dist/core/glob.js +233 -0
  27. package/dist/core/local-ai.d.ts +52 -0
  28. package/dist/core/local-ai.d.ts.map +1 -0
  29. package/dist/core/local-ai.js +119 -0
  30. package/dist/core/lock.d.ts +57 -0
  31. package/dist/core/lock.d.ts.map +1 -0
  32. package/dist/core/lock.js +193 -0
  33. package/dist/core/matrix.d.ts +167 -0
  34. package/dist/core/matrix.d.ts.map +1 -0
  35. package/dist/core/matrix.js +724 -0
  36. package/dist/core/native-notify.d.ts +36 -0
  37. package/dist/core/native-notify.d.ts.map +1 -0
  38. package/dist/core/native-notify.js +113 -0
  39. package/dist/core/one-shot.d.ts +90 -0
  40. package/dist/core/one-shot.d.ts.map +1 -0
  41. package/dist/core/one-shot.js +182 -0
  42. package/dist/core/otel.d.ts +4 -0
  43. package/dist/core/otel.d.ts.map +1 -0
  44. package/dist/core/otel.js +98 -0
  45. package/dist/core/permissions.d.ts +69 -0
  46. package/dist/core/permissions.d.ts.map +1 -0
  47. package/dist/core/permissions.js +143 -0
  48. package/dist/core/prometheus.d.ts +23 -0
  49. package/dist/core/prometheus.d.ts.map +1 -0
  50. package/dist/core/prometheus.js +146 -0
  51. package/dist/core/ps-wrapper.d.ts +73 -0
  52. package/dist/core/ps-wrapper.d.ts.map +1 -0
  53. package/dist/core/ps-wrapper.js +1091 -0
  54. package/dist/core/record-history.d.ts +25 -0
  55. package/dist/core/record-history.d.ts.map +1 -0
  56. package/dist/core/record-history.js +471 -0
  57. package/dist/core/retention.d.ts +29 -0
  58. package/dist/core/retention.d.ts.map +1 -0
  59. package/dist/core/retention.js +98 -0
  60. package/dist/core/savings.d.ts +70 -0
  61. package/dist/core/savings.d.ts.map +1 -0
  62. package/dist/core/savings.js +87 -0
  63. package/dist/core/schedule-gate.d.ts +2 -0
  64. package/dist/core/schedule-gate.d.ts.map +1 -0
  65. package/dist/core/schedule-gate.js +211 -0
  66. package/dist/core/schedule-v2.d.ts +116 -0
  67. package/dist/core/schedule-v2.d.ts.map +1 -0
  68. package/dist/core/schedule-v2.js +586 -0
  69. package/dist/core/scheduler/at-fallback.d.ts +42 -0
  70. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  71. package/dist/core/scheduler/at-fallback.js +70 -0
  72. package/dist/core/scheduler/index.d.ts +32 -0
  73. package/dist/core/scheduler/index.d.ts.map +1 -0
  74. package/dist/core/scheduler/index.js +63 -0
  75. package/dist/core/scheduler/linux.d.ts +46 -0
  76. package/dist/core/scheduler/linux.d.ts.map +1 -0
  77. package/dist/core/scheduler/linux.js +261 -0
  78. package/dist/core/scheduler/logs.d.ts +11 -0
  79. package/dist/core/scheduler/logs.d.ts.map +1 -0
  80. package/dist/core/scheduler/logs.js +34 -0
  81. package/dist/core/scheduler/mac.d.ts +46 -0
  82. package/dist/core/scheduler/mac.d.ts.map +1 -0
  83. package/dist/core/scheduler/mac.js +256 -0
  84. package/dist/core/scheduler/posix.d.ts +40 -0
  85. package/dist/core/scheduler/posix.d.ts.map +1 -0
  86. package/dist/core/scheduler/posix.js +100 -0
  87. package/dist/core/scheduler/registry.d.ts +43 -0
  88. package/dist/core/scheduler/registry.d.ts.map +1 -0
  89. package/dist/core/scheduler/registry.js +57 -0
  90. package/dist/core/scheduler/types.d.ts +86 -0
  91. package/dist/core/scheduler/types.d.ts.map +1 -0
  92. package/dist/core/scheduler/types.js +1 -0
  93. package/dist/core/scheduler/windows.d.ts +112 -0
  94. package/dist/core/scheduler/windows.d.ts.map +1 -0
  95. package/dist/core/scheduler/windows.js +749 -0
  96. package/dist/core/secrets.d.ts +66 -0
  97. package/dist/core/secrets.d.ts.map +1 -0
  98. package/dist/core/secrets.js +433 -0
  99. package/dist/core/self-analysis.d.ts +117 -0
  100. package/dist/core/self-analysis.d.ts.map +1 -0
  101. package/dist/core/self-analysis.js +539 -0
  102. package/dist/core/session.d.ts +42 -0
  103. package/dist/core/session.d.ts.map +1 -0
  104. package/dist/core/session.js +134 -0
  105. package/dist/core/shutdown.d.ts +26 -0
  106. package/dist/core/shutdown.d.ts.map +1 -0
  107. package/dist/core/shutdown.js +49 -0
  108. package/dist/core/structured-log.d.ts +84 -0
  109. package/dist/core/structured-log.d.ts.map +1 -0
  110. package/dist/core/structured-log.js +146 -0
  111. package/dist/core/summary.d.ts +69 -0
  112. package/dist/core/summary.d.ts.map +1 -0
  113. package/dist/core/summary.js +250 -0
  114. package/dist/core/telegram.d.ts +55 -0
  115. package/dist/core/telegram.d.ts.map +1 -0
  116. package/dist/core/telegram.js +344 -0
  117. package/dist/core/triage-chain.d.ts +40 -0
  118. package/dist/core/triage-chain.d.ts.map +1 -0
  119. package/dist/core/triage-chain.js +80 -0
  120. package/dist/core/triage-compare.d.ts +68 -0
  121. package/dist/core/triage-compare.d.ts.map +1 -0
  122. package/dist/core/triage-compare.js +184 -0
  123. package/dist/core/triage-rules.d.ts +23 -0
  124. package/dist/core/triage-rules.d.ts.map +1 -0
  125. package/dist/core/triage-rules.js +196 -0
  126. package/dist/core/triage-shadow.d.ts +91 -0
  127. package/dist/core/triage-shadow.d.ts.map +1 -0
  128. package/dist/core/triage-shadow.js +160 -0
  129. package/dist/core/triage-worker.d.ts +55 -0
  130. package/dist/core/triage-worker.d.ts.map +1 -0
  131. package/dist/core/triage-worker.js +314 -0
  132. package/dist/core/triage.d.ts +76 -0
  133. package/dist/core/triage.d.ts.map +1 -0
  134. package/dist/core/triage.js +271 -0
  135. package/dist/core/watch-paths.d.ts +6 -0
  136. package/dist/core/watch-paths.d.ts.map +1 -0
  137. package/dist/core/watch-paths.js +62 -0
  138. package/dist/core/wrappers/bash.d.ts +95 -0
  139. package/dist/core/wrappers/bash.d.ts.map +1 -0
  140. package/dist/core/wrappers/bash.js +413 -0
  141. package/dist/db/git-state-repo.d.ts +16 -0
  142. package/dist/db/git-state-repo.d.ts.map +1 -0
  143. package/dist/db/git-state-repo.js +38 -0
  144. package/dist/db/history-repo.d.ts +110 -0
  145. package/dist/db/history-repo.d.ts.map +1 -0
  146. package/dist/db/history-repo.js +300 -0
  147. package/dist/db/index.d.ts +49 -0
  148. package/dist/db/index.d.ts.map +1 -0
  149. package/dist/db/index.js +128 -0
  150. package/dist/db/metrics-repo.d.ts +46 -0
  151. package/dist/db/metrics-repo.d.ts.map +1 -0
  152. package/dist/db/metrics-repo.js +103 -0
  153. package/dist/db/migrate.d.ts +24 -0
  154. package/dist/db/migrate.d.ts.map +1 -0
  155. package/dist/db/migrate.js +244 -0
  156. package/dist/db/recovery.d.ts +11 -0
  157. package/dist/db/recovery.d.ts.map +1 -0
  158. package/dist/db/recovery.js +38 -0
  159. package/dist/db/run-journal.d.ts +60 -0
  160. package/dist/db/run-journal.d.ts.map +1 -0
  161. package/dist/db/run-journal.js +143 -0
  162. package/dist/db/run-resume.d.ts +48 -0
  163. package/dist/db/run-resume.d.ts.map +1 -0
  164. package/dist/db/run-resume.js +137 -0
  165. package/dist/db/runs-repo.d.ts +120 -0
  166. package/dist/db/runs-repo.d.ts.map +1 -0
  167. package/dist/db/runs-repo.js +319 -0
  168. package/dist/db/schema.d.ts +38 -0
  169. package/dist/db/schema.d.ts.map +1 -0
  170. package/dist/db/schema.js +325 -0
  171. package/dist/db/settings-repo.d.ts +8 -0
  172. package/dist/db/settings-repo.d.ts.map +1 -0
  173. package/dist/db/settings-repo.js +27 -0
  174. package/dist/db/tasks-repo.d.ts +26 -0
  175. package/dist/db/tasks-repo.d.ts.map +1 -0
  176. package/dist/db/tasks-repo.js +120 -0
  177. package/dist/db/templates-repo.d.ts +17 -0
  178. package/dist/db/templates-repo.d.ts.map +1 -0
  179. package/dist/db/templates-repo.js +57 -0
  180. package/dist/history.d.ts +60 -0
  181. package/dist/history.d.ts.map +1 -0
  182. package/dist/history.js +70 -0
  183. package/dist/i18n.d.ts +75 -0
  184. package/dist/i18n.d.ts.map +1 -0
  185. package/dist/i18n.js +357 -0
  186. package/dist/index.d.ts +858 -0
  187. package/dist/index.d.ts.map +1 -0
  188. package/dist/index.js +5209 -0
  189. package/dist/integrations.d.ts +72 -0
  190. package/dist/integrations.d.ts.map +1 -0
  191. package/dist/integrations.js +233 -0
  192. package/dist/notifications.d.ts +199 -0
  193. package/dist/notifications.d.ts.map +1 -0
  194. package/dist/notifications.js +967 -0
  195. package/dist/profiles.d.ts +64 -0
  196. package/dist/profiles.d.ts.map +1 -0
  197. package/dist/profiles.js +305 -0
  198. package/dist/rpc.d.ts +3915 -0
  199. package/dist/rpc.d.ts.map +1 -0
  200. package/dist/rpc.js +1596 -0
  201. package/dist/schtasks.d.ts +32 -0
  202. package/dist/schtasks.d.ts.map +1 -0
  203. package/dist/schtasks.js +45 -0
  204. package/dist/server.d.ts +128 -0
  205. package/dist/server.d.ts.map +1 -0
  206. package/dist/server.js +2414 -0
  207. package/dist/settings.d.ts +389 -0
  208. package/dist/settings.d.ts.map +1 -0
  209. package/dist/settings.js +770 -0
  210. package/dist/shared/jobs-view.d.ts +59 -0
  211. package/dist/shared/jobs-view.d.ts.map +1 -0
  212. package/dist/shared/jobs-view.js +146 -0
  213. package/dist/skill.d.ts +15 -0
  214. package/dist/skill.d.ts.map +1 -0
  215. package/dist/skill.js +93 -0
  216. package/dist/task-transfer.d.ts +252 -0
  217. package/dist/task-transfer.d.ts.map +1 -0
  218. package/dist/task-transfer.js +632 -0
  219. package/dist/templates.d.ts +57 -0
  220. package/dist/templates.d.ts.map +1 -0
  221. package/dist/templates.js +16 -0
  222. package/dist/types.d.ts +112 -0
  223. package/dist/types.d.ts.map +1 -0
  224. package/dist/types.js +158 -0
  225. package/dist/version.d.ts +8 -0
  226. package/dist/version.d.ts.map +1 -0
  227. package/dist/version.js +27 -0
  228. package/dist/workspaces.d.ts +113 -0
  229. package/dist/workspaces.d.ts.map +1 -0
  230. package/dist/workspaces.js +393 -0
  231. package/docs/ARCHITECTURE.md +559 -0
  232. package/docs/COMPATIBILITY.md +237 -0
  233. package/docs/CONCEPT.md +242 -0
  234. package/docs/CROSS_PLATFORM.ru.md +152 -0
  235. package/docs/CROSS_PLATFORM.zh.md +148 -0
  236. package/docs/FAQ.md +52 -0
  237. package/docs/FAQ.ru.md +53 -0
  238. package/docs/FAQ.zh.md +43 -0
  239. package/docs/FEATURES.md +699 -0
  240. package/docs/FEATURES.zh.md +656 -0
  241. package/docs/LOCAL-AI.md +300 -0
  242. package/docs/MIGRATION.md +363 -0
  243. package/docs/README.ru.md +287 -0
  244. package/docs/README.zh.md +306 -0
  245. package/docs/SAVINGS.md +61 -0
  246. package/docs/SAVINGS.ru.md +60 -0
  247. package/docs/SAVINGS.zh.md +52 -0
  248. package/docs/V1-V2-COMPATIBILITY-PLAN.md +366 -0
  249. package/docs/ZH-LOCALE-PLAN.md +324 -0
  250. package/docs/dashboard.png +0 -0
  251. package/docs/spikes/local-model-structured-output.md +81 -0
  252. package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
  253. package/docs/spikes/ollama-qwen3-4b.json +163 -0
  254. package/gui-experimental.cjs +9 -0
  255. package/index.js +2 -0
  256. package/locales/en.json +781 -0
  257. package/locales/ru.json +781 -0
  258. package/locales/zh.json +781 -0
  259. package/package.json +154 -13
  260. package/scripts/bench-local.mjs +321 -0
  261. package/scripts/check-zh-locale.mjs +218 -0
  262. package/scripts/demo-dashboard.mjs +209 -0
  263. package/scripts/run-tests.mjs +236 -0
  264. package/scripts/spike-local-structured.mjs +182 -0
  265. package/scripts/test-locale.mjs +45 -0
  266. package/skills/scheduled-job-best-practices/SKILL.md +158 -0
  267. package/skills/scheduled-job-best-practices/references/recipes.md +163 -0
  268. package/src/core/analytics.ts +424 -0
  269. package/src/core/audit.ts +418 -0
  270. package/src/core/cron-to-schtasks.ts +209 -0
  271. package/src/core/dry-run.ts +601 -0
  272. package/src/core/file-watcher.ts +245 -0
  273. package/src/core/git-trigger.ts +391 -0
  274. package/src/core/glob.ts +226 -0
  275. package/src/core/local-ai.ts +173 -0
  276. package/src/core/lock.ts +219 -0
  277. package/src/core/matrix.ts +947 -0
  278. package/src/core/native-notify.ts +157 -0
  279. package/src/core/one-shot.ts +239 -0
  280. package/src/core/otel.ts +128 -0
  281. package/src/core/permissions.ts +200 -0
  282. package/src/core/prometheus.ts +215 -0
  283. package/src/core/ps-wrapper.ts +1160 -0
  284. package/src/core/record-history.ts +615 -0
  285. package/src/core/retention.ts +141 -0
  286. package/src/core/savings.ts +150 -0
  287. package/src/core/schedule-gate.ts +253 -0
  288. package/src/core/schedule-v2.ts +668 -0
  289. package/src/core/scheduler/at-fallback.ts +113 -0
  290. package/src/core/scheduler/index.ts +82 -0
  291. package/src/core/scheduler/linux.ts +308 -0
  292. package/src/core/scheduler/logs.ts +37 -0
  293. package/src/core/scheduler/mac.ts +322 -0
  294. package/src/core/scheduler/posix.ts +128 -0
  295. package/src/core/scheduler/registry.ts +101 -0
  296. package/src/core/scheduler/types.ts +90 -0
  297. package/src/core/scheduler/windows.ts +881 -0
  298. package/src/core/secrets.ts +503 -0
  299. package/src/core/self-analysis.ts +744 -0
  300. package/src/core/session.ts +150 -0
  301. package/src/core/shutdown.ts +69 -0
  302. package/src/core/structured-log.ts +214 -0
  303. package/src/core/summary.ts +318 -0
  304. package/src/core/telegram.ts +436 -0
  305. package/src/core/triage-chain.ts +125 -0
  306. package/src/core/triage-compare.ts +277 -0
  307. package/src/core/triage-rules.ts +238 -0
  308. package/src/core/triage-shadow.ts +240 -0
  309. package/src/core/triage-worker.ts +344 -0
  310. package/src/core/triage.ts +366 -0
  311. package/src/core/watch-paths.ts +70 -0
  312. package/src/core/wrappers/bash.ts +532 -0
  313. package/src/db/git-state-repo.ts +62 -0
  314. package/src/db/history-repo.ts +492 -0
  315. package/src/db/index.ts +176 -0
  316. package/src/db/metrics-repo.ts +170 -0
  317. package/src/db/migrate.ts +328 -0
  318. package/src/db/recovery.ts +46 -0
  319. package/src/db/run-journal.ts +212 -0
  320. package/src/db/run-resume.ts +220 -0
  321. package/src/db/runs-repo.ts +481 -0
  322. package/src/db/schema.ts +349 -0
  323. package/src/db/settings-repo.ts +31 -0
  324. package/src/db/tasks-repo.ts +162 -0
  325. package/src/db/templates-repo.ts +77 -0
  326. package/src/gui.tsx +5222 -0
  327. package/src/history.ts +128 -0
  328. package/src/i18n.ts +413 -0
  329. package/src/index.ts +6642 -0
  330. package/src/integrations.ts +297 -0
  331. package/src/notifications.ts +1346 -0
  332. package/src/profiles.ts +345 -0
  333. package/src/rpc.ts +1704 -0
  334. package/src/schtasks.ts +75 -0
  335. package/src/server.ts +2663 -0
  336. package/src/settings.ts +1369 -0
  337. package/src/shared/jobs-view.ts +188 -0
  338. package/src/skill.ts +113 -0
  339. package/src/task-transfer.ts +946 -0
  340. package/src/templates.ts +67 -0
  341. package/src/tui-v1.tsx +341 -0
  342. package/src/tui.tsx +329 -0
  343. package/src/types.ts +226 -0
  344. package/src/version.ts +27 -0
  345. package/src/workspaces.ts +487 -0
@@ -0,0 +1,559 @@
1
+ # Architecture
2
+
3
+ This document explains how `agent-steward` (plugin id
4
+ `opencode-windows-scheduler`) is put together: the process
5
+ model, the modules, the data model and the extension points.
6
+
7
+ - [Design principles](#design-principles)
8
+ - [Process model](#process-model)
9
+ - [Data flow](#data-flow)
10
+ - [Modules](#modules)
11
+ - [Scheduling backends](#scheduling-backends)
12
+ - [Run wrapper](#run-wrapper)
13
+ - [History, metrics and recovery](#history-metrics-and-recovery)
14
+ - [Chains, retries and DAG](#chains-retries-and-dag)
15
+ - [Matrix builds](#matrix-builds)
16
+ - [Workspaces](#workspaces)
17
+ - [Triggers](#triggers)
18
+ - [Storage](#storage)
19
+ - [Interfaces](#interfaces)
20
+ - [Localization](#localization)
21
+ - [Security model](#security-model)
22
+ - [Extension points](#extension-points)
23
+
24
+ ## Design principles
25
+
26
+ 1. **The OS scheduler owns time.** The plugin never keeps a timer in memory for cron
27
+ jobs. Every recurring task becomes a real OS entry (Task Scheduler, launchd,
28
+ crontab), so jobs survive reboots and closed editor windows.
29
+ 2. **The host process owns the UI.** Agent tools, the sidebar GUI, the RPC layer and the
30
+ dashboard live inside the OpenCode plugin host. They are stateless wrappers around
31
+ the database and the OS scheduler.
32
+ 3. **Runs are independent processes.** A job executes `opencode run` through a wrapper
33
+ that enforces timeout, single-instance locking, pre/post hooks and a Quality Gate.
34
+ The wrapper reports the result back to the database, not to the plugin host.
35
+ 4. **One source of truth for definitions is SQLite.** OS entries are derived artifacts:
36
+ they can always be recreated from the database with export/import.
37
+ 5. **Local first.** No network services, no telemetry, no accounts by default. The dashboard binds
38
+ to localhost only. Local AI triage (Ollama) is optional and connects only when explicitly enabled
39
+ via `manage_local_ai`.
40
+
41
+ ## Process model
42
+
43
+ ```
44
+ ┌─────────────────────────────┐
45
+ │ OpenCode (plugin host) │
46
+ │ • agent tools (26) │
47
+ │ • sidebar GUI (gui.tsx) │
48
+ │ • RPC ↔ sidebar │
49
+ │ • dashboard HTTP server │
50
+ │ • chokidar file watcher │
51
+ └──────────┬──────────────────┘
52
+ │ creates / updates
53
+ ▼
54
+ ┌─────────────────────────────┐ ┌──────────────────────────────┐
55
+ │ OS scheduler │ │ SQLite (scheduler.db) │
56
+ │ Windows Task Scheduler │ │ tasks, history, metrics, │
57
+ │ launchd / crontab │ │ templates, settings, │
58
+ └──────────┬──────────────────┘ │ workspaces │
59
+ │ fires │ └──────────────────────────────┘
60
+ ▼ │ ▲
61
+ ┌─────────────────────────────┐ │ │ writes
62
+ │ Run wrapper (.cmd / .sh) │ │ │
63
+ │ • lock │ │ ┌─────────┴──────────────┐
64
+ │ • timeout │ └──│ recorder process │
65
+ │ • pre-flight hook │ │ core/record-history.js │
66
+ │ • opencode run ... │────────▶│ • history / metrics │
67
+ │ • Quality Gate │ │ • retries, chains │
68
+ │ • post-flight hook │ │ • DAG dependents │
69
+ └─────────────────────────────┘ │ • matrix continuation │
70
+ └────────────────────────┘
71
+ ```
72
+
73
+ There are four kinds of processes:
74
+
75
+ | Process | Lifetime | Responsibility |
76
+ | --- | --- | --- |
77
+ | Plugin host | OpenCode session | Register tools/skill, create OS entries, serve RPC and dashboard, watch files |
78
+ | OS scheduler | Always | Fire jobs on schedule or on demand |
79
+ | Run wrapper | Per run | Lock, timeout, hooks, Quality Gate, invoke `opencode run`, call the recorder |
80
+ | Recorder | Per run (short) | Persist history/metrics, schedule retries, trigger chains and dependents, continue matrices |
81
+
82
+ Because the recorder is a separate short-lived process, it cannot rely on in-memory
83
+ state of the plugin host. Everything it needs (definitions, retry state, matrix queue)
84
+ is read from the database or from files under the plugin directory.
85
+
86
+ ## Data flow
87
+
88
+ **Create a task**
89
+
90
+ 1. Agent tool / GUI / import calls `schedulerCreateTask(...)`.
91
+ 2. Definitions are validated (cron, workspace path, matrix rules), a prompt file and a
92
+ wrapper script are written under the plugin directory; if the task's workspace has
93
+ env variables, `<PLUGIN_DIR>/env/<sanitized>.env` is written (mode `0600` on POSIX).
94
+ 3. An OS entry is created through the platform backend.
95
+ 4. The definition is stored in `tasks.definition_json`.
96
+
97
+ **Run a task**
98
+
99
+ 1. The OS scheduler starts the wrapper.
100
+ 2. When the task carries a schedule gate (poll-mode cron, foreign timezone or a
101
+ launch window), the wrapper first runs `node dist/core/schedule-gate.js`: it
102
+ re-checks the extended cron in the task's zone, and if now is outside the
103
+ launch window it waits until the window opens (postpone, deduplicated by a
104
+ defer-file) or exits with code 3 so the wrapper skips silently.
105
+ 3. The wrapper acquires the lock (`locks/<task>.lock`), writes the log
106
+ (`logs/<task>.log`), loads workspace env from `<PLUGIN_DIR>/env/<sanitized>.env`
107
+ (Windows `-EnvFile`, POSIX `set -a; . "$ENV_FILE"; set +a`) before starting
108
+ `opencode run` with the prompt file. Output is streamed to the log.
109
+ 4. When the process ends, the wrapper enforces the timeout result, runs the Quality
110
+ Gate and the post-flight hook.
111
+ 5. The wrapper calls `node dist/core/record-history.js --finish ...` with status,
112
+ duration, tokens, cost, model and hook results.
113
+ 6. The recorder writes `history` and updates `metrics`, then evaluates retries, task
114
+ chains, DAG dependents and matrix continuation.
115
+
116
+ **Read state**
117
+
118
+ `collectTasksView()` (shared by tools, RPC and GUI) merges definitions, the latest
119
+ history record and metrics into a `TaskItem`. Matrix parents get an aggregated status
120
+ from their clones instead of their own last run.
121
+
122
+ ## Router (3-layer)
123
+
124
+ The router decides *how* each task step executes — direct local call, MCP transport, or
125
+ cloud model — without involving a model for known step types.
126
+
127
+ ### Слой 1 — статические правила (0 токенов, мгновенно)
128
+
129
+ Таблица соответствий тип задачи → транспорт + исполнитель. Большинство операций
130
+ известны заранее, модель не нужна.
131
+
132
+ | Тип задачи | Транспорт | Исполнитель |
133
+ | --- | --- | --- |
134
+ | `read_file` | direct | local |
135
+ | `write_file` | direct | local |
136
+ | `run_tests` | direct | local |
137
+ | `apply_diff` | direct | local |
138
+ | `github_create_pr` | mcp | local |
139
+ | `jira_update_task` | mcp | cloud |
140
+
141
+ Агент хочет прочитать файл → роутер смотрит в таблицу → видит `direct + local` →
142
+ выполняет напрямую, без MCP, без модели.
143
+
144
+ ### Слой 2 — Capability Map (0 токенов, быстро)
145
+
146
+ SQLite-таблица `task_type → model / success_rate / avg_cost / avg_time /
147
+ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 learning loop).
148
+
149
+ - `success_rate ≥ 0.85` → маршрут локально
150
+ - `success_rate ≤ 0.30` → эскалация в облако или «нужно ревью»
151
+
152
+ Это и есть learning loop: роутер учится на гейтах и становится точнее без затрат
153
+ токенов на само решение.
154
+
155
+ ### Слой 3 — локальная модель (только декомпозиция и неоднозначность)
156
+
157
+ Модель не маршрутизирует каждый шаг. Она только:
158
+ 1. Разбивает миссию на шаги с типами (планирование);
159
+ 2. Разрешает неоднозначность (Explore-режим, когда в Capability Map нет данных).
160
+
161
+ После этого каждый шаг проходит через Слой 1 и Слой 2.
162
+
163
+ ### Эскалация
164
+
165
+ При провале гейта роутер эскалирует в облако **по правилу**, без участия модели.
166
+
167
+ ---
168
+
169
+ ## Modules
170
+
171
+ | Path | Role |
172
+ | --- | --- |
173
+ | `src/index.ts` | Plugin lifecycle, 26 agent tools, RPC handlers, task CRUD, view assembly |
174
+ | `src/rpc.ts` | JSON-schema contracts for every RPC method |
175
+ | `src/gui.tsx` | OpenCode sidebar panel (SolidJS, built to `gui-experimental.cjs`) |
176
+ | `src/server.ts` | Local web dashboard HTTP server and HTML rendering |
177
+ | `src/skill.ts` | Loads and registers the bundled agent skill |
178
+ | `src/task-transfer.ts` | Export/import, validation, `MatrixConfig` types |
179
+ | `src/profiles.ts` | Profile directory resolution: per-profile plugin dir (base for `default`, `<base>/profiles/<name>` for named profiles); profile name, marker, port, create/delete/switch |
180
+ | `src/workspaces.ts` | Workspace registry and path validation; env pairs and `.env` file resolution with secret masking |
181
+ | `src/templates.ts` | Reusable task templates |
182
+ | `src/settings.ts` | Plugin settings: notifications, history retention, audit, interface locale (`auto`/`ru`/`en`/`zh`) and last known UI locale, local AI/triage |
183
+ | `src/i18n.ts` | Interface locale (`ru` default, `en`/`zh`), BCP 47 mapping, JSON catalogs in `locales/`, ICU subset (`{param}`, `plural`) via built-in `Intl`, fallback to `ru` |
184
+ | `src/notifications.ts` | Multi-channel delivery (webhook, Telegram, native OS) with retries/backoff, templates, task filters, quiet hours, matrix and stuck-clone notifications, daily/weekly digest |
185
+ | `src/core/telegram.ts` | Telegram Bot API `sendMessage`: parse-mode escaping, dashboard link, token validation and masking |
186
+ | `src/core/native-notify.ts` | Native OS notifications: Windows Toast (PowerShell/WinRT), macOS `osascript`, Linux `notify-send`; no external dependency |
187
+ | `src/core/secrets.ts` | Encrypted secret store (AES-256-GCM, `secrets.key` 0600, `${secret:NAME}` refs, redaction) |
188
+ | `src/core/audit.ts` | SQLite audit journal (`audit_log`), redacted details, retention cleanup |
189
+ | `src/history.ts` | History model and status types |
190
+ | `src/version.ts` | Runtime plugin version (reads package.json) |
191
+ | `src/core/retention.ts` | Daily history prune and incremental vacuum |
192
+ | `src/core/analytics.ts` | Pure 14-day analytics and CSV export |
193
+ | `src/core/scheduler/` | Platform backends, registry, logs |
194
+ | `src/core/ps-wrapper.ts` | PowerShell wrapper template and `.cmd` generation |
195
+ | `src/core/wrappers/bash.ts` | POSIX wrapper template |
196
+ | `src/core/record-history.ts` | Recorder: history, retries, chains, DAG, matrix continuation |
197
+ | `src/core/matrix.ts` | Fan-out, aggregation, sync, cancel, orphan cleanup |
198
+ | `src/core/dry-run.ts` | Pipeline simulation (no execution) |
199
+ | `src/core/lock.ts` | Single-instance lock manager |
200
+ | `src/core/file-watcher.ts` | chokidar-based file triggers |
201
+ | `src/core/local-ai.ts` | Local AI triage: LLM classifier with rules fallback, shadow mode, fail-open, manage_local_ai backing |
202
+ | `src/core/cron-to-schtasks.ts` | Cron → Task Scheduler translation |
203
+ | `src/core/schedule-v2.ts` | Extended cron parser/matcher, timezone math, launch windows, poll-mode decisions |
204
+ | `src/core/schedule-gate.ts` | Wrapper-side gate: cron re-check (poll mode), window postpone, defer-file |
205
+ | `src/db/` | SQLite access: schema, migrations, repositories, recovery; `runs-repo.ts` keeps durable `runs`/`run_steps` state, `run-journal.ts` writes transitions around each step, `run-resume.ts` continues a crashed chain |
206
+ | `src/shared/jobs-view.ts` | Task view shared by the GUI and dashboard |
207
+
208
+ ## Scheduling backends
209
+
210
+ `scheduler/registry.ts` keeps the mapping between a task name and its OS entry.
211
+ `scheduler/index.ts` picks a backend from `process.platform`.
212
+
213
+ | Platform | Backend | Notes |
214
+ | --- | --- | --- |
215
+ | Windows | `schtasks.exe` | Cron is translated to `MINUTE/HOURLY/DAILY/WEEKLY/MONTHLY` flags; non-cron triggers are registered as `ONCE` at `31.12.2099` |
216
+ | Linux | `crontab` | Task lines with the plugin marker are rewritten via `crontab -` |
217
+ | macOS | `launchd` | `StartCalendarInterval` plists |
218
+ | POSIX fallback | `crontab` | Used when launchd is unavailable |
219
+
220
+ File and MCP triggers are not time-based. They are still registered as a far-future
221
+ one-shot entry so that `runMatrix`, DAG dependencies and manual runs can start them,
222
+ while the OS never fires them on its own. File triggers are additionally watched by
223
+ chokidar inside the plugin host.
224
+
225
+ ## Run wrapper
226
+
227
+ The wrapper is generated per task and is the only place where execution policy is
228
+ enforced:
229
+
230
+ | Concern | Implementation |
231
+ | --- | --- |
232
+ | Working directory | Task `workingDirectory`, or the workspace path, or the plugin directory |
233
+ | Prompt | Written to a prompt file, passed to `opencode run` |
234
+ | Timeout | `timeoutSeconds`; on expiry the child process tree is stopped and the run is marked `timeout` |
235
+ | Workspace env | Variables from the workspace's `.env` file and explicit pairs are injected before `opencode run` (wrapper `env:` / `export`); secret-looking keys are masked in logs |
236
+ | No overlap | Lock file per task; a second start exits immediately and records `skipped` |
237
+ | Pre-flight | `beforeScript`; non-zero exit marks `preFlight` as failed |
238
+ | Quality Gate | `qualityGate` after a successful run; non-zero exit turns the run into an error |
239
+ | Post-flight | `afterScript`; non-zero exit is reported but does not rewrite a success |
240
+ | Logging | Append-only log per task under `logs/` |
241
+ | History | Calls the recorder with `--start` and `--finish` |
242
+
243
+ Windows uses PowerShell and `.cmd` shims; POSIX uses bash. Both wrappers are generated
244
+ from templates so the policy stays identical across platforms.
245
+
246
+ ## History, metrics and recovery
247
+
248
+ `history` stores one row per run: status (`running`, `success`, `error`, `timeout`,
249
+ `partial`), start/finish timestamps, duration, error text, tokens, cost, model,
250
+ pre/post-flight results, the chained next task, workspace and tool restrictions.
251
+ `metrics` holds per-task counters and totals.
252
+
253
+ If the host or the machine dies mid-run, the row stays in `running`. On the next
254
+ plugin activation, `db/recovery.ts` marks stale `running` rows as `error`, so the UI
255
+ never shows a permanently running task.
256
+
257
+ History is bounded by retention: `settings.json` carries `history.retentionDays` and
258
+ `history.maxRecords` (defaults 30 / 5000, `0` disables). Cleanup runs at most once a
259
+ day on plugin start (`core/retention.ts`), prunes only finished rows via
260
+ `pruneHistory` in `db/history-repo.ts`, then `PRAGMA incremental_vacuum` frees space.
261
+ Aggregates in `metrics` are never pruned. Period analytics (per-day buckets, success
262
+ rate, tokens, cost, matrix/model breakdowns) are computed by `core/analytics.ts` and
263
+ exposed as `get_analytics` / `GET /api/analytics`; the dashboard renders a 14-day
264
+ block and `GET /api/history/export` serves CSV/JSON.
265
+
266
+ ## Chains, retries and DAG
267
+
268
+ All three are evaluated by the recorder after a run finishes:
269
+
270
+ - **Retries** — `retryCount`/`retryDelay` with a retry-state file so a crash cannot
271
+ loop forever. Retries are attempted before chains and dependents.
272
+ - **Chains** — `nextTaskOnSuccess` / `nextTaskOnError` start exactly one follow-up task.
273
+ - **DAG** — `dependsOn` is satisfied only when every dependency's latest run is
274
+ successful. For a matrix dependency, all clones must be successful; the parent's own
275
+ aggregate record is not enough.
276
+
277
+ `selectDependentsToTrigger(taskName, definitions, history)` is a pure function, which
278
+ keeps the rules testable.
279
+
280
+ ## Matrix builds
281
+
282
+ A matrix task is a template, not a runnable job:
283
+
284
+ 1. `expandMatrixTask(parent)` produces one clone per workspace:
285
+ `<parent>-matrix-<workspace>`, each with its own `workspaceId`, `matrixParentId`,
286
+ a file trigger and per-workspace overrides applied.
287
+ 2. `runMatrix(parent)` starts clones according to `strategy` (`parallel`/`sequential`)
288
+ and `concurrency`; extra clones wait in `matrixQueue` persisted on the parent.
289
+ 3. On each clone completion, the recorder calls `advanceMatrixAfterClone` (drain the
290
+ queue or start the next sequential clone) and `finalizeMatrixIfComplete`.
291
+ 4. `aggregateMatrixResults(parent)` derives `success` / `error` / `partial` / `running` /
292
+ `empty` from clone history.
293
+ 5. `syncMatrixFamily(parent)` diffs existing clones against a fresh expansion on update:
294
+ missing clones are created, changed clones are updated, extra clones are removed.
295
+ Clones whose latest run is `running` are never touched.
296
+
297
+ The parent is registered in the OS scheduler as a far-future one-shot entry only so it
298
+ can be addressed by name; it never fires on its own.
299
+
300
+ ## Workspaces
301
+
302
+ A workspace is a named directory (usually a git repository) with an id, path, optional
303
+ remote and color. Workspaces provide:
304
+
305
+ - the working directory for a task (`workspaceId` instead of `workingDirectory`);
306
+ - matrix targets (`matrix.workspaceIds`);
307
+ - per-workspace overrides (`matrix.overrides`);
308
+ - dashboard grouping;
309
+ - env variables: explicit `KEY=VALUE` pairs plus an optional `.env` file (loaded first,
310
+ explicit pairs override), injected into task runs via the wrapper; secret-looking
311
+ keys are masked in logs.
312
+
313
+ Paths are validated on creation, update and import: a workspace must point to an
314
+ existing directory. Env keys must match `^[A-Za-z_][A-Za-z0-9_]*$`; max 100 pairs.
315
+
316
+ ## Triggers
317
+
318
+ | Trigger | How it fires |
319
+ | --- | --- |
320
+ | `cron` | OS scheduler on the translated schedule |
321
+ | `file` | chokidar watches `watchPath`; debounced change starts the task |
322
+ | `git` | Polls `HEAD` in the task working directory; runs when new commits match branch/path/ignore filters |
323
+ | `mcp-event` | `emit_event` RPC/tool matches server + event and starts subscribers |
324
+
325
+ Cron expressions are standard 5-field. The Windows backend supports the subset that
326
+ `schtasks` can express; unsupported shapes are rejected at creation time with a clear
327
+ error instead of silently drifting.
328
+
329
+ ## Storage
330
+
331
+ Everything lives under the plugin directory:
332
+
333
+ | Platform | Path |
334
+ | --- | --- |
335
+ | Windows | `%APPDATA%\opencode\agent-steward` (legacy `windows-scheduler` переносится автоматически) |
336
+ | macOS/Linux | `$XDG_CONFIG_HOME/opencode/agent-steward` (default `~/.config/...`) |
337
+
338
+ ```
339
+ scheduler.db SQLite database (WAL; схема версионируется через PRAGMA user_version)
340
+ logs/ per-task run logs
341
+ locks/ lock files
342
+ wrappers/ generated .cmd / .sh wrappers
343
+ prompts/ prompt files
344
+ env/ per-workspace env files (<task>.env), mode 0600 on POSIX
345
+ ```
346
+
347
+ Named profiles (Sprint 21) each own a copy of this tree under
348
+ `<base>/profiles/<name>` (`default` uses the base directory). Profile directory,
349
+ database, settings, logs, wrappers and locks all resolve per-profile.
350
+
351
+ Override the database location with `OPENCODE_SCHEDULER_DB` (used by tests). Override
352
+ the whole plugin directory (database, logs, locks, wrappers, prompts) with
353
+ `OPENCODE_SCHEDULER_HOME` on any platform. Profile selection uses
354
+ `OPENCODE_SCHEDULER_PROFILE` > `active-profile` marker > `default`.
355
+
356
+ Schema evolution is additive: `applySchema` runs `CREATE TABLE IF NOT EXISTS` on every
357
+ connection and adds missing columns after `PRAGMA table_info`, so upgrading the plugin
358
+ never requires a manual migration. `SCHEMA_VERSION` (currently `3`) is stored in
359
+ `PRAGMA user_version`; incremental steps live in `MIGRATIONS`.
360
+
361
+ ### Durable run state (Sprint 36.1)
362
+
363
+ Sprint 36.1 adds `runs` and `run_steps`, the persistence layer for resumable DAG
364
+ execution:
365
+
366
+ | Table | Purpose |
367
+ | --- | --- |
368
+ | `runs` | One row per execution (`pending → running → passed/failed/cancelled`), with `task_name`, `parent_run_id`, `workspace_id`, `started_at`, `finished_at`, `metadata_json` |
369
+ | `run_steps` | One row per step (`pending → running → passed/failed/skipped`), with `position`, `attempt`, `idempotency_key`, `started_at`, `finished_at`, `error`, `output_json`; unique per `(run_id, step_name)`, cascade-deleted with the run |
370
+
371
+ `src/db/runs-repo.ts` owns the transitions and rejects invalid ones
372
+ (`InvalidTransitionError`). A failed step can be retried explicitly (`retryStep`),
373
+ which increments `attempt` and returns it to `running`. The tables survive process
374
+ crashes and reconnects, which is the prerequisite for resume (36.2) and
375
+ idempotent steps (36.3).
376
+
377
+ `src/db/run-journal.ts` (Sprint 36.1.b) writes every transition to disk before
378
+ and after executing the step body: `beginStepAttempt` commits `running` + `started_at`
379
+ before the body runs; `recordStepSuccess`/`recordStepFailure` commit `passed`/`failed`
380
+ (and `finished_at`/`error`/`output_json`) after it. The high-level wrappers
381
+ `runStepStatefully` / `runStepStatefullyAsync` execute `body` between those two
382
+ commits and propagate its error while still recording `failed`. `recoverInterruptedSteps`
383
+ marks any `running` steps left after a process crash as `failed` — preserving
384
+ `attempt`, so the next repeat gets `attempt + 1` and never restarts from 1.
385
+ SQLite runs in WAL mode with `synchronous = NORMAL`, so a committed transition
386
+ survives a `kill -9` (only the last in-flight commit can be lost with a power cut).
387
+
388
+ ### Resume from the middle (Sprint 36.2)
389
+
390
+ `src/db/run-resume.ts` continues a run after a crash. `run_steps.position`
391
+ (schema v3) fixes the order of a linear chain — `created_at` can be identical
392
+ for steps inserted in one transaction, so it cannot be used for ordering; on an
393
+ existing v2 database the migration backfills `position` from the insertion order.
394
+ The `(run_id, position)` index is created after migrations, not in `SCHEMA_SQL`:
395
+ on an old database the column does not exist yet, so an early `CREATE INDEX`
396
+ would fail before the `ALTER TABLE` step.
397
+ `findResumeStep` returns the first step that is not `passed`/`skipped`.
398
+ `resumeRunSync` / `resumeRun` then:
399
+
400
+ 1. recover dangling `running` steps (`recoverInterruptedSteps`), so the crash
401
+ victim is retried with `attempt + 1`;
402
+ 2. skip already passed/skipped steps without invoking their handlers;
403
+ 3. validate that every remaining step has a handler **before** any side effect;
404
+ 4. reopen a `failed` run (`reopenRun`, the only `failed → running` transition);
405
+ 5. execute the rest through the journal and finalize the run as `passed` or
406
+ `failed`.
407
+
408
+ The result reports `resumedFrom`, `resumedFromAttempt`, `executed`, `skipped`,
409
+ `failedStep` and `error`. With `stopOnError: false` the chain continues after a
410
+ failure, but the run still ends `failed`. This is covered by
411
+ `test-run-resume.mjs`, including a real `kill -9` in the middle of a four-step
412
+ chain.
413
+
414
+ ## Interfaces
415
+
416
+ | Interface | Audience | Entry point |
417
+ | --- | --- | --- |
418
+ | Agent tools | AI agent | 26 tools registered via `ctx.tool.transform` |
419
+ | Agent skill | AI agent | `skills/scheduled-job-best-practices` |
420
+ | RPC | Sidebar GUI | `src/rpc.ts` contracts, 44 methods |
421
+ | Sidebar GUI | Human | `gui-experimental.cjs` |
422
+ | Web dashboard | Human | `startDashboardServer` (localhost, random/fixed port) |
423
+
424
+ ## Localization
425
+
426
+ User-visible text lives in flat JSON catalogs: `locales/ru.json` (default),
427
+ `locales/en.json` and `locales/zh.json`. Keys are dot-separated and grouped by surface —
428
+ `gui.*`, `notify.*`, `tool.*`, `dryRun.*`, `matrix.*`, `schedule.*` — and all catalogs
429
+ must have the same key set with non-empty values.
430
+
431
+ `src/i18n.ts` loads the catalogs once and caches them. It exposes `t(key, params)`,
432
+ `setLocale(locale)`, `messageIn(locale, key)` and `hasKey(key, locale)`. Lookup order is
433
+ active locale → `en` → `ru` → the key itself, so a missing translation never renders as
434
+ an empty string. The `locale` setting (`ru` default, `en`/`zh` optional, `auto` follows
435
+ the OpenCode interface language) is applied immediately, without restarting OpenCode.
436
+ `auto` is resolved in the GUI through `ctx.locale.locale()` with BCP 47 prefix mapping
437
+ (`zh-CN` → `zh`, `en-GB` → `en`); the resolved value is sent to the server as `uiLocale`,
438
+ because the server process cannot see the window. The sidebar GUI embeds the catalogs at
439
+ build time via `registerCatalog`, because a webview bundle cannot read package files at
440
+ runtime.
441
+
442
+ The template subset is deliberately small and dependency-free:
443
+
444
+ - `{name}` — interpolation; the caller formats the value (duration, money, date).
445
+ - `{count, plural, one {…} few {…} many {…} other {…}}` — plural forms through
446
+ `Intl.PluralRules` for the active locale (`ru` uses one/few/many, `en` one/other,
447
+ `zh` only `other`).
448
+
449
+ Rules:
450
+
451
+ - a user-visible message is a whole phrase in the catalog, including punctuation; never
452
+ concatenate translated fragments;
453
+ - store stable codes, not localized text, in the database; translate at render time;
454
+ - agent tool descriptions, schemas and API payloads stay English; `console.*`
455
+ diagnostics stay Russian;
456
+ - add every new key to all catalogs. `test-docs.mjs` enforces parity and non-empty
457
+ values; `npm run test:en` and `npm run test:zh` replay all suites under `en`/`zh` and
458
+ CI runs them. `OPENCODE_SCHEDULER_LOCALE` only overrides the initial locale for tests
459
+ and services — it is not a user-facing setting.
460
+
461
+ ## Security model
462
+
463
+ - The dashboard has **no authentication** and binds to localhost. Do not expose it.
464
+ - A job definition is **code**: prompts, hooks, Quality Gates and wrappers all execute
465
+ with your user privileges. Treat task creation like granting shell access.
466
+ - `allowedTools` / `deniedTools` are **enforced at the run-wrapper level** (Sprint 29.2).
467
+ Before each `opencode run`, the wrapper passes `permissions` rules through
468
+ `OPENCODE_CONFIG_CONTENT`: `deniedTools` are mapped to `effect: "deny"` for the
469
+ corresponding OpenCode action (`shell`, `edit`, `glob`, `grep`, `webfetch`,
470
+ `websearch`, `question`, `subagent`, `skill`), and `allowedTools` (if specified)
471
+ additionally denies every action not in the list. No config file is written, so a
472
+ project-level `opencode.jsonc` is preserved and parallel tasks in one workdir do not
473
+ race. The wrapper passes `--auto` so non-denied permissions are auto-approved.
474
+ `allowedTools`/`deniedTools` metadata is still recorded in history for audit.
475
+ - **Default policy (`src/core/permissions.ts`):** the baseline is
476
+ `permissions.defaultPolicy` — `hybrid` (default) denies `shell` and `question` while
477
+ allowing read/edit/glob/grep/subagent/skill/webfetch/websearch, `secure` allows only
478
+ read/glob/grep/skill, `legacy` allows everything (1.5.x behaviour). Task `legacyShell`
479
+ re-enables `shell` under `hybrid`; `deniedTools` still wins. Policy denials are
480
+ audited as `tool.blocked` with `reason: "default-policy"`, and each wrapper logs
481
+ `policy=<name>, denied=<actions>` before the run.
482
+ - **Audit of blocked tools (Sprint 29.4):** when a task definition is saved,
483
+ `recordTaskToolBlocks()` writes one `tool.blocked` audit event per entry in
484
+ `deniedTools` (`target` = task name, `details.tool` = tool, plus `allowedTools`,
485
+ `deniedTools` and `reason`). In allow-list mode one event with `tool: "*"` records
486
+ that every unlisted tool is denied. The event is emitted on create and on update, so
487
+ changing the task policy also changes the audited details. Because the wrapper runs
488
+ `opencode` as an external process, the plugin cannot observe individual blocked
489
+ attempts at runtime; the audit reflects the enforced policy, not each refusal.
490
+ - Task prompts, hooks and Quality Gate scripts are **plain text** executed with your
491
+ user privileges; only secrets (in `secrets.json`, AES-256-GCM) are encrypted.
492
+ Workspace `env` can reference secrets as `${secret:NAME}`; values are masked in
493
+ logs, history and audit. Treat task creation like granting shell access.
494
+ - Secrets are stored encrypted in `<PLUGIN_DIR>/secrets.json` (AES-256-GCM) with a
495
+ 32-byte key file `secrets.key` (mode 0600 on POSIX; on Windows an ACL that removes
496
+ inheritance and grants the current user only, applied by `icacls` on create and
497
+ re-applied on read for keys created before 1.5.5). Workspace `env` can reference them
498
+ as `${secret:NAME}`; values are substituted at run time and masked in logs,
499
+ history and audit.
500
+ - Workspace paths are validated, but hooks are not sandboxed: only schedule jobs from
501
+ repositories you trust.
502
+
503
+ ### Permission model
504
+
505
+ The effective policy is resolved in this order (later wins):
506
+
507
+ 1. `permissions.defaultPolicy` — the baseline: `hybrid` (default, no `shell`/`question`),
508
+ `secure` (read-only) or `legacy` (everything allowed, 1.5.x behaviour).
509
+ 2. Task `legacyShell` — re-enables `shell` under `hybrid` only.
510
+ 3. Task `allowedTools` — if present, every action not listed is denied; an explicitly
511
+ listed action can override a policy denial.
512
+ 4. Task `deniedTools` — always denied and takes priority over `allowedTools`.
513
+ 5. The generated `OPENCODE_CONFIG_CONTENT` — passed in the wrapper environment; no file
514
+ is written and the project config stays untouched.
515
+ 6. Project `opencode.json(c)` and system config — merged by OpenCode; a closer or
516
+ system-level config can weaken task-scoped denies (see limitations below).
517
+ 7. `--auto` — auto-approves everything that remains, so no interactive prompts block
518
+ an unattended run.
519
+
520
+ Tool mapping used by both wrappers:
521
+
522
+ | Task tool | OpenCode action |
523
+ | --- | --- |
524
+ | `bash`, `shell` | `shell` |
525
+ | `write`, `edit`, `apply_patch`, `remove` | `edit` |
526
+ | `glob`, `grep`, `webfetch`, `websearch` | same name |
527
+ | `question`, `subagent`, `skill` | same name |
528
+
529
+ Hooks, Quality Gates and wrapper scripts are outside this model: they run before or
530
+ after the agent with the user's privileges and are not filtered by tool policy.
531
+
532
+ ### Permission enforcement — known limitations (spike 29.1 findings)
533
+
534
+ - `opencode run` CLI (v2.2.3) supports only `--auto` (auto-approve non-denied
535
+ permissions). There are **no** `--allow-tool` / `--deny-tool` CLI flags, so
536
+ per-task restrictions cannot be passed via arguments. Enforcement is done by
537
+ generating a task-scoped config and passing it through `OPENCODE_CONFIG_CONTENT`.
538
+ - OpenCode merges `opencode.json(c)` from the current directory up to the filesystem
539
+ root. A project-level `opencode.jsonc` with permissive rules can override or weaken
540
+ task-scoped denies (last matching rule wins, closer directory wins for merge).
541
+ System config (`/etc/opencode`, `%ProgramData%\opencode`) overrides project config.
542
+ - Nested agent calls (subagents) use their **own** permissions, not a subset of the
543
+ parent's. A task that denies `subagent` prevents launching subagents, but a launched
544
+ subagent is not further restricted by the parent task's policy.
545
+ - **Plan B**: if the task-scoped config passed via `OPENCODE_CONFIG_CONTENT` proves
546
+ insufficient, enforcement can be moved to wrapper-level tool filtering (intercepting
547
+ `opencode run` invocation and refusing to start when a denied tool would be needed)
548
+ or to a managed system-level `policies` entry that hard-denies specific tools
549
+ globally.
550
+
551
+ ## Extension points
552
+
553
+ | Goal | Where to start |
554
+ | --- | --- |
555
+ | New OS backend | Implement `SchedulerBackend` in `src/core/scheduler/`, register it in `index.ts` |
556
+ | New trigger type | Add a `triggerType` branch in `schedulerCreateTask` and in the wrapper |
557
+ | New agent tool | Add a zod schema + execute function, register in `ctx.tool.transform`, add an RPC contract |
558
+ | New dashboard panel | Extend `server.ts` routes and the HTML template |
559
+ | New matrix policy | Extend `MatrixConfig` in `task-transfer.ts` and the logic in `core/matrix.ts` |