agent-steward 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/CHANGELOG.md +154 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +54 -9
  4. package/ROADMAP-STRATEGY.md +23 -20
  5. package/ROADMAP.md +140 -143
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +351 -0
  9. package/dist/core/dlq-api.d.ts +44 -0
  10. package/dist/core/dlq-api.d.ts.map +1 -0
  11. package/dist/core/dlq-api.js +68 -0
  12. package/dist/core/dry-run.d.ts.map +1 -1
  13. package/dist/core/dry-run.js +18 -1
  14. package/dist/core/execution.d.ts +203 -0
  15. package/dist/core/execution.d.ts.map +1 -0
  16. package/dist/core/execution.js +309 -0
  17. package/dist/core/gate-integrity.d.ts +35 -0
  18. package/dist/core/gate-integrity.d.ts.map +1 -0
  19. package/dist/core/gate-integrity.js +132 -0
  20. package/dist/core/git-trigger.d.ts.map +1 -1
  21. package/dist/core/git-trigger.js +14 -2
  22. package/dist/core/guard-run.d.ts +4 -0
  23. package/dist/core/guard-run.d.ts.map +1 -0
  24. package/dist/core/guard-run.js +101 -0
  25. package/dist/core/guard.d.ts +52 -0
  26. package/dist/core/guard.d.ts.map +1 -0
  27. package/dist/core/guard.js +362 -0
  28. package/dist/core/lock.d.ts +61 -4
  29. package/dist/core/lock.d.ts.map +1 -1
  30. package/dist/core/lock.js +213 -26
  31. package/dist/core/matrix.d.ts.map +1 -1
  32. package/dist/core/matrix.js +75 -15
  33. package/dist/core/mission.d.ts +83 -0
  34. package/dist/core/mission.d.ts.map +1 -0
  35. package/dist/core/mission.js +334 -0
  36. package/dist/core/one-shot.d.ts +5 -1
  37. package/dist/core/one-shot.d.ts.map +1 -1
  38. package/dist/core/one-shot.js +33 -8
  39. package/dist/core/opencode-cli.d.ts +28 -0
  40. package/dist/core/opencode-cli.d.ts.map +1 -0
  41. package/dist/core/opencode-cli.js +74 -0
  42. package/dist/core/opencode-models.d.ts +62 -0
  43. package/dist/core/opencode-models.d.ts.map +1 -0
  44. package/dist/core/opencode-models.js +277 -0
  45. package/dist/core/pipeline-apply.d.ts +38 -0
  46. package/dist/core/pipeline-apply.d.ts.map +1 -0
  47. package/dist/core/pipeline-apply.js +117 -0
  48. package/dist/core/pipeline-io.d.ts +13 -0
  49. package/dist/core/pipeline-io.d.ts.map +1 -0
  50. package/dist/core/pipeline-io.js +64 -0
  51. package/dist/core/pipeline-map.d.ts +46 -0
  52. package/dist/core/pipeline-map.d.ts.map +1 -0
  53. package/dist/core/pipeline-map.js +196 -0
  54. package/dist/core/pipeline-spec.d.ts +109 -0
  55. package/dist/core/pipeline-spec.d.ts.map +1 -0
  56. package/dist/core/pipeline-spec.js +554 -0
  57. package/dist/core/ps-wrapper.d.ts +19 -2
  58. package/dist/core/ps-wrapper.d.ts.map +1 -1
  59. package/dist/core/ps-wrapper.js +261 -63
  60. package/dist/core/record-history.d.ts +15 -0
  61. package/dist/core/record-history.d.ts.map +1 -1
  62. package/dist/core/record-history.js +183 -58
  63. package/dist/core/router/dispatch.d.ts +36 -0
  64. package/dist/core/router/dispatch.d.ts.map +1 -0
  65. package/dist/core/router/dispatch.js +59 -0
  66. package/dist/core/router/escalation.d.ts +47 -0
  67. package/dist/core/router/escalation.d.ts.map +1 -0
  68. package/dist/core/router/escalation.js +87 -0
  69. package/dist/core/router/planner.d.ts +53 -0
  70. package/dist/core/router/planner.d.ts.map +1 -0
  71. package/dist/core/router/planner.js +113 -0
  72. package/dist/core/router/rules.d.ts +46 -0
  73. package/dist/core/router/rules.d.ts.map +1 -0
  74. package/dist/core/router/rules.js +91 -0
  75. package/dist/core/run-panel-api.d.ts +94 -0
  76. package/dist/core/run-panel-api.d.ts.map +1 -0
  77. package/dist/core/run-panel-api.js +169 -0
  78. package/dist/core/schedule-gate.js +5 -1
  79. package/dist/core/schedule-v2.d.ts +34 -0
  80. package/dist/core/schedule-v2.d.ts.map +1 -1
  81. package/dist/core/schedule-v2.js +91 -5
  82. package/dist/core/scheduler/at-fallback.d.ts +55 -2
  83. package/dist/core/scheduler/at-fallback.d.ts.map +1 -1
  84. package/dist/core/scheduler/at-fallback.js +135 -5
  85. package/dist/core/scheduler/linux.d.ts +18 -2
  86. package/dist/core/scheduler/linux.d.ts.map +1 -1
  87. package/dist/core/scheduler/linux.js +63 -20
  88. package/dist/core/scheduler/mac.d.ts +44 -2
  89. package/dist/core/scheduler/mac.d.ts.map +1 -1
  90. package/dist/core/scheduler/mac.js +126 -15
  91. package/dist/core/scheduler/posix.d.ts.map +1 -1
  92. package/dist/core/scheduler/posix.js +25 -1
  93. package/dist/core/scheduler/registry.d.ts +11 -0
  94. package/dist/core/scheduler/registry.d.ts.map +1 -1
  95. package/dist/core/scheduler/registry.js +83 -21
  96. package/dist/core/scheduler/run-now.d.ts +16 -0
  97. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  98. package/dist/core/scheduler/run-now.js +28 -0
  99. package/dist/core/scheduler/windows.d.ts.map +1 -1
  100. package/dist/core/scheduler/windows.js +15 -12
  101. package/dist/core/secrets.d.ts.map +1 -1
  102. package/dist/core/secrets.js +125 -28
  103. package/dist/core/session.d.ts.map +1 -1
  104. package/dist/core/session.js +18 -11
  105. package/dist/core/structured-log.d.ts +7 -1
  106. package/dist/core/structured-log.d.ts.map +1 -1
  107. package/dist/core/task-name.d.ts +24 -0
  108. package/dist/core/task-name.d.ts.map +1 -0
  109. package/dist/core/task-name.js +40 -0
  110. package/dist/core/worktree-run.d.ts +4 -0
  111. package/dist/core/worktree-run.d.ts.map +1 -0
  112. package/dist/core/worktree-run.js +164 -0
  113. package/dist/core/worktree.d.ts +115 -0
  114. package/dist/core/worktree.d.ts.map +1 -0
  115. package/dist/core/worktree.js +462 -0
  116. package/dist/core/wrappers/bash.d.ts +17 -0
  117. package/dist/core/wrappers/bash.d.ts.map +1 -1
  118. package/dist/core/wrappers/bash.js +224 -28
  119. package/dist/db/capability-repo.d.ts +124 -0
  120. package/dist/db/capability-repo.d.ts.map +1 -0
  121. package/dist/db/capability-repo.js +267 -0
  122. package/dist/db/history-repo.d.ts +46 -5
  123. package/dist/db/history-repo.d.ts.map +1 -1
  124. package/dist/db/history-repo.js +107 -25
  125. package/dist/db/index.d.ts +4 -0
  126. package/dist/db/index.d.ts.map +1 -1
  127. package/dist/db/index.js +39 -1
  128. package/dist/db/metrics-repo.js +2 -2
  129. package/dist/db/migrate.d.ts.map +1 -1
  130. package/dist/db/migrate.js +3 -1
  131. package/dist/db/recovery.d.ts.map +1 -1
  132. package/dist/db/recovery.js +5 -4
  133. package/dist/db/run-context.d.ts +103 -0
  134. package/dist/db/run-context.d.ts.map +1 -0
  135. package/dist/db/run-context.js +224 -0
  136. package/dist/db/run-dlq.d.ts +100 -0
  137. package/dist/db/run-dlq.d.ts.map +1 -0
  138. package/dist/db/run-dlq.js +191 -0
  139. package/dist/db/run-journal.d.ts +33 -5
  140. package/dist/db/run-journal.d.ts.map +1 -1
  141. package/dist/db/run-journal.js +78 -14
  142. package/dist/db/run-resume.d.ts +10 -2
  143. package/dist/db/run-resume.d.ts.map +1 -1
  144. package/dist/db/run-resume.js +39 -13
  145. package/dist/db/runs-repo.d.ts +32 -7
  146. package/dist/db/runs-repo.d.ts.map +1 -1
  147. package/dist/db/runs-repo.js +50 -11
  148. package/dist/db/schema.d.ts +2 -2
  149. package/dist/db/schema.d.ts.map +1 -1
  150. package/dist/db/schema.js +216 -3
  151. package/dist/db/settings-repo.d.ts +11 -0
  152. package/dist/db/settings-repo.d.ts.map +1 -1
  153. package/dist/db/settings-repo.js +25 -0
  154. package/dist/db/step-idempotency.d.ts +51 -0
  155. package/dist/db/step-idempotency.d.ts.map +1 -0
  156. package/dist/db/step-idempotency.js +136 -0
  157. package/dist/history.d.ts +1 -1
  158. package/dist/history.d.ts.map +1 -1
  159. package/dist/i18n.d.ts +5 -0
  160. package/dist/i18n.d.ts.map +1 -1
  161. package/dist/i18n.js +11 -4
  162. package/dist/index.d.ts +140 -6
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +480 -18
  165. package/dist/notifications.d.ts +22 -0
  166. package/dist/notifications.d.ts.map +1 -1
  167. package/dist/notifications.js +36 -8
  168. package/dist/profiles.d.ts.map +1 -1
  169. package/dist/profiles.js +25 -4
  170. package/dist/rpc.d.ts +924 -0
  171. package/dist/rpc.d.ts.map +1 -1
  172. package/dist/rpc.js +352 -0
  173. package/dist/server.d.ts +46 -0
  174. package/dist/server.d.ts.map +1 -1
  175. package/dist/server.js +172 -53
  176. package/dist/settings.d.ts +2 -2
  177. package/dist/settings.d.ts.map +1 -1
  178. package/dist/settings.js +3 -3
  179. package/dist/shared/jobs-view.d.ts +1 -1
  180. package/dist/shared/jobs-view.d.ts.map +1 -1
  181. package/dist/shared/jobs-view.js +2 -0
  182. package/dist/task-transfer.d.ts +16 -0
  183. package/dist/task-transfer.d.ts.map +1 -1
  184. package/dist/task-transfer.js +16 -0
  185. package/dist/types.d.ts.map +1 -1
  186. package/dist/types.js +7 -0
  187. package/dist/workspaces.d.ts +25 -3
  188. package/dist/workspaces.d.ts.map +1 -1
  189. package/dist/workspaces.js +43 -8
  190. package/docs/ARCHITECTURE.md +498 -58
  191. package/docs/COMPATIBILITY.md +2 -2
  192. package/docs/CONCEPT.md +185 -91
  193. package/docs/CROSS_PLATFORM.ru.md +20 -0
  194. package/docs/CROSS_PLATFORM.zh.md +18 -0
  195. package/docs/EXECUTION-LOOP.md +211 -0
  196. package/docs/FEATURES.md +65 -4
  197. package/docs/FEATURES.zh.md +52 -4
  198. package/docs/MIGRATION.md +2 -2
  199. package/docs/PIPELINE.md +293 -0
  200. package/docs/README.ru.md +44 -5
  201. package/docs/README.zh.md +46 -6
  202. package/docs/SAFETY.md +142 -0
  203. package/docs/SAVINGS.md +29 -0
  204. package/docs/SAVINGS.ru.md +29 -0
  205. package/docs/SAVINGS.zh.md +18 -0
  206. package/gui-experimental.cjs +9 -8
  207. package/locales/en.json +84 -1
  208. package/locales/ru.json +84 -1
  209. package/locales/zh.json +84 -1
  210. package/opencode.pipeline.yaml +35 -0
  211. package/package.json +46 -2
  212. package/scripts/audit-bundle.mjs +215 -0
  213. package/scripts/test-home.mjs +83 -0
  214. package/src/cli.ts +412 -0
  215. package/src/core/dlq-api.ts +98 -0
  216. package/src/core/dry-run.ts +27 -3
  217. package/src/core/execution.ts +538 -0
  218. package/src/core/file-watcher.ts +2 -2
  219. package/src/core/gate-integrity.ts +160 -0
  220. package/src/core/git-trigger.ts +18 -5
  221. package/src/core/guard-run.ts +119 -0
  222. package/src/core/guard.ts +431 -0
  223. package/src/core/lock.ts +244 -30
  224. package/src/core/matrix.ts +95 -50
  225. package/src/core/mission.ts +485 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/one-shot.ts +36 -8
  228. package/src/core/opencode-cli.ts +103 -0
  229. package/src/core/opencode-models.ts +315 -0
  230. package/src/core/pipeline-apply.ts +158 -0
  231. package/src/core/pipeline-io.ts +79 -0
  232. package/src/core/pipeline-map.ts +264 -0
  233. package/src/core/pipeline-spec.ts +775 -0
  234. package/src/core/ps-wrapper.ts +274 -64
  235. package/src/core/record-history.ts +229 -104
  236. package/src/core/router/dispatch.ts +94 -0
  237. package/src/core/router/escalation.ts +129 -0
  238. package/src/core/router/planner.ts +166 -0
  239. package/src/core/router/rules.ts +115 -0
  240. package/src/core/run-panel-api.ts +262 -0
  241. package/src/core/schedule-gate.ts +7 -3
  242. package/src/core/schedule-v2.ts +114 -5
  243. package/src/core/scheduler/at-fallback.ts +190 -5
  244. package/src/core/scheduler/linux.ts +72 -21
  245. package/src/core/scheduler/logs.ts +2 -2
  246. package/src/core/scheduler/mac.ts +174 -14
  247. package/src/core/scheduler/posix.ts +20 -1
  248. package/src/core/scheduler/registry.ts +107 -26
  249. package/src/core/scheduler/run-now.ts +32 -0
  250. package/src/core/scheduler/windows.ts +19 -15
  251. package/src/core/secrets.ts +131 -31
  252. package/src/core/session.ts +23 -10
  253. package/src/core/structured-log.ts +22 -5
  254. package/src/core/task-name.ts +67 -0
  255. package/src/core/telegram.ts +2 -2
  256. package/src/core/triage-worker.ts +7 -7
  257. package/src/core/triage.ts +2 -2
  258. package/src/core/worktree-run.ts +199 -0
  259. package/src/core/worktree.ts +600 -0
  260. package/src/core/wrappers/bash.ts +239 -27
  261. package/src/db/capability-repo.ts +402 -0
  262. package/src/db/history-repo.ts +151 -22
  263. package/src/db/index.ts +37 -1
  264. package/src/db/metrics-repo.ts +2 -2
  265. package/src/db/migrate.ts +3 -1
  266. package/src/db/recovery.ts +5 -4
  267. package/src/db/run-context.ts +370 -0
  268. package/src/db/run-dlq.ts +310 -0
  269. package/src/db/run-journal.ts +100 -13
  270. package/src/db/run-resume.ts +65 -13
  271. package/src/db/runs-repo.ts +66 -13
  272. package/src/db/schema.ts +218 -3
  273. package/src/db/settings-repo.ts +31 -0
  274. package/src/db/step-idempotency.ts +185 -0
  275. package/src/gui.tsx +692 -13
  276. package/src/history.ts +1 -1
  277. package/src/i18n.ts +12 -4
  278. package/src/index.ts +648 -8
  279. package/src/notifications.ts +38 -8
  280. package/src/profiles.ts +26 -4
  281. package/src/rpc.ts +379 -0
  282. package/src/server.ts +206 -54
  283. package/src/settings.ts +5 -5
  284. package/src/shared/jobs-view.ts +3 -1
  285. package/src/task-transfer.ts +31 -0
  286. package/src/types.ts +9 -0
  287. package/src/workspaces.ts +58 -9
