agent-steward 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/CHANGELOG.md +309 -2
  2. package/CROSS_PLATFORM.md +19 -0
  3. package/README.md +55 -8
  4. package/ROADMAP-STRATEGY.md +22 -19
  5. package/ROADMAP.md +230 -159
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +356 -0
  9. package/dist/core/analytics.d.ts +6 -0
  10. package/dist/core/analytics.d.ts.map +1 -1
  11. package/dist/core/analytics.js +20 -3
  12. package/dist/core/audit.d.ts +6 -0
  13. package/dist/core/audit.d.ts.map +1 -1
  14. package/dist/core/audit.js +24 -0
  15. package/dist/core/budget.d.ts +118 -0
  16. package/dist/core/budget.d.ts.map +1 -0
  17. package/dist/core/budget.js +206 -0
  18. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  19. package/dist/core/cron-to-schtasks.js +38 -0
  20. package/dist/core/dry-run.d.ts +26 -1
  21. package/dist/core/dry-run.d.ts.map +1 -1
  22. package/dist/core/dry-run.js +199 -8
  23. package/dist/core/execution.d.ts +203 -0
  24. package/dist/core/execution.d.ts.map +1 -0
  25. package/dist/core/execution.js +309 -0
  26. package/dist/core/feedback.d.ts +192 -0
  27. package/dist/core/feedback.d.ts.map +1 -0
  28. package/dist/core/feedback.js +426 -0
  29. package/dist/core/gate-integrity.d.ts +71 -0
  30. package/dist/core/gate-integrity.d.ts.map +1 -0
  31. package/dist/core/gate-integrity.js +275 -0
  32. package/dist/core/git-trigger.d.ts.map +1 -1
  33. package/dist/core/git-trigger.js +14 -2
  34. package/dist/core/guard-run.d.ts +4 -0
  35. package/dist/core/guard-run.d.ts.map +1 -0
  36. package/dist/core/guard-run.js +101 -0
  37. package/dist/core/guard.d.ts +52 -0
  38. package/dist/core/guard.d.ts.map +1 -0
  39. package/dist/core/guard.js +362 -0
  40. package/dist/core/local-ai.d.ts.map +1 -1
  41. package/dist/core/local-ai.js +7 -3
  42. package/dist/core/lock.d.ts +41 -0
  43. package/dist/core/lock.d.ts.map +1 -1
  44. package/dist/core/lock.js +141 -29
  45. package/dist/core/matrix.d.ts +8 -0
  46. package/dist/core/matrix.d.ts.map +1 -1
  47. package/dist/core/matrix.js +132 -17
  48. package/dist/core/mission.d.ts +103 -0
  49. package/dist/core/mission.d.ts.map +1 -0
  50. package/dist/core/mission.js +374 -0
  51. package/dist/core/opencode-models.d.ts +2 -2
  52. package/dist/core/opencode-models.d.ts.map +1 -1
  53. package/dist/core/opencode-models.js +28 -21
  54. package/dist/core/opencode-usage.d.ts +35 -0
  55. package/dist/core/opencode-usage.d.ts.map +1 -0
  56. package/dist/core/opencode-usage.js +132 -0
  57. package/dist/core/pipeline-apply.d.ts +38 -0
  58. package/dist/core/pipeline-apply.d.ts.map +1 -0
  59. package/dist/core/pipeline-apply.js +117 -0
  60. package/dist/core/pipeline-io.d.ts +13 -0
  61. package/dist/core/pipeline-io.d.ts.map +1 -0
  62. package/dist/core/pipeline-io.js +78 -0
  63. package/dist/core/pipeline-map.d.ts +52 -0
  64. package/dist/core/pipeline-map.d.ts.map +1 -0
  65. package/dist/core/pipeline-map.js +208 -0
  66. package/dist/core/pipeline-spec.d.ts +109 -0
  67. package/dist/core/pipeline-spec.d.ts.map +1 -0
  68. package/dist/core/pipeline-spec.js +554 -0
  69. package/dist/core/ps-wrapper.d.ts +27 -2
  70. package/dist/core/ps-wrapper.d.ts.map +1 -1
  71. package/dist/core/ps-wrapper.js +424 -65
  72. package/dist/core/record-history.d.ts.map +1 -1
  73. package/dist/core/record-history.js +206 -33
  74. package/dist/core/router/rules.d.ts.map +1 -1
  75. package/dist/core/router/rules.js +6 -0
  76. package/dist/core/run-mode.d.ts +12 -0
  77. package/dist/core/run-mode.d.ts.map +1 -0
  78. package/dist/core/run-mode.js +17 -0
  79. package/dist/core/scheduler/linux.d.ts +8 -1
  80. package/dist/core/scheduler/linux.d.ts.map +1 -1
  81. package/dist/core/scheduler/linux.js +34 -9
  82. package/dist/core/scheduler/logs.d.ts +4 -0
  83. package/dist/core/scheduler/logs.d.ts.map +1 -1
  84. package/dist/core/scheduler/logs.js +25 -1
  85. package/dist/core/scheduler/mac.d.ts +44 -2
  86. package/dist/core/scheduler/mac.d.ts.map +1 -1
  87. package/dist/core/scheduler/mac.js +126 -15
  88. package/dist/core/scheduler/windows.d.ts.map +1 -1
  89. package/dist/core/scheduler/windows.js +15 -12
  90. package/dist/core/secrets.d.ts.map +1 -1
  91. package/dist/core/secrets.js +18 -8
  92. package/dist/core/self-analysis.d.ts +32 -2
  93. package/dist/core/self-analysis.d.ts.map +1 -1
  94. package/dist/core/self-analysis.js +38 -27
  95. package/dist/core/shutdown.d.ts +33 -2
  96. package/dist/core/shutdown.d.ts.map +1 -1
  97. package/dist/core/shutdown.js +58 -2
  98. package/dist/core/structured-log.d.ts +37 -1
  99. package/dist/core/structured-log.d.ts.map +1 -1
  100. package/dist/core/structured-log.js +37 -0
  101. package/dist/core/usage-surface.d.ts +25 -0
  102. package/dist/core/usage-surface.d.ts.map +1 -0
  103. package/dist/core/usage-surface.js +41 -0
  104. package/dist/core/worktree-run.d.ts +4 -0
  105. package/dist/core/worktree-run.d.ts.map +1 -0
  106. package/dist/core/worktree-run.js +164 -0
  107. package/dist/core/worktree.d.ts +115 -0
  108. package/dist/core/worktree.d.ts.map +1 -0
  109. package/dist/core/worktree.js +462 -0
  110. package/dist/core/wrappers/bash.d.ts +19 -0
  111. package/dist/core/wrappers/bash.d.ts.map +1 -1
  112. package/dist/core/wrappers/bash.js +230 -27
  113. package/dist/db/capability-repo.d.ts +43 -2
  114. package/dist/db/capability-repo.d.ts.map +1 -1
  115. package/dist/db/capability-repo.js +96 -11
  116. package/dist/db/history-repo.d.ts +70 -5
  117. package/dist/db/history-repo.d.ts.map +1 -1
  118. package/dist/db/history-repo.js +170 -29
  119. package/dist/db/metrics-repo.d.ts +20 -2
  120. package/dist/db/metrics-repo.d.ts.map +1 -1
  121. package/dist/db/metrics-repo.js +35 -13
  122. package/dist/db/migrate.d.ts.map +1 -1
  123. package/dist/db/migrate.js +37 -17
  124. package/dist/db/recovery.d.ts +3 -1
  125. package/dist/db/recovery.d.ts.map +1 -1
  126. package/dist/db/recovery.js +11 -5
  127. package/dist/db/run-journal.d.ts +33 -5
  128. package/dist/db/run-journal.d.ts.map +1 -1
  129. package/dist/db/run-journal.js +78 -14
  130. package/dist/db/run-resume.d.ts +5 -0
  131. package/dist/db/run-resume.d.ts.map +1 -1
  132. package/dist/db/run-resume.js +9 -2
  133. package/dist/db/runs-repo.d.ts +19 -2
  134. package/dist/db/runs-repo.d.ts.map +1 -1
  135. package/dist/db/runs-repo.js +91 -60
  136. package/dist/db/schema.d.ts +2 -2
  137. package/dist/db/schema.d.ts.map +1 -1
  138. package/dist/db/schema.js +132 -2
  139. package/dist/db/templates-repo.d.ts +2 -2
  140. package/dist/db/templates-repo.d.ts.map +1 -1
  141. package/dist/db/templates-repo.js +5 -3
  142. package/dist/history.d.ts +7 -2
  143. package/dist/history.d.ts.map +1 -1
  144. package/dist/history.js +4 -2
  145. package/dist/hook-output.d.ts +2 -0
  146. package/dist/hook-output.d.ts.map +1 -0
  147. package/dist/hook-output.js +31 -0
  148. package/dist/i18n.d.ts +5 -0
  149. package/dist/i18n.d.ts.map +1 -1
  150. package/dist/i18n.js +11 -4
  151. package/dist/index.d.ts +375 -47
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +1344 -192
  154. package/dist/notifications.d.ts +53 -2
  155. package/dist/notifications.d.ts.map +1 -1
  156. package/dist/notifications.js +168 -21
  157. package/dist/profiles.d.ts.map +1 -1
  158. package/dist/profiles.js +82 -10
  159. package/dist/rpc.d.ts +354 -0
  160. package/dist/rpc.d.ts.map +1 -1
  161. package/dist/rpc.js +145 -0
  162. package/dist/server.d.ts +32 -2
  163. package/dist/server.d.ts.map +1 -1
  164. package/dist/server.js +154 -30
  165. package/dist/settings.d.ts +44 -2
  166. package/dist/settings.d.ts.map +1 -1
  167. package/dist/settings.js +85 -3
  168. package/dist/shared/jobs-view.d.ts +1 -1
  169. package/dist/shared/jobs-view.d.ts.map +1 -1
  170. package/dist/shared/jobs-view.js +2 -0
  171. package/dist/task-transfer.d.ts +21 -0
  172. package/dist/task-transfer.d.ts.map +1 -1
  173. package/dist/task-transfer.js +64 -3
  174. package/dist/templates.d.ts +2 -2
  175. package/dist/templates.d.ts.map +1 -1
  176. package/dist/templates.js +3 -3
  177. package/dist/types.d.ts +22 -2
  178. package/dist/types.d.ts.map +1 -1
  179. package/dist/workspaces.d.ts.map +1 -1
  180. package/dist/workspaces.js +34 -11
  181. package/docs/ARCHITECTURE.md +319 -66
  182. package/docs/COMPATIBILITY.md +2 -2
  183. package/docs/CONCEPT.md +18 -4
  184. package/docs/CROSS_PLATFORM.ru.md +20 -0
  185. package/docs/CROSS_PLATFORM.zh.md +18 -0
  186. package/docs/EXECUTION-LOOP.md +28 -10
  187. package/docs/FEATURES.md +129 -7
  188. package/docs/FEATURES.zh.md +97 -6
  189. package/docs/MIGRATION.md +2 -2
  190. package/docs/PIPELINE.md +293 -0
  191. package/docs/QA-A2-GUI-TUI.md +205 -0
  192. package/docs/README.ru.md +43 -4
  193. package/docs/README.zh.md +44 -4
  194. package/docs/SAFETY.md +23 -3
  195. package/gui-experimental.cjs +9 -8
  196. package/locales/en.json +58 -3
  197. package/locales/ru.json +58 -3
  198. package/locales/zh.json +58 -3
  199. package/opencode.pipeline.yaml +35 -0
  200. package/package.json +36 -4
  201. package/scripts/check-eslint-baseline.mjs +139 -0
  202. package/scripts/gen-test-plan-counters.mjs +117 -0
  203. package/scripts/github-ci-fetch.ps1 +37 -0
  204. package/scripts/pl-commit.ps1 +112 -0
  205. package/scripts/qa-a2-commit.ps1 +104 -0
  206. package/scripts/test-home.mjs +107 -0
  207. package/skills/scheduled-job-best-practices/SKILL.md +95 -1
  208. package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
  209. package/src/cli.ts +417 -0
  210. package/src/core/analytics.ts +27 -4
  211. package/src/core/audit.ts +25 -0
  212. package/src/core/budget.ts +340 -0
  213. package/src/core/cron-to-schtasks.ts +42 -0
  214. package/src/core/dry-run.ts +235 -12
  215. package/src/core/execution.ts +538 -0
  216. package/src/core/feedback.ts +582 -0
  217. package/src/core/file-watcher.ts +2 -2
  218. package/src/core/gate-integrity.ts +330 -0
  219. package/src/core/git-trigger.ts +18 -5
  220. package/src/core/guard-run.ts +119 -0
  221. package/src/core/guard.ts +431 -0
  222. package/src/core/local-ai.ts +7 -3
  223. package/src/core/lock.ts +178 -37
  224. package/src/core/matrix.ts +158 -52
  225. package/src/core/mission.ts +531 -0
  226. package/src/core/native-notify.ts +1 -1
  227. package/src/core/opencode-models.ts +30 -21
  228. package/src/core/opencode-usage.ts +182 -0
  229. package/src/core/pipeline-apply.ts +158 -0
  230. package/src/core/pipeline-io.ts +96 -0
  231. package/src/core/pipeline-map.ts +283 -0
  232. package/src/core/pipeline-spec.ts +775 -0
  233. package/src/core/ps-wrapper.ts +435 -66
  234. package/src/core/record-history.ts +258 -81
  235. package/src/core/router/rules.ts +6 -0
  236. package/src/core/run-mode.ts +19 -0
  237. package/src/core/schedule-gate.ts +1 -1
  238. package/src/core/scheduler/at-fallback.ts +1 -1
  239. package/src/core/scheduler/linux.ts +40 -11
  240. package/src/core/scheduler/logs.ts +34 -3
  241. package/src/core/scheduler/mac.ts +174 -14
  242. package/src/core/scheduler/registry.ts +2 -2
  243. package/src/core/scheduler/windows.ts +19 -15
  244. package/src/core/secrets.ts +26 -19
  245. package/src/core/self-analysis.ts +75 -29
  246. package/src/core/shutdown.ts +90 -4
  247. package/src/core/structured-log.ts +89 -5
  248. package/src/core/telegram.ts +2 -2
  249. package/src/core/triage-worker.ts +7 -7
  250. package/src/core/triage.ts +2 -2
  251. package/src/core/usage-surface.ts +70 -0
  252. package/src/core/worktree-run.ts +199 -0
  253. package/src/core/worktree.ts +600 -0
  254. package/src/core/wrappers/bash.ts +248 -26
  255. package/src/db/capability-repo.ts +127 -10
  256. package/src/db/history-repo.ts +281 -40
  257. package/src/db/metrics-repo.ts +40 -13
  258. package/src/db/migrate.ts +57 -32
  259. package/src/db/recovery.ts +12 -5
  260. package/src/db/run-journal.ts +100 -13
  261. package/src/db/run-resume.ts +17 -1
  262. package/src/db/runs-repo.ts +147 -65
  263. package/src/db/schema.ts +134 -2
  264. package/src/db/templates-repo.ts +5 -3
  265. package/src/gui.tsx +438 -18
  266. package/src/history.ts +11 -4
  267. package/src/hook-output.ts +39 -0
  268. package/src/i18n.ts +12 -4
  269. package/src/index.ts +1902 -320
  270. package/src/notifications.ts +227 -47
  271. package/src/profiles.ts +88 -10
  272. package/src/rpc.ts +158 -0
  273. package/src/server.ts +201 -41
  274. package/src/settings.ts +125 -5
  275. package/src/shared/jobs-view.ts +3 -1
  276. package/src/task-transfer.ts +90 -6
  277. package/src/templates.ts +3 -3
  278. package/src/types.ts +23 -2
  279. package/src/workspaces.ts +37 -14
