agent-steward 0.0.2 → 0.0.4

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 (263) hide show
  1. package/CHANGELOG.md +45 -2
  2. package/CROSS_PLATFORM.md +11 -9
  3. package/README.md +11 -10
  4. package/ROADMAP-STRATEGY.md +93 -44
  5. package/ROADMAP.md +148 -1017
  6. package/dist/core/cron-to-schtasks.d.ts +0 -8
  7. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  8. package/dist/core/cron-to-schtasks.js +11 -86
  9. package/dist/core/dlq-api.d.ts +44 -0
  10. package/dist/core/dlq-api.d.ts.map +1 -0
  11. package/dist/core/dlq-api.js +68 -0
  12. package/dist/core/dry-run.d.ts.map +1 -1
  13. package/dist/core/dry-run.js +19 -2
  14. package/dist/core/file-watcher.js +9 -9
  15. package/dist/core/git-trigger.js +4 -4
  16. package/dist/core/lock.d.ts +20 -4
  17. package/dist/core/lock.d.ts.map +1 -1
  18. package/dist/core/lock.js +99 -26
  19. package/dist/core/one-shot.d.ts +31 -5
  20. package/dist/core/one-shot.d.ts.map +1 -1
  21. package/dist/core/one-shot.js +78 -10
  22. package/dist/core/opencode-cli.d.ts +28 -0
  23. package/dist/core/opencode-cli.d.ts.map +1 -0
  24. package/dist/core/opencode-cli.js +74 -0
  25. package/dist/core/opencode-models.d.ts +62 -0
  26. package/dist/core/opencode-models.d.ts.map +1 -0
  27. package/dist/core/opencode-models.js +277 -0
  28. package/dist/core/otel.js +2 -2
  29. package/dist/core/ps-wrapper.d.ts +1 -1
  30. package/dist/core/ps-wrapper.d.ts.map +1 -1
  31. package/dist/core/ps-wrapper.js +66 -36
  32. package/dist/core/record-history.d.ts +15 -0
  33. package/dist/core/record-history.d.ts.map +1 -1
  34. package/dist/core/record-history.js +78 -54
  35. package/dist/core/router/dispatch.d.ts +36 -0
  36. package/dist/core/router/dispatch.d.ts.map +1 -0
  37. package/dist/core/router/dispatch.js +59 -0
  38. package/dist/core/router/escalation.d.ts +47 -0
  39. package/dist/core/router/escalation.d.ts.map +1 -0
  40. package/dist/core/router/escalation.js +87 -0
  41. package/dist/core/router/planner.d.ts +53 -0
  42. package/dist/core/router/planner.d.ts.map +1 -0
  43. package/dist/core/router/planner.js +113 -0
  44. package/dist/core/router/rules.d.ts +46 -0
  45. package/dist/core/router/rules.d.ts.map +1 -0
  46. package/dist/core/router/rules.js +85 -0
  47. package/dist/core/run-panel-api.d.ts +94 -0
  48. package/dist/core/run-panel-api.d.ts.map +1 -0
  49. package/dist/core/run-panel-api.js +169 -0
  50. package/dist/core/schedule-gate.js +5 -1
  51. package/dist/core/schedule-v2.d.ts +36 -2
  52. package/dist/core/schedule-v2.d.ts.map +1 -1
  53. package/dist/core/schedule-v2.js +98 -12
  54. package/dist/core/scheduler/at-fallback.d.ts +95 -0
  55. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  56. package/dist/core/scheduler/at-fallback.js +200 -0
  57. package/dist/core/scheduler/linux.d.ts +13 -2
  58. package/dist/core/scheduler/linux.d.ts.map +1 -1
  59. package/dist/core/scheduler/linux.js +67 -13
  60. package/dist/core/scheduler/mac.d.ts +14 -8
  61. package/dist/core/scheduler/mac.d.ts.map +1 -1
  62. package/dist/core/scheduler/mac.js +71 -22
  63. package/dist/core/scheduler/posix.d.ts.map +1 -1
  64. package/dist/core/scheduler/posix.js +37 -2
  65. package/dist/core/scheduler/registry.d.ts +13 -0
  66. package/dist/core/scheduler/registry.d.ts.map +1 -1
  67. package/dist/core/scheduler/registry.js +83 -21
  68. package/dist/core/scheduler/run-now.d.ts +16 -0
  69. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  70. package/dist/core/scheduler/run-now.js +28 -0
  71. package/dist/core/scheduler/windows.d.ts +16 -3
  72. package/dist/core/scheduler/windows.d.ts.map +1 -1
  73. package/dist/core/scheduler/windows.js +249 -96
  74. package/dist/core/secrets.d.ts.map +1 -1
  75. package/dist/core/secrets.js +127 -30
  76. package/dist/core/self-analysis.js +55 -55
  77. package/dist/core/session.d.ts.map +1 -1
  78. package/dist/core/session.js +18 -11
  79. package/dist/core/summary.js +1 -1
  80. package/dist/core/task-name.d.ts +24 -0
  81. package/dist/core/task-name.d.ts.map +1 -0
  82. package/dist/core/task-name.js +40 -0
  83. package/dist/core/triage-chain.js +1 -1
  84. package/dist/core/triage-worker.js +2 -2
  85. package/dist/core/triage.js +1 -1
  86. package/dist/core/wrappers/bash.d.ts.map +1 -1
  87. package/dist/core/wrappers/bash.js +82 -37
  88. package/dist/db/capability-repo.d.ts +83 -0
  89. package/dist/db/capability-repo.d.ts.map +1 -0
  90. package/dist/db/capability-repo.js +182 -0
  91. package/dist/db/history-repo.d.ts +8 -0
  92. package/dist/db/history-repo.d.ts.map +1 -1
  93. package/dist/db/history-repo.js +19 -0
  94. package/dist/db/index.d.ts +6 -0
  95. package/dist/db/index.d.ts.map +1 -1
  96. package/dist/db/index.js +48 -2
  97. package/dist/db/migrate.d.ts.map +1 -1
  98. package/dist/db/migrate.js +3 -1
  99. package/dist/db/run-context.d.ts +103 -0
  100. package/dist/db/run-context.d.ts.map +1 -0
  101. package/dist/db/run-context.js +224 -0
  102. package/dist/db/run-dlq.d.ts +100 -0
  103. package/dist/db/run-dlq.d.ts.map +1 -0
  104. package/dist/db/run-dlq.js +191 -0
  105. package/dist/db/run-journal.d.ts +60 -0
  106. package/dist/db/run-journal.d.ts.map +1 -0
  107. package/dist/db/run-journal.js +143 -0
  108. package/dist/db/run-resume.d.ts +51 -0
  109. package/dist/db/run-resume.d.ts.map +1 -0
  110. package/dist/db/run-resume.js +156 -0
  111. package/dist/db/runs-repo.d.ts +128 -0
  112. package/dist/db/runs-repo.d.ts.map +1 -0
  113. package/dist/db/runs-repo.js +342 -0
  114. package/dist/db/schema.d.ts +16 -2
  115. package/dist/db/schema.d.ts.map +1 -1
  116. package/dist/db/schema.js +342 -35
  117. package/dist/db/settings-repo.d.ts +11 -0
  118. package/dist/db/settings-repo.d.ts.map +1 -1
  119. package/dist/db/settings-repo.js +25 -0
  120. package/dist/db/step-idempotency.d.ts +51 -0
  121. package/dist/db/step-idempotency.d.ts.map +1 -0
  122. package/dist/db/step-idempotency.js +136 -0
  123. package/dist/index.d.ts +5 -5
  124. package/dist/index.d.ts.map +1 -1
  125. package/dist/index.js +168 -40
  126. package/dist/notifications.js +18 -18
  127. package/dist/profiles.d.ts +7 -3
  128. package/dist/profiles.d.ts.map +1 -1
  129. package/dist/profiles.js +85 -7
  130. package/dist/rpc.d.ts +787 -0
  131. package/dist/rpc.d.ts.map +1 -1
  132. package/dist/rpc.js +324 -0
  133. package/dist/server.d.ts +33 -2
  134. package/dist/server.d.ts.map +1 -1
  135. package/dist/server.js +115 -54
  136. package/dist/shared/jobs-view.d.ts.map +1 -1
  137. package/dist/skill.js +1 -1
  138. package/dist/task-transfer.d.ts +1 -1
  139. package/dist/task-transfer.d.ts.map +1 -1
  140. package/dist/task-transfer.js +14 -10
  141. package/dist/types.d.ts +20 -4
  142. package/dist/types.d.ts.map +1 -1
  143. package/dist/types.js +44 -9
  144. package/dist/workspaces.d.ts +25 -3
  145. package/dist/workspaces.d.ts.map +1 -1
  146. package/dist/workspaces.js +44 -9
  147. package/docs/ARCHITECTURE.md +335 -9
  148. package/docs/COMPATIBILITY.md +10 -6
  149. package/docs/CONCEPT.md +183 -91
  150. package/docs/CROSS_PLATFORM.ru.md +11 -9
  151. package/docs/CROSS_PLATFORM.zh.md +11 -9
  152. package/docs/EXECUTION-LOOP.md +196 -0
  153. package/docs/FAQ.md +2 -2
  154. package/docs/FAQ.ru.md +2 -2
  155. package/docs/FAQ.zh.md +2 -2
  156. package/docs/FEATURES.md +5 -4
  157. package/docs/FEATURES.zh.md +5 -4
  158. package/docs/MIGRATION.md +34 -26
  159. package/docs/README.ru.md +27 -8
  160. package/docs/README.zh.md +11 -10
  161. package/docs/SAFETY.md +122 -0
  162. package/docs/SAVINGS.md +29 -0
  163. package/docs/SAVINGS.ru.md +29 -0
  164. package/docs/SAVINGS.zh.md +18 -0
  165. package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
  166. package/gui-experimental.cjs +8 -8
  167. package/index.js +1 -0
  168. package/locales/en.json +68 -0
  169. package/locales/ru.json +68 -0
  170. package/locales/zh.json +68 -0
  171. package/package.json +57 -11
  172. package/scripts/audit-bundle.mjs +215 -0
  173. package/src/core/analytics.ts +2 -2
  174. package/src/core/audit.ts +17 -17
  175. package/src/core/cron-to-schtasks.ts +14 -93
  176. package/src/core/dlq-api.ts +98 -0
  177. package/src/core/dry-run.ts +51 -27
  178. package/src/core/file-watcher.ts +17 -17
  179. package/src/core/git-trigger.ts +9 -9
  180. package/src/core/glob.ts +1 -1
  181. package/src/core/local-ai.ts +2 -2
  182. package/src/core/lock.ts +104 -31
  183. package/src/core/matrix.ts +31 -31
  184. package/src/core/native-notify.ts +2 -2
  185. package/src/core/one-shot.ts +91 -13
  186. package/src/core/opencode-cli.ts +103 -0
  187. package/src/core/opencode-models.ts +315 -0
  188. package/src/core/otel.ts +4 -4
  189. package/src/core/permissions.ts +5 -5
  190. package/src/core/prometheus.ts +17 -17
  191. package/src/core/ps-wrapper.ts +68 -38
  192. package/src/core/record-history.ts +114 -76
  193. package/src/core/retention.ts +3 -3
  194. package/src/core/router/dispatch.ts +94 -0
  195. package/src/core/router/escalation.ts +129 -0
  196. package/src/core/router/planner.ts +166 -0
  197. package/src/core/router/rules.ts +109 -0
  198. package/src/core/run-panel-api.ts +262 -0
  199. package/src/core/savings.ts +1 -1
  200. package/src/core/schedule-gate.ts +17 -13
  201. package/src/core/schedule-v2.ts +138 -29
  202. package/src/core/scheduler/at-fallback.ts +298 -0
  203. package/src/core/scheduler/index.ts +3 -3
  204. package/src/core/scheduler/linux.ts +92 -19
  205. package/src/core/scheduler/logs.ts +1 -1
  206. package/src/core/scheduler/mac.ts +112 -60
  207. package/src/core/scheduler/posix.ts +35 -2
  208. package/src/core/scheduler/registry.ts +109 -26
  209. package/src/core/scheduler/run-now.ts +32 -0
  210. package/src/core/scheduler/windows.ts +295 -125
  211. package/src/core/secrets.ts +139 -39
  212. package/src/core/self-analysis.ts +61 -61
  213. package/src/core/session.ts +26 -13
  214. package/src/core/structured-log.ts +3 -3
  215. package/src/core/summary.ts +25 -25
  216. package/src/core/task-name.ts +67 -0
  217. package/src/core/telegram.ts +16 -16
  218. package/src/core/triage-chain.ts +4 -4
  219. package/src/core/triage-compare.ts +8 -8
  220. package/src/core/triage-rules.ts +4 -4
  221. package/src/core/triage-shadow.ts +7 -7
  222. package/src/core/triage-worker.ts +6 -6
  223. package/src/core/triage.ts +23 -23
  224. package/src/core/watch-paths.ts +1 -1
  225. package/src/core/wrappers/bash.ts +90 -45
  226. package/src/db/capability-repo.ts +285 -0
  227. package/src/db/git-state-repo.ts +1 -1
  228. package/src/db/history-repo.ts +44 -22
  229. package/src/db/index.ts +53 -7
  230. package/src/db/metrics-repo.ts +10 -10
  231. package/src/db/migrate.ts +13 -11
  232. package/src/db/recovery.ts +3 -3
  233. package/src/db/run-context.ts +370 -0
  234. package/src/db/run-dlq.ts +310 -0
  235. package/src/db/run-journal.ts +212 -0
  236. package/src/db/run-resume.ts +256 -0
  237. package/src/db/runs-repo.ts +504 -0
  238. package/src/db/schema.ts +357 -44
  239. package/src/db/settings-repo.ts +33 -2
  240. package/src/db/step-idempotency.ts +185 -0
  241. package/src/db/tasks-repo.ts +10 -10
  242. package/src/db/templates-repo.ts +7 -7
  243. package/src/gui.tsx +516 -1
  244. package/src/history.ts +4 -4
  245. package/src/i18n.ts +7 -7
  246. package/src/index.ts +465 -308
  247. package/src/integrations.ts +6 -6
  248. package/src/notifications.ts +76 -76
  249. package/src/profiles.ts +98 -7
  250. package/src/rpc.ts +347 -1
  251. package/src/schtasks.ts +2 -2
  252. package/src/server.ts +155 -78
  253. package/src/settings.ts +44 -44
  254. package/src/shared/jobs-view.ts +60 -60
  255. package/src/skill.ts +1 -1
  256. package/src/task-transfer.ts +58 -56
  257. package/src/templates.ts +1 -1
  258. package/src/types.ts +54 -10
  259. package/src/workspaces.ts +73 -24
  260. package/dist/core/self-analysis.test.d.ts +0 -2
  261. package/dist/core/self-analysis.test.d.ts.map +0 -1
  262. package/dist/core/self-analysis.test.js +0 -219
  263. package/dist/gui-experimental.cjs +0 -1
