local-triage 0.0.0-stage → 0.10.0-dev.32

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 (223) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/THIRD-PARTY-NOTICES.md +48 -0
  4. package/app/__init__.py +3 -0
  5. package/app/affiliation.py +137 -0
  6. package/app/ask.py +300 -0
  7. package/app/build_info.py +98 -0
  8. package/app/capec.py +168 -0
  9. package/app/capec_view.py +27 -0
  10. package/app/codecmp.py +59 -0
  11. package/app/config.py +411 -0
  12. package/app/context.py +1451 -0
  13. package/app/cvss.py +357 -0
  14. package/app/db.py +6234 -0
  15. package/app/defect.py +670 -0
  16. package/app/defect_check.py +323 -0
  17. package/app/defect_drafts.py +612 -0
  18. package/app/defect_dto.py +149 -0
  19. package/app/defect_fields.py +248 -0
  20. package/app/defect_form.py +124 -0
  21. package/app/defect_links.py +107 -0
  22. package/app/defect_local_text.py +103 -0
  23. package/app/defect_references.py +164 -0
  24. package/app/defect_where.py +147 -0
  25. package/app/ecosystem.py +51 -0
  26. package/app/executors.py +660 -0
  27. package/app/feeds.py +1231 -0
  28. package/app/guard.py +164 -0
  29. package/app/hub_block_builder.py +200 -0
  30. package/app/hub_block_version.py +220 -0
  31. package/app/hub_defects.py +4469 -0
  32. package/app/hub_effects.py +421 -0
  33. package/app/hub_entity_versions.py +108 -0
  34. package/app/hub_import.py +2054 -0
  35. package/app/hub_onboarding.py +114 -0
  36. package/app/hub_ops.py +330 -0
  37. package/app/hub_pull.py +1195 -0
  38. package/app/hub_state.py +255 -0
  39. package/app/hub_status.py +237 -0
  40. package/app/hub_sync.py +619 -0
  41. package/app/hub_sync_api.py +241 -0
  42. package/app/hub_sync_compare.py +1054 -0
  43. package/app/hub_sync_contract.py +75 -0
  44. package/app/hub_template_model.py +74 -0
  45. package/app/hub_text_scale.py +159 -0
  46. package/app/journal.py +250 -0
  47. package/app/llm.py +850 -0
  48. package/app/llm_chat.py +596 -0
  49. package/app/llm_http.py +319 -0
  50. package/app/llm_messages.py +401 -0
  51. package/app/llm_net.py +764 -0
  52. package/app/llm_ollama.py +571 -0
  53. package/app/lockfile.py +505 -0
  54. package/app/logsafe.py +54 -0
  55. package/app/main.py +367 -0
  56. package/app/mask_display.py +132 -0
  57. package/app/masking.py +814 -0
  58. package/app/metrics.py +194 -0
  59. package/app/model_traffic.py +519 -0
  60. package/app/models.py +483 -0
  61. package/app/navigation.py +121 -0
  62. package/app/osv.py +279 -0
  63. package/app/package_identity.py +189 -0
  64. package/app/package_transition.py +824 -0
  65. package/app/profile_gate.py +71 -0
  66. package/app/prompts.py +1108 -0
  67. package/app/provider_keys.py +189 -0
  68. package/app/providers.py +511 -0
  69. package/app/routes/__init__.py +10 -0
  70. package/app/routes/api.py +153 -0
  71. package/app/routes/capec.py +186 -0
  72. package/app/routes/common.py +407 -0
  73. package/app/routes/components.py +1499 -0
  74. package/app/routes/cwe.py +168 -0
  75. package/app/routes/decision_selected.py +153 -0
  76. package/app/routes/defect_add.py +223 -0
  77. package/app/routes/defect_card_routes.py +363 -0
  78. package/app/routes/defect_selected.py +342 -0
  79. package/app/routes/feeds.py +155 -0
  80. package/app/routes/findings.py +2736 -0
  81. package/app/routes/hub.py +402 -0
  82. package/app/routes/hub_bulk.py +288 -0
  83. package/app/routes/hub_defect_routes.py +1945 -0
  84. package/app/routes/hub_status_routes.py +1132 -0
  85. package/app/routes/hub_sync_routes.py +463 -0
  86. package/app/routes/journal.py +132 -0
  87. package/app/routes/projects.py +1601 -0
  88. package/app/routes/providers.py +336 -0
  89. package/app/routes/references.py +26 -0
  90. package/app/routes/runs.py +219 -0
  91. package/app/routes/sca.py +2722 -0
  92. package/app/routes/settings.py +163 -0
  93. package/app/run_errors.py +151 -0
  94. package/app/sca.py +1662 -0
  95. package/app/sca_contract.py +1289 -0
  96. package/app/sca_research.py +1089 -0
  97. package/app/sca_research_net.py +1007 -0
  98. package/app/sca_text.py +965 -0
  99. package/app/serve.py +70 -0
  100. package/app/settings_store.py +262 -0
  101. package/app/static/app.css +2802 -0
  102. package/app/static/app.js +3772 -0
  103. package/app/static/capec-license.txt +9 -0
  104. package/app/static/favicon.svg +1 -0
  105. package/app/static/fonts/Golos-Text_DemiBold.woff2 +0 -0
  106. package/app/static/fonts/Golos-Text_Regular.woff2 +0 -0
  107. package/app/static/fonts/OFL.txt +90 -0
  108. package/app/static/navigation.js +234 -0
  109. package/app/static/observability.js +121 -0
  110. package/app/static/theme.js +49 -0
  111. package/app/storage/__init__.py +16 -0
  112. package/app/storage/local_state.py +246 -0
  113. package/app/storage/migrate.py +110 -0
  114. package/app/storage/migrations/postgresql/0001_baseline.sql +896 -0
  115. package/app/storage/migrations/postgresql/0002_feeds_and_secrets.sql +55 -0
  116. package/app/storage/migrations/postgresql/0003_project_mask_display.sql +5 -0
  117. package/app/storage/migrations/postgresql/0004_package_identity.sql +36 -0
  118. package/app/storage/postgresql.py +573 -0
  119. package/app/storage/schema.py +619 -0
  120. package/app/storage/sql.py +57 -0
  121. package/app/storage/tools.py +254 -0
  122. package/app/telemetry.py +307 -0
  123. package/app/templates/base.html +91 -0
  124. package/app/templates/capec/context.html +3 -0
  125. package/app/templates/capec/detail.html +27 -0
  126. package/app/templates/capec/index.html +128 -0
  127. package/app/templates/components/_archive.html +11 -0
  128. package/app/templates/components/archived.html +19 -0
  129. package/app/templates/components/batch.html +35 -0
  130. package/app/templates/components/detail.html +332 -0
  131. package/app/templates/components/index.html +338 -0
  132. package/app/templates/components/research_preview.html +80 -0
  133. package/app/templates/components/research_run.html +54 -0
  134. package/app/templates/cwe/bdu.html +56 -0
  135. package/app/templates/cwe/detail.html +233 -0
  136. package/app/templates/cwe/index.html +97 -0
  137. package/app/templates/error.html +8 -0
  138. package/app/templates/feeds/index.html +65 -0
  139. package/app/templates/findings/card.html +639 -0
  140. package/app/templates/findings/decision_selected.html +41 -0
  141. package/app/templates/findings/defect_add.html +46 -0
  142. package/app/templates/findings/defect_selected.html +47 -0
  143. package/app/templates/findings/list.html +153 -0
  144. package/app/templates/findings/send_selected.html +53 -0
  145. package/app/templates/findings/trace.html +72 -0
  146. package/app/templates/journal/detail.html +19 -0
  147. package/app/templates/journal/index.html +19 -0
  148. package/app/templates/macros.html +440 -0
  149. package/app/templates/navigation-fields.html +1 -0
  150. package/app/templates/navigation.html +11 -0
  151. package/app/templates/projects/_identity_summary.html +42 -0
  152. package/app/templates/projects/defect_card.html +153 -0
  153. package/app/templates/projects/defect_create_preview.html +17 -0
  154. package/app/templates/projects/defect_fields_diff.html +6 -0
  155. package/app/templates/projects/defect_fields_form.html +40 -0
  156. package/app/templates/projects/defect_references.html +17 -0
  157. package/app/templates/projects/defect_sync_preview.html +28 -0
  158. package/app/templates/projects/defect_update_actions.html +6 -0
  159. package/app/templates/projects/defect_update_preview.html +24 -0
  160. package/app/templates/projects/defects.html +126 -0
  161. package/app/templates/projects/delete.html +31 -0
  162. package/app/templates/projects/external.html +61 -0
  163. package/app/templates/projects/folders.html +64 -0
  164. package/app/templates/projects/hub_accepted.html +10 -0
  165. package/app/templates/projects/hub_assignment.html +50 -0
  166. package/app/templates/projects/hub_pending.html +20 -0
  167. package/app/templates/projects/hub_pending_list.html +17 -0
  168. package/app/templates/projects/hub_state_note.html +23 -0
  169. package/app/templates/projects/hub_step_note.html +5 -0
  170. package/app/templates/projects/hub_sync.html +105 -0
  171. package/app/templates/projects/hub_sync_confirm.html +32 -0
  172. package/app/templates/projects/hub_sync_worker.html +5 -0
  173. package/app/templates/projects/hub_text_rules.html +64 -0
  174. package/app/templates/projects/identity_report.html +74 -0
  175. package/app/templates/projects/list.html +90 -0
  176. package/app/templates/projects/project.html +433 -0
  177. package/app/templates/reference-missing.html +14 -0
  178. package/app/templates/runs/run.html +166 -0
  179. package/app/templates/sca/card.html +476 -0
  180. package/app/templates/sca/index.html +321 -0
  181. package/app/templates/settings/hub_url.html +31 -0
  182. package/app/templates/settings/index.html +216 -0
  183. package/app/templates/settings/provider.html +229 -0
  184. package/app/templates/settings/providers.html +37 -0
  185. package/app/templates/worklists.html +52 -0
  186. package/app/textsafe.py +117 -0
  187. package/app/timing.py +245 -0
  188. package/app/triage.py +1743 -0
  189. package/app/view.py +430 -0
  190. package/app/worklists.py +204 -0
  191. package/examples/demo/demo-hub-report-v2.xlsx +0 -0
  192. package/examples/demo/demo-hub-report.xlsx +0 -0
  193. package/examples/demo/repos/billing-core/pom.xml +30 -0
  194. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/Invoice.java +9 -0
  195. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceRepository.java +51 -0
  196. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceStatus.java +11 -0
  197. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/config/DatabaseSettings.java +18 -0
  198. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/payment/PaymentTokenService.java +35 -0
  199. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/web/InvoiceExportController.java +57 -0
  200. package/examples/demo/repos/catalog-api/catalog_api/__init__.py +1 -0
  201. package/examples/demo/repos/catalog-api/catalog_api/products.py +24 -0
  202. package/examples/demo/repos/catalog-api/catalog_api/tasks.py +24 -0
  203. package/examples/demo/repos/catalog-api/catalog_api/views.py +17 -0
  204. package/examples/demo/repos/catalog-api/requirements.txt +3 -0
  205. package/npm/build.json +5 -0
  206. package/npm/cli.js +346 -0
  207. package/npm/files.manifest +224 -0
  208. package/npm/lib/binding.js +64 -0
  209. package/npm/lib/cluster.js +330 -0
  210. package/npm/lib/env.js +88 -0
  211. package/npm/lib/fsx.js +125 -0
  212. package/npm/lib/http.js +53 -0
  213. package/npm/lib/metrics.js +73 -0
  214. package/npm/lib/paths.js +150 -0
  215. package/npm/lib/pg.js +351 -0
  216. package/npm/lib/proc.js +101 -0
  217. package/npm/lib/python.js +133 -0
  218. package/npm/lib/stand.js +46 -0
  219. package/npm/lib/supervisor.js +1141 -0
  220. package/npm/lib/version.js +21 -0
  221. package/npm/requirements.txt +476 -0
  222. package/npm-shrinkwrap.json +111 -0
  223. package/package.json +37 -4
