agent-steward 0.0.3 → 0.0.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 (287) hide show
  1. package/CHANGELOG.md +154 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +54 -9
  4. package/ROADMAP-STRATEGY.md +23 -20
  5. package/ROADMAP.md +140 -143
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +351 -0
  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 +18 -1
  14. package/dist/core/execution.d.ts +203 -0
  15. package/dist/core/execution.d.ts.map +1 -0
  16. package/dist/core/execution.js +309 -0
  17. package/dist/core/gate-integrity.d.ts +35 -0
  18. package/dist/core/gate-integrity.d.ts.map +1 -0
  19. package/dist/core/gate-integrity.js +132 -0
  20. package/dist/core/git-trigger.d.ts.map +1 -1
  21. package/dist/core/git-trigger.js +14 -2
  22. package/dist/core/guard-run.d.ts +4 -0
  23. package/dist/core/guard-run.d.ts.map +1 -0
  24. package/dist/core/guard-run.js +101 -0
  25. package/dist/core/guard.d.ts +52 -0
  26. package/dist/core/guard.d.ts.map +1 -0
  27. package/dist/core/guard.js +362 -0
  28. package/dist/core/lock.d.ts +61 -4
  29. package/dist/core/lock.d.ts.map +1 -1
  30. package/dist/core/lock.js +213 -26
  31. package/dist/core/matrix.d.ts.map +1 -1
  32. package/dist/core/matrix.js +75 -15
  33. package/dist/core/mission.d.ts +83 -0
  34. package/dist/core/mission.d.ts.map +1 -0
  35. package/dist/core/mission.js +334 -0
  36. package/dist/core/one-shot.d.ts +5 -1
  37. package/dist/core/one-shot.d.ts.map +1 -1
  38. package/dist/core/one-shot.js +33 -8
  39. package/dist/core/opencode-cli.d.ts +28 -0
  40. package/dist/core/opencode-cli.d.ts.map +1 -0
  41. package/dist/core/opencode-cli.js +74 -0
  42. package/dist/core/opencode-models.d.ts +62 -0
  43. package/dist/core/opencode-models.d.ts.map +1 -0
  44. package/dist/core/opencode-models.js +277 -0
  45. package/dist/core/pipeline-apply.d.ts +38 -0
  46. package/dist/core/pipeline-apply.d.ts.map +1 -0
  47. package/dist/core/pipeline-apply.js +117 -0
  48. package/dist/core/pipeline-io.d.ts +13 -0
  49. package/dist/core/pipeline-io.d.ts.map +1 -0
  50. package/dist/core/pipeline-io.js +64 -0
  51. package/dist/core/pipeline-map.d.ts +46 -0
  52. package/dist/core/pipeline-map.d.ts.map +1 -0
  53. package/dist/core/pipeline-map.js +196 -0
  54. package/dist/core/pipeline-spec.d.ts +109 -0
  55. package/dist/core/pipeline-spec.d.ts.map +1 -0
  56. package/dist/core/pipeline-spec.js +554 -0
  57. package/dist/core/ps-wrapper.d.ts +19 -2
  58. package/dist/core/ps-wrapper.d.ts.map +1 -1
  59. package/dist/core/ps-wrapper.js +261 -63
  60. package/dist/core/record-history.d.ts +15 -0
  61. package/dist/core/record-history.d.ts.map +1 -1
  62. package/dist/core/record-history.js +183 -58
  63. package/dist/core/router/dispatch.d.ts +36 -0
  64. package/dist/core/router/dispatch.d.ts.map +1 -0
  65. package/dist/core/router/dispatch.js +59 -0
  66. package/dist/core/router/escalation.d.ts +47 -0
  67. package/dist/core/router/escalation.d.ts.map +1 -0
  68. package/dist/core/router/escalation.js +87 -0
  69. package/dist/core/router/planner.d.ts +53 -0
  70. package/dist/core/router/planner.d.ts.map +1 -0
  71. package/dist/core/router/planner.js +113 -0
  72. package/dist/core/router/rules.d.ts +46 -0
  73. package/dist/core/router/rules.d.ts.map +1 -0
  74. package/dist/core/router/rules.js +91 -0
  75. package/dist/core/run-panel-api.d.ts +94 -0
  76. package/dist/core/run-panel-api.d.ts.map +1 -0
  77. package/dist/core/run-panel-api.js +169 -0
  78. package/dist/core/schedule-gate.js +5 -1
  79. package/dist/core/schedule-v2.d.ts +34 -0
  80. package/dist/core/schedule-v2.d.ts.map +1 -1
  81. package/dist/core/schedule-v2.js +91 -5
  82. package/dist/core/scheduler/at-fallback.d.ts +55 -2
  83. package/dist/core/scheduler/at-fallback.d.ts.map +1 -1
  84. package/dist/core/scheduler/at-fallback.js +135 -5
  85. package/dist/core/scheduler/linux.d.ts +18 -2
  86. package/dist/core/scheduler/linux.d.ts.map +1 -1
  87. package/dist/core/scheduler/linux.js +63 -20
  88. package/dist/core/scheduler/mac.d.ts +44 -2
  89. package/dist/core/scheduler/mac.d.ts.map +1 -1
  90. package/dist/core/scheduler/mac.js +126 -15
  91. package/dist/core/scheduler/posix.d.ts.map +1 -1
  92. package/dist/core/scheduler/posix.js +25 -1
  93. package/dist/core/scheduler/registry.d.ts +11 -0
  94. package/dist/core/scheduler/registry.d.ts.map +1 -1
  95. package/dist/core/scheduler/registry.js +83 -21
  96. package/dist/core/scheduler/run-now.d.ts +16 -0
  97. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  98. package/dist/core/scheduler/run-now.js +28 -0
  99. package/dist/core/scheduler/windows.d.ts.map +1 -1
  100. package/dist/core/scheduler/windows.js +15 -12
  101. package/dist/core/secrets.d.ts.map +1 -1
  102. package/dist/core/secrets.js +125 -28
  103. package/dist/core/session.d.ts.map +1 -1
  104. package/dist/core/session.js +18 -11
  105. package/dist/core/structured-log.d.ts +7 -1
  106. package/dist/core/structured-log.d.ts.map +1 -1
  107. package/dist/core/task-name.d.ts +24 -0
  108. package/dist/core/task-name.d.ts.map +1 -0
  109. package/dist/core/task-name.js +40 -0
  110. package/dist/core/worktree-run.d.ts +4 -0
  111. package/dist/core/worktree-run.d.ts.map +1 -0
  112. package/dist/core/worktree-run.js +164 -0
  113. package/dist/core/worktree.d.ts +115 -0
  114. package/dist/core/worktree.d.ts.map +1 -0
  115. package/dist/core/worktree.js +462 -0
  116. package/dist/core/wrappers/bash.d.ts +17 -0
  117. package/dist/core/wrappers/bash.d.ts.map +1 -1
  118. package/dist/core/wrappers/bash.js +224 -28
  119. package/dist/db/capability-repo.d.ts +124 -0
  120. package/dist/db/capability-repo.d.ts.map +1 -0
  121. package/dist/db/capability-repo.js +267 -0
  122. package/dist/db/history-repo.d.ts +46 -5
  123. package/dist/db/history-repo.d.ts.map +1 -1
  124. package/dist/db/history-repo.js +107 -25
  125. package/dist/db/index.d.ts +4 -0
  126. package/dist/db/index.d.ts.map +1 -1
  127. package/dist/db/index.js +39 -1
  128. package/dist/db/metrics-repo.js +2 -2
  129. package/dist/db/migrate.d.ts.map +1 -1
  130. package/dist/db/migrate.js +3 -1
  131. package/dist/db/recovery.d.ts.map +1 -1
  132. package/dist/db/recovery.js +5 -4
  133. package/dist/db/run-context.d.ts +103 -0
  134. package/dist/db/run-context.d.ts.map +1 -0
  135. package/dist/db/run-context.js +224 -0
  136. package/dist/db/run-dlq.d.ts +100 -0
  137. package/dist/db/run-dlq.d.ts.map +1 -0
  138. package/dist/db/run-dlq.js +191 -0
  139. package/dist/db/run-journal.d.ts +33 -5
  140. package/dist/db/run-journal.d.ts.map +1 -1
  141. package/dist/db/run-journal.js +78 -14
  142. package/dist/db/run-resume.d.ts +10 -2
  143. package/dist/db/run-resume.d.ts.map +1 -1
  144. package/dist/db/run-resume.js +39 -13
  145. package/dist/db/runs-repo.d.ts +32 -7
  146. package/dist/db/runs-repo.d.ts.map +1 -1
  147. package/dist/db/runs-repo.js +50 -11
  148. package/dist/db/schema.d.ts +2 -2
  149. package/dist/db/schema.d.ts.map +1 -1
  150. package/dist/db/schema.js +216 -3
  151. package/dist/db/settings-repo.d.ts +11 -0
  152. package/dist/db/settings-repo.d.ts.map +1 -1
  153. package/dist/db/settings-repo.js +25 -0
  154. package/dist/db/step-idempotency.d.ts +51 -0
  155. package/dist/db/step-idempotency.d.ts.map +1 -0
  156. package/dist/db/step-idempotency.js +136 -0
  157. package/dist/history.d.ts +1 -1
  158. package/dist/history.d.ts.map +1 -1
  159. package/dist/i18n.d.ts +5 -0
  160. package/dist/i18n.d.ts.map +1 -1
  161. package/dist/i18n.js +11 -4
  162. package/dist/index.d.ts +140 -6
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +480 -18
  165. package/dist/notifications.d.ts +22 -0
  166. package/dist/notifications.d.ts.map +1 -1
  167. package/dist/notifications.js +36 -8
  168. package/dist/profiles.d.ts.map +1 -1
  169. package/dist/profiles.js +25 -4
  170. package/dist/rpc.d.ts +924 -0
  171. package/dist/rpc.d.ts.map +1 -1
  172. package/dist/rpc.js +352 -0
  173. package/dist/server.d.ts +46 -0
  174. package/dist/server.d.ts.map +1 -1
  175. package/dist/server.js +172 -53
  176. package/dist/settings.d.ts +2 -2
  177. package/dist/settings.d.ts.map +1 -1
  178. package/dist/settings.js +3 -3
  179. package/dist/shared/jobs-view.d.ts +1 -1
  180. package/dist/shared/jobs-view.d.ts.map +1 -1
  181. package/dist/shared/jobs-view.js +2 -0
  182. package/dist/task-transfer.d.ts +16 -0
  183. package/dist/task-transfer.d.ts.map +1 -1
  184. package/dist/task-transfer.js +16 -0
  185. package/dist/types.d.ts.map +1 -1
  186. package/dist/types.js +7 -0
  187. package/dist/workspaces.d.ts +25 -3
  188. package/dist/workspaces.d.ts.map +1 -1
  189. package/dist/workspaces.js +43 -8
  190. package/docs/ARCHITECTURE.md +498 -58
  191. package/docs/COMPATIBILITY.md +2 -2
  192. package/docs/CONCEPT.md +185 -91
  193. package/docs/CROSS_PLATFORM.ru.md +20 -0
  194. package/docs/CROSS_PLATFORM.zh.md +18 -0
  195. package/docs/EXECUTION-LOOP.md +211 -0
  196. package/docs/FEATURES.md +65 -4
  197. package/docs/FEATURES.zh.md +52 -4
  198. package/docs/MIGRATION.md +2 -2
  199. package/docs/PIPELINE.md +293 -0
  200. package/docs/README.ru.md +44 -5
  201. package/docs/README.zh.md +46 -6
  202. package/docs/SAFETY.md +142 -0
  203. package/docs/SAVINGS.md +29 -0
  204. package/docs/SAVINGS.ru.md +29 -0
  205. package/docs/SAVINGS.zh.md +18 -0
  206. package/gui-experimental.cjs +9 -8
  207. package/locales/en.json +84 -1
  208. package/locales/ru.json +84 -1
  209. package/locales/zh.json +84 -1
  210. package/opencode.pipeline.yaml +35 -0
  211. package/package.json +46 -2
  212. package/scripts/audit-bundle.mjs +215 -0
  213. package/scripts/test-home.mjs +83 -0
  214. package/src/cli.ts +412 -0
  215. package/src/core/dlq-api.ts +98 -0
  216. package/src/core/dry-run.ts +27 -3
  217. package/src/core/execution.ts +538 -0
  218. package/src/core/file-watcher.ts +2 -2
  219. package/src/core/gate-integrity.ts +160 -0
  220. package/src/core/git-trigger.ts +18 -5
  221. package/src/core/guard-run.ts +119 -0
  222. package/src/core/guard.ts +431 -0
  223. package/src/core/lock.ts +244 -30
  224. package/src/core/matrix.ts +95 -50
  225. package/src/core/mission.ts +485 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/one-shot.ts +36 -8
  228. package/src/core/opencode-cli.ts +103 -0
  229. package/src/core/opencode-models.ts +315 -0
  230. package/src/core/pipeline-apply.ts +158 -0
  231. package/src/core/pipeline-io.ts +79 -0
  232. package/src/core/pipeline-map.ts +264 -0
  233. package/src/core/pipeline-spec.ts +775 -0
  234. package/src/core/ps-wrapper.ts +274 -64
  235. package/src/core/record-history.ts +229 -104
  236. package/src/core/router/dispatch.ts +94 -0
  237. package/src/core/router/escalation.ts +129 -0
  238. package/src/core/router/planner.ts +166 -0
  239. package/src/core/router/rules.ts +115 -0
  240. package/src/core/run-panel-api.ts +262 -0
  241. package/src/core/schedule-gate.ts +7 -3
  242. package/src/core/schedule-v2.ts +114 -5
  243. package/src/core/scheduler/at-fallback.ts +190 -5
  244. package/src/core/scheduler/linux.ts +72 -21
  245. package/src/core/scheduler/logs.ts +2 -2
  246. package/src/core/scheduler/mac.ts +174 -14
  247. package/src/core/scheduler/posix.ts +20 -1
  248. package/src/core/scheduler/registry.ts +107 -26
  249. package/src/core/scheduler/run-now.ts +32 -0
  250. package/src/core/scheduler/windows.ts +19 -15
  251. package/src/core/secrets.ts +131 -31
  252. package/src/core/session.ts +23 -10
  253. package/src/core/structured-log.ts +22 -5
  254. package/src/core/task-name.ts +67 -0
  255. package/src/core/telegram.ts +2 -2
  256. package/src/core/triage-worker.ts +7 -7
  257. package/src/core/triage.ts +2 -2
  258. package/src/core/worktree-run.ts +199 -0
  259. package/src/core/worktree.ts +600 -0
  260. package/src/core/wrappers/bash.ts +239 -27
  261. package/src/db/capability-repo.ts +402 -0
  262. package/src/db/history-repo.ts +151 -22
  263. package/src/db/index.ts +37 -1
  264. package/src/db/metrics-repo.ts +2 -2
  265. package/src/db/migrate.ts +3 -1
  266. package/src/db/recovery.ts +5 -4
  267. package/src/db/run-context.ts +370 -0
  268. package/src/db/run-dlq.ts +310 -0
  269. package/src/db/run-journal.ts +100 -13
  270. package/src/db/run-resume.ts +65 -13
  271. package/src/db/runs-repo.ts +66 -13
  272. package/src/db/schema.ts +218 -3
  273. package/src/db/settings-repo.ts +31 -0
  274. package/src/db/step-idempotency.ts +185 -0
  275. package/src/gui.tsx +692 -13
  276. package/src/history.ts +1 -1
  277. package/src/i18n.ts +12 -4
  278. package/src/index.ts +648 -8
  279. package/src/notifications.ts +38 -8
  280. package/src/profiles.ts +26 -4
  281. package/src/rpc.ts +379 -0
  282. package/src/server.ts +206 -54
  283. package/src/settings.ts +5 -5
  284. package/src/shared/jobs-view.ts +3 -1
  285. package/src/task-transfer.ts +31 -0
  286. package/src/types.ts +9 -0
  287. package/src/workspaces.ts +58 -9
