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
  /**
9
10
  * Зашифрованное хранилище секретов (Спринт 26).
@@ -26,6 +27,85 @@ export const SECRET_REF_RE = /\$\{secret:([A-Za-z0-9_.-]{1,64})\}/g;
26
27
  const SECRET_NAME_RE = /^[A-Za-z0-9_.-]{1,64}$/;
27
28
  const KEY_BYTES = 32;
28
29
 
30
+ /**
31
+ * P2-20: межпроцессная блокировка записи секретов.
32
+ *
33
+ * setSecret/deleteSecret — это read-modify-write одного JSON. Каждое завершение
34
+ * задачи может быть отдельным процессом, поэтому без лока параллельные записи
35
+ * теряли секреты. Лок синхронный: API setSecret/deleteSecret синхронный и
36
+ * используется из CLI/GUI/плагина, переписывать его на async нельзя.
37
+ */
38
+ const SECRETS_LOCK_FILE = `${SECRETS_FILE}.lock`;
39
+ const SECRETS_LOCK_STALE_MS = 10_000;
40
+ const SECRETS_LOCK_TIMEOUT_MS = 5_000;
41
+ let secretsLockDepth = 0;
42
+
43
+ function sleepSync(ms: number): void {
44
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
45
+ }
46
+
47
+ function withSecretsLock<T>(fn: () => T): T {
48
+ // Реентерабельность: loadKey()/readFileSafe() вызываются внутри setSecret.
49
+ if (secretsLockDepth > 0) {
50
+ secretsLockDepth += 1;
51
+ try {
52
+ return fn();
53
+ } finally {
54
+ secretsLockDepth -= 1;
55
+ }
56
+ }
57
+
58
+ ensureDir();
59
+ const deadline = Date.now() + SECRETS_LOCK_TIMEOUT_MS;
60
+ for (;;) {
61
+ try {
62
+ const fd = fs.openSync(SECRETS_LOCK_FILE, "wx");
63
+ try {
64
+ fs.writeFileSync(fd, String(process.pid));
65
+ } finally {
66
+ fs.closeSync(fd);
67
+ }
68
+ secretsLockDepth = 1;
69
+ break;
70
+ } catch (err: any) {
71
+ if (err?.code !== "EEXIST") throw err;
72
+ try {
73
+ const stat = fs.statSync(SECRETS_LOCK_FILE);
74
+ if (Date.now() - stat.mtimeMs > SECRETS_LOCK_STALE_MS) {
75
+ const owner = Number.parseInt(
76
+ fs.readFileSync(SECRETS_LOCK_FILE, "utf8").trim(),
77
+ 10,
78
+ );
79
+ if (!Number.isInteger(owner) || !isProcessAlive(owner)) {
80
+ fs.rmSync(SECRETS_LOCK_FILE, { force: true });
81
+ continue;
82
+ }
83
+ }
84
+ } catch {
85
+ // Лок исчез между stat и read — повторяем попытку.
86
+ }
87
+ if (Date.now() >= deadline) {
88
+ throw new Error(
89
+ "Не удалось получить блокировку хранилища секретов за " +
90
+ `${SECRETS_LOCK_TIMEOUT_MS} мс.`,
91
+ );
92
+ }
93
+ sleepSync(25);
94
+ }
95
+ }
96
+
97
+ try {
98
+ return fn();
99
+ } finally {
100
+ secretsLockDepth = 0;
101
+ try {
102
+ fs.rmSync(SECRETS_LOCK_FILE, { force: true });
103
+ } catch {
104
+ // Не критично: лок всё равно станет stale.
105
+ }
106
+ }
107
+ }
108
+
29
109
  interface StoredSecret {
30
110
  /** IV в base64 (12 байт). */
31
111
  iv: string;
@@ -59,7 +139,7 @@ let keyCache: { stamp: string; key: Buffer } | null = null;
59
139
  function warn(message: string, err: unknown): void {
60
140
  try {
61
141
  console.warn(
62
- `[secrets] ${message}: ${err instanceof Error ? err.message : String(err)}`
142
+ `[secrets] ${message}: ${err instanceof Error ? err.message : String(err)}`,
63
143
  );
64
144
  } catch {
65
145
  // console может быть недоступен — молча игнорируем.
@@ -71,7 +151,7 @@ export function validateSecretName(name: string): string {
71
151
  const value = String(name ?? "").trim();
72
152
  if (!SECRET_NAME_RE.test(value)) {
73
153
  throw new Error(
74
- "Имя секрета: латиница, цифры, '_', '.', '-', от 1 до 64 символов."
154
+ "Имя секрета: латиница, цифры, '_', '.', '-', от 1 до 64 символов.",
75
155
  );
76
156
  }
77
157
  return value;
@@ -115,18 +195,18 @@ function restrictWindowsAcl(file: string): void {
115
195
  const result = spawnSync(
116
196
  "icacls",
117
197
  [file, "/inheritance:r", "/grant:r", `${currentWindowsUser()}:F`],
118
- { windowsHide: true, stdio: "ignore" }
198
+ { windowsHide: true, stdio: "ignore" },
119
199
  );
120
200
  if (result.status === 0) return;
121
201
  throw new Error(
122
- result.error?.message ?? `icacls завершился с кодом ${result.status}`
202
+ result.error?.message ?? `icacls завершился с кодом ${result.status}`,
123
203
  );
124
204
  } catch (err) {
125
205
  if (windowsAclWarned) return;
126
206
  windowsAclWarned = true;
127
207
  warn(
128
208
  "не удалось ограничить ACL файла секретов; ключ может быть доступен другим локальным пользователям",
129
- err
209
+ err,
130
210
  );
131
211
  }
132
212
  }
@@ -161,11 +241,28 @@ function loadKey(): Buffer {
161
241
  return raw;
162
242
  } catch (err: any) {
163
243
  if (err?.code !== "ENOENT") throw err;
164
- const key = crypto.randomBytes(KEY_BYTES);
165
- fs.writeFileSync(SECRETS_KEY_FILE, key, { mode: 0o600 });
166
- chmodPrivate(SECRETS_KEY_FILE);
167
- keyCache = { stamp: `${fs.statSync(SECRETS_KEY_FILE).mtimeMs}:${KEY_BYTES}`, key };
168
- return key;
244
+ // Два процесса могли одновременно не найти ключ и сгенерировать разный.
245
+ // Под локом перечитываем файл: побеждает первый, остальные используют его ключ.
246
+ return withSecretsLock(() => {
247
+ try {
248
+ const raw = fs.readFileSync(SECRETS_KEY_FILE);
249
+ if (raw.length !== KEY_BYTES) {
250
+ throw new Error("повреждён файл ключа секретов");
251
+ }
252
+ keyCache = {
253
+ stamp: `${fs.statSync(SECRETS_KEY_FILE).mtimeMs}:${raw.length}`,
254
+ key: raw,
255
+ };
256
+ return raw;
257
+ } catch (readErr: any) {
258
+ if (readErr?.code !== "ENOENT") throw readErr;
259
+ }
260
+ const key = crypto.randomBytes(KEY_BYTES);
261
+ fs.writeFileSync(SECRETS_KEY_FILE, key, { mode: 0o600 });
262
+ chmodPrivate(SECRETS_KEY_FILE);
263
+ keyCache = { stamp: `${fs.statSync(SECRETS_KEY_FILE).mtimeMs}:${KEY_BYTES}`, key };
264
+ return key;
265
+ });
169
266
  }
170
267
  }
171
268
 
@@ -197,8 +294,8 @@ function quarantineCorruptStore(err: unknown): boolean {
197
294
  corruptedStore = target;
198
295
  warn(
199
296
  `secrets.json повреждён, но его не удалось переместить в ${target}. ` +
200
- `Запись новых секретов заблокирована, чтобы не потерять данные.`,
201
- renameErr
297
+ "Запись новых секретов заблокирована, чтобы не потерять данные.",
298
+ renameErr,
202
299
  );
203
300
  return false;
204
301
  }
@@ -214,7 +311,7 @@ function readFileSafe(): SecretsFile {
214
311
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
215
312
  throw new Error("некорректный формат secrets.json");
216
313
  }
217
- const rawSecrets = (parsed as any).secrets;
314
+ const rawSecrets = (parsed).secrets;
218
315
  const secrets: Record<string, StoredSecret> = {};
219
316
  if (rawSecrets && typeof rawSecrets === "object" && !Array.isArray(rawSecrets)) {
220
317
  for (const [name, entry] of Object.entries(rawSecrets)) {
@@ -251,13 +348,11 @@ function readFileSafe(): SecretsFile {
251
348
  /** Атомарная запись: temp + rename, права 0600. */
252
349
  function writeFileSafe(file: SecretsFile): void {
253
350
  ensureDir();
254
- const tmp = `${SECRETS_FILE}.tmp`;
351
+ // Уникальный temp: два процесса не должны писать в один и тот же файл.
352
+ const tmp = `${SECRETS_FILE}.${process.pid}.${Date.now()}.tmp`;
255
353
  fs.writeFileSync(tmp, JSON.stringify(file, null, 2), { encoding: "utf8", mode: 0o600 });
256
- try {
257
- fs.rmSync(SECRETS_FILE, { force: true });
258
- } catch {
259
- // файла нет — не ошибка
260
- }
354
+ // Без предварительного rm: rename на POSIX и Windows атомарно заменяет файл,
355
+ // а rm открывал окно, в котором secrets.json отсутствовал при краше.
261
356
  fs.renameSync(tmp, SECRETS_FILE);
262
357
  chmodPrivate(SECRETS_FILE);
263
358
  try {
@@ -285,7 +380,7 @@ function decryptValue(name: string, entry: StoredSecret, key: Buffer): string {
285
380
  const decipher = crypto.createDecipheriv(
286
381
  "aes-256-gcm",
287
382
  key,
288
- Buffer.from(entry.iv, "base64")
383
+ Buffer.from(entry.iv, "base64"),
289
384
  );
290
385
  decipher.setAAD(Buffer.from(name, "utf8"));
291
386
  decipher.setAuthTag(Buffer.from(entry.tag, "base64"));
@@ -300,20 +395,22 @@ export function setSecret(name: string, value: string): SecretListItem {
300
395
  if (corruptedStore) {
301
396
  throw new Error(
302
397
  `Хранилище секретов повреждено (${corruptedStore}). ` +
303
- "Устраните проблему с файлом перед записью новых секретов."
398
+ "Устраните проблему с файлом перед записью новых секретов.",
304
399
  );
305
400
  }
306
401
  const secretName = validateSecretName(name);
307
402
  const text = String(value ?? "");
308
- const key = loadKey();
309
- const file = readFileSafe();
310
- file.secrets[secretName] = encryptValue(secretName, text, key);
311
- writeFileSafe(file);
312
- return {
313
- name: secretName,
314
- preview: previewOf(text),
315
- updatedAt: file.secrets[secretName].updatedAt,
316
- };
403
+ return withSecretsLock(() => {
404
+ const key = loadKey();
405
+ const file = readFileSafe();
406
+ file.secrets[secretName] = encryptValue(secretName, text, key);
407
+ writeFileSafe(file);
408
+ return {
409
+ name: secretName,
410
+ preview: previewOf(text),
411
+ updatedAt: file.secrets[secretName].updatedAt,
412
+ };
413
+ });
317
414
  }
318
415
 
319
416
  /** Читает секрет; undefined, если его нет или он не расшифровывается. */
@@ -338,11 +435,13 @@ export function hasSecret(name: string): boolean {
338
435
  /** Удаляет секрет; true — запись была. */
339
436
  export function deleteSecret(name: string): boolean {
340
437
  const secretName = validateSecretName(name);
341
- const file = readFileSafe();
342
- if (!(secretName in file.secrets)) return false;
343
- delete file.secrets[secretName];
344
- writeFileSafe(file);
345
- return true;
438
+ return withSecretsLock(() => {
439
+ const file = readFileSafe();
440
+ if (!(secretName in file.secrets)) return false;
441
+ delete file.secrets[secretName];
442
+ writeFileSafe(file);
443
+ return true;
444
+ });
346
445
  }
347
446
 
348
447
  function previewOf(value: string): string {
@@ -372,7 +471,7 @@ export function listSecrets(): SecretListItem[] {
372
471
  /** Подставляет все ссылки `${secret:NAME}` в строку. Если задан allowedSecretNames — заменяются только ссылки на имена из этого списка (scoped-инъекция), остальные оставляются без изменений. */
373
472
  export function expandSecretRefs(
374
473
  value: string,
375
- allowedSecretNames?: string[]
474
+ allowedSecretNames?: string[],
376
475
  ): { value: string; missing: string[] } {
377
476
  const missing = new Set<string>();
378
477
  const allowed = allowedSecretNames ? new Set(allowedSecretNames) : null;
@@ -401,7 +500,7 @@ export function expandSecretRefs(
401
500
  */
402
501
  export function resolveSecretRefs(
403
502
  env: Record<string, string>,
404
- allowedSecretNames?: string[]
503
+ allowedSecretNames?: string[],
405
504
  ): { env: Record<string, string>; missing: string[] } {
406
505
  const resolved: Record<string, string> = {};
407
506
  const missing = new Set<string>();
@@ -465,8 +564,9 @@ export function redactSecretsInText(text: unknown): string {
465
564
  }
466
565
 
467
566
  result = result.replace(
468
- /\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|CREDENTIAL|AUTH)[A-Za-z0-9_]*)\b(\s*[=:]\s*)(["']?)([^\s"',;]+)\3/gi,
469
- (_match: string, key: string, sep: string, quote: string) => `${key}${sep}${quote}***${quote}`
567
+ /(["']?)\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,
568
+ (_match: string, openQuote: string, key: string, sep: string, quote: string) =>
569
+ `${openQuote}${key}${openQuote}${sep}${quote}***${quote}`,
470
570
  );
471
571
 
472
572
  // Восстанавливаем защищённые ссылки.
@@ -142,8 +142,8 @@ export function calculateHealthScore(report: AnalyticsReport): HealthScore {
142
142
  const successRateScore = totals.successRate;
143
143
  const errorRateScore = Math.max(0, 100 - (totals.error / Math.max(1, totals.total)) * 100);
144
144
  const avgDurationScore = Math.min(100, Math.max(0, 100 - (totals.avgDurationMs / 300000) * 100)); // 5 минут = 0 баллов
145
- const timeoutRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes('timeout')).length / Math.max(1, totals.total)) * 100));
146
- const crashRecoveryRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes('Прервано')).length / Math.max(1, totals.total)) * 100));
145
+ const timeoutRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes("timeout")).length / Math.max(1, totals.total)) * 100));
146
+ const crashRecoveryRateScore = Math.min(100, Math.max(0, 100 - (errors.filter(e => e.message.includes("Прервано")).length / Math.max(1, totals.total)) * 100));
147
147
 
148
148
  // Взвешенная сумма
149
149
  const score = Math.round(
@@ -151,7 +151,7 @@ export function calculateHealthScore(report: AnalyticsReport): HealthScore {
151
151
  errorRateScore * 0.25 +
152
152
  avgDurationScore * 0.20 +
153
153
  timeoutRateScore * 0.10 +
154
- crashRecoveryRateScore * 0.10
154
+ crashRecoveryRateScore * 0.10,
155
155
  );
156
156
 
157
157
  // Уровень здоровья
@@ -199,7 +199,7 @@ export function calculateHealthScore(report: AnalyticsReport): HealthScore {
199
199
  /** Обнаруживает аномалии в данных. */
200
200
  export function detectAnomalies(
201
201
  records: AnalyticsRecord[],
202
- options: SelfAnalysisOptions = {}
202
+ options: SelfAnalysisOptions = {},
203
203
  ): Anomaly[] {
204
204
  const anomalies: Anomaly[] = [];
205
205
  const now = options.now ?? new Date();
@@ -251,8 +251,8 @@ function detectErrorSpike(records: AnalyticsRecord[], windowDays: number): Anoma
251
251
  const older = records.slice(half);
252
252
  const recent = records.slice(0, half);
253
253
 
254
- const recentErrorRate = recent.filter(r => r.status === 'error').length / recent.length;
255
- const olderErrorRate = older.filter(r => r.status === 'error').length / older.length;
254
+ const recentErrorRate = recent.filter(r => r.status === "error").length / recent.length;
255
+ const olderErrorRate = older.filter(r => r.status === "error").length / older.length;
256
256
 
257
257
  // Всплеск ошибок: недавний период значительно хуже старого
258
258
  if (olderErrorRate < 0.5 && recentErrorRate > olderErrorRate * 2 && recentErrorRate > 0.3) {
@@ -264,13 +264,13 @@ function detectErrorSpike(records: AnalyticsRecord[], windowDays: number): Anoma
264
264
  recommendations: [
265
265
  "Проверьте логи ошибок за последнее время",
266
266
  "Убедитесь, что Quality Gate настроен правильно",
267
- "Рассмотрите добавление retryCount"
267
+ "Рассмотрите добавление retryCount",
268
268
  ],
269
269
  metadata: {
270
270
  recentErrorRate,
271
271
  olderErrorRate,
272
- windowDays
273
- }
272
+ windowDays,
273
+ },
274
274
  };
275
275
  }
276
276
  return null;
@@ -298,13 +298,13 @@ function detectDurationSpike(records: AnalyticsRecord[]): Anomaly | null {
298
298
  recommendations: [
299
299
  "Проверьте, не завис ли процесс",
300
300
  "Увеличьте timeoutSeconds если задача легитимно долгая",
301
- "Рассмотрите разделение задачи на части"
301
+ "Рассмотрите разделение задачи на части",
302
302
  ],
303
303
  metadata: {
304
304
  recentDuration,
305
305
  medianDuration: median,
306
- ratio: recentDuration / median
307
- }
306
+ ratio: recentDuration / median,
307
+ },
308
308
  };
309
309
  }
310
310
  return null;
@@ -313,7 +313,7 @@ function detectDurationSpike(records: AnalyticsRecord[]): Anomaly | null {
313
313
  function detectTimeoutSpike(records: AnalyticsRecord[]): Anomaly | null {
314
314
  if (records.length < 5) return null;
315
315
 
316
- const timeoutCount = records.filter(r => r.error?.includes('timeout')).length;
316
+ const timeoutCount = records.filter(r => r.error?.includes("timeout")).length;
317
317
  const timeoutRate = timeoutCount / records.length;
318
318
 
319
319
  if (timeoutRate > 0.2) {
@@ -325,13 +325,13 @@ function detectTimeoutSpike(records: AnalyticsRecord[]): Anomaly | null {
325
325
  recommendations: [
326
326
  "Увеличьте timeoutSeconds",
327
327
  "Упростите промпты задачи",
328
- "Проверьте производительность модели"
328
+ "Проверьте производительность модели",
329
329
  ],
330
330
  metadata: {
331
331
  timeoutCount,
332
332
  totalRecords: records.length,
333
- timeoutRate
334
- }
333
+ timeoutRate,
334
+ },
335
335
  };
336
336
  }
337
337
  return null;
@@ -359,13 +359,13 @@ function detectCostSpike(records: AnalyticsRecord[]): Anomaly | null {
359
359
  recommendations: [
360
360
  "Проверьте, не используется ли более дорогая модель",
361
361
  "Оптимизируйте промпты для снижения токенов",
362
- "Рассмотрите использование локальной модели"
362
+ "Рассмотрите использование локальной модели",
363
363
  ],
364
364
  metadata: {
365
365
  recentCost,
366
366
  medianCost: median,
367
- ratio: recentCost / median
368
- }
367
+ ratio: recentCost / median,
368
+ },
369
369
  };
370
370
  }
371
371
  return null;
@@ -376,8 +376,8 @@ function detectUnusualPattern(records: AnalyticsRecord[]): Anomaly | null {
376
376
 
377
377
  // Проверяем паттерн: все подряд ошибки или все подряд успехи
378
378
  const recent = records.slice(0, 5);
379
- const allErrors = recent.every(r => r.status === 'error');
380
- const allSuccess = recent.every(r => r.status === 'success');
379
+ const allErrors = recent.every(r => r.status === "error");
380
+ const allSuccess = recent.every(r => r.status === "success");
381
381
 
382
382
  if (allErrors) {
383
383
  return {
@@ -388,12 +388,12 @@ function detectUnusualPattern(records: AnalyticsRecord[]): Anomaly | null {
388
388
  recommendations: [
389
389
  "Проверьте, не сломалась ли зависимость",
390
390
  "Проверьте доступность внешних сервисов",
391
- "Рассмотрите приостановку задачи до устранения проблемы"
391
+ "Рассмотрите приостановку задачи до устранения проблемы",
392
392
  ],
393
393
  metadata: {
394
394
  pattern: "consecutive_errors",
395
- count: 5
396
- }
395
+ count: 5,
396
+ },
397
397
  };
398
398
  }
399
399
 
@@ -401,7 +401,7 @@ function detectUnusualPattern(records: AnalyticsRecord[]): Anomaly | null {
401
401
  }
402
402
 
403
403
  function detectStalledRun(records: AnalyticsRecord[], now: Date): Anomaly | null {
404
- const running = records.find(r => r.status === 'running');
404
+ const running = records.find(r => r.status === "running");
405
405
  if (!running) return null;
406
406
 
407
407
  const startedAt = new Date(running.startedAt);
@@ -416,13 +416,13 @@ function detectStalledRun(records: AnalyticsRecord[], now: Date): Anomaly | null
416
416
  recommendations: [
417
417
  "Проверьте, не завис ли процесс",
418
418
  "Рассмотрите принудительное завершение",
419
- "Проверьте блокировки (lock file)"
419
+ "Проверьте блокировки (lock file)",
420
420
  ],
421
421
  metadata: {
422
422
  hoursRunning,
423
423
  startedAt: running.startedAt,
424
- taskId: (running as any).id
425
- }
424
+ taskId: (running as any).id,
425
+ },
426
426
  };
427
427
  }
428
428
  return null;
@@ -433,7 +433,7 @@ function detectStalledRun(records: AnalyticsRecord[], now: Date): Anomaly | null
433
433
  /** Анализирует тренды метрик. */
434
434
  export function analyzeTrends(
435
435
  records: AnalyticsRecord[],
436
- options: SelfAnalysisOptions = {}
436
+ options: SelfAnalysisOptions = {},
437
437
  ): Trend[] {
438
438
  const trends: Trend[] = [];
439
439
  const windowDays = options.days ?? 14;
@@ -446,8 +446,8 @@ export function analyzeTrends(
446
446
  if (older.length < 3 || recent.length < 3) return trends;
447
447
 
448
448
  // 1. Тренд успешности
449
- const olderSuccessRate = older.filter(r => r.status === 'success').length / older.length;
450
- const recentSuccessRate = recent.filter(r => r.status === 'success').length / recent.length;
449
+ const olderSuccessRate = older.filter(r => r.status === "success").length / older.length;
450
+ const recentSuccessRate = recent.filter(r => r.status === "success").length / recent.length;
451
451
  const successChange = ((recentSuccessRate - olderSuccessRate) / Math.max(olderSuccessRate, 0.01)) * 100;
452
452
 
453
453
  trends.push({
@@ -457,8 +457,8 @@ export function analyzeTrends(
457
457
  description: `Успешность: ${Math.round(olderSuccessRate * 100)}% → ${Math.round(recentSuccessRate * 100)}%`,
458
458
  recommendations: successChange < -10 ? [
459
459
  "Проверьте, что изменилось в последнее время",
460
- "Проверьте логи ошибок"
461
- ] : []
460
+ "Проверьте логи ошибок",
461
+ ] : [],
462
462
  });
463
463
 
464
464
  // 2. Тренд длительности
@@ -477,8 +477,8 @@ export function analyzeTrends(
477
477
  description: `Средняя длительность: ${Math.round(olderAvgDuration / 1000)}с → ${Math.round(recentAvgDuration / 1000)}с`,
478
478
  recommendations: durationChange > 20 ? [
479
479
  "Оптимизируйте промпты",
480
- "Проверьте, не увеличилась ли нагрузка"
481
- ] : []
480
+ "Проверьте, не увеличилась ли нагрузка",
481
+ ] : [],
482
482
  });
483
483
  }
484
484
 
@@ -498,8 +498,8 @@ export function analyzeTrends(
498
498
  description: `Средняя стоимость: $${olderAvgCost.toFixed(4)} → $${recentAvgCost.toFixed(4)}`,
499
499
  recommendations: costChange > 20 ? [
500
500
  "Проверьте, не используется ли более дорогая модель",
501
- "Оптимизируйте промпты для снижения токенов"
502
- ] : []
501
+ "Оптимизируйте промпты для снижения токенов",
502
+ ] : [],
503
503
  });
