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
package/src/server.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import http from "node:http";
2
+ import { randomBytes } from "node:crypto";
2
3
  import fs from "node:fs/promises";
3
4
  import { execFile } from "node:child_process";
4
5
  import { promisify } from "node:util";
@@ -9,9 +10,16 @@ import { getSchedulerTitle } from "./core/scheduler/index.js";
9
10
  import { getPluginVersion } from "./version.js";
10
11
  import { checkpointDb, getDbFile, getDbStatus } from "./db/index.js";
11
12
  import { listWorkspaces } from "./workspaces.js";
12
- import { getProfileName, getProfilePort } from "./profiles.js";
13
+ import { DEFAULT_PROFILE, getProfileName, getProfilePort } from "./profiles.js";
13
14
  import { simulatePipeline } from "./core/dry-run.js";
14
15
  import { loadSettings } from "./settings.js";
16
+ import {
17
+ DEFAULT_MODEL_PRICE_PER_MILLION,
18
+ DEFAULT_PRICE_PER_MILLION,
19
+ catalogPricePerMillion,
20
+ normalizeModelId,
21
+ resolveWhatIfModels,
22
+ } from "./core/opencode-models.js";
15
23
  import {
16
24
  authenticateHookRequest,
17
25
  extractHookSignature,
@@ -62,6 +70,14 @@ function normalizeProcessName(name: string): string {
62
70
  const DASHBOARD_HEADER = "x-plugin-dashboard";
63
71
  const DASHBOARD_MARKER = "agent-steward";
64
72
 
73
+ /**
74
+ * Профиль, которому принадлежит ответившее приложение (B4).
75
+ * Маркер DASHBOARD_MARKER одинаков у всех профилей, поэтому без этого
76
+ * заголовка второй профиль принимал чужой дашборд за свой: переиспользовал
77
+ * чужой порт и показывал данные другого профиля.
78
+ */
79
+ const PROFILE_HEADER = "x-plugin-profile";
80
+
65
81
  /** Переопределение портов (используется в тестах; по умолчанию 3782/4782). */
66
82
  export interface DashboardPorts {
67
83
  preferred?: number;
@@ -158,25 +174,42 @@ export interface ModelAnalysis {
158
174
  successRate: number;
159
175
  }
160
176
 
177
+ /** Чтение JSON из переменной окружения с фолбэком на значение по умолчанию. */
178
+ function envJson<T>(name: string, fallback: T): T {
179
+ const raw = process.env[name];
180
+ if (!raw) return fallback;
181
+ try {
182
+ return JSON.parse(raw) as T;
183
+ } catch {
184
+ console.warn(
185
+ `[scheduler] Неверный JSON в переменной ${name}, используются значения по умолчанию.`,
186
+ );
187
+ return fallback;
188
+ }
189
+ }
190
+
191
+ /** Ручное переопределение цен: OPENCODE_SCHEDULER_MODEL_PRICES (JSON). */
192
+ const envModelPrices = envJson<Record<string, number>>(
193
+ "OPENCODE_SCHEDULER_MODEL_PRICES",
194
+ {},
195
+ );
196
+
161
197
  /**
162
- * Приблизительные цены моделей в USD за 1M токенов.
163
- * Используются для What-If-анализа, когда в логе нет точной стоимости.
198
+ * Цена модели за 1M токенов.
199
+ *
200
+ * Порядок: ручное переопределение → каталог цен OpenCode (models.dev) →
201
+ * встроенная таблица → средняя оценка.
164
202
  */
165
- const MODEL_PRICE_PER_MILLION: Record<string, number> = {
166
- "openai/gpt-4o": 10,
167
- "openai/gpt-4o-mini": 0.6,
168
- "deepseek/deepseek-coder": 0.28,
169
- "anthropic/claude-3-5-sonnet": 9,
170
- "anthropic/claude-3-5-haiku": 1.2,
171
- "google/gemini-2.5-pro": 3.5,
172
- "google/gemini-2.0-flash": 0.3,
173
- };
174
- const DEFAULT_PRICE_PER_MILLION = 3;
175
-
176
- /** Цена модели за 1M токенов (fallback — средняя оценка). */
177
- function modelPrice(model: string | undefined): number {
178
- const key = (model ?? "").trim().toLowerCase();
179
- return MODEL_PRICE_PER_MILLION[key] ?? DEFAULT_PRICE_PER_MILLION;
203
+ export function modelPrice(model: string | undefined): number {
204
+ const key = normalizeModelId(model);
205
+
206
+ const override = envModelPrices[key];
207
+ if (typeof override === "number" && Number.isFinite(override)) return override;
208
+
209
+ const fromOpencode = catalogPricePerMillion(key);
210
+ if (fromOpencode !== null) return fromOpencode;
211
+
212
+ return DEFAULT_MODEL_PRICE_PER_MILLION[key] ?? DEFAULT_PRICE_PER_MILLION;
180
213
  }
181
214
 
182
215
  /** Оценка стоимости запуска по токенам (если точная цена неизвестна). */
@@ -188,7 +221,7 @@ function estimateCost(tokens: number, model: string | undefined): number {
188
221
  * Агрегирует историю по моделям и считает сценарии What-If.
189
222
  * Возвращает данные для GET /api/models-analysis и блока дашборда.
190
223
  */
191
- function aggregateModels(
224
+ export function aggregateModels(
192
225
  history: {
193
226
  status: string;
194
227
  durationMs: number;
@@ -239,14 +272,33 @@ function aggregateModels(
239
272
  }))
240
273
  .sort((a, b) => b.totalRuns - a.totalRuns);
241
274
 
242
- const whatIfModels = ["openai/gpt-4o", "deepseek/deepseek-coder"];
243
- const whatIf = whatIfModels.map((model) => ({
275
+ // What-If: сначала модели, которые реально запускались, затем по одной
276
+ // модели на каждую цену из доступных в OpenCode. Явный список из
277
+ // окружения главнее.
278
+ const usedModels = models
279
+ .map((item) => item.model)
280
+ .filter((model) => model !== "по умолчанию");
281
+ const envWhatIfModels = envJson<string[] | null>(
282
+ "OPENCODE_SCHEDULER_WHAT_IF_MODELS",
283
+ null,
284
+ );
285
+ const selection =
286
+ Array.isArray(envWhatIfModels) && envWhatIfModels.length > 0
287
+ ? { models: envWhatIfModels, source: "env" as const }
288
+ : resolveWhatIfModels(usedModels);
289
+
290
+ const whatIf = selection.models.map((model) => ({
244
291
  model,
245
292
  pricePerMillion: modelPrice(model),
246
293
  cost: Number(((totalTokens * modelPrice(model)) / 1_000_000).toFixed(4)),
247
294
  }));
248
295
 
249
- return { models, totals: { totalRuns, totalTokens, totalCost: Number(totalCost.toFixed(6)) }, whatIf };
296
+ return {
297
+ models,
298
+ totals: { totalRuns, totalTokens, totalCost: Number(totalCost.toFixed(6)) },
299
+ whatIf,
300
+ whatIfSource: selection.source,
301
+ };
250
302
  }
251
303
 
252
304
  /**
@@ -383,14 +435,23 @@ export async function startDashboardServer(
383
435
  return null;
384
436
  }
385
437
 
386
- // Порт занят: если это уже наш дашборд (другой экземпляр плагина
387
- // в том же процессе/сессии), переиспользуем его, а не вешаем второй порт.
388
- if (port !== 0 && (await isOwnDashboardOn(port))) {
438
+ // Порт занят: если это уже наш дашборд того же профиля (другой
439
+ // экземпляр плагина в том же процессе/сессии), переиспользуем его,
440
+ // а не вешаем второй порт. Дашборд другого профиля не наш: его нельзя
441
+ // ни переиспользовать (покажет чужие данные), ни снимать как зомби.
442
+ const probe = port !== 0 ? await probeDashboardOn(port) : null;
443
+ if (probe?.dashboard && probe.profile === getProfileName()) {
389
444
  console.log(
390
445
  `[agent-steward] Дашборд уже запущен на http://localhost:${port} — переиспользуем его.`,
391
446
  );
392
447
  return { port };
393
448
  }
449
+ if (probe?.dashboard && probe.profile !== getProfileName()) {
450
+ console.warn(
451
+ `[agent-steward] Порт ${port} занят дашбордом профиля "${probe.profile}" — не трогаем, пробуем другой порт.`,
452
+ );
453
+ continue;
454
+ }
394
455
 
395
456
  // Порт занят чужим или старым процессом: пробуем снять зомби
396
457
  // (только node/bun этого плагина) и повторить bind.
@@ -626,16 +687,34 @@ async function getProcessInfoPosix(
626
687
  }
627
688
  }
628
689
 
629
- /** Проверяет по маркер-заголовку, что на порту отвечает наш дашборд. */
630
- async function isOwnDashboardOn(port: number): Promise<boolean> {
690
+ export interface DashboardProbe {
691
+ /** На порту отвечает наш дашборд (маркер-заголовок совпал). */
692
+ dashboard: boolean;
693
+ /** Профиль ответившего дашборда; null, если это не дашборд. */
694
+ profile: string | null;
695
+ }
696
+
697
+ /**
698
+ * Проверяет по маркер-заголовку, что на порту отвечает наш дашборд,
699
+ * и определяет его профиль (B4.1).
700
+ *
701
+ * Заголовок профиля появился в B4.1. Более старые сборки его не отдают —
702
+ * таких считаем профилем `default`: до появления профилей база была одна,
703
+ * а значит старый процесс работал именно с default.
704
+ */
705
+ export async function probeDashboardOn(port: number): Promise<DashboardProbe> {
631
706
  try {
632
707
  const res = await fetch(`http://127.0.0.1:${port}/`, {
633
708
  method: "GET",
634
709
  signal: AbortSignal.timeout(1500),
635
710
  });
636
- return res.headers.get(DASHBOARD_HEADER) === DASHBOARD_MARKER;
711
+ if (res.headers.get(DASHBOARD_HEADER) !== DASHBOARD_MARKER) {
712
+ return { dashboard: false, profile: null };
713
+ }
714
+ const profile = res.headers.get(PROFILE_HEADER)?.trim() || DEFAULT_PROFILE;
715
+ return { dashboard: true, profile };
637
716
  } catch {
638
- return false;
717
+ return { dashboard: false, profile: null };
639
718
  }
640
719
  }
641
720
 
@@ -746,7 +825,10 @@ async function handleRequest(
746
825
 
747
826
  // Статический HTML-файл — страница дашборда.
748
827
  if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
749
- send(res, 200, "text/html; charset=utf-8", renderPage());
828
+ const nonce = randomBytes(16).toString("base64");
829
+ send(res, 200, "text/html; charset=utf-8", renderPage(nonce), {
830
+ "Content-Security-Policy": dashboardCsp(nonce),
831
+ });
750
832
  return;
751
833
  }
752
834
 
@@ -1337,16 +1419,43 @@ function sanitizeError(err: any): string {
1337
1419
  }
1338
1420
 
1339
1421
  /** Отправляет ответ с телом и закрывает соединение. */
1340
- function send(res: http.ServerResponse, status: number, contentType: string, body: string): void {
1422
+ function send(
1423
+ res: http.ServerResponse,
1424
+ status: number,
1425
+ contentType: string,
1426
+ body: string,
1427
+ extraHeaders?: Record<string, string>,
1428
+ ): void {
1341
1429
  res.writeHead(status, {
1342
1430
  "Content-Type": contentType,
1343
1431
  "Cache-Control": "no-store",
1344
1432
  "X-Content-Type-Options": "nosniff",
1345
1433
  [DASHBOARD_HEADER]: DASHBOARD_MARKER,
1434
+ [PROFILE_HEADER]: getProfileName(),
1435
+ ...extraHeaders,
1346
1436
  });
1347
1437
  res.end(body);
1348
1438
  }
1349
1439
 
1440
+ /**
1441
+ * CSP страницы дашборда: defense in depth к экранированию (B3.4).
1442
+ * Единственный инлайн-скрипт помечается nonce, внешние скрипты запрещены;
1443
+ * инлайн-стили остаются разрешёнными, потому что разметка использует style="…".
1444
+ */
1445
+ function dashboardCsp(nonce: string): string {
1446
+ return [
1447
+ "default-src 'none'",
1448
+ `script-src 'nonce-${nonce}'`,
1449
+ "style-src 'unsafe-inline'",
1450
+ "connect-src 'self'",
1451
+ "img-src 'self' data:",
1452
+ "base-uri 'none'",
1453
+ "form-action 'none'",
1454
+ "frame-ancestors 'none'",
1455
+ "object-src 'none'",
1456
+ ].join("; ");
1457
+ }
1458
+
1350
1459
  /** Отправляет бинарный файл (скачивание .db-бэкапа). */
1351
1460
  function sendBuffer(
1352
1461
  res: http.ServerResponse,
@@ -1366,6 +1475,7 @@ function sendBuffer(
1366
1475
  "Cache-Control": "no-store",
1367
1476
  "X-Content-Type-Options": "nosniff",
1368
1477
  [DASHBOARD_HEADER]: DASHBOARD_MARKER,
1478
+ [PROFILE_HEADER]: getProfileName(),
1369
1479
  });
1370
1480
  res.end(body);
1371
1481
  }
@@ -1389,6 +1499,7 @@ function sendAttachment(
1389
1499
  "Cache-Control": "no-store",
1390
1500
  "X-Content-Type-Options": "nosniff",
1391
1501
  [DASHBOARD_HEADER]: DASHBOARD_MARKER,
1502
+ [PROFILE_HEADER]: getProfileName(),
1392
1503
  });
1393
1504
  res.end(body);
1394
1505
  }
@@ -1428,7 +1539,7 @@ async function collectTasksWithMetrics(deps: DashboardDeps) {
1428
1539
  * Данные тянутся fetch'ем с JSON-API и перерисовываются каждые 5 секунд.
1429
1540
  * Внутри строковой константы не используются бэктики и ${}, чтобы не экранировать.
1430
1541
  */
1431
- function renderPage(): string {
1542
+ function renderPage(nonce: string): string {
1432
1543
  return `<!DOCTYPE html>
1433
1544
  <html lang="${getLocale()}">
1434
1545
  <head>
@@ -1713,7 +1824,7 @@ function renderPage(): string {
1713
1824
  </div>
1714
1825
  <div id="toast" role="status" aria-live="polite"></div>
1715
1826
 
1716
- <script>
1827
+ <script nonce="${nonce}">
1717
1828
  (function () {
1718
1829
  'use strict';
1719
1830
 
@@ -1721,6 +1832,7 @@ function renderPage(): string {
1721
1832
  var updated = document.getElementById('updated');
1722
1833
  var allTasks = [];
1723
1834
  var allWorkspaces = [];
1835
+ var allAnalytics = null;
1724
1836
  var activeWorkspace = 'all';
1725
1837
  /** Раскрытые родители матриц (имя → true). */
1726
1838
  var expandedMatrixParents = {};
@@ -1732,11 +1844,20 @@ function renderPage(): string {
1732
1844
  // (HTTP 499), и тогда в консоли появляется ошибка при каждой загрузке.
1733
1845
  var preferSummaryMetrics = true;
1734
1846
  var metricsFallbackLogged = false;
1847
+ // P3-29: тяжёлая аналитика обновляется реже остальных блоков.
1848
+ var ANALYTICS_INTERVAL_MS = 60000;
1735
1849
 
1850
+ // Экранирование для текстового и атрибутного контекста.
1851
+ // Раньше использовался div.innerHTML: он превращает & < > в сущности,
1852
+ // но оставляет кавычки как есть, а результат подставляется в
1853
+ // title="…", style="…", data-*="…" и href="…" — это и был вектор XSS.
1736
1854
  function esc(s) {
1737
- var d = document.createElement('div');
1738
- d.textContent = s == null ? '' : String(s);
1739
- return d.innerHTML;
1855
+ return String(s == null ? '' : s)
1856
+ .replace(/&/g, '&amp;')
1857
+ .replace(/</g, '&lt;')
1858
+ .replace(/>/g, '&gt;')
1859
+ .replace(/"/g, '&quot;')
1860
+ .replace(/'/g, '&#39;');
1740
1861
  }
1741
1862
 
1742
1863
  function toast(msg, kind) {
@@ -1806,7 +1927,7 @@ function renderPage(): string {
1806
1927
  );
1807
1928
  throw new Error('Сервер вернул не JSON. Проверьте консоль.');
1808
1929
  }
1809
- if (marker !== 'opencode-windows-scheduler') {
1930
+ if (marker !== 'agent-steward' && marker !== 'opencode-windows-scheduler') {
1810
1931
  console.warn(
1811
1932
  'В ответе нет заголовка x-plugin-dashboard — возможно, это не дашборд плагина.'
1812
1933
  );
@@ -2076,18 +2197,18 @@ function renderPage(): string {
2076
2197
  html += '</tbody></table>';
2077
2198
  box.innerHTML = html;
2078
2199
 
2079
- var gpt = null;
2080
- var deepseek = null;
2081
- for (var j = 0; j < whatIf.length; j++) {
2082
- if (whatIf[j].model === 'openai/gpt-4o') gpt = whatIf[j];
2083
- if (whatIf[j].model === 'deepseek/deepseek-coder') deepseek = whatIf[j];
2084
- }
2085
2200
  var parts = [];
2086
- if (gpt) {
2087
- parts.push('Если бы все запуски выполнялись через <b>openai/gpt-4o</b>, это стоило бы ~<b>' + money(gpt.cost) + '</b> (' + gpt.pricePerMillion + ' $/1M токенов).');
2201
+ var source = data && data.whatIfSource;
2202
+ if (source === 'opencode') {
2203
+ parts.push('Модели и цены — из OpenCode (ваши доступные модели):');
2204
+ } else if (source === 'history') {
2205
+ parts.push('Модели для сравнения — те, что уже запускались:');
2206
+ } else if (source === 'default') {
2207
+ parts.push('OpenCode недоступен, показаны модели по умолчанию:');
2088
2208
  }
2089
- if (deepseek) {
2090
- parts.push('Если через <b>deepseek/deepseek-coder</b> — <b>' + money(deepseek.cost) + '</b> (' + deepseek.pricePerMillion + ' $/1M токенов).');
2209
+ for (var j = 0; j < whatIf.length; j++) {
2210
+ var w = whatIf[j];
2211
+ parts.push('Если бы все запуски выполнялись через <b>' + esc(w.model) + '</b>, это стоило бы ~<b>' + money(w.cost) + '</b> (' + w.pricePerMillion + ' $/1M токенов).');
2091
2212
  }
2092
2213
  parts.push('Всего запусков: <b>' + totals.totalRuns + '</b>, токенов: <b>' + Number(totals.totalTokens || 0).toLocaleString('ru-RU') + '</b>, фактическая стоимость: <b>' + money(totals.totalCost) + '</b>.');
2093
2214
  text.innerHTML = parts.join(' ');
@@ -2186,8 +2307,9 @@ function renderPage(): string {
2186
2307
  var text = String(value == null ? '' : value);
2187
2308
  return text.length > max ? text.slice(0, max - 1) + '…' : text;
2188
2309
  }
2310
+ // esc() уже экранирует кавычки, отдельная подмена " больше не нужна.
2189
2311
  function attr(value) {
2190
- return esc(String(value == null ? '' : value)).replace(/"/g, '&quot;');
2312
+ return esc(value);
2191
2313
  }
2192
2314
  function statusClass(status) {
2193
2315
  if (status === 'success') return ' okg';
@@ -2314,7 +2436,7 @@ function renderPage(): string {
2314
2436
  }
2315
2437
 
2316
2438
  if (visible.length === 0) {
2317
- rows.innerHTML = '<tr><td colspan="9" class="empty">🎄 Задач пока нет. Самое время украсить ёлку!</td></tr>';
2439
+ rows.innerHTML = '<tr><td colspan="9" class="empty">' + EMPTY_TASKS_HTML + '</td></tr>';
2318
2440
  return;
2319
2441
  }
2320
2442
  var html = '';
@@ -2335,7 +2457,7 @@ function renderPage(): string {
2335
2457
  }
2336
2458
  }
2337
2459
  if (shown === 0) {
2338
- rows.innerHTML = '<tr><td colspan="9" class="empty">🎄 Задач пока нет. Самое время украсить ёлку!</td></tr>';
2460
+ rows.innerHTML = '<tr><td colspan="9" class="empty">' + EMPTY_TASKS_HTML + '</td></tr>';
2339
2461
  return;
2340
2462
  }
2341
2463
  rows.innerHTML = html;
@@ -2398,6 +2520,16 @@ function renderPage(): string {
2398
2520
  // Без него кросс-сайтовый fetch не пройдёт (нужен CORS-preflight, которого нет).
2399
2521
  var CLIENT_HEADERS = { 'X-Scheduler-Client': 'dashboard' };
2400
2522
 
2523
+ // P3-29: новогоднее оформление (снежинки и «украсить ёлку») — только по
2524
+ // явному флагу ?snow=1, чтобы не крутить 18 анимаций круглый год.
2525
+ var FESTIVE = false;
2526
+ try {
2527
+ FESTIVE = new URLSearchParams(location.search).get('snow') === '1';
2528
+ } catch (_) {}
2529
+ var EMPTY_TASKS_HTML = FESTIVE
2530
+ ? '🎄 Задач пока нет. Самое время украсить ёлку!'
2531
+ : 'Задач пока нет. Самое время создать!';
2532
+
2401
2533
  // Устойчивая загрузка: антивирусы иногда блокируют отдельные URL
2402
2534
  // (например, /api/metrics) статусом 499 и картинкой вместо JSON.
2403
2535
  // Один сбой не должен ломать весь дашборд.
@@ -2445,8 +2577,7 @@ function renderPage(): string {
2445
2577
  loadMetricsJson(),
2446
2578
  safeJson('/api/history', { records: [] }),
2447
2579
  safeJson('/api/models-analysis', { models: [], totals: {}, whatIf: [] }),
2448
- safeJson('/api/workspaces', { workspaces: [] }),
2449
- safeJson('/api/analytics?days=14', null)
2580
+ safeJson('/api/workspaces', { workspaces: [] })
2450
2581
  ]);
2451
2582
  var tasks = (results[0] && results[0].tasks) || [];
2452
2583
  var m = results[1] || {};
@@ -2466,7 +2597,7 @@ function renderPage(): string {
2466
2597
  renderGraph(tasks);
2467
2598
  renderHistory(history);
2468
2599
  renderModelsAnalysis(modelsAnalysis);
2469
- renderAnalytics(results[5]);
2600
+ renderAnalytics(allAnalytics);
2470
2601
  showServerWarn(results[0] ? null : 'Не удалось загрузить список задач — остальные блоки обновлены. Подробности в консоли (F12).');
2471
2602
  updated.textContent = 'Обновлено: ' + new Date().toLocaleTimeString();
2472
2603
  } catch (err) {
@@ -2476,6 +2607,25 @@ function renderPage(): string {
2476
2607
  }
2477
2608
  }
2478
2609
 
2610
+ // P3-29: аналитика — тяжёлая агрегация SQLite, грузим реже основных блоков
2611
+ // и используем ETag/If-None-Match, чтобы не перезапрашивать неизменённые данные.
2612
+ var analyticsEtag = null;
2613
+ async function loadAnalytics() {
2614
+ try {
2615
+ var headers = { 'X-Scheduler-Client': 'dashboard' };
2616
+ if (analyticsEtag) headers['If-None-Match'] = analyticsEtag;
2617
+ var res = await fetch('/api/analytics?days=14', { cache: 'no-store', headers: headers });
2618
+ if (res.status === 304) return; // не изменилось с прошлого раза
2619
+ analyticsEtag = res.headers.get('ETag');
2620
+ allAnalytics = await readJson(res);
2621
+ if (allAnalytics && allAnalytics.totals) {
2622
+ renderAnalytics(allAnalytics);
2623
+ }
2624
+ } catch (err) {
2625
+ console.error('Аналитика недоступна:', err);
2626
+ }
2627
+ }
2628
+
2479
2629
  document.addEventListener('click', function (e) {
2480
2630
  var matrixBtn = e.target && e.target.closest ? e.target.closest('button[data-matrix]') : null;
2481
2631
  if (!matrixBtn) return;
@@ -2640,10 +2790,12 @@ function renderPage(): string {
2640
2790
 
2641
2791
  loadAll();
2642
2792
  setInterval(loadAll, 5000);
2793
+ loadAnalytics();
2794
+ setInterval(loadAnalytics, ANALYTICS_INTERVAL_MS);
2643
2795
  })();
2644
2796
  </script>
2645
2797
 
2646
- <script>
2798
+ <script nonce="${nonce}">
2647
2799
  (function () {
2648
2800
  var flakes = ['❄', '❅', '❆'];
2649
2801
  for (var i = 0; i < 18; i++) {
package/src/settings.ts CHANGED
@@ -2,7 +2,7 @@ import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { PLUGIN_DIR } from "./types.js";
5
- import { DEFAULT_LOCALE, normalizeLocale, normalizeLocaleMode, SUPPORTED_LOCALES, messageIn, t, type Locale, type LocaleMode } from "./i18n.js";
5
+ import { DEFAULT_LOCALE, DEFAULT_LOCALE_MODE, normalizeLocale, normalizeLocaleMode, SUPPORTED_LOCALES, messageIn, t, type Locale, type LocaleMode } from "./i18n.js";
6
6
  import {
7
7
  DEFAULT_PERMISSION_POLICY,
8
8
  normalizePolicy,
@@ -362,8 +362,8 @@ export interface SchedulerSettings {
362
362
  /** Максимум одновременно выполняющихся задач. 0 — без ограничения. */
363
363
  maxConcurrent: number;
364
364
  /**
365
- * Язык интерфейса (Спринт 28, режим `auto` — T7): `ru` по умолчанию,
366
- * `en`/`zh` — явный выбор, `auto` — следовать за языком OpenCode.
365
+ * Язык интерфейса (Спринт 28, режим `auto` — T7): `auto` по умолчанию —
366
+ * следовать за языком OpenCode; `ru`/`en`/`zh` — явный выбор пользователя.
367
367
  */
368
368
  locale: LocaleMode;
369
369
  /**
@@ -1266,7 +1266,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
1266
1266
  parsed?.maxConcurrent,
1267
1267
  DEFAULT_MAX_CONCURRENT,
1268
1268
  ),
1269
- locale: normalizeLocaleMode(parsed?.locale, DEFAULT_LOCALE),
1269
+ locale: normalizeLocaleMode(parsed?.locale, DEFAULT_LOCALE_MODE),
1270
1270
  uiLocale: normalizeLocale(parsed?.uiLocale, DEFAULT_LOCALE),
1271
1271
  winterMode: normalizeWinterMode(
1272
1272
  parsed?.winterMode,
@@ -1290,7 +1290,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
1290
1290
  } catch {
1291
1291
  return {
1292
1292
  maxConcurrent: DEFAULT_MAX_CONCURRENT,
1293
- locale: DEFAULT_LOCALE,
1293
+ locale: DEFAULT_LOCALE_MODE,
1294
1294
  uiLocale: DEFAULT_LOCALE,
1295
1295
  winterMode: DEFAULT_WINTER_MODE,
1296
1296
  notifications: fallbackNotifications,
@@ -6,7 +6,7 @@ import {
6
6
  } from "../task-transfer.js";
7
7
  import type { ScheduledTaskInfo } from "../types.js";
8
8
 
9
- export type JobStatus = "running" | "success" | "error" | "partial" | "idle" | "unknown"
9
+ export type JobStatus = "running" | "success" | "error" | "partial" | "skipped" | "idle" | "unknown"
10
10
 
11
11
  export interface JobView {
12
12
  name: string
@@ -117,6 +117,8 @@ export function statusIcon(status: JobStatus): string {
117
117
  return "✓";
118
118
  case "partial":
119
119
  return "◐";
120
+ case "skipped":
121
+ return "⏭";
120
122
  case "idle":
121
123
  // Задача создана, но ещё ни разу не запускалась.
122
124
  return "○";
@@ -14,6 +14,7 @@ import {
14
14
  validateLaunchWindow,
15
15
  } from "./core/schedule-v2.js";
16
16
  import { isValidSessionId } from "./core/session.js";
17
+ import { normalizeTaskGuards, type TaskGuards } from "./core/guard.js";
17
18
 
18
19
  /** Триггер задачи по событию из MCP-шины. */
19
20
  export interface McpEventTrigger {
@@ -158,6 +159,13 @@ export interface TaskDefinition {
158
159
  * перечислить shell в allowedTools.
159
160
  */
160
161
  legacyShell?: boolean;
162
+ /**
163
+ * W-1: запускать задачу в одноразовом git worktree, созданном от HEAD
164
+ * рабочей директории. По умолчанию выключено. Требует git-репозиторий.
165
+ */
166
+ worktree?: boolean;
167
+ /** W-3: guard-условия перед запуском (semantic-проверки и shell-команда). */
168
+ guards?: TaskGuards;
161
169
  /** Настройки fan-out матрицы (родитель). */
162
170
  matrix?: MatrixConfig;
163
171
  /** Для клона матрицы — имя родительской задачи-шаблона. */
@@ -225,6 +233,14 @@ export interface TaskDefinition {
225
233
  runWhenLoggedOff?: boolean;
226
234
  /** Когда задача была создана — защита от ложного catch-up сразу после создания. */
227
235
  createdAt?: string;
236
+ /**
237
+ * Спринт 32 (Pipeline-as-code): имя pipeline, из которого создан шаг.
238
+ * Хранится в definition_json и позволяет apply отличать «свои» задачи
239
+ * от созданных вручную. Не участвует в запуске.
240
+ */
241
+ pipelineName?: string;
242
+ /** Спринт 32: стабильный id шага внутри pipeline (для diff/apply). */
243
+ pipelineStepId?: string;
228
244
  }
229
245
 
230
246
  const PREFIX = `\\OpenCode\\${TASK_FOLDER_NAME}\\`;
@@ -397,6 +413,10 @@ export async function buildExportJson(
397
413
  ...(definition?.paused === true ? { paused: true } : {}),
398
414
  // Спринт 27.5.10: режим входа переживает перенос между профилями.
399
415
  ...(definition?.runWhenLoggedOff === true ? { runWhenLoggedOff: true } : {}),
416
+ // W-1: изоляция запуска в одноразовом git worktree.
417
+ ...(definition?.worktree === true ? { worktree: true } : {}),
418
+ // W-3: guard-условия переживают перенос между профилями.
419
+ ...(definition?.guards ? { guards: definition.guards } : {}),
400
420
  ...(Array.isArray(definition?.allowedTools) && definition.allowedTools.length > 0
401
421
  ? { allowedTools: definition.allowedTools }
402
422
  : {}),
@@ -720,6 +740,15 @@ export function parseImportJson(raw: string): ParsedImport {
720
740
  // Спринт 27.5.10: режим входа. Только явный `true` делает задачу фоновой;
721
741
  // всё остальное (false, null, строка) означает интерактивную задачу.
722
742
  const runWhenLoggedOffFlag = source.runWhenLoggedOff === true;
743
+ // W-1: одноразовый git worktree; только явный `true`.
744
+ const worktreeFlag = source.worktree === true;
745
+ // W-3: guard-условия. Ошибка нормализации попадает в общий список ошибок
746
+ // импорта; валидная конфигурация переносится вместе с задачей.
747
+ const guardsResult = normalizeTaskGuards(source.guards);
748
+ if (!guardsResult.ok) {
749
+ errors.push(`Запись ${position}${name ? ` (${name})` : ""}: ${guardsResult.error}`);
750
+ }
751
+ const guards = guardsResult.ok ? guardsResult.guards : undefined;
723
752
 
724
753
  // Ограничения инструментов (Спринт 14): массив непустых строк без дублей.
725
754
  // Пустой allowedTools отклоняется с явной ошибкой (избегаем «запрещено всё»).
@@ -934,6 +963,8 @@ export function parseImportJson(raw: string): ParsedImport {
934
963
  ...(pausedFlag ? { paused: true } : {}),
935
964
  // Спринт 27.5.10: сохраняем режим входа при переносе задачи.
936
965
  ...(runWhenLoggedOffFlag ? { runWhenLoggedOff: true } : {}),
966
+ ...(worktreeFlag ? { worktree: true } : {}),
967
+ ...(guards ? { guards } : {}),
937
968
  ...(mcpEvent ? { mcpEvent } : {}),
938
969
  ...(allowedTools !== undefined ? { allowedTools } : {}),
939
970
  ...(deniedTools !== undefined ? { deniedTools } : {}),
package/src/types.ts CHANGED
@@ -112,6 +112,15 @@ export function validateTaskName(raw: string): string | null {
112
112
  if (!name) {
113
113
  return "Имя задачи не может быть пустым.";
114
114
  }
115
+ // P1-10.T1.3: имена из одних разделителей («---», «...», «.») после
116
+ // sanitizeName превращаются в «task» и молча конфликтуют с реальной
117
+ // задачей «task». Требуем хотя бы одну букву или цифру.
118
+ if (!/[\p{L}\p{N}]/u.test(name)) {
119
+ return (
120
+ `Имя задачи «${name}» не содержит букв или цифр: после нормализации ` +
121
+ "оно стало бы «task». Добавьте буквы или цифры."
122
+ );
123
+ }
115
124
  if (/[\u0000-\u001f\u007f]/.test(name)) {
116
125
  return "Имя задачи не должно содержать управляющие символы.";
117
126
  }