opencode-windows-scheduler 1.5.2 → 1.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/CHANGELOG.md +107 -2
  2. package/CROSS_PLATFORM.md +107 -71
  3. package/LICENSE +21 -21
  4. package/README.md +74 -26
  5. package/ROADMAP-STRATEGY.md +11 -4
  6. package/ROADMAP.md +322 -112
  7. package/dist/core/analytics.d.ts +3 -0
  8. package/dist/core/analytics.d.ts.map +1 -1
  9. package/dist/core/analytics.js +4 -0
  10. package/dist/core/audit.d.ts +2 -1
  11. package/dist/core/audit.d.ts.map +1 -1
  12. package/dist/core/audit.js +32 -1
  13. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  14. package/dist/core/cron-to-schtasks.js +21 -4
  15. package/dist/core/file-watcher.d.ts.map +1 -1
  16. package/dist/core/file-watcher.js +16 -1
  17. package/dist/core/git-trigger.d.ts +4 -2
  18. package/dist/core/git-trigger.d.ts.map +1 -1
  19. package/dist/core/git-trigger.js +34 -16
  20. package/dist/core/local-ai.d.ts +52 -0
  21. package/dist/core/local-ai.d.ts.map +1 -0
  22. package/dist/core/local-ai.js +119 -0
  23. package/dist/core/lock.d.ts +14 -0
  24. package/dist/core/lock.d.ts.map +1 -1
  25. package/dist/core/lock.js +81 -4
  26. package/dist/core/matrix.d.ts.map +1 -1
  27. package/dist/core/matrix.js +3 -2
  28. package/dist/core/native-notify.d.ts.map +1 -1
  29. package/dist/core/native-notify.js +3 -0
  30. package/dist/core/one-shot.d.ts +7 -1
  31. package/dist/core/one-shot.d.ts.map +1 -1
  32. package/dist/core/one-shot.js +15 -2
  33. package/dist/core/permissions.d.ts +69 -0
  34. package/dist/core/permissions.d.ts.map +1 -0
  35. package/dist/core/permissions.js +143 -0
  36. package/dist/core/ps-wrapper.d.ts +9 -30
  37. package/dist/core/ps-wrapper.d.ts.map +1 -1
  38. package/dist/core/ps-wrapper.js +477 -108
  39. package/dist/core/record-history.d.ts +11 -0
  40. package/dist/core/record-history.d.ts.map +1 -1
  41. package/dist/core/record-history.js +106 -4
  42. package/dist/core/savings.d.ts +70 -0
  43. package/dist/core/savings.d.ts.map +1 -0
  44. package/dist/core/savings.js +87 -0
  45. package/dist/core/schedule-gate.js +7 -3
  46. package/dist/core/schedule-v2.js +1 -1
  47. package/dist/core/scheduler/index.d.ts +13 -1
  48. package/dist/core/scheduler/index.d.ts.map +1 -1
  49. package/dist/core/scheduler/index.js +35 -4
  50. package/dist/core/scheduler/linux.d.ts +4 -1
  51. package/dist/core/scheduler/linux.d.ts.map +1 -1
  52. package/dist/core/scheduler/linux.js +53 -20
  53. package/dist/core/scheduler/mac.d.ts +2 -1
  54. package/dist/core/scheduler/mac.d.ts.map +1 -1
  55. package/dist/core/scheduler/mac.js +24 -6
  56. package/dist/core/scheduler/posix.d.ts +1 -1
  57. package/dist/core/scheduler/posix.d.ts.map +1 -1
  58. package/dist/core/scheduler/posix.js +2 -2
  59. package/dist/core/scheduler/registry.d.ts +3 -2
  60. package/dist/core/scheduler/registry.d.ts.map +1 -1
  61. package/dist/core/scheduler/registry.js +6 -5
  62. package/dist/core/scheduler/windows.d.ts +49 -1
  63. package/dist/core/scheduler/windows.d.ts.map +1 -1
  64. package/dist/core/scheduler/windows.js +219 -34
  65. package/dist/core/secrets.d.ts +5 -3
  66. package/dist/core/secrets.d.ts.map +1 -1
  67. package/dist/core/secrets.js +86 -8
  68. package/dist/core/self-analysis.d.ts +117 -0
  69. package/dist/core/self-analysis.d.ts.map +1 -0
  70. package/dist/core/self-analysis.js +539 -0
  71. package/dist/core/session.d.ts +11 -3
  72. package/dist/core/session.d.ts.map +1 -1
  73. package/dist/core/session.js +34 -5
  74. package/dist/core/shutdown.d.ts +26 -0
  75. package/dist/core/shutdown.d.ts.map +1 -0
  76. package/dist/core/shutdown.js +49 -0
  77. package/dist/core/summary.d.ts +69 -0
  78. package/dist/core/summary.d.ts.map +1 -0
  79. package/dist/core/summary.js +250 -0
  80. package/dist/core/telegram.d.ts +10 -0
  81. package/dist/core/telegram.d.ts.map +1 -1
  82. package/dist/core/telegram.js +228 -47
  83. package/dist/core/triage-chain.d.ts +40 -0
  84. package/dist/core/triage-chain.d.ts.map +1 -0
  85. package/dist/core/triage-chain.js +80 -0
  86. package/dist/core/triage-compare.d.ts +68 -0
  87. package/dist/core/triage-compare.d.ts.map +1 -0
  88. package/dist/core/triage-compare.js +184 -0
  89. package/dist/core/triage-rules.d.ts +23 -0
  90. package/dist/core/triage-rules.d.ts.map +1 -0
  91. package/dist/core/triage-rules.js +196 -0
  92. package/dist/core/triage-shadow.d.ts +91 -0
  93. package/dist/core/triage-shadow.d.ts.map +1 -0
  94. package/dist/core/triage-shadow.js +160 -0
  95. package/dist/core/triage-worker.d.ts +55 -0
  96. package/dist/core/triage-worker.d.ts.map +1 -0
  97. package/dist/core/triage-worker.js +314 -0
  98. package/dist/core/triage.d.ts +76 -0
  99. package/dist/core/triage.d.ts.map +1 -0
  100. package/dist/core/triage.js +271 -0
  101. package/dist/core/watch-paths.d.ts +6 -0
  102. package/dist/core/watch-paths.d.ts.map +1 -0
  103. package/dist/core/watch-paths.js +62 -0
  104. package/dist/core/wrappers/bash.d.ts +15 -3
  105. package/dist/core/wrappers/bash.d.ts.map +1 -1
  106. package/dist/core/wrappers/bash.js +153 -120
  107. package/dist/db/history-repo.d.ts +1 -1
  108. package/dist/db/history-repo.d.ts.map +1 -1
  109. package/dist/db/history-repo.js +29 -14
  110. package/dist/db/schema.d.ts +1 -1
  111. package/dist/db/schema.d.ts.map +1 -1
  112. package/dist/db/schema.js +31 -0
  113. package/dist/history.d.ts +2 -2
  114. package/dist/history.d.ts.map +1 -1
  115. package/dist/history.js +3 -3
  116. package/dist/i18n.d.ts +25 -2
  117. package/dist/i18n.d.ts.map +1 -1
  118. package/dist/i18n.js +75 -10
  119. package/dist/index.d.ts +66 -3
  120. package/dist/index.d.ts.map +1 -1
  121. package/dist/index.js +527 -68
  122. package/dist/integrations.d.ts +9 -1
  123. package/dist/integrations.d.ts.map +1 -1
  124. package/dist/integrations.js +34 -6
  125. package/dist/notifications.d.ts +30 -2
  126. package/dist/notifications.d.ts.map +1 -1
  127. package/dist/notifications.js +289 -10
  128. package/dist/profiles.d.ts +1 -1
  129. package/dist/profiles.d.ts.map +1 -1
  130. package/dist/profiles.js +21 -3
  131. package/dist/rpc.d.ts +401 -5
  132. package/dist/rpc.d.ts.map +1 -1
  133. package/dist/rpc.js +138 -5
  134. package/dist/server.d.ts +20 -0
  135. package/dist/server.d.ts.map +1 -1
  136. package/dist/server.js +136 -14
  137. package/dist/settings.d.ts +167 -3
  138. package/dist/settings.d.ts.map +1 -1
  139. package/dist/settings.js +322 -3
  140. package/dist/task-transfer.d.ts +8 -1
  141. package/dist/task-transfer.d.ts.map +1 -1
  142. package/dist/task-transfer.js +2 -2
  143. package/dist/types.d.ts +8 -1
  144. package/dist/types.d.ts.map +1 -1
  145. package/dist/types.js +23 -5
  146. package/dist/workspaces.d.ts +9 -0
  147. package/dist/workspaces.d.ts.map +1 -1
  148. package/dist/workspaces.js +25 -0
  149. package/docs/ARCHITECTURE.md +48 -28
  150. package/docs/CONCEPT.md +230 -0
  151. package/docs/CROSS_PLATFORM.ru.md +150 -0
  152. package/docs/CROSS_PLATFORM.zh.md +146 -0
  153. package/docs/FAQ.md +52 -0
  154. package/docs/FAQ.ru.md +53 -0
  155. package/docs/FAQ.zh.md +43 -0
  156. package/docs/FEATURES.md +141 -44
  157. package/docs/FEATURES.zh.md +655 -0
  158. package/docs/LOCAL-AI.md +300 -0
  159. package/docs/MIGRATION.md +17 -0
  160. package/docs/README.ru.md +22 -16
  161. package/docs/README.zh.md +286 -0
  162. package/docs/SAVINGS.md +61 -0
  163. package/docs/SAVINGS.ru.md +60 -0
  164. package/docs/SAVINGS.zh.md +52 -0
  165. package/docs/ZH-LOCALE-PLAN.md +324 -0
  166. package/docs/spikes/local-model-structured-output.md +81 -0
  167. package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
  168. package/docs/spikes/ollama-qwen3-4b.json +163 -0
  169. package/gui-experimental.cjs +8 -8
  170. package/locales/en.json +85 -0
  171. package/locales/ru.json +85 -0
  172. package/locales/zh.json +780 -0
  173. package/package.json +31 -7
  174. package/scripts/bench-local.mjs +321 -0
  175. package/scripts/check-zh-locale.mjs +218 -0
  176. package/scripts/run-tests.mjs +236 -0
  177. package/scripts/spike-local-structured.mjs +182 -0
  178. package/scripts/test-locale.mjs +4 -3
  179. package/skills/scheduled-job-best-practices/SKILL.md +6 -3
  180. package/skills/scheduled-job-best-practices/references/recipes.md +40 -0
  181. package/src/core/analytics.ts +10 -0
  182. package/src/core/audit.ts +39 -1
  183. package/src/core/cron-to-schtasks.ts +23 -4
  184. package/src/core/file-watcher.ts +20 -1
  185. package/src/core/git-trigger.ts +34 -16
  186. package/src/core/local-ai.ts +173 -0
  187. package/src/core/lock.ts +88 -3
  188. package/src/core/matrix.ts +5 -1
  189. package/src/core/native-notify.ts +3 -0
  190. package/src/core/one-shot.ts +18 -2
  191. package/src/core/permissions.ts +200 -0
  192. package/src/core/ps-wrapper.ts +492 -108
  193. package/src/core/record-history.ts +111 -4
  194. package/src/core/savings.ts +150 -0
  195. package/src/core/schedule-gate.ts +9 -3
  196. package/src/core/schedule-v2.ts +1 -1
  197. package/src/core/scheduler/index.ts +41 -3
  198. package/src/core/scheduler/linux.ts +67 -22
  199. package/src/core/scheduler/mac.ts +24 -7
  200. package/src/core/scheduler/posix.ts +2 -2
  201. package/src/core/scheduler/registry.ts +7 -5
  202. package/src/core/scheduler/windows.ts +237 -32
  203. package/src/core/secrets.ts +101 -7
  204. package/src/core/self-analysis.ts +744 -0
  205. package/src/core/session.ts +40 -5
  206. package/src/core/shutdown.ts +69 -0
  207. package/src/core/summary.ts +318 -0
  208. package/src/core/telegram.ts +266 -55
  209. package/src/core/triage-chain.ts +125 -0
  210. package/src/core/triage-compare.ts +277 -0
  211. package/src/core/triage-rules.ts +238 -0
  212. package/src/core/triage-shadow.ts +240 -0
  213. package/src/core/triage-worker.ts +344 -0
  214. package/src/core/triage.ts +366 -0
  215. package/src/core/watch-paths.ts +70 -0
  216. package/src/core/wrappers/bash.ts +181 -138
  217. package/src/db/history-repo.ts +31 -18
  218. package/src/db/schema.ts +31 -0
  219. package/src/gui.tsx +551 -14
  220. package/src/history.ts +7 -3
  221. package/src/i18n.ts +87 -13
  222. package/src/index.ts +649 -71
  223. package/src/integrations.ts +50 -6
  224. package/src/notifications.ts +468 -5
  225. package/src/profiles.ts +21 -3
  226. package/src/rpc.ts +143 -5
  227. package/src/server.ts +135 -16
  228. package/src/settings.ts +582 -5
  229. package/src/task-transfer.ts +10 -3
  230. package/src/types.ts +24 -5
  231. package/src/workspaces.ts +22 -0
