Starfield 1.16.244 (Steam) · reverse engineering plus an in-game test · checked 2026-11-21 · page built 2026-12-03 23:56 UTC

Do Vortex mods and Creations really have separate load orders?

A Facebook comment claimed that Vortex mods load through the script extender, that Creations load when you load a save, and that this gives Starfield two load orders. We checked the claim twice: by reading the game's own code, and by watching Plugins.txt in the game step by step. This page shows every step, what each one found, and how you can repeat the test on your own PC.

1load order: Creations and other plugins share one Plugins.txt
0times Plugins.txt changed when a save was loaded (Continue and Load)
2places in Starfield.exe that rewrite Plugins.txt: the Creations sync and the Creations menu
7in-game snapshots, including a control step that proved the test catches a rewrite

Richard is modding

What's new

  • 2026-12-03. The page now has a Richard is modding panel that links to Richard's mods at Creations and Nexus Mods, and to Help Richard Help You.
  • 2026-11-29. The page now has the same look as the other Richard Presents pages. The menu is a little wider so long links fit on one line, What's new comes right after the numbers at the top, and the footer is laid out like the other pages.
  • 2026-11-24. The MO2 notes were corrected: MO2 never deploys, MO2 users run the test with MO2 closed and the default folders, and the snapshot script reads ContentCatalog.txt from its own folder (-CatalogDir) instead of the Plugins.txt folder, because an MO2 profile holds no copy of it.
Earlier changes (1)
  • 2026-11-21. This page went live, with the code check, the in-game test, the scripts and the verdicts.

TL;DR

I tested this. I RE'd the game's code (Starfield.exe 1.16.244) and snapshotted Plugins.txt in game during a series of tests.

  • Starfield reads Plugins.txt itself at startup, so Vortex and MO2 plugins load without SFSE. SFSE is for DLL plugins.
  • Creations aren't loaded from your save. They're in the same Plugins.txt as your other mods: one list, one load order.
  • Loading a save (Continue or Load) didn't change Plugins.txt at all. A save only records which plugins it used.
  • The game does rewrite Plugins.txt at every launch and when you reorder Creations in game. In my test it kept every mod and only moved what I moved.

The conflict isn't two load orders. It's two tools editing one file: if you reorder in game and your mod manager later deploys its own order, one undoes the other. Manage the order in one place.

This is Richard's reply to the comment, word for word. The rest of the page shows the evidence behind each sentence.

The claim

Vortex mods load when you start the game via the script extender. Creations load when you load the character save. This means load orders are managed seperatly. This is what creates most conflicts. I make mods and this is something that we must account for.

The comment was posted on Facebook by a mod author. We quote it as written. It makes three testable claims: Vortex mods depend on the script extender, Creations load from the save, and the two have separate load orders.

Verdict, claim by claim

ClaimVerdictEvidence
Vortex mods load via the script extender.FalseStarfield.exe has its own Plugins.txt reader, and the game's startup code calls it. SFSE describes itself as mostly a loader for its own DLL plugins. SFSE also only supports the Steam version, yet Game Pass players load mods from Plugins.txt too.
Creations load when you load the character save.FalseCreations are plugin files in the Data folder, listed in the same Plugins.txt. The game reads that list at startup, before the main menu. In the test, loading two different saves didn't touch Plugins.txt.
Load orders are managed separately.FalseThere's one list in the game and one file on disk. The Creations code looks up each Creation's plugin in the same file list as every other plugin, writes them all to the same Plugins.txt, and rebuilds the list from it.
This is what creates most conflicts.Partly trueThere is a real conflict, but it comes from two tools editing one file. The game rewrites Plugins.txt at every launch and after an in-game reorder. Vortex writes its own order into Plugins.txt when it deploys. MO2 never deploys: it keeps its own plugins.txt in its profile and normally shows that copy to the game when you start the game from MO2 (see Limits for the exception).
We must account for it.TrueManage the order in one place, and check it again after you change Creations in the game.
What happens to Plugins.txt from launch to loading a save, as the code and the test showed.
1 Start the game You launch Starfield from Steam, Game Pass or a mod manager. 2 Read the INI files The start-up code reads Starfield.ini, StarfieldCustom.ini and StarfieldPrefs.ini. 3 Read Plugins.txt The game's own reader takes every line that starts with * as an active plugin. 4 Creations sync The Creations code matches each Creation's plugin to the same file list. 5 Rewrite Plugins.txt The game deletes the file and writes it again from its list. Comments are dropped. 6 Main menu All plugins are loaded now, Creations and Vortex mods alike, in one order. 7 Load a save The game compares the save's plugin list with what is loaded. Plugins.txt is untouched. 8 One load order One list in memory and one file on disk. Change it in one place.
the playerStarfield.exefiles on diskwhat it means

