agent-steward 0.0.4 → 0.0.6

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 (279) hide show
  1. package/CHANGELOG.md +309 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +55 -8
  4. package/ROADMAP-STRATEGY.md +22 -19
  5. package/ROADMAP.md +230 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +356 -0
  9. package/dist/core/analytics.d.ts +6 -0
  10. package/dist/core/analytics.d.ts.map +1 -1
  11. package/dist/core/analytics.js +20 -3
  12. package/dist/core/audit.d.ts +6 -0
  13. package/dist/core/audit.d.ts.map +1 -1
  14. package/dist/core/audit.js +24 -0
  15. package/dist/core/budget.d.ts +118 -0
  16. package/dist/core/budget.d.ts.map +1 -0
  17. package/dist/core/budget.js +206 -0
  18. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  19. package/dist/core/cron-to-schtasks.js +38 -0
  20. package/dist/core/dry-run.d.ts +26 -1
  21. package/dist/core/dry-run.d.ts.map +1 -1
  22. package/dist/core/dry-run.js +199 -8
  23. package/dist/core/execution.d.ts +203 -0
  24. package/dist/core/execution.d.ts.map +1 -0
  25. package/dist/core/execution.js +309 -0
  26. package/dist/core/feedback.d.ts +192 -0
  27. package/dist/core/feedback.d.ts.map +1 -0
  28. package/dist/core/feedback.js +426 -0
  29. package/dist/core/gate-integrity.d.ts +71 -0
  30. package/dist/core/gate-integrity.d.ts.map +1 -0
  31. package/dist/core/gate-integrity.js +275 -0
  32. package/dist/core/git-trigger.d.ts.map +1 -1
  33. package/dist/core/git-trigger.js +14 -2
  34. package/dist/core/guard-run.d.ts +4 -0
  35. package/dist/core/guard-run.d.ts.map +1 -0
  36. package/dist/core/guard-run.js +101 -0
  37. package/dist/core/guard.d.ts +52 -0
  38. package/dist/core/guard.d.ts.map +1 -0
  39. package/dist/core/guard.js +362 -0
  40. package/dist/core/local-ai.d.ts.map +1 -1
  41. package/dist/core/local-ai.js +7 -3
  42. package/dist/core/lock.d.ts +41 -0
  43. package/dist/core/lock.d.ts.map +1 -1
  44. package/dist/core/lock.js +141 -29
  45. package/dist/core/matrix.d.ts +8 -0
  46. package/dist/core/matrix.d.ts.map +1 -1
  47. package/dist/core/matrix.js +132 -17
  48. package/dist/core/mission.d.ts +103 -0
  49. package/dist/core/mission.d.ts.map +1 -0
  50. package/dist/core/mission.js +374 -0
  51. package/dist/core/opencode-models.d.ts +2 -2
  52. package/dist/core/opencode-models.d.ts.map +1 -1
  53. package/dist/core/opencode-models.js +28 -21
  54. package/dist/core/opencode-usage.d.ts +35 -0
  55. package/dist/core/opencode-usage.d.ts.map +1 -0
  56. package/dist/core/opencode-usage.js +132 -0
  57. package/dist/core/pipeline-apply.d.ts +38 -0
  58. package/dist/core/pipeline-apply.d.ts.map +1 -0
  59. package/dist/core/pipeline-apply.js +117 -0
  60. package/dist/core/pipeline-io.d.ts +13 -0
  61. package/dist/core/pipeline-io.d.ts.map +1 -0
  62. package/dist/core/pipeline-io.js +78 -0
  63. package/dist/core/pipeline-map.d.ts +52 -0
  64. package/dist/core/pipeline-map.d.ts.map +1 -0
  65. package/dist/core/pipeline-map.js +208 -0
  66. package/dist/core/pipeline-spec.d.ts +109 -0
  67. package/dist/core/pipeline-spec.d.ts.map +1 -0
  68. package/dist/core/pipeline-spec.js +554 -0
  69. package/dist/core/ps-wrapper.d.ts +27 -2
  70. package/dist/core/ps-wrapper.d.ts.map +1 -1
  71. package/dist/core/ps-wrapper.js +424 -65
  72. package/dist/core/record-history.d.ts.map +1 -1
  73. package/dist/core/record-history.js +206 -33
  74. package/dist/core/router/rules.d.ts.map +1 -1
  75. package/dist/core/router/rules.js +6 -0
  76. package/dist/core/run-mode.d.ts +12 -0
  77. package/dist/core/run-mode.d.ts.map +1 -0
  78. package/dist/core/run-mode.js +17 -0
  79. package/dist/core/scheduler/linux.d.ts +8 -1
  80. package/dist/core/scheduler/linux.d.ts.map +1 -1
  81. package/dist/core/scheduler/linux.js +34 -9
  82. package/dist/core/scheduler/logs.d.ts +4 -0
  83. package/dist/core/scheduler/logs.d.ts.map +1 -1
  84. package/dist/core/scheduler/logs.js +25 -1
  85. package/dist/core/scheduler/mac.d.ts +44 -2
  86. package/dist/core/scheduler/mac.d.ts.map +1 -1
  87. package/dist/core/scheduler/mac.js +126 -15
  88. package/dist/core/scheduler/windows.d.ts.map +1 -1
  89. package/dist/core/scheduler/windows.js +15 -12
  90. package/dist/core/secrets.d.ts.map +1 -1
  91. package/dist/core/secrets.js +18 -8
  92. package/dist/core/self-analysis.d.ts +32 -2
  93. package/dist/core/self-analysis.d.ts.map +1 -1
  94. package/dist/core/self-analysis.js +38 -27
  95. package/dist/core/shutdown.d.ts +33 -2
  96. package/dist/core/shutdown.d.ts.map +1 -1
  97. package/dist/core/shutdown.js +58 -2
  98. package/dist/core/structured-log.d.ts +37 -1
  99. package/dist/core/structured-log.d.ts.map +1 -1
  100. package/dist/core/structured-log.js +37 -0
  101. package/dist/core/usage-surface.d.ts +25 -0
  102. package/dist/core/usage-surface.d.ts.map +1 -0
  103. package/dist/core/usage-surface.js +41 -0
  104. package/dist/core/worktree-run.d.ts +4 -0
  105. package/dist/core/worktree-run.d.ts.map +1 -0
  106. package/dist/core/worktree-run.js +164 -0
  107. package/dist/core/worktree.d.ts +115 -0
  108. package/dist/core/worktree.d.ts.map +1 -0
  109. package/dist/core/worktree.js +462 -0
  110. package/dist/core/wrappers/bash.d.ts +19 -0
  111. package/dist/core/wrappers/bash.d.ts.map +1 -1
  112. package/dist/core/wrappers/bash.js +230 -27
  113. package/dist/db/capability-repo.d.ts +43 -2
  114. package/dist/db/capability-repo.d.ts.map +1 -1
  115. package/dist/db/capability-repo.js +96 -11
  116. package/dist/db/history-repo.d.ts +70 -5
  117. package/dist/db/history-repo.d.ts.map +1 -1
  118. package/dist/db/history-repo.js +170 -29
  119. package/dist/db/metrics-repo.d.ts +20 -2
  120. package/dist/db/metrics-repo.d.ts.map +1 -1
  121. package/dist/db/metrics-repo.js +35 -13
  122. package/dist/db/migrate.d.ts.map +1 -1
  123. package/dist/db/migrate.js +37 -17
  124. package/dist/db/recovery.d.ts +3 -1
  125. package/dist/db/recovery.d.ts.map +1 -1
  126. package/dist/db/recovery.js +11 -5
  127. package/dist/db/run-journal.d.ts +33 -5
  128. package/dist/db/run-journal.d.ts.map +1 -1
  129. package/dist/db/run-journal.js +78 -14
  130. package/dist/db/run-resume.d.ts +5 -0
  131. package/dist/db/run-resume.d.ts.map +1 -1
  132. package/dist/db/run-resume.js +9 -2
  133. package/dist/db/runs-repo.d.ts +19 -2
  134. package/dist/db/runs-repo.d.ts.map +1 -1
  135. package/dist/db/runs-repo.js +91 -60
  136. package/dist/db/schema.d.ts +2 -2
  137. package/dist/db/schema.d.ts.map +1 -1
  138. package/dist/db/schema.js +132 -2
  139. package/dist/db/templates-repo.d.ts +2 -2
  140. package/dist/db/templates-repo.d.ts.map +1 -1
  141. package/dist/db/templates-repo.js +5 -3
  142. package/dist/history.d.ts +7 -2
  143. package/dist/history.d.ts.map +1 -1
  144. package/dist/history.js +4 -2
  145. package/dist/hook-output.d.ts +2 -0
  146. package/dist/hook-output.d.ts.map +1 -0
  147. package/dist/hook-output.js +31 -0
  148. package/dist/i18n.d.ts +5 -0
  149. package/dist/i18n.d.ts.map +1 -1
  150. package/dist/i18n.js +11 -4
  151. package/dist/index.d.ts +375 -47
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +1344 -192
  154. package/dist/notifications.d.ts +53 -2
  155. package/dist/notifications.d.ts.map +1 -1
  156. package/dist/notifications.js +168 -21
  157. package/dist/profiles.d.ts.map +1 -1
  158. package/dist/profiles.js +82 -10
  159. package/dist/rpc.d.ts +354 -0
  160. package/dist/rpc.d.ts.map +1 -1
  161. package/dist/rpc.js +145 -0
  162. package/dist/server.d.ts +32 -2
  163. package/dist/server.d.ts.map +1 -1
  164. package/dist/server.js +154 -30
  165. package/dist/settings.d.ts +44 -2
  166. package/dist/settings.d.ts.map +1 -1
  167. package/dist/settings.js +85 -3
  168. package/dist/shared/jobs-view.d.ts +1 -1
  169. package/dist/shared/jobs-view.d.ts.map +1 -1
  170. package/dist/shared/jobs-view.js +2 -0
  171. package/dist/task-transfer.d.ts +21 -0
  172. package/dist/task-transfer.d.ts.map +1 -1
  173. package/dist/task-transfer.js +64 -3
  174. package/dist/templates.d.ts +2 -2
  175. package/dist/templates.d.ts.map +1 -1
  176. package/dist/templates.js +3 -3
  177. package/dist/types.d.ts +22 -2
  178. package/dist/types.d.ts.map +1 -1
  179. package/dist/workspaces.d.ts.map +1 -1
  180. package/dist/workspaces.js +34 -11
  181. package/docs/ARCHITECTURE.md +319 -66
  182. package/docs/COMPATIBILITY.md +2 -2
  183. package/docs/CONCEPT.md +18 -4
  184. package/docs/CROSS_PLATFORM.ru.md +20 -0
  185. package/docs/CROSS_PLATFORM.zh.md +18 -0
  186. package/docs/EXECUTION-LOOP.md +28 -10
  187. package/docs/FEATURES.md +129 -7
  188. package/docs/FEATURES.zh.md +97 -6
  189. package/docs/MIGRATION.md +2 -2
  190. package/docs/PIPELINE.md +293 -0
  191. package/docs/QA-A2-GUI-TUI.md +205 -0
  192. package/docs/README.ru.md +43 -4
  193. package/docs/README.zh.md +44 -4
  194. package/docs/SAFETY.md +23 -3
  195. package/gui-experimental.cjs +9 -8
  196. package/locales/en.json +58 -3
  197. package/locales/ru.json +58 -3
  198. package/locales/zh.json +58 -3
  199. package/opencode.pipeline.yaml +35 -0
  200. package/package.json +36 -4
  201. package/scripts/check-eslint-baseline.mjs +139 -0
  202. package/scripts/gen-test-plan-counters.mjs +117 -0
  203. package/scripts/github-ci-fetch.ps1 +37 -0
  204. package/scripts/pl-commit.ps1 +112 -0
  205. package/scripts/qa-a2-commit.ps1 +104 -0
  206. package/scripts/test-home.mjs +107 -0
  207. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  208. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  209. package/src/cli.ts +417 -0
  210. package/src/core/analytics.ts +27 -4
  211. package/src/core/audit.ts +25 -0
  212. package/src/core/budget.ts +340 -0
  213. package/src/core/cron-to-schtasks.ts +42 -0
  214. package/src/core/dry-run.ts +235 -12
  215. package/src/core/execution.ts +538 -0
  216. package/src/core/feedback.ts +582 -0
  217. package/src/core/file-watcher.ts +2 -2
  218. package/src/core/gate-integrity.ts +330 -0
  219. package/src/core/git-trigger.ts +18 -5
  220. package/src/core/guard-run.ts +119 -0
  221. package/src/core/guard.ts +431 -0
  222. package/src/core/local-ai.ts +7 -3
  223. package/src/core/lock.ts +178 -37
  224. package/src/core/matrix.ts +158 -52
  225. package/src/core/mission.ts +531 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/opencode-models.ts +30 -21
  228. package/src/core/opencode-usage.ts +182 -0
  229. package/src/core/pipeline-apply.ts +158 -0
  230. package/src/core/pipeline-io.ts +96 -0
  231. package/src/core/pipeline-map.ts +283 -0
  232. package/src/core/pipeline-spec.ts +775 -0
  233. package/src/core/ps-wrapper.ts +435 -66
  234. package/src/core/record-history.ts +258 -81
  235. package/src/core/router/rules.ts +6 -0
  236. package/src/core/run-mode.ts +19 -0
  237. package/src/core/schedule-gate.ts +1 -1
  238. package/src/core/scheduler/at-fallback.ts +1 -1
  239. package/src/core/scheduler/linux.ts +40 -11
  240. package/src/core/scheduler/logs.ts +34 -3
  241. package/src/core/scheduler/mac.ts +174 -14
  242. package/src/core/scheduler/registry.ts +2 -2
  243. package/src/core/scheduler/windows.ts +19 -15
  244. package/src/core/secrets.ts +26 -19
  245. package/src/core/self-analysis.ts +75 -29
  246. package/src/core/shutdown.ts +90 -4
  247. package/src/core/structured-log.ts +89 -5
  248. package/src/core/telegram.ts +2 -2
  249. package/src/core/triage-worker.ts +7 -7
  250. package/src/core/triage.ts +2 -2
  251. package/src/core/usage-surface.ts +70 -0
  252. package/src/core/worktree-run.ts +199 -0
  253. package/src/core/worktree.ts +600 -0
  254. package/src/core/wrappers/bash.ts +248 -26
  255. package/src/db/capability-repo.ts +127 -10
  256. package/src/db/history-repo.ts +281 -40
  257. package/src/db/metrics-repo.ts +40 -13
  258. package/src/db/migrate.ts +57 -32
  259. package/src/db/recovery.ts +12 -5
  260. package/src/db/run-journal.ts +100 -13
  261. package/src/db/run-resume.ts +17 -1
  262. package/src/db/runs-repo.ts +147 -65
  263. package/src/db/schema.ts +134 -2
  264. package/src/db/templates-repo.ts +5 -3
  265. package/src/gui.tsx +438 -18
  266. package/src/history.ts +11 -4
  267. package/src/hook-output.ts +39 -0
  268. package/src/i18n.ts +12 -4
  269. package/src/index.ts +1902 -320
  270. package/src/notifications.ts +227 -47
  271. package/src/profiles.ts +88 -10
  272. package/src/rpc.ts +158 -0
  273. package/src/server.ts +201 -41
  274. package/src/settings.ts +125 -5
  275. package/src/shared/jobs-view.ts +3 -1
  276. package/src/task-transfer.ts +90 -6
  277. package/src/templates.ts +3 -3
  278. package/src/types.ts +23 -2
  279. package/src/workspaces.ts +37 -14