@@ -0,0 +1,300 @@
1
+ # Local assistant (triage)
2
+
3
+ The local assistant is an optional, fully offline classifier for run outcomes.
4
+ After a run finishes, the scheduler can ask a local model to classify the
5
+ outcome (quality, timeout, permission, network, unknown) and write the verdict
6
+ to the triage audit. It is **opt-in**: when no model is available the scheduler
7
+ keeps working exactly as before and notifications are never blocked.
8
+
9
+ Triage is not a scheduler feature by itself — it only affects notifications. It
10
+ never changes run status, retries, Quality Gates, DAG dependencies or history.
11
+
12
+ ## How it works
13
+
14
+ ```
15
+ run finished ──► triage chain ──► notify / skip / log-only (shadow)
16
+ │
17
+ ├─ llm — local model classifies the failure
18
+ └─ rules - built-in patterns (timeout, permission, network, quality, cost, task)
19
+ ```
20
+
21
+ - `off` — no triage; every notification is sent (default).
22
+ - `rules` — built-in rules only. No model, no network calls.
23
+ - `llm` — the configured local model only.
24
+ - `auto` — the model first, then the rules engine (recommended).
25
+
26
+ Rules semantics: if `rules` is omitted (`undefined`), the built-in rule set is
27
+ active. An explicit empty array (`rules: []`) disables the rules engine entirely.
28
+ A non-empty custom array replaces the built-in set; it does not extend it.
29
+
30
+ ### Built-in rules
31
+
32
+ The built-in set classifies errors by text, status, cost and task name. All
33
+ built-in rules are notify-only: they never suppress a notification.
34
+
35
+ | Rule | Match | Severity |
36
+ | --- | --- | --- |
37
+ | `error-timeout` | timeout / deadline in the error text | high |
38
+ | `error-permission` | permission denied, access denied, forbidden | high |
39
+ | `error-network` | connection refused/reset, DNS, network error | high |
40
+ | `error-quality` | Quality Gate, failed tests, failed build, lint | high |
41
+ | `cost-high` | `costUsd >= 1` | high |
42
+ | `task-important` | task name contains deploy, release, publish, production, backup, restore or migration | high |
43
+ | `status-error` | status is `error` | high |
44
+ | `status-partial` | status is `partial` | medium |
45
+ | `status-success` | status is `success` | low |
46
+
47
+ A custom array replaces the built-in set. For example, this configuration
48
+ suppresses noisy nightly runs and marks runs costing $5 or more as high:
49
+
50
+ ```json
51
+ "notifications": {
52
+ "triage": {
53
+ "mode": "rules",
54
+ "rules": [
55
+ { "id": "skip-nightly", "field": "task", "operator": "contains", "value": "nightly", "action": "skip", "priority": 50 },
56
+ { "id": "expensive", "field": "cost", "operator": "gte", "value": 5, "severity": "high", "priority": 90 }
57
+ ]
58
+ }
59
+ }
60
+ ```
61
+
62
+ The result is validated against a fixed JSON schema. Invalid JSON, an
63
+ unreachable endpoint, a timeout or low confidence all fall back to the rules
64
+ engine (fail-open). With `fallback: "notify"` the scheduler skips the rules step
65
+ and delivers the notification instead. The legacy name `"skip"` is still
66
+ accepted and normalized to `"notify"`.
67
+
68
+ The model only **classifies** a run: a valid verdict never suppresses a
69
+ notification on its own. Only a matching rule with `action: "skip"` can
70
+ suppress delivery. This is intentional: an uncertain small model must not be
71
+ able to hide a real failure.
72
+
73
+ ## Delivery latency (async triage)
74
+
75
+ In `llm` and `auto` modes triage runs asynchronously. `record-history` delivers
76
+ the notification immediately and starts a detached worker for the model call;
77
+ the worker writes the verdict to `audit_log` with `async: true`. The configured
78
+ `timeoutMs` applies to that background request, not to delivery: a cold model
79
+ that takes 40 seconds cannot delay the webhook, chain triggers or the task lock.
80
+
81
+ Only `rules` mode triages synchronously, because rules are the only thing that
82
+ can suppress a notification. In `llm`/`auto` the model and its rules fallback
83
+ are advisory: the notification is already sent, so `action: "skip"` in the
84
+ audit means “would have been skipped”, not “was suppressed”. Use `rules` mode
85
+ if rules must actually suppress delivery. The GUI shows this warning when a
86
+ model mode is selected.
87
+
88
+ In shadow mode the worker records `shadow: true` and `suppressed: false`, so a
89
+ shadow report remains a safe preview of triage decisions.
90
+
91
+ ## Requirements
92
+
93
+ - [Ollama](https://ollama.com/) running locally, or any OpenAI-compatible
94
+ server (a `baseUrl` ending with `/v1` switches to the OpenAI protocol).
95
+ - One pulled model, for example `qwen3:4b`.
96
+ - No internet access is required after the model is downloaded.
97
+
98
+ ```bash
99
+ ollama serve
100
+ ollama pull qwen3:4b
101
+ ```
102
+
103
+ ## Configuration
104
+
105
+ Triage settings live under `notifications.triage` and are edited from the GUI
106
+ side panel ("Local assistant") or through the `manage_local_ai` agent tool.
107
+
108
+ The panel shows a persistent connection status next to **Test connection**:
109
+ grey means "not checked", amber "checking", green "connected", red "no
110
+ connection" with the provider error. The test sends one synthetic
111
+ classification request (it is not saved) and reports the model, protocol and
112
+ latency. Status resets when `mode`, `baseUrl` or `model` changes, so a stale
113
+ green cannot hide a new endpoint. A red status never blocks notifications:
114
+ `llm`/`auto` triage is asynchronous and fail-open.
115
+
116
+ | Setting | Values | Default | Meaning |
117
+ | --- | --- | --- | --- |
118
+ | `mode` | `off` / `rules` / `llm` / `auto` | `off` | Triage strategy. |
119
+ | `baseUrl` | URL | `http://127.0.0.1:11434` | Ollama or OpenAI-compatible endpoint. |
120
+ | `model` | string | `""` | Model id, for example `qwen3:4b`. |
121
+ | `timeoutMs` | 1000..120000 | `60000` | Background request timeout in `llm`/`auto`; does not delay delivery. |
122
+ | `fallback` | `rules` / `notify` | `rules` | Behaviour when the model fails or is unsure. |
123
+ | `confidenceThreshold` | 0..1 | `0.6` | Minimum model confidence; below it the fallback applies. |
124
+ | `shadow.enabled` | boolean | `true` | Log decisions without suppressing notifications. |
125
+ | `shadow.days` | 1..365 | `14` | Shadow period length. |
126
+ | `shadow.startedAt` | ISO string / null | `null` | Start of the shadow period; `null` restarts it. |
127
+
128
+ `fallback: "skip"` is accepted as a legacy alias for `notify` and is normalized
129
+ on load, so old settings keep working without edits.
130
+
131
+ ## Message summaries
132
+
133
+ `notifications.summary` turns a notification into at most three short lines for
134
+ Telegram and OS toasts. The same Ollama/OpenAI-compatible provider is used, but
135
+ the request is independent of triage and has its own timeout.
136
+
137
+ | Setting | Values | Default | Meaning |
138
+ | --- | --- | --- | --- |
139
+ | `summary.enabled` | boolean | `false` | Use the model summary instead of the template message. |
140
+ | `summary.maxLines` | 1..3 | `3` | Maximum number of lines. |
141
+ | `summary.maxCharsPerLine` | 20..500 | `120` | Hard cut per line. |
142
+ | `summary.timeoutMs` | 1000..120000 | `8000` | Summary request timeout. |
143
+
144
+ The model must answer with strict JSON `{"lines": ["...", "..."]}`. Any
145
+ failure — no provider, HTTP error, timeout, invalid JSON or schema — falls back
146
+ to a deterministic truncation: status and task name, the error text, then
147
+ runtime, tokens and cost. A summary never blocks or drops the notification:
148
+ delivery waits at most `timeoutMs`.
149
+
150
+ ## Managing triage from the agent
151
+
152
+ The `manage_local_ai` tool has three actions.
153
+
154
+ Read the current state:
155
+
156
+ ```json
157
+ { "action": "get" }
158
+ ```
159
+
160
+ Update one or more fields (merged with the current settings):
161
+
162
+ ```json
163
+ {
164
+ "action": "update",
165
+ "mode": "auto",
166
+ "baseUrl": "http://127.0.0.1:11434",
167
+ "model": "qwen3:4b",
168
+ "timeoutMs": 60000,
169
+ "fallback": "rules",
170
+ "confidenceThreshold": 0.6,
171
+ "shadow": { "enabled": true, "days": 14 }
172
+ }
173
+ ```
174
+
175
+ Send one classification request against the configured model (or a candidate
176
+ patch without saving it):
177
+
178
+ ```json
179
+ { "action": "test", "model": "qwen3:4b", "timeoutMs": 60000 }
180
+ ```
181
+
182
+ `get` and `update` return a summary: `mode`, `baseUrl`, `model`, `timeoutMs`,
183
+ `fallback`, `confidenceThreshold`, `rules` (number of active rules or `null`),
184
+ `shadow`, `llmReady`, `shadowActive` and `protocol` (`ollama` or `openai`).
185
+
186
+ ## Picking a model by RAM
187
+
188
+ The classifier is a small, structured task: a 4B model is usually enough. The
189
+ benchmark below prints a tier for the current machine.
190
+
191
+ | RAM | Tier | Recommended model | Notes |
192
+ | --- | --- | --- | --- |
193
+ | < 8 GB | rules-only | `qwen3:0.6b` | Prefer `mode: "rules"`; a tiny model may be too slow. |
194
+ | 8–15 GB | light | `qwen3:1.7b` | Fast, lower accuracy. |
195
+ | 15–30 GB | balanced | `qwen3:4b` | Recommended default. |
196
+ | > 30 GB | max | `qwen3:8b` | Better accuracy, more latency. |
197
+
198
+ ## Benchmarking a machine
199
+
200
+ `scripts/bench-local.mjs` measures latency, schema validity and throughput
201
+ (tokens/s) for the configured model. It reuses the same triage prompt and JSON
202
+ schema as the scheduler.
203
+
204
+ ```bash
205
+ npm run bench:local -- --model qwen3:4b --runs 3
206
+ npm run bench:local -- --model qwen3:4b --runs 5 --out bench.json
207
+ ```
208
+
209
+ Options: `--base-url`, `--model`, `--runs` (1..50), `--timeout` (1000..600000),
210
+ `--out`, `--help`.
211
+
212
+ The report is a versioned JSON envelope (`schemaVersion: "1"`) suitable for
213
+ crowdsourcing results:
214
+
215
+ ```json
216
+ {
217
+ "schemaVersion": "1",
218
+ "generatedAt": "2026-11-15T12:00:00.000Z",
219
+ "available": true,
220
+ "machine": { "platform": "win32", "arch": "x64", "cpu": "…", "cpuCount": 16, "ramGb": 15.9, "nodeVersion": "v24.21.0" },
221
+ "tier": { "id": "balanced", "recommendedModel": "qwen3:4b", "reason": "…" },
222
+ "model": "qwen3:4b",
223
+ "runs": 3,
224
+ "metrics": {
225
+ "schemaValid": 3,
226
+ "schemaValidRate": 1,
227
+ "jsonValid": 3,
228
+ "jsonValidRate": 1,
229
+ "avgLatencyMs": 23785,
230
+ "p95LatencyMs": 26904,
231
+ "avgTokPerSec": 28.7,
232
+ "p95TokPerSec": 28.98
233
+ },
234
+ "results": []
235
+ }
236
+ ```
237
+
238
+ Exit codes: `0` when at least 70% of responses are schema-valid, `1` otherwise,
239
+ `2` when the endpoint or model is unavailable (the JSON report is still written
240
+ with `available: false`).
241
+
242
+ ## Shadow mode
243
+
244
+ Shadow mode is the safe way to evaluate triage. Decisions are written to the
245
+ persistent audit journal (`audit_log`, action `triage.decision`), but no
246
+ notification is suppressed. In `llm`/`auto` the verdict arrives asynchronously
247
+ after delivery; in `rules` mode it is computed before delivery. Check the shadow
248
+ report before switching to `mode: "auto"`: it shows how many notifications
249
+ would have been skipped and whether any of those were false positives.
250
+
251
+ The journal survives restarts and runs in the short-lived `record-history`
252
+ process, unlike the old in-memory counters. Read individual decisions with
253
+ `get_audit_log` (`action: "triage.decision"`); the report is also available as
254
+ `rpc.get_shadow_report` (including the last 50 decisions). The report covers
255
+ the configured shadow window `[startedAt, startedAt + days]`; resetting it
256
+ deletes only shadow rows and keeps ordinary decision history.
257
+
258
+ Start with `mode: "auto"`, `shadow.enabled: true` and `shadow.days: 14`. After
259
+ the period, review the shadow report and only then disable shadow mode.
260
+
261
+ ## Troubleshooting
262
+
263
+ | Symptom | Cause | Fix |
264
+ | --- | --- | --- |
265
+ | `connection refused` / `fetch failed` | Ollama is not running | `ollama serve` |
266
+ | `model not found` | Model not pulled | `ollama pull <model>`, then check `ollama list` |
267
+ | Requests time out | Model too large for the machine or context too long | Lower the model tier, raise `timeoutMs`, cap context (below) |
268
+ | `llmReady: false` in `manage_local_ai` `get` | Endpoint or model unavailable | Check `baseUrl` and `model` |
269
+ | Very slow first response | Cold model load | Run once to warm the model; the benchmark shows steady-state numbers |
270
+ | Invalid JSON from the model | Model too small or prompt drift | Use a larger model or `mode: "rules"` |
271
+
272
+ ### OLLAMA_CONTEXT_LENGTH
273
+
274
+ Ollama allocates a large context window by default, which costs RAM and slows
275
+ CPU inference. For triage, a short context is enough. Set it in the environment
276
+ before starting the server:
277
+
278
+ ```bash
279
+ # Windows (PowerShell)
280
+ $env:OLLAMA_CONTEXT_LENGTH = "2048"
281
+ ollama serve
282
+ ```
283
+
284
+ ```bash
285
+ # Linux / macOS
286
+ OLLAMA_CONTEXT_LENGTH=2048 ollama serve
287
+ ```
288
+
289
+ Restart Ollama after changing the variable. If the model still does not fit,
290
+ choose a smaller tier or use `mode: "rules"`.
291
+
292
+ ## Limits
293
+
294
+ - Triage only affects notifications. It never rewrites run results.
295
+ - The model runs locally; prompts and logs are not sent to a third party.
296
+ - A missing model never blocks scheduling: rules or direct delivery take over.
297
+ - The classifier is intentionally conservative. When in doubt it delivers the
298
+ notification (fail-open).
299
+ - The benchmark measures a single machine; results are not a guarantee for other
300
+ hardware.
package/docs/MIGRATION.md CHANGED
@@ -240,6 +240,20 @@ For every migrated job:
240
240
  right workspace path.
241
241
  6. Wait for at least one natural scheduled run before deleting the old definition.
242
242
 
243
+ ## Local AI / triage migration
244
+
245
+ If you are migrating from a setup that used cloud AI for lightweight task triage or
246
+ classification, you can move that load to a local model to save tokens:
247
+
248
+ 1. Install Ollama: `ollama serve` and `ollama pull qwen3:4b` (or a smaller model for
249
+ RAM-constrained machines — see `docs/LOCAL-AI.md` for tier recommendations).
250
+ 2. Configure triage via `manage_local_ai({action: "update", mode: "auto", ...})` or
251
+ through the GUI notifications panel.
252
+ 3. Start in `shadow` mode so decisions are logged but not applied, then switch to `auto`
253
+ once confidence is acceptable.
254
+ 4. Ollama is optional — if it is unavailable, the plugin falls back to rules-only mode
255
+ (fail-open) and never blocks notifications.
256
+
243
257
  ## Common pitfalls
244
258
 
245
259
  | Symptom | Cause | Fix |
@@ -252,6 +266,9 @@ For every migrated job:
252
266
  | Two runs at once after migration | old scheduler is still enabled | disable the old job |
253
267
  | Cron rejected | expression not expressible by `schtasks` | use a supported pattern (`*/N`, fixed minute/hour, weekdays) |
254
268
  | Prompts behave differently at night | interactive shell environment vs scheduler environment | use absolute paths, avoid alias-dependent commands |
269
+ | Local AI (Ollama) unreachable | `manage_local_ai` test fails or triage falls back to rules | run `ollama serve`, `ollama pull <model>`, check `OLLAMA_CONTEXT_LENGTH` |
270
+ | Local AI confidence too low | rules fire instead of LLM, more tokens used than expected | raise `confidenceThreshold` in `manage_local_ai`, review rule reasons in audit |
271
+
255
272
 
256
273
  ## Rollback
257
274
 
package/docs/README.ru.md CHANGED
@@ -7,13 +7,20 @@
7
7
  [![license](https://img.shields.io/npm/l/opencode-windows-scheduler.svg)](../LICENSE)
8
8
  [![node](https://img.shields.io/node/v/opencode-windows-scheduler.svg)](../package.json)
9
9
 
10
- English version: [README.md](../README.md).
10
+ Translations: [English](../README.md) · [中文](README.zh.md).
11
11
 
12
12
  ---
13
13
 
14
- ![Локальный веб-дашборд: матричные сборки, граф DAG, метрики и история запусков](dashboard.png)
14
+ ## Быстрый старт
15
+
16
+ 1. Установите плагин (см. [Установка](#установка)) и перезапустите OpenCode.
17
+ 2. Попросите агента поставить первую задачу — достаточно одного вызова:
18
+
19
+ > Поставь задачу «утренний-отчёт»: каждый день в 09:00 с промптом «Просуммаризируй вчерашние git-коммиты и запиши отчёт в ~/reports/».
15
20
 
16
- Хотите посмотреть без установки OpenCode? `node scripts/demo-dashboard.mjs` поднимет дашборд с демо-данными на http://localhost:4380.
21
+ 3. Откройте дашборд: агент печатает ссылку при создании задачи (по умолчанию `http://localhost:4380`), позже её можно получить инструментом `get_dashboard_info`. Посмотреть демо без установки: `node scripts/demo-dashboard.mjs` — дашборд с демо-данными на `http://localhost:4380`.
22
+
23
+ ![Локальный веб-дашборд: матричные сборки, граф DAG, метрики и история запусков](dashboard.png)
17
24
 
18
25
  ## Зачем
19
26
 
@@ -38,18 +45,18 @@ English version: [README.md](../README.md).
38
45
  | Триггеры | cron, одноразовый запуск (`triggerType: "once"`), git-коммиты (`triggerType: "git"`, фильтры ветки/путей/игнорирования), изменение файла (chokidar, glob-маски `watchGlobs`/`watchIgnore`), MCP-события, входящие webhooks (`POST /api/hooks/:task` с HMAC) |
39
46
  | Мультирепо | workspaces с валидацией путей, запуски по workspace, матрица поверх родительской задачи |
40
47
  | Наблюдаемость | история SQLite (success / error / timeout / partial / running), метрики (длительность, токены, стоимость), JSONL-логи с `/api/logs`, Prometheus `/metrics`, экспорт OTLP, логи по задачам, веб-дашборд с аналитикой за 14 дней, ретеншн истории и экспорт CSV/JSON |
41
- | Эксплуатация | dry-run, экспорт/импорт JSON, шаблоны, уведомления по нескольким каналам (webhook, Telegram, нативные toast), тихие часы, дайджест, зашифрованные секреты (`${secret:NAME}`), журнал аудита, настройки |
42
- | Интерфейсы | панель OpenCode GUI, веб-дашборд, 24 инструмента для агента, встроенный скилл |
48
+ | Эксплуатация | dry-run, экспорт/импорт JSON, шаблоны, уведомления по нескольким каналам (webhook, Telegram, нативные toast), тихие часы, дайджест, локальный ассистент для триажа уведомлений (fail-open, shadow-режим), зашифрованные секреты (`${secret:NAME}`), журнал аудита, настройки |
49
+ | Интерфейсы | панель OpenCode GUI, веб-дашборд, 25 инструментов для агента, встроенный скилл |
43
50
 
44
51
  ### Язык интерфейса
45
52
 
46
- Интерфейс доступен на русском (по умолчанию) и английском. Язык переключается в настройках сайдбара (Настройки → Язык) или инструментом `manage_settings` (`action: "update"`, `locale: "en"`). Изменение применяется сразу к панели, уведомлениям и дайджесту, дашборду и результатам инструментов агента — перезапуск не нужен. Описания и схемы инструментов агента остаются английскими, диагностика в консоли — русской.
53
+ Интерфейс доступен на русском (по умолчанию), английском и китайском (упрощённом). Переключатель языка находится в шапке панели планировщика (🌐 Авто / Русский / English / 中文), а также доступен через инструмент `manage_settings` (`action: "update"`, `locale: "zh"`). Значение `locale: "auto"` («Авто») следует за языком интерфейса OpenCode: панель реагирует на смену языка сразу, а разрешённая локаль отправляется на сервер, чтобы уведомления, дайджест и дашборд использовали тот же язык. Переключение применяется без перезапуска. Локализация дашборда ещё не завершена: часть строк на стороне клиента пока остаётся русской. Описания и схемы инструментов агента остаются английскими, диагностика в консоли — русской.
47
54
 
48
- Каталоги лежат в `locales/ru.json` и `locales/en.json`; набор ключей в них должен совпадать, иначе CI падает.
55
+ Каталоги лежат в `locales/ru.json`, `locales/en.json` и `locales/zh.json`; набор ключей в них должен совпадать, иначе CI падает.
49
56
 
50
57
  ## Установка
51
58
 
52
- Нужны OpenCode v2 и Node.js 20+.
59
+ Нужны OpenCode v2 и Node.js 22.22+.
53
60
 
54
61
  ```bash
55
62
  opencode plugin add opencode-windows-scheduler
@@ -69,12 +76,6 @@ opencode plugin add opencode-windows-scheduler
69
76
 
70
77
  `experimental.schedules: false` отключает встроенный планировщик OpenCode, чтобы агент не путал встроенные инструменты расписаний с инструментами этого плагина. После изменения конфигурации перезапустите OpenCode.
71
78
 
72
- Альтернатива — глобальная установка через npm:
73
-
74
- ```bash
75
- npm install -g opencode-windows-scheduler
76
- ```
77
-
78
79
  Из исходников:
79
80
 
80
81
  ```bash
@@ -86,7 +87,7 @@ npm run build && npm run build:gui
86
87
 
87
88
  ## Инструменты для агента
88
89
 
89
- Агенту доступен весь функционал — 24 инструмента: расписание, пайплайны, эксплуатация, аналитика и администрирование.
90
+ Агенту доступен весь функционал — 25 инструментов: расписание, пайплайны, эксплуатация, аналитика и администрирование.
90
91
 
91
92
  | Инструмент | Аргументы | Что делает |
92
93
  |---|---|---|
@@ -105,6 +106,7 @@ npm run build && npm run build:gui
105
106
  | `get_metrics` | — | Всего запусков, успехов и падений |
106
107
  | `get_analytics` | `days?`, `topLimit?` | Отчёт за период: запуски, успешность, длительность, токены, стоимость, топ задач |
107
108
  | `manage_settings` | `action`, `maxConcurrent?`, `winterMode?`, `notifications?`, `history?` | Чтение и изменение глобальных настроек (параллелизм, уведомления, retention) |
109
+ | `manage_local_ai` | `action` (`get`/`update`/`test`), `mode?`, `baseUrl?`, `model?`, `timeoutMs?`, `fallback?`, `confidenceThreshold?`, `shadow?` | Настройки локального ассистента для триажа уведомлений и проверка модели одним запросом (см. [LOCAL-AI.md](LOCAL-AI.md)) |
108
110
  | `manage_templates` | `action`, поля шаблона | Список, сохранение и удаление шаблонов задач |
109
111
  | `manage_profiles` | `action`, `name?`, `port?` | Список, создание, переключение и удаление изолированных профилей |
110
112
  | `transfer_tasks` | `action`, `data?` | Экспорт всех задач в JSON и импорт обратно |
@@ -184,7 +186,7 @@ src/
184
186
  npm install
185
187
  npm run build # tsc
186
188
  npm run build:gui # vite
187
- npm test # 33 сюиты, 500+ проверок
189
+ npm test # 58 сюит, 600+ проверок
188
190
  npm run test:en # те же сюиты с английской локалью
189
191
  ```
190
192
 
@@ -195,8 +197,12 @@ npm run test:en # те же сюиты с английской локаль
195
197
  ## Документация
196
198
 
197
199
  - [ARCHITECTURE.md](ARCHITECTURE.md) — модель процессов, модули, бэкенды, модель данных.
200
+ - [CONCEPT.md](CONCEPT.md) — north star: верифицируемая локально-первая оркестрация.
198
201
  - [FEATURES.md](FEATURES.md) — полный каталог возможностей с примерами.
202
+ - [FAQ.md](FAQ.md) — сценарии восстановления и ответы по эксплуатации (English).
199
203
  - [MIGRATION.md](MIGRATION.md) — переезд с cron, systemd, launchd или Планировщика Windows.
204
+ - [SAVINGS.md](SAVINGS.md) — как считается оценка «Сэкономлено $» (English).
205
+ - [../CROSS_PLATFORM.md](../CROSS_PLATFORM.md) — различия и бэкенды Windows / macOS / Linux.
200
206
 
201
207
  ## FAQ
202
208