package/npm/lib/pg.js ADDED
@@ -0,0 +1,351 @@
1
+ 'use strict';
2
+ // PostgreSQL учебного стенда (раздел 3.4 плана): свой цикл жизни сервера на бинарниках пакета @embedded-postgres.
3
+ // Сам пакет embedded-postgres не используется: его остановка на Windows – taskkill /f /t, пароль кладётся в TEMP,
4
+ // сервер запускается напрямую, а не через pg_ctl. Аргументы вызовов – по таблице плана; тесты проверяют массивы.
5
+
6
+ const crypto = require('node:crypto');
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const fsx = require('./fsx');
10
+ const { spawnSync } = require('node:child_process');
11
+
12
+ const { StandError } = require('./paths');
13
+
14
+ const PG_MAJOR = '17';
15
+ const PG_RELEASE = '17.12';
16
+ const PACKAGE_VERSION = '17.12.0-beta.19';
17
+ const PLATFORM_PACKAGES = {
18
+ 'win32-x64': '@embedded-postgres/windows-x64',
19
+ 'linux-x64': '@embedded-postgres/linux-x64',
20
+ 'linux-arm64': '@embedded-postgres/linux-arm64',
21
+ 'darwin-arm64': '@embedded-postgres/darwin-arm64',
22
+ 'darwin-x64': '@embedded-postgres/darwin-x64',
23
+ };
24
+ const CLUSTER_FILES = ['PG_VERSION', path.join('global', 'pg_control'), 'postgresql.conf'];
25
+ const CONF_NAME = 'local-triage.conf';
26
+ const INCLUDE_LINE = `include_if_exists = '${CONF_NAME}'`;
27
+ const LOG_KEEP_DAYS = 14;
28
+
29
+ function platformPackage(platform = process.platform, arch = process.arch) {
30
+ if (platform === 'win32' && arch === 'arm64') {
31
+ throw new StandError('Windows на ARM64 стенд не поддерживает: для неё нет ни сборки PostgreSQL, ни колеса psycopg-binary.');
32
+ }
33
+ const name = PLATFORM_PACKAGES[`${platform}-${arch}`];
34
+ if (!name) throw new StandError(`Платформа ${platform}-${arch} не поддерживается: есть сборки для Windows x64, Linux x64 и arm64, macOS.`);
35
+ return name;
36
+ }
37
+
38
+ /** Папка native платформенного пакета – ищется от папки пакета стенда (в кэше npx – рядом с ним). */
39
+ function nativeDir(packageDir, platform = process.platform, arch = process.arch) {
40
+ const name = platformPackage(platform, arch);
41
+ // package.json пакета закрыт полем exports, поэтому не require.resolve, а обход node_modules вверх от папки пакета:
42
+ // в кэше npx платформенный пакет лежит рядом с самим стендом
43
+ for (let dir = path.resolve(packageDir); ; dir = path.dirname(dir)) {
44
+ const pkgDir = path.join(dir, 'node_modules', ...name.split('/'));
45
+ const native = path.join(pkgDir, 'native');
46
+ let found = '';
47
+ try { found = JSON.parse(fs.readFileSync(path.join(pkgDir, 'package.json'), 'utf8')).version || ''; } catch { found = ''; }
48
+ // только закреплённая версия: пакет другой версии выше по дереву не подменяет PostgreSQL стенда (ревью круга 9)
49
+ if (found === PACKAGE_VERSION && fs.existsSync(path.join(native, 'bin'))) return native;
50
+ if (path.dirname(dir) === dir) break;
51
+ }
52
+ // npm cache clean дерево npx не трогает; удалить можно только дерево npx, а не проект пользователя (ревью круга 8)
53
+ // дерево кэша npx: <кэш>/_npx/<хеш>/node_modules/local-triage – только оно, не проект с похожим именем
54
+ const tree = path.resolve(packageDir, '..', '..');
55
+ const npx = path.basename(path.dirname(tree)) === '_npx' && /^[0-9a-f]{8,}$/i.test(path.basename(tree)) &&
56
+ path.basename(path.dirname(path.resolve(packageDir))) === 'node_modules';
57
+ throw new StandError(`Не найден пакет ${name}: установка npm неполная (платформенный пакет не скачался). ` + (npx
58
+ ? `Удалите папку установки стенда в кэше npx ${tree} (в npm 11 – командой npm cache npx rm --force) и запустите стенд снова.`
59
+ : 'Переустановите зависимости проекта без пропуска необязательных: npm install (без --omit=optional).'));
60
+ }
61
+
62
+ function exe(binDir, name, platform = process.platform) {
63
+ return path.join(binDir, 'bin', platform === 'win32' ? `${name}.exe` : name);
64
+ }
65
+
66
+ // ---------------------------------------------------------------- аргументы вызовов (таблица раздела 3.4)
67
+
68
+ function initdbArgs(dataDir, pwfile) {
69
+ return ['-D', dataDir, '-U', 'triage', `--pwfile=${pwfile}`, '--auth=scram-sha-256', '-E', 'UTF8', '--locale=C',
70
+ '--locale-provider=builtin', '--builtin-locale=C.UTF-8'];
71
+ }
72
+
73
+ function syncOnlyArgs(dataDir) {
74
+ return ['--sync-only', '-D', dataDir];
75
+ }
76
+
77
+ function startArgs(dataDir, logFile) {
78
+ return ['start', '-D', dataDir, '-l', logFile, '-w', '-t', '60'];
79
+ }
80
+
81
+ function statusArgs(dataDir) {
82
+ return ['status', '-D', dataDir];
83
+ }
84
+
85
+ function stopArgs(dataDir, mode = 'fast') {
86
+ return ['stop', '-D', dataDir, '-m', mode, '-w', '-t', '30'];
87
+ }
88
+
89
+ // ---------------------------------------------------------------- бинарники
90
+
91
+ /**
92
+ * Копия бинарников из платформенного пакета в pg/bin-17.12: во временную папку без разыменования ссылок, затем каждая
93
+ * цель из pg-symlinks.json (Linux) пересоздаётся относительной ссылкой, затем атомарное переименование. Повторный
94
+ * запуск поверх готовой папки ничего не меняет. Ответ – true, если папка создана этим вызовом.
95
+ */
96
+ /** Копия бинарников полная: каждый файл платформенного пакета (все вложенные папки: bin, lib, share…) есть в копии
97
+ * (ревью кругов 4–5: без pg_ctl или share/postgres.bki стенд не поднимался, хотя пакет был цел). */
98
+ function binariesComplete(source, binDir) {
99
+ const walk = (rel) => {
100
+ let entries;
101
+ try { entries = fs.readdirSync(path.join(source, rel), { withFileTypes: true }); } catch { return false; }
102
+ for (const entry of entries) {
103
+ const child = rel ? path.join(rel, entry.name) : entry.name;
104
+ if (entry.isDirectory()) {
105
+ if (!walk(child)) return false;
106
+ } else {
107
+ // файл на месте и того же размера (усечённый файл – не копия); ссылка – раскрывается
108
+ let src;
109
+ let dst;
110
+ try { src = fs.statSync(path.join(source, child)); dst = fs.statSync(path.join(binDir, child)); } catch { return false; }
111
+ // размер и время изменения (копия сохраняет время источника, допуск 2 мс на округление файловой системы);
112
+ // время разошлось – решает содержимое (ревью кругов 7–8)
113
+ if (!dst.isFile() || dst.size !== src.size) return false;
114
+ if (Math.abs(dst.mtimeMs - src.mtimeMs) > 2) {
115
+ try {
116
+ if (!fs.readFileSync(path.join(binDir, child)).equals(fs.readFileSync(path.join(source, child)))) return false;
117
+ } catch { return false; }
118
+ }
119
+ }
120
+ }
121
+ return true;
122
+ };
123
+ if (!fs.existsSync(path.join(source, 'bin')) || !walk('')) return false;
124
+ // ссылки из pg-symlinks.json (Linux) создаются при копировании: каждая должна раскрываться в файл
125
+ let links = [];
126
+ try { links = JSON.parse(fs.readFileSync(path.join(source, 'pg-symlinks.json'), 'utf8')); } catch { links = []; }
127
+ for (const link of Array.isArray(links) ? links : []) {
128
+ const strip = (p) => String(p).replace(/^native[\\/]/, '');
129
+ const target = path.join(binDir, strip(link.target));
130
+ const expected = path.relative(path.dirname(target), path.join(binDir, strip(link.source)));
131
+ try {
132
+ if (fs.readlinkSync(target) !== expected || !fs.statSync(target).isFile()) return false; // цель ссылки – та самая
133
+ } catch { return false; }
134
+ }
135
+ return true;
136
+ }
137
+
138
+ /** Мажорная версия каталога – до любого переноса или удаления (§3.4): чужая версия – отказ, каталог не тронут. */
139
+ function checkMajor(dir, required = false) {
140
+ let major;
141
+ try {
142
+ major = fs.readFileSync(path.join(dir, 'PG_VERSION'), 'utf8').trim();
143
+ } catch (error) {
144
+ // версии нет у незаконченной копии – её можно убрать; каталог, который станет рабочим, обязан быть целым
145
+ if (error.code === 'ENOENT' && !required) return;
146
+ throw new StandError(`Версию PostgreSQL каталога ${dir} прочитать не удалось (${error.code}): стенд его не меняет, ` +
147
+ 'оба каталога и метки оставлены как были. Пришлите журнал преподавателю.');
148
+ }
149
+ if (required) checkCluster(dir);
150
+ if (major !== PG_MAJOR) {
151
+ throw new StandError(`Каталог ${dir} создан PostgreSQL ${major}, а в стенде – ${PG_RELEASE}: стенд его не меняет. ` +
152
+ 'Запустите версию стенда, которая создала эту базу.');
153
+ }
154
+ }
155
+
156
+ function installBinaries(source, binDir, platform = process.platform, { force = false } = {}) {
157
+ if (!force && binariesComplete(source, binDir)) return false; // --reinstall – пересборка копии в любом случае
158
+ fs.mkdirSync(path.dirname(binDir), { recursive: true });
159
+ fsx.removeLeftovers(path.dirname(binDir), path.basename(binDir)); // остатки прерванных копий с любым номером процесса
160
+ const tmp = `${binDir}.tmp-${process.pid}`;
161
+ fs.cpSync(source, tmp, { recursive: true, dereference: false, verbatimSymlinks: true, errorOnExist: false, preserveTimestamps: true });
162
+ let links = [];
163
+ try {
164
+ links = JSON.parse(fs.readFileSync(path.join(source, 'pg-symlinks.json'), 'utf8'));
165
+ } catch {
166
+ links = [];
167
+ }
168
+ for (const link of Array.isArray(links) ? links : []) {
169
+ // пути в pg-symlinks.json – от корня пакета: native/lib/… – их часть после native/ ложится в копию
170
+ const strip = (p) => String(p).replace(/^native[\\/]/, '');
171
+ const target = path.join(tmp, strip(link.target));
172
+ const sourcePath = path.join(tmp, strip(link.source));
173
+ fs.rmSync(target, { force: true });
174
+ fs.symlinkSync(path.relative(path.dirname(target), sourcePath), target);
175
+ }
176
+ if (platform !== 'win32') {
177
+ for (const name of fs.readdirSync(path.join(tmp, 'bin'))) fs.chmodSync(path.join(tmp, 'bin', name), 0o755);
178
+ }
179
+ // неполная прежняя папка – в сторону, новая – на место, прежняя удаляется последней
180
+ const old = `${binDir}.old-${process.pid}`;
181
+ if (fs.existsSync(binDir)) fsx.renameSync(binDir, old);
182
+ try {
183
+ fsx.renameSync(tmp, binDir);
184
+ } catch (error) {
185
+ if (fs.existsSync(old) && !fs.existsSync(binDir)) fs.renameSync(old, binDir);
186
+ throw error;
187
+ }
188
+ try { fsx.rmSync(old, { recursive: true, force: true }, 5000); } catch { /* удалится при следующей установке */ }
189
+ return true;
190
+ }
191
+
192
+ // ---------------------------------------------------------------- пароль и кластер
193
+
194
+ /**
195
+ * Пароль базы: до первого initdb – 24 случайных байта в base64url одной строкой (так его читает --pwfile – первая
196
+ * строка файла, Д17), только для пользователя. Файл появляется сразу целым: временный файл и переименование. При
197
+ * существующем кластере – прежний; кластер есть, а файла нет или он повреждён – отдельная ошибка. Кластера нет, а
198
+ * файл повреждён (обрыв первой установки) – пароль создаётся заново.
199
+ */
200
+ function ensurePassword(secretsDir, clusterExists) {
201
+ const file = path.join(secretsDir, 'pg.pw');
202
+ if (fs.existsSync(file)) {
203
+ const value = fs.readFileSync(file, 'utf8').split(/\r?\n/)[0].trim();
204
+ if (/^[A-Za-z0-9_-]{16,}$/.test(value)) {
205
+ restrictToUser(file);
206
+ return { file, password: value, created: false };
207
+ }
208
+ if (clusterExists) throw new StandError(`Файл пароля базы ${file} повреждён, а кластер на месте: к базе не подключиться.`);
209
+ fs.rmSync(file, { force: true });
210
+ } else if (clusterExists) {
211
+ throw new StandError(`Кластер базы на месте, а файла пароля ${file} нет: без него к базе не подключиться. Верните файл ` +
212
+ 'из копии служебной папки или начните с новой базы ключом --new-database (прежняя база останется в pg/backups).');
213
+ }
214
+ fs.mkdirSync(secretsDir, { recursive: true, mode: 0o700 });
215
+ restrictToUser(secretsDir);
216
+ const password = crypto.randomBytes(24).toString('base64url');
217
+ fsx.writeSecret(file, `${password}\n`, restrictToUser);
218
+ return { file, password, created: true };
219
+ }
220
+
221
+ /** Файл пароля читается: формат верен. Не бросает – для решения, можно ли начать заново. */
222
+ function passwordReadable(secretsDir) {
223
+ try {
224
+ return /^[A-Za-z0-9_-]{16,}$/.test(fs.readFileSync(path.join(secretsDir, 'pg.pw'), 'utf8').split(/\r?\n/)[0].trim());
225
+ } catch {
226
+ return false;
227
+ }
228
+ }
229
+
230
+ /**
231
+ * На Windows mode 0600 не действует, а папка может наследовать чтение для группы Users (ревью сборки А, В11): у папки
232
+ * секретов наследование снимается, полный доступ – только текущему пользователю. Не вышло – отказ до записи пароля.
233
+ */
234
+ function restrictToUser(target, platform = process.platform) {
235
+ if (platform !== 'win32') {
236
+ try { fs.chmodSync(target, fs.statSync(target).isDirectory() ? 0o700 : 0o600); } catch { /* проверка ниже */ }
237
+ const mode = fs.statSync(target).mode;
238
+ if (mode & 0o077) {
239
+ throw new StandError(`Права ${target} не ограничить владельцем (сейчас ${(mode & 0o777).toString(8)}): файл принадлежит ` +
240
+ 'другому пользователю? Исправьте владельца или права и запустите стенд снова.');
241
+ }
242
+ return;
243
+ }
244
+ // точный список доступа: защищён от наследования и содержит только текущего пользователя (ревью, круг 2)
245
+ const script = [
246
+ '$ErrorActionPreference = "Stop"',
247
+ '$item = Get-Item -LiteralPath $env:LT_TARGET -Force',
248
+ '$acl = $item.GetAccessControl()',
249
+ '$acl.SetAccessRuleProtection($true, $false)',
250
+ 'foreach ($rule in @($acl.Access)) { [void]$acl.RemoveAccessRuleAll($rule) }',
251
+ '$me = [System.Security.Principal.WindowsIdentity]::GetCurrent().User',
252
+ '$flags = if ($item.PSIsContainer) { "ContainerInherit, ObjectInherit" } else { "None" }',
253
+ '$acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($me, "FullControl", $flags, "None", "Allow")))',
254
+ '$item.SetAccessControl($acl)',
255
+ '$left = @((Get-Item -LiteralPath $env:LT_TARGET -Force).GetAccessControl().Access | Where-Object { $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]) -ne $me })',
256
+ 'if ($left.Count) { exit 3 }',
257
+ ].join('; ');
258
+ const run = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script],
259
+ { windowsHide: true, encoding: 'latin1', timeout: 60000, env: { ...process.env, LT_TARGET: target } });
260
+ if (run.status !== 0) {
261
+ throw new StandError(`Не удалось закрыть ${target} от других пользователей (код ${run.status}). Укажите служебную папку в ` +
262
+ 'своём профиле ключом --home.');
263
+ }
264
+ }
265
+
266
+ /** Каталог кластера пригоден: все обязательные файлы есть, мажорная версия совпадает с бинарниками. */
267
+ function checkCluster(dataDir) {
268
+ // обязательные файлы – обычные файлы, читаются; pg_control – не короче своей структуры (296 байт): обнулённая или
269
+ // усечённая копия не ставится на место рабочей базы (ревью круга 7)
270
+ const bad = CLUSTER_FILES.filter((name) => {
271
+ try {
272
+ const st = fs.statSync(path.join(dataDir, name));
273
+ if (!st.isFile()) return true;
274
+ fs.closeSync(fs.openSync(path.join(dataDir, name), 'r'));
275
+ return name === path.join('global', 'pg_control') && st.size < 296;
276
+ } catch {
277
+ return true;
278
+ }
279
+ });
280
+ if (bad.length) {
281
+ throw new StandError(`Каталог базы ${dataDir} неполный или повреждён (${bad.join(', ')}). Он не удаляется автоматически; ` +
282
+ 'перенесите его в сторону и запустите стенд с ключом --new-database.');
283
+ }
284
+ const major = fs.readFileSync(path.join(dataDir, 'PG_VERSION'), 'utf8').trim();
285
+ if (major !== PG_MAJOR) {
286
+ throw new StandError(`Каталог базы ${dataDir} создан PostgreSQL ${major}, а в стенде – ${PG_RELEASE}. Обновления ` +
287
+ 'мажорной версии в стенде нет: запустите версию стенда, которая создала базу.');
288
+ }
289
+ }
290
+
291
+ function confText(port) {
292
+ return ['# Файл пишет учебный стенд перед каждым запуском сервера: правки вручную пропадут.',
293
+ "listen_addresses = '127.0.0.1'",
294
+ `port = ${Number(port)}`,
295
+ '# журнал без данных: ни текста ошибочных запросов, ни DETAIL и CONTEXT (раздел 3.4 плана стенда)',
296
+ 'log_min_messages = log',
297
+ 'log_min_error_statement = panic',
298
+ 'log_error_verbosity = terse',
299
+ 'log_statement = none',
300
+ 'log_min_duration_statement = -1',
301
+ ''].join('\n');
302
+ }
303
+
304
+ /** Перед каждым запуском: local-triage.conf переписывается, строка include в postgresql.conf – одна. */
305
+ function writeConf(dataDir, port) {
306
+ const conf = path.join(dataDir, 'postgresql.conf');
307
+ const text = fs.readFileSync(conf, 'utf8');
308
+ if (!text.split(/\r?\n/).some((line) => line.trim() === INCLUDE_LINE)) {
309
+ fs.appendFileSync(conf, `${text.endsWith('\n') ? '' : '\n'}${INCLUDE_LINE}\n`);
310
+ }
311
+ const tmp = path.join(dataDir, `${CONF_NAME}.tmp`);
312
+ fs.writeFileSync(tmp, confText(port));
313
+ fsx.renameSync(tmp, path.join(dataDir, CONF_NAME));
314
+ }
315
+
316
+ /** Пока сервер остановлен: postgres.log – в файл с датой, файлы старше 14 дней удаляются. */
317
+ function rotateLog(logsDir, now = new Date()) {
318
+ fs.mkdirSync(logsDir, { recursive: true });
319
+ const current = path.join(logsDir, 'postgres.log');
320
+ if (fs.existsSync(current)) {
321
+ const stamp = now.toISOString().replace(/[:T]/g, '-').slice(0, 19);
322
+ try {
323
+ fs.renameSync(current, path.join(logsDir, `postgres-${stamp}.log`));
324
+ } catch (error) {
325
+ // журнал держит другая программа: сервер пишет в новый файл, прежний не трогается
326
+ if (!fsx.BUSY.has(error.code)) throw error;
327
+ return path.join(logsDir, `postgres-${stamp}-run.log`);
328
+ }
329
+ }
330
+ pruneLogs(logsDir, now);
331
+ return current;
332
+ }
333
+
334
+ function pruneLogs(logsDir, now = new Date()) {
335
+ const edge = now.getTime() - LOG_KEEP_DAYS * 86400000;
336
+ for (const name of fs.readdirSync(logsDir)) {
337
+ // только свои журналы по имени: чужие *.log в папке logs не трогаются (проверка агентами, круг 7)
338
+ if (!/^(?:supervisor|app|initdb|postgres)-[\w.-]+\.log$/.test(name)) continue;
339
+ const file = path.join(logsDir, name);
340
+ try {
341
+ if (fs.statSync(file).mtimeMs < edge) fs.unlinkSync(file);
342
+ } catch { /* файл занят – удалится в следующий раз */ }
343
+ }
344
+ }
345
+
346
+ module.exports = {
347
+ PG_MAJOR, PG_RELEASE, PACKAGE_VERSION, PLATFORM_PACKAGES, CONF_NAME, INCLUDE_LINE, platformPackage, nativeDir, exe,
348
+ initdbArgs, syncOnlyArgs, startArgs, statusArgs, stopArgs, installBinaries, ensurePassword, passwordReadable, restrictToUser,
349
+ checkCluster, checkMajor, confText, binariesComplete,
350
+ writeConf, rotateLog, pruneLogs,
351
+ };
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+ // Запуск дочерних процессов стенда: всегда без окна консоли (windowsHide), с пределом времени.
3
+
4
+ const { spawn } = require('node:child_process');
5
+
6
+ const KEEP = 200000; // сколько знаков вывода хранить: хвост для сообщений об ошибке
7
+ // Запущенные и ещё не завершённые процессы: при остановке держатель дожидается их или снимает (ревью сборки А, В4)
8
+ const ACTIVE = new Set();
9
+
10
+ /** Дождаться завершения запущенных процессов (ms), затем снять оставшиеся вместе с дочерними. */
11
+ async function settle(ms = 60000) {
12
+ const deadline = Date.now() + ms;
13
+ while (ACTIVE.size && Date.now() < deadline) await new Promise((r) => setTimeout(r, 200));
14
+ for (const child of ACTIVE) {
15
+ if (process.platform === 'win32') spawn('taskkill.exe', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true, stdio: 'ignore' });
16
+ else stop(child, 'SIGKILL');
17
+ }
18
+ const after = Date.now() + 10000;
19
+ while (ACTIVE.size && Date.now() < after) await new Promise((r) => setTimeout(r, 200));
20
+ }
21
+
22
+ /** Сигнал процессу, а запущенному группой (POSIX) – всей группе: конвейер curl | sh не переживает отмену. */
23
+ function stop(child, signal = 'SIGTERM') {
24
+ try {
25
+ if (child.group) process.kill(-child.pid, signal);
26
+ else child.kill(signal);
27
+ } catch { /* уже вышел */ }
28
+ }
29
+
30
+ function groupAlive(child) {
31
+ try {
32
+ process.kill(-child.pid, 0);
33
+ return true;
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Запускает процесс и ждёт его завершения. stdio: pipe – вывод возвращается; ignore – никаких унаследованных
41
+ * дескрипторов (pg_ctl start: его postgres живёт дольше pg_ctl и держал бы канал открытым); fd – вывод в открытый файл.
42
+ * Ответ: {code, signal, stdout, stderr, timedOut, error}; code -1 – процесс не запустился.
43
+ */
44
+ function run(file, args, { env, cwd, timeoutMs = 0, input = null, stdio = 'pipe', fd = null, group = false } = {}) {
45
+ return new Promise((resolve) => {
46
+ let mode;
47
+ if (stdio === 'ignore') mode = 'ignore';
48
+ else if (fd !== null) mode = ['ignore', fd, fd];
49
+ else mode = ['pipe', 'pipe', 'pipe'];
50
+ let child;
51
+ try {
52
+ const own = group && process.platform !== 'win32';
53
+ child = spawn(file, args, { env, cwd, windowsHide: true, stdio: mode, detached: own });
54
+ child.group = own;
55
+ } catch (error) {
56
+ resolve({ code: -1, signal: null, stdout: '', stderr: '', timedOut: false, error });
57
+ return;
58
+ }
59
+ let stdout = '';
60
+ let stderr = '';
61
+ let timedOut = false;
62
+ let done = false;
63
+ ACTIVE.add(child);
64
+ child.once('exit', () => {
65
+ if (!child.group) { ACTIVE.delete(child); return; }
66
+ // группа: держатель ждёт, пока выйдут и потомки (settle видит её до конца)
67
+ const poll = setInterval(() => {
68
+ if (!groupAlive(child)) { clearInterval(poll); ACTIVE.delete(child); }
69
+ }, 200);
70
+ });
71
+ child.once('error', () => ACTIVE.delete(child));
72
+ const finish = (code, signal, error = null) => {
73
+ if (done) return;
74
+ done = true;
75
+ if (!child.group) ACTIVE.delete(child);
76
+ if (timer) clearTimeout(timer);
77
+ resolve({ code: code === null ? -1 : code, signal, stdout, stderr, timedOut, error });
78
+ };
79
+ const timer = timeoutMs ? setTimeout(() => {
80
+ timedOut = true;
81
+ // на Windows – всё дерево служебной команды, пока жив её корень (ревью круга 6)
82
+ if (process.platform === 'win32') spawn('taskkill.exe', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true, stdio: 'ignore' });
83
+ else stop(child);
84
+ }, timeoutMs) : null;
85
+ if (child.stdout) child.stdout.on('data', (d) => { stdout = (stdout + d).slice(-KEEP); });
86
+ if (child.stderr) child.stderr.on('data', (d) => { stderr = (stderr + d).slice(-KEEP); });
87
+ child.on('error', (error) => finish(-1, null, error));
88
+ // с каналами – по закрытию каналов (весь вывод прочитан), без них – по завершению процесса
89
+ child.on(Array.isArray(mode) && mode[1] === 'pipe' ? 'close' : 'exit', (code, signal) => finish(code, signal));
90
+ if (child.stdin) {
91
+ child.stdin.on('error', () => {});
92
+ child.stdin.end(input === null ? undefined : input);
93
+ }
94
+ });
95
+ }
96
+
97
+ function tail(text, lines = 20) {
98
+ return String(text || '').trimEnd().split(/\r?\n/).slice(-lines).join('\n');
99
+ }
100
+
101
+ module.exports = { run, tail, settle, ACTIVE };
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+ // Python стенда (раздел 3.3 плана): свой uv или uv в PATH; иначе системный Python 3.12 (venv и
3
+ // pip); иначе официальный установщик uv закреплённой версии в служебную папку, без правки PATH. Пути – абсолютные,
4
+ // зависимости – по хешам (npm/requirements.txt). Отметка installed.json – только после проверки импорта.
5
+
6
+ const crypto = require('node:crypto');
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const fsx = require('./fsx');
10
+
11
+ const { StandError } = require('./paths');
12
+ const { run, tail } = require('./proc');
13
+ const { writeJsonAtomic, readJson } = require('./stand');
14
+
15
+ const UV_VERSION = '0.11.19';
16
+ const PYTHON = '3.12';
17
+ const IMPORT_CHECK = 'import fastapi, uvicorn, psycopg, psycopg_pool, openpyxl, jinja2, multipart, pydantic';
18
+
19
+ function sha256File(file) {
20
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
21
+ }
22
+
23
+ function venvPython(venv, platform = process.platform) {
24
+ return platform === 'win32' ? path.join(venv, 'Scripts', 'python.exe') : path.join(venv, 'bin', 'python');
25
+ }
26
+
27
+ async function findUv(home, env) {
28
+ const own = path.join(home, 'uv', process.platform === 'win32' ? 'uv.exe' : 'uv');
29
+ for (const candidate of [own, 'uv']) {
30
+ const probe = await run(candidate, ['--version'], { env, timeoutMs: 30000 });
31
+ if (probe.code === 0) return candidate;
32
+ }
33
+ return '';
34
+ }
35
+
36
+ async function findSystemPython(env) {
37
+ const tries = process.platform === 'win32' ? [['py', ['-3.12']], ['python3.12', []], ['python', []]]
38
+ : [['python3.12', []], ['python3', []]];
39
+ for (const [file, pre] of tries) {
40
+ // путь – JSON с экранированием не-ASCII (кодовая страница консоли его не искажает); ensurepip – venv с pip создастся
41
+ const probe = await run(file, [...pre, '-E', '-s', '-X', 'utf8', '-c',
42
+ 'import sys,json,venv,ensurepip;assert sys.version_info[:2]==(3,12);print(json.dumps(sys.executable))'],
43
+ { env, timeoutMs: 30000 });
44
+ if (probe.code === 0 && probe.stdout.trim()) {
45
+ try { return JSON.parse(probe.stdout.trim().split(/\r?\n/).pop()); } catch { /* следующий вариант */ }
46
+ }
47
+ }
48
+ return '';
49
+ }
50
+
51
+ async function installUv(home, env, say) {
52
+ const dir = path.join(home, 'uv');
53
+ fs.mkdirSync(dir, { recursive: true });
54
+ const installEnv = { ...env, UV_INSTALL_DIR: dir, UV_UNMANAGED_INSTALL: dir, UV_NO_MODIFY_PATH: '1' };
55
+ say(`Ставлю uv ${UV_VERSION} официальным установщиком в ${dir}…`);
56
+ const result = process.platform === 'win32'
57
+ ? await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command',
58
+ `irm https://astral.sh/uv/${UV_VERSION}/install.ps1 | iex`], { env: installEnv, timeoutMs: 600000 })
59
+ : await run('sh', ['-c', `curl -LsSf https://astral.sh/uv/${UV_VERSION}/install.sh | sh`],
60
+ { env: installEnv, timeoutMs: 600000, group: true });
61
+ const own = path.join(dir, process.platform === 'win32' ? 'uv.exe' : 'uv');
62
+ if (result.code !== 0 || !fs.existsSync(own)) {
63
+ throw new StandError(`uv не установился (код ${result.code}). ${tail(result.stderr || result.stdout, 8)}\nПоставьте Python ` +
64
+ '3.12 с python.org или uv вручную и запустите стенд снова.');
65
+ }
66
+ return own;
67
+ }
68
+
69
+ function failed(step, result) {
70
+ return new StandError(`${step}: код ${result.code}.\n${tail(result.stderr || result.stdout, 15)}`);
71
+ }
72
+
73
+ /**
74
+ * Окружение Python для версии стенда: <служебная>/<версия>/venv. Готовое (отметка совпадает с перечнем зависимостей
75
+ * и интерпретатор отвечает) не трогается. Ответ – путь к python.exe окружения.
76
+ */
77
+ async function ensurePython({ home, version, requirements, env, say, reinstall = false }) {
78
+ const base = path.join(home, version);
79
+ const venv = path.join(base, 'venv');
80
+ const python = venvPython(venv);
81
+ const marker = path.join(base, 'installed.json');
82
+ const wanted = sha256File(requirements);
83
+ const done = readJson(marker);
84
+ if (!reinstall && done && done.requirements_sha256 === wanted && fs.existsSync(python)) {
85
+ const ok = await run(python, ['-E', '-s', '-c', IMPORT_CHECK], { env, timeoutMs: 120000 });
86
+ if (ok.code === 0) return python;
87
+ }
88
+ fsx.rmSync(marker, { force: true });
89
+ fsx.rmSync(venv, { recursive: true, force: true });
90
+ fs.mkdirSync(base, { recursive: true });
91
+ let uv = await findUv(home, env);
92
+ let system = '';
93
+ if (!uv) system = await findSystemPython(env);
94
+ if (!uv && system) {
95
+ const viaSystem = await systemVenv(system, venv, python, requirements, env, say);
96
+ if (viaSystem.ok) return finish();
97
+ say(`${viaSystem.why} Перехожу к установке Python через uv…`);
98
+ fsx.rmSync(venv, { recursive: true, force: true });
99
+ system = '';
100
+ }
101
+ if (!uv) uv = await installUv(home, env, say);
102
+ {
103
+ say(`Готовлю Python ${PYTHON} (uv)…`);
104
+ const made = await run(uv, ['venv', venv, '--python', PYTHON, '--no-config'], { env, timeoutMs: 900000 });
105
+ if (made.code !== 0) throw failed('uv venv не создал окружение Python', made);
106
+ say('Ставлю зависимости приложения по хешам…');
107
+ const installed = await run(uv, ['pip', 'install', '--python', python, '--require-hashes', '--no-config', '-r', requirements],
108
+ { env, timeoutMs: 1800000 });
109
+ if (installed.code !== 0) throw failed('Зависимости не установились', installed);
110
+ }
111
+ return finish();
112
+
113
+ async function finish() {
114
+ const check = await run(python, ['-E', '-s', '-c', IMPORT_CHECK], { env, timeoutMs: 120000 });
115
+ if (check.code !== 0) throw failed('Окружение Python собрано, но модули не импортируются', check);
116
+ writeJsonAtomic(marker, { requirements_sha256: wanted, python: PYTHON, via: uv ? 'uv' : 'pip', at: new Date().toISOString() });
117
+ return python;
118
+ }
119
+ }
120
+
121
+ /** Окружение из системного Python 3.12: venv и pip по хешам. Отказ – {ok: false, why}, чтобы перейти к uv. */
122
+ async function systemVenv(system, venv, python, requirements, env, say) {
123
+ say(`Готовлю Python ${PYTHON} (системный, venv и pip)…`);
124
+ const made = await run(system, ['-E', '-s', '-m', 'venv', venv], { env, timeoutMs: 600000 });
125
+ if (made.code !== 0) return { ok: false, why: `Системный Python не создал окружение (код ${made.code}).` };
126
+ const index = env.PIP_INDEX_URL ? ['--index-url', env.PIP_INDEX_URL] : [];
127
+ const installed = await run(python, ['-E', '-s', '-m', 'pip', 'install', '--isolated', '--disable-pip-version-check',
128
+ '--no-input', ...index, '--require-hashes', '-r', requirements], { env, timeoutMs: 1800000 });
129
+ if (installed.code !== 0) throw failed('Зависимости не установились', installed); // сеть или хеши – uv тут не поможет
130
+ return { ok: true };
131
+ }
132
+
133
+ module.exports = { ensurePython, venvPython, UV_VERSION, PYTHON, IMPORT_CHECK };
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+ // stand.json – состояние стенда в служебной папке (раздел 3.2 плана): идентификатор, фаза установки базы, порты,
3
+ // папка кода, последняя успешная версия. Пароля и строк подключения в нём нет. Запись – временный файл, fsync,
4
+ // переименование.
5
+
6
+ const crypto = require('node:crypto');
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const fsx = require('./fsx');
10
+
11
+ const PHASES = ['none', 'db-creating', 'db-created', 'ready'];
12
+
13
+ function writeJsonAtomic(file, data) {
14
+ fs.mkdirSync(path.dirname(file), { recursive: true });
15
+ const tmp = `${file}.tmp-${process.pid}`;
16
+ const fd = fs.openSync(tmp, 'w');
17
+ try {
18
+ fsx.writeAll(fd, `${JSON.stringify(data, null, 1)}\n`);
19
+ fs.fsyncSync(fd);
20
+ } finally {
21
+ fs.closeSync(fd);
22
+ }
23
+ fsx.renameSync(tmp, file);
24
+ }
25
+
26
+ function readJson(file, fallback = null) {
27
+ try {
28
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
29
+ } catch {
30
+ return fallback;
31
+ }
32
+ }
33
+
34
+ function load(home) {
35
+ const file = path.join(home, 'stand.json');
36
+ const data = readJson(file);
37
+ if (data && typeof data === 'object' && PHASES.includes(data.phase)) return { file, data, existed: true };
38
+ return { file, data: { schema: 1, id: crypto.randomBytes(8).toString('hex'), phase: 'none' }, existed: false };
39
+ }
40
+
41
+ function save(state, changes = {}) {
42
+ Object.assign(state.data, changes, { updated_at: new Date().toISOString() });
43
+ writeJsonAtomic(state.file, state.data);
44
+ }
45
+
46
+ module.exports = { PHASES, load, save, readJson, writeJsonAtomic };