504
504
  }
505
505
 
@@ -512,7 +512,7 @@ export function analyzeTrends(
512
512
  export function generateRecommendations(
513
513
  report: AnalyticsReport,
514
514
  anomalies: Anomaly[],
515
- trends: Trend[]
515
+ trends: Trend[],
516
516
  ): Recommendation[] {
517
517
  const recommendations: Recommendation[] = [];
518
518
 
@@ -534,8 +534,8 @@ export function generateRecommendations(
534
534
  "Проверьте логи ошибок за последние 7 дней",
535
535
  "Убедитесь, что Quality Gate настроен правильно",
536
536
  "Добавьте retryCount для флакких задач",
537
- "Проверьте доступность внешних сервисов"
538
- ]
537
+ "Проверьте доступность внешних сервисов",
538
+ ],
539
539
  });
540
540
  }
541
541
 
@@ -544,12 +544,12 @@ export function generateRecommendations(
544
544
  if (anomaly.severity > 70) {
545
545
  recommendations.push({
546
546
  priority: Math.min(10, Math.round(anomaly.severity / 10)),
547
- category: anomaly.type.includes('cost') ? "cost" : "performance",
547
+ category: anomaly.type.includes("cost") ? "cost" : "performance",
548
548
  title: `Устраните аномалию: ${anomaly.type}`,
549
549
  description: anomaly.description,
550
550
  expectedImpact: "Снизит нагрузку и улучшит стабильность",
551
551
  effort: "medium",
552
- steps: anomaly.recommendations
552
+ steps: anomaly.recommendations,
553
553
  });
554
554
  }
555
555
  }