@@ -1,6 +1,7 @@
1
1
  # Architecture
2
2
 
3
- This document explains how `opencode-windows-scheduler` is put together: the process
3
+ This document explains how `agent-steward` (plugin id
4
+ `opencode-windows-scheduler`) is put together: the process
4
5
  model, the modules, the data model and the extension points.
5
6
 
6
7
  - [Design principles](#design-principles)
@@ -42,7 +43,7 @@ model, the modules, the data model and the extension points.
42
43
  ```
43
44
  ┌─────────────────────────────┐
44
45
  │ OpenCode (plugin host) │
45
- │ • agent tools (25) │
46
+ │ • agent tools (26) │
46
47
  │ • sidebar GUI (gui.tsx) │
47
48
  │ • RPC ↔ sidebar │
48
49
  │ • dashboard HTTP server │
@@ -118,11 +119,81 @@ is read from the database or from files under the plugin directory.
118
119
  history record and metrics into a `TaskItem`. Matrix parents get an aggregated status
119
120
  from their clones instead of their own last run.
120
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
+ Реализация (Спринт 36.5.a): `src/core/router/rules.ts` — замороженная таблица
145
+ `STATIC_ROUTE_RULES`, `routeStaticStep(taskType)` (нормализует `Run Tests` /
146
+ `run-tests` → `run_tests`), `isStaticTaskType`, `listStaticRouteRules`.
147
+ Модуль не импортирует ни БД, ни модель, ни транспорт, поэтому горячий путь
148
+ физически не может стоить токенов; неизвестный тип возвращает `undefined` и
149
+ передаётся слою 2. Покрытие — `test-router-rules.mjs` (22 проверки, включая
150
+ 1000 маршрутизаций быстрее 50 мс).
151
+
152
+ ### Слой 2 — Capability Map (0 токенов, быстро)
153
+
154
+ SQLite-таблица `task_type → model / success_rate / avg_cost / avg_time /
155
+ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 learning loop).
156
+
157
+ - `success_rate ≥ 0.85` → маршрут локально
158
+ - `success_rate ≤ 0.30` → эскалация в облако или «нужно ревью»
159
+
160
+ Это и есть learning loop: роутер учится на гейтах и становится точнее без затрат
161
+ токенов на само решение.
162
+
163
+ Реализация (Спринт 36.5.b): `src/db/capability-repo.ts`, таблица `capability_map`
164
+ (`SCHEMA_VERSION = 6`). `recordCapabilityOutcome` обновляет счётчики, считает
165
+ `success_rate` и скользящие средние стоимости/времени, хранит `last_10_runs`
166
+ (JSON, новые справа). `decideCapabilityRoute` решает по правилам:
167
+ меньше `MIN_RUNS_FOR_DECISION = 3` исходов → `explore` (решает слой 3),
168
+ `≥ 0.85` → `local`, `≤ 0.30` → `cloud`, между порогами → `review`. Пороги
169
+ передаются параметром, поэтому политика меняется без миграции данных.
170
+ Покрытие — `test-capability-map.mjs`.
171
+
172
+ ### Слой 3 — локальная модель (только декомпозиция и неоднозначность)
173
+
174
+ Модель не маршрутизирует каждый шаг. Она только:
175
+ 1. Разбивает миссию на шаги с типами (планирование);
176
+ 2. Разрешает неоднозначность (Explore-режим, когда в Capability Map нет данных).
177
+
178
+ После этого каждый шаг проходит через Слой 1 и Слой 2.
179
+
180
+ **Реализация (Спринт 36.5.c):** `src/core/router/planner.ts`. `planMission(mission, { decomposer, maxSteps })` вызывает декомпозер — локальную модель — один раз на миссию и нормализует типы через `normalizeTaskType`; без декомпозера работает `decomposeHeuristically` по ключевым словам, без сети и модели. `planMissionSync` — вариант для синхронных мест. Шаг плана содержит только `stepName` и `taskType`, маршрут по-прежнему выбирают слои 1–2; типы вне статических правил собираются в `ambiguousTaskTypes` для `decideCapabilityRoute`. Пустая миссия, пустой или битый план модели — ошибка, а не молчаливый план. Покрытие — `test-planner.mjs`.
181
+
182
+ **Реализация (Спринт 36.5.d):** `escalateAfterGate(current, gate)` в `src/core/router/escalation.ts` решает судьбу шага по одному флагу `passed` и таблице переходов `local → cloud → review → blocked`. Модуль не импортирует ни БД, ни модель, ни сеть: это чистые функции (`nextGateTarget`, `isEscalationExhausted`, `escalationChain`), поэтому 1000 решений стоят доли миллисекунды. Переход в `blocked` означает, что автоматических уровней больше нет и нужен человек.
183
+
184
+ Слои 1–2 собираются в `routeStep(taskType, thresholds)` из `src/core/router/dispatch.ts`: сначала статическое правило (0 токенов), затем Capability Map. Для `review` и `explore` маршрут возвращается без транспорта и исполнителя — исполнять пока нечего. Модуль не импортирует `planner`, поэтому известный тип задачи не может случайно дойти до модели; это закреплено тестом `test-router-dispatch.mjs`, который также проверяет, что статика не оставляет записей в `capability_map` и работает ещё до инициализации БД.
185
+
186
+ ### Эскалация
187
+
188
+ При провале гейта роутер эскалирует в облако **по правилу**, без участия модели.
189
+
190
+ ---
191
+
121
192
  ## Modules