@@ -38,50 +38,197 @@ model, the modules, the data model and the extension points.
38
38
  to localhost only. Local AI triage (Ollama) is optional and connects only when explicitly enabled
39
39
  via `manage_local_ai`.
40
40
 
41
- ## Process model
41
+ ## Execution model
42
+
43
+ agent-steward is an execution engine with optional trigger registration — not a
44
+ scheduler with extras attached. Four kinds of entry lead into the same execution
45
+ path, and the OS scheduler is only one of them (CONCEPT §5, §8):
46
+
47
+ | Entry | Examples | Goes through the OS scheduler? |
48
+ | --- | --- | --- |
49
+ | ad-hoc (no OS registration) | agent tools · GUI · CLI · TUI · RPC (`run_mission`) | No |
50
+ | internal orchestration (core-driven, no OS) | chains · DAG dependents · retries · matrix continuation · escalation · resume after pause/crash | No |
51
+ | registered triggers | `cron` / `once` | Yes — registered with Task Scheduler / launchd / crontab |
52
+ | registered, in-process | `file` / `git` / `mcp-event` / webhook | No — watched inside the plugin process |
53
+
54
+ Orchestration (chains, DAG, retries, matrix, escalation) is performed by the core
55
+ and the recorder through **direct wrapper launches**, never by the OS scheduler.
56
+ The OS scheduler is responsible only for firing registered `cron`/`once` ticks.
42
57
 