@@ -38,50 +38,198 @@ 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) | 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
+ │ 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 RPC method `run_mission` (not registered as an agent tool), 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 **12**; migrations are additive and idempotent,
212
+ applied through `PRAGMA user_version` on open. Step 11 adds functional indexes
213
+ `idx_history_task_lower` / `idx_history_status_lower` for `getHistory()` filters.
214
+
215
+ | Tables | Purpose |
216
+ | --- | --- |
217
+ | `tasks`, `workspaces`, `templates`, `settings` | definitions and configuration |
218
+ | `history`, `metrics` | run outcomes, duration / tokens / cost, analytics; v8 adds `owner_pid` / `owner_host` / `owner_started_at` so recovery can keep live runs |
219
+ | `audit_log` | mutation journal (who / what / when / which interface) |
220
+ | `git_state` | git-trigger heads and polling state |
221
+ | `notification_dedup`, `notification_embeddings` | rule-based and embedding dedup; tokenizer emits overlapping CJK bigrams so CJK messages get non-zero vectors |
222
+ | `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` |
223
+ | `capability_map` | router layer 2: task type → model / success rate / costs / last runs; v10 adds `first_pass_count` |
224
+
225
+ ### Known limitations (execution)
226
+
227
+ - Startup recovery (`recoverInterrupted*`) marks unfinished rows as `error`; it
228
+ does not yet check whether the wrapper process is still alive, so a plugin
229
+ restart during a live run finalizes that run early (tracked: Trust hotfix).
230
+ - Durable steps currently execute through the same wrapper machinery; the
231
+ agent-executor abstraction (run missions without an OpenCode-specific
232
+ transport) is Stage 2 of the strategy (sprints 32/38).
85
233
 