@@ -559,12 +559,12 @@ export function generateRecommendations(
559
559
  if (trend.direction === "degrading" && Math.abs(trend.changePercent) > 20) {
560
560
  recommendations.push({
561
561
  priority: 7,
562
- category: trend.metric.includes('cost') ? "cost" : "performance",
562
+ category: trend.metric.includes("cost") ? "cost" : "performance",
563
563
  title: `Обратите внимание на тренд: ${trend.metric}`,
564
564
  description: trend.description,
565
565
  expectedImpact: "Предотвратит дальнейшее ухудшение",
566
566
  effort: "low",
567
- steps: trend.recommendations
567
+ steps: trend.recommendations,
568
568
  });
569
569
  }
570
570
  }
@@ -582,8 +582,8 @@ export function generateRecommendations(
582
582
  "Проверьте, не используется ли более дорогая модель для простых задач",
583
583
  "Оптимизируйте промпты для снижения токенов",
584
584
  "Рассмотрите использование локальной модели для простых задач",
585
- "Настройте лимиты на задачи с высокими затратами"
586
- ]
585
+ "Настройте лимиты на задачи с высокими затратами",
586
+ ],
587
587
  });
588
588
  }
589
589
 
@@ -600,13 +600,13 @@ export function generateRecommendations(
600
600
  "Разбейте длинные задачи на более мелкие",
601
601
  "Упростите промпты",
602
602
  "Проверьте, не используются ли медленные модели",
603
- "Увеличьте timeoutSeconds если задачи легитимно долгие"
604
- ]
603
+ "Увеличьте timeoutSeconds если задачи легитимно долгие",
604
+ ],
605
605
  });