122
193
 
123
194
  | Path | Role |
124
195
  | --- | --- |
125
- | `src/index.ts` | Plugin lifecycle, 25 agent tools, RPC handlers, task CRUD, view assembly |
196
+ | `src/index.ts` | Plugin lifecycle, 26 agent tools, RPC handlers, task CRUD, view assembly |
126
197
  | `src/rpc.ts` | JSON-schema contracts for every RPC method |
127
198
  | `src/gui.tsx` | OpenCode sidebar panel (SolidJS, built to `gui-experimental.cjs`) |
128
199
  | `src/server.ts` | Local web dashboard HTTP server and HTML rendering |
@@ -154,7 +225,12 @@ from their clones instead of their own last run.
154
225
  | `src/core/cron-to-schtasks.ts` | Cron → Task Scheduler translation |
155
226
  | `src/core/schedule-v2.ts` | Extended cron parser/matcher, timezone math, launch windows, poll-mode decisions |
156
227
  | `src/core/schedule-gate.ts` | Wrapper-side gate: cron re-check (poll mode), window postpone, defer-file |
157
- | `src/db/` | SQLite access: schema, migrations, repositories, recovery |
228
+ | `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, `step-idempotency.ts` replays steps by key, `run-dlq.ts` parks deterministically failed steps |
229
+ | `src/core/router/rules.ts` | Router layer 1: static rules task type → transport + executor, normalization, no imports (0 tokens) |
230
+ | `src/db/capability-repo.ts` | Router layer 2: Capability Map - gate outcomes per task type, success_rate, moving averages, last 10 runs, threshold decision |
231
+ | `src/core/router/planner.ts` | Router layer 3: mission decomposition (model once per mission) and heuristic fallback, steps carry type only, routing stays in layers 1-2 |
232
+ | `src/core/router/dispatch.ts` | Router assembly: `routeStep` runs layer 1 then layer 2 and returns transport/executor, never imports the planner |
233
+ | `src/core/router/escalation.ts` | Gate failure escalation `local → cloud → review → blocked` by pure transition table, no DB, no model |
158
234
  | `src/shared/jobs-view.ts` | Task view shared by the GUI and dashboard |
159
235
 
160
236
  ## Scheduling backends
@@ -284,11 +360,11 @@ Everything lives under the plugin directory:
284
360
 
285
361
  | Platform | Path |
286
362
  | --- | --- |
287
- | Windows | `%APPDATA%\opencode\windows-scheduler` |
288
- | macOS/Linux | `$XDG_CONFIG_HOME/opencode/windows-scheduler` (default `~/.config/...`) |
363
+ | Windows | `%APPDATA%\opencode\agent-steward` (legacy `windows-scheduler` переносится автоматически) |
364
+ | macOS/Linux | `$XDG_CONFIG_HOME/opencode/agent-steward` (default `~/.config/...`) |
289
365
 
290
366
  ```
