agent-steward 0.0.4 → 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 (190) hide show
  1. package/CHANGELOG.md +134 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +52 -7
  4. package/ROADMAP-STRATEGY.md +21 -18
  5. package/ROADMAP.md +140 -159
  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/execution.d.ts +203 -0
  10. package/dist/core/execution.d.ts.map +1 -0
  11. package/dist/core/execution.js +309 -0
  12. package/dist/core/gate-integrity.d.ts +35 -0
  13. package/dist/core/gate-integrity.d.ts.map +1 -0
  14. package/dist/core/gate-integrity.js +132 -0
  15. package/dist/core/git-trigger.d.ts.map +1 -1
  16. package/dist/core/git-trigger.js +14 -2
  17. package/dist/core/guard-run.d.ts +4 -0
  18. package/dist/core/guard-run.d.ts.map +1 -0
  19. package/dist/core/guard-run.js +101 -0
  20. package/dist/core/guard.d.ts +52 -0
  21. package/dist/core/guard.d.ts.map +1 -0
  22. package/dist/core/guard.js +362 -0
  23. package/dist/core/lock.d.ts +41 -0
  24. package/dist/core/lock.d.ts.map +1 -1
  25. package/dist/core/lock.js +141 -29
  26. package/dist/core/matrix.d.ts.map +1 -1
  27. package/dist/core/matrix.js +75 -15
  28. package/dist/core/mission.d.ts +83 -0
  29. package/dist/core/mission.d.ts.map +1 -0
  30. package/dist/core/mission.js +334 -0
  31. package/dist/core/pipeline-apply.d.ts +38 -0
  32. package/dist/core/pipeline-apply.d.ts.map +1 -0
  33. package/dist/core/pipeline-apply.js +117 -0
  34. package/dist/core/pipeline-io.d.ts +13 -0
  35. package/dist/core/pipeline-io.d.ts.map +1 -0
  36. package/dist/core/pipeline-io.js +64 -0
  37. package/dist/core/pipeline-map.d.ts +46 -0
  38. package/dist/core/pipeline-map.d.ts.map +1 -0
  39. package/dist/core/pipeline-map.js +196 -0
  40. package/dist/core/pipeline-spec.d.ts +109 -0
  41. package/dist/core/pipeline-spec.d.ts.map +1 -0
  42. package/dist/core/pipeline-spec.js +554 -0
  43. package/dist/core/ps-wrapper.d.ts +19 -2
  44. package/dist/core/ps-wrapper.d.ts.map +1 -1
  45. package/dist/core/ps-wrapper.js +250 -62
  46. package/dist/core/record-history.d.ts.map +1 -1
  47. package/dist/core/record-history.js +130 -29
  48. package/dist/core/router/rules.d.ts.map +1 -1
  49. package/dist/core/router/rules.js +6 -0
  50. package/dist/core/scheduler/linux.d.ts +8 -1
  51. package/dist/core/scheduler/linux.d.ts.map +1 -1
  52. package/dist/core/scheduler/linux.js +34 -9
  53. package/dist/core/scheduler/mac.d.ts +44 -2
  54. package/dist/core/scheduler/mac.d.ts.map +1 -1
  55. package/dist/core/scheduler/mac.js +126 -15
  56. package/dist/core/scheduler/windows.d.ts.map +1 -1
  57. package/dist/core/scheduler/windows.js +15 -12
  58. package/dist/core/structured-log.d.ts +7 -1
  59. package/dist/core/structured-log.d.ts.map +1 -1
  60. package/dist/core/worktree-run.d.ts +4 -0
  61. package/dist/core/worktree-run.d.ts.map +1 -0
  62. package/dist/core/worktree-run.js +164 -0
  63. package/dist/core/worktree.d.ts +115 -0
  64. package/dist/core/worktree.d.ts.map +1 -0
  65. package/dist/core/worktree.js +462 -0
  66. package/dist/core/wrappers/bash.d.ts +17 -0
  67. package/dist/core/wrappers/bash.d.ts.map +1 -1
  68. package/dist/core/wrappers/bash.js +175 -24
  69. package/dist/db/capability-repo.d.ts +43 -2
  70. package/dist/db/capability-repo.d.ts.map +1 -1
  71. package/dist/db/capability-repo.js +96 -11
  72. package/dist/db/history-repo.d.ts +38 -5
  73. package/dist/db/history-repo.d.ts.map +1 -1
  74. package/dist/db/history-repo.js +88 -25
  75. package/dist/db/metrics-repo.js +2 -2
  76. package/dist/db/recovery.d.ts.map +1 -1
  77. package/dist/db/recovery.js +5 -4
  78. package/dist/db/run-journal.d.ts +33 -5
  79. package/dist/db/run-journal.d.ts.map +1 -1
  80. package/dist/db/run-journal.js +78 -14
  81. package/dist/db/run-resume.d.ts +5 -0
  82. package/dist/db/run-resume.d.ts.map +1 -1
  83. package/dist/db/run-resume.js +9 -2
  84. package/dist/db/runs-repo.d.ts +19 -2
  85. package/dist/db/runs-repo.d.ts.map +1 -1
  86. package/dist/db/runs-repo.js +22 -6
  87. package/dist/db/schema.d.ts +2 -2
  88. package/dist/db/schema.d.ts.map +1 -1
  89. package/dist/db/schema.js +63 -2
  90. package/dist/history.d.ts +1 -1
  91. package/dist/history.d.ts.map +1 -1
  92. package/dist/i18n.d.ts +5 -0
  93. package/dist/i18n.d.ts.map +1 -1
  94. package/dist/i18n.js +11 -4
  95. package/dist/index.d.ts +136 -2
  96. package/dist/index.d.ts.map +1 -1
  97. package/dist/index.js +378 -14
  98. package/dist/notifications.d.ts +22 -0
  99. package/dist/notifications.d.ts.map +1 -1
  100. package/dist/notifications.js +36 -8
  101. package/dist/profiles.d.ts.map +1 -1
  102. package/dist/profiles.js +25 -4
  103. package/dist/rpc.d.ts +246 -0
  104. package/dist/rpc.d.ts.map +1 -1
  105. package/dist/rpc.js +117 -0
  106. package/dist/server.d.ts +15 -0
  107. package/dist/server.d.ts.map +1 -1
  108. package/dist/server.js +77 -18
  109. package/dist/settings.d.ts +2 -2
  110. package/dist/settings.d.ts.map +1 -1
  111. package/dist/settings.js +3 -3
  112. package/dist/shared/jobs-view.d.ts +1 -1
  113. package/dist/shared/jobs-view.d.ts.map +1 -1
  114. package/dist/shared/jobs-view.js +2 -0
  115. package/dist/task-transfer.d.ts +16 -0
  116. package/dist/task-transfer.d.ts.map +1 -1
  117. package/dist/task-transfer.js +16 -0
  118. package/docs/ARCHITECTURE.md +281 -65
  119. package/docs/COMPATIBILITY.md +2 -2
  120. package/docs/CONCEPT.md +18 -4
  121. package/docs/CROSS_PLATFORM.ru.md +20 -0
  122. package/docs/CROSS_PLATFORM.zh.md +18 -0
  123. package/docs/EXECUTION-LOOP.md +22 -7
  124. package/docs/FEATURES.md +65 -4
  125. package/docs/FEATURES.zh.md +52 -4
  126. package/docs/MIGRATION.md +2 -2
  127. package/docs/PIPELINE.md +293 -0
  128. package/docs/README.ru.md +42 -3
  129. package/docs/README.zh.md +43 -3
  130. package/docs/SAFETY.md +23 -3
  131. package/gui-experimental.cjs +9 -8
  132. package/locales/en.json +17 -1
  133. package/locales/ru.json +17 -1
  134. package/locales/zh.json +17 -1
  135. package/opencode.pipeline.yaml +35 -0
  136. package/package.json +23 -4
  137. package/scripts/test-home.mjs +83 -0
  138. package/src/cli.ts +412 -0
  139. package/src/core/dry-run.ts +2 -2
  140. package/src/core/execution.ts +538 -0
  141. package/src/core/file-watcher.ts +2 -2
  142. package/src/core/gate-integrity.ts +160 -0
  143. package/src/core/git-trigger.ts +18 -5
  144. package/src/core/guard-run.ts +119 -0
  145. package/src/core/guard.ts +431 -0
  146. package/src/core/lock.ts +178 -37
  147. package/src/core/matrix.ts +95 -50
  148. package/src/core/mission.ts +485 -0
  149. package/src/core/native-notify.ts +1 -1
  150. package/src/core/pipeline-apply.ts +158 -0
  151. package/src/core/pipeline-io.ts +79 -0
  152. package/src/core/pipeline-map.ts +264 -0
  153. package/src/core/pipeline-spec.ts +775 -0
  154. package/src/core/ps-wrapper.ts +263 -63
  155. package/src/core/record-history.ts +164 -77
  156. package/src/core/router/rules.ts +6 -0
  157. package/src/core/schedule-gate.ts +1 -1
  158. package/src/core/scheduler/at-fallback.ts +1 -1
  159. package/src/core/scheduler/linux.ts +40 -11
  160. package/src/core/scheduler/logs.ts +2 -2
  161. package/src/core/scheduler/mac.ts +174 -14
  162. package/src/core/scheduler/registry.ts +2 -2
  163. package/src/core/scheduler/windows.ts +19 -15
  164. package/src/core/secrets.ts +8 -8
  165. package/src/core/structured-log.ts +22 -5
  166. package/src/core/telegram.ts +2 -2
  167. package/src/core/triage-worker.ts +7 -7
  168. package/src/core/triage.ts +2 -2
  169. package/src/core/worktree-run.ts +199 -0
  170. package/src/core/worktree.ts +600 -0
  171. package/src/core/wrappers/bash.ts +190 -23
  172. package/src/db/capability-repo.ts +127 -10
  173. package/src/db/history-repo.ts +129 -22
  174. package/src/db/metrics-repo.ts +2 -2
  175. package/src/db/recovery.ts +5 -4
  176. package/src/db/run-journal.ts +100 -13
  177. package/src/db/run-resume.ts +17 -1
  178. package/src/db/runs-repo.ts +36 -6
  179. package/src/db/schema.ts +65 -2
  180. package/src/gui.tsx +177 -13
  181. package/src/history.ts +1 -1
  182. package/src/i18n.ts +12 -4
  183. package/src/index.ts +524 -4
  184. package/src/notifications.ts +38 -8
  185. package/src/profiles.ts +26 -4
  186. package/src/rpc.ts +128 -0
  187. package/src/server.ts +94 -18
  188. package/src/settings.ts +5 -5
  189. package/src/shared/jobs-view.ts +3 -1
  190. package/src/task-transfer.ts +31 -0
