agent-steward 0.0.2 → 0.0.4

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 (263) hide show
  1. package/CHANGELOG.md +45 -2
  2. package/CROSS_PLATFORM.md +11 -9
  3. package/README.md +11 -10
  4. package/ROADMAP-STRATEGY.md +93 -44
  5. package/ROADMAP.md +148 -1017
  6. package/dist/core/cron-to-schtasks.d.ts +0 -8
  7. package/dist/core/cron-to-schtasks.d.ts.map +1 -1
  8. package/dist/core/cron-to-schtasks.js +11 -86
  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 +19 -2
  14. package/dist/core/file-watcher.js +9 -9
  15. package/dist/core/git-trigger.js +4 -4
  16. package/dist/core/lock.d.ts +20 -4
  17. package/dist/core/lock.d.ts.map +1 -1
  18. package/dist/core/lock.js +99 -26
  19. package/dist/core/one-shot.d.ts +31 -5
  20. package/dist/core/one-shot.d.ts.map +1 -1
  21. package/dist/core/one-shot.js +78 -10
  22. package/dist/core/opencode-cli.d.ts +28 -0
  23. package/dist/core/opencode-cli.d.ts.map +1 -0
  24. package/dist/core/opencode-cli.js +74 -0
  25. package/dist/core/opencode-models.d.ts +62 -0
  26. package/dist/core/opencode-models.d.ts.map +1 -0
  27. package/dist/core/opencode-models.js +277 -0
  28. package/dist/core/otel.js +2 -2
  29. package/dist/core/ps-wrapper.d.ts +1 -1
  30. package/dist/core/ps-wrapper.d.ts.map +1 -1
  31. package/dist/core/ps-wrapper.js +66 -36
  32. package/dist/core/record-history.d.ts +15 -0
  33. package/dist/core/record-history.d.ts.map +1 -1
  34. package/dist/core/record-history.js +78 -54
  35. package/dist/core/router/dispatch.d.ts +36 -0
  36. package/dist/core/router/dispatch.d.ts.map +1 -0
  37. package/dist/core/router/dispatch.js +59 -0
  38. package/dist/core/router/escalation.d.ts +47 -0
  39. package/dist/core/router/escalation.d.ts.map +1 -0
  40. package/dist/core/router/escalation.js +87 -0
  41. package/dist/core/router/planner.d.ts +53 -0
  42. package/dist/core/router/planner.d.ts.map +1 -0
  43. package/dist/core/router/planner.js +113 -0
  44. package/dist/core/router/rules.d.ts +46 -0
  45. package/dist/core/router/rules.d.ts.map +1 -0
  46. package/dist/core/router/rules.js +85 -0
  47. package/dist/core/run-panel-api.d.ts +94 -0
  48. package/dist/core/run-panel-api.d.ts.map +1 -0
  49. package/dist/core/run-panel-api.js +169 -0
  50. package/dist/core/schedule-gate.js +5 -1
  51. package/dist/core/schedule-v2.d.ts +36 -2
  52. package/dist/core/schedule-v2.d.ts.map +1 -1
  53. package/dist/core/schedule-v2.js +98 -12
  54. package/dist/core/scheduler/at-fallback.d.ts +95 -0
  55. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  56. package/dist/core/scheduler/at-fallback.js +200 -0
  57. package/dist/core/scheduler/linux.d.ts +13 -2
  58. package/dist/core/scheduler/linux.d.ts.map +1 -1
  59. package/dist/core/scheduler/linux.js +67 -13
  60. package/dist/core/scheduler/mac.d.ts +14 -8
  61. package/dist/core/scheduler/mac.d.ts.map +1 -1
  62. package/dist/core/scheduler/mac.js +71 -22
  63. package/dist/core/scheduler/posix.d.ts.map +1 -1
  64. package/dist/core/scheduler/posix.js +37 -2
  65. package/dist/core/scheduler/registry.d.ts +13 -0
  66. package/dist/core/scheduler/registry.d.ts.map +1 -1
  67. package/dist/core/scheduler/registry.js +83 -21
  68. package/dist/core/scheduler/run-now.d.ts +16 -0
  69. package/dist/core/scheduler/run-now.d.ts.map +1 -0
  70. package/dist/core/scheduler/run-now.js +28 -0
  71. package/dist/core/scheduler/windows.d.ts +16 -3
  72. package/dist/core/scheduler/windows.d.ts.map +1 -1
  73. package/dist/core/scheduler/windows.js +249 -96
  74. package/dist/core/secrets.d.ts.map +1 -1
  75. package/dist/core/secrets.js +127 -30
  76. package/dist/core/self-analysis.js +55 -55
  77. package/dist/core/session.d.ts.map +1 -1
  78. package/dist/core/session.js +18 -11
  79. package/dist/core/summary.js +1 -1
  80. package/dist/core/task-name.d.ts +24 -0
  81. package/dist/core/task-name.d.ts.map +1 -0
  82. package/dist/core/task-name.js +40 -0
  83. package/dist/core/triage-chain.js +1 -1
  84. package/dist/core/triage-worker.js +2 -2
  85. package/dist/core/triage.js +1 -1
  86. package/dist/core/wrappers/bash.d.ts.map +1 -1
  87. package/dist/core/wrappers/bash.js +82 -37
  88. package/dist/db/capability-repo.d.ts +83 -0
  89. package/dist/db/capability-repo.d.ts.map +1 -0
  90. package/dist/db/capability-repo.js +182 -0
  91. package/dist/db/history-repo.d.ts +8 -0
  92. package/dist/db/history-repo.d.ts.map +1 -1
  93. package/dist/db/history-repo.js +19 -0
  94. package/dist/db/index.d.ts +6 -0
  95. package/dist/db/index.d.ts.map +1 -1
  96. package/dist/db/index.js +48 -2
  97. package/dist/db/migrate.d.ts.map +1 -1
  98. package/dist/db/migrate.js +3 -1
  99. package/dist/db/run-context.d.ts +103 -0
  100. package/dist/db/run-context.d.ts.map +1 -0
  101. package/dist/db/run-context.js +224 -0
  102. package/dist/db/run-dlq.d.ts +100 -0
  103. package/dist/db/run-dlq.d.ts.map +1 -0
  104. package/dist/db/run-dlq.js +191 -0
  105. package/dist/db/run-journal.d.ts +60 -0
  106. package/dist/db/run-journal.d.ts.map +1 -0
  107. package/dist/db/run-journal.js +143 -0
  108. package/dist/db/run-resume.d.ts +51 -0
  109. package/dist/db/run-resume.d.ts.map +1 -0
  110. package/dist/db/run-resume.js +156 -0
  111. package/dist/db/runs-repo.d.ts +128 -0
  112. package/dist/db/runs-repo.d.ts.map +1 -0
  113. package/dist/db/runs-repo.js +342 -0
  114. package/dist/db/schema.d.ts +16 -2
  115. package/dist/db/schema.d.ts.map +1 -1
  116. package/dist/db/schema.js +342 -35
  117. package/dist/db/settings-repo.d.ts +11 -0
  118. package/dist/db/settings-repo.d.ts.map +1 -1
  119. package/dist/db/settings-repo.js +25 -0
  120. package/dist/db/step-idempotency.d.ts +51 -0
  121. package/dist/db/step-idempotency.d.ts.map +1 -0
  122. package/dist/db/step-idempotency.js +136 -0
  123. package/dist/index.d.ts +5 -5
  124. package/dist/index.d.ts.map +1 -1
  125. package/dist/index.js +168 -40
  126. package/dist/notifications.js +18 -18
  127. package/dist/profiles.d.ts +7 -3
  128. package/dist/profiles.d.ts.map +1 -1
  129. package/dist/profiles.js +85 -7
  130. package/dist/rpc.d.ts +787 -0
  131. package/dist/rpc.d.ts.map +1 -1
  132. package/dist/rpc.js +324 -0
  133. package/dist/server.d.ts +33 -2
  134. package/dist/server.d.ts.map +1 -1
  135. package/dist/server.js +115 -54
  136. package/dist/shared/jobs-view.d.ts.map +1 -1
  137. package/dist/skill.js +1 -1
  138. package/dist/task-transfer.d.ts +1 -1
  139. package/dist/task-transfer.d.ts.map +1 -1
  140. package/dist/task-transfer.js +14 -10
  141. package/dist/types.d.ts +20 -4
  142. package/dist/types.d.ts.map +1 -1
  143. package/dist/types.js +44 -9
  144. package/dist/workspaces.d.ts +25 -3
  145. package/dist/workspaces.d.ts.map +1 -1
  146. package/dist/workspaces.js +44 -9
  147. package/docs/ARCHITECTURE.md +335 -9
  148. package/docs/COMPATIBILITY.md +10 -6
  149. package/docs/CONCEPT.md +183 -91
  150. package/docs/CROSS_PLATFORM.ru.md +11 -9
  151. package/docs/CROSS_PLATFORM.zh.md +11 -9
  152. package/docs/EXECUTION-LOOP.md +196 -0
  153. package/docs/FAQ.md +2 -2
  154. package/docs/FAQ.ru.md +2 -2
  155. package/docs/FAQ.zh.md +2 -2
  156. package/docs/FEATURES.md +5 -4
  157. package/docs/FEATURES.zh.md +5 -4
  158. package/docs/MIGRATION.md +34 -26
  159. package/docs/README.ru.md +27 -8
  160. package/docs/README.zh.md +11 -10
  161. package/docs/SAFETY.md +122 -0
  162. package/docs/SAVINGS.md +29 -0
  163. package/docs/SAVINGS.ru.md +29 -0
  164. package/docs/SAVINGS.zh.md +18 -0
  165. package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
  166. package/gui-experimental.cjs +8 -8
  167. package/index.js +1 -0
  168. package/locales/en.json +68 -0
  169. package/locales/ru.json +68 -0
  170. package/locales/zh.json +68 -0
  171. package/package.json +57 -11
  172. package/scripts/audit-bundle.mjs +215 -0
  173. package/src/core/analytics.ts +2 -2
  174. package/src/core/audit.ts +17 -17
  175. package/src/core/cron-to-schtasks.ts +14 -93
  176. package/src/core/dlq-api.ts +98 -0
  177. package/src/core/dry-run.ts +51 -27
  178. package/src/core/file-watcher.ts +17 -17
  179. package/src/core/git-trigger.ts +9 -9
  180. package/src/core/glob.ts +1 -1
  181. package/src/core/local-ai.ts +2 -2
  182. package/src/core/lock.ts +104 -31
  183. package/src/core/matrix.ts +31 -31
  184. package/src/core/native-notify.ts +2 -2
  185. package/src/core/one-shot.ts +91 -13
  186. package/src/core/opencode-cli.ts +103 -0
  187. package/src/core/opencode-models.ts +315 -0
  188. package/src/core/otel.ts +4 -4
  189. package/src/core/permissions.ts +5 -5
  190. package/src/core/prometheus.ts +17 -17
  191. package/src/core/ps-wrapper.ts +68 -38
  192. package/src/core/record-history.ts +114 -76
  193. package/src/core/retention.ts +3 -3
  194. package/src/core/router/dispatch.ts +94 -0
  195. package/src/core/router/escalation.ts +129 -0
  196. package/src/core/router/planner.ts +166 -0
  197. package/src/core/router/rules.ts +109 -0
  198. package/src/core/run-panel-api.ts +262 -0
  199. package/src/core/savings.ts +1 -1
  200. package/src/core/schedule-gate.ts +17 -13
  201. package/src/core/schedule-v2.ts +138 -29
  202. package/src/core/scheduler/at-fallback.ts +298 -0
  203. package/src/core/scheduler/index.ts +3 -3
  204. package/src/core/scheduler/linux.ts +92 -19
  205. package/src/core/scheduler/logs.ts +1 -1
  206. package/src/core/scheduler/mac.ts +112 -60
  207. package/src/core/scheduler/posix.ts +35 -2
  208. package/src/core/scheduler/registry.ts +109 -26
  209. package/src/core/scheduler/run-now.ts +32 -0
  210. package/src/core/scheduler/windows.ts +295 -125
  211. package/src/core/secrets.ts +139 -39
  212. package/src/core/self-analysis.ts +61 -61
  213. package/src/core/session.ts +26 -13
  214. package/src/core/structured-log.ts +3 -3
  215. package/src/core/summary.ts +25 -25
  216. package/src/core/task-name.ts +67 -0
  217. package/src/core/telegram.ts +16 -16
  218. package/src/core/triage-chain.ts +4 -4
  219. package/src/core/triage-compare.ts +8 -8
  220. package/src/core/triage-rules.ts +4 -4
  221. package/src/core/triage-shadow.ts +7 -7
  222. package/src/core/triage-worker.ts +6 -6
  223. package/src/core/triage.ts +23 -23
  224. package/src/core/watch-paths.ts +1 -1
  225. package/src/core/wrappers/bash.ts +90 -45
  226. package/src/db/capability-repo.ts +285 -0
  227. package/src/db/git-state-repo.ts +1 -1
  228. package/src/db/history-repo.ts +44 -22
  229. package/src/db/index.ts +53 -7
  230. package/src/db/metrics-repo.ts +10 -10
  231. package/src/db/migrate.ts +13 -11
  232. package/src/db/recovery.ts +3 -3
  233. package/src/db/run-context.ts +370 -0
  234. package/src/db/run-dlq.ts +310 -0
  235. package/src/db/run-journal.ts +212 -0
  236. package/src/db/run-resume.ts +256 -0
  237. package/src/db/runs-repo.ts +504 -0
  238. package/src/db/schema.ts +357 -44
  239. package/src/db/settings-repo.ts +33 -2
  240. package/src/db/step-idempotency.ts +185 -0
  241. package/src/db/tasks-repo.ts +10 -10
  242. package/src/db/templates-repo.ts +7 -7
  243. package/src/gui.tsx +516 -1
  244. package/src/history.ts +4 -4
  245. package/src/i18n.ts +7 -7
  246. package/src/index.ts +465 -308
  247. package/src/integrations.ts +6 -6
  248. package/src/notifications.ts +76 -76
  249. package/src/profiles.ts +98 -7
  250. package/src/rpc.ts +347 -1
  251. package/src/schtasks.ts +2 -2
  252. package/src/server.ts +155 -78
  253. package/src/settings.ts +44 -44
  254. package/src/shared/jobs-view.ts +60 -60
  255. package/src/skill.ts +1 -1
  256. package/src/task-transfer.ts +58 -56
  257. package/src/templates.ts +1 -1
  258. package/src/types.ts +54 -10
  259. package/src/workspaces.ts +73 -24
  260. package/dist/core/self-analysis.test.d.ts +0 -2
  261. package/dist/core/self-analysis.test.d.ts.map +0 -1
  262. package/dist/core/self-analysis.test.js +0 -219
  263. package/dist/gui-experimental.cjs +0 -1