291
- scheduler.db SQLite database (WAL)
367
+ scheduler.db SQLite database (WAL; схема версионируется через PRAGMA user_version)
292
368
  logs/ per-task run logs
293
369
  locks/ lock files
294
370
  wrappers/ generated .cmd / .sh wrappers
@@ -307,7 +383,213 @@ the whole plugin directory (database, logs, locks, wrappers, prompts) with
307
383
 
308
384
  Schema evolution is additive: `applySchema` runs `CREATE TABLE IF NOT EXISTS` on every
309
385
  connection and adds missing columns after `PRAGMA table_info`, so upgrading the plugin
310
- never requires a manual migration.
386
+ never requires a manual migration. `SCHEMA_VERSION` (currently `6`) is stored in
387
+ `PRAGMA user_version`; incremental steps live in `MIGRATIONS`.
388
+
389
+ ### Durable run state (Sprint 36.1)
390
+
391
+ Sprint 36.1 adds `runs` and `run_steps`, the persistence layer for resumable DAG
392
+ execution:
393
+
394
+ | Table | Purpose |
395
+ | --- | --- |
396
+ | `runs` | One row per execution (`pending → running → passed/failed/cancelled`), with `task_name`, `parent_run_id`, `workspace_id`, `started_at`, `finished_at`, `metadata_json` |
397
+ | `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 |
398
+
399
+ `src/db/runs-repo.ts` owns the transitions and rejects invalid ones
400
+ (`InvalidTransitionError`). A failed step can be retried explicitly (`retryStep`),
401
+ which increments `attempt` and returns it to `running`. The tables survive process
402
+ crashes and reconnects, which is the prerequisite for resume (36.2),
403
+ idempotent steps (36.3) and the dead letter queue (36.4).
404
+
405
+ `src/db/run-journal.ts` (Sprint 36.1.b) writes every transition to disk before
406
+ and after executing the step body: `beginStepAttempt` commits `running` + `started_at`
407
+ before the body runs; `recordStepSuccess`/`recordStepFailure` commit `passed`/`failed`
408
+ (and `finished_at`/`error`/`output_json`) after it. The high-level wrappers
409
+ `runStepStatefully` / `runStepStatefullyAsync` execute `body` between those two
410
+ commits and propagate its error while still recording `failed`. `recoverInterruptedSteps`
411
+ marks any `running` steps left after a process crash as `failed` — preserving
412
+ `attempt`, so the next repeat gets `attempt + 1` and never restarts from 1.
413
+ SQLite runs in WAL mode with `synchronous = NORMAL`, so a committed transition
414
+ survives a `kill -9` (only the last in-flight commit can be lost with a power cut).
415
+
416
+ ### Resume from the middle (Sprint 36.2)
417
+
418
+ `src/db/run-resume.ts` continues a run after a crash. `run_steps.position`
419
+ (schema v3) fixes the order of a linear chain — `created_at` can be identical
420
+ for steps inserted in one transaction, so it cannot be used for ordering; on an
421
+ existing v2 database the migration backfills `position` from the insertion order.
422
+ The `(run_id, position)` index is created after migrations, not in `SCHEMA_SQL`:
423
+ on an old database the column does not exist yet, so an early `CREATE INDEX`
424
+ would fail before the `ALTER TABLE` step.
425
+ `findResumeStep` returns the first step that is not `passed`/`skipped`.
426
+ `resumeRunSync` / `resumeRun` then:
427
+
428
+ 1. recover dangling `running` steps (`recoverInterruptedSteps`), so the crash
429
+ victim is retried with `attempt + 1`;
430
+ 2. skip already passed/skipped steps without invoking their handlers;
431
+ 3. validate that every remaining step has a handler **before** any side effect;
432
+ 4. reopen a `failed` run (`reopenRun`, the only `failed → running` transition);
433
+ 5. execute the rest through the journal and finalize the run as `passed` or
434
+ `failed`.
435
+
436
+ The result reports `resumedFrom`, `resumedFromAttempt`, `executed`, `skipped`,
437
+ `failedStep` and `error`. With `stopOnError: false` the chain continues after a
438
+ failure, but the run still ends `failed`. This is covered by
439
+ `test-run-resume.mjs`, including a real `kill -9` in the middle of a four-step
440
+ chain.
441
+
442
+ The crash path is also exercised nightly by `test-chaos-dag.mjs`: a child process
443
+ runs a four-step chain, the parent sends `SIGKILL` right after the next step has
444
+ committed `running`, and the test then verifies the durable state (`passed` steps
445
+ are untouched, the victim is `running` with `attempt = 1`, later steps are
446
+ `pending`), `PRAGMA integrity_check = ok`, recovery to `failed` with
447
+ `attempt = 1`, and a resume that retries the victim with `attempt = 2` and never
448
+ re-invokes handlers of completed steps. `.github/workflows/nightly.yml` runs it
449
+ on a schedule on Windows and Ubuntu; locally it is `npm run test:chaos`.
450
+
451
+ ### Idempotent steps (Sprint 36.3)
452
+
453
+ `run_steps.idempotency_key` is unique per run: schema v4 deduplicates legacy
454
+ duplicates (keeping the first row, nulling the rest) and replaces the old
455
+ non-unique index with the partial unique index `idx_run_steps_key_unique
456
+ (run_id, idempotency_key) WHERE idempotency_key IS NOT NULL`. The index is
457
+ created in the migration, after the dedupe — the same ordering trap as
458
+ `position`.
459
+
460
+ `src/db/step-idempotency.ts` exposes `runStepOnce` / `runStepOnceAsync`:
461
+
462
+ 1. a key that belongs to another step in the same run is rejected with
463
+ `IdempotencyConflictError`;
464
+ 2. an already `passed`/`skipped` step is **replayed** from `output_json` — the
465
+ body is not called, `attempt` does not grow and no side effect repeats
466
+ (`replayed: true`, `executed: false`);
467
+ 3. a `failed` step is retried with `attempt + 1`, so a transient error does not
468
+ turn into a permanent skip;
469
+ 4. a `running` step, or a second call for the same key while the first is still
470
+ inside the body, raises `StepInFlightError` — the in-process `inFlight` set
471
+ covers parallel async calls, the unique index covers the database;
472
+ 5. a missing step is created with the key, then executed through the journal
473
+ from 36.1.b.
474
+
475
+ The same key is allowed in different runs; `test-step-idempotency.mjs` covers
476
+ first execution, replay from cache (including after reconnect), conflicts,
477
+ retry and parallel deduplication.
478
+
479
+ ### Dead letter queue (Sprint 36.4)
480
+
481
+ A step that fails on every attempt is not transient: resuming the run again just
482
+ burns another attempt and hides the real problem. Schema v5 adds `run_dlq`, the
483
+ durable queue of deterministically failed steps:
484
+
485
+ | Column | Purpose |
486
+ | --- | --- |
487
+ | `run_id`, `step_name` | Which step dead-lettered; cascade-deleted with the run |
488
+ | `status` | `open → retried` or `open → discarded` |
489
+ | `reason` | `attempts-exhausted` (automatic scan) or `manual` |
490
+ | `error`, `attempts` | Snapshot of the failure at the moment of enqueue |
491
+ | `resolved_at`, `resolution` | When and how the entry was closed (`manual-retry`, `discarded`) |
492
+
493
+ `src/db/run-dlq.ts` provides:
494
+
495
+ 1. `scanDeadLetters({ runId?, minAttempts = 3, limit })` selects steps with
496
+ `status = failed` and `attempt >= threshold` and enqueues only new ones. The
497
+ partial unique index `idx_run_dlq_open_unique (run_id, step_name) WHERE
498
+ status = 'open'` makes enqueue idempotent, so a repeated scan does not create
499
+ duplicates.
500
+ 2. `retryDeadLetter(id)` is the manual retry: it reopens the failed run, calls
501
+ `retryStep` (attempt + 1, step back to `running`) and closes the entry as
502
+ `retried` with `resolution = manual-retry`. Closed entries cannot be retried
503
+ or discarded twice.
504
+ 3. `discardDeadLetter(id, resolution = "discarded")` closes the entry without
505
+ touching the step — the run stays failed.
506
+ 4. `listDeadLetters` / `countDeadLetters` filter `open` or `all` for dashboards
507
+ (36.6) and metrics.
508
+
509
+ `retryDeadLetter` calls `reopenRun` and `retryStep`, which each open their own
510
+ transaction. `withTransaction` therefore nests through `SAVEPOINT` when a
511
+ transaction is already active, keeping the whole retry atomic instead of failing
512
+ with `cannot start a transaction within a transaction`. `test-run-dlq.mjs`
513
+ covers the threshold, idempotent scans, manual retry, discard, cascade delete,
514
+ reconnect and the v4 → v5 migration.
515
+
516
+ ### Dead letter queue in the GUI (Sprint 36.6)
517
+
518
+ The side panel exposes the queue through `src/core/dlq-api.ts`, a thin facade
519
+ that normalises the filter (`open` by default, plus `all`/`retried`/`discarded`)
520
+ and clamps the limit, then calls `listDeadLetters` / `retryDeadLetter` /
521
+ `discardDeadLetter`. RPC methods `list_dlq`, `retry_dlq` and `discard_dlq` are
522
+ declared in `src/rpc.ts` and handled in `src/index.ts`; the two mutations are
523
+ audited as `dlq.retry` and `dlq.discard`. `retry_dlq` only prepares the step
524
+ (reopen + `attempt + 1` + entry closed) — the handler itself is executed by a
525
+ later resume, so the panel never claims a step has already run. The UI section
526
+ shows the open count, status filter, creation time, run/step, reason, attempts,
527
+ error and status-aware actions; retry and discard ask for confirmation and
528
+ refresh the list through the same facade. `test-dlq-gui.mjs` checks the RPC/GUI
529
+ wiring, locale parity and the facade behaviour on a temporary SQLite database.
530
+
531
+ ### Pause with context injection (Sprint 36.7)
532
+
533
+ The durable run model gains a new table `run_injections` (`SCHEMA_VERSION = 7`, migration step 7)
534
+ with columns `id`, `run_id` (cascade delete from `runs`), `step_name`, `kind` (`comment` /
535
+ `file` / `artifact`), `content`, `author`, `metadata_json`, `created_at`, `consumed_at`,
536
+ `consumed_by_step`, `consumed_attempt`, plus indexes `idx_run_injections_run(run_id, created_at)`
537
+ and a partial index `idx_run_injections_pending(run_id, step_name) WHERE consumed_at IS NULL`.
538
+
539
+ A run can be paused between steps: `RunStatus` gains `paused` with transitions
540
+ `pending → running/paused/cancelled`, `running → paused/passed/failed/cancelled`,
541
+ `paused → running/passed/cancelled`. `pauseRunRecord(id)` sets `paused` without filling
542
+ `finished_at`. `pauseRun(runId, input)` in `src/db/run-context.ts` requires an existing,
543
+ non-terminal run with no step currently `running`, addresses the first unfinished step (or an
544
+ explicit `stepName`), rejects completed/missing targets, and stores one injection per provided
545
+ payload (`comment`, `file` with path/content/title, `artifact` with name/content). Secrets are
546
+ masked on write: `redactSecretsInText` covers text/comment/file content, and a recursive
547
+ `redactValue` with `SENSITIVE_KEY_RE` masks whole values of sensitive JSON keys
548
+ (`*TOKEN*`, `*SECRET*`, `*PASSWORD*`, `*API_KEY*`, `*CREDENTIAL*`, `*AUTH*`, ...) to `***`.
549
+ A single injection is capped at `MAX_INJECTION_CONTENT` (100 kB).
550
+
551
+ `listRunInjections(runId, { pendingOnly })` returns history ordered by creation time, exposing
552
+ author, masked content and consumption state. `pendingInjectionsForStep(runId, stepName)` returns
553
+ the not-yet-consumed injections addressed to a step.
554
+
555
+ `StepHandler` now receives `(step, context: StepContext)` where `StepContext.injections` holds
556
+ the injections for that step. `resumeRunSync` / `resumeRun` pass them before executing each step,
557
+ and after a successful step call `consumeInjections(ids, stepName, attempt)` to mark the
558
+ injections consumed exactly once (retry keeps them for the next attempt). `finalize` calls
559
+ `consumeOrphanInjections` so injections addressed to already-completed steps do not look pending
560
+ in the history, and supports `paused → passed` when no steps remain. `ResumeResult` gains
561
+ `injected: string[]`. `test-run-context.mjs` covers schema v7, pause-before-start / pause-between
562
+ steps / explicit targeting, comment + file + artifact with secret masking and author visibility,
563
+ single-consumption on resume, repeated resume without re-delivery, pause without context,
564
+ validation errors (missing/completed/running target, terminal run, no unfinished steps, empty
565
+ path, artifact without content, oversized content), async resume and cascade delete on run
566
+ removal.
567
+
568
+ ### Pause and resume in the GUI (Sprint 36.8)
569
+
570
+ `src/core/run-panel-api.ts` is the GUI-facing facade over durable runs. `listRunPanel({ filter, limit })`
571
+ accepts `active` (pending/running/paused/failed), `all`, or a concrete run status, normalizes the
572
+ limit to 1..100 and returns compact `RunPanelRun` entries: status, progress (`doneSteps` /
573
+ `totalSteps`), first unfinished `currentStep` with a stable `anchor`, up to 20 context injections
574
+ (content preview capped at 500 characters, author, timestamps, consumer) and the count of pending
575
+ injections. `active` is also reported for the panel badge.
576
+
577
+ `pauseRunPanel(runId, { comment, author, stepName? })` delegates to `pauseRun`, returning
578
+ `{ success: false, error }` instead of throwing, so the GUI can show the database error next to the
579
+ button. `resumeRunPanel(runId)` only prepares the run: it accepts `paused` or `failed`, calls
580
+ `reopenRun` (status becomes `running`), and returns the next unfinished step from `findResumeStep`.
581
+ Actual step execution remains with `resumeRun` / the DAG executor; the facade never pretends that a
582
+ step ran.
583
+
584
+ RPC methods `list_durable_runs`, `pause_durable_run` and `resume_durable_run` are declared in
585
+ `src/rpc.ts`, implemented in `src/index.ts`, and audited as `run.pause` / `run.resume` (target is the
586
+ run id). The GUI section «⏯️ Запуски DAG» in `src/gui.tsx` renders the run list with status filter,
587
+ progress, current-step anchor link, a comment field, pause/resume buttons with confirmation, a
588
+ blocked pause plus warning while the current step is `running`, and the context history with author
589
+ and consumer. Locales ru/en/zh stay in sync. `test-pause-gui.mjs` verifies the RPC contract, locale
590
+ parity, current-step/progress output, pause with masked comment and author, active/paused filters,
591
+ resume preparation, rejection of a repeated resume, end-to-end comment delivery through
592
+ `resumeRun`, running-step rejection, failed-run resume and list limits.
311
593
 
312
594
  ## Interfaces
313
595
 
@@ -315,7 +597,7 @@ never requires a manual migration.
315
597
  | --- | --- | --- |
316
598
  | Agent tools | AI agent | 26 tools registered via `ctx.tool.transform` |
317
599
  | Agent skill | AI agent | `skills/scheduled-job-best-practices` |
318
- | RPC | Sidebar GUI | `src/rpc.ts` contracts, 44 methods |
600
+ | RPC | Sidebar GUI | `src/rpc.ts` contracts, 47 methods |
319
601
  | Sidebar GUI | Human | `gui-experimental.cjs` |
320
602
  | Web dashboard | Human | `startDashboardServer` (localhost, random/fixed port) |
321
603
 
@@ -455,3 +737,47 @@ after the agent with the user's privileges and are not filtered by tool policy.
455
737
  | New agent tool | Add a zod schema + execute function, register in `ctx.tool.transform`, add an RPC contract |
456
738
  | New dashboard panel | Extend `server.ts` routes and the HTML template |
457
739
  | New matrix policy | Extend `MatrixConfig` in `task-transfer.ts` and the logic in `core/matrix.ts` |
740
+
741
+ ## Mission runtime и гибридные входы (план 38–40)
742
+
743
+ > Статус: спека. Что уже в коде, а что нет — [ROADMAP.md](../ROADMAP.md) §1.
744
+
745
+ Система гибридная: ядро (**mission runtime**) не знает про планировщик ОС.
746
+ Планировщик — адаптер входа, регистрация опциональна.
747
+
748
+ ### Классы входа
749
+
750
+ | Класс | Вход | Регистрация в ОС | Реализация |
751
+ |---|---|---|---|
752
+ | Ad-hoc | `run_mission` / CLI / GUI / RPC | нет | план 38 |
753
+ | Внутренний | chain / DAG / retry / escalation | нет | сейчас через `backend.runTask` + force-маркер; план 40 — напрямую в runtime |
754
+ | Registered | cron / once / file / git / mcp-event / webhook | да (cron/once) | есть: `core/scheduler/*`, `file-watcher`, `git-trigger`, `integrations` |
755
+
756
+ ### Объекты
757
+
758
+ | Объект | Содержимое | Таблица |
759
+ |---|---|---|
760
+ | Миссия | цель + scope + gate-спека + safety + бюджет | `missions` (план 38, опциональный шаблон) |
761
+ | Задача | миссия-шаблон + триггер | `tasks` (есть) |
762
+ | Запуск | durable-исполнение: шаги, попытки, вердикты | `runs` / `run_steps` (есть, SCHEMA_VERSION 7) |
763
+ | Исход гейта | вердикт + provenance + экономика | `gate_outcomes` (план 40) |
764
+
765
+ ### Путь исполнения (целевой)
766
+
767
+ ```
768
+ вход → intake (gate + safety → политика + бюджет) → createRun(trigger_kind)
769
+ → planner → [route → context compile → execute → GATE]* → artifact → report
770
+ ```
771
+
772
+ Существующий путь планировщика (`wrapper → opencode run → record-history → history`)
773
+ сохраняется для обратной совместимости; в 40 он подключается к runtime и создаёт
774
+ durable-run, а исходы гейта пишутся в ledger.
775
+
776
+ ### Что переиспользуется
777
+
778
+ - Durable state: `db/runs-repo`, `run-journal`, `run-resume`, `step-idempotency`, `run-context`.
779
+ - Роутинг: `core/router/rules|dispatch|escalation|planner`, `db/capability-repo`.
780
+ - Права и секреты: `core/permissions`, `core/secrets` (scoped-инъекция).
781
+ - Телеметрия: `core/otel`, `core/prometheus`, `core/structured-log`.
782
+ - Пауза с инъекциями: `db/run-context` + `core/run-panel-api` → основа approval-гейта.
783
+ - Retrieval для scaffolding: подход bag-of-words из `notification_embeddings`.
@@ -34,7 +34,7 @@
34
34
  **Конфигурация по линиям.** Ключ выбирает загрузчик OpenCode, а не плагин: сам
35
35
  пакет не читает ни `plugin`, ни `plugins`, поэтому чужое поле не может уронить
36
36
  его код. V1 подключается ключом `plugin` в `opencode.jsonc`, V2 — ключом
37
- `plugins` или командой `opencode plugin add opencode-windows-scheduler`. Оба
37
+ `plugins` или командой `opencode plugin add agent-steward`. Оба
38
38
  ключа одновременно не нужны. Примеры для обеих линий — в README (en/ru/zh).
39
39
 
40
40
  **TUI в V1.** `src/tui-v1.tsx` реализует `TuiPluginModule` и живёт на тех же
@@ -206,25 +206,29 @@ Zod-объекта. `@opencode-ai/plugin@1.19.5` зависит от `zod@4.1.8`
206
206
  ## Инварианты состояния
207
207
 
208
208
  Эти значения не меняются ни при переходе на dual-support в `1.5.6`, ни при
209
- rename в `agent-steward` (`2.0.0`): иначе пользователи теряют историю, задачи,
209
+ rename в `agent-steward` (Д7): иначе пользователи теряют историю, задачи,
210
210
  настройки и уже созданные записи в планировщике ОС. Значения проверяются
211
211
  `test-docs` по исходникам.
212
212
 
213
213
  | Что | Значение | Где |
214
214
  |---|---|---|
215
215
  | `plugin id` | `opencode-windows-scheduler` | `src/index.ts`, `Plugin.define({ id })` |
216
- | Каталог состояния (default) | Windows: `%APPDATA%\opencode\windows-scheduler`; macOS/Linux: `$XDG_CONFIG_HOME/opencode/windows-scheduler` или `~/.config/opencode/windows-scheduler` | `src/profiles.ts` |
216
+ | Каталог состояния (default) | Windows: `%APPDATA%\opencode\agent-steward`; macOS/Linux: `$XDG_CONFIG_HOME/opencode/agent-steward` или `~/.config/opencode/agent-steward` | `src/profiles.ts` |
217
217
  | Каталог нестандартного профиля | `<каталог состояния>/profiles/<profile>` | `src/profiles.ts` |
218
218
  | SQLite | `<PLUGIN_DIR>/scheduler.db`; `OPENCODE_SCHEDULER_DB` — только для тестов | `src/db/index.ts` |
219
219
  | Логи, обёртки, locks | `<PLUGIN_DIR>/logs`, `<PLUGIN_DIR>/wrappers`, `<PLUGIN_DIR>/locks` | `src/types.ts` |
220
220
  | Промпты и env-файлы задач | `<PLUGIN_DIR>/prompts`, `<PLUGIN_DIR>/env` | `src/index.ts` |
221
221
  | Секреты | `<PLUGIN_DIR>/secrets.json`, `<PLUGIN_DIR>/secrets.key` | `src/core/secrets.ts` |
222
- | Префикс задач Windows | `\OpenCode\windows-scheduler\`; профиль: `\OpenCode\windows-scheduler-<profile>\` | `src/core/scheduler/windows.ts` |
222
+ | Префикс задач Windows | `\OpenCode\agent-steward\` (новый, профиль: `\OpenCode\agent-steward-<profile>\`); legacy `\OpenCode\windows-scheduler\` по-прежнему распознаётся (алиасинг) | `src/core/scheduler/windows.ts` |
223
223
  | Блок crontab | `# >>> opencode-scheduler:<folder> >>>` … `# <<< opencode-scheduler:<folder> <<<` (legacy-блок без суффикса читается) | `src/core/scheduler/linux.ts` |
224
224
  | launchd label | `com.opencode.scheduler.<name>` | `src/core/scheduler/mac.ts` |
225
225
 
226
- Rename `2.0.0` меняет только npm-имя пакета (`agent-steward@0.0.2`): `plugin id`,
227
- пути, имена файлов БД/логов и префиксы задач остаются прежними (П7.2).
226
+ Rename (Д7) меняет npm-имя пакета (`agent-steward@0.0.2`), каталог данных
227
+ (`opencode/agent-steward`; legacy `opencode/windows-scheduler` копируется при первом
228
+ запуске) и папку задач Windows (`\OpenCode\agent-steward\`; legacy-папка читается и
229
+ удаляется по требованию). `plugin id`, имена файлов SQLite/логов и
230
+ crontab/launchd-маркеры остаются прежними (П7.2); ключи TUI-хранилища вида
231
+ `opencode-windows-scheduler.*` тоже не меняются.
228
232
 
229
233
  ## Связанные документы
230
234