43
58
  ```
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
- └────────────────────────┘
59
+ ┌─────────────────────────────────────────────────────────────────────┐
60
+ │ ENTRIES │
61
+ │ │
62
+ │ ad-hoc (no OS registration) │
63
+ │ agent tools · GUI · CLI · TUI · RPC (`run_mission`) │
64
+ │ │
65
+ │ internal orchestration (core-driven, no OS) │
66
+ │ chains · DAG dependents · retries · matrix continuation · │
67
+ │ escalation · resume after pause/crash │
68
+ │ │
69
+ │ registered triggers │
70
+ │ cron / once ────────────────▶ OS scheduler registration │
71
+ │ file / git / mcp-event / webhook ▶ in-process watchers │
72
+ └──────────────┬──────────────────────────────┬───────────────────────┘
73
+ │ │
74
+ ▼ ▼
75
+ ┌───────────────────────┐ ┌───────────────────────────────────┐
76
+ │ OS scheduler │ │ Execution core │
77
+ │ optional lane — │ │ createRun → plan → route → │
78
+ │ cron/once ticks only │ │ execute → GATE → ledger │
79
+ │ schtasks / launchd / │ │ (today: run journal, resume, DLQ, │
80
+ │ crontab (+ at; │ │ router; full mission runtime — │
81
+ │ sleep fallback when │ │ sprints 32/38) │
82
+ │ at is unavailable) │ └───────┬───────────────┬───────────┘
83
+ └──────────┬────────────┘ │ direct launch │ registered
84
+ │ fires │ (bypasses OS) │ tick
85
+ │ ▼ ▼
86
+ │ ┌──────────────────────────────────────────────────┐
87
+ └──▶│ Run wrapper (.cmd+.ps1 / .sh) — ONE execution │
88
+ │ unit for BOTH lanes: │
89
+ │ • schedule-gate (child node process): poll-mode │
90
+ │ IANA timezone, launch window, defer/force │
91
+ │ markers — BEFORE the lock │
92
+ │ • lock (.lock / .lock.d) + timeout watchdog │
93
+ │ • env/secrets + permission policy │
94
+ │ (OPENCODE_CONFIG_CONTENT) │
95
+ │ • opencode run --auto → Quality Gate → │
96
+ │ before/after hooks → one-shot cleanup (POSIX) │
97
+ └─────────────────────┬────────────────────────────┘
98
+ │ --start / --finish
99
+ ▼
100
+ ┌──────────────────────────────────────────────────┐
101
+ │ recorder process (core/record-history.js) │
102
+ │ • history / metrics → SQLite │
103
+ │ • retries ─────────────────┐ │
104
+ │ • chains / DAG dependents ─┼─▶ direct wrapper │
105
+ │ • matrix aggregation ──────┘ launches (no OS) │
106
+ │ • session rotation │
107
+ │ • one-shot cleanup (Windows) ─▶ OS scheduler │
108
+ │ • notifications: webhook / Telegram / toasts │
109
+ │ (+ async triage, optional local model) │
110
+ └──────────────────────────────────────────────────┘
71
111
  ```
72
112
 