Complete conclusion

  • There is one load order. Starfield keeps one list of plugins and one file on disk, Plugins.txt. Creations are ordinary plugin files in the Data folder, and they sit in that list with every other plugin. ContentCatalog.txt only records which Creations are installed.
  • The game reads Plugins.txt itself, at startup. The reader is part of Starfield.exe and runs from the game's start-up code. The script extender isn't needed for .esm, .esp or .esl plugins. SFSE loads DLL plugins.
  • Loading a save doesn't load or reorder plugins. Continue and Load left Plugins.txt untouched. A save only records which plugins it used, so the game can warn you when one is missing.
  • The game rewrites Plugins.txt at every launch, before the main menu, and again whenever you change Creations in the in-game menu. In the test, both rewrites kept every plugin. The launch rewrite changed nothing, and the menu rewrite moved only what was moved. Anything that isn't a plugin line, such as a comment, is dropped.
  • The real conflict is two tools editing one file. If you reorder in the game and Vortex later deploys its own order, the last one to write wins. MO2 doesn't deploy. It keeps its own plugins.txt in its profile, so a reorder made in a game started without MO2 goes into a file MO2 doesn't use. Manage the order in one place, and check it again after you change Creations in the game.
The comment's model of loading compared with what we found.
What the comment says • Vortex mods load through SFSE at launch • Creations load when a save loads • Two load orders, managed separately • Conflicts come from the two orders What the code and the test show • Starfield.exe reads Plugins.txt itself at launch • Creations load at launch, from the same list • One load order in one file • Conflicts come from two tools writing one file

What we used

Every tool here only reads. Nothing changed the game files. The only file written was a comment line added to Plugins.txt for the test, after a backup.

ToolKindWhat it isUsed for
Starfield.exe 1.16.244Game fileThe Steam game executable, the version the test ran on.The code under study. Read only, never changed.
Ghidra 12.1.2Public toolThe NSA's free reverse-engineering tool.Disassembling and decompiling Starfield.exe.
Bethesda Ghidra ScriptsPublic toolCommunity scripts that name Starfield's classes and functions in Ghidra from public data (RTTI and CommonLibSF).Names such as TESDataHandler, MainMenu and UserContent.
GhidraSQL 0.0.8Public toolElias Bachaalany's SQL interface to a Ghidra project.Read-only queries: strings, cross-references, callers and decompiled functions.
PluginsTxtSnapshot.ps1Our scriptA short PowerShell script written for this test (on this page).Copying Plugins.txt, ContentCatalog.txt and StarfieldCustom.ini, with times and checksums, after each in-game step.
compare_snapshots.pyOur scriptA short Python script written for this test (on this page).Comparing the steps: rewrites, line changes and catalog fields.
How we checked: first the code, then the game itself.
1 The claim A comment said Vortex mods and Creations load at different times, in different orders. 2 Strings Find where Starfield.exe names Plugins.txt and ContentCatalog.txt. 3 Reader and writer Decompile the two Plugins.txt functions and see what each one does. 4 Callers Trace each function back to start- up, the Creations code and the main menu. 5 Snapshot script Copy the load-order files, with times and checksums, after each in-game step. 6 Marker line Add a comment line the game ignores but drops on a rewrite. 7 Seven steps Start, look at Creations, Continue, Load, quit, then reorder a Creation. 8 Verdict One load order. Rewrites at launch and on reorder, not on save load.
the playerStarfield.exefiles on diskwhat it means

Part 1: the game's code

