@animastor/installer 0.1.0

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 (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -0
  3. package/ai/install-manifests/audio/qwen-tts.json +445 -0
  4. package/ai/install-manifests/image/qwen-image.json +465 -0
  5. package/ai/install-manifests/video/ltx-2.3.json +892 -0
  6. package/package.json +42 -0
  7. package/src/installer/cli.js +1067 -0
  8. package/src/installer/compatibility-resolver.js +1287 -0
  9. package/src/installer/download-planner.js +172 -0
  10. package/src/installer/engine/comfyui.js +508 -0
  11. package/src/installer/engine/downloader.js +514 -0
  12. package/src/installer/engine/engine.js +1180 -0
  13. package/src/installer/engine/io.js +437 -0
  14. package/src/installer/engine/logger.js +75 -0
  15. package/src/installer/engine/nodes.js +146 -0
  16. package/src/installer/engine/prereq.js +399 -0
  17. package/src/installer/engine/probe.js +349 -0
  18. package/src/installer/engine/progress.js +350 -0
  19. package/src/installer/engine/state.js +170 -0
  20. package/src/installer/engine/term.js +298 -0
  21. package/src/installer/engine/worker.js +430 -0
  22. package/src/installer/engine/workflows.js +153 -0
  23. package/src/installer/index.js +40 -0
  24. package/src/installer/install-manifest.js +376 -0
  25. package/src/installer/install-plan.js +741 -0
  26. package/src/installer/management.js +489 -0
  27. package/src/installer/platform/deployment/docker.js +78 -0
  28. package/src/installer/platform/deployment/native.js +36 -0
  29. package/src/installer/platform/index.js +165 -0
  30. package/src/installer/platform/linux.js +341 -0
  31. package/src/installer/platform/windows.js +360 -0
  32. package/src/installer/safety-rules.js +156 -0
  33. package/src/installer/setup-contract.js +1401 -0
  34. package/src/installer/uninstaller.js +572 -0
  35. package/src/installer/verification-report.js +220 -0
  36. package/src/installer/worker-bundle-source.js +64 -0
  37. package/src/installer/workflow-artifacts.js +152 -0
@@ -0,0 +1,360 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Windows platform adapter — Private Worker Installer (cross-platform prep).
5
+ *
6
+ * STATUS: architectural preview. The adapter defines every platform
7
+ * touchpoint needed to run the universal installer on Windows and the parts
8
+ * that can be implemented safely without a Windows test machine are
9
+ * implemented (paths, venv layout, tool wrappers, remediation commands,
10
+ * home/env resolution, daemon pid marker). The process-management commands
11
+ * are implemented against standard Windows tooling (PowerShell CIM,
12
+ * tasklist) but are NOT yet production-validated — the adapter is marked
13
+ * productionReady:false and the CLI prints an explicit preview notice.
14
+ *
15
+ * Design notes (why this differs from the Linux adapter):
16
+ * - Windows has no /proc: process discovery cannot cwd-verify. The managed
17
+ * worker is instead identified by a pid marker file written next to the
18
+ * bundle (worker.pid) at start time — a foreign worker in another
19
+ * directory never has our marker, which preserves the "never touch
20
+ * foreign processes" invariant.
21
+ * - A managed ComfyUI process runs on the venv python whose ExecutablePath
22
+ * lives under the installation root — that is the ownership marker.
23
+ * - venv layout is Scripts\python.exe (not bin/python).
24
+ * - Management tools are .cmd batch wrappers (cmd.exe), not shell scripts.
25
+ * - Grace sleeps use ping (timeout.exe refuses redirected input).
26
+ * - The uid/ownership guard is a POSIX concept; Windows returns null uids
27
+ * and the guard passes (path ACLs are a later concern).
28
+ */
29
+
30
+ const path = require('path');
31
+
32
+ const NAME = 'windows';
33
+ const PID_MARKER_FILE = 'worker.pid';
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // Paths (true Windows paths, independent of the host the adapter runs on —
37
+ // the adapter must produce backslash paths even when unit-tested on Linux)
38
+ // ---------------------------------------------------------------------------
39
+
40
+ /** Join path segments with Windows separators (backslash), never POSIX. */
41
+ function winJoin(...parts) {
42
+ return parts
43
+ .filter((p) => p != null && String(p) !== '')
44
+ .map((p, i) => (i === 0 ? String(p) : String(p).replace(/^[\\/]+/, '')))
45
+ .join('\\')
46
+ .replace(/[\\/]+/g, '\\');
47
+ }
48
+
49
+ /** Default ComfyUI root: %USERPROFILE%\ComfyUI. */
50
+ function defaultRoot(home) {
51
+ return winJoin(home || 'C:\\Users\\Public', 'ComfyUI');
52
+ }
53
+
54
+ /** Default worker bundle dir: %USERPROFILE%\animastor\worker. */
55
+ function defaultWorkerDir(home) {
56
+ return winJoin(home || 'C:\\Users\\Public', 'animastor', 'worker');
57
+ }
58
+
59
+ /** Home directory env var on Windows. */
60
+ const HOME_ENV = 'USERPROFILE';
61
+
62
+ /** Python interpreter inside a venv (Windows layout). */
63
+ function venvPythonBin(venvDir) {
64
+ return winJoin(venvDir, 'Scripts', 'python.exe');
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Process management (PowerShell CIM / pid marker)
69
+ // ---------------------------------------------------------------------------
70
+
71
+ /** Normalize a Windows path for case/slash-insensitive comparison. */
72
+ function normWinPath(p) {
73
+ return String(p || '').replace(/\//g, '\\').toLowerCase();
74
+ }
75
+
76
+ function ps(script) {
77
+ return { cmd: 'powershell', args: ['-NoProfile', '-NonInteractive', '-Command', script] };
78
+ }
79
+
80
+ /** Read the pid marker file written by onWorkerSpawned, or null. */
81
+ function readPidMarker(io, workerDir) {
82
+ try {
83
+ const p = winJoin(workerDir, PID_MARKER_FILE);
84
+ if (!io.fs.existsSync(p)) return null;
85
+ const parsed = JSON.parse(io.fs.readFileSync(p, 'utf8'));
86
+ return parsed && Number.isFinite(parsed.pid) ? parsed : null;
87
+ } catch (_) {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ /** Is the pid alive? (tasklist filter — present on every Windows install) */
93
+ function pidAlive(io, pid) {
94
+ const r = io.exec('tasklist', ['/FO', 'CSV', '/NH', '/FI', `PID eq ${pid}`]);
95
+ if (!r || r.code !== 0) return false;
96
+ return new RegExp(`["]${pid}["]`).test(String(r.stdout));
97
+ }
98
+
99
+ /**
100
+ * Post-spawn bookkeeping: Windows has no /proc, so the managed worker is
101
+ * identified by a pid marker written next to the bundle at start time.
102
+ * Best effort — discovery simply finds nothing when the write failed.
103
+ */
104
+ function onWorkerSpawned(io, { workerDir, pid }) {
105
+ try {
106
+ io.fs.writeFileSync(
107
+ winJoin(workerDir, PID_MARKER_FILE),
108
+ JSON.stringify({ pid, started_at: io.now ? io.now() : Date.now() }),
109
+ );
110
+ } catch (_) { /* best effort */ }
111
+ }
112
+
113
+ /**
114
+ * PIDs of worker processes for THIS workerDir. Windows has no cwd to verify,
115
+ * so the managed marker is the pid file written when the installer started
116
+ * the worker; the pid must still be alive AND running node on worker.cjs.
117
+ * @returns {number[]}
118
+ */
119
+ function findPidsByCmdlineAndCwd(io, { cwd, cmdPattern = 'worker\\.cjs' }) {
120
+ const marker = readPidMarker(io, cwd);
121
+ if (!marker) return [];
122
+ if (!pidAlive(io, marker.pid)) return [];
123
+ const q = ps(`(Get-CimInstance Win32_Process -Filter "ProcessId=${marker.pid}").CommandLine`);
124
+ const r = io.exec(q.cmd, q.args);
125
+ const cmdline = r && r.code === 0 ? String(r.stdout).trim() : '';
126
+ if (!cmdline || !new RegExp(cmdPattern).test(cmdline)) return [];
127
+ return [marker.pid];
128
+ }
129
+
130
+ /** cwd of a pid — not resolvable on Windows (no /proc). Always null. */
131
+ function readProcessCwd(_io, _pid) {
132
+ return null;
133
+ }
134
+
135
+ /** Command line of a pid via PowerShell CIM, or null. */
136
+ function readProcessCmdline(io, pid) {
137
+ const q = ps(`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`);
138
+ const r = io.exec(q.cmd, q.args);
139
+ if (!r || r.code !== 0 || !String(r.stdout).trim()) return null;
140
+ return String(r.stdout).trim().split(/\s+/);
141
+ }
142
+
143
+ /**
144
+ * Process start time. Windows has no /proc mtime; the pid marker written at
145
+ * spawn time is the source of truth (same role as .env-newer detection).
146
+ */
147
+ function processStartMs(io, pid) {
148
+ return null; // caller falls back to the marker via workerStartMarker
149
+ }
150
+
151
+ /**
152
+ * Marker of when the managed worker started (replaces /proc mtime check).
153
+ * Returns ms or null when no marker exists.
154
+ */
155
+ function workerStartMarkerMs(io, workerDir) {
156
+ const marker = readPidMarker(io, workerDir);
157
+ return marker && Number.isFinite(marker.started_at) ? marker.started_at : null;
158
+ }
159
+
160
+ /** Uid owning a process — POSIX concept, null on Windows. */
161
+ function pidUid(_io, _pid) {
162
+ return null;
163
+ }
164
+
165
+ /**
166
+ * PIDs of ComfyUI processes managed by THIS installation root: python
167
+ * processes running main.py whose ExecutablePath is the venv python under
168
+ * `root` (the venv lives inside the root — a strong managed marker), and by
169
+ * default on `port`.
170
+ */
171
+ function findComfyUIPids(io, { root, port = null }) {
172
+ const script = 'Get-CimInstance Win32_Process -Filter "Name=\'python.exe\'" '
173
+ + '| Select-Object ProcessId,ExecutablePath,CommandLine '
174
+ + '| ConvertTo-Json -Compress';
175
+ const q = ps(script);
176
+ const r = io.exec(q.cmd, q.args);
177
+ if (!r || r.code !== 0 || !String(r.stdout).trim()) return [];
178
+ let items = [];
179
+ try {
180
+ const parsed = JSON.parse(String(r.stdout).trim());
181
+ items = Array.isArray(parsed) ? parsed : [parsed];
182
+ } catch (_) { return []; }
183
+ const rootNorm = normWinPath(root);
184
+ const out = [];
185
+ for (const it of items) {
186
+ if (!it || !it.ProcessId) continue;
187
+ const exe = normWinPath(it.ExecutablePath);
188
+ if (!exe || !exe.startsWith(rootNorm)) continue; // foreign python
189
+ const cmdline = String(it.CommandLine || '');
190
+ if (!/(^|[\\\/])main\.py(["']|\s|$)/.test(cmdline)) continue;
191
+ if (port != null) {
192
+ const m = /--port\s+(\d+)/.exec(cmdline);
193
+ if ((m ? Number(m[1]) : 8188) !== Number(port)) continue;
194
+ }
195
+ out.push(Number(it.ProcessId));
196
+ }
197
+ return out;
198
+ }
199
+
200
+ /**
201
+ * Process discovery by cwd prefix — not supported on Windows (no /proc).
202
+ * The uninstaller reports this explicitly instead of pretending to scan.
203
+ */
204
+ function findPidsByCwdPrefix(_io, _paths) {
205
+ return [];
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // Shell command fragments
210
+ // ---------------------------------------------------------------------------
211
+
212
+ /**
213
+ * Grace sleep. `timeout /t` refuses redirected input, so the standard trick
214
+ * is pinging loopback N+1 times (≈ N seconds).
215
+ */
216
+ function sleepCommand(seconds) {
217
+ const n = Math.max(1, Math.ceil(seconds));
218
+ return { cmd: 'ping', args: ['-n', String(n + 1), '127.0.0.1'] };
219
+ }
220
+
221
+ /** Kill a pid: taskkill /PID (graceful-then-force is handled by the engine). */
222
+ function killCommand(pid) {
223
+ return { cmd: 'taskkill', args: ['/PID', String(pid)] };
224
+ }
225
+
226
+ /**
227
+ * Daemon liveness check. Linux greps `ps -o args=` for the marker; on
228
+ * Windows the pid marker + tasklist is the check (see checkDaemonAlive).
229
+ */
230
+ function psCheckCommand(_pid) {
231
+ return { cmd: 'tasklist', args: ['/FO', 'CSV', '/NH', '/FI', 'PID eq 0'] }; // unused
232
+ }
233
+
234
+ /** Alive check used by the engine after spawning the daemon. */
235
+ function checkDaemonAlive(io, { pid, workerDir }) {
236
+ if (!pidAlive(io, pid)) return false;
237
+ const marker = readPidMarker(io, workerDir);
238
+ return !!marker && marker.pid === pid;
239
+ }
240
+
241
+ // ---------------------------------------------------------------------------
242
+ // Host prerequisites / remediation
243
+ // ---------------------------------------------------------------------------
244
+
245
+ /** Windows package remediation hint (winget preferred, choco fallback). */
246
+ function hostPackageCommand(pkg) {
247
+ return `winget install --id ${pkg} (or: choco install ${pkg})`;
248
+ }
249
+
250
+ function hostPackagesCommand(pkgs) {
251
+ return `winget install ${pkgs} (or: choco install ${pkgs})`;
252
+ }
253
+
254
+ /**
255
+ * C build-tool prerequisites — on Windows the supported path is the Visual
256
+ * Studio Build Tools. Not yet validated; reported as an explicit limitation
257
+ * instead of probing the Linux package set.
258
+ */
259
+ function checkBuildPrerequisites(_io, _opts = {}) {
260
+ return {
261
+ ok: false,
262
+ missing: [],
263
+ remediation: { package: 'Microsoft Visual Studio Build Tools', command: 'winget install Microsoft.VisualStudio.2022.BuildTools' },
264
+ message: 'Windows build-tool detection is not implemented yet (preview platform). '
265
+ + 'Python packages with native extensions require the Visual Studio Build Tools.',
266
+ };
267
+ }
268
+
269
+ // ---------------------------------------------------------------------------
270
+ // Management tools (cmd.exe batch wrappers)
271
+ // ---------------------------------------------------------------------------
272
+
273
+ /** Tool script filename: cmd.exe batch extension (.sh → .cmd). */
274
+ function toolScriptName(fileName) {
275
+ return String(fileName).replace(/\.sh$/i, '.cmd');
276
+ }
277
+
278
+ function cmdQuote(s) {
279
+ return `"${String(s).replace(/"/g, '')}"`;
280
+ }
281
+
282
+ /** Render one management-tool wrapper (cmd.exe shim around the CLI). */
283
+ function renderToolScript({ command, nodePath, cliPath, statePath, root, workerDir }) {
284
+ return [
285
+ '@echo off',
286
+ 'rem Animastor management tool — generated by animastor-installer.',
287
+ 'rem Do not edit: re-run the installer to refresh (paths are recorded at install time).',
288
+ `${cmdQuote(nodePath)} ${cmdQuote(cliPath)} ${command} --state ${cmdQuote(statePath)} --root ${cmdQuote(root || '')} --worker-dir ${cmdQuote(workerDir || '')} %*`,
289
+ ].join('\r\n') + '\r\n';
290
+ }
291
+
292
+ /** Mode bits for generated tools (ignored on Windows, kept for parity). */
293
+ const TOOL_SCRIPT_MODE = 0o755;
294
+
295
+ // ---------------------------------------------------------------------------
296
+ // GPU probing (platform-specific parts)
297
+ // ---------------------------------------------------------------------------
298
+
299
+ /**
300
+ * AMD GPU detection on Windows — sysfs/rocm-smi do not exist. Detection via
301
+ * wmic path win32_VideoController. Preview-grade; never guessed.
302
+ */
303
+ function probeAmdGpu(io) {
304
+ const r = io.exec('wmic', ['path', 'win32_VideoController', 'get', 'name', '/format:list']);
305
+ if (!r || r.code !== 0) return null;
306
+ const m = /Name=(.*(Radeon|AMD).*)/i.exec(String(r.stdout));
307
+ if (m && m[1].trim()) {
308
+ return { vendor: 'amd', name: m[1].trim(), vram_mib: null, driver_version: null, detection: 'wmic' };
309
+ }
310
+ return null;
311
+ }
312
+
313
+ // ---------------------------------------------------------------------------
314
+ // Ownership guard
315
+ // ---------------------------------------------------------------------------
316
+
317
+ /** POSIX uid guard is not applicable on Windows. */
318
+ const UID_GUARD = false;
319
+
320
+ module.exports = {
321
+ name: NAME,
322
+ displayName: 'Windows (native)',
323
+ productionReady: false, // architectural preview — not production-validated
324
+ previewNotice: 'Windows support is an architectural preview: paths, venv layout and tool wrappers are implemented, process management is not yet production-validated.',
325
+
326
+ HOME_ENV,
327
+ UID_GUARD,
328
+ TOOL_SCRIPT_MODE,
329
+ PID_MARKER_FILE,
330
+
331
+ defaultRoot,
332
+ defaultWorkerDir,
333
+ venvPythonBin,
334
+
335
+ findPidsByCmdlineAndCwd,
336
+ readProcessCwd,
337
+ readProcessCmdline,
338
+ processStartMs,
339
+ workerStartMarkerMs,
340
+ pidUid,
341
+ findComfyUIPids,
342
+ findPidsByCwdPrefix,
343
+ readPidMarker,
344
+ pidAlive,
345
+ checkDaemonAlive,
346
+ onWorkerSpawned,
347
+
348
+ sleepCommand,
349
+ killCommand,
350
+ psCheckCommand,
351
+
352
+ hostPackageCommand,
353
+ hostPackagesCommand,
354
+ checkBuildPrerequisites,
355
+
356
+ toolScriptName,
357
+ renderToolScript,
358
+
359
+ probeAmdGpu,
360
+ };
@@ -0,0 +1,156 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Safety Rules — Private Worker Installer Phase 1.5.
5
+ *
6
+ * Declarative, pure safety model for the (future) interactive installer.
7
+ * The installer's write engine must consult these rules BEFORE any mutation;
8
+ * anything listed in NEVER_AUTOMATIC is forbidden without an explicit,
9
+ * recorded user confirmation — and some operations are forbidden outright.
10
+ *
11
+ * Companion invariant: the compatibility resolver never emits destructive
12
+ * actions (see compatibility-resolver.js ACTIONS). These rules extend that
13
+ * invariant to the execution layer.
14
+ */
15
+
16
+ /**
17
+ * Operations the installer must NEVER perform automatically.
18
+ * Each requires an explicit interactive user confirmation; operations marked
19
+ * `forbidden: true` must not be performed by the installer at all in v1.
20
+ */
21
+ const NEVER_AUTOMATIC = Object.freeze([
22
+ { op: 'delete_model', forbidden: true, description: 'delete user models' },
23
+ { op: 'delete_custom_node', forbidden: true, description: 'delete user custom nodes' },
24
+ { op: 'delete_workflow', forbidden: true, description: 'delete user workflows' },
25
+ { op: 'replace_user_workflow', forbidden: true, description: 'overwrite/replace a user workflow (a fresh baseline copy goes to a DISTINCT path)' },
26
+ { op: 'downgrade_comfyui', forbidden: false, description: 'downgrade ComfyUI (only with explicit consent, checkpoint before)' },
27
+ { op: 'downgrade_torch', forbidden: true, description: "downgrade/replace the user's torch in existing mode" },
28
+ { op: 'change_cuda', forbidden: true, description: 'install/change CUDA or the NVIDIA driver' },
29
+ { op: 'destroy_python_environment', forbidden: true, description: "recreate/destroy the user's existing Python environment" },
30
+ { op: 'overwrite_env_token', forbidden: true, description: 'overwrite an existing valid Worker Key in .env (merge semantics only)' },
31
+ { op: 'update_comfyui', forbidden: false, description: 'update an existing ComfyUI to the recommended version (only with explicit consent)' },
32
+ { op: 'checkout_custom_node', forbidden: false, description: 'git-safe checkout of an existing custom node to the pinned commit (only with explicit consent)' },
33
+ ]);
34
+
35
+ const NEVER_AUTOMATIC_OPS = Object.freeze(NEVER_AUTOMATIC.map((r) => r.op));
36
+
37
+ /**
38
+ * Secret environment variable names (mirrors scripts/animastor-runtime-audit.sh
39
+ * SECRET_NAMES). Values of these keys must never appear in logs, reports,
40
+ * plan renderings, argv, or state files.
41
+ */
42
+ const SECRET_NAMES = Object.freeze([
43
+ 'ANIMASTOR_WORKER_TOKEN',
44
+ 'POSTGRES_PASSWORD',
45
+ 'HF_TOKEN',
46
+ 'HUGGINGFACE_HUB_TOKEN',
47
+ 'WORKSPACE_SECRET_KEY',
48
+ 'GPU_HUB_API_KEY',
49
+ 'OPENROUTER_API_KEY',
50
+ ]);
51
+
52
+ const SECRET_NAME_PATTERN = /(^|_)(TOKEN|SECRET|PASSWORD|API_KEY)$/i;
53
+
54
+ function isSecretName(name) {
55
+ const n = String(name || '').toUpperCase();
56
+ return SECRET_NAMES.includes(n) || SECRET_NAME_PATTERN.test(n);
57
+ }
58
+
59
+ /**
60
+ * Redact secret values from arbitrary text (defense in depth for logging).
61
+ * `secrets` is a list of concrete values to scrub; additionally any
62
+ * KEY=value style assignment of a secret-looking name is masked.
63
+ */
64
+ function redactSecrets(text, secrets = []) {
65
+ let out = String(text);
66
+ for (const s of secrets) {
67
+ if (s) out = out.split(s).join('<REDACTED>');
68
+ }
69
+ out = out.replace(/^([ \t]*[A-Za-z_][A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY)[A-Za-z0-9_]*\s*=\s*)(?!<REDACTED>).*$/gim, '$1<REDACTED>');
70
+ return out;
71
+ }
72
+
73
+ /**
74
+ * Classify a resolver entry into execution safety attributes.
75
+ * Returns { destructive, requires_confirmation, forbidden }.
76
+ *
77
+ * - install of a NEW file (missing entry) is non-destructive but is still
78
+ * part of the plan the user confirms before anything runs;
79
+ * - review entries always require a user decision;
80
+ * - configure requires interactive input (Worker Key: hidden, never logged);
81
+ * - nothing produced by the resolver is ever destructive — that invariant is
82
+ * asserted by assertSafeReport.
83
+ */
84
+ function classifyEntry(entry) {
85
+ const base = { destructive: false, forbidden: false, requires_confirmation: false };
86
+ switch (entry.action) {
87
+ case 'install':
88
+ return { ...base, requires_confirmation: entry.requirement === 'required' ? true : entry.requirement === 'unknown' };
89
+ case 'configure':
90
+ return { ...base, requires_confirmation: true, interactive_secret: entry.kind === 'worker' };
91
+ case 'review':
92
+ return { ...base, requires_confirmation: true };
93
+ case 'skip':
94
+ case 'none':
95
+ return base;
96
+ default:
97
+ return { ...base, requires_confirmation: true };
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Hard invariant: a resolver report must never plan destructive operations.
103
+ * Throws on violation. Safe to run on every report (tests do).
104
+ */
105
+ function assertSafeReport(report) {
106
+ if (!report || !Array.isArray(report.entries)) {
107
+ throw new Error('assertSafeReport: not a resolution report');
108
+ }
109
+ if (!Array.isArray(report.destructive_operations) || report.destructive_operations.length !== 0) {
110
+ throw new Error('assertSafeReport: report contains destructive operations');
111
+ }
112
+ const forbidden = ['remove', 'delete', 'downgrade', 'uninstall', 'replace', 'destroy'];
113
+ for (const e of report.entries) {
114
+ if (forbidden.includes(e.action)) {
115
+ throw new Error(`assertSafeReport: entry ${e.id} has forbidden action "${e.action}"`);
116
+ }
117
+ // secret values must never be embedded in entries (keys are fine)
118
+ if (e.env && e.env.values) {
119
+ throw new Error(`assertSafeReport: entry ${e.id} embeds env values — only key names are allowed`);
120
+ }
121
+ }
122
+ return true;
123
+ }
124
+
125
+ /**
126
+ * Gate for potentially disruptive operations executed by the (future)
127
+ * installer engine. Returns { allowed, reason }.
128
+ * An operation is allowed only if:
129
+ * - it is not in the forbidden subset of NEVER_AUTOMATIC, AND
130
+ * - an explicit user confirmation object is provided
131
+ * ({ confirmed: true, op, via: 'interactive-prompt' }).
132
+ */
133
+ function confirmationGate(op, confirmation = null) {
134
+ const rule = NEVER_AUTOMATIC.find((r) => r.op === op);
135
+ if (!rule) {
136
+ return { allowed: false, reason: `unknown operation "${op}" — not in the safety model` };
137
+ }
138
+ if (rule.forbidden) {
139
+ return { allowed: false, reason: `operation "${op}" (${rule.description}) is forbidden for the installer in v1` };
140
+ }
141
+ if (!confirmation || confirmation.confirmed !== true || confirmation.op !== op) {
142
+ return { allowed: false, reason: `operation "${op}" requires explicit user confirmation before execution` };
143
+ }
144
+ return { allowed: true, reason: null };
145
+ }
146
+
147
+ module.exports = {
148
+ NEVER_AUTOMATIC,
149
+ NEVER_AUTOMATIC_OPS,
150
+ SECRET_NAMES,
151
+ isSecretName,
152
+ redactSecrets,
153
+ classifyEntry,
154
+ assertSafeReport,
155
+ confirmationGate,
156
+ };