@@ -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
@@ -151,23 +302,34 @@ cloud model — without involving a model for known step types.
151
302
 
152
303
  ### Слой 2 — Capability Map (0 токенов, быстро)
153
304
 
154
- SQLite-таблица `task_type → model / success_rate / avg_cost / avg_time /
155
- 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` → эскалация в облако или «нужно ревью»
156
311
 
157
- - `success_rate ≥ 0.85` → маршрут локально
158
- - `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` позволяет переопределить это для конкретного исхода.
159
318
 
160
319
  Это и есть learning loop: роутер учится на гейтах и становится точнее без затрат
161
320
  токенов на само решение.
162
321
 
163
- Реализация (Спринт 36.5.b): `src/db/capability-repo.ts`, таблица `capability_map`
164
- (`SCHEMA_VERSION = 6`). `recordCapabilityOutcome` обновляет счётчики, считает
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`), кумулятивный
165
325
  `success_rate` и скользящие средние стоимости/времени, хранит `last_10_runs`
166
326
  (JSON, новые справа). `decideCapabilityRoute` решает по правилам:
167
327
  меньше `MIN_RUNS_FOR_DECISION = 3` исходов → `explore` (решает слой 3),
168
- `≥ 0.85` → `local`, `≤ 0.30` → `cloud`, между порогами → `review`. Пороги
169
- передаются параметром, поэтому политика меняется без миграции данных.
170
- Покрытие — `test-capability-map.mjs`.
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`.
171
333
 
