agent-steward 0.0.0-stage → 0.0.2

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 (334) hide show
  1. package/CHANGELOG.md +376 -0
  2. package/CROSS_PLATFORM.md +149 -0
  3. package/LICENSE +21 -0
  4. package/README.md +314 -2
  5. package/ROADMAP-STRATEGY.md +147 -0
  6. package/ROADMAP.md +1069 -0
  7. package/dist/core/analytics.d.ts +132 -0
  8. package/dist/core/analytics.d.ts.map +1 -0
  9. package/dist/core/analytics.js +290 -0
  10. package/dist/core/audit.d.ts +96 -0
  11. package/dist/core/audit.d.ts.map +1 -0
  12. package/dist/core/audit.js +297 -0
  13. package/dist/core/cron-to-schtasks.d.ts +20 -0
  14. package/dist/core/cron-to-schtasks.d.ts.map +1 -0
  15. package/dist/core/cron-to-schtasks.js +250 -0
  16. package/dist/core/dry-run.d.ts +102 -0
  17. package/dist/core/dry-run.d.ts.map +1 -0
  18. package/dist/core/dry-run.js +447 -0
  19. package/dist/core/file-watcher.d.ts +31 -0
  20. package/dist/core/file-watcher.d.ts.map +1 -0
  21. package/dist/core/file-watcher.js +186 -0
  22. package/dist/core/git-trigger.d.ts +82 -0
  23. package/dist/core/git-trigger.d.ts.map +1 -0
  24. package/dist/core/git-trigger.js +312 -0
  25. package/dist/core/glob.d.ts +38 -0
  26. package/dist/core/glob.d.ts.map +1 -0
  27. package/dist/core/glob.js +233 -0
  28. package/dist/core/local-ai.d.ts +52 -0
  29. package/dist/core/local-ai.d.ts.map +1 -0
  30. package/dist/core/local-ai.js +119 -0
  31. package/dist/core/lock.d.ts +57 -0
  32. package/dist/core/lock.d.ts.map +1 -0
  33. package/dist/core/lock.js +195 -0
  34. package/dist/core/matrix.d.ts +167 -0
  35. package/dist/core/matrix.d.ts.map +1 -0
  36. package/dist/core/matrix.js +724 -0
  37. package/dist/core/native-notify.d.ts +36 -0
  38. package/dist/core/native-notify.d.ts.map +1 -0
  39. package/dist/core/native-notify.js +113 -0
  40. package/dist/core/one-shot.d.ts +68 -0
  41. package/dist/core/one-shot.d.ts.map +1 -0
  42. package/dist/core/one-shot.js +139 -0
  43. package/dist/core/otel.d.ts +4 -0
  44. package/dist/core/otel.d.ts.map +1 -0
  45. package/dist/core/otel.js +98 -0
  46. package/dist/core/permissions.d.ts +69 -0
  47. package/dist/core/permissions.d.ts.map +1 -0
  48. package/dist/core/permissions.js +143 -0
  49. package/dist/core/prometheus.d.ts +23 -0
  50. package/dist/core/prometheus.d.ts.map +1 -0
  51. package/dist/core/prometheus.js +146 -0
  52. package/dist/core/ps-wrapper.d.ts +73 -0
  53. package/dist/core/ps-wrapper.d.ts.map +1 -0
  54. package/dist/core/ps-wrapper.js +1071 -0
  55. package/dist/core/record-history.d.ts +25 -0
  56. package/dist/core/record-history.d.ts.map +1 -0
  57. package/dist/core/record-history.js +471 -0
  58. package/dist/core/retention.d.ts +29 -0
  59. package/dist/core/retention.d.ts.map +1 -0
  60. package/dist/core/retention.js +98 -0
  61. package/dist/core/savings.d.ts +70 -0
  62. package/dist/core/savings.d.ts.map +1 -0
  63. package/dist/core/savings.js +87 -0
  64. package/dist/core/schedule-gate.d.ts +2 -0
  65. package/dist/core/schedule-gate.d.ts.map +1 -0
  66. package/dist/core/schedule-gate.js +211 -0
  67. package/dist/core/schedule-v2.d.ts +116 -0
  68. package/dist/core/schedule-v2.d.ts.map +1 -0
  69. package/dist/core/schedule-v2.js +586 -0
  70. package/dist/core/scheduler/index.d.ts +32 -0
  71. package/dist/core/scheduler/index.d.ts.map +1 -0
  72. package/dist/core/scheduler/index.js +63 -0
  73. package/dist/core/scheduler/linux.d.ts +44 -0
  74. package/dist/core/scheduler/linux.d.ts.map +1 -0
  75. package/dist/core/scheduler/linux.js +225 -0
  76. package/dist/core/scheduler/logs.d.ts +11 -0
  77. package/dist/core/scheduler/logs.d.ts.map +1 -0
  78. package/dist/core/scheduler/logs.js +34 -0
  79. package/dist/core/scheduler/mac.d.ts +40 -0
  80. package/dist/core/scheduler/mac.d.ts.map +1 -0
  81. package/dist/core/scheduler/mac.js +207 -0
  82. package/dist/core/scheduler/posix.d.ts +40 -0
  83. package/dist/core/scheduler/posix.d.ts.map +1 -0
  84. package/dist/core/scheduler/posix.js +89 -0
  85. package/dist/core/scheduler/registry.d.ts +41 -0
  86. package/dist/core/scheduler/registry.d.ts.map +1 -0
  87. package/dist/core/scheduler/registry.js +57 -0
  88. package/dist/core/scheduler/types.d.ts +86 -0
  89. package/dist/core/scheduler/types.d.ts.map +1 -0
  90. package/dist/core/scheduler/types.js +1 -0
  91. package/dist/core/scheduler/windows.d.ts +99 -0
  92. package/dist/core/scheduler/windows.d.ts.map +1 -0
  93. package/dist/core/scheduler/windows.js +596 -0
  94. package/dist/core/secrets.d.ts +66 -0
  95. package/dist/core/secrets.d.ts.map +1 -0
  96. package/dist/core/secrets.js +433 -0
  97. package/dist/core/self-analysis.d.ts +117 -0
  98. package/dist/core/self-analysis.d.ts.map +1 -0
  99. package/dist/core/self-analysis.js +539 -0
  100. package/dist/core/self-analysis.test.d.ts +2 -0
  101. package/dist/core/self-analysis.test.d.ts.map +1 -0
  102. package/dist/core/self-analysis.test.js +219 -0
  103. package/dist/core/session.d.ts +42 -0
  104. package/dist/core/session.d.ts.map +1 -0
  105. package/dist/core/session.js +134 -0
  106. package/dist/core/shutdown.d.ts +26 -0
  107. package/dist/core/shutdown.d.ts.map +1 -0
  108. package/dist/core/shutdown.js +49 -0
  109. package/dist/core/structured-log.d.ts +84 -0
  110. package/dist/core/structured-log.d.ts.map +1 -0
  111. package/dist/core/structured-log.js +146 -0
  112. package/dist/core/summary.d.ts +69 -0
  113. package/dist/core/summary.d.ts.map +1 -0
  114. package/dist/core/summary.js +250 -0
  115. package/dist/core/telegram.d.ts +55 -0
  116. package/dist/core/telegram.d.ts.map +1 -0
  117. package/dist/core/telegram.js +344 -0
  118. package/dist/core/triage-chain.d.ts +40 -0
  119. package/dist/core/triage-chain.d.ts.map +1 -0
  120. package/dist/core/triage-chain.js +80 -0
  121. package/dist/core/triage-compare.d.ts +68 -0
  122. package/dist/core/triage-compare.d.ts.map +1 -0
  123. package/dist/core/triage-compare.js +184 -0
  124. package/dist/core/triage-rules.d.ts +23 -0
  125. package/dist/core/triage-rules.d.ts.map +1 -0
  126. package/dist/core/triage-rules.js +196 -0
  127. package/dist/core/triage-shadow.d.ts +91 -0
  128. package/dist/core/triage-shadow.d.ts.map +1 -0
  129. package/dist/core/triage-shadow.js +160 -0
  130. package/dist/core/triage-worker.d.ts +55 -0
  131. package/dist/core/triage-worker.d.ts.map +1 -0
  132. package/dist/core/triage-worker.js +314 -0
  133. package/dist/core/triage.d.ts +76 -0
  134. package/dist/core/triage.d.ts.map +1 -0
  135. package/dist/core/triage.js +271 -0
  136. package/dist/core/watch-paths.d.ts +6 -0
  137. package/dist/core/watch-paths.d.ts.map +1 -0
  138. package/dist/core/watch-paths.js +62 -0
  139. package/dist/core/wrappers/bash.d.ts +95 -0
  140. package/dist/core/wrappers/bash.d.ts.map +1 -0
  141. package/dist/core/wrappers/bash.js +413 -0
  142. package/dist/db/git-state-repo.d.ts +16 -0
  143. package/dist/db/git-state-repo.d.ts.map +1 -0
  144. package/dist/db/git-state-repo.js +38 -0
  145. package/dist/db/history-repo.d.ts +110 -0
  146. package/dist/db/history-repo.d.ts.map +1 -0
  147. package/dist/db/history-repo.js +300 -0
  148. package/dist/db/index.d.ts +47 -0
  149. package/dist/db/index.d.ts.map +1 -0
  150. package/dist/db/index.js +120 -0
  151. package/dist/db/metrics-repo.d.ts +46 -0
  152. package/dist/db/metrics-repo.d.ts.map +1 -0
  153. package/dist/db/metrics-repo.js +103 -0
  154. package/dist/db/migrate.d.ts +24 -0
  155. package/dist/db/migrate.d.ts.map +1 -0
  156. package/dist/db/migrate.js +244 -0
  157. package/dist/db/recovery.d.ts +11 -0
  158. package/dist/db/recovery.d.ts.map +1 -0
  159. package/dist/db/recovery.js +38 -0
  160. package/dist/db/schema.d.ts +24 -0
  161. package/dist/db/schema.d.ts.map +1 -0
  162. package/dist/db/schema.js +170 -0
  163. package/dist/db/settings-repo.d.ts +8 -0
  164. package/dist/db/settings-repo.d.ts.map +1 -0
  165. package/dist/db/settings-repo.js +27 -0
  166. package/dist/db/tasks-repo.d.ts +26 -0
  167. package/dist/db/tasks-repo.d.ts.map +1 -0
  168. package/dist/db/tasks-repo.js +120 -0
  169. package/dist/db/templates-repo.d.ts +17 -0
  170. package/dist/db/templates-repo.d.ts.map +1 -0
  171. package/dist/db/templates-repo.js +57 -0
  172. package/dist/gui-experimental.cjs +1 -0
  173. package/dist/history.d.ts +60 -0
  174. package/dist/history.d.ts.map +1 -0
  175. package/dist/history.js +70 -0
  176. package/dist/i18n.d.ts +75 -0
  177. package/dist/i18n.d.ts.map +1 -0
  178. package/dist/i18n.js +357 -0
  179. package/dist/index.d.ts +858 -0
  180. package/dist/index.d.ts.map +1 -0
  181. package/dist/index.js +5179 -0
  182. package/dist/integrations.d.ts +72 -0
  183. package/dist/integrations.d.ts.map +1 -0
  184. package/dist/integrations.js +233 -0
  185. package/dist/notifications.d.ts +199 -0
  186. package/dist/notifications.d.ts.map +1 -0
  187. package/dist/notifications.js +967 -0
  188. package/dist/profiles.d.ts +60 -0
  189. package/dist/profiles.d.ts.map +1 -0
  190. package/dist/profiles.js +227 -0
  191. package/dist/rpc.d.ts +3806 -0
  192. package/dist/rpc.d.ts.map +1 -0
  193. package/dist/rpc.js +1507 -0
  194. package/dist/schtasks.d.ts +32 -0
  195. package/dist/schtasks.d.ts.map +1 -0
  196. package/dist/schtasks.js +45 -0
  197. package/dist/server.d.ts +128 -0
  198. package/dist/server.d.ts.map +1 -0
  199. package/dist/server.js +2413 -0
  200. package/dist/settings.d.ts +389 -0
  201. package/dist/settings.d.ts.map +1 -0
  202. package/dist/settings.js +770 -0
  203. package/dist/shared/jobs-view.d.ts +59 -0
  204. package/dist/shared/jobs-view.d.ts.map +1 -0
  205. package/dist/shared/jobs-view.js +146 -0
  206. package/dist/skill.d.ts +15 -0
  207. package/dist/skill.d.ts.map +1 -0
  208. package/dist/skill.js +93 -0
  209. package/dist/task-transfer.d.ts +252 -0
  210. package/dist/task-transfer.d.ts.map +1 -0
  211. package/dist/task-transfer.js +628 -0
  212. package/dist/templates.d.ts +57 -0
  213. package/dist/templates.d.ts.map +1 -0
  214. package/dist/templates.js +16 -0
  215. package/dist/types.d.ts +96 -0
  216. package/dist/types.d.ts.map +1 -0
  217. package/dist/types.js +130 -0
  218. package/dist/version.d.ts +8 -0
  219. package/dist/version.d.ts.map +1 -0
  220. package/dist/version.js +27 -0
  221. package/dist/workspaces.d.ts +113 -0
  222. package/dist/workspaces.d.ts.map +1 -0
  223. package/dist/workspaces.js +393 -0
  224. package/docs/ARCHITECTURE.md +457 -0
  225. package/docs/COMPATIBILITY.md +233 -0
  226. package/docs/CONCEPT.md +230 -0
  227. package/docs/CROSS_PLATFORM.ru.md +150 -0
  228. package/docs/CROSS_PLATFORM.zh.md +146 -0
  229. package/docs/FAQ.md +52 -0
  230. package/docs/FAQ.ru.md +53 -0
  231. package/docs/FAQ.zh.md +43 -0
  232. package/docs/FEATURES.md +698 -0
  233. package/docs/FEATURES.zh.md +655 -0
  234. package/docs/LOCAL-AI.md +300 -0
  235. package/docs/MIGRATION.md +355 -0
  236. package/docs/README.ru.md +268 -0
  237. package/docs/README.zh.md +305 -0
  238. package/docs/SAVINGS.md +61 -0
  239. package/docs/SAVINGS.ru.md +60 -0
  240. package/docs/SAVINGS.zh.md +52 -0
  241. package/docs/V1-V2-COMPATIBILITY-PLAN.md +366 -0
  242. package/docs/ZH-LOCALE-PLAN.md +324 -0
  243. package/docs/dashboard.png +0 -0
  244. package/docs/spikes/local-model-structured-output.md +81 -0
  245. package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
  246. package/docs/spikes/ollama-qwen3-4b.json +163 -0
  247. package/gui-experimental.cjs +9 -0
  248. package/index.js +1 -0
  249. package/locales/en.json +780 -0
  250. package/locales/ru.json +780 -0
  251. package/locales/zh.json +780 -0
  252. package/package.json +149 -4
  253. package/scripts/bench-local.mjs +321 -0
  254. package/scripts/check-zh-locale.mjs +218 -0
  255. package/scripts/demo-dashboard.mjs +209 -0
  256. package/scripts/run-tests.mjs +236 -0
  257. package/scripts/spike-local-structured.mjs +182 -0
  258. package/scripts/test-locale.mjs +45 -0
  259. package/skills/scheduled-job-best-practices/SKILL.md +158 -0
  260. package/skills/scheduled-job-best-practices/references/recipes.md +163 -0
  261. package/src/core/analytics.ts +424 -0
  262. package/src/core/audit.ts +418 -0
  263. package/src/core/cron-to-schtasks.ts +288 -0
  264. package/src/core/dry-run.ts +601 -0
  265. package/src/core/file-watcher.ts +245 -0
  266. package/src/core/git-trigger.ts +391 -0
  267. package/src/core/glob.ts +226 -0
  268. package/src/core/local-ai.ts +173 -0
  269. package/src/core/lock.ts +219 -0
  270. package/src/core/matrix.ts +947 -0
  271. package/src/core/native-notify.ts +157 -0
  272. package/src/core/one-shot.ts +189 -0
  273. package/src/core/otel.ts +128 -0
  274. package/src/core/permissions.ts +200 -0
  275. package/src/core/prometheus.ts +215 -0
  276. package/src/core/ps-wrapper.ts +1140 -0
  277. package/src/core/record-history.ts +615 -0
  278. package/src/core/retention.ts +141 -0
  279. package/src/core/savings.ts +150 -0
  280. package/src/core/schedule-gate.ts +253 -0
  281. package/src/core/schedule-v2.ts +668 -0
  282. package/src/core/scheduler/index.ts +82 -0
  283. package/src/core/scheduler/linux.ts +257 -0
  284. package/src/core/scheduler/logs.ts +37 -0
  285. package/src/core/scheduler/mac.ts +270 -0
  286. package/src/core/scheduler/posix.ts +114 -0
  287. package/src/core/scheduler/registry.ts +99 -0
  288. package/src/core/scheduler/types.ts +90 -0
  289. package/src/core/scheduler/windows.ts +711 -0
  290. package/src/core/secrets.ts +503 -0
  291. package/src/core/self-analysis.ts +744 -0
  292. package/src/core/session.ts +150 -0
  293. package/src/core/shutdown.ts +69 -0
  294. package/src/core/structured-log.ts +214 -0
  295. package/src/core/summary.ts +318 -0
  296. package/src/core/telegram.ts +436 -0
  297. package/src/core/triage-chain.ts +125 -0
  298. package/src/core/triage-compare.ts +277 -0
  299. package/src/core/triage-rules.ts +238 -0
  300. package/src/core/triage-shadow.ts +240 -0
  301. package/src/core/triage-worker.ts +344 -0
  302. package/src/core/triage.ts +366 -0
  303. package/src/core/watch-paths.ts +70 -0
  304. package/src/core/wrappers/bash.ts +532 -0
  305. package/src/db/git-state-repo.ts +62 -0
  306. package/src/db/history-repo.ts +492 -0
  307. package/src/db/index.ts +166 -0
  308. package/src/db/metrics-repo.ts +170 -0
  309. package/src/db/migrate.ts +328 -0
  310. package/src/db/recovery.ts +46 -0
  311. package/src/db/schema.ts +188 -0
  312. package/src/db/settings-repo.ts +31 -0
  313. package/src/db/tasks-repo.ts +162 -0
  314. package/src/db/templates-repo.ts +77 -0
  315. package/src/gui.tsx +5222 -0
  316. package/src/history.ts +128 -0
  317. package/src/i18n.ts +413 -0
  318. package/src/index.ts +6605 -0
  319. package/src/integrations.ts +297 -0
  320. package/src/notifications.ts +1346 -0
  321. package/src/profiles.ts +254 -0
  322. package/src/rpc.ts +1609 -0
  323. package/src/schtasks.ts +75 -0
  324. package/src/server.ts +2662 -0
  325. package/src/settings.ts +1369 -0
  326. package/src/shared/jobs-view.ts +188 -0
  327. package/src/skill.ts +113 -0
  328. package/src/task-transfer.ts +944 -0
  329. package/src/templates.ts +67 -0
  330. package/src/tui-v1.tsx +341 -0
  331. package/src/tui.tsx +329 -0
  332. package/src/types.ts +191 -0
  333. package/src/version.ts +27 -0
  334. package/src/workspaces.ts +487 -0
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Спайк structured output локальной модели через Ollama.
3
+ *
4
+ * Запуск:
5
+ * node scripts/spike-local-structured.mjs --model qwen3:4b --runs 10
6
+ *
7
+ * Скрипт не входит в `npm test`: он требует запущенную Ollama и скачанную
8
+ * модель. Цель — получить воспроизводимый ответ на вопрос, можно ли доверять
9
+ * JSON 4B-модели без retry. Результат печатается в stdout и, если указан
10
+ * `--out`, сохраняется в JSON.
11
+ */
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+
15
+ const DEFAULTS = {
16
+ baseUrl: "http://127.0.0.1:11434",
17
+ model: "qwen3:4b",
18
+ runs: 10,
19
+ timeoutMs: 60000,
20
+ out: "",
21
+ };
22
+
23
+ function parseArgs(argv) {
24
+ const args = { ...DEFAULTS };
25
+ for (let i = 0; i < argv.length; i += 1) {
26
+ const key = argv[i];
27
+ const value = argv[i + 1];
28
+ if (key === "--base-url") args.baseUrl = value;
29
+ else if (key === "--model") args.model = value;
30
+ else if (key === "--runs") args.runs = Number(value);
31
+ else if (key === "--timeout") args.timeoutMs = Number(value);
32
+ else if (key === "--out") args.out = value;
33
+ else if (key === "--help" || key === "-h") {
34
+ console.log("node scripts/spike-local-structured.mjs [--model qwen3:4b] [--runs 10] [--base-url URL] [--timeout MS] [--out FILE]");
35
+ process.exit(0);
36
+ } else {
37
+ console.error(`Неизвестный аргумент: ${key}`);
38
+ process.exit(2);
39
+ }
40
+ i += 1;
41
+ }
42
+ if (!Number.isInteger(args.runs) || args.runs < 1 || args.runs > 100) {
43
+ console.error("--runs должен быть целым числом от 1 до 100.");
44
+ process.exit(2);
45
+ }
46
+ return args;
47
+ }
48
+
49
+ const schema = {
50
+ type: "object",
51
+ properties: {
52
+ category: { type: "string", enum: ["quality", "timeout", "permission", "network", "unknown"] },
53
+ severity: { type: "string", enum: ["low", "medium", "high"] },
54
+ confidence: { type: "number", minimum: 0, maximum: 1 },
55
+ reason: { type: "string" },
56
+ },
57
+ required: ["category", "severity", "confidence", "reason"],
58
+ };
59
+
60
+ const prompt = `Ты классифицируешь уведомление планировщика задач.
61
+ Верни только JSON без markdown и пояснений по схеме:
62
+ {"category":"quality|timeout|permission|network|unknown","severity":"low|medium|high","confidence":0..1,"reason":"кратко"}
63
+
64
+ Уведомление:
65
+ Задача "nightly-tests" упала за 2.3s. Quality Gate вернул код 1: 3 теста не прошли в auth-модуле.`;
66
+
67
+ function validate(value) {
68
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "not an object";
69
+ for (const key of schema.required) {
70
+ if (!(key in value)) return `missing ${key}`;
71
+ }
72
+ if (!schema.properties.category.enum.includes(value.category)) return "bad category";
73
+ if (!schema.properties.severity.enum.includes(value.severity)) return "bad severity";
74
+ if (typeof value.confidence !== "number" || value.confidence < 0 || value.confidence > 1) return "bad confidence";
75
+ if (typeof value.reason !== "string" || value.reason.trim() === "") return "bad reason";
76
+ return "";
77
+ }
78
+
79
+ async function loadModel(baseUrl, model) {
80
+ const response = await fetch(`${baseUrl}/api/tags`, { signal: AbortSignal.timeout(10000) });
81
+ if (!response.ok) throw new Error(`/api/tags: HTTP ${response.status}`);
82
+ const data = await response.json();
83
+ const names = (data.models ?? []).map((item) => item.name);
84
+ if (names.length === 0) throw new Error("Ollama запущена, но моделей нет: выполните ollama pull " + model);
85
+ if (!names.some((name) => name === model || name === `${model}:latest`)) {
86
+ throw new Error(`Модель "${model}" не найдена. Доступны: ${names.join(", ")}`);
87
+ }
88
+ }
89
+
90
+ async function runOnce(args, index) {
91
+ const started = Date.now();
92
+ const body = {
93
+ model: args.model,
94
+ messages: [{ role: "user", content: prompt }],
95
+ stream: false,
96
+ format: schema,
97
+ options: { temperature: 0, seed: index + 1 },
98
+ };
99
+ const response = await fetch(`${args.baseUrl}/api/chat`, {
100
+ method: "POST",
101
+ headers: { "content-type": "application/json" },
102
+ body: JSON.stringify(body),
103
+ signal: AbortSignal.timeout(args.timeoutMs),
104
+ });
105
+ const latencyMs = Date.now() - started;
106
+ if (!response.ok) {
107
+ return { run: index + 1, ok: false, jsonValid: false, schemaValid: false, latencyMs, error: `HTTP ${response.status}` };
108
+ }
109
+ const data = await response.json();
110
+ const content = data?.message?.content ?? "";
111
+ let parsed;
112
+ try {
113
+ parsed = JSON.parse(content);
114
+ } catch {
115
+ return { run: index + 1, ok: false, jsonValid: false, schemaValid: false, latencyMs, content, error: "invalid JSON" };
116
+ }
117
+ const error = validate(parsed);
118
+ return {
119
+ run: index + 1,
120
+ ok: !error,
121
+ jsonValid: true,
122
+ schemaValid: !error,
123
+ latencyMs,
124
+ content,
125
+ parsed,
126
+ error,
127
+ };
128
+ }
129
+
130
+ const args = parseArgs(process.argv.slice(2));
131
+
132
+ try {
133
+ await loadModel(args.baseUrl, args.model);
134
+ } catch (error) {
135
+ console.error(`Не удалось подключиться к Ollama: ${error.message}`);
136
+ console.error("Спайк заблокирован: установите Ollama, выполните `ollama serve` и `ollama pull " + args.model + "`.");
137
+ process.exit(2);
138
+ }
139
+
140
+ const results = [];
141
+ for (let i = 0; i < args.runs; i += 1) {
142
+ const result = await runOnce(args, i);
143
+ results.push(result);
144
+ const mark = result.schemaValid ? "OK" : "FAIL";
145
+ console.log(`${result.run}/${args.runs} ${mark} ${result.latencyMs}ms${result.error ? ` — ${result.error}` : ""}`);
146
+ }
147
+
148
+ const jsonValid = results.filter((item) => item.jsonValid).length;
149
+ const schemaValid = results.filter((item) => item.schemaValid).length;
150
+ const latencies = results.map((item) => item.latencyMs).sort((a, b) => a - b);
151
+ const avg = Math.round(latencies.reduce((sum, value) => sum + value, 0) / latencies.length);
152
+ const p95 = latencies[Math.max(0, Math.ceil(latencies.length * 0.95) - 1)];
153
+
154
+ const summary = {
155
+ generatedAt: new Date().toISOString(),
156
+ baseUrl: args.baseUrl,
157
+ model: args.model,
158
+ runs: args.runs,
159
+ jsonValid,
160
+ schemaValid,
161
+ schemaValidRate: Number((schemaValid / args.runs).toFixed(2)),
162
+ avgLatencyMs: avg,
163
+ p95LatencyMs: p95,
164
+ results,
165
+ };
166
+
167
+ console.log("");
168
+ console.log(`Модель: ${args.model}`);
169
+ console.log(`JSON валиден: ${jsonValid}/${args.runs}; схема: ${schemaValid}/${args.runs} (${Math.round(summary.schemaValidRate * 100)}%)`);
170
+ console.log(`Латентность: avg ${avg}ms, p95 ${p95}ms`);
171
+ if (schemaValid >= 9) console.log("Вывод: 4B можно использовать без retry, но валидацию схемы оставить.");
172
+ else if (schemaValid >= 7) console.log("Вывод: нужен ровно один retry и fallback на правила.");
173
+ else console.log("Вывод: 4B нельзя использовать для критичных вердиктов; только правила или модель крупнее.");
174
+
175
+ if (args.out) {
176
+ const target = path.resolve(args.out);
177
+ fs.mkdirSync(path.dirname(target), { recursive: true });
178
+ fs.writeFileSync(target, `${JSON.stringify(summary, null, 2)}\n`, "utf8");
179
+ console.log(`Результат: ${target}`);
180
+ }
181
+
182
+ process.exit(schemaValid >= 7 ? 0 : 1);
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Прогоняет тот же набор сюит, что `npm test`, с заданной локалью.
3
+ *
4
+ * Локаль задаётся переменной `OPENCODE_SCHEDULER_LOCALE`, которую читает
5
+ * `src/i18n.ts` при загрузке: так один и тот же код проверяется в ru, en и zh
6
+ * без правки settings.json.
7
+ *
8
+ * Запуск: node scripts/test-locale.mjs en
9
+ * Локали: ru (по умолчанию), en, zh.
10
+ */
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { spawnSync } from "node:child_process";
14
+ import { fileURLToPath } from "node:url";
15
+
16
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
17
+ const locale = process.argv[2] ?? "en";
18
+
19
+ if (locale !== "ru" && locale !== "en" && locale !== "zh") {
20
+ console.error(`Неизвестная локаль: ${locale}. Ожидается ru, en или zh.`);
21
+ process.exit(2);
22
+ }
23
+
24
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
25
+ const suites = pkg.scripts.test
26
+ .split("&&")
27
+ .map((part) => part.trim().replace(/^node\s+/, ""))
28
+ .filter(Boolean);
29
+
30
+ const failed = [];
31
+ for (const suite of suites) {
32
+ const result = spawnSync(process.execPath, [suite], {
33
+ cwd: root,
34
+ env: { ...process.env, OPENCODE_SCHEDULER_LOCALE: locale },
35
+ stdio: "inherit",
36
+ });
37
+ if (result.status !== 0) failed.push(suite);
38
+ }
39
+
40
+ if (failed.length > 0) {
41
+ console.error(`\n${locale}: провалено ${failed.length} из ${suites.length}: ${failed.join(", ")}`);
42
+ process.exit(1);
43
+ }
44
+
45
+ console.log(`\n${locale}: все ${suites.length} сюит зелёные.`);
@@ -0,0 +1,158 @@
1
+ ---
2
+ name: Scheduled Job Best Practices
3
+ description: Use when the user wants recurring or event-driven automation (cron, file changes, MCP events), multi-repository fan-out, or agent pipelines. Covers safe defaults, prompt design, Quality Gates, matrix builds, DAG dependencies and post-incident diagnosis with the scheduler tools.
4
+ ---
5
+
6
+ # Scheduled Job Best Practices
7
+
8
+ Use this skill whenever the user asks to automate something on a schedule, on a file change,
9
+ on an MCP event, or as a multi-step pipeline. The goal is automation that is safe, cheap,
10
+ idempotent and debuggable a month later.
11
+
12
+ Respond in the user's language. This document is in English for portability.
13
+
14
+ ## 1. Start by looking at what already exists
15
+
16
+ Call `list_tasks` before creating anything. If a similar task exists, prefer `update_task`
17
+ (partial update, matrix clones are synchronized) over delete + create. Automation that
18
+ silently duplicates work is worse than no automation.
19
+
20
+ Check the returned fields: schedule, trigger, working directory, model, dependencies, matrix
21
+ summary, last run.
22
+
23
+ ## 2. Choose the simplest shape that works
24
+
25
+ | User need | Shape | Why |
26
+ | --- | --- | --- |
27
+ | "Every morning / every hour / weekly" | `schedule_task` with cron | Durable OS-level schedule, survives restarts |
28
+ | "When this file changes" | `triggerType: "file"` + `watchPath` | No polling; the watcher debounces bursts |
29
+ | "When my MCP server reports an event" | `triggerType: "mcp-event"` + `mcpEvent` | Event-driven, no wasted runs |
30
+ | "Same work in N repositories" | `matrix.workspaceIds` | One definition, isolated clones, aggregated status |
31
+ | "A then B then C" | `dependsOn` + `nextTaskOnSuccess` / `nextTaskOnError` | Explicit DAG, failures stop the line |
32
+ | "Try again if it fails" | `retryCount` + `retryDelay` | Handles flaky networks and rate limits |
33
+
34
+ Do not use a 5-field cron for a one-off reminder. Do not build a pipeline with chained
35
+ prompts inside a single task when `dependsOn` exists: a failed step would be invisible.
36
+
37
+ ## 3. Write prompts that survive without context
38
+
39
+ Every run starts from a clean slate: no chat history, no memory of the previous run, nobody
40
+ to answer questions. A good prompt states:
41
+
42
+ 1. **Goal** — the outcome in one sentence.
43
+ 2. **Scope** — exact paths, repositories or modules to touch.
44
+ 3. **Constraints** — what must not change, tool limits, style rules.
45
+ 4. **Verification** — the command that proves success (this is the Quality Gate).
46
+ 5. **Output** — where to write the report and what to include (counts, links, failures).
47
+
48
+ Bad: `Check the repo and fix problems.`
49
+ Good: `In ./services/api run the test suite. If tests fail, fix only failures caused by
50
+ type errors, then re-run until green or 20 minutes elapse. Write a summary to
51
+ reports/nightly-api.md with the failing test names and the commit you started from.`
52
+
53
+ Never ask the agent to "ask the user" in a scheduled prompt — nobody is there. If a decision
54
+ is genuinely ambiguous, tell it to stop and write the question into the report.
55
+
56
+ ## 4. Safety defaults
57
+
58
+ - **Least privilege**: the default `hybrid` policy already denies `shell` and `question`; keep it
59
+ that way. Read-only monitoring jobs should not be allowed to `write` or run shell. Do not ask
60
+ for `shell` just to run `git commit`, a build or tests — put those in `qualityGate`/`afterScript`,
61
+ which the wrapper runs outside the agent. If a job truly needs shell, list `shell` in
62
+ `allowedTools` (or set `legacyShell: true` for a migrated task) and explain why.
63
+ - **Timeout**: always set `timeoutSeconds` for jobs that call networks or models. Default
64
+ timeouts are a safety net, not a plan.
65
+ - **Quality Gate**: pass `qualityGate` whenever a machine-checkable success criterion exists
66
+ (`npm test`, `pytest -q`, `curl -f`, `git diff --quiet`). A run that "looks successful" is
67
+ not evidence.
68
+ - **No secrets in prompts**: prompts are stored in plain text and appear in logs. Reference
69
+ environment variables or files instead.
70
+ - **Idempotent by design**: a job may run twice (retry, catch-up after downtime, manual run).
71
+ Prefer "ensure state" over "append" — e.g. rewrite a report file rather than appending.
72
+ - **Blast radius**: avoid `git push --force`, `rm -rf`, mass dependency upgrades or
73
+ production deploys without a Quality Gate and a manual `run_task_now` smoke test first.
74
+
75
+ ## 5. Matrix builds (multi-repository)
76
+
77
+ Use a matrix when the same prompt must run in several workspaces:
78
+
79
+ - `matrix.workspaceIds` — the repositories, referenced by workspace ID (call
80
+ `manage_workspaces` with `action: "list"` to discover them).
81
+ - `matrix.strategy` — `parallel` (default) or `sequential`.
82
+ - `matrix.failureMode` — `continue` (default, aggregated as `partial`) or `stop`.
83
+ - `matrix.concurrency` — cap simultaneous clones; respect machine and API limits. Keep it
84
+ small (2–4) unless the work is purely local.
85
+ - `matrix.overrides` — per-workspace prompt/model/qualityGate/hooks when one repository
86
+ differs (different package manager, stricter gate).
87
+ - `matrix.createAggregator` — creates a follow-up task that runs once after all clones.
88
+
89
+ Rules of thumb:
90
+
91
+ - The matrix parent never runs itself; only its clones do. Do not set `workspaceId` on the
92
+ parent — it is a validation error to combine it with `matrix`.
93
+ - A dependency on a matrix parent waits for **all** clones to succeed.
94
+ - If clones are inherently independent (linting, docs), `failureMode: "continue"` gives a
95
+ useful aggregate. If one failure makes the rest pointless (deploy), use `"stop"`.
96
+ - After editing a matrix parent with `update_task`, clones are diffed and synchronized;
97
+ running clones are left alone.
98
+
99
+ ## 6. DAG rules
100
+
101
+ - `dependsOn` lists task names that must have succeeded (their latest run) before this task
102
+ starts.
103
+ - `nextTaskOnSuccess` / `nextTaskOnError` chain a single follow-up run; use them for
104
+ notifications and rollbacks.
105
+ - Keep chains short and named by intent (`deploy` → `smoke-tests` → `notify-release`).
106
+ - Cycles and self-dependencies are rejected; if a chain grows past 4–5 nodes, consider one
107
+ task with an explicit internal checklist instead.
108
+
109
+ ## 7. Validate before you commit
110
+
111
+ 1. `dry_run` with the task name (or without a name for the whole pipeline): shows order,
112
+ dependencies, matrix fan-out, estimated duration and cost. Nothing is executed.
113
+ 2. Create the task with `schedule_task`.
114
+ 3. `run_task_now` once and inspect `get_history` / `get_task_logs`. A schedule that has never
115
+ run successfully is a liability.
116
+ 4. Only then tell the user it is ready, and state the cron expression in plain language
117
+ ("every weekday at 09:00 local time").
118
+
119
+ ## 8. Diagnosing failures later
120
+
121
+ - `get_history` filtered by `taskName` and `status` — statuses: `running`, `success`, `error`,
122
+ `timeout`, `partial`.
123
+ - `get_task_logs` with `lines` — tail of the wrapper log; use it to distinguish model failure,
124
+ Quality Gate failure, timeout and lock-skip.
125
+ - Matrix problems: `matrix_control` with `action: "results"` for counters, `action: "cancel"`
126
+ to stop pending clones, `action: "cleanup"` to remove clones whose parent is gone.
127
+ - A timeout usually means the prompt is too broad. Split it or raise `timeoutSeconds`
128
+ deliberately.
129
+ - A skipped run (`already running`) means the previous run overran its interval; shorten the
130
+ prompt, raise the interval, or set a smaller timeout.
131
+
132
+ ## 9. Anti-patterns
133
+
134
+ | Anti-pattern | Consequence | Fix |
135
+ | --- | --- | --- |
136
+ | `* * * * *` with a heavy prompt | Runs overlap, lock-skips, cost spikes | Realistic interval + timeout |
137
+ | Prompt depending on chat context | Nonsense output at 03:00 | Self-contained prompt with paths |
138
+ | No Quality Gate on a "fixer" job | Broken code reported as success | `qualityGate: "npm test"` |
139
+ | Matrix with 20 workspaces, no concurrency cap | Machine and API saturation | `matrix.concurrency: 2–4` |
140
+ | Secrets inside the prompt | Leak into DB, logs and dashboard | Env vars or files |
141
+ | Deleting a matrix parent's clone by hand | Orphaned history, broken aggregate | `update_task` on the parent |
142
+ | Creating a duplicate instead of updating | Double runs, conflicting writes | `update_task` |
143
+
144
+ ## 10. Final checklist
145
+
146
+ Before saying the job is done, confirm:
147
+
148
+ - [ ] `list_tasks` checked; no duplicate exists.
149
+ - [ ] Trigger type matches the need (cron / file / MCP event).
150
+ - [ ] Prompt states goal, scope, constraints, verification and output.
151
+ - [ ] `timeoutSeconds` set; `qualityGate` set when checkable.
152
+ - [ ] `allowedTools` / `deniedTools` follow least privilege; shell is absent unless justified.
153
+ - [ ] Matrix: workspaces correct, concurrency capped, failure mode justified.
154
+ - [ ] `dry_run` reviewed.
155
+ - [ ] One successful `run_task_now` with clean `get_history`.
156
+ - [ ] Cron expressed in words for the user.
157
+
158
+ See `references/recipes.md` for complete examples.
@@ -0,0 +1,163 @@
1
+ # Recipes
2
+
3
+ Complete, copy-ready examples. Values in `<angle brackets>` are placeholders.
4
+
5
+ ## 1. Nightly dependency and test run
6
+
7
+ ```json
8
+ {
9
+ "name": "nightly-deps",
10
+ "schedule": "0 2 * * *",
11
+ "prompt": "In the repository root run `npm outdated` and `npm audit --omit=dev`. Do not upgrade majors. Apply only patch/minor security fixes, run `npm test` after each upgrade, and revert a package if tests fail. Write a summary to reports/nightly-deps.md: upgraded packages with versions, rejected upgrades and why, final test result.",
12
+ "workingDirectory": "<absolute path to repository>",
13
+ "timeoutSeconds": 2400,
14
+ "qualityGate": "npm test",
15
+ "retryCount": 1,
16
+ "retryDelay": 300,
17
+ "allowedTools": ["read", "write", "bash"],
18
+ "deniedTools": ["webfetch"]
19
+ }
20
+ ```
21
+
22
+ Why: bounded scope (no majors), machine-checkable gate, report for the morning.
23
+
24
+ ## 2. Weekday morning digest
25
+
26
+ ```json
27
+ {
28
+ "name": "morning-digest",
29
+ "schedule": "0 9 * * 1-5",
30
+ "prompt": "Collect: commits to main since the last working day (`git log --since=yesterday`), open pull requests (`gh pr list --state open`), and failed CI runs (`gh run list --status failure --limit 10`). Write a Russian-language digest to reports/digest-<date>.md with sections Commits / PRs / CI failures. If a command is unavailable, record that instead of failing.",
31
+ "workingDirectory": "<absolute path to repository>",
32
+ "timeoutSeconds": 900,
33
+ "allowedTools": ["read", "bash"]
34
+ }
35
+ ```
36
+
37
+ Why: read-only, tolerant of missing CLIs, output is the product.
38
+
39
+ ## 3. Regenerate a client when the API contract changes
40
+
41
+ ```json
42
+ {
43
+ "name": "regenerate-api-client",
44
+ "prompt": "openapi.yaml changed. Run `npm run generate:client`, then `npm run typecheck` and `npm test -- --runInBand`. If generation fails because of a schema error, do not edit the schema: write the failing path and reason to reports/api-client-error.md and stop. On success write the list of regenerated files to reports/api-client.md.",
45
+ "triggerType": "file",
46
+ "watchPath": "<absolute path to openapi.yaml>",
47
+ "workingDirectory": "<absolute path to client repository>",
48
+ "timeoutSeconds": 1200,
49
+ "qualityGate": "npm run typecheck",
50
+ "allowedTools": ["read", "write", "bash"]
51
+ }
52
+ ```
53
+
54
+ Why: event-driven instead of polling, explicit "do not touch the contract" constraint.
55
+
56
+ ## 4. Multi-repository lint and test matrix
57
+
58
+ ```json
59
+ {
60
+ "name": "repo-health",
61
+ "schedule": "0 6 * * 1",
62
+ "prompt": "Run the project's lint and test commands. Write a short report to reports/weekly-health.md with the command output summary. Fix nothing; only report.",
63
+ "timeoutSeconds": 1800,
64
+ "matrix": {
65
+ "workspaceIds": ["<frontend-id>", "<backend-id>", "<mobile-id>"],
66
+ "strategy": "parallel",
67
+ "failureMode": "continue",
68
+ "concurrency": 2,
69
+ "aggregation": "summary",
70
+ "overrides": {
71
+ "<mobile-id>": {
72
+ "qualityGate": "flutter test",
73
+ "prompt": "Run `flutter analyze` and `flutter test`. Write the summary to reports/weekly-health.md. Fix nothing."
74
+ }
75
+ }
76
+ },
77
+ "allowedTools": ["read", "bash"]
78
+ }
79
+ ```
80
+
81
+ Why: one definition, per-repository deviation in `overrides`, capped parallelism, partial
82
+ results still actionable.
83
+
84
+ ## 5. Deploy pipeline with gate and rollback
85
+
86
+ Tasks, in order:
87
+
88
+ 1. `deploy` — `schedule: "0 3 * * *"`, prompt builds and deploys, `qualityGate: "npm run smoke"`,
89
+ `timeoutSeconds: 1800`, `nextTaskOnSuccess: "notify-release"`,
90
+ `nextTaskOnError: "rollback"`.
91
+ 2. `notify-release` — posts a release message, `timeoutSeconds: 300`, read-only tools.
92
+ 3. `rollback` — restores the previous release, `qualityGate: "npm run smoke"`,
93
+ `triggerType: "file"` (started only by the chain), `timeoutSeconds: 1200`.
94
+
95
+ Verify the chain with `dry_run` for `deploy`: the output must show `deploy → notify-release`
96
+ and the error branch.
97
+
98
+ ## 6. Weekly cleanup of stale branches
99
+
100
+ ```json
101
+ {
102
+ "name": "stale-branches",
103
+ "schedule": "0 10 * * 5",
104
+ "prompt": "List merged remote branches older than 30 days (`git branch -r --merged main`). Do not delete `main`, `develop`, `release/*` or branches whose last commit is younger than 30 days. Delete the rest with `git push origin --delete`. Write the deleted and kept branches to reports/stale-branches.md with reasons.",
105
+ "workingDirectory": "<absolute path to repository>",
106
+ "timeoutSeconds": 600,
107
+ "qualityGate": "git diff --quiet",
108
+ "allowedTools": ["read", "bash"],
109
+ "deniedTools": ["write"]
110
+ }
111
+ ```
112
+
113
+ Why: explicit protected list, dry-run first, auditable report. Ask the user to run
114
+ `run_task_now` and confirm the report before enabling the schedule.
115
+
116
+ ## 7. Diagnosing a `partial` matrix
117
+
118
+ 1. `matrix_control` with `action: "results"` and the parent name → counters and the failing clones.
119
+ 2. `get_history` with `taskName: "<parent>-matrix-<workspace>"` and `status: "error"`.
120
+ 3. `get_task_logs` for that clone, `lines: 120`.
121
+ 4. Fix the cause (`update_task` on the parent for a definition bug, or the repository itself).
122
+ 5. Re-run only the failed clone with `run_task_now`, then confirm the aggregate becomes
123
+ `success`.
124
+
125
+ ## 8. Safe rollout of local triage
126
+
127
+ Start in shadow mode so the model logs decisions without suppressing notifications,
128
+ then verify with the benchmark and the shadow report before enforcing.
129
+
130
+ ```json
131
+ {
132
+ "action": "update",
133
+ "mode": "auto",
134
+ "baseUrl": "http://127.0.0.1:11434",
135
+ "model": "qwen3:4b",
136
+ "timeoutMs": 60000,
137
+ "fallback": "rules",
138
+ "confidenceThreshold": 0.6,
139
+ "shadow": { "enabled": true, "days": 14 }
140
+ }
141
+ ```
142
+
143
+ Check readiness and run one classification request:
144
+
145
+ ```json
146
+ { "action": "get" }
147
+ ```
148
+
149
+ ```json
150
+ { "action": "test", "model": "qwen3:4b" }
151
+ ```
152
+
153
+ Measure the machine before trusting the model:
154
+
155
+ ```bash
156
+ npm run bench:local -- --model qwen3:4b --runs 3 --out bench.json
157
+ ```
158
+
159
+ Why: `auto` keeps the rules engine as a fallback, `fallback: "rules"` is
160
+ fail-open, and shadow mode makes false skips visible. Only disable shadow mode
161
+ after the shadow report shows no false positives. See `docs/LOCAL-AI.md` for
162
+ model tiers by RAM, `OLLAMA_CONTEXT_LENGTH` troubleshooting and the full JSON
163
+ report format.