@@ -4,6 +4,7 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { spawnSync } from "node:child_process";
6
6
  import { PLUGIN_DIR } from "../types.js";
7
+ import { isProcessAlive } from "./lock.js";
7
8
  /**
8
9
  * Зашифрованное хранилище секретов (Спринт 26).
9
10
  *
@@ -23,6 +24,82 @@ export const SECRETS_KEY_FILE = path.join(PLUGIN_DIR, "secrets.key");
23
24
  export const SECRET_REF_RE = /\$\{secret:([A-Za-z0-9_.-]{1,64})\}/g;
24
25
  const SECRET_NAME_RE = /^[A-Za-z0-9_.-]{1,64}$/;
25
26
  const KEY_BYTES = 32;
27
+ /**
28
+ * P2-20: межпроцессная блокировка записи секретов.
29
+ *
30
+ * setSecret/deleteSecret — это read-modify-write одного JSON. Каждое завершение
31
+ * задачи может быть отдельным процессом, поэтому без лока параллельные записи
32
+ * теряли секреты. Лок синхронный: API setSecret/deleteSecret синхронный и
33
+ * используется из CLI/GUI/плагина, переписывать его на async нельзя.
34
+ */
35
+ const SECRETS_LOCK_FILE = `${SECRETS_FILE}.lock`;
36
+ const SECRETS_LOCK_STALE_MS = 10000;
37
+ const SECRETS_LOCK_TIMEOUT_MS = 5000;
38
+ let secretsLockDepth = 0;
39
+ function sleepSync(ms) {
40
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
41
+ }
42
+ function withSecretsLock(fn) {
43
+ // Реентерабельность: loadKey()/readFileSafe() вызываются внутри setSecret.
44
+ if (secretsLockDepth > 0) {
45
+ secretsLockDepth += 1;
46
+ try {
47
+ return fn();
48
+ }
49
+ finally {
50
+ secretsLockDepth -= 1;
51
+ }
52
+ }
53
+ ensureDir();
54
+ const deadline = Date.now() + SECRETS_LOCK_TIMEOUT_MS;
55
+ for (;;) {
56
+ try {
57
+ const fd = fs.openSync(SECRETS_LOCK_FILE, "wx");
58
+ try {
59
+ fs.writeFileSync(fd, String(process.pid));
60
+ }
61
+ finally {
62
+ fs.closeSync(fd);
63
+ }
64
+ secretsLockDepth = 1;
65
+ break;
66
+ }
67
+ catch (err) {
68
+ if (err?.code !== "EEXIST")
69
+ throw err;
70
+ try {
71
+ const stat = fs.statSync(SECRETS_LOCK_FILE);
72
+ if (Date.now() - stat.mtimeMs > SECRETS_LOCK_STALE_MS) {
73
+ const owner = Number.parseInt(fs.readFileSync(SECRETS_LOCK_FILE, "utf8").trim(), 10);
74
+ if (!Number.isInteger(owner) || !isProcessAlive(owner)) {
75
+ fs.rmSync(SECRETS_LOCK_FILE, { force: true });
76
+ continue;
77
+ }
78
+ }
79
+ }
80
+ catch {
81
+ // Лок исчез между stat и read — повторяем попытку.
82
+ }
83
+ if (Date.now() >= deadline) {
84
+ throw new Error("Не удалось получить блокировку хранилища секретов за " +
85
+ `${SECRETS_LOCK_TIMEOUT_MS} мс.`);
86
+ }
87
+ sleepSync(25);
88
+ }
89
+ }
90
+ try {
91
+ return fn();
92
+ }
93
+ finally {
94
+ secretsLockDepth = 0;
95
+ try {
96
+ fs.rmSync(SECRETS_LOCK_FILE, { force: true });
97
+ }
98
+ catch {
99
+ // Не критично: лок всё равно станет stale.
100
+ }
101
+ }
102
+ }
26
103
  let cache = null;