We loaded Starfield.exe 1.16.244, the same build the test ran on, into Ghidra with the Bethesda Ghidra Scripts names, and queried it read-only with GhidraSQL. The addresses below are for that build and will move in other versions. The page describes what the code does and shows none of it.

  1. 1

    Find the file names in the executable

    Game file

    What we did. We searched Starfield.exe's strings for the load-order file names and the old INI settings.

    What it showed. The executable holds %sPlugins.txt, %sContentCatalog.txt, the ten sTestFile1 to sTestFile10 settings of the [General] INI section (the old way to load a plugin without Plugins.txt) and bInvalidateOlderFiles. Two functions use the Plugins.txt name, and one uses the ContentCatalog.txt name.

  2. 2

    Read the first Plugins.txt function: the reader

    Game file

    What we did. We decompiled the function at 0x140425310.

    What it showed. It opens Plugins.txt for reading and reads it a line at a time. It skips lines that start with # and lines that are too short. When it's asked for active plugins only, it keeps only lines that start with * and drops the star. It adds each remaining name to the game's list of files. This is the game's own code, not the script extender's.

  3. 3

    Follow the reader back to startup

    Game file

    What we did. We listed the reader's callers, then their callers, until we reached code we could identify.

    What it showed. One path starts in the game's start-up function (0x141898870), the same function that reads Starfield.ini, StarfieldCustom.ini and StarfieldPrefs.ini and checks the storefront. A second path runs through the function that loads Starfield.esm (0x141883440) and the function that builds TESDataHandler's file list (0x140598750). Both run when the game starts, before any save is loaded.

  4. 4

    Read the second Plugins.txt function: the writer

    Game file

    What we did. We decompiled the function at 0x140424dc0.

    What it showed. It clears the file's read-only flag, deletes Plugins.txt and creates a new one. It writes the two-line header ("This file is used by Starfield to keep track of your downloaded content. Please do not modify this file."), then one line per plugin in the list it is given, with a * in front of active ones. It skips TestData.esm and the game's built-in files. Anything else in the old file, such as a comment line, is gone after a rewrite.

  5. 5

    Find who calls the writer

    Game file

    What we did. We listed every caller of the writer.

    What it showed. There are exactly two. One is the Creations sync (0x14218bb40) in the game's UserContent code, which has eight callers of its own. The other is a menu function (0x141ecdc70) reached from MainMenu: the Creations menu on the main menu. No other code writes Plugins.txt.

  6. 6

    Read the Creations sync

    Game file

    What we did. We decompiled the Creations sync.

    What it showed. For each Creation, it takes the Creation's .esm, .esp or .esl files and looks each one up in TESDataHandler's list, the same list that holds every other plugin. Then it calls the writer and runs the list builder again, so the new order takes effect. Creations and manually installed plugins share one list and one file.

  7. 7

    Check ContentCatalog.txt

    Game file

    What we did. We followed the ContentCatalog.txt name to its function (0x142183f00).

    What it showed. It belongs to the same UserContent code, next to a function that names the Creations data folder. ContentCatalog.txt is a JSON file that records which Creations are installed (title, version, files, timestamp). It doesn't hold the load order.

  8. 8

    Look for a path from loading a save

    Game file

    What we did. We looked for any path from save loading to the writer.

    What it showed. We found none, and a save only stores the list of plugins it was made with. Code alone can't rule out every indirect call, so the in-game test checked this directly.

Part 2: the in-game test

The code showed what can happen. The test showed what does happen. A script copied Plugins.txt, ContentCatalog.txt and StarfieldCustom.ini after each step, along with each file's modified time and SHA256 checksum. Vortex was closed for the whole test, so only the game could change the files.

The marker line. Before the first launch the script added one comment line to Plugins.txt. The game's reader skips lines that start with #, so the line is harmless. The writer only writes its own header and plugin lines, so if the marker vanished, the game had rewritten the file. After the marker was gone, the file's modified time was the signal, because the writer deletes the file and creates it again.

The control. Step 06 reorders a Creation, which the code says must rewrite the file. It did. That shows the test can see a rewrite when one happens, so the quiet steps really were quiet.

StepWhat the player didPlugins.txtContentCatalog.txt
00Snapshot with the game closed, adding the marker lineMarker added-
01Start the game from Steam and wait at the main menuRewritten before the menu appeared. Only the marker line was dropped. All 149 active plugins kept their order.Not changed
02Open Creations, look at the load order, back out without changing anythingNot rewrittenNot changed
03Press Continue and wait until in the gameNot rewrittenRewritten: only every Creation's Timestamp field changed
04Load a different save from the Load menuNot rewrittenNot changed
05Quit to the desktopNot rewrittenNot changed
06Start again, open Creations, move one Creation, back outRewritten: only the moved Creation's line changed placeNot changed

All times were on 2026-11-21. Plugins.txt was rewritten at 16:17:10 (launch) and 16:21:37 (reorder) and at no other time. ContentCatalog.txt was rewritten once, at 16:18:45, while Continue loaded the save. The only change was that every Creation entry's Timestamp field was set to that moment.

Limits

  • The test ran once, on one PC, with the Steam version 1.16.244, Vortex closed, and one set of installed Creations.
  • We didn't test what Vortex does on its next deploy after an in-game reorder, or what MO2 does when the game reorders the plugins.txt that MO2 gave it. That's where two managers would really fight.
  • MO2 never deploys. It normally gives the game its own copy of Plugins.txt through its virtual file system, so the file this script reads may not be the one the game sees when you start it from MO2. The exception is sTestFile lines in StarfieldCustom.ini, which turn MO2's plugin management off. MO2 leaves ContentCatalog.txt in %LOCALAPPDATA%\Starfield and keeps no copy in the profile. We checked these MO2 points in the source of MO2 2.5.2 and of the 2.5.3 betas of 2026-05-23 (modorganizer and modorganizer-game_bethesda) on 2026-11-24. The two versions behave the same on these points. We didn't test them in a run.
  • We didn't test the Game Pass version or a Plugins.txt line for a plugin file that's missing.
  • We didn't trace all eight callers of the Creations sync, so other moments may also trigger a rewrite. The launch rewrite is the one the test caught.