@@ -0,0 +1,211 @@
1
+ # EXECUTION-LOOP — цикл v2.1 (спринты 38–43)
2
+
3
+ > Спека исполнительного цикла. North star: [CONCEPT.md](./CONCEPT.md) §6, §11.
4
+ > Безопасность: [SAFETY.md](./SAFETY.md). Статус компонентов: [ROADMAP.md](../ROADMAP.md) §1.
5
+
6
+ ## 1. Разрыв, который закрываем
7
+
8
+ Построено модулями (спринт 36), но не течёт в живом пути:
9
+
10
+ - **Два мира исполнения.** Планировщик: `wrapper → opencode run → record-history → history`. Durable DAG: `runs/run_steps → resumeRun`. Запланированная задача не создаёт durable-run.
11
+ - **Роутер не вызывается live.** `routeStep` / `decideCapabilityRoute` отсутствуют в `index.ts` / `record-history.ts`.
12
+ - **Карта не обучается.** `recordCapabilityOutcome` не вызывается из горячего пути.
13
+ - **Эскалация не живая.** `escalateAfterGate` есть, но провал гейта идёт в retry/chain.
14
+ - **Нет ad-hoc входа.** Любой запуск требует регистрации: `schedule_task` + `run_task_now`; `once` — это `at` / `schtasks ONCE` / launchd. Цепочки/DAG/retry обходят расписание костылём force-маркера. *(Закрыто в AB-8: `run_mission` / CLI `run` / GUI / RPC.)*
15
+
16
+ Не построено вовсе: ledger + provenance; класс риска и компиляция политики;
17
+ бюджет миссии; целостность гейта, flake-aware, отложенные эффекты; context
18
+ compilation, repo-map, инъекция scaffolding; worktree/sandbox, egress-контроль,
19
+ approvals-очередь.
20
+
21
+ Подтверждение:
22
+
23
+ ```bash
24
+ grep -rn "routeStep\|recordCapabilityOutcome\|escalateAfterGate\|planMission" \
25
+ src/index.ts src/core/record-history.ts src/core/ps-wrapper.ts src/core/wrappers/bash.ts
26
+ grep -rn "createRun\|runs-repo" src/core/record-history.ts
27
+ ```
28
+
29
+ ## 2. Целевой кровоток
30
+
31
+ ```
32
+ вход (ad-hoc / внутренний / registered)
33
+ → intake (gate-спека + safety) → компиляция политики → approval?
34
+ → createRun (durable, trigger_kind) → planner (декомпозиция)
35
+ → для каждого шага:
36
+ routeStep (static → capability, reliability, explore capped)
37
+ → context compilation (окно модели + бюджет токенов)
38
+ → capability issuance (TTL) → исполнение (worktree/sandbox)
39
+ внешние эффекты → effect_intents (не применяются)
40
+ → GATE (hard, независимый, tamper-evident, flake-aware)
41
+ pass → применить intents → ledger → карта → пример
42
+ fail → escalate / retry / rollback → к роутингу
43
+ → артефакт (diff/PR) → отчёт из ledger → обучение
44
+
45
+ сквозные: телеметрия (span/шаг) · живой бюджет · аудит · durable state
46
+ ```
47
+
48
+ ## 2.1 Классы входа (гибрид)
49
+
50
+ | Класс | Вход | Регистрация в ОС | Catch-up | Pause расписания |
51
+ |---|---|---|---|---|
52
+ | **Ad-hoc** | `run_mission` / CLI / GUI / RPC | нет | нет | нет (пауза run'а есть) |
53
+ | **Внутренний** | chain / DAG / retry / escalation | нет | нет | нет |
54
+ | **Registered** | cron / once / file / git / mcp-event / webhook | да (cron/once) | да | да |
55
+
56
+ Все три класса проходят **один** runtime. Различаются только источником триггера
57
+ и персистентностью шаблона.
58
+
59
+ Инварианты:
60
+
61
+ 1. Ad-hoc исполняется без единой записи в планировщике ОС.
62
+ 2. Ad-hoc не обходит gate, политику, бюджет, ledger и аудит.
63
+ 3. Внутренние запуски не консультируются с расписанием (force-маркер не нужен структурно).
64
+ 4. Одинаковая спека через ad-hoc и registered даёт одинаковый маршрут и вердикт.
65
+ 5. `trigger_kind` пишется в run и ledger; метрики честно разделяют классы входа.
66
+ 6. Недоступность планировщика ОС не блокирует ad-hoc.
67
+
68
+ Lock/no-overlap для ad-hoc — по run/mission id и по workspace (не по имени задачи);
69
+ изоляция worktree предотвращает конкуренцию двух миссий в одном репо.
70
+
71
+ ## 2.2 Объекты
72
+
73
+ | Объект | Что это | Персистентность |
74
+ |---|---|---|
75
+ | **Миссия** | цель + scope + gate-спека + safety + бюджет | опциональный шаблон; snapshot всегда в run |
76
+ | **Задача** | миссия-шаблон + регистрация триггера | только для registered |
77
+ | **Запуск** | durable-исполнение: шаги, попытки, вердикты | всегда |
78
+
79
+ ## 3. Ledger (append-only, источник правды)
80
+
81
+ ```sql
82
+ CREATE TABLE gate_outcomes (
83
+ id INTEGER PRIMARY KEY,
84
+ mission_id TEXT, run_id TEXT, step_id TEXT, task_type TEXT,
85
+ trigger_kind TEXT, -- adhoc | chain | dag | retry | escalation | cron | once | file | git | mcp | webhook
86
+ executor TEXT, -- local / cloud / model-id
87
+ route_source TEXT, -- static | capability | explore
88
+ route_reason TEXT,
89
+ gate_type TEXT, -- cmd | tests | lint | schema | diff | approval
90
+ verdict TEXT, -- pass | fail | flake | infra_fail
91
+ attempts_to_pass INTEGER, first_pass INTEGER,
92
+ evidence_path TEXT,
93
+ gate_hash TEXT, policy_hash TEXT, prompt_hash TEXT,
94
+ model_version TEXT, tool_versions TEXT,
95
+ effect_intents TEXT, -- JSON: заявленные внешние эффекты
96
+ effects_applied_at TEXT, -- NULL, пока гейт не пройден
97
+ tokens INTEGER, cost_usd REAL,
98
+ counterfactual_cost_usd REAL, verification_cost_usd REAL,
99
+ net_savings_usd REAL,
100
+ time_ms INTEGER, overhead_ms INTEGER,
101
+ escalation_from TEXT, escalation_to TEXT,
102
+ example_ref TEXT, training_record_ref TEXT,
103
+ prev_hash TEXT, -- хеш-цепочка: tamper-evident аудит
104
+ created_at TEXT
105
+ );
106
+ ```
107
+
108
+ - `capability_map` — агрегат по ledger, не отдельная правда.
109
+ - Отчёт (43) и датасет (48) читают **только** ledger.
110
+ - Нет ledger-строки — нет запуска.
111
+ - `prev_hash` даёт **tamper-evident** аудит: подделка заметна. Это **не граница
112
+ безопасности** — у кого есть запись в файл, тот перепишет цепочку. Граница —
113
+ изоляция прав и snapshot гейта.
114
+
115
+ ### Поля capability_map (расширение)
116
+
117
+ `first_pass_rate REAL`, `avg_attempts REAL`, `decay_updated_at TEXT` (EWMA),
118
+ `parent_type TEXT` (иерархия при малых данных).
119
+
120
+ ## 4. Целостность гейта (спринт 39)
121
+
122
+ **Реализовано (G-1.2):** при создании задачи `src/core/gate-integrity.ts`
123
+ фиксирует snapshot входов гейта — команду/файл хука, prompt и таймаут — с
124
+ SHA-256 в `PLUGIN_DIR/gate-snapshots/`, вне write-scope задачи. Перед запуском
125
+ гейта обе обёртки (Windows и POSIX) вызывают `gate-integrity.js verify`; при
126
+ расхождении хэша, отсутствии или повреждении snapshot гейт не выполняется,
127
+ запуск переходит в `error` с сообщением «snapshot mismatch». Snapshot
128
+ проверяет именно определение гейта, а не исходники репозитория, которые гейт
129
+ тестирует.
130
+
131
+ **Обязательная тест-атака в CI:** `test-execution-hardening.mjs` (Windows) и
132
+ `test-posix-e2e.mjs` (macOS/Linux) подменяют сгенерированный gate-файл/команду
133
+ на `exit 0` после создания snapshot и требуют падения запуска; оба теста уже
134
+ входят в `npm test`/`test:parallel`. Юнит-проверки хэша и CLI — в
135
+ `test-execution-pipeline.mjs`.
136
+
137
+ **Остаётся планом:** отдельный gate-executor, `gate_outcomes` с `gate_hash`,
138
+ `policy_hash`, `prompt_hash` и `prev_hash` в ledger, аудит-инцидент при
139
+ расхождении и перенос gate-файлов под привилегии, отличные от пользовательских.
140
+ Гейт по-прежнему **всегда hard**; shadow/canary — только для маршрутов и
141
+ адаптеров (49). Подмена самих тестов агентом текущей мерой не детектируется —
142
+ защита ограничена целостностью определения гейта.
143
+
144
+ ## 5. Отложенные внешние эффекты
145
+
146
+ Worktree не защищает от сети/API/БД. Поэтому:
147
+
148
+ 1. До гейта агент **не выполняет** irreversible-действие, а пишет `effect_intents`.
149
+ 2. Гейт проверяет артефакт **и** валидность intents (политика, egress, blast-radius).
150
+ 3. `pass` → применение intents, запись `effects_applied_at`.
151
+ 4. `fail` → discard intents; частично применённые — компенсация (saga, спринт 42).
152
+
153
+ ## 6. Flake-aware вердикт
154
+
155
+ - Повтор гейта на том же артефакте (N=2) при подозрении на флак.
156
+ - verdict `fail` (вина агента) vs `flake` / `infra_fail` (шум/инфра).
157
+ - `flake` и `infra_fail` **не обучают** capability-карту.
158
+ - Quarantine стабильно флакующих гейтов + предупреждение пользователю.
159
+ - `attempts_to_pass` и `first_pass` пишутся всегда.
160
+
161
+ ## 7. Роутинг, бюджет, issuance
162
+
163
+ - `routeStep(taskType)` до сборки контекста; `explore` — с capped бюджетом.
164
+ - Решение учитывает `first_pass_rate`, `avg_attempts`, EWMA-decay; мало данных → `parent_type`.
165
+ - **Живой бюджет** в durable-run: $ / токены / время / эскалации. При подходе к
166
+ границе — даунгрейд модели или `review`; превышение → circuit-breaker.
167
+ - **Capability issuance на шаг**: scoped-конфиг + короткоживущие секреты, очистка
168
+ после шага. База — существующие `permissions` и scoped-инъекция секретов.
169
+
170
+ ## 8. Context compilation (спринт 41)
171
+
172
+ - Выполняется **после роутинга**: окно и бюджет токенов зависят от исполнителя.
173
+ - Пересборка при эскалации (другая модель → другое окно).
174
+ - Repo-map + отбор файлов + gate-passed примеры по типу задачи; дедуп, лимит,
175
+ scrub секретов.
176
+ - Retrieval — bag-of-words векторы (подход `notification_embeddings`), без вектор-БД.
177
+
178
+ ## 9. Приёмка (= CONCEPT §11)
179
+
180
+ 1. Ad-hoc миссия с gate-спекой и safety-контрактом принята, политика скомпилирована,
181
+ планировщик ОС не изменён.
182
+ 2. Шаги смаршрутированы local-first с учётом reliability.
183
+ 3. Гейт объективно верифицировал; провал экалировался/откатился без тихих отказов;
184
+ irreversible не произошёл до pass.
185
+ 4. Ledger показал честную net-экономию и escalation rate.
186
+ 5. Карта обновилась, пример сохранён и переиспользован.
187
+ 6. Паритет: та же спека через registered даёт тот же маршрут и вердикт.
188
+
189
+ Тесты: E2E всего среза + chaos (`kill -9` посреди миссии) + атака на гейт +
190
+ попытка irreversible до pass + недоступность планировщика ОС.
191
+
192
+ ## 10. Архитектурные решения: что отклонено и почему
193
+
194
+ | Предложение | Решение | Причина |
195
+ |---|---|---|
196
+ | Soft-gate / canary для **приёмки** артефакта | ❌ отклонено | Ослабляет keystone: побочные эффекты по «мягкому» вердикту. Canary — только маршруты и адаптеры (49). |
197
+ | AOCL как нормативная модель слоёв | ❌ не опираемся | Стандарт не подтверждён. Интероперабельность — через MCP (уже используется) и стабильные форматы YAML/SQLite. |
198
+ | OPA/Rego или Cedar как движок политик | ⏸ отложено | Внешняя зависимость против «мало deps / одна машина». Достаточно компилятора политики в существующий enforcement. |
199
+ | Hash-linked ledger как «доказуемость» | ✅ переформулировано | **tamper-evident аудит**, не граница безопасности. |
200
+ | Вектор-БД / «динамический RAG» | ❌ отклонено | Durable state уже есть; retrieval — на существующих bag-of-words векторах. |
201
+ | Capability-токены как OAuth/JWT | ⏸ упрощено | Локальная одна машина: scoped-конфиг + TTL-секреты дают тот же эффект без инфраструктуры. |
202
+ | «Сначала зарегистрируй задачу» для одноразовой работы | ❌ отклонено | Гибрид: ad-hoc — полноправный вход; регистрация опциональна. |
203
+
204
+ ## 11. Границы (CONCEPT §8)
205
+
206
+ - Миссии ограниченные, с явным критерием; не open-ended swarm.
207
+ - Облако — эскалация, не замена способной модели.
208
+ - Локальный control plane, одна машина; базовый путь работает без Docker и без
209
+ локальной модели.
210
+ - Планировщик ОС опционален; его недоступность не блокирует ядро.
211
+ - Критичное — человеку: гейт поднимает пол, не потолок.
package/docs/FEATURES.md CHANGED
@@ -259,6 +259,41 @@ not to hooks, Quality Gates or scripts, which still run with your user privilege
259
259
  for the exact action mapping and known limitations (project/system config, nested
260
260
  subagents).
261
261
 
262
+ ### One-off git worktree (W-1)
263
+
264
+ Set `worktree: true` to run every tick in a fresh `git worktree` of
265
+ `workingDirectory` on its own `agent-steward/...` branch. The wrapper creates the
266
+ worktree after the schedule gate and before `opencode`, passes the path to the agent
267
+ through the prompt preamble and `AGENT_STEWARD_WORKTREE`, and fails the run closed
268
+ if creation fails (for example, the directory is not a git repository). Paths and
269
+ branches are unique per run, so matrix clones and parallel missions can write files
270
+ without touching the main checkout or each other — safe fan-out without Docker.
271
+
272
+ Worktrees live under `PLUGIN_DIR/worktrees` with a `.json` sidecar used by cleanup.
273
+ After the run the wrapper removes the worktree and its `agent-steward/...` branch
274
+ even when the task fails (W-2.1). Leftovers from crashes are swept opportunistically
275
+ on the next run: worktrees older than 24 hours are removed, sidecars without a
276
+ checkout are pruned, and a `.cleanup-lock` serialises concurrent sweeps (W-2.2).
277
+ Cleanup only touches paths under the worktree root that have a sidecar and an
278
+ `agent-steward/` branch, so foreign directories and fresh active runs are never
279
+ deleted. A worktree does not isolate network, API or database access, and Quality
280
+ Gates still run with your user privileges.
281
+
282
+ ### Guard conditions (W-3)
283
+
284
+ Set `guards` on a task to require conditions before it runs: an optional shell
285
+ `command` (exit 0 — пройден, non-zero — скип, `timeoutSeconds` 1..3600) and/or
286
+ `semantic` conditions — `filesExist` / `filesMissing` (relative paths, resolved
287
+ inside the worktree or cwd), `branch` (glob), and `changedPaths` (glob, at least
288
+ one path in the diff of `changedSince..HEAD`, default `HEAD~1`). All conditions
289
+ are ANDed: when any check fails or errors, the run is skipped gracefully with a
290
+ visible `skipped` status in history and the GUI (`record-history --skip`, no
291
+ notification and no success/error chain). Guards are evaluated after the
292
+ worktree is created, so they run inside the fresh worktree when combined with
293
+ `worktree: true`; the `guard-run.js` helper lives in `src/core/guard-run.ts` and
294
+ `src/core/guard.ts` provides normalization, evaluation and the exit-code
295
+ convention (4 = skip).
296
+
262
297
  ## Orchestration
263
298
 
264
299
  ### Chains
@@ -323,6 +358,21 @@ Behavior worth knowing:
323
358
  - `matrix_control` with `action: "cleanup"` removes orphaned clones whose parent is
324
359
  gone; the same cleanup also runs at plugin startup.
325
360
 
361
+ ### Pipeline as code
362
+
363
+ A whole DAG can be declared in `opencode.pipeline.yaml` and applied as code:
364
+
365
+ - `version: 1`, a pipeline `name`, optional `defaults` and 1..200 `steps`.
366
+ - Each step has a stable `id`, a `prompt` and an optional `needs` list that becomes
367
+ `dependsOn`.
368
+ - `trigger: cron` (default) needs a `schedule`; `trigger: once` needs `runAt`;
369
+ `trigger: dag` runs only after its `needs` succeed.
370
+ - `matrix.workspaces` fans a step out over workspace names or ids.
371
+ - `agent-steward pipeline validate|apply|export` and the `pipeline_validate`,
372
+ `pipeline_apply`, `pipeline_export` tools cover the lifecycle; apply is idempotent,
373
+ skips unchanged steps and never deletes stale tasks.
374
+ - Full format and limits: [PIPELINE.md](PIPELINE.md).
375
+
326
376
  ## Multi-repository workspaces
327
377
 
328
378
  A workspace is a named directory: id, name, path, optional git remote and color.
@@ -348,7 +398,9 @@ This is useful for separating projects, clients or environments (e.g. `default`
348
398
  in the base directory → `default`. Switching profiles writes the marker and requires
349
399
  an OpenCode restart because plugin directories are resolved at module load time.
350
400
  - Dashboard port per profile: `OPENCODE_SCHEDULER_PORT` env var → port from
351
- `profile.json` → server default (3782, then 4782/5782 fallback).
401
+ `profile.json` → server default (3782, then 4782/5782 fallback). A new profile is
402
+ allocated the first free port from 3783 up, skipping 3782/4782, ports already
403
+ recorded in other profiles' `profile.json`, and `OPENCODE_SCHEDULER_PORT`.
352
404
  - RPC: `get_profiles` lists profiles with dirs, ports and the active flag;
353
405
  `set_profile` switches the active profile (restart hint); `create_profile` /
354
406
  `delete_profile` manage named profiles (`default` cannot be deleted).
@@ -474,6 +526,12 @@ agent's stdout/stderr. `get_task_logs` returns the tail (1–1000 lines).
474
526
  `dry_run` simulates one task or every task: execution order, DAG prerequisites, matrix
475
527
  fan-out and estimated time. Nothing is executed and nothing is created.
476
528
 
529
+ The ad-hoc mission API (`runMission` / `agent-steward run --dry-run`) has its own
530
+ `dryRun` contract: it builds the step plan and its description, but does not acquire
531
+ the `activeWorkspaces` lock and does not write `runs`/`run_steps` to the ledger.
532
+ This is intentional — several dry runs in the same `cwd` run in parallel and leave
533
+ no trace in history. Only a real mission is locked to one workspace at a time.
534
+
477
535
  ### Dashboard
478
536
 
479
537
  A local web dashboard shows tasks, matrix tabs, per-workspace summaries, DAG markers,
@@ -610,14 +668,15 @@ the `cleanup_history` RPC and the GUI's **Clear now** button. Aggregates in
610
668
 
611
669
  ## Agent interface
612
670
 
613
- Twenty-six tools: `schedule_task`, `list_tasks`, `update_task`, `delete_task`,
671
+ Twenty-nine tools: `schedule_task`, `list_tasks`, `update_task`, `delete_task`,
614
672
  `run_task_now`, `pause_task`, `resume_task`, `get_history`, `get_task_logs`, `dry_run`,
615
673
  `manage_workspaces`, `matrix_control` (results/cancel/cleanup/preview), `get_metrics`,
616
674
  `get_analytics`, `self_analysis` (health score, anomalies, trends), `manage_settings`,
617
675
  `manage_local_ai`, `manage_templates`, `manage_profiles`,
618
676
  `transfer_tasks`, `send_notification`, `get_dashboard_info`, `cleanup_history`,
619
677
  `manage_secrets`, `get_audit_log`,
620
- `emit_event`.
678
+ `emit_event`,
679
+ `pipeline_validate`, `pipeline_apply`, `pipeline_export`.
621
680
 
622
681
  A bundled skill, `scheduled-job-best-practices`, teaches the agent safe defaults:
623
682
  least privilege, Quality Gates, timeout, matrix concurrency, DAG rules and a
@@ -654,7 +713,9 @@ It never changes run status, retries, Quality Gates, DAG dependencies or history
654
713
  messages are converted to normalized bag-of-words vectors stored in SQLite,
655
714
  compared by cosine similarity against the window, and suppressed above
656
715
  `threshold` (0.85 default). Important statuses are never suppressed. No new
657
- dependencies and no external embedding model are required.
716
+ dependencies and no external embedding model are required. CJK text (Chinese,
717
+ Japanese, Korean) is tokenized into overlapping bigrams, so messages without
718
+ spaces produce non-zero vectors and participate in dedup too.
658
719
  - `notifications.summary` renders at most three short lines for Telegram and
659
720
  toasts. The model returns strict JSON `{"lines": [...]}`; any failure falls
660
721
  back to deterministic truncation (status, error, runtime/tokens/cost), and
@@ -221,6 +221,36 @@ OpenCode 动作的 `effect: "deny"` 规则,而 `allowedTools`(一旦设置
221
221
  嵌套子代理)见
222
222
  [ARCHITECTURE.md](ARCHITECTURE.md#permission-enforcement--known-limitations-spike-291-findings)。
223
223
 
224
+ ### 一次性 git worktree(W-1)
225
+
226
+ 设置 `worktree: true` 后,每次运行都会在 `workingDirectory` 的全新 `git worktree`
227
+ 中执行,并使用独立的 `agent-steward/...` 分支。包装脚本在调度门禁之后、启动
228
+ `opencode` 之前创建 worktree,通过提示词前导和 `AGENT_STEWARD_WORKTREE` 把路径传给
229
+ Agent;创建失败时(例如目录不是 git 仓库)运行会 fail-closed 终止。每次运行的路径和
230
+ 分支都唯一,因此矩阵克隆和并行任务可以各自写文件,互不影响主工作区和彼此——无需
231
+ Docker 即可安全扇出。
232
+
233
+ Worktree 位于 `PLUGIN_DIR/worktrees`,旁边的 `.json` sidecar 用于清理。运行结束后,
234
+ 包装脚本会删除 worktree 及其 `agent-steward/...` 分支,任务失败时也会删除(W-2.1)。
235
+ 崩溃留下的残留会在下一次运行时顺带清扫:超过 24 小时的 worktree 被删除,没有工作
236
+ 副本的 sidecar 被清理,`.cleanup-lock` 串行化并发清扫(W-2.2)。清理只处理 worktree
237
+ 根目录下带 sidecar 且分支为 `agent-steward/` 的路径,因此不会删除外来目录和正在
238
+ 运行的 worktree。worktree 不隔离网络、API 或数据库访问,Quality Gate 仍以你的
239
+ 用户权限运行。
240
+
241
+ ### Guard 条件(W-3)
242
+
243
+ 可以为任务设置 `guards` — 运行前必须满足的条件:可选的 shell `command`
244
+ (exit 0 表示通过,非 0 表示跳过,`timeoutSeconds` 1..3600)和/或 `semantic`
245
+ 条件 — `filesExist` / `filesMissing`(相对路径,在 worktree 或 cwd 内解析)、
246
+ `branch`(glob)和 `changedPaths`(glob;`changedSince..HEAD` 的 diff 中至少
247
+ 匹配一个路径,默认 `HEAD~1`)。所有条件按「与」组合:任一检查失败或出错时,
248
+ 运行会被优雅跳过,并在历史记录和 GUI 中显示为可见的 `skipped` 状态
249
+ (`record-history --skip`;不发送通知、不触发成功/错误链)。检查在创建
250
+ worktree 之后执行,因此与 `worktree: true` 组合时它们在新 worktree 内运行;
251
+ `guard-run.js` 帮助程序位于 `src/core/guard-run.ts`,`src/core/guard.ts`
252
+ 提供规范化、求值和退出码约定(4 = 跳过)。
253
+
224
254
  ## 编排
225
255
 
226
256
  ### 链式调度
@@ -283,6 +313,20 @@ OpenCode 动作的 `effect: "deny"` 规则,而 `allowedTools`(一旦设置
283
313
  - `matrix_control` 的 `action: "cleanup"` 会移除父任务已不存在的孤立
284
314
  克隆;同样的清理也会在插件启动时运行。
285
315
 
316
+ ### 流水线即代码
317
+
318
+ 整个 DAG 可以声明在 `opencode.pipeline.yaml` 中并按代码应用:
319
+
320
+ - `version: 1`、流水线 `name`、可选的 `defaults` 和 1..200 个 `steps`。
321
+ - 每个步骤有稳定的 `id`、`prompt` 和可选的 `needs`(转换为 `dependsOn`)。
322
+ - `trigger: cron`(默认)需要 `schedule`;`trigger: once` 需要 `runAt`;
323
+ `trigger: dag` 只在其 `needs` 成功后运行。
324
+ - `matrix.workspaces` 按 workspace 名称或 id 将步骤扇出。
325
+ - `agent-steward pipeline validate|apply|export` 与 `pipeline_validate`、
326
+ `pipeline_apply`、`pipeline_export` 工具覆盖整个生命周期;apply 幂等、
327
+ 跳过未变化的步骤,且从不删除 stale 任务。
328
+ - 完整格式与限制:[PIPELINE.md](PIPELINE.md)。
329
+
286
330
  ## 多仓库工作区
287
331
 
288
332
  工作区是一个命名目录:id、name、path、可选的 git 远程仓库和颜色。
@@ -308,7 +352,9 @@ OpenCode 动作的 `effect: "deny"` 规则,而 `allowedTools`(一旦设置
308
352
  `active-profile` 文件 → `default`。切换配置档案会写入标记文件,并且需要
309
353
  重启 OpenCode,因为插件目录在模块加载时解析。
310
354
  - 每个配置档案的仪表板端口:`OPENCODE_SCHEDULER_PORT` 环境变量 → 来自
311
- `profile.json` 的端口 → 服务器默认值(3782,其次 4782/5782 回退)。
355
+ `profile.json` 的端口 → 服务器默认值(3782,其次 4782/5782 回退)。新配置档案
356
+ 会分配 3783 起的第一个空闲端口,跳过 3782/4782、其他配置档案 `profile.json`
357
+ 中已记录的端口以及 `OPENCODE_SCHEDULER_PORT`。
312
358
  - RPC:`get_profiles` 列出配置档案及其目录、端口和活动标志;
313
359
  `set_profile` 切换活动配置档案(会提示重启);`create_profile` /
314
360
  `delete_profile` 管理命名配置档案(`default` 不能被删除)。
@@ -566,14 +612,14 @@ GUI 面板)支持 `list`、`set` 和 `delete`。密钥名匹配
566
612
 
567
613
  ## Agent 接口
568
614
 
569
- 二十六个工具:`schedule_task`、`list_tasks`、`update_task`、`delete_task`、
615
+ 二十九个工具:`schedule_task`、`list_tasks`、`update_task`、`delete_task`、
570
616
  `run_task_now`、`pause_task`、`resume_task`、`get_history`、`get_task_logs`、`dry_run`、
571
617
  `manage_workspaces`、`matrix_control`(results/cancel/cleanup/preview)、`get_metrics`、
572
618
  `get_analytics`、`self_analysis`(健康评分、异常、趋势)、`manage_settings`、
573
619
  `manage_local_ai`、`manage_templates`、`manage_profiles`、
574
620
  `transfer_tasks`、`send_notification`、`get_dashboard_info`、`cleanup_history`、
575
621
  `manage_secrets`、`get_audit_log`、
576
- `emit_event`。
622
+ `emit_event`、`pipeline_validate`、`pipeline_apply`、`pipeline_export`。
577
623
 
578
624
  捆绑的 skill `scheduled-job-best-practices` 教会 agent 安全的默认做法:
579
625
  最小权限、Quality Gate、超时、矩阵并发、DAG 规则以及
@@ -611,7 +657,9 @@ GUI 面板)支持 `list`、`set` 和 `delete`。密钥名匹配
611
657
  在窗口内按余弦相似度比较,超过
612
658
  `threshold`(默认 0.85)时被抑制。重要状态
613
659
  永远不会被抑制。不需要新依赖,也不需要外部
614
- 嵌入模型。
660
+ 嵌入模型。CJK 文本(中文、日文、韩文)按重叠的
661
+ 二元组切分,因此没有空格的消息也会得到非零向量
662
+ 并参与去重。
615
663
  - `notifications.summary` 为 Telegram 和
616
664
  toast 最多渲染三行短文本。模型返回严格的 JSON
617
665
  `{"lines": [...]}`;任何失败都会回退到确定性截断(状态、
package/docs/MIGRATION.md CHANGED
@@ -27,8 +27,8 @@ timers, launchd, Windows Task Scheduler, or another scheduler plugin.
27
27
  automatically; on V1 restart it). If OpenCode's built-in
28
28
  schedules are enabled, disable them so two schedulers do not run the same work.
29
29
 
30
- 2. **Check Node.** `node --version` must be 20 or newer (22.5+ for the built-in SQLite
31
- driver; Node 24 recommended).
30
+ 2. **Check Node.** `node --version` must be 22.22+ (the built-in SQLite driver and
31
+ chokidar 6 require 22.22+; Node 24 recommended).
32
32
 
33
33
  3. **Inventory the old jobs.** For each job write down: name, schedule, command,
34
34
  working directory, environment variables, timeout, and what "success" means. The