27
104
  let keyCache = null;
28
105
  function warn(message, err) {
@@ -118,11 +195,30 @@ function loadKey() {
118
195
  catch (err) {
119
196
  if (err?.code !== "ENOENT")
120
197
  throw err;
121
- const key = crypto.randomBytes(KEY_BYTES);
122
- fs.writeFileSync(SECRETS_KEY_FILE, key, { mode: 0o600 });
123
- chmodPrivate(SECRETS_KEY_FILE);
124
- keyCache = { stamp: `${fs.statSync(SECRETS_KEY_FILE).mtimeMs}:${KEY_BYTES}`, key };
125
- return key;
198
+ // Два процесса могли одновременно не найти ключ и сгенерировать разный.
199
+ // Под локом перечитываем файл: побеждает первый, остальные используют его ключ.
200
+ return withSecretsLock(() => {
201
+ try {
202
+ const raw = fs.readFileSync(SECRETS_KEY_FILE);
203
+ if (raw.length !== KEY_BYTES) {
204
+ throw new Error("повреждён файл ключа секретов");
205
+ }
206
+ keyCache = {
207
+ stamp: `${fs.statSync(SECRETS_KEY_FILE).mtimeMs}:${raw.length}`,
208
+ key: raw,
209
+ };
210
+ return raw;
211
+ }
212
+ catch (readErr) {
213
+ if (readErr?.code !== "ENOENT")
214
+ throw readErr;
215
+ }
216
+ const key = crypto.randomBytes(KEY_BYTES);
217
+ fs.writeFileSync(SECRETS_KEY_FILE, key, { mode: 0o600 });
218
+ chmodPrivate(SECRETS_KEY_FILE);
219
+ keyCache = { stamp: `${fs.statSync(SECRETS_KEY_FILE).mtimeMs}:${KEY_BYTES}`, key };
220
+ return key;
221
+ });
126
222
  }
127
223
  }
128
224
  function emptyFile() {
@@ -151,7 +247,7 @@ function quarantineCorruptStore(err) {
151
247
  catch (renameErr) {
152
248
  corruptedStore = target;
153
249
  warn(`secrets.json повреждён, но его не удалось переместить в ${target}. ` +
154
- `Запись новых секретов заблокирована, чтобы не потерять данные.`, renameErr);
250
+ "Запись новых секретов заблокирована, чтобы не потерять данные.", renameErr);
155
251
  return false;
156
252
  }
157
253
  }
@@ -166,7 +262,7 @@ function readFileSafe() {
166
262
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
167
263
  throw new Error("некорректный формат secrets.json");
168
264
  }
169
- const rawSecrets = parsed.secrets;
265
+ const rawSecrets = (parsed).secrets;
170
266
  const secrets = {};
171
267
  if (rawSecrets && typeof rawSecrets === "object" && !Array.isArray(rawSecrets)) {
172
268
  for (const [name, entry] of Object.entries(rawSecrets)) {
@@ -201,14 +297,11 @@ function readFileSafe() {
201
297
  /** Атомарная запись: temp + rename, права 0600. */
202
298
  function writeFileSafe(file) {
203
299
  ensureDir();
204
- const tmp = `${SECRETS_FILE}.tmp`;
300
+ // Уникальный temp: два процесса не должны писать в один и тот же файл.
301
+ const tmp = `${SECRETS_FILE}.${process.pid}.${Date.now()}.tmp`;
205
302
  fs.writeFileSync(tmp, JSON.stringify(file, null, 2), { encoding: "utf8", mode: 0o600 });
206
- try {
207
- fs.rmSync(SECRETS_FILE, { force: true });
208
- }
209
- catch {
210
- // файла нет — не ошибка
211
- }
303
+ // Без предварительного rm: rename на POSIX и Windows атомарно заменяет файл,
304
+ // а rm открывал окно, в котором secrets.json отсутствовал при краше.
212
305
  fs.renameSync(tmp, SECRETS_FILE);
213
306
  chmodPrivate(SECRETS_FILE);
214
307
  try {
@@ -248,15 +341,17 @@ export function setSecret(name, value) {
248
341
  }
249
342
  const secretName = validateSecretName(name);
250
343
  const text = String(value ?? "");
251
- const key = loadKey();
252
- const file = readFileSafe();
253
- file.secrets[secretName] = encryptValue(secretName, text, key);
254
- writeFileSafe(file);
255
- return {
256
- name: secretName,
257
- preview: previewOf(text),
258
- updatedAt: file.secrets[secretName].updatedAt,
259
- };
344
+ return withSecretsLock(() => {
345
+ const key = loadKey();
346
+ const file = readFileSafe();
347
+ file.secrets[secretName] = encryptValue(secretName, text, key);
348
+ writeFileSafe(file);
349
+ return {
350
+ name: secretName,
351
+ preview: previewOf(text),
352
+ updatedAt: file.secrets[secretName].updatedAt,
353
+ };
354
+ });
260
355
  }
261
356
  /** Читает секрет; undefined, если его нет или он не расшифровывается. */
262
357
  export function getSecret(name) {
@@ -280,12 +375,14 @@ export function hasSecret(name) {
280
375
  /** Удаляет секрет; true — запись была. */
281
376
  export function deleteSecret(name) {
282
377
  const secretName = validateSecretName(name);
283
- const file = readFileSafe();
284
- if (!(secretName in file.secrets))
285
- return false;
286
- delete file.secrets[secretName];
287
- writeFileSafe(file);
288
- return true;
378
+ return withSecretsLock(() => {
379
+ const file = readFileSafe();
380
+ if (!(secretName in file.secrets))
381
+ return false;
382
+ delete file.secrets[secretName];
383
+ writeFileSafe(file);
384
+ return true;
385
+ });
289
386
  }
290
387
  function previewOf(value) {
291
388
  const text = String(value ?? "");
@@ -400,7 +497,7 @@ export function redactSecretsInText(text) {
400
497
  continue;
401
498
  result = result.split(value).join("***");
402
499
  }
403
- result = result.replace(/\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|CREDENTIAL|AUTH)[A-Za-z0-9_]*)\b(\s*[=:]\s*)(["']?)([^\s"',;]+)\3/gi, (_match, key, sep, quote) => `${key}${sep}${quote}***${quote}`);
500
+ result = result.replace(/(["']?)\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|CREDENTIAL|AUTH)[A-Za-z0-9_]*)\b\1(\s*[=:]\s*)(["']?)([^\s"',;]+)\4/gi, (_match, openQuote, key, sep, quote) => `${openQuote}${key}${openQuote}${sep}${quote}***${quote}`);
404
501
  // Восстанавливаем защищённые ссылки.
405
502
  for (let i = 0; i < protectedRefs.length; i++) {
406
503
  result = result.split(`\u0000SECRET_REF_${i}\u0000`).join(protectedRefs[i]);
@@ -13,8 +13,8 @@ export function calculateHealthScore(report) {
13
13
  const successRateScore = totals.successRate;
14
14
  const errorRateScore = Math.max(0, 100 - (totals.error / Math.max(1, totals.total)) * 100);
15
15
  const avgDurationScore = Math.min(100, Math.max(0, 100 - (totals.avgDurationMs / 300000) * 100)); // 5 минут = 0 баллов
16
- const timeoutRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes('timeout')).length / Math.max(1, totals.total)) * 100));
17
- const crashRecoveryRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes('Прервано')).length / Math.max(1, totals.total)) * 100));
16
+ const timeoutRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes("timeout")).length / Math.max(1, totals.total)) * 100));
17
+ const crashRecoveryRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes("Прервано")).length / Math.max(1, totals.total)) * 100));
18
18
  // Взвешенная сумма