172
334
  ### Слой 3 — локальная модель (только декомпозиция и неоднозначность)
173
335
 
@@ -175,7 +337,11 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
175
337
  1. Разбивает миссию на шаги с типами (планирование);
176
338
  2. Разрешает неоднозначность (Explore-режим, когда в Capability Map нет данных).
177
339
 
178
- После этого каждый шаг проходит через Слой 1 и Слой 2.
340
+ После этого каждый шаг проходит через Слой 1 и Слой 2. Слой 3 — **декомпозиция
341
+ миссии**, а не маршрутизация шага: он решает, *что* делать, но никогда не
342
+ выбирает, *где* исполнять. `RouteSource` в `src/core/router/dispatch.ts:15`
343
+ принимает только `static` и `capability` — значения `model`/`planner` в нём
344
+ нет, и `routeStep` не импортирует `planner`.
179
345
 
180
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`.
181
347
 
@@ -193,7 +359,7 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
193
359
 
194
360
  | Path | Role |
195
361
  | --- | --- |
196
- | `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 |
197
363
  | `src/rpc.ts` | JSON-schema contracts for every RPC method |
198
364
  | `src/gui.tsx` | OpenCode sidebar panel (SolidJS, built to `gui-experimental.cjs`) |
199
365
  | `src/server.ts` | Local web dashboard HTTP server and HTML rendering |
