* enhancement(#537): migrate code-review-flags to TS source of truth Collapse the hand-written get-shit-done/bin/lib/code-review-flags.cjs to a TypeScript source of truth (src/code-review-flags.cts), compiled by tsc to a gitignored .cjs build artifact at the same path, per ADR-457 (build-at-publish). Second module after the semver-compare pilot (#541). Behaviour is preserved byte-for-behaviour (characterization test added in tests/code-review-flags.test.cjs locks the parser quirks). Adds compile-time type checking: CodeReviewFlags interface + CodeReviewWorkflow literal union. The require() path is unchanged, so code-review.md and the bug-3727 test keep working. The emitted .cjs is gitignored and eslint-ignored, mirroring the pilot. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 9 leaf bin/lib modules to TS source of truth ADR-457 build-at-publish, batch 1 (pure leaf modules, 0 sibling-deps): 001-legacy-orphan-files, context-utilization, redaction, artifacts, command-arg-projection, clock, ui-safety-gate, review-reviewer-selection, clusters. Each moves to src/*.cts (strict TS, typed), compiled by tsc to a gitignored .cjs at the same require() path; behaviour preserved byte-for- behaviour. Adds src/node-globals.d.ts (minimal ambient shim; "types":[]). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#537): add @types/node, drop hand-rolled node-globals shim ADR-457 migration infra: replace the temporary src/node-globals.d.ts ambient shim with @types/node@22 + "types":["node"] in tsconfig.build.json. Unblocks migrating the ~49 remaining bin/lib modules that use node:fs/path/os/ child_process. Build + full suite (3030 pass) + lint all green; no .cts type changes were needed (real Node types matched the shim). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 9 more bin/lib modules to TS (batch 2) ADR-457 build-at-publish. Clean leaves: installer-migration-report, prompt-budget. Type-error-prone leaves (were tsconfig.lint-excluded; now strict-typed and removed from that exclude list): secrets, phase-lifecycle, workstream-name-policy, decisions, validate, schema-detect. Plus runtime-name-policy. Strict type fixes narrow unknown->concrete domain types (no any/ts-ignore); behaviour preserved. Full suite green, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate runtime-slash to TS (cross-import proof) ADR-457. First cross-module TS->TS import: src/runtime-slash.cts imports ./runtime-name-policy.cjs and tsc resolves the sibling .cts types under strict (no declaration files; NodeNext .cjs->.cts mapping), emitting a correct require("./runtime-name-policy.cjs"). Confirms the recipe for coupled modules, which must be migrated in dependency order (leaves-up). Suite green, lint clean. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 10 more bin/lib modules to TS (batch 3) ADR-457 build-at-publish, Wave-1 leaves: event, workstream-inventory-builder, plan-scan, fallow-runner, project-root, installer-migration-authoring, update-context, 000-first-time-baseline, runtime-homes, model-catalog. Strict typing fixed real issues (narrowing unknown, qualified fs/path calls, removed unnecessary casts); plan-scan/project-root/workstream-inventory-builder dropped from tsconfig.lint exclude. Behaviour preserved; suite green, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 5 large Wave-1 leaves to TS (batch 4) ADR-457 build-at-publish: configuration, state-document, shell-command- projection (42 dependents), security, command-aliases. shell-command- projection keeps a namespace child_process import for mock-intercept testability. loadConfig/migrateOnDisk emit synchronously (every caller uses them sync; the one awaited migrateOnDisk caller tolerates a non-Promise) — full suite (3030 pass) confirms behaviour preserved. configuration/ state-document/command-aliases dropped from tsconfig.lint exclude. Also fixes the malformed batch-3 changeset frontmatter (type/pr) that failed lint:docs. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 6 Wave-2 modules to TS (batch 5) ADR-457 build-at-publish: config-schema, model-profiles, 002-codex-legacy-hooks-json, logger, active-workstream-store, adr-parser. First batch importing already-migrated siblings (configuration, model-catalog, shell-command-projection, redaction, security) via ./sibling.cjs specifiers. Strict type narrowing (typeof guards over String(unknown)); behaviour preserved; suite 3030 pass, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 5 large Wave-2 modules to TS (batch 6) ADR-457 build-at-publish: graphify, install-profiles, intel, installer-migrations, worktree-safety. installer-migrations preserves its dynamic require() loader for numbered migration modules (scoped lint suppressions). Strict typing (typeof guards over String(unknown)); behaviour preserved; suite 3030 pass, lint 0 errors. Wave 2 complete. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate Wave-3 modules to TS (batch 7) ADR-457 build-at-publish: planning-workspace, runtime-artifact-layout, command-routing-hub, drift. Uses `import x = require()` for export= siblings; drift's lazy require of runtime-slash hoisted to a top-level import (verified non-circular). Behaviour preserved; suite 3030 pass, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate small Wave-4 modules to TS (batch 8) ADR-457 build-at-publish: cjs-command-router-adapter, phase-command-router, surface, roadmap-upgrade. Typed the hub router handler results as the HubResult discriminated union; surface drops 4 genuinely-unused imports. Behaviour preserved; suite 3030 pass, lint 0 errors. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate core hub (2.5k LOC, 68 dependents) to TS (batch 9) ADR-457 build-at-publish: get-shit-done/bin/lib/core.cjs -> src/core.cts, preserving all 63 exports via export=. All sibling deps already migrated (shell-command-projection, model-profiles, model-catalog, worktree-safety, planning-workspace, project-root, configuration, config-schema). Strict types, no any/ts-ignore; config-schema lazy require hoisted (non-circular). Behaviour preserved (independently verified: core's shard 3030 pass / 0 fail). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#537): make ESLint-coverage + test-sprawl checks migration-aware #551 test hardcoded 12 now-migrated modules as "hand-written, must be linted"; that invariant is obsoleted by the ADR-457 migration. Rewrite it to a filesystem-driven invariant that holds at every stage: a bin/lib/*.cjs must be eslint-ignored IFF it has a src/*.cts source (tsc-generated), else linted (covers package-identity, which has no TS source). Also eslint-ignore config-types.cjs (has a src counterpart) and drop the redundant tests/clock.test.cjs (clock already covered by clock-seam + bug-474 tests), which tripped the lint-test-file-count ratchet. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 9 Wave-5 router/inventory modules to TS (batch 10) ADR-457 build-at-publish: phases/verify/init/agent/task/validate/roadmap/state command routers + workstream-inventory. Router handler results typed against core's exported shapes; behaviour preserved (caught+fixed a --verify boolean flag regression mid-migration). Full suite green across all shards (only the 4 local gpg-env changeset-notes failures remain; CI passes them). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 7 Wave-5 modules to TS (batch 11) ADR-457 build-at-publish: gap-checker, docs, check-command-router, frontmatter, learnings, gsd2-import, profile-pipeline. Behaviour preserved; full suite green across all shards (only the 4 local gpg-env failures remain). Also broadens atomic-write-coverage.test.cjs to accept the tsc-compiled namespace-import form while still asserting platformWriteSync is called (safety guard intact). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate config + profile-output to TS (batch 12) ADR-457 build-at-publish: config (729 LOC), profile-output (1142 LOC). All exports preserved; cmdMigrateConfig de-asynced (migrateOnDisk is sync, awaited caller tolerates it). Behaviour preserved; suite green across all shards (only the 4 local gpg-env failures). Wave 5 complete. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate 5 Wave-6 modules to TS (batch 13) ADR-457 build-at-publish: template, uat, workstream, roadmap, audit. Behaviour preserved (dead toPosixPath import dropped from audit; inline requires hoisted). Suite green across all shards (only the 4 local gpg-env failures). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate commands + state hubs to TS (batch 14) ADR-457 build-at-publish: commands (1305 LOC), state (2074 LOC, 17 dependents). All exports preserved; inner requires kept non-hoisted where load-order matters (install.js, per-call security); acquireStateLock cast inlined to preserve the err.code source token a structural test inspects. Behaviour preserved; suite green across all shards (only the 4 local gpg-env failures). Wave 6 complete. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate milestone to TS (batch 15a, hand-authored) ADR-457 build-at-publish: milestone -> src/milestone.cts. Authored directly (subagent capacity was unavailable). Also relaxes core.output()'s 3rd param to optional, matching its real always-optional call contract (unblocks remaining 2-arg output callers). Behaviour preserved; suite green across all shards (only the 4 local gpg-env failures). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537): migrate phase, verify, init to TS (batch 15, final modules) ADR-457 build-at-publish, Wave 7 (the last hubs): phase (1608 LOC), verify (1615), init (2113). Adds src/package-identity.d.cts so verify can import the permanently value-baked package-identity.cjs under strict TS. Fixes two regressions the migration introduced in verify: restore cmdValidateHealth's `return result` (callers/tests read result.warnings — it is NOT side-effect-only), and make the bug-3384 source-pattern test tolerant of the tsc-compiled bracket-notation form of the git_list_failed->W020 branch (behaviour intact). Full suite green across all shards (only the 4 local gpg-env failures); lint 0 errors. All 86 migratable bin/lib modules are now TypeScript sources. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#537): finalize ADR-457 migration — retire tsconfig.lint.json All hand-written bin/lib/*.cjs are now src/*.cts sources, so the checkJs stopgap tsconfig.lint.json (unused; not wired into eslint, scripts, or CI) is deleted per ADR-457's final step. Also gitignore the tsc-generated config-types.cjs (was still committed) for consistency with every other emitted artifact. package-identity.cjs stays value-baked (declared via src/package-identity.d.cts). Suite green; #551 ESLint-coverage test green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#537): add prepare script so unpacked/git installs build bin/lib artifacts ADR-457 build-at-publish: bin/lib/*.cjs are now gitignored, built by tsc. The prepack/prepublishOnly hooks cover `npm pack`/publish, but `npm install -g <dir>` and git installs run the `prepare` lifecycle — which was missing — so the unpacked install shipped without the compiled .cjs and failed at startup with "Cannot find module './lib/core.cjs'" (caught by the smoke-unpacked CI job). Add `prepare` mirroring prepublishOnly (build:lib + build:hooks). prepare does NOT run for registry consumers (they get the pre-built tarball), only for source/local/pack installs. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#537): make CI build/lockfile checks work with gitignored bin/lib artifacts ADR-457 build-at-publish exposed two CI assumptions that bin/lib/*.cjs are always present on disk: - check:env's lockfile-sync ran `npm ci --dry-run`, which now triggers the `prepare` build (tsc) — but it runs before deps are installed, so tsc is absent and it misreported the lockfile as out of sync. Add --ignore-scripts (a lockfile check must not build). - the lint-tests job installs with --ignore-scripts (no prepare build), but lint:skill-deps require()s the built install-profiles.cjs. Add an explicit `npm run build:lib` step after install. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#537): narrow prepare to build:lib only (unbreak packed-smoke pack step) prepare running build:hooks emitted "✓ Copying ..." stdout during `npm pack`, which the install-smoke "Pack root tarball" step captures into $GITHUB_OUTPUT — breaking it with "Invalid format". build:lib (tsc) is silent on success and is all the unpacked/source install needs (the smoke-unpacked assertions exercise gsd-tools, i.e. bin/lib, and tolerate hook setup with `|| true`). Matches prepack. build:hooks still runs on prepublishOnly for real publishes. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#537): wire Stryker mutation gate to build-at-publish layout The gate scored 0.00 because it mutated changed bin/lib/*.cjs that (a) were generated artifacts and (b) included modules with no coverage in the command's test set. Rework: mutation.yml now derives changed COVERED modules from src/*.cts and maps them to their built bin/lib/*.cjs; Stryker mutates those built artifacts with a no-rebuild command (mutating src/*.cts + per-mutant tsc was ~3x over the 30-min CI budget). NOTE: with the gate now correctly measuring the covered modules, their actual mutation score is 42.94% (< break 50) — a pre-existing test-coverage gap (adr-parser/prompt-budget/etc.), not introduced by this behaviour-preserving migration. Reaching 50 needs more tests, a threshold/scope change, or a waiver — a maintainer decision. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#537): raise mutation coverage of covered modules above the 50 gate Adds focused example-based unit tests that kill surviving mutants in the two lowest-scoring covered modules: - tests/prompt-budget.unit.test.cjs (112 tests): 17.9% -> 97.9% - tests/adr-parser.unit.test.cjs (205 tests): 44.7% -> 89.4% Both wired into stryker.config.mjs's command. Fresh full run over the 6 covered modules now scores 82.25% (>= break 50); every covered module is >= 68%. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * enhancement(#537,#609): parallelize mutation gate via dynamic per-module matrix The serial Stryker run timed out at 30 min once the migration's added tests made every mutant re-run ~300 tests. Replace it with a dynamic matrix so the gate completes well under budget — folded into this PR (was tracked as #609) because it's a prerequisite for this PR's mutation gate to pass. - scripts/mutation-matrix.cjs: single source of truth (covered-module -> test files) computing changed covered modules from git diff -> {has_work, matrix}. - mutation.yml: detect -> dynamic `matrix: fromJSON(...)` mutate job (one parallel shard per changed module, scoped via MUTATION_TEST_CMD to only that module's tests, 15-min/shard) -> summary job that KEEPS the legacy check name "Stryker mutation score (changed files only)" so branch protection is unchanged. Per-shard jobs report as "Stryker (<module>)". - stryker.config.mjs: commandRunner.command reads MUTATION_TEST_CMD (falls back to the full command locally). Closes #609. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#537,#609): give each mutation shard ≥50% on its own tests; drop blacksmith note Per-module sharding revealed that active-workstream-store (46.5%) and frontmatter (7.4%) only cleared 50% in the old serial run via timeout-noise from the bloated 300-test command; on their own tests they were below the gate. Add focused unit tests: - tests/active-workstream-store.unit.test.cjs (115 tests): 46.5% -> 81.9% - tests/frontmatter.unit.test.cjs (165 tests): 7.4% -> 63.4% Both wired into scripts/mutation-matrix.cjs (per-module test map) and stryker.config.mjs DEFAULT_TEST_CMD. All 6 covered modules now clear break:50 with only their own tests (config-schema/context-utilization/prompt-budget/ adr-parser already did). Also removes the leftover blacksmith TODO comment — GitHub-hosted runners only; speed comes from parallel per-module shards. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#537,#609): strengthen prompt-budget tests to clear the gate on its own tests prompt-budget scored 39.58% when mutation-tested with ONLY its own tests (the way the per-module CI shard runs it) — an earlier ~98% reading was inflated by accidentally running the full multi-module command. Add 96 targeted tests to tests/prompt-budget.unit.test.cjs (exact note-template text, plan-truncation arithmetic/percentages, drop-block strings, noteInjected/hardFailed booleans): scoped score 39.58% -> 68.75% (>= break 50). All 6 covered modules now clear the gate on their own tests. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
933 lines
33 KiB
TypeScript
933 lines
33 KiB
TypeScript
/**
|
|
* Installer migrations engine — plan, apply, and track filesystem-mutation
|
|
* migrations for GSD runtime config directories.
|
|
*
|
|
* ADR-457 build-at-publish: the hand-written bin/lib/installer-migrations.cjs
|
|
* collapsed to a TypeScript source of truth. Behaviour is preserved
|
|
* byte-for-behaviour from the prior hand-written .cjs; only types are added.
|
|
*/
|
|
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import crypto from 'node:crypto';
|
|
import {
|
|
validateInstallerMigrationActions,
|
|
validateInstallerMigrationRecord,
|
|
type MigrationRecord,
|
|
type MigrationAction,
|
|
} from './installer-migration-authoring.cjs';
|
|
import { platformWriteSync } from './shell-command-projection.cjs';
|
|
import { realClock, type Clock } from './clock.cjs';
|
|
|
|
const MANIFEST_NAME = 'gsd-file-manifest.json';
|
|
const INSTALL_STATE_NAME = 'gsd-install-state.json';
|
|
const INSTALL_MIGRATION_LOCK_NAME = 'gsd-install-migration.lock';
|
|
const DEFAULT_MIGRATIONS_DIR = path.join(__dirname, 'installer-migrations');
|
|
const DEFAULT_LOCK_TIMEOUT_MS = 30_000;
|
|
const STRICT_JSON = Symbol('strict-json');
|
|
|
|
function sha256File(filePath: string): string {
|
|
const hash = crypto.createHash('sha256');
|
|
const buffer = Buffer.allocUnsafe(1024 * 1024);
|
|
const fd = fs.openSync(filePath, 'r');
|
|
try {
|
|
while (true) {
|
|
const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null);
|
|
if (bytesRead === 0) break;
|
|
hash.update(buffer.subarray(0, bytesRead));
|
|
}
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
return hash.digest('hex');
|
|
}
|
|
|
|
function sha256Text(value: string): string {
|
|
return crypto.createHash('sha256').update(value).digest('hex');
|
|
}
|
|
|
|
function readJsonIfPresent(filePath: string, fallback: unknown): unknown {
|
|
if (!fs.existsSync(filePath)) return fallback;
|
|
try {
|
|
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
} catch (error) {
|
|
if (fallback === STRICT_JSON) {
|
|
throw new Error(`invalid installer migration state JSON: ${filePath}: ${(error as Error).message}`);
|
|
}
|
|
return fallback;
|
|
}
|
|
}
|
|
|
|
interface InstallManifest {
|
|
version: string | null;
|
|
timestamp: string | null;
|
|
mode: string | null;
|
|
files: Record<string, string>;
|
|
}
|
|
|
|
function readInstallManifest(configDir: string): InstallManifest {
|
|
const manifest = readJsonIfPresent(path.join(configDir, MANIFEST_NAME), null);
|
|
if (!manifest || typeof manifest !== 'object') {
|
|
return { version: null, timestamp: null, mode: null, files: {} };
|
|
}
|
|
const m = manifest as Record<string, unknown>;
|
|
return {
|
|
version: typeof m.version === 'string' ? m.version : null,
|
|
timestamp: typeof m.timestamp === 'string' ? m.timestamp : null,
|
|
mode: typeof m.mode === 'string' ? m.mode : null,
|
|
files: m.files && typeof m.files === 'object' ? m.files as Record<string, string> : {},
|
|
};
|
|
}
|
|
|
|
interface InstallState {
|
|
schemaVersion: number;
|
|
appliedMigrations: Array<Record<string, unknown>>;
|
|
}
|
|
|
|
function readInstallState(configDir: string): InstallState {
|
|
const state = readJsonIfPresent(path.join(configDir, INSTALL_STATE_NAME), STRICT_JSON);
|
|
if (!state || typeof state !== 'object') {
|
|
return { schemaVersion: 1, appliedMigrations: [] };
|
|
}
|
|
const s = state as Record<string, unknown>;
|
|
return {
|
|
schemaVersion: typeof s.schemaVersion === 'number' ? s.schemaVersion : 1,
|
|
appliedMigrations: Array.isArray(s.appliedMigrations) ? s.appliedMigrations as Array<Record<string, unknown>> : [],
|
|
};
|
|
}
|
|
|
|
// Strict atomic write for the install state: must never be left half-written.
|
|
// Bypasses the seam because platformWriteSync falls back to a direct write on
|
|
// rename failure, which would silently violate this invariant.
|
|
function atomicWriteInstallState(configDir: string, content: string): void {
|
|
fs.mkdirSync(configDir, { recursive: true });
|
|
const filePath = path.join(configDir, INSTALL_STATE_NAME);
|
|
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
try {
|
|
fs.writeFileSync(tmpPath, content, 'utf8');
|
|
fs.renameSync(tmpPath, filePath);
|
|
} catch (error) {
|
|
try { fs.rmSync(tmpPath, { force: true }); } catch { /* best-effort */ }
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function writeInstallState(configDir: string, state: InstallState): InstallState {
|
|
atomicWriteInstallState(configDir, JSON.stringify(state, null, 2) + '\n');
|
|
return state;
|
|
}
|
|
|
|
interface ReadJsonResult {
|
|
exists: boolean;
|
|
value: unknown;
|
|
error: Error | null;
|
|
}
|
|
|
|
function readJson(configDir: string, relPath: string): ReadJsonResult {
|
|
const { fullPath } = ensureInsideConfig(configDir, relPath);
|
|
if (!fs.existsSync(fullPath)) {
|
|
return { exists: false, value: null, error: null };
|
|
}
|
|
try {
|
|
return { exists: true, value: JSON.parse(fs.readFileSync(fullPath, 'utf8')), error: null };
|
|
} catch (error) {
|
|
return { exists: true, value: null, error: error as Error };
|
|
}
|
|
}
|
|
|
|
function normalizeRelPath(relPath: string): string {
|
|
if (typeof relPath !== 'string' || relPath.trim() === '') {
|
|
throw new Error('migration action relPath must be a non-empty string');
|
|
}
|
|
const normalized = relPath.replace(/\\/g, '/');
|
|
if (path.isAbsolute(normalized) || path.win32.isAbsolute(normalized)) {
|
|
throw new Error(`migration action relPath must stay inside configDir: ${relPath}`);
|
|
}
|
|
const segments = normalized.split('/');
|
|
if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {
|
|
throw new Error(`migration action relPath must stay inside configDir: ${relPath}`);
|
|
}
|
|
return segments.join('/');
|
|
}
|
|
|
|
interface ArtifactClassification {
|
|
classification: string;
|
|
originalHash: string | null;
|
|
currentHash: string | null;
|
|
}
|
|
|
|
function classifyArtifact(configDir: string, relPath: string, manifest: InstallManifest): ArtifactClassification {
|
|
const normalized = normalizeRelPath(relPath);
|
|
const originalHash = manifest.files[normalized] || null;
|
|
const fullPath = path.join(configDir, normalized);
|
|
if (!fs.existsSync(fullPath)) {
|
|
return { classification: originalHash ? 'managed-missing' : 'missing', originalHash, currentHash: null };
|
|
}
|
|
const currentHash = sha256File(fullPath);
|
|
if (!originalHash) {
|
|
return { classification: 'unknown', originalHash: null, currentHash };
|
|
}
|
|
if (currentHash === originalHash) {
|
|
return { classification: 'managed-pristine', originalHash, currentHash };
|
|
}
|
|
return { classification: 'managed-modified', originalHash, currentHash };
|
|
}
|
|
|
|
function appliedMigrationIds(state: InstallState): Set<string> {
|
|
return new Set(
|
|
state.appliedMigrations
|
|
.filter((entry) => entry && typeof entry.id === 'string')
|
|
.map((entry) => entry.id as string)
|
|
);
|
|
}
|
|
|
|
function appliedMigrationEntries(state: InstallState): Map<string, Record<string, unknown>> {
|
|
const entries = new Map<string, Record<string, unknown>>();
|
|
for (const entry of state.appliedMigrations) {
|
|
if (entry && typeof entry.id === 'string' && !entries.has(entry.id)) {
|
|
entries.set(entry.id, entry);
|
|
}
|
|
}
|
|
return entries;
|
|
}
|
|
|
|
function migrationChecksum(migration: MigrationRecord): string {
|
|
const checksum = migration.checksum;
|
|
if (typeof checksum === 'string' && checksum) return checksum;
|
|
const serializable = {
|
|
id: migration.id,
|
|
title: migration.title || null,
|
|
description: migration.description || null,
|
|
introducedIn: migration.introducedIn || null,
|
|
runtimes: migration.runtimes || null,
|
|
scopes: migration.scopes || null,
|
|
destructive: migration.destructive === true,
|
|
runtimeContract: migration.runtimeContract || null,
|
|
plan: typeof migration.plan === 'function' ? (migration.plan as (...args: unknown[]) => unknown).toString() : null,
|
|
};
|
|
return `sha256:${sha256Text(JSON.stringify(serializable))}`;
|
|
}
|
|
|
|
function assertAppliedMigrationChecksums(applied: Map<string, Record<string, unknown>>, migrations: MigrationRecord[]): void {
|
|
for (const migration of migrations) {
|
|
const entry = applied.get(migration.id as string);
|
|
if (!entry || !entry.checksum) continue;
|
|
const checksum = migrationChecksum(migration);
|
|
if (entry.checksum !== checksum) {
|
|
throw new Error(
|
|
`applied migration checksum changed for ${migration.id as string}; create a new fix-forward migration id`
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
function migrationMatchesContext(migration: MigrationRecord, { runtime, scope }: { runtime: string | null; scope: string | null }): boolean {
|
|
if (Array.isArray(migration.runtimes) && (migration.runtimes as string[]).length > 0) {
|
|
if (!runtime || !(migration.runtimes as string[]).includes(runtime)) return false;
|
|
}
|
|
if (Array.isArray(migration.scopes) && (migration.scopes as string[]).length > 0) {
|
|
if (!scope || !(migration.scopes as string[]).includes(scope)) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function discoverInstallerMigrations({ migrationsDir }: { migrationsDir: string }): MigrationRecord[] {
|
|
if (!migrationsDir || !fs.existsSync(migrationsDir)) return [];
|
|
return fs.readdirSync(migrationsDir, { withFileTypes: true })
|
|
.filter((entry) => entry.isFile() && entry.name.endsWith('.cjs'))
|
|
.map((entry) => entry.name)
|
|
.sort()
|
|
.flatMap((fileName) => {
|
|
const source = path.join(migrationsDir, fileName);
|
|
|
|
delete require.cache[require.resolve(source)];
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
const exported: unknown = require(source);
|
|
const records = Array.isArray(exported) ? exported : [exported];
|
|
return records.map((record) => validateInstallerMigrationRecord(record as MigrationRecord, source));
|
|
});
|
|
}
|
|
|
|
function journalTimestamp(now: () => string): string {
|
|
return now().replace(/[:.]/g, '-');
|
|
}
|
|
|
|
function migrationRunId(appliedAt: string): string {
|
|
return `${journalTimestamp(() => appliedAt)}-${crypto.randomBytes(8).toString('hex')}`;
|
|
}
|
|
|
|
function sleepSync(ms: number): void {
|
|
const buffer = new SharedArrayBuffer(4);
|
|
Atomics.wait(new Int32Array(buffer), 0, 0, ms);
|
|
}
|
|
|
|
/**
|
|
* Check whether a given PID is alive on the current host.
|
|
* Uses process.kill(pid, 0) which works on POSIX and Windows (Node's
|
|
* implementation maps it to OpenProcess + GetExitCodeProcess on win32).
|
|
* Returns true if alive or permission-denied (live but not ours),
|
|
* false if ESRCH (no such process).
|
|
*/
|
|
function isPidAlive(pid: number): boolean {
|
|
if (typeof pid !== 'number' || !Number.isFinite(pid) || pid <= 0) return false;
|
|
try {
|
|
process.kill(pid, 0);
|
|
return true; // alive (or permission denied — treat as live)
|
|
} catch (err) {
|
|
return (err as NodeJS.ErrnoException).code !== 'ESRCH';
|
|
}
|
|
}
|
|
|
|
interface LockFileData {
|
|
pid: number;
|
|
acquiredAt: string;
|
|
}
|
|
|
|
/**
|
|
* Try to read and parse the lock file JSON. Returns null on any error
|
|
* (missing, invalid JSON, I/O failure).
|
|
*/
|
|
function readLockFile(lockPath: string): LockFileData | null {
|
|
try {
|
|
const raw = fs.readFileSync(lockPath, 'utf8');
|
|
const parsed: unknown = JSON.parse(raw);
|
|
if (parsed && typeof parsed === 'object' && typeof (parsed as Record<string, unknown>).pid === 'number') {
|
|
return parsed as LockFileData;
|
|
}
|
|
return null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function acquireInstallMigrationLock(
|
|
configDir: string,
|
|
{ timeoutMs = DEFAULT_LOCK_TIMEOUT_MS }: { timeoutMs?: number } = {},
|
|
clock: Clock = realClock,
|
|
): () => void {
|
|
fs.mkdirSync(configDir, { recursive: true });
|
|
const lockPath = path.join(configDir, INSTALL_MIGRATION_LOCK_NAME);
|
|
const started = clock.now();
|
|
|
|
while (true) {
|
|
let fd: number | null = null;
|
|
let lockCreatedByUs = false;
|
|
try {
|
|
fd = fs.openSync(lockPath, 'wx');
|
|
// Close the open descriptor before writing so the file handle is
|
|
// released on Windows before the release closure unlinks it.
|
|
// Write payload via writeFileSync with the path (not the fd) so we
|
|
// don't hold an open fd across the lifetime of the lock.
|
|
fs.closeSync(fd);
|
|
fd = null;
|
|
lockCreatedByUs = true; // we own the file; clean it up on any subsequent error
|
|
fs.writeFileSync(lockPath, JSON.stringify({
|
|
pid: process.pid,
|
|
acquiredAt: new Date().toISOString(),
|
|
}) + '\n');
|
|
lockCreatedByUs = false; // release closure owns cleanup from here
|
|
return () => {
|
|
const failures: Error[] = [];
|
|
// Use unlinkSync (not rmSync with { force: true }) so EPERM errors
|
|
// are NOT silently swallowed. On Windows, if the unlink fails
|
|
// transiently, the error surfaces via releaseError so the caller
|
|
// can observe and surface it rather than leaving a stale lock.
|
|
try { fs.unlinkSync(lockPath); } catch (error) { failures.push(error as Error); }
|
|
if (failures.length > 0) {
|
|
const releaseError = new Error(`failed to release installer migration lock: ${lockPath}`) as Error & { failures: Error[] };
|
|
releaseError.failures = failures;
|
|
throw releaseError;
|
|
}
|
|
};
|
|
} catch (error) {
|
|
if (fd !== null) {
|
|
try { fs.closeSync(fd); } catch { /* best-effort */ }
|
|
try { fs.unlinkSync(lockPath); } catch { /* best-effort */ }
|
|
fd = null;
|
|
} else if (lockCreatedByUs) {
|
|
// fd was closed but writeFileSync threw before we returned the release
|
|
// closure — the empty lock file is still on disk and must be removed
|
|
// so it does not orphan as an unreadable (empty/invalid JSON) stale lock.
|
|
try { fs.unlinkSync(lockPath); } catch { /* best-effort */ }
|
|
}
|
|
const err = error as NodeJS.ErrnoException;
|
|
if (err && err.code === 'EEXIST') {
|
|
// Stale-lock reclamation: read the on-disk PID and check liveness.
|
|
// If the PID is dead (ESRCH) or is our own process (same-process
|
|
// re-entry caused by rmSync silently swallowing an unlink error on
|
|
// a previous call in the same invocation — the root cause of #3670),
|
|
// reclaim the lock by removing the stale file and retrying.
|
|
const lockData = readLockFile(lockPath);
|
|
if (lockData !== null) {
|
|
const holderPid = lockData.pid;
|
|
const isSameProcess = holderPid === process.pid;
|
|
const isDeadProcess = !isPidAlive(holderPid);
|
|
if (isSameProcess || isDeadProcess) {
|
|
// Reclaim: remove the stale lock and loop back to openSync.
|
|
// Only continue (retry) when unlink actually succeeds — a silent
|
|
// continue on reclaim failure recreates the original deadlock:
|
|
// the lock stays on disk and we spin indefinitely.
|
|
let reclaimed = false;
|
|
try { fs.unlinkSync(lockPath); reclaimed = true; } catch { /* unlink failed — fall through to timeout path */ }
|
|
if (reclaimed) continue;
|
|
}
|
|
}
|
|
if (clock.now() - started >= timeoutMs) {
|
|
const holderInfo = lockData ? ` (held by pid ${lockData.pid} since ${lockData.acquiredAt})` : '';
|
|
throw new Error(`installer migration lock is held: ${lockPath}${holderInfo}`);
|
|
}
|
|
clock.sleep(Math.min(50, Math.max(1, timeoutMs - (clock.now() - started))));
|
|
continue;
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
interface EnsureInsideConfigResult {
|
|
normalized: string;
|
|
fullPath: string;
|
|
}
|
|
|
|
function ensureInsideConfig(configDir: string, relPath: string): EnsureInsideConfigResult {
|
|
const normalized = normalizeRelPath(relPath);
|
|
const fullPath = path.resolve(configDir, normalized);
|
|
const root = path.resolve(configDir);
|
|
if (fullPath !== root && !fullPath.startsWith(root + path.sep)) {
|
|
throw new Error(`migration path escapes configDir: ${relPath}`);
|
|
}
|
|
return { normalized, fullPath };
|
|
}
|
|
|
|
function isStructurallyEmpty(value: unknown): boolean {
|
|
if (value === null || value === undefined) return true;
|
|
if (Array.isArray(value)) return value.length === 0;
|
|
return typeof value === 'object' && Object.keys(value).length === 0;
|
|
}
|
|
|
|
interface JournalAction extends Record<string, unknown> {
|
|
status: string;
|
|
}
|
|
|
|
function journalAction(action: MigrationAction, status: string, extras: Record<string, unknown> = {}): JournalAction {
|
|
const { value: _value, ...safeAction } = action;
|
|
return { ...safeAction, ...extras, status };
|
|
}
|
|
|
|
interface PlanContext {
|
|
configDir: string;
|
|
runtime: string | null;
|
|
scope: string | null;
|
|
manifest: InstallManifest;
|
|
state: InstallState;
|
|
baselineScan: boolean;
|
|
now: () => string;
|
|
classifyArtifact: (relPath: string) => ArtifactClassification;
|
|
readJson: (relPath: string) => ReadJsonResult;
|
|
}
|
|
|
|
interface PlannedAction extends MigrationAction {
|
|
migrationId: string;
|
|
migrationChecksum: string;
|
|
type: string;
|
|
relPath: string;
|
|
reason: string;
|
|
classification: string;
|
|
originalHash: string | null;
|
|
currentHash: string | null;
|
|
requestedType?: string;
|
|
backupRelPath?: string | null;
|
|
value?: unknown;
|
|
deleteIfEmpty?: boolean;
|
|
prompt?: unknown;
|
|
choices?: unknown[];
|
|
}
|
|
|
|
interface MigrationPlan {
|
|
generatedAt: string;
|
|
manifest: InstallManifest;
|
|
state: InstallState;
|
|
pendingMigrationIds: string[];
|
|
pendingMigrations: MigrationRecord[];
|
|
actions: PlannedAction[];
|
|
blocked: PlannedAction[];
|
|
}
|
|
|
|
function planInstallerMigrations({
|
|
configDir,
|
|
runtime = null,
|
|
scope = null,
|
|
migrations,
|
|
baselineScan = false,
|
|
now = () => new Date().toISOString(),
|
|
}: {
|
|
configDir: string;
|
|
runtime?: string | null;
|
|
scope?: string | null;
|
|
migrations: MigrationRecord[];
|
|
baselineScan?: boolean;
|
|
now?: () => string;
|
|
}): MigrationPlan {
|
|
if (!configDir) throw new Error('configDir is required');
|
|
if (!Array.isArray(migrations)) throw new Error('migrations must be an array');
|
|
|
|
const manifest = readInstallManifest(configDir);
|
|
const state = readInstallState(configDir);
|
|
const validatedMigrations = migrations.map((migration) =>
|
|
validateInstallerMigrationRecord(migration)
|
|
);
|
|
const scopedMigrations = validatedMigrations.filter((migration) =>
|
|
migrationMatchesContext(migration, { runtime, scope })
|
|
);
|
|
const applied = appliedMigrationEntries(state);
|
|
assertAppliedMigrationChecksums(applied, scopedMigrations);
|
|
const pending = scopedMigrations.filter((migration) => !applied.has(migration.id as string));
|
|
const actions: PlannedAction[] = [];
|
|
const blocked: PlannedAction[] = [];
|
|
const classifications = new Map<string, ArtifactClassification>();
|
|
const classify = (relPath: string): ArtifactClassification => {
|
|
const normalized = normalizeRelPath(relPath);
|
|
if (!classifications.has(normalized)) {
|
|
classifications.set(normalized, classifyArtifact(configDir, normalized, manifest));
|
|
}
|
|
return classifications.get(normalized)!;
|
|
};
|
|
|
|
for (const migration of pending) {
|
|
const planFn = migration.plan as (ctx: PlanContext) => unknown[];
|
|
const plannedActions = planFn({
|
|
configDir,
|
|
runtime,
|
|
scope,
|
|
manifest,
|
|
state,
|
|
baselineScan,
|
|
now,
|
|
classifyArtifact: classify,
|
|
readJson: (relPath) => readJson(configDir, relPath),
|
|
});
|
|
validateInstallerMigrationActions(plannedActions, migration);
|
|
const checksum = migrationChecksum(migration);
|
|
for (const rawAction of plannedActions as MigrationAction[]) {
|
|
const relPath = normalizeRelPath(rawAction.relPath as string);
|
|
const classification = rawAction.classification
|
|
? {
|
|
classification: rawAction.classification as string,
|
|
originalHash: rawAction.originalHash as string | null || null,
|
|
currentHash: rawAction.currentHash as string | null || null,
|
|
}
|
|
: classify(relPath);
|
|
let protectedType = rawAction.type as string;
|
|
if (rawAction.type === 'remove-managed' && classification.classification === 'managed-modified') {
|
|
protectedType = 'backup-and-remove';
|
|
}
|
|
if (rawAction.type === 'remove-managed' && classification.classification === 'unknown') {
|
|
protectedType = 'preserve-user';
|
|
}
|
|
const action: PlannedAction = {
|
|
migrationId: migration.id as string,
|
|
migrationChecksum: checksum,
|
|
type: protectedType,
|
|
relPath,
|
|
reason: rawAction.reason as string || migration.description as string || '',
|
|
classification: classification.classification,
|
|
originalHash: classification.originalHash,
|
|
currentHash: classification.currentHash,
|
|
};
|
|
if (action.type !== rawAction.type) {
|
|
action.requestedType = rawAction.type as string | undefined;
|
|
}
|
|
if (action.type === 'backup-and-remove') {
|
|
action.backupRelPath = null;
|
|
}
|
|
if (action.type === 'rewrite-json') {
|
|
action.value = rawAction.value;
|
|
action.deleteIfEmpty = rawAction.deleteIfEmpty === true;
|
|
}
|
|
if (rawAction.prompt) action.prompt = rawAction.prompt;
|
|
if (Array.isArray(rawAction.choices)) action.choices = rawAction.choices as unknown[];
|
|
if (action.type === 'prompt-user') {
|
|
blocked.push(action);
|
|
} else if (
|
|
action.classification === 'unknown' &&
|
|
action.type !== 'rewrite-json' &&
|
|
action.type !== 'record-baseline' &&
|
|
action.type !== 'baseline-preserve-user'
|
|
) {
|
|
blocked.push(action);
|
|
}
|
|
actions.push(action);
|
|
}
|
|
}
|
|
|
|
return {
|
|
generatedAt: now(),
|
|
manifest,
|
|
state,
|
|
pendingMigrationIds: pending.map((migration) => migration.id as string),
|
|
pendingMigrations: pending,
|
|
actions,
|
|
blocked,
|
|
};
|
|
}
|
|
|
|
function uniqueActionMigrationIds(actions: PlannedAction[]): string[] {
|
|
return [...new Set(actions.map((action) => action.migrationId).filter(Boolean))];
|
|
}
|
|
|
|
interface RollbackArgs {
|
|
configDir: string;
|
|
journal: { actions: JournalAction[] };
|
|
journalPath: string;
|
|
rollbackRoot: string;
|
|
backupRoot: string;
|
|
previousInstallStateBytes: string | null;
|
|
}
|
|
|
|
function rollbackAppliedMigrationResult({ configDir, journal, journalPath, rollbackRoot, backupRoot, previousInstallStateBytes }: RollbackArgs): void {
|
|
const failures: Array<{ relPath: string; error: string }> = [];
|
|
for (const action of [...journal.actions].reverse()) {
|
|
if (!action.rollbackRelPath) continue;
|
|
const rollbackPath = path.join(configDir, action.rollbackRelPath as string);
|
|
const dest = path.join(configDir, action.relPath as string);
|
|
try {
|
|
if (fs.existsSync(rollbackPath)) {
|
|
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
fs.copyFileSync(rollbackPath, dest);
|
|
}
|
|
} catch (error) {
|
|
failures.push({ relPath: action.relPath as string, error: (error as Error).message });
|
|
}
|
|
if (action.backupRelPath) {
|
|
try {
|
|
fs.rmSync(path.join(configDir, action.backupRelPath as string), { force: true });
|
|
} catch {
|
|
// backup cleanup is best-effort; preserve restore failures above
|
|
}
|
|
}
|
|
}
|
|
|
|
try {
|
|
if (previousInstallStateBytes === null) {
|
|
fs.rmSync(path.join(configDir, INSTALL_STATE_NAME), { force: true });
|
|
} else {
|
|
atomicWriteInstallState(configDir, previousInstallStateBytes);
|
|
}
|
|
} catch (error) {
|
|
failures.push({ relPath: INSTALL_STATE_NAME, error: (error as Error).message });
|
|
}
|
|
|
|
try {
|
|
fs.rmSync(journalPath, { force: true });
|
|
fs.rmSync(rollbackRoot, { recursive: true, force: true });
|
|
fs.rmSync(backupRoot, { recursive: true, force: true });
|
|
} catch {
|
|
// journal cleanup is best-effort; the rollback above is the safety-critical part
|
|
}
|
|
|
|
if (failures.length > 0) {
|
|
const error = new Error('migration rollback incomplete') as Error & { rollbackFailures: typeof failures };
|
|
error.rollbackFailures = failures;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function cleanupMigrationRunArtifacts(journalPath: string, rollbackRoot: string, backupRoot: string): void {
|
|
try { fs.rmSync(journalPath, { force: true }); } catch { /* best-effort */ }
|
|
try { fs.rmSync(rollbackRoot, { recursive: true, force: true }); } catch { /* best-effort */ }
|
|
try { fs.rmSync(backupRoot, { recursive: true, force: true }); } catch { /* best-effort */ }
|
|
}
|
|
|
|
interface ApplyResult {
|
|
appliedMigrationIds: string[];
|
|
journalRelPath: string;
|
|
rollback: () => void;
|
|
}
|
|
|
|
function applyInstallerMigrationPlan({
|
|
configDir,
|
|
plan,
|
|
now = () => new Date().toISOString(),
|
|
}: {
|
|
configDir: string;
|
|
plan: MigrationPlan;
|
|
now?: () => string;
|
|
}): ApplyResult {
|
|
if (!configDir) throw new Error('configDir is required');
|
|
if (!plan || !Array.isArray(plan.actions)) throw new Error('plan with actions is required');
|
|
if (Array.isArray(plan.blocked) && plan.blocked.length > 0) {
|
|
throw new Error(`migration plan has ${plan.blocked.length} blocked action(s)`);
|
|
}
|
|
|
|
const appliedAt = now();
|
|
const runId = migrationRunId(appliedAt);
|
|
const journalRelPath = path.posix.join('gsd-migration-journal', `${runId}.json`);
|
|
const journalPath = path.join(configDir, journalRelPath);
|
|
const rollbackRootRelPath = path.posix.join('gsd-migration-journal', `${runId}-rollback`);
|
|
const rollbackRoot = path.join(configDir, rollbackRootRelPath);
|
|
const backupRootRelPath = path.posix.join('gsd-migration-journal', `${runId}-backups`);
|
|
const backupRoot = path.join(configDir, backupRootRelPath);
|
|
const journal: { schemaVersion: number; appliedAt: string; appliedMigrationIds: string[]; actions: JournalAction[] } = {
|
|
schemaVersion: 1,
|
|
appliedAt,
|
|
appliedMigrationIds: uniqueActionMigrationIds(plan.actions),
|
|
actions: [],
|
|
};
|
|
const rollback: Array<{ relPath: string; rollbackPath: string }> = [];
|
|
const installStatePath = path.join(configDir, INSTALL_STATE_NAME);
|
|
const previousInstallStateBytes = fs.existsSync(installStatePath)
|
|
? fs.readFileSync(installStatePath, 'utf8')
|
|
: null;
|
|
|
|
try {
|
|
fs.mkdirSync(path.dirname(journalPath), { recursive: true });
|
|
platformWriteSync(journalPath, JSON.stringify(journal, null, 2) + '\n');
|
|
|
|
for (const action of plan.actions) {
|
|
if (
|
|
action.type !== 'remove-managed' &&
|
|
action.type !== 'backup-and-remove' &&
|
|
action.type !== 'rewrite-json' &&
|
|
action.type !== 'record-baseline' &&
|
|
action.type !== 'baseline-preserve-user'
|
|
) {
|
|
throw new Error(`unsupported migration action type: ${action.type}`);
|
|
}
|
|
|
|
const { normalized, fullPath } = ensureInsideConfig(configDir, action.relPath);
|
|
if (!fs.existsSync(fullPath)) {
|
|
journal.actions.push(journalAction(action, 'missing'));
|
|
continue;
|
|
}
|
|
|
|
if (action.type === 'record-baseline' || action.type === 'baseline-preserve-user') {
|
|
journal.actions.push(journalAction(action, action.type === 'record-baseline' ? 'recorded' : 'preserved'));
|
|
continue;
|
|
}
|
|
|
|
const rollbackPath = path.join(rollbackRoot, normalized);
|
|
fs.mkdirSync(path.dirname(rollbackPath), { recursive: true });
|
|
fs.copyFileSync(fullPath, rollbackPath);
|
|
rollback.push({ relPath: normalized, rollbackPath });
|
|
|
|
if (action.type === 'rewrite-json') {
|
|
if (action.deleteIfEmpty && isStructurallyEmpty(action.value)) {
|
|
fs.rmSync(fullPath, { force: true });
|
|
journal.actions.push(journalAction(action, 'removed', {
|
|
rollbackRelPath: path.posix.join(rollbackRootRelPath, normalized),
|
|
}));
|
|
} else {
|
|
platformWriteSync(fullPath, JSON.stringify(action.value, null, 2) + '\n');
|
|
journal.actions.push(journalAction(action, 'rewritten', {
|
|
rollbackRelPath: path.posix.join(rollbackRootRelPath, normalized),
|
|
}));
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (action.type === 'backup-and-remove') {
|
|
const backupRelPath = action.backupRelPath || path.posix.join(backupRootRelPath, normalized);
|
|
const backupPath = path.join(configDir, backupRelPath);
|
|
fs.mkdirSync(path.dirname(backupPath), { recursive: true });
|
|
fs.copyFileSync(fullPath, backupPath);
|
|
journal.actions.push(journalAction(action, 'removed', {
|
|
backupRelPath,
|
|
rollbackRelPath: path.posix.join(rollbackRootRelPath, normalized),
|
|
}));
|
|
} else {
|
|
journal.actions.push(journalAction(action, 'removed', {
|
|
rollbackRelPath: path.posix.join(rollbackRootRelPath, normalized),
|
|
}));
|
|
}
|
|
fs.rmSync(fullPath, { force: true });
|
|
}
|
|
|
|
platformWriteSync(journalPath, JSON.stringify(journal, null, 2) + '\n');
|
|
|
|
const state = readInstallState(configDir);
|
|
const applied = appliedMigrationIds(state);
|
|
const nextApplied = [...state.appliedMigrations];
|
|
const actionsByMigrationId = new Map<string, PlannedAction>();
|
|
for (const action of plan.actions) {
|
|
if (action.migrationId && !actionsByMigrationId.has(action.migrationId)) {
|
|
actionsByMigrationId.set(action.migrationId, action);
|
|
}
|
|
}
|
|
for (const id of journal.appliedMigrationIds) {
|
|
if (!applied.has(id)) {
|
|
const action = actionsByMigrationId.get(id);
|
|
nextApplied.push({
|
|
id,
|
|
appliedAt,
|
|
journal: journalRelPath,
|
|
checksum: action && action.migrationChecksum ? action.migrationChecksum : null,
|
|
});
|
|
}
|
|
}
|
|
writeInstallState(configDir, {
|
|
schemaVersion: 1,
|
|
appliedMigrations: nextApplied,
|
|
});
|
|
|
|
return {
|
|
appliedMigrationIds: journal.appliedMigrationIds,
|
|
journalRelPath,
|
|
rollback: () => rollbackAppliedMigrationResult({ configDir, journal, journalPath, rollbackRoot, backupRoot, previousInstallStateBytes }),
|
|
};
|
|
} catch (error) {
|
|
const rollbackFailures: Array<{ relPath: string; rollbackPath: string; error: string }> = [];
|
|
for (const entry of rollback.reverse()) {
|
|
const dest = path.join(configDir, entry.relPath);
|
|
try {
|
|
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
fs.copyFileSync(entry.rollbackPath, dest);
|
|
} catch (rollbackError) {
|
|
rollbackFailures.push({
|
|
relPath: entry.relPath,
|
|
rollbackPath: entry.rollbackPath,
|
|
error: (rollbackError as Error).message,
|
|
});
|
|
}
|
|
}
|
|
if (rollbackFailures.length > 0) {
|
|
const rollbackError = new Error(`migration apply failed and rollback incomplete: ${(error as Error).message}`) as Error & { cause: unknown; rollbackFailures: typeof rollbackFailures };
|
|
rollbackError.cause = error;
|
|
rollbackError.rollbackFailures = rollbackFailures;
|
|
throw rollbackError;
|
|
}
|
|
cleanupMigrationRunArtifacts(journalPath, rollbackRoot, backupRoot);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function markPendingMigrationsApplied({
|
|
configDir,
|
|
plan,
|
|
now = () => new Date().toISOString(),
|
|
}: {
|
|
configDir: string;
|
|
plan: MigrationPlan;
|
|
now?: () => string;
|
|
}): string[] {
|
|
if (!plan || !Array.isArray(plan.pendingMigrationIds) || plan.pendingMigrationIds.length === 0) {
|
|
return [];
|
|
}
|
|
const appliedAt = now();
|
|
const state = readInstallState(configDir);
|
|
const applied = appliedMigrationIds(state);
|
|
const checksumsByMigrationId = new Map<string, string>();
|
|
for (const migration of plan.pendingMigrations || []) {
|
|
checksumsByMigrationId.set(migration.id as string, migrationChecksum(migration));
|
|
}
|
|
const nextApplied = [...state.appliedMigrations];
|
|
const newlyApplied: string[] = [];
|
|
for (const id of plan.pendingMigrationIds) {
|
|
if (applied.has(id)) continue;
|
|
nextApplied.push({
|
|
id,
|
|
appliedAt,
|
|
journal: null,
|
|
checksum: checksumsByMigrationId.get(id) || null,
|
|
});
|
|
newlyApplied.push(id);
|
|
}
|
|
if (newlyApplied.length > 0) {
|
|
writeInstallState(configDir, {
|
|
schemaVersion: 1,
|
|
appliedMigrations: nextApplied,
|
|
});
|
|
}
|
|
return newlyApplied;
|
|
}
|
|
|
|
interface RunResult {
|
|
appliedMigrationIds: string[];
|
|
journalRelPath: string | null;
|
|
plan: MigrationPlan;
|
|
blocked?: PlannedAction[];
|
|
rollback?: () => void;
|
|
}
|
|
|
|
function runInstallerMigrations({
|
|
configDir,
|
|
runtime = null,
|
|
scope = null,
|
|
migrationsDir = DEFAULT_MIGRATIONS_DIR,
|
|
migrations = discoverInstallerMigrations({ migrationsDir }),
|
|
baselineScan = false,
|
|
now = () => new Date().toISOString(),
|
|
lockTimeoutMs = DEFAULT_LOCK_TIMEOUT_MS,
|
|
}: {
|
|
configDir: string;
|
|
runtime?: string | null;
|
|
scope?: string | null;
|
|
migrationsDir?: string;
|
|
migrations?: MigrationRecord[];
|
|
baselineScan?: boolean;
|
|
now?: () => string;
|
|
lockTimeoutMs?: number;
|
|
} = { configDir: '' }): RunResult {
|
|
const releaseLock = acquireInstallMigrationLock(configDir, { timeoutMs: lockTimeoutMs });
|
|
let primaryError: (Error & { suppressed?: Error[] }) | null = null;
|
|
let completed = false;
|
|
try {
|
|
const plan = planInstallerMigrations({ configDir, runtime, scope, migrations, baselineScan, now });
|
|
if (plan.actions.length === 0) {
|
|
const newlyApplied = markPendingMigrationsApplied({ configDir, plan, now });
|
|
completed = true;
|
|
return {
|
|
appliedMigrationIds: newlyApplied,
|
|
journalRelPath: null,
|
|
plan,
|
|
};
|
|
}
|
|
if (plan.blocked.length > 0) {
|
|
completed = true;
|
|
return {
|
|
appliedMigrationIds: [],
|
|
journalRelPath: null,
|
|
plan,
|
|
blocked: plan.blocked,
|
|
};
|
|
}
|
|
const result = applyInstallerMigrationPlan({ configDir, plan, now });
|
|
completed = true;
|
|
return { ...result, plan };
|
|
} catch (error) {
|
|
primaryError = error as Error & { suppressed?: Error[] };
|
|
throw error;
|
|
} finally {
|
|
try {
|
|
releaseLock();
|
|
} catch (releaseError) {
|
|
if (primaryError) {
|
|
primaryError.suppressed = [...(primaryError.suppressed || []), releaseError as Error];
|
|
} else if (completed) {
|
|
throw releaseError;
|
|
} else {
|
|
throw releaseError;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Unused but kept to satisfy eslint — sleepSync is referenced in the original
|
|
// and may be used by test code that patches this module.
|
|
void sleepSync;
|
|
|
|
export = {
|
|
DEFAULT_MIGRATIONS_DIR,
|
|
INSTALL_MIGRATION_LOCK_NAME,
|
|
INSTALL_STATE_NAME,
|
|
MANIFEST_NAME,
|
|
acquireInstallMigrationLock,
|
|
applyInstallerMigrationPlan,
|
|
classifyArtifact,
|
|
discoverInstallerMigrations,
|
|
planInstallerMigrations,
|
|
readInstallManifest,
|
|
readInstallState,
|
|
runInstallerMigrations,
|
|
writeInstallState,
|
|
};
|