19
19
  const score = Math.round(successRateScore * 0.35 +
20
20
  errorRateScore * 0.25 +
@@ -112,8 +112,8 @@ function detectErrorSpike(records, windowDays) {
112
112
  const half = Math.floor(records.length / 2);
113
113
  const older = records.slice(half);
114
114
  const recent = records.slice(0, half);
115
- const recentErrorRate = recent.filter(r => r.status === 'error').length / recent.length;
116
- const olderErrorRate = older.filter(r => r.status === 'error').length / older.length;
115
+ const recentErrorRate = recent.filter(r => r.status === "error").length / recent.length;
116
+ const olderErrorRate = older.filter(r => r.status === "error").length / older.length;
117
117
  // Всплеск ошибок: недавний период значительно хуже старого
118
118
  if (olderErrorRate < 0.5 && recentErrorRate > olderErrorRate * 2 && recentErrorRate > 0.3) {
119
119
  return {
@@ -124,13 +124,13 @@ function detectErrorSpike(records, windowDays) {
124
124
  recommendations: [
125
125
  "Проверьте логи ошибок за последнее время",
126
126
  "Убедитесь, что Quality Gate настроен правильно",
127
- "Рассмотрите добавление retryCount"
127
+ "Рассмотрите добавление retryCount",
128
128
  ],
129
129
  metadata: {
130
130
  recentErrorRate,
131
131
  olderErrorRate,
132
- windowDays
133
- }
132
+ windowDays,
133
+ },
134
134
  };
135
135
  }
136
136
  return null;
@@ -155,13 +155,13 @@ function detectDurationSpike(records) {
155
155
  recommendations: [
156
156
  "Проверьте, не завис ли процесс",
157
157
  "Увеличьте timeoutSeconds если задача легитимно долгая",
158
- "Рассмотрите разделение задачи на части"
158
+ "Рассмотрите разделение задачи на части",
159
159
  ],
160
160
  metadata: {
161
161
  recentDuration,
162
162
  medianDuration: median,
163
- ratio: recentDuration / median
164
- }
163
+ ratio: recentDuration / median,
164
+ },
165
165
  };
166
166
  }