73
- There are four kinds of processes:
74
-
75
- | Process | Lifetime | Responsibility |
113
+ | Process | Lifetime | Notes |
76
114
  | --- | --- | --- |
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.
115
+ | Plugin host | OpenCode session | agent tools and RPC; sidebar GUI and TUI; dashboard HTTP server (UI, `/api/*` with origin guard, `/api/hooks` HMAC, `/metrics`); in-process triggers (chokidar file watcher, git polling, MCP events, webhook ingestion); durable-run executor (resume / pause / DLQ); startup recovery |
116
+ | OS scheduler | system service | optional lane for `cron`/`once` ticks only: Task Scheduler (Windows), launchd (macOS), crontab + `at` (Linux; detached `sleep` fallback when `at` is unavailable) |
117
+ | Run wrapper | one per run | the single execution unit; direct launches and registered ticks execute the same wrapper, so direct runs get the same gate, lock, timeout, hooks and policy |
118
+ | schedule-gate | seconds, child of the wrapper | separate `node` process; exit 3 = "not now" (skip or postpone), fail-closed on invalid cron |
119
+ | recorder | seconds, one per run | short-lived `node` process started by the wrapper with `--start` / `--finish`; independent of the plugin host |
120
+
121
+ ### Why direct launches are safe
122
+
123
+ A common question: does `run_task_now` / chain continuation skip the safety
124
+ machinery? No. Both lanes converge on the same wrapper, so every direct run still
125
+ passes through the schedule gate, takes the lock, runs under the timeout watchdog,
126
+ loads env/secrets with the task permission policy, and records history through the
127
+ recorder. The only difference is *who starts the wrapper*: the OS scheduler or the
128
+ core.
129
+
130
+ ### Unified execution path (AC-1)
131
+
132
+ `src/core/execution.ts` is the single core path for both registered tasks and
133
+ ad-hoc missions: `createRun → plan → route → execute → GATE → ledger`. The origin
134
+ (`registered` or `ad-hoc`) changes where the context comes from, not what happens
135
+ next.
136
+
137
+ - **`RunContext` (AC-1.1)** — entry, trigger, task name, mission/prompt, cwd,
138
+ profile (model, session policy, workspace) and safety contract (permission
139
+ policy, allowed/denied tools). `createRegisteredRunContext` builds it from a
140
+ task definition; `createAdHocRunContext` from a free-form mission, defaulting
141
+ to `ad-hoc` / `new` session / `hybrid` policy. `validateRunContext` rejects
142
+ empty fields, unknown policies and tools listed as both allowed and denied.
143
+ - **Plan and dry-run trace (AC-1.3)** — `buildExecutionPlan` either uses the
144
+ explicit task type or asks the heuristic planner to decompose the mission, then
145
+ routes every step through the capability map. `describeExecutionPlan` prints the
146
+ ordered steps, their local/cloud/review targets and routing source without
147
+ creating a run row, so the same plan can be inspected before execution.
148
+ - **Executor abstraction (AC-1.2)** — `StepExecutor` advertises which routes it
149
+ supports and receives `{ step, context, plan }`. `createOpenCodeExecutor`
150
+ adapts the OpenCode CLI, but the core no longer depends on that transport:
151
+ another executor can serve the same plan.
152
+ - **Execution and GATE (AC-1.4)** — `executeExecutionPlan` creates one ledger run,
153
+ executes steps through the journal (so retries, leases and crash recovery still
154
+ apply), calls the optional GATE after each result and stops on the first
155
+ failure. Steps routed to review/explore are recorded as `skipped` with the
156
+ routing reason instead of being silently dropped.
157
+
158
+ The test `test-execution-pipeline.mjs` drives a registered task and an ad-hoc
159
+ mission through the same executor, including a rejecting GATE and a skipped
160
+ review step.
161
+
162
+ ### Ad-hoc mission runtime (AB-8)
163
+
164
+ `src/core/mission.ts` turns a one-off request into a `RunContext` without
165
+ registering anything in the OS scheduler. The same entry point is exposed by
166
+ the agent tool / RPC method `run_mission`, the CLI command `agent-steward run`
167
+ and the GUI panel «Ad-hoc миссия».
168
+
169
+ - **MissionSpec (AB-8.1)** — `prompt` is required; `cwd`, `taskName`,
170
+ `taskType`, `model`, `session` (`new` / `reuse` / `last`), `sessionId`,
171
+ `timeoutSeconds` (1–86400), `gate`, `gateTimeoutSeconds`, `policy`
172
+ (`hybrid` / `secure` / `legacy`), `allowedTools`, `deniedTools` and `dryRun`
173
+ are optional. `normalizeMissionSpec` trims the prompt, makes `cwd` absolute,
174
+ rejects unknown policies/timers/sessions and tools listed as both allowed and
175
+ denied. The default task type is `mission`, routed statically to
176
+ `local`/`direct`.
177
+ - **Safety contract** — the mission is a normal `RunContext` with its own
178
+ permission policy and tool lists. It does not bypass the GATE, budget, audit
179
+ or ledger; the wrapper receives the gate command and permission config just
180
+ like a registered task. An in-process lock keyed by the resolved workspace
181
+ rejects a second mission in the same directory
182
+ (`В workspace … уже выполняется миссия …`).
183
+ - **Planning and dry-run** — `buildExecutionPlan` + `describeExecutionPlan`
184
+ produce the same trace as registered runs. `dryRun: true` returns the plan
185
+ with `status: "planned"` and does not create a ledger row.
186
+ - **Execution (AB-8.2/8.3)** — without an injected executor the mission writes
187
+ the prompt file, log, lock and wrapper (`writeWrapperCmd` on Windows,
188
+ `writeBashWrapper` on POSIX), spawns the wrapper with a hard timeout, and
189
+ feeds its output into `executeExecutionPlan`; the run is stored with
190
+ `metadata.adHoc = true` and tasks are never created in Windows Task Scheduler,
191
+ launchd or crontab. An injected `StepExecutor` is used by tests and
192
+ alternative transports.
193
+ - **Results** — `MissionResult` reports `success`, `dryRun`, `runId`, `status`
194
+ (`planned` / `passed` / `failed`), `steps`, `error`, `logFile` and the
195
+ human-readable plan description. `run_mission` returns the same data minus
196
+ raw step output.
197
+
198
+ The test `test-mission-run.mjs` covers dry-run (no ledger row), a successful
199
+ ad-hoc run, executor failure, the workspace lock, input validation and a static
200
+ check that the mission path never imports the OS scheduler.
201
+
202
+ ### Data: one SQLite per profile
203
+
204
+ Each profile has its own plugin directory, its own SQLite database, its own OS-task
205
+ namespace and its own dashboard port. `default` keeps 3782 (fallback 4782); a named
206
+ profile gets the first free port from 3783 upward when it is created, recorded in its
207
+ `profile.json`, and never one already reserved by `default` or another profile. Every
208
+ dashboard response carries `x-plugin-profile`, so a second profile neither reuses
209
+ another profile's server nor treats it as a zombie.
210
+
211
+ `SCHEMA_VERSION` is currently **10**; migrations are additive and idempotent,
212
+ applied through `PRAGMA user_version` on open.
213
+
214
+ | Tables | Purpose |
215
+ | --- | --- |
216
+ | `tasks`, `workspaces`, `templates`, `settings` | definitions and configuration |
217
+ | `history`, `metrics` | run outcomes, duration / tokens / cost, analytics; v8 adds `owner_pid` / `owner_host` / `owner_started_at` so recovery can keep live runs |
218
+ | `audit_log` | mutation journal (who / what / when / which interface) |
219
+ | `git_state` | git-trigger heads and polling state |
220
+ | `notification_dedup`, `notification_embeddings` | rule-based and embedding dedup; tokenizer emits overlapping CJK bigrams so CJK messages get non-zero vectors |
221
+ | `runs`, `run_steps`, `run_dlq`, `run_injections` | durable runs: state machine, step journal, dead-letter queue, pause-time context injections; v9 adds `owner_id` / `lease_until` to `run_steps` |
222
+ | `capability_map` | router layer 2: task type → model / success rate / costs / last runs; v10 adds `first_pass_count` |
223
+
224
+ ### Known limitations (execution)
225
+
226
+ - Startup recovery (`recoverInterrupted*`) marks unfinished rows as `error`; it
227
+ does not yet check whether the wrapper process is still alive, so a plugin
228
+ restart during a live run finalizes that run early (tracked: Trust hotfix).
229
+ - Durable steps currently execute through the same wrapper machinery; the
230
+ agent-executor abstraction (run missions without an OpenCode-specific
231
+ transport) is Stage 2 of the strategy (sprints 32/38).
85
232
 
86
233
  ## Data flow
87
234
 
@@ -105,9 +252,13 @@ is read from the database or from files under the plugin directory.
105
252
  3. The wrapper acquires the lock (`locks/<task>.lock`), writes the log
106
253
  (`logs/<task>.log`), loads workspace env from `<PLUGIN_DIR>/env/<sanitized>.env`
107
254
  (Windows `-EnvFile`, POSIX `set -a; . "$ENV_FILE"; set +a`) before starting
108
- `opencode run` with the prompt file. Output is streamed to the log.
255
+ `opencode run` with the prompt file. The prompt is passed after `--`, so a
256
+ prompt starting with `-` is never parsed as an option. Output is streamed to the log.
109
257
  4. When the process ends, the wrapper enforces the timeout result, runs the Quality
110
- Gate and the post-flight hook.
258
+ Gate and the post-flight hook. On Windows the watchdog snapshots the process tree
259
+ via CIM and falls back to WMI, then to `tasklist`/`Get-Process`; when no tree data
260
+ is available at all it fails closed and kills the root process tree with
261
+ `taskkill /F /T`.
111
262
  5. The wrapper calls `node dist/core/record-history.js --finish ...` with status,
112
263
  duration, tokens, cost, model and hook results.
113
264
  6. The recorder writes `history` and updates `metrics`, then evaluates retries, task
@@ -141,24 +292,62 @@ cloud model — without involving a model for known step types.
141
292
  Агент хочет прочитать файл → роутер смотрит в таблицу → видит `direct + local` →
142
293
  выполняет напрямую, без MCP, без модели.
143
294
 
295
+ Реализация (Спринт 36.5.a): `src/core/router/rules.ts` — замороженная таблица
296
+ `STATIC_ROUTE_RULES`, `routeStaticStep(taskType)` (нормализует `Run Tests` /
297
+ `run-tests` → `run_tests`), `isStaticTaskType`, `listStaticRouteRules`.
298
+ Модуль не импортирует ни БД, ни модель, ни транспорт, поэтому горячий путь
299
+ физически не может стоить токенов; неизвестный тип возвращает `undefined` и
300
+ передаётся слою 2. Покрытие — `test-router-rules.mjs` (22 проверки, включая
301
+ 1000 маршрутизаций быстрее 50 мс).
302
+
144
303
  ### Слой 2 — Capability Map (0 токенов, быстро)
145
304
 