What this means for your mod setup

  • Pick one place to manage the order: your mod manager or the in-game Creations menu, not both.
  • After you change Creations in the game, open your mod manager and check the order before you play. MO2 shows only its own profile copy, so a reorder made in a game started from Steam won't appear there. With Vortex, you can also deploy again to put back Vortex's order.
  • Don't put notes in Plugins.txt. The game deletes comment lines when it rewrites the file.
  • If a save says content is missing, the fix is in Plugins.txt and the Data folder, not in the save. The save only lists what it was made with.

Run it yourself

You need Windows PowerShell (built into Windows) and, for the comparison, Python 3.9 or later. Save both scripts from this page (or from the repository) in one folder. Close Vortex or MO2 first, so only the game can change the files. Run the snapshot script from the Windows account you play on. Its output goes to PluginsTxtTest on your Desktop unless you add -OutDir.

# 0. Before starting the game: first snapshot, and add the marker line
powershell -ExecutionPolicy Bypass -File .\PluginsTxtSnapshot.ps1 00-start -AddMarker

# After each step in the game, Alt-Tab out and take a snapshot
powershell -ExecutionPolicy Bypass -File .\PluginsTxtSnapshot.ps1 01-menu
powershell -ExecutionPolicy Bypass -File .\PluginsTxtSnapshot.ps1 02-creations-look
powershell -ExecutionPolicy Bypass -File .\PluginsTxtSnapshot.ps1 03-continue
powershell -ExecutionPolicy Bypass -File .\PluginsTxtSnapshot.ps1 04-load-save
powershell -ExecutionPolicy Bypass -File .\PluginsTxtSnapshot.ps1 05-quit
powershell -ExecutionPolicy Bypass -File .\PluginsTxtSnapshot.ps1 06-creations-change

# Then compare the steps
python compare_snapshots.py

Here is part of the comparison from our test:

===== 00-start -> 01-menu
Plugins.txt: rewritten (lines added or removed)
    -# PluginsTxtSnapshot marker - safe to delete
ContentCatalog.txt: not changed
===== 02-creations-look -> 03-continue
Plugins.txt: not rewritten
ContentCatalog.txt: changed
    (one line for each installed Creation: its ID, then "Timestamp changed")
===== 03-continue -> 04-load-save
Plugins.txt: not rewritten
ContentCatalog.txt: not changed

If a result looks wrong, add -Verbose to a snapshot command. It prints and logs each file it read or couldn't find to snapshot.log in the output folder. python compare_snapshots.py --verbose writes compare.log there too.

Afterward, Vortex users deploy again to put back Vortex's order. The marker line is harmless if it's still there. The Plugins.txt you had when the test started is saved as Plugins.txt.backup in the output folder. When you start a new test in the same folder, the earlier test's backup and step folders move into a dated earlier-test-... folder, so the two tests never mix.

MO2 users: MO2 never deploys, and it keeps its own plugins.txt in its profile. Close MO2, start the game from Steam and keep the default folders. If you have only ever started the game from MO2, start it once from Steam before the first snapshot, so the game creates its own Plugins.txt. That tests the game itself: the game then reads %LOCALAPPDATA%\Starfield\Plugins.txt, MO2's profile copy isn't touched, and there is nothing to put back afterward. With MO2 closed, the game doesn't see the mods in MO2's own folders, so a save may report missing content: use a throwaway character, or don't save during the test. We haven't tested a run started from MO2, where MO2 shows the game its profile copy and can rewrite that file itself, so a changed file there wouldn't prove the game changed it. ContentCatalog.txt stays in %LOCALAPPDATA%\Starfield under MO2 too.

PluginsTxtSnapshot.ps1 (MIT license)
<#
.SYNOPSIS
  Copy Starfield's load-order files after one test step, with times and checksums.

.DESCRIPTION
  Copies Plugins.txt and ContentCatalog.txt (by default from %LOCALAPPDATA%\Starfield) and StarfieldCustom.ini (by
  default from Documents\My Games\Starfield) into <OutDir>\<Step>\, and writes info.txt there with each file's modified time,
  size and SHA256. It only reads those files, except with -AddMarker.

  -AddMarker (use it on the first step only) backs up Plugins.txt to <OutDir>\Plugins.txt.backup, then adds one
  comment line. The game ignores lines that start with #, but when it rewrites Plugins.txt it writes only its own
  header and plugin lines, so the marker disappearing means the game rewrote the file. If the marker is still in
  Plugins.txt, the test is already running: the marker isn't added twice, and the backup is kept (or made from the
  file without the marker if it's missing). Otherwise a new test starts: the earlier test's backup and step folders
  move into <OutDir>\earlier-test-<date and time>, and a fresh backup is made.

  -PluginsDir, -CatalogDir and -IniDir change where Plugins.txt, ContentCatalog.txt and StarfieldCustom.ini are
  read from. MO2 users: close MO2 and keep the defaults. MO2 (2.5.2 and the 2.5.3 betas) never deploys, keeps its
  own plugins.txt in its profile, and keeps no copy of ContentCatalog.txt there.

  Run it from the Windows account you play on: it reads that account's own folders.