167
167
  return null;
@@ -169,7 +169,7 @@ function detectDurationSpike(records) {
169
169
  function detectTimeoutSpike(records) {
170
170
  if (records.length < 5)
171
171
  return null;
172
- const timeoutCount = records.filter(r => r.error?.includes('timeout')).length;
172
+ const timeoutCount = records.filter(r => r.error?.includes("timeout")).length;
173
173
  const timeoutRate = timeoutCount / records.length;
174
174
  if (timeoutRate > 0.2) {
175
175
  return {
@@ -180,13 +180,13 @@ function detectTimeoutSpike(records) {
180
180
  recommendations: [
181
181
  "Увеличьте timeoutSeconds",
182
182
  "Упростите промпты задачи",
183
- "Проверьте производительность модели"
183
+ "Проверьте производительность модели",
184
184
  ],
185
185
  metadata: {
186
186
  timeoutCount,
187
187
  totalRecords: records.length,
188
- timeoutRate
189
- }
188
+ timeoutRate,
189
+ },
190
190
  };
191
191
  }
192
192
  return null;
@@ -211,13 +211,13 @@ function detectCostSpike(records) {
211
211
  recommendations: [
212
212
  "Проверьте, не используется ли более дорогая модель",
213
213
  "Оптимизируйте промпты для снижения токенов",
214
- "Рассмотрите использование локальной модели"
214
+ "Рассмотрите использование локальной модели",
215
215
  ],
216
216
  metadata: {
217
217
  recentCost,
218
218
  medianCost: median,
219
- ratio: recentCost / median
220
- }
219
+ ratio: recentCost / median,
220
+ },
221
221
  };
222
222
  }