146
- SQLite-таблица `task_type → model / success_rate / avg_cost / avg_time /
147
- last_10_runs`. Обучается на исходах гейта (CONCEPT §9 learning loop).
305
+ SQLite-таблица `task_type → model / success_rate / first_pass_rate /
306
+ avg_cost / avg_time / last_10_runs`. Обучается на исходах гейта
307
+ (CONCEPT §9 learning loop).
308
+
309
+ - `effective_success_rate ≥ 0.85` → маршрут локально
310
+ - `effective_success_rate ≤ 0.30` → эскалация в облако или «нужно ревью»
148
311
 
149
- - `success_rate ≥ 0.85` → маршрут локально
150
- - `success_rate ≤ 0.30` → эскалация в облако или «нужно ревью»
312
+ `effective_success_rate = 0.7 × decayed_success_rate + 0.3 × first_pass_rate`.
313
+ `decayed_success_rate` считается по `last_10_runs` с half-life 8 исходов
314
+ (свежий исход весит 1, каждый предыдущий — вдвое меньше на каждые 8 шагов),
315
+ поэтому недавние провалы быстро перевешивают старые успехи. `first_pass_rate`
316
+ — доля успехов, достигнутых с первой попытки (`attempts = 1`); явный флаг
317
+ `firstPass` позволяет переопределить это для конкретного исхода.
151
318
 
152
319
  Это и есть learning loop: роутер учится на гейтах и становится точнее без затрат
153
320
  токенов на само решение.
154
321
 
322
+ Реализация (Спринт 36.5.b, B13): `src/db/capability-repo.ts`, таблица
323
+ `capability_map` (`SCHEMA_VERSION = 10`). `recordCapabilityOutcome` обновляет
324
+ счётчики (`runs_total`, `runs_passed`, `first_pass_count`), кумулятивный
325
+ `success_rate` и скользящие средние стоимости/времени, хранит `last_10_runs`
326
+ (JSON, новые справа). `decideCapabilityRoute` решает по правилам:
327
+ меньше `MIN_RUNS_FOR_DECISION = 3` исходов → `explore` (решает слой 3),
328
+ `effective_success_rate ≥ 0.85` → `local`, `≤ 0.30` → `cloud`, между порогами →
329
+ `review`. Пороги передаются параметром, поэтому политика меняется без миграции
330
+ данных. При миграции v9 → v10 legacy-записи получают
331
+ `first_pass_count = runs_passed` (старые успехи считаются успехами с первой
332
+ попытки). Покрытие — `test-capability-map.mjs`.
333
+
155
334
  ### Слой 3 — локальная модель (только декомпозиция и неоднозначность)
156
335
 
157
336
  Модель не маршрутизирует каждый шаг. Она только:
158
337
  1. Разбивает миссию на шаги с типами (планирование);
159
338
  2. Разрешает неоднозначность (Explore-режим, когда в Capability Map нет данных).
160
339
 
161
- После этого каждый шаг проходит через Слой 1 и Слой 2.
340
+ После этого каждый шаг проходит через Слой 1 и Слой 2. Слой 3 — **декомпозиция
341
+ миссии**, а не маршрутизация шага: он решает, *что* делать, но никогда не
342
+ выбирает, *где* исполнять. `RouteSource` в `src/core/router/dispatch.ts:15`
343
+ принимает только `static` и `capability` — значения `model`/`planner` в нём
344
+ нет, и `routeStep` не импортирует `planner`.
345
+
346
+ **Реализация (Спринт 36.5.c):** `src/core/router/planner.ts`. `planMission(mission, { decomposer, maxSteps })` вызывает декомпозер — локальную модель — один раз на миссию и нормализует типы через `normalizeTaskType`; без декомпозера работает `decomposeHeuristically` по ключевым словам, без сети и модели. `planMissionSync` — вариант для синхронных мест. Шаг плана содержит только `stepName` и `taskType`, маршрут по-прежнему выбирают слои 1–2; типы вне статических правил собираются в `ambiguousTaskTypes` для `decideCapabilityRoute`. Пустая миссия, пустой или битый план модели — ошибка, а не молчаливый план. Покрытие — `test-planner.mjs`.
347
+
348
+ **Реализация (Спринт 36.5.d):** `escalateAfterGate(current, gate)` в `src/core/router/escalation.ts` решает судьбу шага по одному флагу `passed` и таблице переходов `local → cloud → review → blocked`. Модуль не импортирует ни БД, ни модель, ни сеть: это чистые функции (`nextGateTarget`, `isEscalationExhausted`, `escalationChain`), поэтому 1000 решений стоят доли миллисекунды. Переход в `blocked` означает, что автоматических уровней больше нет и нужен человек.
349
+
350
+ Слои 1–2 собираются в `routeStep(taskType, thresholds)` из `src/core/router/dispatch.ts`: сначала статическое правило (0 токенов), затем Capability Map. Для `review` и `explore` маршрут возвращается без транспорта и исполнителя — исполнять пока нечего. Модуль не импортирует `planner`, поэтому известный тип задачи не может случайно дойти до модели; это закреплено тестом `test-router-dispatch.mjs`, который также проверяет, что статика не оставляет записей в `capability_map` и работает ещё до инициализации БД.
162
351
 
163
352
  ### Эскалация
164
353
 
@@ -170,7 +359,7 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
170
359
 
171
360
  | Path | Role |
172
361
  | --- | --- |
173
- | `src/index.ts` | Plugin lifecycle, 26 agent tools, RPC handlers, task CRUD, view assembly |
362
+ | `src/index.ts` | Plugin lifecycle, 29 agent tools, RPC handlers, task CRUD, view assembly |
174
363
  | `src/rpc.ts` | JSON-schema contracts for every RPC method |
175
364
  | `src/gui.tsx` | OpenCode sidebar panel (SolidJS, built to `gui-experimental.cjs`) |
176
365
  | `src/server.ts` | Local web dashboard HTTP server and HTML rendering |
@@ -180,7 +369,7 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
180
369
  | `src/workspaces.ts` | Workspace registry and path validation; env pairs and `.env` file resolution with secret masking |
181
370
  | `src/templates.ts` | Reusable task templates |
182
371
  | `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` |
372
+ | `src/i18n.ts` | Interface locale mode (`auto` default, follows OpenCode; `ru`/`en`/`zh` explicit), BCP 47 mapping, JSON catalogs in `locales/`, ICU subset (`{param}`, `plural`) via built-in `Intl`, fallback catalog `ru` |
184
373
  | `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
374
  | `src/core/telegram.ts` | Telegram Bot API `sendMessage`: parse-mode escaping, dashboard link, token validation and masking |
186
375
  | `src/core/native-notify.ts` | Native OS notifications: Windows Toast (PowerShell/WinRT), macOS `osascript`, Linux `notify-send`; no external dependency |
@@ -202,7 +391,12 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
202
391
  | `src/core/cron-to-schtasks.ts` | Cron → Task Scheduler translation |
203
392
  | `src/core/schedule-v2.ts` | Extended cron parser/matcher, timezone math, launch windows, poll-mode decisions |
204
393
  | `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 |
394
+ | `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 |
395
+ | `src/core/router/rules.ts` | Router layer 1: static rules task type → transport + executor, normalization, no imports (0 tokens) |
396
+ | `src/db/capability-repo.ts` | Router layer 2: Capability Map - gate outcomes per task type, cumulative and decayed success_rate, first_pass_rate, moving averages, last 10 runs, threshold decision |
397
+ | `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 |
398
+ | `src/core/router/dispatch.ts` | Router assembly: `routeStep` runs layer 1 then layer 2 and returns transport/executor, never imports the planner |
399
+ | `src/core/router/escalation.ts` | Gate failure escalation `local → cloud → review → blocked` by pure transition table, no DB, no model |
206
400
  | `src/shared/jobs-view.ts` | Task view shared by the GUI and dashboard |
207
401
 
208
402
  ## Scheduling backends
@@ -231,7 +425,7 @@ enforced:
231
425
  | --- | --- |