.EXAMPLE
  powershell -ExecutionPolicy Bypass -File .\PluginsTxtSnapshot.ps1 00-start -AddMarker

.EXAMPLE
  powershell -ExecutionPolicy Bypass -File .\PluginsTxtSnapshot.ps1 01-menu -Verbose
#>
[CmdletBinding()]
param(
  [Parameter(Mandatory = $true, Position = 0)][string]$Step,
  [switch]$AddMarker,
  [string]$OutDir = (Join-Path ([Environment]::GetFolderPath('Desktop')) 'PluginsTxtTest'),
  # Folder that holds Plugins.txt.
  [string]$PluginsDir = (Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'Starfield'),
  # Folder that holds ContentCatalog.txt.
  [string]$CatalogDir = (Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'Starfield'),
  # Folder that holds StarfieldCustom.ini.
  [string]$IniDir = (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'My Games\Starfield')
)
$ErrorActionPreference = 'Stop'
$inv = [Globalization.CultureInfo]::InvariantCulture
$timeFmt = 'yyyy-MM-dd HH\:mm\:ss'   # literal colons on every regional setting (compare_snapshots.py reads them)
$log = Join-Path $OutDir 'snapshot.log'
# Every path goes through -LiteralPath, so [ and ] in a user name or folder are not read as wildcards.

function Write-Log([string]$Text) {
  Write-Verbose $Text
  if ($VerbosePreference -ne 'SilentlyContinue') {
    try {
      if (-not (Test-Path -LiteralPath $OutDir)) { New-Item -ItemType Directory -Force -Path $OutDir | Out-Null }
      Add-Content -LiteralPath $log -Value "$((Get-Date).ToString($timeFmt, $inv)) [$Step] $Text"
    } catch { Write-Verbose "Could not write ${log}: $($_.Exception.Message)" }
  }
}

function Stop-Snapshot([string]$Text, [int]$Code) {
  [Console]::Error.WriteLine("PluginsTxtSnapshot: $Text")
  Write-Log "FAILED (exit $Code): $Text"
  exit $Code
}

$reserved = '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\..*)?$'
$ownFiles = '^(snapshot\.log|compare\.log|Plugins\.txt\.backup.*)$'
if ($Step -notmatch '^[A-Za-z0-9._-]+$' -or $Step -notmatch '[A-Za-z0-9]' -or $Step.EndsWith('.') -or
    $Step -match $reserved -or $Step -match $ownFiles) {
  Stop-Snapshot ("step name '$Step' must use letters, digits, dots, dashes and underscores, contain a letter or " +
                 "digit, not end with a dot, and not be a reserved Windows name (such as CON) or a file name this " +
                 "script uses (snapshot.log, Plugins.txt.backup). Example: 01-menu.") 2
}

$app   = $PluginsDir
$docs  = $IniDir
$latin1 = [Text.Encoding]::GetEncoding(28591)   # maps every byte to one character and back unchanged
$files = @(
  (Join-Path $app  'Plugins.txt'),
  (Join-Path $catalogDir 'ContentCatalog.txt'),
  (Join-Path $docs 'StarfieldCustom.ini')
)
$plugins = $files[0]
$marker  = '# PluginsTxtSnapshot marker - safe to delete'
$out     = Join-Path $OutDir $Step

try {
  New-Item -ItemType Directory -Force -Path $out | Out-Null
} catch {
  Stop-Snapshot "could not create $out ($($_.Exception.Message)). Pick another folder with -OutDir." 1
}

function Test-Marker([string]$Path) {
  # True or False, or 'unknown' when the file is missing or can't be read.
  try {
    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return 'unknown' }
    return [bool]((Get-Content -LiteralPath $Path) | Where-Object { $_.Trim() -eq $marker })
  } catch { return 'unknown' }
}

Write-Log "Output folder: $out"
Write-Log "Reading Plugins.txt from $app; ContentCatalog.txt from $catalogDir; StarfieldCustom.ini from $docs"