@@ -203,7 +369,7 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
203
369
  | `src/workspaces.ts` | Workspace registry and path validation; env pairs and `.env` file resolution with secret masking |
204
370
  | `src/templates.ts` | Reusable task templates |
205
371
  | `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` |
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` |
207
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 |
208
374
  | `src/core/telegram.ts` | Telegram Bot API `sendMessage`: parse-mode escaping, dashboard link, token validation and masking |
209
375
  | `src/core/native-notify.ts` | Native OS notifications: Windows Toast (PowerShell/WinRT), macOS `osascript`, Linux `notify-send`; no external dependency |
@@ -227,7 +393,7 @@ last_10_runs`. Обучается на исходах гейта (CONCEPT §9 le
227
393
  | `src/core/schedule-gate.ts` | Wrapper-side gate: cron re-check (poll mode), window postpone, defer-file |
228
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 |
229
395
  | `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 |
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 |
231
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 |
232
398
  | `src/core/router/dispatch.ts` | Router assembly: `routeStep` runs layer 1 then layer 2 and returns transport/executor, never imports the planner |
233
399
  | `src/core/router/escalation.ts` | Gate failure escalation `local → cloud → review → blocked` by pure transition table, no DB, no model |
@@ -259,7 +425,7 @@ enforced:
259
425
  | --- | --- |
260
426
  | Working directory | Task `workingDirectory`, or the workspace path, or the plugin directory |
261
427
  | 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` |
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) |
263
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 |
264
430
  | No overlap | Lock file per task; a second start exits immediately and records `skipped` |
265
431
  | Pre-flight | `beforeScript`; non-zero exit marks `preFlight` as failed |
@@ -268,6 +434,26 @@ enforced:
268
434
  | Logging | Append-only log per task under `logs/` |
269
435
  | History | Calls the recorder with `--start` and `--finish` |
270
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
+
271
457
  Windows uses PowerShell and `.cmd` shims; POSIX uses bash. Both wrappers are generated
272
458
  from templates so the policy stays identical across platforms.
273
459
 
@@ -278,6 +464,12 @@ from templates so the policy stays identical across platforms.
278
464
  pre/post-flight results, the chained next task, workspace and tool restrictions.
279
465
  `metrics` holds per-task counters and totals.
280
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
+
281
473
  If the host or the machine dies mid-run, the row stays in `running`. On the next
282
474
  plugin activation, `db/recovery.ts` marks stale `running` rows as `error`, so the UI
283
475
  never shows a permanently running task.
@@ -383,7 +575,7 @@ the whole plugin directory (database, logs, locks, wrappers, prompts) with
383
575
 
384
576
  Schema evolution is additive: `applySchema` runs `CREATE TABLE IF NOT EXISTS` on every
385
577
  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
578
+ never requires a manual migration. `SCHEMA_VERSION` (currently `10`) is stored in
387
579
  `PRAGMA user_version`; incremental steps live in `MIGRATIONS`.
388
580
 
389
581
  ### Durable run state (Sprint 36.1)
@@ -413,6 +605,20 @@ marks any `running` steps left after a process crash as `failed` — preserving
413
605
  SQLite runs in WAL mode with `synchronous = NORMAL`, so a committed transition
414
606
  survives a `kill -9` (only the last in-flight commit can be lost with a power cut).
415
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
+
416
622
  ### Resume from the middle (Sprint 36.2)
417
623
 
418
624
  `src/db/run-resume.ts` continues a run after a crash. `run_steps.position`
@@ -595,15 +801,15 @@ resume preparation, rejection of a repeated resume, end-to-end comment delivery
595
801
 
596
802
  | Interface | Audience | Entry point |
597
803
  | --- | --- | --- |
598
- | Agent tools | AI agent | 26 tools registered via `ctx.tool.transform` |
804
+ | Agent tools | AI agent | 29 tools registered via `ctx.tool.transform` |
599
805
  | Agent skill | AI agent | `skills/scheduled-job-best-practices` |