223
223
  return null;
@@ -227,8 +227,8 @@ function detectUnusualPattern(records) {
227
227
  return null;
228
228
  // Проверяем паттерн: все подряд ошибки или все подряд успехи
229
229
  const recent = records.slice(0, 5);
230
- const allErrors = recent.every(r => r.status === 'error');
231
- const allSuccess = recent.every(r => r.status === 'success');
230
+ const allErrors = recent.every(r => r.status === "error");
231
+ const allSuccess = recent.every(r => r.status === "success");
232
232
  if (allErrors) {
233
233
  return {
234
234
  type: "unusual_pattern",
@@ -238,18 +238,18 @@ function detectUnusualPattern(records) {
238
238
  recommendations: [
239
239
  "Проверьте, не сломалась ли зависимость",
240
240
  "Проверьте доступность внешних сервисов",
241
- "Рассмотрите приостановку задачи до устранения проблемы"
241
+ "Рассмотрите приостановку задачи до устранения проблемы",
242
242
  ],
243
243
  metadata: {
244
244
  pattern: "consecutive_errors",
245
- count: 5
246
- }
245
+ count: 5,
246
+ },
247
247
  };
248
248
  }
249
249
  return null;
250
250
  }
251
251
  function detectStalledRun(records, now) {
252
- const running = records.find(r => r.status === 'running');
252
+ const running = records.find(r => r.status === "running");
253
253
  if (!running)
254
254
  return null;
255
255
  const startedAt = new Date(running.startedAt);
@@ -263,13 +263,13 @@ function detectStalledRun(records, now) {
263
263
  recommendations: [
264
264
  "Проверьте, не завис ли процесс",
265
265
  "Рассмотрите принудительное завершение",
266
- "Проверьте блокировки (lock file)"
266
+ "Проверьте блокировки (lock file)",
267
267
  ],
268
268
  metadata: {
269
269
  hoursRunning,
270
270
  startedAt: running.startedAt,
271
- taskId: running.id
272
- }
271
+ taskId: running.id,
272
+ },
273
273
  };
274
274
  }
275
275
  return null;
@@ -286,8 +286,8 @@ export function analyzeTrends(records, options = {}) {
286
286
  if (older.length < 3 || recent.length < 3)
287
287
  return trends;
288
288
  // 1. Тренд успешности
289
- const olderSuccessRate = older.filter(r => r.status === 'success').length / older.length;
290
- const recentSuccessRate = recent.filter(r => r.status === 'success').length / recent.length;
289
+ const olderSuccessRate = older.filter(r => r.status === "success").length / older.length;
290
+ const recentSuccessRate = recent.filter(r => r.status === "success").length / recent.length;
291
291
  const successChange = ((recentSuccessRate - olderSuccessRate) / Math.max(olderSuccessRate, 0.01)) * 100;
292
292
  trends.push({
293
293
  metric: "success_rate",
@@ -296,8 +296,8 @@ export function analyzeTrends(records, options = {}) {
296
296
  description: `Успешность: ${Math.round(olderSuccessRate * 100)}% → ${Math.round(recentSuccessRate * 100)}%`,
297
297
  recommendations: successChange < -10 ? [
298
298
  "Проверьте, что изменилось в последнее время",
299
- "Проверьте логи ошибок"
300
- ] : []
299
+ "Проверьте логи ошибок",
300
+ ] : [],
301
301
  });
302
302
  // 2. Тренд длительности
303
303
  const olderDurations = older.map(r => r.durationMs || 0).filter(d => d > 0);
@@ -313,8 +313,8 @@ export function analyzeTrends(records, options = {}) {
313
313
  description: `Средняя длительность: ${Math.round(olderAvgDuration / 1000)}с → ${Math.round(recentAvgDuration / 1000)}с`,
314
314
  recommendations: durationChange > 20 ? [
315
315
  "Оптимизируйте промпты",
316
- "Проверьте, не увеличилась ли нагрузка"
317
- ] : []
316
+ "Проверьте, не увеличилась ли нагрузка",
317
+ ] : [],
318
318
  });
319
319
  }
320
320
  // 3. Тренд стоимости
@@ -331,8 +331,8 @@ export function analyzeTrends(records, options = {}) {
331
331
  description: `Средняя стоимость: $${olderAvgCost.toFixed(4)} → $${recentAvgCost.toFixed(4)}`,
332
332
  recommendations: costChange > 20 ? [
333
333
  "Проверьте, не используется ли более дорогая модель",
334
- "Оптимизируйте промпты для снижения токенов"
335
- ] : []
334
+ "Оптимизируйте промпты для снижения токенов",
335
+ ] : [],
336
336
  });
337
337
  }
338
338
  return trends;
@@ -358,8 +358,8 @@ export function generateRecommendations(report, anomalies, trends) {
358
358
  "Проверьте логи ошибок за последние 7 дней",
359
359
  "Убедитесь, что Quality Gate настроен правильно",
360
360
  "Добавьте retryCount для флакких задач",
361
- "Проверьте доступность внешних сервисов"
362
- ]
361
+ "Проверьте доступность внешних сервисов",
362
+ ],
363
363
  });
364
364
  }
365
365
  // Рекомендации на основе аномалий
@@ -367,12 +367,12 @@ export function generateRecommendations(report, anomalies, trends) {
367
367
  if (anomaly.severity > 70) {
368
368
  recommendations.push({
369
369
  priority: Math.min(10, Math.round(anomaly.severity / 10)),
370
- category: anomaly.type.includes('cost') ? "cost" : "performance",
370
+ category: anomaly.type.includes("cost") ? "cost" : "performance",
371
371
  title: `Устраните аномалию: ${anomaly.type}`,
372
372
  description: anomaly.description,
373
373
  expectedImpact: "Снизит нагрузку и улучшит стабильность",
374
374
  effort: "medium",
375
- steps: anomaly.recommendations
375
+ steps: anomaly.recommendations,
376
376
  });
377
377
  }
378
378
  }