86
234
  ## Data flow
87
235
 
@@ -105,9 +253,13 @@ is read from the database or from files under the plugin directory.
105
253
  3. The wrapper acquires the lock (`locks/<task>.lock`), writes the log
106
254
  (`logs/<task>.log`), loads workspace env from `<PLUGIN_DIR>/env/<sanitized>.env`
107
255
  (Windows `-EnvFile`, POSIX `set -a; . "$ENV_FILE"; set +a`) before starting
108
- `opencode run` with the prompt file. Output is streamed to the log.
256
+ `opencode run` with the prompt file. The prompt is passed after `--`, so a
257
+ prompt starting with `-` is never parsed as an option. Output is streamed to the log.
109
258
  4. When the process ends, the wrapper enforces the timeout result, runs the Quality
110
- Gate and the post-flight hook.
259
+ Gate and the post-flight hook. On Windows the watchdog snapshots the process tree
260
+ via CIM and falls back to WMI, then to `tasklist`/`Get-Process`; when no tree data
261
+ is available at all it fails closed and kills the root process tree with
262
+ `taskkill /F /T`.
111
263
  5. The wrapper calls `node dist/core/record-history.js --finish ...` with status,
112
264
  duration, tokens, cost, model and hook results.
113
265
  6. The recorder writes `history` and updates `metrics`, then evaluates retries, task