600
- | RPC | Sidebar GUI | `src/rpc.ts` contracts, 47 methods |
806
+ | RPC | Sidebar GUI | `src/rpc.ts` contracts, 57 methods |
601
807
  | Sidebar GUI | Human | `gui-experimental.cjs` |
602
808
  | Web dashboard | Human | `startDashboardServer` (localhost, random/fixed port) |
603
809
 
604
810
  ## Localization
605
811
 
606
- 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),
607
813
  `locales/en.json` and `locales/zh.json`. Keys are dot-separated and grouped by surface —
608
814
  `gui.*`, `notify.*`, `tool.*`, `dryRun.*`, `matrix.*`, `schedule.*` — and all catalogs
609
815
  must have the same key set with non-empty values.
@@ -611,8 +817,9 @@ must have the same key set with non-empty values.
611
817
  `src/i18n.ts` loads the catalogs once and caches them. It exposes `t(key, params)`,
612
818
  `setLocale(locale)`, `messageIn(locale, key)` and `hasKey(key, locale)`. Lookup order is
613
819
  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.
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.
616
823
  `auto` is resolved in the GUI through `ctx.locale.locale()` with BCP 47 prefix mapping
617
824
  (`zh-CN` → `zh`, `en-GB` → `en`); the resolved value is sent to the server as `uiLocale`,
618
825
  because the server process cannot see the window. The sidebar GUI embeds the catalogs at
@@ -641,6 +848,15 @@ Rules:
641
848
  ## Security model
642
849
 
643
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.
644
860
  - A job definition is **code**: prompts, hooks, Quality Gates and wrappers all execute
645
861
  with your user privileges. Treat task creation like granting shell access.
646
862
  - `allowedTools` / `deniedTools` are **enforced at the run-wrapper level** (Sprint 29.2).
@@ -740,7 +956,7 @@ after the agent with the user's privileges and are not filtered by tool policy.
740
956
 
741
957
  ## Mission runtime и гибридные входы (план 38–40)
742
958
 
743
- > Статус: спека. Что уже в коде, а что нет — [ROADMAP.md](../ROADMAP.md) §1.
959
+ > Статус: ad-hoc вход реализован (AB-8); internal-оркестрация и `gate_outcomes` — план 40. Что уже в коде — [ROADMAP.md](../ROADMAP.md) §1.
744
960
 
745
961
  Система гибридная: ядро (**mission runtime**) не знает про планировщик ОС.
746
962
  Планировщик — адаптер входа, регистрация опциональна.
@@ -749,7 +965,7 @@ after the agent with the user's privileges and are not filtered by tool policy.
749
965
 
750
966
  | Класс | Вход | Регистрация в ОС | Реализация |
751
967
  |---|---|---|---|
752
- | Ad-hoc | `run_mission` / CLI / GUI / RPC | нет | план 38 |
968
+ | Ad-hoc | `run_mission` / CLI `run` / GUI / RPC | нет | есть: `core/mission.ts` (AB-8) |
753
969
  | Внутренний | chain / DAG / retry / escalation | нет | сейчас через `backend.runTask` + force-маркер; план 40 — напрямую в runtime |
754
970
  | Registered | cron / once / file / git / mcp-event / webhook | да (cron/once) | есть: `core/scheduler/*`, `file-watcher`, `git-trigger`, `integrations` |
755
971
 
@@ -757,9 +973,9 @@ after the agent with the user's privileges and are not filtered by tool policy.
757
973
 
758
974
  | Объект | Содержимое | Таблица |
759
975
  |---|---|---|
760
- | Миссия | цель + scope + gate-спека + safety + бюджет | `missions` (план 38, опциональный шаблон) |
976
+ | Миссия | цель + scope + gate-спека + safety + бюджет | `runs` metadata (AB-8); шаблон `missions` — план 38 |
761
977
  | Задача | миссия-шаблон + триггер | `tasks` (есть) |
762
- | Запуск | durable-исполнение: шаги, попытки, вердикты | `runs` / `run_steps` (есть, SCHEMA_VERSION 7) |
978
+ | Запуск | durable-исполнение: шаги, попытки, вердикты | `runs` / `run_steps` (есть, SCHEMA_VERSION 10) |
763
979
  | Исход гейта | вердикт + provenance + экономика | `gate_outcomes` (план 40) |
764
980
 
765
981
  ### Путь исполнения (целевой)
@@ -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
+ | 29 инструментов агента | да, `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`, 29 инструментов, совпадение имён с 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
  граница — права и изоляция.