if ($AddMarker) {
  if (-not (Test-Path -LiteralPath $plugins -PathType Leaf)) {
    Stop-Snapshot "no Plugins.txt at $plugins. Start Starfield once from Steam (with MO2 closed) so the game creates the file, then run this again." 1
  }
  $backup = Join-Path $OutDir 'Plugins.txt.backup'
  $hasMarker = Test-Marker $plugins
  if ($hasMarker -is [string]) {   # 'unknown' (a plain -eq would also match $true)
    Stop-Snapshot "could not read $plugins. Close the game and your mod manager, then try again." 1
  }
  try {
    if ($hasMarker) {
      Write-Host "The marker line is already in Plugins.txt, so this test is still running: the marker isn't added again."
      if (Test-Path -LiteralPath $backup -PathType Leaf) {
        Write-Host "Kept the backup at $backup."
        Write-Log "Marker already present; backup kept"
      } else {
        # No backup here (new folder, or it was deleted): save the file without the marker line, which is the original.
        # Remove only the marker line, byte for byte, so the encoding and line endings stay as they were.
        $text = [IO.File]::ReadAllText($plugins, $latin1)
        $orig = [regex]::Replace($text, '(?m)^[ \t]*' + [regex]::Escape($marker) + '[ \t]*(\r?\n|$)', '')
        [IO.File]::WriteAllText($backup, $orig, $latin1)
        Write-Host ("No backup was in this folder, so saved Plugins.txt without the marker line to $backup. It matches " +
                    "the original unless the original's last line had no line break (the game always writes one).")
        Write-Log "Marker already present; backup made from the file without the marker"
      }
    } else {
      # A new test starts: move the earlier test's backup and step folders into a dated folder, so the
      # comparison never mixes two tests. (compare_snapshots.py only reads folders that hold info.txt.)
      $earlierSteps = @(Get-ChildItem -LiteralPath $OutDir -Directory |
                        Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName 'info.txt') })
      if ((Test-Path -LiteralPath $backup) -or $earlierSteps.Count -gt 0) {
        $stamp = (Get-Date).ToString('yyyyMMdd-HHmmss', $inv)
        $archive = Join-Path $OutDir "earlier-test-$stamp"
        $n = 1
        while (Test-Path -LiteralPath $archive) { $archive = Join-Path $OutDir "earlier-test-$stamp-$n"; $n++ }
        New-Item -ItemType Directory -Path $archive | Out-Null
        if (Test-Path -LiteralPath $backup) { Move-Item -LiteralPath $backup -Destination $archive }
        foreach ($d in $earlierSteps) { Move-Item -LiteralPath $d.FullName -Destination $archive }
        New-Item -ItemType Directory -Force -Path $out | Out-Null
        Write-Host "Moved the earlier test's backup and $($earlierSteps.Count) step folder(s) to $archive."
        Write-Log "Earlier test moved to $archive"
      }
      Copy-Item -LiteralPath $plugins -Destination $backup
      Write-Host "Backed up Plugins.txt to $backup."
      Write-Log "Backup written to $backup"
      # Start the marker on its own line even when the file doesn't end with a line break.
      $bytes = [IO.File]::ReadAllBytes($plugins)
      $prefix = if ($bytes.Length -gt 0 -and $bytes[-1] -ne 10) { "`r`n" } else { '' }
      [IO.File]::AppendAllText($plugins, "$prefix$marker`r`n")
      Write-Host "Added the marker line."
      Write-Log "Marker added"
    }
  } catch {
    Stop-Snapshot "could not back up or mark $plugins ($($_.Exception.Message)). Close the game and your mod manager, then try again." 1
  }
}