@@ -381,12 +381,12 @@ export function generateRecommendations(report, anomalies, trends) {
381
381
  if (trend.direction === "degrading" && Math.abs(trend.changePercent) > 20) {
382
382
  recommendations.push({
383
383
  priority: 7,
384
- category: trend.metric.includes('cost') ? "cost" : "performance",
384
+ category: trend.metric.includes("cost") ? "cost" : "performance",
385
385
  title: `Обратите внимание на тренд: ${trend.metric}`,
386
386
  description: trend.description,
387
387
  expectedImpact: "Предотвратит дальнейшее ухудшение",
388
388
  effort: "low",
389
- steps: trend.recommendations
389
+ steps: trend.recommendations,
390
390
  });
391
391
  }
392
392
  }
@@ -403,8 +403,8 @@ export function generateRecommendations(report, anomalies, trends) {
403
403
  "Проверьте, не используется ли более дорогая модель для простых задач",
404
404
  "Оптимизируйте промпты для снижения токенов",
405
405
  "Рассмотрите использование локальной модели для простых задач",
406
- "Настройте лимиты на задачи с высокими затратами"
407
- ]
406
+ "Настройте лимиты на задачи с высокими затратами",
407
+ ],
408
408
  });
409
409
  }
410
410
  // Рекомендации на основе длительности
@@ -420,12 +420,12 @@ export function generateRecommendations(report, anomalies, trends) {
420
420
  "Разбейте длинные задачи на более мелкие",
421
421
  "Упростите промпты",
422
422
  "Проверьте, не используются ли медленные модели",
423
- "Увеличьте timeoutSeconds если задачи легитимно долгие"
424
- ]
423
+ "Увеличьте timeoutSeconds если задачи легитимно долгие",
424
+ ],
425
425
  });
426
426
  }
427
427
  // Рекомендации на основе таймаутов
428
- const timeoutErrors = report.errors.filter(e => e.message.includes('timeout'));
428
+ const timeoutErrors = report.errors.filter(e => e.message.includes("timeout"));
429
429
  if (timeoutErrors.length > 0) {
430
430
  recommendations.push({
431
431
  priority: 8,
@@ -438,12 +438,12 @@ export function generateRecommendations(report, anomalies, trends) {
438
438
  "Увеличьте timeoutSeconds для затронутых задач",
439
439
  "Упростите промпты",
440
440
  "Проверьте производительность модели",
441
- "Рассмотрите разделение сложных задач"
442
- ]
441
+ "Рассмотрите разделение сложных задач",
442
+ ],
443
443
  });
444
444
  }
445
445
  // Рекомендации на основе крашей
446
- const crashErrors = report.errors.filter(e => e.message.includes('Прервано'));
446
+ const crashErrors = report.errors.filter(e => e.message.includes("Прервано"));
447
447
  if (crashErrors.length > 0) {
448
448
  recommendations.push({
449
449
  priority: 7,
@@ -456,8 +456,8 @@ export function generateRecommendations(report, anomalies, trends) {
456
456
  "Проверьте стабильность системы",
457
457
  "Проверьте, нет ли конфликтов между задачами",
458
458
  "Убедитесь, что задачи не превышают лимиты ресурсов",
459
- "Рассмотрите настройку crash recovery"
460
- ]
459
+ "Рассмотрите настройку crash recovery",
460
+ ],
461
461
  });
462
462
  }
463
463
  // Сортируем по приоритету
@@ -473,7 +473,7 @@ export function generateSelfAnalysisReport(records, options = {}) {
473
473
  days: windowDays,
474
474
  now,
475
475
  topLimit: options.topLimit,
476
- tasks: options.tasks
476
+ tasks: options.tasks,
477
477
  });
478
478
  // Health Score
479
479
  const health = calculateHealthScore(analyticsReport);
@@ -496,8 +496,8 @@ export function generateSelfAnalysisReport(records, options = {}) {
496
496
  sources: {
497
497
  historyRecords: records.length,
498
498
  recordsInWindow: analyticsReport.sources.recordsInWindow,
499
- tasksAnalyzed: analyticsReport.tasks.length
500
- }
499
+ tasksAnalyzed: analyticsReport.tasks.length,
500
+ },
501
501
  };
502
502
  }