@@ -54,6 +54,13 @@ interface SchedulerBackend {
54
54
  - Обёртка: `run-task.ps1` + персональный `run-<name>.cmd` в `%APPDATA%\opencode\agent-steward\wrapper`. Legacy-каталог `%APPDATA%\opencode\windows-scheduler` переносится при первом запуске.
55
55
  - Логи: `%APPDATA%\opencode\agent-steward\logs\<name>.log`.
56
56
  - cron конвертируется в schtasks (`convertCronToSchTasks`) — поддерживается тот же набор шаблонов.
57
+ - Промпт передаётся в `opencode run` после `--`, поэтому промпт, начинающийся с `-`,
58
+ не может быть принят за флаг. Обёртка отклоняет промпты длиннее 30 000 символов
59
+ до `CreateProcess` (лимит командной строки — 32 767 символов).
60
+ - Сторож таймаута: дерево процессов читается через `Get-CimInstance`; при сбое CIM
61
+ или пустом результате обёртка переходит на `Get-WmiObject`, затем проверяет
62
+ `tasklist`/`Get-Process`. Если данных о дереве нет, срабатывает fail-closed:
63
+ `taskkill /F /T /PID <root>`, чтобы внуки не остались работать.
57
64
 
58
65
  ### Linux
59
66
  - Задачи живут в управляемом блоке `crontab`:
@@ -70,19 +77,32 @@ interface SchedulerBackend {
70
77
  - Полный cron-синтаксис (в отличие от Windows), т.к. crontab понимает его нативно.
71
78
  - Разовый запуск (`once`): `at -t`; если `at` не установлен, плагин ставит отвязанный процесс `sleep && команда` (`pid:<pid>` в реестре). Fallback не переживает перезагрузку — для надёжности установите пакет `at`.
72
79
  - Удаление/пересборка — только своего блока, остальные строки `crontab` не трогаются.
80
+ - Незакрытый блок плагина (маркер начала без конца) — fail-closed: плагин сообщает об ошибке и не перезаписывает crontab, поэтому строки пользователя после маркера не теряются.
73
81
 
74
82
  ### macOS
75
83
  - Задачи — LaunchAgent-плисты `~/Library/LaunchAgents/com.opencode.scheduler.<name>.plist`.
76
84
  - Расписание: `StartInterval` для `* * * * *` и `*/N`, `StartCalendarInterval` для `M * * * *`,
77
85
  `M H * * *`, `M H * * D`.
78
86
  - Пауза = `launchctl unload -w`, возобновление = `launchctl load -w`.
87
+ - Установка приостановленной задачи пишет plist, но не вызывает `load -w`
88
+ (он снял бы паузу); `unload -w` оставляет агент выключенным и после входа.
89
+ - Ошибки `launchctl load` не глотаются: ошибка установки/возобновления содержит
90
+ команду, exit code и stderr (например, `Invalid property list` у битого plist).
79
91
  - Обёртка — тот же `.sh`, что и на Linux; пути конфигов:
80
92
  `~/.config/opencode/agent-steward/` (или `$XDG_CONFIG_HOME`).
81
93
 
82
94
  ### Общая POSIX-обёртка (`.sh`)
83
95
  - `cd` в рабочую директорию, `opencode run` с промптом из файла.
96
+ Промпт идёт после `--`, поэтому ведущий `-` не считается опцией.
97
+ - Backstop argv отклоняет `PROMPT_BYTES >= 131072`: `MAX_ARG_STRLEN` в Linux
98
+ включает завершающий NUL, поэтому полезных данных помещается максимум 131 071 байт.
84
99
  - Логи пишутся в файл через `>>` и дублируются метками времени.
85
100
  - Блокировка через атомарный `mkdir` — защита от параллельных запусков.
101
+ - Node, PS и bash пишут владельца lock как `<pid>-<iso>`; старые форматы
102
+ `<iso>|<pid>` (PS) и голый `<pid>` тоже читаются, поэтому живой lock не
103
+ вытесняется другой средой исполнения.
104
+ - При старте плагин читает владельца и из `<task>.lock`, и из `<task>.lock.d/pid`:
105
+ каталог lock вытесняется только если PID мёртв или отсутствует; возраст — fallback.
86
106
  - Таймаут: дочерний процесс + watchdog (`TERM`, затем `KILL`).
87
107
  - Quality Gate: `bash -lc "<команда>"` (аналог `cmd.exe /c` на Windows).
88
108
  - Метрики: `node "<record-history.js>" <task> <status> <started> <duration> <error> "-" "-"` —