$info = @(
  "Step: $Step",
  "Taken: $((Get-Date).ToString($timeFmt, $inv))",
  "Starfield running: $([bool](Get-Process Starfield -ErrorAction SilentlyContinue))",
  "Vortex running: $([bool](Get-Process Vortex -ErrorAction SilentlyContinue))",
  "Mod Organizer running: $([bool](Get-Process ModOrganizer -ErrorAction SilentlyContinue))",
  ""
)
foreach ($f in $files) {
  $name = Split-Path $f -Leaf
  $copy = Join-Path $out $name
  # Remove a copy left by an earlier run of this step, so a failed read never leaves stale text behind.
  if (Test-Path -LiteralPath $copy) { Remove-Item -LiteralPath $copy -Force -ErrorAction SilentlyContinue }
  if (Test-Path -LiteralPath $f -PathType Leaf) {
    try {
      Copy-Item -LiteralPath $f -Destination $copy -Force
      # Time, size and hash all come from the copy (Copy-Item keeps the modified time), so they always match.
      $i = Get-Item -LiteralPath $copy
      $line = "${name}: modified $($i.LastWriteTime.ToString($timeFmt, $inv)), ticks $($i.LastWriteTimeUtc.Ticks), $($i.Length) bytes, SHA256 $((Get-FileHash -LiteralPath $copy).Hash)"
      Write-Log "Copied $f"
    } catch {
      if (Test-Path -LiteralPath $copy) { Remove-Item -LiteralPath $copy -Force -ErrorAction SilentlyContinue }
      $line = "${name}: could not read ($($_.Exception.Message)); take this step's snapshot again"
      Write-Log "Could not read ${f}: $($_.Exception.Message)"
    }
  } else {
    $line = "${name}: not found at $f"
    Write-Log "Not found: $f"
  }
  $info += $line
}
$info += '', "Marker line present: $(Test-Marker (Join-Path $out 'Plugins.txt'))"
$infoFile = Join-Path $out 'info.txt'
try {
  Set-Content -LiteralPath $infoFile -Value $info
} catch {
  Stop-Snapshot "could not write $infoFile ($($_.Exception.Message)). Check that the drive has space and isn't read-only, or pick another folder with -OutDir." 1
}
$info | ForEach-Object { Write-Host $_ }
Write-Host "Saved to $out"
exit 0
compare_snapshots.py (MIT license)
"""Compare the step folders made by PluginsTxtSnapshot.ps1.

Each step is a folder holding info.txt. Steps are taken in the order of their number prefix (2-x before 10-x).
For each pair of steps it reports:
  - whether Plugins.txt was rewritten (its modified time changed) and how its lines changed,
  - whether ContentCatalog.txt changed, field by field.

Usage:
  python compare_snapshots.py [FOLDER] [--verbose]

FOLDER defaults to PluginsTxtTest on your Desktop. --verbose also writes compare.log in FOLDER.
Exit codes: 0 compared; 1 folder missing or fewer than two steps; 2 wrong arguments.
It only reads the snapshot folders.
"""
import argparse
import difflib
import json
import os
import re
import sys
from pathlib import Path

LOG = []
MISSING = object()


def log(msg):
    LOG.append(msg)


def lines(p):
    if not p.exists():
        return None
    return p.read_text(encoding="utf-8", errors="replace").splitlines()


def mtime(step, name):
    info = step / "info.txt"
    if not info.exists():
        return None
    m = re.search(re.escape(name) + r": modified ([0-9-]+ [0-9:]+)(?:, ticks (\d+))?",
                  info.read_text(encoding="utf-8", errors="replace"))
    if not m:
        return None
    # (ticks or None, time text). Ticks are 100-nanosecond units; older snapshots only have whole seconds.
    return m.group(2), m.group(1)


def same_time(ta, tb):
    """Compare by ticks when both steps recorded them, otherwise by the whole-second time text."""
    if ta[0] and tb[0]:
        return ta[0] == tb[0]
    return ta[1] == tb[1]


def desktop():
    """The real Desktop folder (OneDrive can move it), as PluginsTxtSnapshot.ps1 finds it."""
    if os.name == "nt":
        try:
            import ctypes
            from ctypes import wintypes

            class GUID(ctypes.Structure):
                _fields_ = [("d1", wintypes.DWORD), ("d2", wintypes.WORD), ("d3", wintypes.WORD),
                            ("d4", ctypes.c_ubyte * 8)]

            fid = GUID(0xB4BFCC3A, 0xDB2C, 0x424C, (ctypes.c_ubyte * 8)(0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41))
            path = ctypes.c_wchar_p()
            if ctypes.windll.shell32.SHGetKnownFolderPath(ctypes.byref(fid), 0, None, ctypes.byref(path)) == 0:
                result = path.value
                ctypes.windll.ole32.CoTaskMemFree(path)
                if result:
                    return Path(result)
        except (OSError, AttributeError):
            pass
    return Path(os.path.expanduser("~")) / "Desktop"


def step_key(p):
    """Sort steps by their number prefix (2-x before 10-x), then by name."""
    m = re.match(r"(\d+)", p.name)
    return (int(m.group(1)) if m else float("inf"), p.name)


def catalog_diff(pa, pb):
    try:
        ja = json.loads(pa.read_text(encoding="utf-8-sig"))
        jb = json.loads(pb.read_text(encoding="utf-8-sig"))
    except (OSError, ValueError) as ex:
        return [f"    could not read as JSON ({ex}); compare the two files by hand"]
    if not isinstance(ja, dict) or not isinstance(jb, dict):
        return ["    not the expected JSON object; compare the two files by hand"]
    out = []
    for k in sorted(set(ja) | set(jb)):
        va, vb = ja.get(k, MISSING), jb.get(k, MISSING)
        if va == vb:
            continue
        if isinstance(va, dict) and isinstance(vb, dict):
            fields = [f for f in sorted(set(va) | set(vb)) if va.get(f, MISSING) != vb.get(f, MISSING)]
            out.append(f"    {k}: {', '.join(fields) or 'entry'} changed")
        else:
            out.append(f"    {k}: {'added' if va is MISSING else 'removed' if vb is MISSING else 'changed'}")
    return out