@@ -9,13 +9,16 @@ import {
9
9
  isShadowActive,
10
10
  type TriageSettings,
11
11
  type NotificationDedupSettings,
12
- type NotificationEmbeddingSettings,
13
12
  } from "./settings.js";
14
13
  import {
15
14
  buildAnalytics,
16
15
  type AnalyticsRecord,
17
16
  type ErrorAnalyticsRow,
18
17
  } from "./core/analytics.js";
18
+ import {
19
+ formatBudgetAlertMessage,
20
+ type BudgetGateDecision,
21
+ } from "./core/budget.js";
19
22
  import { getHistory } from "./db/history-repo.js";
20
23
  import { getDb, withTransaction } from "./db/index.js";
21
24
  import { sendTelegramMessage } from "./core/telegram.js";
@@ -30,8 +33,15 @@ import {
30
33
  import type { TriageInput } from "./core/triage.js";
31
34
  import { t } from "./i18n.js";
32
35
 
33
- /** Статус завершения задачи, который приходит из record-history. */
34
- export type NotificationStatus = "success" | "error" | "timeout" | string;
36
+ /**
37
+ * Статус завершения задачи, который приходит из record-history.
38
+ *
39
+ * Три известных значения оставлены для автодополнения, `(string & {})`
40
+ * сохраняет возможность прийти произвольному статусу из внешней истории
41
+ * (иначе @typescript-eslint/no-redundant-type-constituents считает literals
42
+ * перекрытыми `string`). Поведение и пейлоады не меняются — это только тип.
43
+ */
44
+ export type NotificationStatus = "success" | "error" | "timeout" | (string & {});
35
45
 
36
46
  /** Содержимое уведомления. */
37
47
  export interface NotificationPayload {
@@ -246,6 +256,19 @@ function validateWebhookUrl(url: string): URL {
246
256
  return parsed;
247
257
  }
248
258
 
259
+ /**
260
+ * Type guard для AbortError от fetch (DOMException): проверяем свойство `name`
261
+ * на границе внешнего API, не расширяя значение до `any`.
262
+ */
263
+ function isAbortError(err: unknown): boolean {
264
+ return (
265
+ typeof err === "object" &&
266
+ err !== null &&
267
+ "name" in err &&
268
+ err.name === "AbortError"
269
+ );
270
+ }
271
+
249
272
  /** Одна попытка POST. Бросает WebhookError с признаком retryable. */
250
273
  async function postOnce(
251
274
  parsed: URL,
@@ -270,8 +293,8 @@ async function postOnce(
270
293
  retryable,
271
294
  );
272
295
  }
273
- } catch (err: any) {
274
- if (err?.name === "AbortError") {
296
+ } catch (err: unknown) {
297
+ if (isAbortError(err)) {
275
298
  throw new WebhookError(
276
299
  t("notify.error.webhookTimeout", { seconds: timeoutMs / 1000 }),
277
300
  true,
@@ -419,7 +442,7 @@ async function deliverDetailed(
419
442
  await sendWebhook(webhook.url, message, webhookOptionsFrom(config));
420
443
  console.log("[agent-steward] Уведомление отправлено в webhook.");
421
444
  results.push({ channel: "webhook", ok: true });
422
- } catch (err: any) {
445
+ } catch (err: unknown) {
423
446
  const text = err instanceof Error ? err.message : String(err);
424
447
  console.error(`[agent-steward] Webhook: ${text}`);
425
448
  results.push({ channel: "webhook", ok: false, error: text });
@@ -445,7 +468,7 @@ async function deliverDetailed(
445
468
  });
446
469
  console.log("[agent-steward] Уведомление отправлено в Telegram.");
447
470
  results.push({ channel: "telegram", ok: true });
448
- } catch (err: any) {
471
+ } catch (err: unknown) {
449
472
  const text = err instanceof Error ? err.message : String(err);
450
473
  console.error(`[agent-steward] Telegram: ${text}`);
451
474
  results.push({ channel: "telegram", ok: false, error: text });
@@ -478,6 +501,49 @@ async function deliver(config: NotificationSettings, message: string): Promise<b
478
501
  return results.some((item) => item.ok);
479
502
  }
480
503
 
504
+ /** E-1.3: окно дедупа бюджетного алерта — не чаще одного раза в сутки. */
505
+ const BUDGET_ALERT_WINDOW_MINUTES = 24 * 60;
506
+
507
+ /**
508
+ * E-1.3: уведомление о превышении бюджета во все включённые каналы.
509
+ *
510
+ * Повторяющиеся алерты с той же причиной подавляются в течение 24 часов
511
+ * через общую таблицу `notification_dedup`. Ошибки доставки и БД только
512
+ * логируются: уведомление не должно ломать запуск задачи (fail-open).
513
+ *
514
+ * @returns true, если хотя бы один канал успешно доставил алерт.
515
+ */
516
+ export async function notifyBudgetExceeded(
517
+ decision: BudgetGateDecision,
518
+ ): Promise<boolean> {
519
+ if (decision.allowed) return false;
520
+ try {
521
+ const settings = await loadSettings();
522
+ const config = settings.notifications;
523
+ if (!config?.enabled) return false;
524
+
525
+ const dedup: NotificationDedupSettings = {
526
+ enabled: true,
527
+ windowMinutes: BUDGET_ALERT_WINDOW_MINUTES,
528
+ suppressDuplicates: true,
529
+ importantStatuses: [],
530
+ maxCount: 1,
531
+ };
532
+ const db = getDb();
533
+ const key = dedupKey("budget", decision.reason);
534
+ const { isDuplicate } = withTransaction(() =>
535
+ dedupReadOrCreate(db, key, "budget", decision.reason, dedup),
536
+ );
537
+ if (isDuplicate) return false;
538
+
539
+ return await deliver(config, formatBudgetAlertMessage(decision));
540
+ } catch (err) {
541
+ const text = err instanceof Error ? err.message : String(err);
542
+ console.error(`[agent-steward] Бюджетный алерт не отправлен: ${text}`);
543
+ return false;
544
+ }
545
+ }
546
+
481
547
  /**
482
548
  * Уведомляет о завершении задачи во все включённые каналы.
483
549
  *
@@ -505,6 +571,21 @@ export interface DedupRecord {
505
571
  windowMinutes: number;
506
572
  }
507
573
 
574
+ /**
575
+ * Строка таблицы `notification_dedup` в snake_case (как её возвращает
576
+ * `node:sqlite`). Граница БД: `SqliteStatement.get()` типизирован как `any`
577
+ * в src/db/index.ts, поэтому сужаем до доменного интерфейса сразу на чтении.
578
+ */
579
+ interface DedupRow {
580
+ key: string;
581
+ task_name: string;
582
+ status: string;
583
+ count: number;
584
+ first_at: string;
585
+ last_at: string;
586
+ window_minutes: number | null;
587
+ }
588
+
508
589
  /** Ключ дедупа: комбинация задачи и статуса. */
509
590
  function dedupKey(taskName: string, status: string): string {
510
591
  return (taskName + "|" + status).toLowerCase();
@@ -524,7 +605,7 @@ function dedupReadOrCreate(
524
605
  const now = new Date().toISOString();
525
606
  const row = db
526
607
  .prepare("SELECT * FROM notification_dedup WHERE key = ?")
527
- .get(key);
608
+ .get(key) as DedupRow | undefined;
528
609
 
529
610
  if (!row) {
530
611
  db.prepare(
@@ -611,15 +692,10 @@ function messageWithDedupCount(message: string, count: number): string {
611
692
  * В будущем можно заменить на nomic-embed-text-v2-moe или другую модель.
612
693
  */
613
694
 
614
- interface EmbeddingRecord {
695
+ /** Строка `notification_embeddings`, достаточная для поиска похожего вектора. */
696
+ interface EmbeddingRow {
615
697
  key: string;
616
- task_name: string;
617
- status: string;
618
- message_text: string;
619
- embedding: number[];
620
- dimension: number;
621
- created_at: string;
622
- window_minutes: number;
698
+ embedding_json: string;
623
699
  }
624
700
 
625
701
  /** Размерность вектора фиксирована: feature hashing, а не словарь сообщения. */
@@ -639,13 +715,43 @@ function embeddingKey(taskName: string, status: string): string {
639
715
  return `emb:${(taskName + "|" + status).toLowerCase()}`;
640
716
  }
641
717
 
642
- /** Простой токенизатор: слова, цифры, нижний регистр. */
643
- function tokenize(text: string): string[] {
644
- return text
645
- .toLowerCase()
646
- .replace(/[^a-zа-яё0-9\s]/g, " ")
647
- .split(/\s+/)
648
- .filter((t) => t.length > 0);
718
+ /**
719
+ * CJK-символы: хирагана, катакана, хань, совместимые идеограммы, хангыль.
720
+ * Регэксп без `g`, проверяется посимвольно.
721
+ */
722
+ const CJK_CHAR_RE = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]/;
723
+
724
+ /** Латиница, кириллица, цифры и диакритика — как раньше, но без вырезания CJK. */
725
+ const TOKEN_CHUNK_RE =
726
+ /[a-z\u00c0-\u024f\u0400-\u04ff0-9]+|[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]+/g;
727
+
728
+ /**
729
+ * Простой токенизатор: слова, цифры, нижний регистр.
730
+ *
731
+ * B14: CJK-блоки больше не вырезаются. Иероглифы не разделены пробелами,
732
+ * поэтому слово режется на перекрывающиеся биграммы («任务失败» → «任务»,
733
+ * «务失», «失败»); одиночный иероглиф остаётся униграммой. Это даёт
734
+ * ненулевой вектор для `zh`/`ja`/`ko` и работает без словарей и
735
+ * `Intl.Segmenter`, одинаково на всех платформах.
736
+ */
737
+ export function tokenize(text: string): string[] {
738
+ const tokens: string[] = [];
739
+ for (const match of text.toLowerCase().matchAll(TOKEN_CHUNK_RE)) {
740
+ const chunk = match[0];
741
+ if (CJK_CHAR_RE.test(chunk[0])) {
742
+ const chars = Array.from(chunk);
743
+ if (chars.length === 1) {
744
+ tokens.push(chars[0]);
745
+ continue;
746
+ }
747
+ for (let i = 0; i < chars.length - 1; i++) {
748
+ tokens.push(chars[i] + chars[i + 1]);
749
+ }
750
+ } else {
751
+ tokens.push(chunk);
752
+ }
753
+ }
754
+ return tokens;
649
755
  }
650
756
 
651
757
  /**
@@ -659,9 +765,9 @@ function tokenize(text: string): string[] {
659
765
  * Вес — 1 + log(tf), L2-нормализация; знак из старшего бита хеша снижает
660
766
  * влияние коллизий.
661
767
  */
662
- function textToVector(text: string): number[] {
768
+ export function textToVector(text: string): number[] {
663
769
  const tokens = tokenize(text);
664
- const vec: number[] = new Array(EMBEDDING_DIMENSION).fill(0);
770
+ const vec: number[] = new Array<number>(EMBEDDING_DIMENSION).fill(0);
665
771
  if (tokens.length === 0) return vec;
666
772
 
667
773
  const counts = new Map<string, number>();
@@ -699,6 +805,26 @@ function cosineSimilarity(a: number[], b: number[]): number {
699
805
  return dot / denom;
700
806
  }
701
807
 
808
+ /**
809
+ * Безопасный разбор JSON-вектора из БД — граница внешних данных.
810
+ * Возвращает null для битых/нечисловых записей вместо `any` из JSON.parse.
811
+ */
812
+ function parseNumberArray(json: string): number[] | null {
813
+ let value: unknown;
814
+ try {
815
+ value = JSON.parse(json);
816
+ } catch {
817
+ return null;
818
+ }
819
+ if (!Array.isArray(value)) return null;
820
+ const result: number[] = [];
821
+ for (const item of value) {
822
+ if (typeof item !== "number") return null;
823
+ result.push(item);
824
+ }
825
+ return result;
826
+ }
827
+
702
828
  /**
703
829
  * Проверяет, есть ли в БД вектор, достаточно похожий на text.
704
830
  * Сравниваются только векторы той же задачи и того же статуса: иначе успех
@@ -721,24 +847,18 @@ function embeddingExists(
721
847
  "WHERE task_name = ? AND status = ? AND created_at >= ? " +
722
848
  "ORDER BY created_at DESC LIMIT 500",
723
849
  )
724
- .all(taskName, status, since) as {
725
- key: string;
726
- embedding_json: string;
727
- }[];
850
+ .all(taskName, status, since) as EmbeddingRow[];
728
851
  const vec = textToVector(message);
729
852
  let bestKey = "";
730
853
  let bestSim = 0;
731
854
  for (const row of rows) {
732
- try {
733
- const emb: number[] = JSON.parse(row.embedding_json);
734
- if (!Array.isArray(emb) || emb.length !== vec.length) continue;
735
- const sim = cosineSimilarity(vec, emb);
736
- if (sim > bestSim) {
737
- bestSim = sim;
738
- bestKey = row.key;
739
- }
740
- } catch {
741
- // пропускаем битую запись
855
+ const emb = parseNumberArray(row.embedding_json);
856
+ if (emb === null) continue;
857
+ if (emb.length !== vec.length) continue;
858
+ const sim = cosineSimilarity(vec, emb);
859
+ if (sim > bestSim) {
860
+ bestSim = sim;
861
+ bestKey = row.key;
742
862
  }
743
863
  }
744
864
  if (bestSim >= threshold) return { found: true, key: bestKey };
@@ -838,7 +958,7 @@ export async function notifyTaskCompletion(
838
958
  );
839
959
  // Injected scheduler может быть асинхронным — не оставляем rejection.
840
960
  if (job && typeof (job as PromiseLike<unknown>).then === "function") {
841
- void Promise.resolve(job).catch((err: any) => {
961
+ void Promise.resolve(job).catch((err: unknown) => {
842
962
  console.error(
843
963
  `[agent-steward] Ошибка фонового триажа: ${
844
964
  err instanceof Error ? err.message : String(err)
@@ -846,7 +966,7 @@ export async function notifyTaskCompletion(
846
966
  );
847
967
  });
848
968
  }
849
- } catch (err: any) {
969
+ } catch (err: unknown) {
850
970
  console.error(
851
971
  `[agent-steward] Не удалось запустить фоновый триаж: ${
852
972
  err instanceof Error ? err.message : String(err)
@@ -953,7 +1073,7 @@ export async function notifyTaskCompletion(
953
1073
  }
954
1074
  }
955
1075
  await deliver(config, finalMessage);
956
- } catch (err: any) {
1076
+ } catch (err: unknown) {
957
1077
  // Уведомление не должно ломать запись истории и саму задачу.
958
1078
  console.error(
959
1079
  `[agent-steward] Ошибка подготовки уведомления: ${
@@ -988,7 +1108,7 @@ export async function notifyMatrixCompletion(
988
1108
  }
989
1109
 
990
1110
  await deliver(config, formatMatrixMessage(info));
991
- } catch (err: any) {
1111
+ } catch (err: unknown) {
992
1112
  console.error(
993
1113
  `[agent-steward] Ошибка уведомления о матрице: ${
994
1114
  err instanceof Error ? err.message : String(err)
@@ -1063,7 +1183,7 @@ export async function notifyStuckMatrix(stuck: StuckMatrixClone): Promise<boolea
1063
1183
  if (!config.matrix?.enabled) return false;
1064
1184
  if (!isTaskAllowed(stuck.parentName, config.filters)) return false;
1065
1185
  return await deliver(config, formatStuckMatrixMessage(stuck));
1066
- } catch (err: any) {
1186
+ } catch (err: unknown) {
1067
1187
  console.error(
1068
1188
  `[agent-steward] Ошибка уведомления о зависшей матрице: ${
1069
1189
  err instanceof Error ? err.message : String(err)
@@ -1238,7 +1358,7 @@ export async function sendDigestNow(
1238
1358
  });
1239
1359
  }
1240
1360
  return { success: true, message: t("notify.ok.digestSent") };
1241
- } catch (err: any) {
1361
+ } catch (err: unknown) {
1242
1362
  return {
1243
1363
  success: false,
1244
1364
  message: err instanceof Error ? err.message : String(err),
@@ -1262,7 +1382,7 @@ export async function maybeSendDigest(now: Date = new Date()): Promise<boolean>
1262
1382
  }
1263
1383
  console.error(`[agent-steward] Дайджест не отправлен: ${result.message}`);
1264
1384
  return false;
1265
- } catch (err: any) {
1385
+ } catch (err: unknown) {
1266
1386
  console.error(
1267
1387
  `[agent-steward] Ошибка дайджеста: ${
1268
1388
  err instanceof Error ? err.message : String(err)
@@ -1337,10 +1457,70 @@ export async function sendTestNotification(
1337
1457
  success: failed.length === 0 && sent.length > 0,
1338
1458
  message: parts.join(" ") || t("notify.error.testNotSent"),
1339
1459
  };
1340
- } catch (err: any) {
1460
+ } catch (err: unknown) {
1461
+ return {
1462
+ success: false,
1463
+ message: err instanceof Error ? err.message : String(err),
1464
+ };
1465
+ }
1466
+ }
1467
+
1468
+ /**
1469
+ * Отправляет отчёт о баге во все включённые каналы (webhook/telegram/native).
1470
+ * Используется агент-инструментом `report_bug`: пользователь плагина описывает
1471
+ * проблему через агент-чат, а отчёт с логами и аналитикой уходит разработчику
1472
+ * (владельцу настроенного бота/вебхука).
1473
+ */
1474
+ export async function sendBugReport(
1475
+ report: string,
1476
+ channel: "all" | NotificationChannel = "all",
1477
+ ): Promise<{
1478
+ success: boolean;
1479
+ message: string;
1480
+ results: ChannelDeliveryResult[];
1481
+ }> {
1482
+ try {
1483
+ const settings = await loadSettings();
1484
+ const config = settings.notifications;
1485
+ if (!config?.enabled) {
1486
+ return {
1487
+ success: false,
1488
+ message: t("notify.error.testDisabled"),
1489
+ results: [],
1490
+ };
1491
+ }
1492
+
1493
+ const enabled: NotificationChannel[] = [];
1494
+ if (config.webhook?.enabled && config.webhook.url.trim()) enabled.push("webhook");
1495
+ if (config.telegram?.enabled) enabled.push("telegram");
1496
+ if (config.native?.enabled) enabled.push("native");
1497
+ if (enabled.length === 0) {
1498
+ return {
1499
+ success: false,
1500
+ message: t("notify.error.testNoChannels"),
1501
+ results: [],
1502
+ };
1503
+ }
1504
+
1505
+ const results = await deliverDetailed(
1506
+ config,
1507
+ report,
1508
+ channel === "all" ? undefined : channel,
1509
+ );
1510
+ const sent = results.filter((item) => item.ok).map((item) => item.channel);
1511
+ const failed = results.filter((item) => !item.ok);
1512
+ return {
1513
+ success: failed.length === 0 && sent.length > 0,
1514
+ message: sent.length > 0
1515
+ ? `Отправлено в каналы: ${sent.join(", ")}`
1516
+ : t("notify.error.testNotSent"),
1517
+ results,
1518
+ };
1519
+ } catch (err: unknown) {
1341
1520
  return {
1342
1521
  success: false,
1343
1522
  message: err instanceof Error ? err.message : String(err),
1523
+ results: [],
1344
1524
  };
1345
1525
  }
1346
1526
  }
package/src/profiles.ts CHANGED
@@ -194,17 +194,83 @@ function profileMetaFile(name: string): string {
194
194
  return path.join(getProfileDir(name), "profile.json");
195
195
  }
196
196
 
197
+ /**
198
+ * Порты, зарезервированные за профилем default: основной (PREFERRED_PORT
199
+ * в server.ts) и запасной. У default может не быть profile.json, поэтому
200
+ * в listProfiles() его порт — null, и раньше аллокатор выдавал 3782 второму
201
+ * профилю: два дашборда дрались за один порт.
202
+ */
203
+ const DEFAULT_PROFILE_PORTS = new Set([3782, 4782]);
204
+ const FIRST_PROFILE_PORT = 3783;
205
+ const LAST_PORT = 65535;
206
+
207
+ /**
208
+ * Свободный порт для профиля без вызова listProfiles()/readProfileMeta()
209
+ * (иначе рекурсия: allocateProfilePort -> listProfiles -> readProfileMeta).
210
+ * Сканирует profile.json всех профилей напрямую с файловой системы.
211
+ * Возвращает null, если свободных портов не осталось.
212
+ */
213
+ function findFreeProfilePort(): number | null {
214
+ const used = new Set<number>(DEFAULT_PROFILE_PORTS);
215
+ const fromEnv = Number(process.env.OPENCODE_SCHEDULER_PORT);
216
+ if (Number.isFinite(fromEnv) && fromEnv >= 1 && fromEnv <= LAST_PORT) {
217
+ used.add(Math.floor(fromEnv));
218
+ }
219
+ const profilesRoot = path.join(getBasePluginDir(), "profiles");
220
+ let entries: fs.Dirent[] = [];
221
+ try {
222
+ entries = fs.readdirSync(profilesRoot, { withFileTypes: true });
223
+ } catch {
224
+ // profiles/ ещё нет — учитываем только зарезервированные и env.
225
+ }
226
+ for (const entry of entries) {
227
+ if (!entry.isDirectory()) continue;
228
+ try {
229
+ const raw = fs.readFileSync(
230
+ path.join(profilesRoot, entry.name, "profile.json"),
231
+ "utf8",
232
+ );
233
+ const parsed = JSON.parse(raw) as Partial<ProfileMeta>;
234
+ const port = Number(parsed?.port);
235
+ if (Number.isFinite(port) && port >= 1 && port <= LAST_PORT) {
236
+ used.add(Math.floor(port));
237
+ }
238
+ } catch {
239
+ // Битый/отсутствующий profile.json — игнорируем.
240
+ }
241
+ }
242
+ for (let port = FIRST_PROFILE_PORT; port <= LAST_PORT; port += 1) {
243
+ if (!used.has(port)) return port;
244
+ }
245
+ return null;
246
+ }
247
+
197
248
  /** Читает profile.json профиля (или null, если файла нет/он битый). */
198
249
  export function readProfileMeta(name: string): ProfileMeta | null {
199
250
  try {
200
- const raw = fs.readFileSync(profileMetaFile(name), "utf8");
251
+ const file = profileMetaFile(name);
252
+ const raw = fs.readFileSync(file, "utf8");
201
253
  const parsed = JSON.parse(raw) as Partial<ProfileMeta>;
202
254
  const profileName = sanitizeProfileName(parsed?.name ?? name);
203
- const port = Number(parsed?.port);
204
- return {
205
- name: profileName,
206
- port: Number.isFinite(port) && port >= 1 && port <= 65535 ? Math.floor(port) : 0,
207
- };
255
+ let port = Number(parsed?.port);
256
+ port = Number.isFinite(port) && port >= 1 && port <= LAST_PORT ? Math.floor(port) : 0;
257
+
258
+ // B4.3 (QA #3): профили, созданные до B4.2, могли получить порт default
259
+ // (3782/4782). Он зарезервирован — два дашборда дрались бы за один порт.
260
+ // Мигрируем такой профиль на свободный порт и перезаписываем profile.json.
261
+ // Идемпотентно: после первой миграции порт уже не из DEFAULT_PROFILE_PORTS.
262
+ if (name !== DEFAULT_PROFILE && port > 0 && DEFAULT_PROFILE_PORTS.has(port)) {
263
+ const free = findFreeProfilePort();
264
+ if (free === null) return { name: profileName, port: 0 };
265
+ fs.writeFileSync(
266
+ file,
267
+ JSON.stringify({ ...parsed, name: profileName, port: free }, null, 2),
268
+ "utf8",
269
+ );
270
+ port = free;
271
+ }
272
+
273
+ return { name: profileName, port };
208
274
  } catch {
209
275
  return null;
210
276
  }
@@ -253,16 +319,28 @@ export function listProfiles(): ProfileInfo[] {
253
319
  });
254
320
  }
255
321
 
256
- /** Свободный порт для нового профиля: 3782+N, занятые profile.json пропускаются. */
322
+ /**
323
+ * Свободный порт для нового профиля (B4.2).
324
+ *
325
+ * Исключает зарезервированные порты default, порты из profile.json всех
326
+ * профилей и порт, заданный через OPENCODE_SCHEDULER_PORT. Сканирует диапазон
327
+ * от 3783 до 65535 и берёт первый не занятый — прежняя формула
328
+ * `3782 + used.size` могла выдать уже занятый порт (например, при
329
+ * зарезервированном 3783 и одном профиле).
330
+ */
257
331
  function allocateProfilePort(): number {
258
- const used = new Set<number>();
332
+ const used = new Set<number>(DEFAULT_PROFILE_PORTS);
259
333
  for (const profile of listProfiles()) {
260
334
  if (profile.port) used.add(profile.port);
261
335
  }
262
- for (let port = 3782; port < 3882; port += 1) {
336
+ const fromEnv = Number(process.env.OPENCODE_SCHEDULER_PORT);
337
+ if (Number.isFinite(fromEnv) && fromEnv >= 1 && fromEnv <= LAST_PORT) {
338
+ used.add(Math.floor(fromEnv));
339
+ }
340
+ for (let port = FIRST_PROFILE_PORT; port <= LAST_PORT; port += 1) {
263
341
  if (!used.has(port)) return port;
264
342
  }
265
- return 3782 + used.size;
343
+ throw new Error("Не удалось выделить порт профилю: свободных портов не осталось.");
266
344
  }
267
345
 
268
346
  /**