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
@@ -0,0 +1,215 @@
1
+ #!/usr/bin/env node
2
+ // Сбор фактов для внешнего аудита. ПО УМОЛЧАНИЮ READ-ONLY.
3
+ // Мутирующее/сетевое — только по флагам: --build --tests --audit
4
+ // Выход: audit-bundle.md (для вставки), audit-bundle.json (для агента), audit-raw/*.log (полные логи)
5
+ import { spawnSync } from "node:child_process";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+
9
+ const argv = process.argv.slice(2);
10
+ const flag = (n) => argv.includes(`--${n}`);
11
+ const opt = (n, d) => { const a = argv.find(x => x.startsWith(`--${n}=`)); return a ? a.slice(n.length + 3) : d; };
12
+
13
+ const O = {
14
+ build: flag("build"), tests: flag("tests"), audit: flag("audit"),
15
+ since: opt("since", null),
16
+ cap: Number(opt("cap", 6000)),
17
+ maxBytes: Number(opt("max-bytes", 60000)),
18
+ budgetMs: Number(opt("budget", 180)) * 1000,
19
+ cmdMs: Number(opt("cmd-timeout", 60)) * 1000,
20
+ };
21
+
22
+ const T0 = Date.now();
23
+ const left = () => O.budgetMs - (Date.now() - T0);
24
+ const RAW = "audit-raw";
25
+ fs.mkdirSync(RAW, { recursive: true });
26
+ const NPM = process.platform === "win32" ? "npm.cmd" : "npm";
27
+
28
+ function run(cmd, args, { label, cwd, shell = false, timeout = O.cmdMs } = {}) {
29
+ if (left() <= 0) return { ok: false, out: "", note: "SKIP: бюджет времени исчерпан" };
30
+ const r = spawnSync(cmd, args, {
31
+ encoding: "utf8", cwd, shell, windowsHide: true,
32
+ timeout: Math.max(1000, Math.min(timeout, left())),
33
+ killSignal: "SIGKILL", maxBuffer: 64e6,
34
+ });
35
+ const out = (r.stdout || "") + (r.stderr || "");
36
+ if (label) fs.writeFileSync(path.join(RAW, `${label}.log`), out);
37
+ return { ok: r.status === 0, status: r.status, out, err: r.error ? String(r.error.message) : null };
38
+ }
39
+ const git = (...a) => run("git", a);
40
+ const npm = (a, o = {}) => run(NPM, a, { shell: true, ...o }); // .cmd требует shell
41
+
42
+ if (!fs.existsSync("package.json")) { console.error("Запусти из корня репозитория"); process.exit(1); }
43
+ const inGit = git("rev-parse", "--git-dir").ok;
44
+ const pkg = JSON.parse(fs.readFileSync("package.json", "utf8"));
45
+
46
+ // ---------- инвентарь с blob-sha ----------
47
+ let tracked = [];
48
+ if (inGit) {
49
+ tracked = git("ls-files", "-s").out.split("\n").filter(Boolean).map(l => {
50
+ const m = /^\d+ ([0-9a-f]+) \d+\t(.*)$/.exec(l);
51
+ return m ? { path: m[2], sha: m[1] } : null;
52
+ }).filter(Boolean);
53
+ } else {
54
+ const walk = (d, acc = []) => {
55
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
56
+ if (["node_modules", "dist", ".git", "coverage", RAW].includes(e.name)) continue;
57
+ const p = path.join(d, e.name);
58
+ e.isDirectory() ? walk(p, acc) : acc.push({ path: p.replace(/\\/g, "/"), sha: "" });
59
+ }
60
+ return acc;
61
+ };
62
+ tracked = walk(".");
63
+ }
64
+ const trackedSet = new Set(tracked.map(t => t.path));
65
+ for (const t of tracked) { try { t.size = fs.statSync(t.path).size; } catch { t.size = -1; } }
66
+ const bySize = [...tracked].sort((a, b) => b.size - a.size);
67
+
68
+ // игнорируемые исходники (ловит legacy/gui-experimental.cjs-класс багов)
69
+ const ignoredSrc = inGit
70
+ ? git("ls-files", "--others", "--ignored", "--exclude-standard").out
71
+ .split("\n").filter(p => /^(src|legacy|scripts)\//.test(p) || /\.(ts|tsx|js|cjs|mjs)$/.test(p))
72
+ : [];
73
+
74
+ // ---------- exports → диск / git / тарбол ----------
75
+ const targets = (e) => { const o = []; const w = v => { if (typeof v === "string") o.push(v); else if (v && typeof v === "object") Object.values(v).forEach(w); }; w(e); return [...new Set(o)]; };
76
+ function packList(cwd, label) {
77
+ const r = npm(["pack", "--dry-run", "--json", "--ignore-scripts"], { cwd, label });
78
+ try { const j = JSON.parse(r.out.slice(r.out.indexOf("["))); return new Set((j[0]?.files || []).map(f => f.path)); }
79
+ catch { return null; }
80
+ }
81
+ const packMain = packList(undefined, "pack-main");
82
+ const hasLegacy = fs.existsSync("legacy/package.json");
83
+ const packLegacy = hasLegacy ? packList("legacy", "pack-legacy") : null;
84
+
85
+ function expReport(p, base, pack) {
86
+ const rows = [];
87
+ for (const [k, v] of Object.entries(p.exports || {})) {
88
+ for (const t of targets(v)) {
89
+ const rel = path.posix.normalize(path.posix.join(base, t));
90
+ const disk = fs.existsSync(rel);
91
+ const inGitRepo = trackedSet.has(rel);
92
+ const inPack = pack ? pack.has(path.posix.relative(base, rel)) : null;
93
+ const bad = !disk || (inGit && !inGitRepo) || inPack === false;
94
+ rows.push(`${bad ? "❌" : "✅"} ${k} → ${t} | disk:${disk ? "ok" : "MISSING"} git:${inGitRepo ? "ok" : "UNTRACKED"} pack:${inPack === null ? "n/a" : inPack ? "ok" : "MISSING"}`);
95
+ }
96
+ }
97
+ return rows.join("\n") || "нет exports";
98
+ }
99
+
100
+ // ---------- тесты: обе стороны ----------
101
+ const chain = (pkg.scripts?.test || "").split("&&").map(s => s.trim().replace(/^node\s+/, "")).filter(Boolean);
102
+ const onDisk = tracked.filter(t => /^test-.*\.mjs$/.test(t.path)).map(t => t.path);
103
+ const notWired = onDisk.filter(f => !chain.includes(f));
104
+ const brokenChain = chain.filter(f => f.endsWith(".mjs") && !fs.existsSync(f));
105
+
106
+ // ---------- локали ----------
107
+ let localeReport = "нет locales/";
108
+ if (fs.existsSync("locales")) {
109
+ const cats = {};
110
+ for (const f of fs.readdirSync("locales").filter(f => f.endsWith(".json")))
111
+ cats[f.replace(".json", "")] = new Set(Object.keys(JSON.parse(fs.readFileSync(path.join("locales", f), "utf8"))));
112
+ const names = Object.keys(cats);
113
+ const all = new Set(names.flatMap(n => [...cats[n]]));
114
+ localeReport = names.map(n => {
115
+ const miss = [...all].filter(k => !cats[n].has(k));
116
+ return `${n}: ${cats[n].size} ключей, отсутствует ${miss.length}${miss.length ? " → " + miss.slice(0, 15).join(", ") : ""}`;
117
+ }).join("\n") + `\nвсего уникальных ключей: ${all.size}`;
118
+ }
119
+
120
+ // ---------- схема ----------
121
+ const schemaFile = ["src/db/schema.ts"].find(f => fs.existsSync(f));
122
+ const schemaSrc = schemaFile ? fs.readFileSync(schemaFile, "utf8") : "";
123
+ const schemaVer = /SCHEMA_VERSION\s*=\s*(\d+)/.exec(schemaSrc)?.[1] ?? "?";
124
+ const tables = [...schemaSrc.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?[`"]?(\w+)/g)].map(m => m[1]);
125
+
126
+ // ---------- grep (POSIX ERE, без shell) ----------
127
+ const gg = (pattern, ...paths) => {
128
+ if (!inGit) return "не git-репозиторий";
129
+ const r = run("git", ["grep", "-nE", pattern, "--", ...paths]);
130
+ return r.out.trim() || "(нет совпадений)";
131
+ };
132
+ const wiring = gg("routeStep|recordCapabilityOutcome|escalateAfterGate|planMission|createRun",
133
+ "src/index.ts", "src/core/record-history.ts", "src/core/wrappers", "src/core/ps-wrapper.ts");
134
+ const risky = gg("execSync|spawnSync|shell:[[:space:]]*true|JSON\\.parse|catch[[:space:]]*\\{[[:space:]]*\\}", "src");
135
+ const todos = gg("TODO|FIXME|HACK|XXX", "src");
136
+
137
+ // ---------- CI и конфиги ----------
138
+ const wfDir = ".github/workflows";
139
+ const workflows = fs.existsSync(wfDir)
140
+ ? fs.readdirSync(wfDir).map(f => {
141
+ const s = fs.readFileSync(path.join(wfDir, f), "utf8");
142
+ const keys = s.split("\n").filter(l => /runs-on|node-version|npm (run|ci|test)|matrix|cron/.test(l));
143
+ return `### ${f}\n${keys.join("\n")}`;
144
+ }).join("\n\n")
145
+ : "нет workflows";
146
+ const configs = ["tsconfig.json", "eslint.config.mjs", "vite.config.ts", ".gitignore"]
147
+ .filter(fs.existsSync).map(f => `### ${f}\n${fs.readFileSync(f, "utf8")}`).join("\n\n");
148
+
149
+ // ---------- опциональное ----------
150
+ const opt_ = {};
151
+ if (O.build) opt_.build = npm(["run", "build"], { label: "build", timeout: 240000 });
152
+ if (fs.existsSync("eslint.config.mjs") || pkg.scripts?.lint) opt_.lint = npm(["run", "lint", "--if-present"], { label: "lint", timeout: 180000 });
153
+ if (O.tests) {
154
+ const r = npm(["test"], { label: "tests", timeout: 1500000 });
155
+ const fails = r.out.split("\n").filter(l => /FAIL|✖|not ok|Error:|failed/i.test(l)).slice(0, 80);
156
+ opt_.tests = { ok: r.ok, out: `exit=${r.status}\n--- FAIL-строки ---\n${fails.join("\n")}\n--- хвост ---\n${r.out.split("\n").slice(-80).join("\n")}` };
157
+ }
158
+ if (O.audit) opt_.audit = npm(["audit", "--omit=dev"], { label: "audit", timeout: 90000 });
159
+
160
+ // ---------- сборка ----------
161
+ const sections = [];
162
+ const S = (t, b) => sections.push({ title: t, body: String(b ?? "").slice(0, O.cap) + (String(b ?? "").length > O.cap ? "\n…[обрезано, полный лог в audit-raw/]" : "") });
163
+
164
+ S("Окружение", [
165
+ `node ${process.version}`, `npm ${npm(["-v"]).out.trim()}`, `git ${git("--version").out.trim()}`,
166
+ `os ${process.platform} ${process.arch}`, `cwd ${process.cwd()}`,
167
+ `HEAD ${inGit ? git("rev-parse", "HEAD").out.trim() : "не git"}`,
168
+ `branch ${inGit ? git("rev-parse", "--abbrev-ref", "HEAD").out.trim() : "-"}`,
169
+ `dirty:\n${inGit ? git("status", "--porcelain").out.trim() || "(чисто)" : "-"}`,
170
+ `режим: read-only${O.build ? " +build" : ""}${O.tests ? " +tests" : ""}${O.audit ? " +audit" : ""}`,
171
+ ].join("\n"));
172
+ S("Последние 25 коммитов", inGit ? git("log", "-25", "--oneline").out : "-");
173
+ if (O.since) S(`Изменено с ${O.since}`, git("diff", "--name-only", `${O.since}..HEAD`).out);
174
+ S("Инвентарь: топ-60 по размеру", bySize.slice(0, 60).map(t => `${String(t.size).padStart(8)} ${t.sha.slice(0, 8)} ${t.path}`).join("\n"));
175
+ S("Итого", `${tracked.length} отслеживаемых файлов, ${tracked.reduce((a, t) => a + Math.max(0, t.size), 0)} байт`);
176
+ S("Игнорируемые исходники (риск невоспроизводимой публикации)", ignoredSrc.join("\n") || "(нет)");
177
+ S("package.json (срез)", JSON.stringify({ name: pkg.name, version: pkg.version, dependencies: pkg.dependencies, devDependencies: pkg.devDependencies, exports: pkg.exports, files: pkg.files, engines: pkg.engines }, null, 2));
178
+ S("EXPORTS main: диск / git / тарбол", expReport(pkg, ".", packMain));
179
+ if (hasLegacy) S("EXPORTS legacy: диск / git / тарбол", expReport(JSON.parse(fs.readFileSync("legacy/package.json", "utf8")), "legacy", packLegacy));
180
+ S("Сюиты на диске, но НЕ в npm test", notWired.join("\n") || "(все подключены)");
181
+ S("Сюиты в npm test, но файла НЕТ (битый chain)", brokenChain.join("\n") || "(нет)");
182
+ S("Локали: parity ключей", localeReport);
183
+ S("Схема", `SCHEMA_VERSION=${schemaVer}\nтаблицы: ${tables.join(", ") || "?"}`);
184
+ S("Wiring горячего пути", wiring);
185
+ S("Рискованные паттерны", risky);
186
+ S("TODO/FIXME", todos);
187
+ S("CI workflows (ключевые строки)", workflows);
188
+ S("Конфиги", configs);
189
+ S("npm ls --depth=0", npm(["ls", "--depth=0"], { label: "ls" }).out);
190
+ for (const [k, v] of Object.entries(opt_)) S(`Опционально: ${k}`, typeof v === "string" ? v : (v.out ?? JSON.stringify(v)));
191
+
192
+ let md = `# audit-bundle\n\nСобрано ${new Date().toISOString()} · бюджет ${O.budgetMs / 1000}s, потрачено ${((Date.now() - T0) / 1000).toFixed(1)}s\n\n`;
193
+ for (const s of sections) {
194
+ const chunk = `## ${s.title}\n\n\`\`\`\n${s.body}\n\`\`\`\n\n`;
195
+ if (md.length + chunk.length > O.maxBytes) { md += `## …усечено по --max-bytes\n\nПолные данные: audit-bundle.json и audit-raw/\n`; break; }
196
+ md += chunk;
197
+ }
198
+ fs.writeFileSync("audit-bundle.md", md);
199
+ fs.writeFileSync("audit-bundle.json", JSON.stringify({ head: inGit ? git("rev-parse", "HEAD").out.trim() : null, opts: O, tracked, ignoredSrc, notWired, brokenChain, schemaVer, tables, sections }, null, 2));
200
+
201
+ // coverage-ledger — только если ещё нет
202
+ if (!fs.existsSync("AUDIT-COVERAGE.md")) {
203
+ const rows = tracked.filter(t => /^src\//.test(t.path) || /^test-.*\.mjs$/.test(t.path))
204
+ .sort((a, b) => b.size - a.size)
205
+ .map(t => `| ${t.path} | ${t.size} | ${t.sha.slice(0, 8)} | — | не покрыто | — |`).join("\n");
206
+ fs.writeFileSync("AUDIT-COVERAGE.md", `# AUDIT-COVERAGE\n\n| Файл | Байт | Blob | Аудит (SHA) | Покрытие | Находки |\n|---|---|---|---|---|---|\n${rows}\n`);
207
+ }
208
+
209
+ const alerts = [
210
+ ignoredSrc.length && `игнорируемые исходники: ${ignoredSrc.length}`,
211
+ brokenChain.length && `битый test-chain: ${brokenChain.length}`,
212
+ notWired.length && `сюиты вне chain: ${notWired.length}`,
213
+ ].filter(Boolean);
214
+ console.log(`audit-bundle.md (${fs.statSync("audit-bundle.md").size} б), audit-bundle.json, audit-raw/`);
215
+ console.log(alerts.length ? "⚠ " + alerts.join(" · ") : "✅ быстрых аномалий не найдено");
@@ -164,7 +164,7 @@ function percent(part: number, total: number): number {
164
164
  */
165
165
  export function buildAnalytics(
166
166
  records: AnalyticsRecord[],
167
- options: BuildAnalyticsOptions = {}
167
+ options: BuildAnalyticsOptions = {},
168
168
  ): AnalyticsReport {
169
169
  const windowDays = Math.max(1, Math.floor(options.days ?? 14));
170
170
  const topLimit = Math.max(1, Math.floor(options.topLimit ?? 10));
@@ -416,7 +416,7 @@ export function historyToCsv(records: AnalyticsRecord[]): string {
416
416
  record.error ?? "",
417
417
  ]
418
418
  .map(csvCell)
419
- .join(";")
419
+ .join(";"),
420
420
  );
421
421
  }
422
422
  // BOM, чтобы Excel корректно открыл UTF-8 с кириллицей.
package/src/core/audit.ts CHANGED
@@ -110,7 +110,7 @@ export function recordAudit(entry: AuditEntryInput): number | null {
110
110
  .prepare(
111
111
  `INSERT INTO audit_log
112
112
  (ts, action, target_type, target, actor, source, details_json, remote)
113
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
113
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
114
114
  )
115
115
  .run(
116
116
  ts,
@@ -120,7 +120,7 @@ export function recordAudit(entry: AuditEntryInput): number | null {
120
120
  String(entry.actor || "system").slice(0, 32),
121
121
  entry.source == null ? null : String(entry.source).slice(0, 128),
122
122
  safeJson(entry.details),
123
- entry.remote == null ? null : String(entry.remote).slice(0, 128)
123
+ entry.remote == null ? null : String(entry.remote).slice(0, 128),
124
124
  );
125
125
  maybeCleanup();
126
126
  return Number(result.lastInsertRowid) || null;
@@ -129,7 +129,7 @@ export function recordAudit(entry: AuditEntryInput): number | null {
129
129
  console.warn(
130
130
  `[audit] не удалось записать событие: ${
131
131
  err instanceof Error ? err.message : String(err)
132
- }`
132
+ }`,
133
133
  );
134
134
  } catch {
135
135
  // console недоступен — молча игнорируем.
@@ -222,21 +222,21 @@ export function recordTaskToolBlocks(
222
222
  actor: AuditActor = "system",
223
223
  source = "policy",
224
224
  policy?: PermissionPolicy,
225
- legacyShell?: boolean
225
+ legacyShell?: boolean,
226
226
  ): number {
227
227
  const normalizedDenied = Array.from(
228
228
  new Set(
229
229
  (deniedTools ?? [])
230
230
  .map((tool) => String(tool).trim())
231
- .filter(Boolean)
232
- )
231
+ .filter(Boolean),
232
+ ),
233
233
  );
234
234
  const normalizedAllowed = Array.from(
235
235
  new Set(
236
236
  (allowedTools ?? [])
237
237
  .map((tool) => String(tool).trim())
238
- .filter(Boolean)
239
- )
238
+ .filter(Boolean),
239
+ ),
240
240
  );
241
241
  const details = {
242
242
  reason: "deniedTools",
@@ -331,17 +331,17 @@ export function readAuditLog(filter: ReadAuditFilter = {}): ReadAuditResult {
331
331
  const db = getDb();
332
332
  const totalRow = db
333
333
  .prepare(`SELECT COUNT(*) AS count FROM audit_log ${clause}`)
334
- .get(...params) as any;
334
+ .get(...params);
335
335
  const rows = db
336
336
  .prepare(`SELECT * FROM audit_log ${clause} ORDER BY ts DESC, id DESC LIMIT ?`)
337
- .all(...params, limit) as any[];
337
+ .all(...params, limit);
338
338
  return { records: rows.map(rowToRecord), total: Number(totalRow?.count) || 0 };
339
339
  } catch (err) {
340
340
  try {
341
341
  console.warn(
342
342
  `[audit] не удалось прочитать журнал: ${
343
343
  err instanceof Error ? err.message : String(err)
344
- }`
344
+ }`,
345
345
  );
346
346
  } catch {
347
347
  // ignore
@@ -360,23 +360,23 @@ export function cleanupAuditLog(options: {
360
360
  } = {}): number {
361
361
  const retentionDays = Math.max(
362
362
  0,
363
- Math.floor(options.retentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS) || 0
363
+ Math.floor(options.retentionDays ?? DEFAULT_AUDIT_RETENTION_DAYS) || 0,
364
364
  );
365
365
  const maxRecords = Math.max(
366
366
  100,
367
- Math.floor(options.maxRecords ?? DEFAULT_AUDIT_MAX_RECORDS) || DEFAULT_AUDIT_MAX_RECORDS
367
+ Math.floor(options.maxRecords ?? DEFAULT_AUDIT_MAX_RECORDS) || DEFAULT_AUDIT_MAX_RECORDS,
368
368
  );
369
369
  let deleted = 0;
370
370
  try {
371
371
  const db = getDb();
372
372
  if (retentionDays > 0) {
373
373
  const cutoff = new Date(
374
- Date.now() - retentionDays * 24 * 60 * 60 * 1000
374
+ Date.now() - retentionDays * 24 * 60 * 60 * 1000,
375
375
  ).toISOString();
376
376
  const result = db.prepare("DELETE FROM audit_log WHERE ts < ?").run(cutoff);
377
377
  deleted += Number(result.changes) || 0;
378
378
  }
379
- const countRow = db.prepare("SELECT COUNT(*) AS count FROM audit_log").get() as any;
379
+ const countRow = db.prepare("SELECT COUNT(*) AS count FROM audit_log").get();
380
380
  const count = Number(countRow?.count) || 0;
381
381
  if (count > maxRecords) {
382
382
  const excess = count - maxRecords;
@@ -384,7 +384,7 @@ export function cleanupAuditLog(options: {
384
384
  .prepare(
385
385
  `DELETE FROM audit_log WHERE id IN (
386
386
  SELECT id FROM audit_log ORDER BY ts ASC, id ASC LIMIT ?
387
- )`
387
+ )`,
388
388
  )
389
389
  .run(excess);
390
390
  deleted += Number(result.changes) || 0;
@@ -394,7 +394,7 @@ export function cleanupAuditLog(options: {
394
394
  console.warn(
395
395
  `[audit] не удалось очистить журнал: ${
396
396
  err instanceof Error ? err.message : String(err)
397
- }`
397
+ }`,
398
398
  );
399
399
  } catch {
400
400
  // ignore
@@ -46,7 +46,7 @@ function isStar(value: string): boolean {
46
46
  * Возвращает N или undefined.
47
47
  */
48
48
  function parseStep(value: string): number | undefined {
49
- const match = value.match(/^\*\/(\d+)$/);
49
+ const match = /^\*\/(\d+)$/.exec(value);
50
50
  if (!match) return undefined;
51
51
  const n = parseInt(match[1], 10);
52
52
  return n > 0 ? n : undefined;
@@ -74,7 +74,7 @@ export function convertCronToSchTasks(cron: string): CronConversion {
74
74
  "Ожидалось 5 полей cron-выражения (минута час день_месяца месяц день_недели), получено " +
75
75
  fields.length +
76
76
  ".\n\n" +
77
- UNSUPPORTED_ERROR
77
+ UNSUPPORTED_ERROR,
78
78
  );
79
79
  }
80
80
 
@@ -108,24 +108,30 @@ export function convertCronToSchTasks(cron: string): CronConversion {
108
108
  "Интервал /mo " +
109
109
  stepN +
110
110
  " минут превышает максимально допустимый для schtasks (1439 минут).\n\n" +
111
- UNSUPPORTED_ERROR
111
+ UNSUPPORTED_ERROR,
112
112
  );
113
113
  }
114
- // schtasks /mo N запускает задачу каждые N минут начиная с момента создания
115
- // задачи, а cron */N — в минуты 0, N, 2N внутри каждого часа. Семантики
116
- // совпадают только когда N делит 60 без остатка; иначе отдаём задачу в
117
- // минутный опрос с gate во враппере (needsPollMode).
114
+ // schtasks /mo Nanchors на момент создания задачи, а cron */N означает
115
+ // минуты 0, N, 2N … внутри часа. Семантики совпадают только когда N
116
+ // делит 60 без остатка И есть выровненный старт (00:00), поэтому ниже
117
+ // добавляется startTime: "00:00". Для N, не делящих 60, выбрасывается
118
+ // ошибка — задача уходит в минутный опрос с gate во враппере
119
+ // (needsPollMode в windows.ts), а не конвертируется здесь нативно.
118
120
  if (60 % stepN !== 0) {
119
121
  throw new Error(
120
122
  "Интервал */" +
121
123
  stepN +
122
124
  " не делит час нацело: cron и schtasks понимают его по-разному.\n\n" +
123
- UNSUPPORTED_ERROR
125
+ UNSUPPORTED_ERROR,
124
126
  );
125
127
  }
126
128
  return {
127
129
  sc: "MINUTE",
128
130
  extraFlags: ["/mo", String(stepN)],
131
+ // schtasks /mo Nanchors на момент создания задачи; cron */N означает
132
+ // минуты 0, N, 2N … внутри часа. Выровненный старт 00:00 делает
133
+ // расписание идентичным cron для любого N, делящего 60.
134
+ startTime: "00:00",
129
135
  };
130
136
  }
131
137
 
@@ -186,91 +192,6 @@ export function convertCronToSchTasks(cron: string): CronConversion {
186
192
  throw new Error(UNSUPPORTED_ERROR);
187
193
  }
188
194
 
189
- /**
190
- * Вычисляет ближайшее прошедшее (<= now) время срабатывания для поддерживаемых
191
- * cron-выражений. Нужно для восстановления пропущенных запусков (catch-up):
192
- * сравнивая это время с историей, можно понять, выполнялась ли задача.
193
- *
194
- * Возвращает null, если выражение не поддерживается или не распознано.
195
- */
196
- export function previousRunTime(cron: string, now: Date = new Date()): Date | null {
197
- const fields = cron.trim().split(/\s+/);
198
- if (fields.length !== 5) return null;
199
-
200
- const [minute, hour, dayOfMonth, month, dayOfWeek] = fields;
201
- const star = (value: string) => value === "*";
202
- const intIn = (value: string, min: number, max: number): number | undefined => {
203
- if (!/^\d+$/.test(value)) return undefined;
204
- const n = parseInt(value, 10);
205
- return n >= min && n <= max ? n : undefined;
206
- };
207
- const nowMs = now.getTime();
208
-
209
- // * * * * * — каждую минуту: последняя граница минуты.
210
- if (star(minute) && star(hour) && star(dayOfMonth) && star(month) && star(dayOfWeek)) {
211
- return new Date(Math.floor(nowMs / 60000) * 60000);
212
- }
213
-
214
- // */N * * * * — каждые N минут внутри часа (минуты 0, N, 2N...).
215
- const step = /^\*\/(\d+)$/.exec(minute);
216
- if (step && star(hour) && star(dayOfMonth) && star(month) && star(dayOfWeek)) {
217
- const n = parseInt(step[1], 10);
218
- if (n > 0) {
219
- const result = new Date(now);
220
- result.setSeconds(0, 0);
221
- const minuteOfHour = result.getMinutes();
222
- result.setMinutes(n >= 60 ? 0 : minuteOfHour - (minuteOfHour % n));
223
- return result;
224
- }
225
- return null;
226
- }
227
-
228
- // M * * * * — каждый час в минуту M.
229
- const hourlyMinute = intIn(minute, 0, 59);
230
- if (
231
- hourlyMinute !== undefined &&
232
- star(hour) &&
233
- star(dayOfMonth) &&
234
- star(month) &&
235
- star(dayOfWeek)
236
- ) {
237
- const result = new Date(now);
238
- result.setSeconds(0, 0);
239
- result.setMinutes(hourlyMinute);
240
- if (result.getTime() > nowMs) result.setHours(result.getHours() - 1);
241
- return result;
242
- }
243
-
244
- const m = intIn(minute, 0, 59);
245
- const h = intIn(hour, 0, 23);
246
- if (m === undefined || h === undefined || !star(dayOfMonth) || !star(month)) {
247
- return null;
248
- }
249
-
250
- // M H * * * — ежедневно в HH:MM.
251
- if (star(dayOfWeek)) {
252
- const result = new Date(now);
253
- result.setSeconds(0, 0);
254
- result.setHours(h, m, 0, 0);
255
- if (result.getTime() > nowMs) result.setDate(result.getDate() - 1);
256
- return result;
257
- }
258
-
259
- // M H * * D — еженедельно в день D (0 и 7 — воскресенье) в HH:MM.
260
- const dow = intIn(dayOfWeek, 0, 7);
261
- if (dow === undefined) return null;
262
- const targetDow = dow === 7 ? 0 : dow;
263
- const result = new Date(now);
264
- result.setSeconds(0, 0);
265
- result.setHours(h, m, 0, 0);
266
- // Не больше 8 итераций: одна неделя гарантированно содержит нужный день.
267
- for (let i = 0; i <= 8; i += 1) {
268
- if (result.getTime() <= nowMs && result.getDay() === targetDow) return result;
269
- result.setDate(result.getDate() - 1);
270
- }
271
- return null;
272
- }
273
-
274
195
  /**
275
196
  * Формирует массив флагов расписания для schtasks на основе CronConversion.
276
197
  * Включает /sc, /st (если есть), и дополнительные флаги (/mo, /d).
@@ -0,0 +1,98 @@
1
+ /**
2
+ * GUI/RPC-фасад над dead-letter queue (Спринт 36.6).
3
+ *
4
+ * Тонкий слой между `src/db/run-dlq.ts` и RPC: приводит вход от GUI к
5
+ * безопасным значениям (статус, лимит), не даёт панике БД выйти наружу и
6
+ * возвращает единый `{ success, error }`-контракт. Логика очереди (идемпотентный
7
+ * enqueue, retry через reopenRun, discard) остаётся в БД-слое.
8
+ *
9
+ * Retry здесь только готовит шаг к повторному выполнению: переоткрывает запуск,
10
+ * переводит шаг в `running` и закрывает запись DLQ. Сам обработчик шага
11
+ * запускает resume (Спринт 36.7), поэтому фасад не притворяется, что шаг уже
12
+ * выполнен.
13
+ */
14
+ import {
15
+ countDeadLetters,
16
+ discardDeadLetter,
17
+ listDeadLetters,
18
+ retryDeadLetter,
19
+ type DlqEntry,
20
+ type DlqStatus,
21
+ } from "../db/run-dlq.js";
22
+
23
+ /** Фильтр списка: конкретный статус или все записи. */
24
+ export type DlqFilter = DlqStatus | "all";
25
+
26
+ export interface DlqListResult {
27
+ success: boolean;
28
+ entries: DlqEntry[];
29
+ /** Сколько записей открыто (для бейджа в заголовке панели). */
30
+ open: number;
31
+ error?: string;
32
+ }
33
+
34
+ export interface DlqActionResult {
35
+ success: boolean;
36
+ error?: string;
37
+ entry?: DlqEntry;
38
+ runId?: string;
39
+ stepName?: string;
40
+ /** true, если retry переоткрыл упавший запуск. */
41
+ runReopened?: boolean;
42
+ }
43
+
44
+ function errorText(err: unknown): string {
45
+ return err instanceof Error ? err.message : String(err);
46
+ }
47
+
48
+ /** Неизвестный статус трактуем как `open`: безопасный дефолт очереди. */
49
+ export function normalizeDlqFilter(value: unknown): DlqFilter {
50
+ return value === "all" || value === "retried" || value === "discarded" || value === "open"
51
+ ? value
52
+ : "open";
53
+ }
54
+
55
+ function normalizeLimit(value: unknown, fallback = 100): number {
56
+ const num = Math.floor(Number(value));
57
+ if (!Number.isFinite(num) || num < 1) return fallback;
58
+ return Math.min(num, 500);
59
+ }
60
+
61
+ /** Список записей DLQ и счётчик открытых. */
62
+ export function listDlq(options: { status?: unknown; limit?: unknown } = {}): DlqListResult {
63
+ try {
64
+ const status = normalizeDlqFilter(options.status);
65
+ return {
66
+ success: true,
67
+ entries: listDeadLetters({ status, limit: normalizeLimit(options.limit) }),
68
+ open: countDeadLetters("open"),
69
+ };
70
+ } catch (err) {
71
+ return { success: false, entries: [], open: 0, error: errorText(err) };
72
+ }
73
+ }
74
+
75
+ /** Ручной retry: готовит шаг к выполнению и закрывает запись DLQ. */
76
+ export function retryDlq(id: string): DlqActionResult {
77
+ try {
78
+ const result = retryDeadLetter(id);
79
+ return {
80
+ success: true,
81
+ entry: result.entry,
82
+ runId: result.run.id,
83
+ stepName: result.step.stepName,
84
+ runReopened: result.runReopened,
85
+ };
86
+ } catch (err) {
87
+ return { success: false, error: errorText(err) };
88
+ }
89
+ }
90
+
91
+ /** Осознанный отказ от повтора: запись закрывается, шаг остаётся failed. */
92
+ export function discardDlq(id: string, resolution = "discarded"): DlqActionResult {
93
+ try {
94
+ return { success: true, entry: discardDeadLetter(id, resolution) };
95
+ } catch (err) {
96
+ return { success: false, error: errorText(err) };
97
+ }
98
+ }