@@ -151,23 +303,34 @@ cloud model — without involving a model for known step types.
151
303
 
152
304
  ### Слой 2 — Capability Map (0 токенов, быстро)
153
305
 
154
- SQLite-таблица `task_type → model / success_rate / avg_cost / avg_time /
155
- last_10_runs`. Обучается на исходах гейта (CONCEPT §9 learning loop).
306
+ SQLite-таблица `task_type → model / success_rate / first_pass_rate /
307
+ avg_cost / avg_time / last_10_runs`. Обучается на исходах гейта
308
+ (CONCEPT §9 learning loop).
156
309
 
157
- - `success_rate ≥ 0.85` → маршрут локально
158
- - `success_rate ≤ 0.30` → эскалация в облако или «нужно ревью»
310
+ - `effective_success_rate ≥ 0.85` → маршрут локально
311
+ - `effective_success_rate ≤ 0.30` → эскалация в облако или «нужно ревью»
312
+
313
+ `effective_success_rate = 0.7 × decayed_success_rate + 0.3 × first_pass_rate`.
314
+ `decayed_success_rate` считается по `last_10_runs` с half-life 8 исходов
315
+ (свежий исход весит 1, каждый предыдущий — вдвое меньше на каждые 8 шагов),
316
+ поэтому недавние провалы быстро перевешивают старые успехи. `first_pass_rate`
317
+ — доля успехов, достигнутых с первой попытки (`attempts = 1`); явный флаг
318
+ `firstPass` позволяет переопределить это для конкретного исхода.
159
319
 
160
320
  Это и есть learning loop: роутер учится на гейтах и становится точнее без затрат
161
321
  токенов на само решение.
162
322
 
163
- Реализация (Спринт 36.5.b): `src/db/capability-repo.ts`, таблица `capability_map`
164
- (`SCHEMA_VERSION = 6`). `recordCapabilityOutcome` обновляет счётчики, считает
323
+ Реализация (Спринт 36.5.b, B13): `src/db/capability-repo.ts`, таблица
324
+ `capability_map` (`SCHEMA_VERSION = 12`). `recordCapabilityOutcome` обновляет
325
+ счётчики (`runs_total`, `runs_passed`, `first_pass_count`), кумулятивный
165
326
  `success_rate` и скользящие средние стоимости/времени, хранит `last_10_runs`
166
327
  (JSON, новые справа). `decideCapabilityRoute` решает по правилам:
167
328
  меньше `MIN_RUNS_FOR_DECISION = 3` исходов → `explore` (решает слой 3),
168
- `≥ 0.85` → `local`, `≤ 0.30` → `cloud`, между порогами → `review`. Пороги
169
- передаются параметром, поэтому политика меняется без миграции данных.
170
- Покрытие — `test-capability-map.mjs`.
329
+ `effective_success_rate ≥ 0.85` → `local`, `≤ 0.30` → `cloud`, между порогами →
330
+ `review`. Пороги передаются параметром, поэтому политика меняется без миграции
331
+ данных. При миграции v9 → v10 legacy-записи получают
332
+ `first_pass_count = runs_passed` (старые успехи считаются успехами с первой
333
+ попытки). Покрытие — `test-capability-map.mjs`.
171
334
 
172
335
  ### Слой 3 — локальная модель (только декомпозиция и неоднозначность)
173
336
 
@@ -175,7 +338,11 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
175
338
  1. Разбивает миссию на шаги с типами (планирование);
176
339
  2. Разрешает неоднозначность (Explore-режим, когда в Capability Map нет данных).
177
340
 
178
- После этого каждый шаг проходит через Слой 1 и Слой 2.
341
+ После этого каждый шаг проходит через Слой 1 и Слой 2. Слой 3 — **декомпозиция
342
+ миссии**, а не маршрутизация шага: он решает, *что* делать, но никогда не
343
+ выбирает, *где* исполнять. `RouteSource` в `src/core/router/dispatch.ts:15`
344
+ принимает только `static` и `capability` — значения `model`/`planner` в нём
345
+ нет, и `routeStep` не импортирует `planner`.
179
346
 