def changed_lines(pa, pb):
    """The removed (-) and added (+) lines, from the diff's change blocks only (no file headers)."""
    out = []
    for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(a=pa, b=pb, autojunk=False).get_opcodes():
        if tag in ("delete", "replace"):
            out += ["-" + x for x in pa[i1:i2]]
        if tag in ("insert", "replace"):
            out += ["+" + x for x in pb[j1:j2]]
    return out


def compare(a, b):
    print(f"===== {a.name} -> {b.name}")
    ta, tb = mtime(a, "Plugins.txt"), mtime(b, "Plugins.txt")
    pa, pb = lines(a / "Plugins.txt"), lines(b / "Plugins.txt")
    log(f"{a.name} -> {b.name}: Plugins.txt modified {ta} -> {tb}")
    if pa is None or pb is None:
        print("Plugins.txt: missing from one of the steps")
    elif ta is None or tb is None:
        which = " and ".join(s.name for s, t in ((a, ta), (b, tb)) if t is None)
        print(f"Plugins.txt: modified time unknown for {which} (see info.txt there); can't tell whether it was "
              "rewritten. Take that step's snapshot again.")
    else:
        rewritten = not same_time(ta, tb)
        if pa == pb:
            print(f"Plugins.txt: {'rewritten (new modified time), same text' if rewritten else 'not rewritten'}")
        elif not rewritten:
            print(f"Plugins.txt: text differs but the modified time didn't change ({ta[1]}); one copy may have been "
                  "taken while the file was being written. Compare the two copies by hand:")
            for d in changed_lines(pa, pb):
                print("   ", d)
        else:
            strip = lambda ls: [x.lstrip("*") for x in ls]
            if sorted(pa) == sorted(pb):
                kind = "same lines, new order"
            elif strip(pa) == strip(pb):
                kind = "plugins enabled or disabled"
            elif sorted(strip(pa)) == sorted(strip(pb)):
                kind = "plugins enabled or disabled, and order changed"
            else:
                kind = "lines added or removed"
            print(f"Plugins.txt: rewritten ({kind})")
            for d in changed_lines(pa, pb):
                print("   ", d)
    ca, cb = a / "ContentCatalog.txt", b / "ContentCatalog.txt"
    if ca.exists() and cb.exists():
        if ca.read_bytes() == cb.read_bytes():
            print("ContentCatalog.txt: not changed")
        else:
            print("ContentCatalog.txt: changed")
            for d in catalog_diff(ca, cb) or ["    same JSON content (formatting only)"]:
                print(d)
    else:
        print("ContentCatalog.txt: missing from one of the steps")


def main(argv):
    # Plugin names can hold any character; never crash on a console or file that can't show them.
    for stream in (sys.stdout, sys.stderr):
        try:
            stream.reconfigure(errors="backslashreplace")
        except (AttributeError, ValueError):
            pass
    desk = desktop() / "PluginsTxtTest"
    ap = argparse.ArgumentParser(description="Compare PluginsTxtSnapshot.ps1 step folders.")
    ap.add_argument("folder", nargs="?", default=str(desk), help="snapshot folder (default: %(default)s)")
    ap.add_argument("--verbose", action="store_true", help="also write compare.log in the folder")
    args = ap.parse_args(argv)
    root = Path(args.folder)

    def fail(msg):
        print(f"compare_snapshots: {msg}", file=sys.stderr)
        log(f"FAILED: {msg}")
        write_log(root, args.verbose)
        return 1

    if not root.is_dir():
        return fail(f"folder not found: {root}. Pass the folder PluginsTxtSnapshot.ps1 wrote to.")
    try:
        steps = sorted((p for p in root.iterdir() if p.is_dir() and (p / "info.txt").exists()), key=step_key)
        log(f"folder {root}: steps {[s.name for s in steps]}")
        if len(steps) < 2:
            return fail(f"{root} has {len(steps)} step folder(s) with info.txt; take at least two snapshots first.")
        for a, b in zip(steps, steps[1:]):
            compare(a, b)
    except OSError as ex:
        where = ex.filename or root
        return fail(f"could not read {where} ({ex.strerror or ex}). If the folder is on OneDrive, make it "
                    "'Always keep on this device', or copy it to a local folder and pass that folder.")
    write_log(root, args.verbose)
    return 0


def write_log(root, verbose):
    """With --verbose, write compare.log in the folder (or the current folder if that one is missing)."""
    if not verbose:
        return
    target = (root if root.is_dir() else Path.cwd()) / "compare.log"
    try:
        target.write_text("\n".join(LOG) + "\n", encoding="utf-8")
        print(f"log: {target}", file=sys.stderr)
    except OSError as ex:
        print(f"compare_snapshots: could not write {target} ({ex})", file=sys.stderr)


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))