232
426
  | Working directory | Task `workingDirectory`, or the workspace path, or the plugin directory |
233
427
  | 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` |
428
+ | Timeout | `timeoutSeconds`; on expiry the child process tree is stopped and the run is marked `timeout` (Windows: CIM → WMI → `tasklist`/`Get-Process`, fail-closed tree kill) |
235
429
  | 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
430
  | No overlap | Lock file per task; a second start exits immediately and records `skipped` |
237
431
  | Pre-flight | `beforeScript`; non-zero exit marks `preFlight` as failed |
@@ -240,6 +434,26 @@ enforced:
240
434
  | Logging | Append-only log per task under `logs/` |
241
435
  | History | Calls the recorder with `--start` and `--finish` |
242
436
 
437
+ **Единый формат lock-токена (B6).** Node (`src/core/lock.ts`), PowerShell
438
+ (`src/core/ps-wrapper.ts`) и bash (`src/core/wrappers/bash.ts`) используют один
439
+ формат записи владельца: `<pid>-<iso>` (Node добавляет `-<uuid>` для
440
+ уникальности токена). Все три стороны понимают и старые варианты:
441
+ `<iso>|<pid>` (legacy PowerShell), `<pid>-<epoch>-<uuid>` (legacy Node) и
442
+ голый `<pid>` из pid-файла bash. Общий парсер — `parseLockToken()` в Node,
443
+ `Get-LockOwnerPid` в PS и `parse_lock_pid` в bash — разбирает legacy
444
+ `<iso>|<pid>` до проверки `<pid>-…`: раньше год из ISO принимался за PID,
445
+ из-за чего живой lock вытеснялся. Перед своим каталогом `<lock>.d` bash
446
+ проверяет файловый lock Node/PS и не запускает задачу, если его владелец жив.
447
+ `test-lock-format.mjs` проверяет парсеры и interop в обе стороны.
448
+
449
+ **Вытеснение каталога `.lock.d` (B7).** При старте плагина `LockManager.initialize()`
450
+ читает владельца из `<task>.lock.d/pid` тем же парсером, что и `.lock`, и не
451
+ трогает каталог, пока процесс жив, — даже если он старше 24 ч (задача с
452
+ `timeoutSeconds: 0` может работать легально долго). Возраст остаётся только
453
+ fallback'ом: каталог без pid-файла или с мёртвым PID вытесняется атомарным
454
+ `rename` в `.stale-*`. Тест — `test-stale-lock.mjs` (живой PID сохраняется,
455
+ мёртвый и безымянный вытесняются).
456
+
243
457
  Windows uses PowerShell and `.cmd` shims; POSIX uses bash. Both wrappers are generated
244
458
  from templates so the policy stays identical across platforms.
245
459
 
@@ -250,6 +464,12 @@ from templates so the policy stays identical across platforms.
250
464
  pre/post-flight results, the chained next task, workspace and tool restrictions.
251
465
  `metrics` holds per-task counters and totals.
252
466
 
467
+ Usage (tokens/cost) resolves in both recorder modes: explicit wrapper arguments win,
468
+ and when they are `-` the recorder parses the log tail (`parseUsageFromLog`) using the
469
+ log path passed as the last argument. This applies to `--finish` (12th argument) and to
470
+ the legacy pre-`--start` mode (11th argument, B10); a missing/unreadable log degrades to
471
+ "no usage" without failing the record.
472
+
253
473
  If the host or the machine dies mid-run, the row stays in `running`. On the next
254
474
  plugin activation, `db/recovery.ts` marks stale `running` rows as `error`, so the UI
255
475
  never shows a permanently running task.
@@ -355,7 +575,7 @@ the whole plugin directory (database, logs, locks, wrappers, prompts) with
355
575
 
356
576
  Schema evolution is additive: `applySchema` runs `CREATE TABLE IF NOT EXISTS` on every
357
577
  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
578
+ never requires a manual migration. `SCHEMA_VERSION` (currently `10`) is stored in
359
579
  `PRAGMA user_version`; incremental steps live in `MIGRATIONS`.
360
580
 
361
581
  ### Durable run state (Sprint 36.1)
@@ -371,8 +591,8 @@ execution:
371
591
  `src/db/runs-repo.ts` owns the transitions and rejects invalid ones
372
592
  (`InvalidTransitionError`). A failed step can be retried explicitly (`retryStep`),
373
593
  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).
594
+ crashes and reconnects, which is the prerequisite for resume (36.2),
595
+ idempotent steps (36.3) and the dead letter queue (36.4).
376
596
 
377
597
  `src/db/run-journal.ts` (Sprint 36.1.b) writes every transition to disk before
378
598
  and after executing the step body: `beginStepAttempt` commits `running` + `started_at`
@@ -385,6 +605,20 @@ marks any `running` steps left after a process crash as `failed` — preserving
385
605
  SQLite runs in WAL mode with `synchronous = NORMAL`, so a committed transition
386
606
  survives a `kill -9` (only the last in-flight commit can be lost with a power cut).
387
607
 
608
+ ### Step leases (B12)
609
+
610
+ Schema v9 adds ownership to `run_steps`: `owner_id` (`hostname:pid:startedAt` of
611
+ the executing process) and `lease_until`. `beginStepAttempt` writes both when it
612
+ commits `running`, with the lease `STEP_LEASE_MS` (60 s) ahead.
613
+ `runStepStatefullyAsync` renews the lease from an `unref`'d timer every third of
614
+ the lease; synchronous chains call `renewStepLease(runId, stepName)` before long
615
+ work. `recoverInterruptedSteps` finalizes only `running` steps whose lease is
616
+ missing (legacy rows) or already expired — a live lease belongs to another
617
+ process and is left running. Consequently `resumeRunSync` / `resumeRun` refuse to
618
+ continue while a live lease remains; `recoverNow` lets a caller treat a lease as
619
+ expired (tests and delayed recovery). This prevents a restarted plugin from
620
+ marking a live worker's step as failed and from running the same step twice.
621
+
388
622
  ### Resume from the middle (Sprint 36.2)
389
623
 
390
624
  `src/db/run-resume.ts` continues a run after a crash. `run_steps.position`
@@ -411,19 +645,171 @@ failure, but the run still ends `failed`. This is covered by
411
645
  `test-run-resume.mjs`, including a real `kill -9` in the middle of a four-step
412
646
  chain.
413
647
 
648
+ The crash path is also exercised nightly by `test-chaos-dag.mjs`: a child process
649
+ runs a four-step chain, the parent sends `SIGKILL` right after the next step has
650
+ committed `running`, and the test then verifies the durable state (`passed` steps
651
+ are untouched, the victim is `running` with `attempt = 1`, later steps are
652
+ `pending`), `PRAGMA integrity_check = ok`, recovery to `failed` with
653
+ `attempt = 1`, and a resume that retries the victim with `attempt = 2` and never
654
+ re-invokes handlers of completed steps. `.github/workflows/nightly.yml` runs it
655
+ on a schedule on Windows and Ubuntu; locally it is `npm run test:chaos`.
656
+
657
+ ### Idempotent steps (Sprint 36.3)
658
+
659
+ `run_steps.idempotency_key` is unique per run: schema v4 deduplicates legacy
660
+ duplicates (keeping the first row, nulling the rest) and replaces the old
661
+ non-unique index with the partial unique index `idx_run_steps_key_unique
662
+ (run_id, idempotency_key) WHERE idempotency_key IS NOT NULL`. The index is
663
+ created in the migration, after the dedupe — the same ordering trap as
664
+ `position`.
665
+
666
+ `src/db/step-idempotency.ts` exposes `runStepOnce` / `runStepOnceAsync`:
667
+
668
+ 1. a key that belongs to another step in the same run is rejected with
669
+ `IdempotencyConflictError`;
670
+ 2. an already `passed`/`skipped` step is **replayed** from `output_json` — the
671
+ body is not called, `attempt` does not grow and no side effect repeats
672
+ (`replayed: true`, `executed: false`);
673
+ 3. a `failed` step is retried with `attempt + 1`, so a transient error does not
674
+ turn into a permanent skip;
675
+ 4. a `running` step, or a second call for the same key while the first is still
676
+ inside the body, raises `StepInFlightError` — the in-process `inFlight` set
677
+ covers parallel async calls, the unique index covers the database;
678
+ 5. a missing step is created with the key, then executed through the journal
679
+ from 36.1.b.
680
+
681
+ The same key is allowed in different runs; `test-step-idempotency.mjs` covers
682
+ first execution, replay from cache (including after reconnect), conflicts,
683
+ retry and parallel deduplication.
684
+
685
+ ### Dead letter queue (Sprint 36.4)
686
+
687
+ A step that fails on every attempt is not transient: resuming the run again just
688
+ burns another attempt and hides the real problem. Schema v5 adds `run_dlq`, the
689
+ durable queue of deterministically failed steps:
690
+
691
+ | Column | Purpose |
692
+ | --- | --- |
693
+ | `run_id`, `step_name` | Which step dead-lettered; cascade-deleted with the run |
694
+ | `status` | `open → retried` or `open → discarded` |
695
+ | `reason` | `attempts-exhausted` (automatic scan) or `manual` |
696
+ | `error`, `attempts` | Snapshot of the failure at the moment of enqueue |
697
+ | `resolved_at`, `resolution` | When and how the entry was closed (`manual-retry`, `discarded`) |
698
+
699
+ `src/db/run-dlq.ts` provides:
700
+
701
+ 1. `scanDeadLetters({ runId?, minAttempts = 3, limit })` selects steps with
702
+ `status = failed` and `attempt >= threshold` and enqueues only new ones. The
703
+ partial unique index `idx_run_dlq_open_unique (run_id, step_name) WHERE
704
+ status = 'open'` makes enqueue idempotent, so a repeated scan does not create
705
+ duplicates.
706
+ 2. `retryDeadLetter(id)` is the manual retry: it reopens the failed run, calls
707
+ `retryStep` (attempt + 1, step back to `running`) and closes the entry as
708
+ `retried` with `resolution = manual-retry`. Closed entries cannot be retried
709
+ or discarded twice.
710
+ 3. `discardDeadLetter(id, resolution = "discarded")` closes the entry without
711
+ touching the step — the run stays failed.
712
+ 4. `listDeadLetters` / `countDeadLetters` filter `open` or `all` for dashboards
713
+ (36.6) and metrics.
714
+
715
+ `retryDeadLetter` calls `reopenRun` and `retryStep`, which each open their own
716
+ transaction. `withTransaction` therefore nests through `SAVEPOINT` when a
717
+ transaction is already active, keeping the whole retry atomic instead of failing
718
+ with `cannot start a transaction within a transaction`. `test-run-dlq.mjs`
719
+ covers the threshold, idempotent scans, manual retry, discard, cascade delete,
720
+ reconnect and the v4 → v5 migration.
721
+
722
+ ### Dead letter queue in the GUI (Sprint 36.6)
723
+
724
+ The side panel exposes the queue through `src/core/dlq-api.ts`, a thin facade
725
+ that normalises the filter (`open` by default, plus `all`/`retried`/`discarded`)
726
+ and clamps the limit, then calls `listDeadLetters` / `retryDeadLetter` /
727
+ `discardDeadLetter`. RPC methods `list_dlq`, `retry_dlq` and `discard_dlq` are
728
+ declared in `src/rpc.ts` and handled in `src/index.ts`; the two mutations are
729
+ audited as `dlq.retry` and `dlq.discard`. `retry_dlq` only prepares the step
730
+ (reopen + `attempt + 1` + entry closed) — the handler itself is executed by a
731
+ later resume, so the panel never claims a step has already run. The UI section
732
+ shows the open count, status filter, creation time, run/step, reason, attempts,
733
+ error and status-aware actions; retry and discard ask for confirmation and
734
+ refresh the list through the same facade. `test-dlq-gui.mjs` checks the RPC/GUI
735
+ wiring, locale parity and the facade behaviour on a temporary SQLite database.
736
+
737
+ ### Pause with context injection (Sprint 36.7)
738
+
739
+ The durable run model gains a new table `run_injections` (`SCHEMA_VERSION = 7`, migration step 7)
740
+ with columns `id`, `run_id` (cascade delete from `runs`), `step_name`, `kind` (`comment` /
741
+ `file` / `artifact`), `content`, `author`, `metadata_json`, `created_at`, `consumed_at`,
742
+ `consumed_by_step`, `consumed_attempt`, plus indexes `idx_run_injections_run(run_id, created_at)`
743
+ and a partial index `idx_run_injections_pending(run_id, step_name) WHERE consumed_at IS NULL`.
744
+
745
+ A run can be paused between steps: `RunStatus` gains `paused` with transitions
746
+ `pending → running/paused/cancelled`, `running → paused/passed/failed/cancelled`,
747
+ `paused → running/passed/cancelled`. `pauseRunRecord(id)` sets `paused` without filling
748
+ `finished_at`. `pauseRun(runId, input)` in `src/db/run-context.ts` requires an existing,
749
+ non-terminal run with no step currently `running`, addresses the first unfinished step (or an
750
+ explicit `stepName`), rejects completed/missing targets, and stores one injection per provided
751
+ payload (`comment`, `file` with path/content/title, `artifact` with name/content). Secrets are
752
+ masked on write: `redactSecretsInText` covers text/comment/file content, and a recursive
753
+ `redactValue` with `SENSITIVE_KEY_RE` masks whole values of sensitive JSON keys
754
+ (`*TOKEN*`, `*SECRET*`, `*PASSWORD*`, `*API_KEY*`, `*CREDENTIAL*`, `*AUTH*`, ...) to `***`.
755
+ A single injection is capped at `MAX_INJECTION_CONTENT` (100 kB).
756
+
757
+ `listRunInjections(runId, { pendingOnly })` returns history ordered by creation time, exposing
758
+ author, masked content and consumption state. `pendingInjectionsForStep(runId, stepName)` returns
759
+ the not-yet-consumed injections addressed to a step.
760
+
761
+ `StepHandler` now receives `(step, context: StepContext)` where `StepContext.injections` holds
762
+ the injections for that step. `resumeRunSync` / `resumeRun` pass them before executing each step,
763
+ and after a successful step call `consumeInjections(ids, stepName, attempt)` to mark the
764
+ injections consumed exactly once (retry keeps them for the next attempt). `finalize` calls
765
+ `consumeOrphanInjections` so injections addressed to already-completed steps do not look pending
766
+ in the history, and supports `paused → passed` when no steps remain. `ResumeResult` gains
767
+ `injected: string[]`. `test-run-context.mjs` covers schema v7, pause-before-start / pause-between
768
+ steps / explicit targeting, comment + file + artifact with secret masking and author visibility,
769
+ single-consumption on resume, repeated resume without re-delivery, pause without context,
770
+ validation errors (missing/completed/running target, terminal run, no unfinished steps, empty
771
+ path, artifact without content, oversized content), async resume and cascade delete on run
772
+ removal.
773
+
774
+ ### Pause and resume in the GUI (Sprint 36.8)
775
+
776
+ `src/core/run-panel-api.ts` is the GUI-facing facade over durable runs. `listRunPanel({ filter, limit })`
777
+ accepts `active` (pending/running/paused/failed), `all`, or a concrete run status, normalizes the
778
+ limit to 1..100 and returns compact `RunPanelRun` entries: status, progress (`doneSteps` /
779
+ `totalSteps`), first unfinished `currentStep` with a stable `anchor`, up to 20 context injections
780
+ (content preview capped at 500 characters, author, timestamps, consumer) and the count of pending
781
+ injections. `active` is also reported for the panel badge.
782
+
783
+ `pauseRunPanel(runId, { comment, author, stepName? })` delegates to `pauseRun`, returning
784
+ `{ success: false, error }` instead of throwing, so the GUI can show the database error next to the
785
+ button. `resumeRunPanel(runId)` only prepares the run: it accepts `paused` or `failed`, calls
786
+ `reopenRun` (status becomes `running`), and returns the next unfinished step from `findResumeStep`.
787
+ Actual step execution remains with `resumeRun` / the DAG executor; the facade never pretends that a
788
+ step ran.
789
+
790
+ RPC methods `list_durable_runs`, `pause_durable_run` and `resume_durable_run` are declared in
791
+ `src/rpc.ts`, implemented in `src/index.ts`, and audited as `run.pause` / `run.resume` (target is the
792
+ run id). The GUI section «⏯️ Запуски DAG» in `src/gui.tsx` renders the run list with status filter,
793
+ progress, current-step anchor link, a comment field, pause/resume buttons with confirmation, a
794
+ blocked pause plus warning while the current step is `running`, and the context history with author
795
+ and consumer. Locales ru/en/zh stay in sync. `test-pause-gui.mjs` verifies the RPC contract, locale
796
+ parity, current-step/progress output, pause with masked comment and author, active/paused filters,
797
+ resume preparation, rejection of a repeated resume, end-to-end comment delivery through
798
+ `resumeRun`, running-step rejection, failed-run resume and list limits.
799
+
414
800
  ## Interfaces
415
801
 
416
802
  | Interface | Audience | Entry point |
417
803
  | --- | --- | --- |
418
- | Agent tools | AI agent | 26 tools registered via `ctx.tool.transform` |
804
+ | Agent tools | AI agent | 29 tools registered via `ctx.tool.transform` |
419
805
  | Agent skill | AI agent | `skills/scheduled-job-best-practices` |
420
- | RPC | Sidebar GUI | `src/rpc.ts` contracts, 44 methods |
806
+ | RPC | Sidebar GUI | `src/rpc.ts` contracts, 57 methods |
421
807
  | Sidebar GUI | Human | `gui-experimental.cjs` |
422
808
  | Web dashboard | Human | `startDashboardServer` (localhost, random/fixed port) |
423
809
 
424
810
  ## Localization
425
811
 
426
- User-visible text lives in flat JSON catalogs: `locales/ru.json` (default),
812
+ User-visible text lives in flat JSON catalogs: `locales/ru.json` (fallback),
427
813
  `locales/en.json` and `locales/zh.json`. Keys are dot-separated and grouped by surface —
428
814
  `gui.*`, `notify.*`, `tool.*`, `dryRun.*`, `matrix.*`, `schedule.*` — and all catalogs
429
815
  must have the same key set with non-empty values.
@@ -431,8 +817,9 @@ must have the same key set with non-empty values.
431
817
  `src/i18n.ts` loads the catalogs once and caches them. It exposes `t(key, params)`,
432
818
  `setLocale(locale)`, `messageIn(locale, key)` and `hasKey(key, locale)`. Lookup order is
433
819
  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.
820
+ an empty string. The `locale` setting (`auto` default, follows the OpenCode interface
821
+ language; `ru`/`en`/`zh` are explicit choices) is applied immediately, without restarting
822
+ OpenCode.
436
823
  `auto` is resolved in the GUI through `ctx.locale.locale()` with BCP 47 prefix mapping
437
824
  (`zh-CN` → `zh`, `en-GB` → `en`); the resolved value is sent to the server as `uiLocale`,
438
825
  because the server process cannot see the window. The sidebar GUI embeds the catalogs at
@@ -461,6 +848,15 @@ Rules:
461
848
  ## Security model
462
849
 
463
850
  - The dashboard has **no authentication** and binds to localhost. Do not expose it.
851
+ - **Dashboard XSS hardening (B3):** every dynamic value passes through `esc()` before
852
+ reaching text or attribute context; it escapes `&`, `<`, `>`, `"` and `'` (the old
853
+ `div.innerHTML` trick left quotes intact). `GET /` also sends
854
+ `Content-Security-Policy: default-src 'none'; script-src 'nonce-…'; style-src
855
+ 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none';
856
+ form-action 'none'; frame-ancestors 'none'; object-src 'none'`. Both inline scripts
857
+ carry a per-response nonce (16 random bytes, base64). `test-dashboard-xss.mjs`
858
+ extracts the shipped `esc()` from the served page and checks quote/angle-bracket
859
+ payloads in text, `title=` and `data-*=` contexts, plus nonce/CSP consistency.
464
860
  - A job definition is **code**: prompts, hooks, Quality Gates and wrappers all execute