503
503
  function generateSummary(health, anomalies, trends, recommendations) {
@@ -508,7 +508,7 @@ function generateSummary(health, anomalies, trends, recommendations) {
508
508
  good: "хорошее",
509
509
  fair: "удовлетворительное",
510
510
  poor: "плохое",
511
- critical: "критическое"
511
+ critical: "критическое",
512
512
  };
513
513
  parts.push(`Здоровье системы: ${levelNames[health.level]} (${health.score}/100)`);
514
514
  // Аномалии
@@ -525,7 +525,7 @@ function generateSummary(health, anomalies, trends, recommendations) {
525
525
  parts.push("Критических аномалий не обнаружено");
526
526
  }
527
527
  // Тренды
528
- const degradingTrends = trends.filter(t => t.direction === 'degrading').length;
528
+ const degradingTrends = trends.filter(t => t.direction === "degrading").length;
529
529
  if (degradingTrends > 0) {
530
530
  parts.push(`${degradingTrends} метрик ухудшаются`);
531
531
  }
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/core/session.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,aAAa,mCAAoC,CAAC;AAC/D,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC;AAIzD,wDAAwD;AACxD,wBAAgB,iBAAiB,IAAI,MAAM,CAU1C;AAED,kCAAkC;AAClC,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEhE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,WAAW,GAAG,SAAS,CAI5E;AAED,4DAA4D;AAC5D,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,WAAW,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAShF;AAED,iEAAiE;AACjE,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAE9E;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EACJ;IAAE,OAAO,CAAC,EAAE,WAAW,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,CAAA;CAAE,GACvE,SAAS,EACb,OAAO,EAAE,WAAW,EACpB,SAAS,EAAE,MAAM,GAAG,SAAS,GAC5B,MAAM,CAIR;AAED,0DAA0D;AAC1D,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CACzC,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,GAAG,SAAS,GAC5B,OAAO,CAAC,IAAI,CAAC,CAef;AAED;;;;;GAKG;AACH,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAqC3E"}
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/core/session.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,aAAa,mCAAoC,CAAC;AAC/D,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC;AAIzD,wDAAwD;AACxD,wBAAgB,iBAAiB,IAAI,MAAM,CAU1C;AAED,kCAAkC;AAClC,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEhE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,WAAW,GAAG,SAAS,CAI5E;AAED,4DAA4D;AAC5D,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,WAAW,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAShF;AAED,iEAAiE;AACjE,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAE9E;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EACJ;IAAE,OAAO,CAAC,EAAE,WAAW,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,CAAA;CAAE,GACvE,SAAS,EACb,OAAO,EAAE,WAAW,EACpB,SAAS,EAAE,MAAM,GAAG,SAAS,GAC5B,MAAM,CAIR;AAED,0DAA0D;AAC1D,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CACzC,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,GAAG,SAAS,GAC5B,OAAO,CAAC,IAAI,CAAC,CAef;AAED;;;;;GAKG;AACH,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAkD3E"}
@@ -1,7 +1,7 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { execFile } from "node:child_process";
4
+ import { runOpencode } from "./opencode-cli.js";
5
5
  import { getTask, saveTask } from "../db/tasks-repo.js";
6
6
  import { appendStructuredLog } from "./structured-log.js";
7
7
  import { WRAPPER_DIR, sanitizeName } from "../types.js";
@@ -100,17 +100,24 @@ export async function rotateSessionIfNeeded(taskName) {
100
100
  const maxRuns = def.sessionMaxRuns ?? 0;
101
101
  const count = (def.sessionRunCount ?? 0) + 1;
102
102
  if (shouldRotateSession(count, maxRuns)) {
103
- const sessionId = def.sessionId;
104
- if (sessionId && isValidSessionId(sessionId)) {
105
- try {
106
- await new Promise((resolve) => {
107
- execFile("opencode", ["session", "delete", sessionId], () => resolve());
108
- });
109
- }
110
- catch {
111
- // Удаление не должно мешать: просто фиксируем в логе ниже.
103
+ const oldSessionId = def.sessionId;
104
+ const hasOldSession = Boolean(oldSessionId && isValidSessionId(oldSessionId));
105
+ let deleteError;
106
+ if (hasOldSession && oldSessionId) {
107
+ // На Windows `opencode` — это `opencode.cmd`, который Node не запускает
108
+ // напрямую через execFile (ENOENT/EINVAL). Общий модуль сам выбирает
109
+ // cmd.exe на Windows, поэтому удаление действительно выполняется.
110
+ const result = await runOpencode(["session", "delete", oldSessionId]);
111
+ if (!result.ok) {
112
+ deleteError = result.error ?? "неизвестная ошибка";
113
+ console.warn(`[session] Не удалось удалить сессию ${oldSessionId} задачи "${taskName}": ${deleteError}`);
112
114
  }
113
115
  }
116
+ const rotationNote = !hasOldSession
117
+ ? "старой сессии не было"
118
+ : deleteError
119
+ ? `старую сессию удалить не удалось (${deleteError})`
120
+ : "сессия удалена";
114
121
  const newSessionId = generateSessionId();
115
122
  await saveTask({
116
123
  ...def,
@@ -121,7 +128,7 @@ export async function rotateSessionIfNeeded(taskName) {
121
128
  appendStructuredLog({
122
129
  event: "session.rotated",
123
130
  task: taskName,
124
- reason: `maxRuns=${maxRuns} достигнут; сессия удалена, создана новая, счётчик сброшен`,
131
+ reason: `maxRuns=${maxRuns} достигнут; ${rotationNote}, создана новая, счётчик сброшен`,
125
132
  });
126
133
  }
127
134
  else {
@@ -32,7 +32,7 @@ function isRecord(value) {
32
32
  }
33
33
  function resolveEndpoint(baseUrl) {
34
34
  const base = baseUrl.replace(/\/+$/, "");
35
- if (/\/v1$/.test(base)) {
35
+ if (base.endsWith("/v1")) {
36
36
  return { url: `${base}/chat/completions`, protocol: "openai" };
37
37
  }
38
38
  return { url: `${base}/api/chat`, protocol: "ollama" };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * P1-10: разные имена задач могут сжаться в один sanitized-идентификатор
3
+ * («my task» и «my-task» → «my-task»), после чего делят wrapper, prompt,
4
+ * lock и log. При создании новой задачи такую коллизию нужно отклонить,
5
+ * иначе вторая задача молча перезапишет файлы первой.
6
+ */
7
+ export type SanitizedConflict = {
8
+ kind: "task";
9
+ taskName: string;
10
+ } | {
11
+ kind: "file";
12
+ file: string;
13
+ };
14
+ /**
15
+ * Ищет конфликт sanitized-имени среди существующих задач и их артефактов.
16
+ *
17
+ * @param name имя создаваемой задачи;
18
+ * @param existingNames имена уже существующих задач (без самой создаваемой);
19
+ * @param artifactExists проверка существования файла — подменяется в тестах.
20
+ */
21
+ export declare function findSanitizedNameConflict(name: string, existingNames: readonly string[], artifactExists?: (file: string) => boolean): SanitizedConflict | null;
22
+ /** Человекочитаемое объяснение конфликта для ошибки создания задачи. */
23
+ export declare function sanitizedConflictMessage(name: string, conflict: SanitizedConflict): string;
24
+ //# sourceMappingURL=task-name.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"task-name.d.ts","sourceRoot":"","sources":["../../src/core/task-name.ts"],"names":[],"mappings":"AAIA;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAEnC;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,MAAM,EACZ,aAAa,EAAE,SAAS,MAAM,EAAE,EAChC,cAAc,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAoB,GACrD,iBAAiB,GAAG,IAAI,CAwB1B;AAED,wEAAwE;AACxE,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,iBAAiB,GAC1B,MAAM,CAWR"}