180
347
  **Реализация (Спринт 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
348
 
@@ -193,7 +360,7 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
193
360
 
194
361
  | Path | Role |
195
362
  | --- | --- |
196
- | `src/index.ts` | Plugin lifecycle, 26 agent tools, RPC handlers, task CRUD, view assembly |
363
+ | `src/index.ts` | Plugin lifecycle, 30 agent tools, RPC handlers, task CRUD, view assembly |
197
364
  | `src/rpc.ts` | JSON-schema contracts for every RPC method |
198
365
  | `src/gui.tsx` | OpenCode sidebar panel (SolidJS, built to `gui-experimental.cjs`) |
199
366
  | `src/server.ts` | Local web dashboard HTTP server and HTML rendering |
@@ -203,7 +370,7 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
203
370
  | `src/workspaces.ts` | Workspace registry and path validation; env pairs and `.env` file resolution with secret masking |
204
371
  | `src/templates.ts` | Reusable task templates |
205
372
  | `src/settings.ts` | Plugin settings: notifications, history retention, audit, interface locale (`auto`/`ru`/`en`/`zh`) and last known UI locale, local AI/triage |
206
- | `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` |
373
+ | `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` |
207
374
  | `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 |
208
375
  | `src/core/telegram.ts` | Telegram Bot API `sendMessage`: parse-mode escaping, dashboard link, token validation and masking |
209
376
  | `src/core/native-notify.ts` | Native OS notifications: Windows Toast (PowerShell/WinRT), macOS `osascript`, Linux `notify-send`; no external dependency |
@@ -227,7 +394,7 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
227
394
  | `src/core/schedule-gate.ts` | Wrapper-side gate: cron re-check (poll mode), window postpone, defer-file |
228
395
  | `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
396
  | `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 |
397
+ | `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 |
231
398
  | `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
399
  | `src/core/router/dispatch.ts` | Router assembly: `routeStep` runs layer 1 then layer 2 and returns transport/executor, never imports the planner |
233
400
  | `src/core/router/escalation.ts` | Gate failure escalation `local → cloud → review → blocked` by pure transition table, no DB, no model |
@@ -240,7 +407,7 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
240
407
 
241
408
  | Platform | Backend | Notes |
242
409
  | --- | --- | --- |
243
- | Windows | `schtasks.exe` | Cron is translated to `MINUTE/HOURLY/DAILY/WEEKLY/MONTHLY` flags; non-cron triggers are registered as `ONCE` at `31.12.2099` |
410
+ | Windows | `schtasks.exe` | Cron is translated to `MINUTE/HOURLY/DAILY/WEEKLY/MONTHLY` flags; non-cron triggers are registered as an **enabled** `ONCE` entry at `31.12.2099` (Status `Ready`, never fires by itself) |
244
411
  | Linux | `crontab` | Task lines with the plugin marker are rewritten via `crontab -` |
245
412
  | macOS | `launchd` | `StartCalendarInterval` plists |
246
413
  | POSIX fallback | `crontab` | Used when launchd is unavailable |
@@ -259,7 +426,7 @@ enforced:
259
426
  | --- | --- |
260
427
  | Working directory | Task `workingDirectory`, or the workspace path, or the plugin directory |
261
428
  | Prompt | Written to a prompt file, passed to `opencode run` |
262
- | Timeout | `timeoutSeconds`; on expiry the child process tree is stopped and the run is marked `timeout` |
429
+ | 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) |
263
430
  | 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 |
264
431
  | No overlap | Lock file per task; a second start exits immediately and records `skipped` |
265
432
  | Pre-flight | `beforeScript`; non-zero exit marks `preFlight` as failed |
@@ -268,6 +435,40 @@ enforced:
268
435
  | Logging | Append-only log per task under `logs/` |
269
436
  | History | Calls the recorder with `--start` and `--finish` |
270
437
 
438
+ **Gate input and worktree snapshots.** A task with `qualityGate` stores a hash of
439
+ the gate command, prompt and timeout when it is created (`core/gate-integrity.ts`,
440
+ `gate-snapshots/*.json`); before the gate runs, both wrappers verify that hash and
441
+ fail closed on a mismatch (G-1.2). **PL-25:** a parallel agent can edit `src/`
442
+ without committing while a task is running, which used to make the start lint green
443
+ and the post-flight gate fail on somebody else's uncommitted code. The wrappers now
444
+ also capture a worktree snapshot at task start — `HEAD` plus
445
+ `git status --porcelain --untracked-files=no -- src` — into a sibling
446
+ `*.worktree.json` file, and verify it immediately before the gate. Guard paths are
447
+ configurable via `AGENT_STEWARD_GATE_GUARD_PATHS` (separator `|` or `;`). If `HEAD`
448
+ or the guarded working tree changed during the run, the gate is skipped and the run
449
+ is marked as an error with an explicit message; non-git directories are not guarded.
450
+ This prevents a green gate from certifying code that was changed by another task.
451
+
452
+ **Единый формат lock-токена (B6).** Node (`src/core/lock.ts`), PowerShell
453
+ (`src/core/ps-wrapper.ts`) и bash (`src/core/wrappers/bash.ts`) используют один
454
+ формат записи владельца: `<pid>-<iso>` (Node добавляет `-<uuid>` для
455
+ уникальности токена). Все три стороны понимают и старые варианты:
456
+ `<iso>|<pid>` (legacy PowerShell), `<pid>-<epoch>-<uuid>` (legacy Node) и
457
+ голый `<pid>` из pid-файла bash. Общий парсер — `parseLockToken()` в Node,
458
+ `Get-LockOwnerPid` в PS и `parse_lock_pid` в bash — разбирает legacy
459
+ `<iso>|<pid>` до проверки `<pid>-…`: раньше год из ISO принимался за PID,
460
+ из-за чего живой lock вытеснялся. Перед своим каталогом `<lock>.d` bash
461
+ проверяет файловый lock Node/PS и не запускает задачу, если его владелец жив.
462
+ `test-lock-format.mjs` проверяет парсеры и interop в обе стороны.
463
+
464
+ **Вытеснение каталога `.lock.d` (B7).** При старте плагина `LockManager.initialize()`
465
+ читает владельца из `<task>.lock.d/pid` тем же парсером, что и `.lock`, и не
466
+ трогает каталог, пока процесс жив, — даже если он старше 24 ч (задача с
467
+ `timeoutSeconds: 0` может работать легально долго). Возраст остаётся только
468
+ fallback'ом: каталог без pid-файла или с мёртвым PID вытесняется атомарным
469
+ `rename` в `.stale-*`. Тест — `test-stale-lock.mjs` (живой PID сохраняется,
470
+ мёртвый и безымянный вытесняются).
471
+
271
472
  Windows uses PowerShell and `.cmd` shims; POSIX uses bash. Both wrappers are generated
272
473
  from templates so the policy stays identical across platforms.
273
474
 
@@ -278,6 +479,22 @@ from templates so the policy stays identical across platforms.
278
479
  pre/post-flight results, the chained next task, workspace and tool restrictions.
279
480
  `metrics` holds per-task counters and totals.
280
481
 
482
+ Usage (tokens/cost) resolves in both recorder modes: explicit wrapper arguments win,
483
+ and when they are `-` the recorder parses the log tail (`parseUsageFromLog`) using the
484
+ log path passed as the last argument. This applies to `--finish` (12th argument) and to
485
+ the legacy pre-`--start` mode (11th argument, B10); a missing/unreadable log degrades to
486
+ the next source instead of failing the record. Many OpenCode providers (for example
487
+ hy4-flash-free and local Ollama) print no usage lines at all, so `parseUsageFromLog`
488
+ alone leaves tokens at zero. In that case `core/opencode-usage.ts` reads OpenCode's own
489
+ SQLite database read-only (`~/.local/share/opencode/opencode.db`, override via
490
+ `OPENCODE_USAGE_DB`) and sums assistant-message `tokens`/`cost` from `message.data`
491
+ inside a ±2 s window around the run, optionally restricted to the task's working
492
+ directory. `record-history.ts` fills only fields that are still missing and emits a
493
+ `usage.from_opencode_db` structured event; a missing or locked database is ignored.
494
+ Offline tool-surface measurement lives in `core/usage-surface.ts`: it accepts an
495
+ injected tokenizer (the test uses `gpt-tokenizer`) so the reported size of the 30-tool
496
+ registry is a real token count, not a character heuristic.
497
+
281
498
  If the host or the machine dies mid-run, the row stays in `running`. On the next
282
499
  plugin activation, `db/recovery.ts` marks stale `running` rows as `error`, so the UI
283
500
  never shows a permanently running task.
@@ -305,6 +522,18 @@ All three are evaluated by the recorder after a run finishes:
305
522
  `selectDependentsToTrigger(taskName, definitions, history)` is a pure function, which
306
523
  keeps the rules testable.
307
524
 
525
+ **Dependency completion is an event, not a one-shot latch (PL-40).** Every time a
526
+ dependency finishes, its completion is evaluated against the dependencies' latest
527
+ records. If all dependencies are currently successful, the dependent is started — even
528
+ when an earlier run of the same generation already started it. With two parents this
529
+ means the dependent may run once per parent completion (e.g. `T5` with
530
+ `dependsOn: [T3, T4]` runs when `T3` finishes while `T4` is still successful, and again
531
+ when `T4` finishes). This also applies to a stale but successful record: an older
532
+ success still satisfies the gate. The dependent's own latest `startedAt` only suppresses
533
+ a re-trigger when it is newer than the newest dependency `finishedAt`. Do not dedupe
534
+ across generations — `test-dag-latest-history.mjs` locks this in. For a strict single
535
+ run per trigger use `nextTaskOnSuccess` instead of a multi-parent `dependsOn`.
536
+
308
537
  ## Matrix builds
309
538
 
310
539
  A matrix task is a template, not a runnable job:
@@ -383,7 +612,7 @@ the whole plugin directory (database, logs, locks, wrappers, prompts) with
383
612
 
384
613
  Schema evolution is additive: `applySchema` runs `CREATE TABLE IF NOT EXISTS` on every
385
614
  connection and adds missing columns after `PRAGMA table_info`, so upgrading the plugin
386
- never requires a manual migration. `SCHEMA_VERSION` (currently `6`) is stored in
615
+ never requires a manual migration. `SCHEMA_VERSION` (currently `12`) is stored in
387
616
  `PRAGMA user_version`; incremental steps live in `MIGRATIONS`.
388
617
 
389
618
  ### Durable run state (Sprint 36.1)
@@ -413,6 +642,20 @@ marks any `running` steps left after a process crash as `failed` — preserving
413
642
  SQLite runs in WAL mode with `synchronous = NORMAL`, so a committed transition
414
643
  survives a `kill -9` (only the last in-flight commit can be lost with a power cut).
415
644
 
645
+ ### Step leases (B12)
646
+
647
+ Schema v9 adds ownership to `run_steps`: `owner_id` (`hostname:pid:startedAt` of
648
+ the executing process) and `lease_until`. `beginStepAttempt` writes both when it
649
+ commits `running`, with the lease `STEP_LEASE_MS` (60 s) ahead.
650
+ `runStepStatefullyAsync` renews the lease from an `unref`'d timer every third of
651
+ the lease; synchronous chains call `renewStepLease(runId, stepName)` before long
652
+ work. `recoverInterruptedSteps` finalizes only `running` steps whose lease is
653
+ missing (legacy rows) or already expired — a live lease belongs to another
654
+ process and is left running. Consequently `resumeRunSync` / `resumeRun` refuse to
655
+ continue while a live lease remains; `recoverNow` lets a caller treat a lease as
656
+ expired (tests and delayed recovery). This prevents a restarted plugin from
657
+ marking a live worker's step as failed and from running the same step twice.
658
+
416
659
  ### Resume from the middle (Sprint 36.2)
417
660
 
418
661
  `src/db/run-resume.ts` continues a run after a crash. `run_steps.position`
@@ -595,15 +838,15 @@ resume preparation, rejection of a repeated resume, end-to-end comment delivery
595
838
 
596
839
  | Interface | Audience | Entry point |
597
840
  | --- | --- | --- |
598
- | Agent tools | AI agent | 26 tools registered via `ctx.tool.transform` |
841
+ | Agent tools | AI agent | 30 tools registered via `ctx.tool.transform` |
599
842
  | Agent skill | AI agent | `skills/scheduled-job-best-practices` |
600
- | RPC | Sidebar GUI | `src/rpc.ts` contracts, 47 methods |
843
+ | RPC | Sidebar GUI | `src/rpc.ts` contracts, 57 methods |
601
844
  | Sidebar GUI | Human | `gui-experimental.cjs` |
602
845
  | Web dashboard | Human | `startDashboardServer` (localhost, random/fixed port) |
603
846
 
604
847
  ## Localization
605
848
 
606
- User-visible text lives in flat JSON catalogs: `locales/ru.json` (default),
849
+ User-visible text lives in flat JSON catalogs: `locales/ru.json` (fallback),
607
850
  `locales/en.json` and `locales/zh.json`. Keys are dot-separated and grouped by surface —
608
851
  `gui.*`, `notify.*`, `tool.*`, `dryRun.*`, `matrix.*`, `schedule.*` — and all catalogs
609
852
  must have the same key set with non-empty values.
@@ -611,8 +854,9 @@ must have the same key set with non-empty values.
611
854
  `src/i18n.ts` loads the catalogs once and caches them. It exposes `t(key, params)`,
612
855
  `setLocale(locale)`, `messageIn(locale, key)` and `hasKey(key, locale)`. Lookup order is
613
856
  active locale → `en` → `ru` → the key itself, so a missing translation never renders as
614
- an empty string. The `locale` setting (`ru` default, `en`/`zh` optional, `auto` follows
615
- the OpenCode interface language) is applied immediately, without restarting OpenCode.
857
+ an empty string. The `locale` setting (`auto` default, follows the OpenCode interface
858
+ language; `ru`/`en`/`zh` are explicit choices) is applied immediately, without restarting
859
+ OpenCode.
616
860
  `auto` is resolved in the GUI through `ctx.locale.locale()` with BCP 47 prefix mapping
617
861
  (`zh-CN` → `zh`, `en-GB` → `en`); the resolved value is sent to the server as `uiLocale`,
618
862
  because the server process cannot see the window. The sidebar GUI embeds the catalogs at
@@ -641,6 +885,15 @@ Rules:
641
885
  ## Security model
642
886
 
643
887
  - The dashboard has **no authentication** and binds to localhost. Do not expose it.
888
+ - **Dashboard XSS hardening (B3):** every dynamic value passes through `esc()` before
889
+ reaching text or attribute context; it escapes `&`, `<`, `>`, `"` and `'` (the old
890
+ `div.innerHTML` trick left quotes intact). `GET /` also sends
891
+ `Content-Security-Policy: default-src 'none'; script-src 'nonce-…'; style-src
892
+ 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none';
893
+ form-action 'none'; frame-ancestors 'none'; object-src 'none'`. Both inline scripts
894
+ carry a per-response nonce (16 random bytes, base64). `test-dashboard-xss.mjs`
895
+ extracts the shipped `esc()` from the served page and checks quote/angle-bracket
896
+ payloads in text, `title=` and `data-*=` contexts, plus nonce/CSP consistency.
644
897
  - A job definition is **code**: prompts, hooks, Quality Gates and wrappers all execute
645
898
  with your user privileges. Treat task creation like granting shell access.
646
899
  - `allowedTools` / `deniedTools` are **enforced at the run-wrapper level** (Sprint 29.2).
@@ -740,7 +993,7 @@ after the agent with the user's privileges and are not filtered by tool policy.
740
993
 
741
994
  ## Mission runtime и гибридные входы (план 38–40)
742
995
 
743
- > Статус: спека. Что уже в коде, а что нет — [ROADMAP.md](../ROADMAP.md) §1.
996
+ > Статус: ad-hoc вход реализован (AB-8); internal-оркестрация и `gate_outcomes` — план 40. Что уже в коде — [ROADMAP.md](../ROADMAP.md) §1.
744
997
 
745
998
  Система гибридная: ядро (**mission runtime**) не знает про планировщик ОС.
746
999
  Планировщик — адаптер входа, регистрация опциональна.
@@ -749,7 +1002,7 @@ after the agent with the user's privileges and are not filtered by tool policy.
749
1002
 
750
1003
  | Класс | Вход | Регистрация в ОС | Реализация |
751
1004
  |---|---|---|---|
752
- | Ad-hoc | `run_mission` / CLI / GUI / RPC | нет | план 38 |
1005
+ | Ad-hoc | `run_mission` / CLI `run` / GUI / RPC | нет | есть: `core/mission.ts` (AB-8) |
753
1006
  | Внутренний | chain / DAG / retry / escalation | нет | сейчас через `backend.runTask` + force-маркер; план 40 — напрямую в runtime |
754
1007
  | Registered | cron / once / file / git / mcp-event / webhook | да (cron/once) | есть: `core/scheduler/*`, `file-watcher`, `git-trigger`, `integrations` |
755
1008
 
@@ -757,9 +1010,9 @@ after the agent with the user's privileges and are not filtered by tool policy.
757
1010
 
758
1011
  | Объект | Содержимое | Таблица |
759
1012
  |---|---|---|
760
- | Миссия | цель + scope + gate-спека + safety + бюджет | `missions` (план 38, опциональный шаблон) |
1013
+ | Миссия | цель + scope + gate-спека + safety + бюджет | `runs` metadata (AB-8); шаблон `missions` — план 38 |
761
1014
  | Задача | миссия-шаблон + триггер | `tasks` (есть) |
762
- | Запуск | durable-исполнение: шаги, попытки, вердикты | `runs` / `run_steps` (есть, SCHEMA_VERSION 7) |
1015
+ | Запуск | durable-исполнение: шаги, попытки, вердикты | `runs` / `run_steps` (есть, SCHEMA_VERSION 12) |
763
1016
  | Исход гейта | вердикт + provenance + экономика | `gate_outcomes` (план 40) |
764
1017
 
765
1018
  ### Путь исполнения (целевой)
@@ -15,7 +15,7 @@
15
15
 
16
16
  | Возможность | V1 (`>=1.18.29`) | V2 (`>=2.2.7`) | Комментарий |
17
17
  |---|---|---|---|
18
- | 26 инструментов агента | да, `tool()`; без `options.codemode` | да, `ctx.tool.transform`; `options: { codemode: true }` | имена, схемы и обработчики совпадают |
18
+ | 30 инструментов агента | да, `tool()`; без `options.codemode` | да, `ctx.tool.transform`; `options: { codemode: true }` | имена, схемы и обработчики совпадают |
19
19
  | Хуки (tool / session / event / config) | да, строковые ключи в `Hooks` | да, типизированные домены `ctx.*` | API есть, но плагин его **не использует** — см. ниже |
20
20
  | TUI-панель «Планировщик» | да, `src/tui-v1.tsx`; маршрут `/scheduler` + снимок в сайдбаре | да, `src/tui.tsx`; reactive store | **обе линии**, один модуль `./tui` |
21
21
  | GUI-панель | **нет** | да | subpath `@opencode/plugin/gui` в V1 отсутствует |
@@ -102,7 +102,7 @@ SDK — совместимость мажора проверяется в `test-
102
102
 
103
103
  | Проверка | Что покрывает |
104
104
  |---|---|
105
- | `test-dual-entry.mjs` | форму default export (`id`, `setup`, `server`), `createV1Hooks` → `tool` + `dispose`, 26 инструментов, совпадение имён с V2-реестром `createToolHandlers`, кросс-версию zod |
105
+ | `test-dual-entry.mjs` | форму default export (`id`, `setup`, `server`), `createV1Hooks` → `tool` + `dispose`, 30 инструментов, совпадение имён с V2-реестром `createToolHandlers`, кросс-версию zod |
106
106
  | `test-v1-integration.mjs` | реальный V1-путь: `server({ directory })`, изолированные `OPENCODE_SCHEDULER_HOME` и порт дашборда, три read-only инструмента, повторный `dispose` |
107
107
  | `test-docs.mjs` | контракт в документации и коде: `exports["./tui"]`, `sidebar_content`, ключи `plugin`/`plugins`, инварианты состояния |
108
108
  | CI `compat-v1` / `compat-v2` | отдельные jobs: V1 SDK `1.19.x` и V2 SDK `2.3.0` (устанавливается поверх `2.2.7`), не блокируют матрицу трёх ОС |
package/docs/CONCEPT.md CHANGED
@@ -70,8 +70,14 @@
70
70
 
71
71
  ## 4. Цель и критерии приёмки (north star)
72
72
 
73
- Четыре столпа. При конфликте порядок:
74
- **надёжно > приватно > дёшево > краткосрочные фичи**; explore — управляемая
73
+ Четыре столпа — **Надёжно, Приватно, Дёшево, Компаундится** (таблица ниже).
74
+ Это независимый список свойств системы, а не формула приоритетов.
75
+
76
+ Формула приоритетов при конфликте — другая вещь:
77
+ **надёжно > приватно > дёшево > краткосрочные фичи**. Её последний член —
78
+ **не четвёртый столп**: это то, чем жертвуют в первую очередь. Четвёртый
79
+ столп «Компаундится» не противопоставлен «краткосрочным фичам», а накапливается
80
+ за счёт того, что краткосрочные фичи откладываются. `explore` — управляемая
75
81
  инвестиция «дёшево-сегодня» в «компаунд-завтра».
76
82
 
77
83
  | Столп | Что значит | Метрика |
@@ -263,8 +269,16 @@ local first_pass_rate → больше экономия и сильнее ада
263
269
  - Датасет для весов копится медленно → staged-прокачка, не обещать онлайн-LoRA.
264
270
  - Prompt-injection даже при гейте → гейт + аудит + allowedTools как пол;
265
271
  внешний контент недоверенный по умолчанию; критичное — человеку.
266
- - **Reward hacking**: агент правит тесты/гейт → snapshot + hash + права вне
267
- write-scope; обязательный тест-атака в CI.
272
+ - **Reward hacking**: агент правит тесты/гейт → при создании задачи
273
+ `src/core/gate-integrity.ts` фиксирует snapshot входов гейта (команда/файл
274
+ хука, prompt, таймаут) в `PLUGIN_DIR/gate-snapshots/` с SHA-256; обе обёртки
275
+ проверяют хэш непосредственно перед запуском гейта. Расхождение или отсутствие
276
+ snapshot → fail-closed: гейт не выполняется, запуск считается ошибкой.
277
+ Обязательная тест-атака (подмена gate-команды/хука) есть в `npm test` и в CI
278
+ на Windows, macOS и Linux. Мера защищает **определение гейта**, а не исходники
279
+ репозитория, которые гейт проверяет: подмена самих тестов агентом эту проверку
280
+ не обходит, но и не детектируется ею. Права вне write-scope и `gate_outcomes`
281
+ с хэш-цепочкой остаются планом. Status: 🔄 (реализована базовая мера).
268
282
  - **Irreversible до вердикта** → отложенные эффекты (intents) и компенсация.
269
283
  - **Хеш-цепочка ledger** — tamper-evident аудит, **не** граница безопасности;
270
284
  граница — права и изоляция.