465
861
  with your user privileges. Treat task creation like granting shell access.
466
862
  - `allowedTools` / `deniedTools` are **enforced at the run-wrapper level** (Sprint 29.2).
@@ -557,3 +953,47 @@ after the agent with the user's privileges and are not filtered by tool policy.
557
953
  | New agent tool | Add a zod schema + execute function, register in `ctx.tool.transform`, add an RPC contract |
558
954
  | New dashboard panel | Extend `server.ts` routes and the HTML template |
559
955
  | New matrix policy | Extend `MatrixConfig` in `task-transfer.ts` and the logic in `core/matrix.ts` |
956
+
957
+ ## Mission runtime и гибридные входы (план 38–40)
958
+
959
+ > Статус: ad-hoc вход реализован (AB-8); internal-оркестрация и `gate_outcomes` — план 40. Что уже в коде — [ROADMAP.md](../ROADMAP.md) §1.
960
+
961
+ Система гибридная: ядро (**mission runtime**) не знает про планировщик ОС.
962
+ Планировщик — адаптер входа, регистрация опциональна.
963
+
964
+ ### Классы входа
965
+
966
+ | Класс | Вход | Регистрация в ОС | Реализация |
967
+ |---|---|---|---|
968
+ | Ad-hoc | `run_mission` / CLI `run` / GUI / RPC | нет | есть: `core/mission.ts` (AB-8) |
969
+ | Внутренний | chain / DAG / retry / escalation | нет | сейчас через `backend.runTask` + force-маркер; план 40 — напрямую в runtime |
970
+ | Registered | cron / once / file / git / mcp-event / webhook | да (cron/once) | есть: `core/scheduler/*`, `file-watcher`, `git-trigger`, `integrations` |
971
+
972
+ ### Объекты
973
+
974
+ | Объект | Содержимое | Таблица |
975
+ |---|---|---|
976
+ | Миссия | цель + scope + gate-спека + safety + бюджет | `runs` metadata (AB-8); шаблон `missions` — план 38 |
977
+ | Задача | миссия-шаблон + триггер | `tasks` (есть) |
978
+ | Запуск | durable-исполнение: шаги, попытки, вердикты | `runs` / `run_steps` (есть, SCHEMA_VERSION 10) |
979
+ | Исход гейта | вердикт + provenance + экономика | `gate_outcomes` (план 40) |
980
+
981
+ ### Путь исполнения (целевой)
982
+
983
+ ```
984
+ вход → intake (gate + safety → политика + бюджет) → createRun(trigger_kind)
985
+ → planner → [route → context compile → execute → GATE]* → artifact → report
986
+ ```
987
+
988
+ Существующий путь планировщика (`wrapper → opencode run → record-history → history`)
989
+ сохраняется для обратной совместимости; в 40 он подключается к runtime и создаёт
990
+ durable-run, а исходы гейта пишутся в ledger.
991
+
992
+ ### Что переиспользуется
993
+
994
+ - Durable state: `db/runs-repo`, `run-journal`, `run-resume`, `step-idempotency`, `run-context`.
995
+ - Роутинг: `core/router/rules|dispatch|escalation|planner`, `db/capability-repo`.
996
+ - Права и секреты: `core/permissions`, `core/secrets` (scoped-инъекция).
997
+ - Телеметрия: `core/otel`, `core/prometheus`, `core/structured-log`.
998
+ - Пауза с инъекциями: `db/run-context` + `core/run-panel-api` → основа approval-гейта.
999
+ - Retrieval для scaffolding: подход bag-of-words из `notification_embeddings`.