606
606
  }
607
607
 
608
608
  // Рекомендации на основе таймаутов
609
- const timeoutErrors = report.errors.filter(e => e.message.includes('timeout'));
609
+ const timeoutErrors = report.errors.filter(e => e.message.includes("timeout"));
610
610
  if (timeoutErrors.length > 0) {
611
611
  recommendations.push({
612
612
  priority: 8,
@@ -619,13 +619,13 @@ export function generateRecommendations(
619
619
  "Увеличьте timeoutSeconds для затронутых задач",
620
620
  "Упростите промпты",
621
621
  "Проверьте производительность модели",
622
- "Рассмотрите разделение сложных задач"
623
- ]
622
+ "Рассмотрите разделение сложных задач",
623
+ ],
624
624
  });
625
625
  }
626
626
 
627
627
  // Рекомендации на основе крашей
628
- const crashErrors = report.errors.filter(e => e.message.includes('Прервано'));
628
+ const crashErrors = report.errors.filter(e => e.message.includes("Прервано"));
629
629
  if (crashErrors.length > 0) {
630
630
  recommendations.push({
631
631
  priority: 7,
@@ -638,8 +638,8 @@ export function generateRecommendations(
638
638
  "Проверьте стабильность системы",
639
639
  "Проверьте, нет ли конфликтов между задачами",
640
640
  "Убедитесь, что задачи не превышают лимиты ресурсов",
641
- "Рассмотрите настройку crash recovery"
642
- ]
641
+ "Рассмотрите настройку crash recovery",
642
+ ],
643
643
  });
644
644
  }
645
645
 
@@ -652,7 +652,7 @@ export function generateRecommendations(
652
652
  /** Генерирует полный отчёт самоанализа. */
653
653
  export function generateSelfAnalysisReport(
654
654
  records: AnalyticsRecord[],
655
- options: SelfAnalysisOptions = {}
655
+ options: SelfAnalysisOptions = {},
656
656
  ): SelfAnalysisReport {
657
657
  const windowDays = options.days ?? 14;
658
658
  const now = options.now ?? new Date();
@@ -662,7 +662,7 @@ export function generateSelfAnalysisReport(
662
662
  days: windowDays,
663
663
  now,
664
664
  topLimit: options.topLimit,
665
- tasks: options.tasks
665
+ tasks: options.tasks,
666
666
  });
667
667
 
668
668
  // Health Score
@@ -691,8 +691,8 @@ export function generateSelfAnalysisReport(
691
691
  sources: {
692
692
  historyRecords: records.length,
693
693
  recordsInWindow: analyticsReport.sources.recordsInWindow,
694
- tasksAnalyzed: analyticsReport.tasks.length
695
- }
694
+ tasksAnalyzed: analyticsReport.tasks.length,
695
+ },
696
696
  };
697
697
  }
698
698
 
@@ -700,7 +700,7 @@ function generateSummary(
700
700
  health: HealthScore,
701
701
  anomalies: Anomaly[],
702
702
  trends: Trend[],
703
- recommendations: Recommendation[]
703
+ recommendations: Recommendation[],
704
704
  ): string {
705
705
  const parts: string[] = [];
706
706
 
@@ -710,7 +710,7 @@ function generateSummary(
710
710
  good: "хорошее",
711
711
  fair: "удовлетворительное",
712
712
  poor: "плохое",
713
- critical: "критическое"
713
+ critical: "критическое",
714
714
  };
715
715
  parts.push(`Здоровье системы: ${levelNames[health.level]} (${health.score}/100)`);
716
716
 
@@ -727,7 +727,7 @@ function generateSummary(
727
727
  }
728
728
 
729
729
  // Тренды
730
- const degradingTrends = trends.filter(t => t.direction === 'degrading').length;
730
+ const degradingTrends = trends.filter(t => t.direction === "degrading").length;
731
731
  if (degradingTrends > 0) {
732
732
  parts.push(`${degradingTrends} метрик ухудшаются`);
733
733
  }