Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5 8059ffd83b test: the harness's overlay logs leave with the test run that wrote them, and a gate keeps it so
The injection tests inject the shipped Overlay into hook-harness, and the Overlay logs to the real
%LOCALAPPDATA%\FrameLedger\logs by design (SHGetKnownFolderPath, not the environment, per S21). The owner's folder
held 2506 overlay logs on 2026-09-15, 2492 of them hook-harness's from test runs, beside 14 from real titles.

No switch goes into the injected DLL. Each test binary removes, when its run ends, the logs it caused: an
overlay-*.log created after the run started whose first line names a hook-harness image it owns. Natively a Catch2
listener in guard_test.cpp over src/native/tests/overlay_log_sweep.h (the image must be FL_HARNESS_EXE); in managed
code tests/Shared/HarnessOverlayLogSweep.cs, an xUnit assembly fixture that FrameLedger.DrainFixtures.targets compiles
into every test project staging the harness, with PipeEndToEndTests registering its renamed copy's directory. Parallel
assemblies own different copies, so none removes a log another is about to read, and a game's log is never touched.

tools/test-artifacts-check.ps1 (seven self-test cases) is a new gate step: a hook-harness log created during the gate
and still there fails it, which is what makes a missing sweep red. Existing logs are left for the owner.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 20:20:53 +07:00
13 changed files with 687 additions and 0 deletions

No files matched your search

+14
View File
@@ -241,6 +241,20 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
### Fixed
- **Test runs stop filling the real data folder with hook-harness logs (2026-09-15).** The injection tests inject the
shipped Overlay, whose log goes to `%LOCALAPPDATA%\FrameLedger\logs` by design (§S21: not the environment, and no
switch in the injected DLL), so the owner's folder held 2506 overlay logs, 2492 of them hook-harness's from test
runs since 2026-09-06, beside 14 from real titles. Each test binary now removes, when its run ends, exactly the logs
it caused: an `overlay-*.log` created after the run started whose first line names a hook-harness image it owns. A
Catch2 listener in `guard_test.cpp` does it natively (`src/native/tests/overlay_log_sweep.h`, the image must be this build's
`FL_HARNESS_EXE`), and `tests/Shared/HarnessOverlayLogSweep.cs`, an xUnit assembly fixture that
`FrameLedger.DrainFixtures.targets` compiles into every test project staging the harness, does it for the managed
suites (the copy beside the test binary, plus the renamed copy `PipeEndToEndTests` registers). Assemblies run in
parallel with their own copies, so none removes a log another is about to read, and a game's log is never touched.
The new `test-artifacts` gate (`tools/test-artifacts-check.ps1`, seven self-test cases) fails for a harness log
created during the gate and still there, which is red on the unswept tree. Tests: `[sweep]` in `fl_guard_test`,
`HarnessOverlayLogSweepTests`. The logs from before this change are left for the owner. Docs: `17_HOOK_ENGINE`
§Native logging, `12_BUILD` gate list, `14_TESTING`, HANDOFF §Traps. No Overlay change, so no hook-path overhead.
- **The native log test read another process's log, and was filed as a flake four times (2026-09-14).**
`guard_test.cpp`'s `FindOverlayLog` took the first `overlay-<pid>-*.log` by name in the real
`%LOCALAPPDATA%\FrameLedger\logs`, which keeps every run's log — 2130 on the dev box. A harness that drew a
+12
View File
@@ -39,6 +39,18 @@
</None>
</ItemGroup>
<!--
THE HARNESS'S LOGS LEAVE WITH THE ASSEMBLY THAT CAUSED THEM. The Overlay logs to the real
%LOCALAPPDATA%\FrameLedger\logs by design (§S21), so every TEST project that stages hook-harness
compiles tests/Shared/HarnessOverlayLogSweep.cs, an xUnit assembly fixture that removes, when the
assembly finishes, the overlay logs of the harness copies it owns (17_HOOK_ENGINE §Native logging).
The CaptureHost imports this file too and is not a test project, so it does not get the sweep.
tools/test-artifacts-check.ps1 is what makes a missing sweep red.
-->
<ItemGroup Condition="'$(IsTestProject)' == 'true'">
<Compile Include="$(MSBuildThisFileDirectory)tests\Shared\HarnessOverlayLogSweep.cs" Link="Shared\HarnessOverlayLogSweep.cs" />
</ItemGroup>
<!--
Warn at build, fail at test. build.ps1 runs the native build first, so by the
time this evaluates both exist; a hard error here would break `dotnet build` on
+11
View File
@@ -488,6 +488,15 @@ function Invoke-ProjectGates {
}
Write-Host " $($mirrorResults.Count) mirror assertion(s) executed and passed (fl_shm.h vs FrameLedger.Shared)" -ForegroundColor DarkGray
# Test hygiene (17_HOOK_ENGINE §Native logging). The injection tests use the shipped Overlay, whose log goes to the
# real data folder by design (§S21), and 2492 hook-harness logs had piled up there by 2026-09-15. Each test binary
# that starts the harness now removes the logs it caused; this is what makes a missing sweep red: a hook-harness
# overlay log created since this gate started and still there after the tests fails it. A game's log never counts.
Write-Step 'test-artifacts'
$artifactsTool = Join-Path $repo 'tools/test-artifacts-check.ps1'
Invoke-Checked 'test-artifacts (self-test)' { & $artifactsTool -SelfTest }
Invoke-Checked 'test-artifacts' { & $artifactsTool -SinceUtc $script:GateStartedUtc }
Write-Step 'placeholder guard'
# {{RELEASE_DATE}} is substituted at release time and is the only token
# allowed to survive. Anything else in a document FR-11 displays for
@@ -503,6 +512,8 @@ function Invoke-ProjectGates {
# --- Entry point ------------------------------------------------------------
$sw = [Diagnostics.Stopwatch]::StartNew()
# The test-artifacts gate counts only what this run could have written.
$script:GateStartedUtc = [DateTime]::UtcNow
switch ($Task) {
'native' { Invoke-Native $false }
'managed' { Invoke-Managed $false }
+1
View File
@@ -241,6 +241,7 @@ document the app displays for acceptance (FR-11) is a defect, not a template.
14b. `tools/release-notes.ps1 -SelfTest` — five cases over a fixture changelog (a dated and an undated section, a missing one, a prefix that must not match, an empty one). The live half needs a tag's version and runs in `release.yml`, where a missing or empty section is a red release (P4 PR-5)
15. `tools/resx-audit.ps1` — ~~**skipped loudly; it does not exist, and no `.resx` file does either**~~ **built 2026-09-13 (P3 PR-2)**: `-SelfTest` first (11 fixture cases, both directions), then the live pass over every `Strings.resx` family under `src/` — key sets equal across en/vi/ja, `Safety_*` in `ja` marked for review or signed, `Strings.Designer.cs` current with `tools/resx-gen.ps1`. A tree with no family is red (`09_I18N` §Translation workflow)
16. **struct-mirror** — reads this run's `.trx` and fails when `ShmLayoutMirrorTests` did not execute, so deleting the mirror test is red as well as breaking it
16b. **`tools/test-artifacts-check.ps1`** — `-SelfTest` first (seven cases, two RED), then live: an `overlay-*.log` created since this gate started, still in the real `%LOCALAPPDATA%\FrameLedger\logs` after the tests, whose first line names a `hook-harness*` image, fails the gate. It is what makes a test binary without its log sweep red (`17_HOOK_ENGINE` §Native logging, 2026-09-15); a game's log never counts
17. Placeholder guard — fails if any `{{` token other than `{{RELEASE_DATE}}` survives in `README.md` or `legal/*.md`
> **This list was wrong in two ways until 2026-08-06 and both were the same kind of wrong.** Step 6
+5
View File
@@ -56,6 +56,11 @@ The anti-cheat guard is the one component where a bug can cost someone an accoun
into an `interrupted` row whose `frame_count` IS the prefix, deletes the file, and finds nothing on a
second pass. `PartialSessionFileTests` already kills at every byte offset; what this adds is that the
Agent wrote a recoverable prefix *on its own* before it died.
- **Test hygiene: the harness's overlay logs leave with the run.** The Overlay logs to the real
`%LOCALAPPDATA%\FrameLedger\logs` by design, so every test binary that starts hook-harness removes the logs it
caused when its run ends, and `tools/test-artifacts-check.ps1` fails the gate for one left behind
(`17_HOOK_ENGINE` §Native logging, 2026-09-15). A new native test binary that starts the harness needs the listener;
a managed test project that stages it gets the sweep from `FrameLedger.DrainFixtures.targets`.
- Guard integration: harness loads a **dummy DLL named like an anti-cheat module** → injection refused pre-launch; loaded late → safety unhook. (A renamed harmless DLL, not real anti-cheat software.)
## Hook overhead measurement (NFR-1, per release)
+14
View File
@@ -688,6 +688,20 @@ No logging in hook bodies. A small fixed-size in-memory ring of structured event
> `UNHOOK_*` / `SYMBOL_MISSING` / `SUPERVISION_LOST` lines at the end of every session
> (`Consume/OverlayLog.cs`).
> **Tests and the real logs folder (2026-09-15).** The injection tests use the shipped Overlay, so their harness
> logs land in the user's real `logs\` too: measured that day, 2506 overlay logs, **2492 of them hook-harness's**,
> left by test runs since 2026-09-06, beside the owner's 14 from real titles. **The path stays not-a-parameter**: an
> environment variable or any other switch in the injected DLL would reopen the per-launch vector §S21 closed, and a
> test build of the Overlay would stop testing the binary that ships. Instead **each test binary removes what it
> caused** when its run ends: an `overlay-*.log` created after the run started whose first line names a hook-harness
> image that binary owns. Natively a Catch2 listener in `guard_test.cpp` over `src/native/tests/overlay_log_sweep.h` (the image
> must be this build's `FL_HARNESS_EXE`); in managed code `tests/Shared/HarnessOverlayLogSweep.cs`, an xUnit assembly
> fixture that `FrameLedger.DrainFixtures.targets` compiles into every test project staging the harness (the copy
> beside the test binary, plus directories a test registers — `PipeEndToEndTests` runs a renamed copy from its
> scratch directory). Test assemblies run in parallel with their own copies, so none removes a log another is about
> to read; a game's log names the game. **`tools/test-artifacts-check.ps1` makes a missing sweep red**: a harness log
> created during the gate and still there fails it. The logs from before this change are the owner's to delete.
## Test harness
`src/native/tools/hook-harness` — a minimal D3D11 app that presents at a controlled rate. It lets CI and local dev exercise hook paths with **no game and no anti-cheat surface at all** (`14_TESTING`).
+7
View File
@@ -1410,6 +1410,13 @@ deferred with a written rationale.
The mechanical ones live in the toolchain notes; these are the ones that cost a *wrong
diagnosis*.
- **THE TESTS WRITE INTO THE REAL DATA FOLDER, AND THAT IS NOT A SWITCH TO ADD.** The Overlay's log path is
`SHGetKnownFolderPath`, never the environment (§S21), and the tests inject the shipped DLL, so 2492 hook-harness
logs had piled up in the owner's `%LOCALAPPDATA%\FrameLedger\logs` by 2026-09-15. Each test binary now sweeps the
harness logs it caused (`17_HOOK_ENGINE` §Native logging) and the `test-artifacts` gate is red for one left behind.
A new native test executable that starts hook-harness needs the Catch2 listener from `guard_test.cpp`; do not "fix"
a red `test-artifacts` by pointing the Overlay somewhere else.
- **A CHROMIUM-BASED TITLE IS SEVERAL PROCESSES WITH ONE IMAGE PATH.** *Flower in Us* (NW.js /
RPG Maker) returned `TargetAmbiguous`, exit 6, on 2026-09-03: three processes match the
consented path. The presenting one is the GPU process, which owns no window — so do not "fix"
+157
View File
@@ -14,6 +14,9 @@
#include <algorithm>
#include <catch2/catch_test_macros.hpp>
#include <catch2/reporters/catch_reporter_event_listener.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <fl_ac_rules.h>
@@ -25,6 +28,8 @@
#include <utility>
#include <vector>
#include "overlay_log_sweep.h"
using namespace fl::guard;
namespace {
@@ -4822,3 +4827,155 @@ TEST_CASE("the injected Overlay records ray-tracing work, and an AS-build-only t
CHECK(rayquery.withDispatch == 0u);
CHECK(rayquery.volume == 0u);
}
// ===========================================================================
// Test hygiene: the harness's overlay logs leave with the run that wrote them.
// ===========================================================================
namespace {
// Every run of this binary -- the full fl_guard run and the [prescan] selection alike -- removes, when it ends, the
// hook-harness overlay logs it created under the real data folder. overlay_log_sweep.h says why a sweep and not a
// redirect: the shipped Overlay is the one under test, and its log path is not a parameter by design (§S21).
class HarnessLogSweepListener final : public Catch::EventListenerBase {
public:
using Catch::EventListenerBase::EventListenerBase;
void testRunStarting(const Catch::TestRunInfo& /*info*/) override { GetSystemTimeAsFileTime(&started_); }
void testRunEnded(const Catch::TestRunStats& /*stats*/) override {
std::wstring logs;
if (!fl::testing::RealOverlayLogsDir(logs)) {
return;
}
const fl::testing::SweepCount count = fl::testing::SweepHarnessLogs(logs, started_, FL_HARNESS_EXE);
std::printf("harness log sweep: removed %d hook-harness overlay log(s) this run created; left %d other(s)\n",
count.removed, count.kept);
}
private:
FILETIME started_{};
};
std::string NarrowAnsi(const std::wstring& text) {
const int n =
WideCharToMultiByte(CP_ACP, 0, text.c_str(), static_cast<int>(text.size()), nullptr, 0, nullptr, nullptr);
std::string out(static_cast<std::size_t>(n > 0 ? n : 0), '\0');
if (n > 0) {
WideCharToMultiByte(CP_ACP, 0, text.c_str(), static_cast<int>(text.size()), out.data(), n, nullptr, nullptr);
}
return out;
}
void WriteText(const std::wstring& path, const std::string& text) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
REQUIRE(h != INVALID_HANDLE_VALUE);
DWORD written = 0;
const BOOL ok = WriteFile(h, text.data(), static_cast<DWORD>(text.size()), &written, nullptr);
CloseHandle(h);
REQUIRE(ok);
}
// A creation time in 1999: a log an earlier run left behind.
void Backdate(const std::wstring& path) {
HANDLE h =
CreateFileW(path.c_str(), FILE_WRITE_ATTRIBUTES, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
REQUIRE(h != INVALID_HANDLE_VALUE);
SYSTEMTIME then{};
then.wYear = 1999;
then.wMonth = 1;
then.wDay = 1;
FILETIME old{};
const bool ok = SystemTimeToFileTime(&then, &old) != FALSE && SetFileTime(h, &old, &old, &old) != FALSE;
CloseHandle(h);
REQUIRE(ok);
}
bool FileExists(const std::wstring& path) {
return GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES;
}
struct ScratchLogsDir {
std::wstring path;
std::vector<std::wstring> files;
ScratchLogsDir() {
wchar_t temp[MAX_PATH]{};
REQUIRE(GetTempPathW(MAX_PATH, temp) != 0);
path = std::wstring(temp) + L"fl-sweep-" + std::to_wstring(GetCurrentProcessId()) + L"-" +
std::to_wstring(GetTickCount64());
REQUIRE(CreateDirectoryW(path.c_str(), nullptr));
}
ScratchLogsDir(const ScratchLogsDir&) = delete;
ScratchLogsDir& operator=(const ScratchLogsDir&) = delete;
~ScratchLogsDir() {
for (const std::wstring& file : files) {
static_cast<void>(DeleteFileW(file.c_str()));
}
static_cast<void>(RemoveDirectoryW(path.c_str()));
}
std::wstring Add(const wchar_t* name) {
files.push_back(path + L"\\" + name);
return files.back();
}
};
} // namespace
CATCH_REGISTER_LISTENER(HarnessLogSweepListener)
TEST_CASE("the harness log sweep removes this run's harness logs and nothing else", "[sweep]") {
ScratchLogsDir dir;
// One second before now: the files below are created within the same clock tick as the start.
FILETIME since{};
GetSystemTimeAsFileTime(&since);
ULARGE_INTEGER t{};
t.LowPart = since.dwLowDateTime;
t.HighPart = since.dwHighDateTime;
t.QuadPart -= 10000000ULL;
since.dwLowDateTime = t.LowPart;
since.dwHighDateTime = t.HighPart;
// The image as the Overlay spells it: GetModuleFileNameA, backslashes, while CMake names the harness with '/'.
std::wstring harness = FL_HARNESS_EXE;
for (wchar_t& ch : harness) {
if (ch == L'/') {
ch = L'\\';
}
}
const std::string image = NarrowAnsi(harness);
std::string shouted = image;
CharUpperBuffA(shouted.data(), static_cast<DWORD>(shouted.size()));
const auto header = [](const std::string& path) {
return "# FrameLedger.Overlay build test pid 101 layout v9 image " + path + "\r\n";
};
const std::wstring ours = dir.Add(L"overlay-101-20260915-010101.log");
const std::wstring oursShouted = dir.Add(L"overlay-102-20260915-010101.log");
const std::wstring game = dir.Add(L"overlay-103-20260915-010101.log");
const std::wstring earlier = dir.Add(L"overlay-104-19990101-000000.log");
const std::wstring stranger = dir.Add(L"overlay-105-20260915-010101.log");
const std::wstring agent = dir.Add(L"agent-20260915.log");
WriteText(ours, header(image) + "RING_CREATED\n");
WriteText(oursShouted, header(shouted));
WriteText(game, header("C:\\Games\\Title\\title.exe"));
WriteText(earlier, header(image));
Backdate(earlier);
WriteText(stranger, "# a file that is not an overlay log\n");
WriteText(agent, header(image));
const fl::testing::SweepCount count = fl::testing::SweepHarnessLogs(dir.path, since, FL_HARNESS_EXE);
CHECK(count.removed == 2);
CHECK(count.kept == 2); // the game's and the stranger; the 1999 log predates the run, agent-* is not overlay-*
CHECK_FALSE(FileExists(ours));
CHECK_FALSE(FileExists(oursShouted));
CHECK(FileExists(game));
CHECK(FileExists(earlier));
CHECK(FileExists(stranger));
CHECK(FileExists(agent));
std::string parsed;
CHECK(fl::testing::OverlayLogImage(header("C:\\x\\hook-harness.exe"), parsed));
CHECK(parsed == "C:\\x\\hook-harness.exe");
CHECK_FALSE(fl::testing::OverlayLogImage("# a stale log planted by guard_test\r\n", parsed));
}
+134
View File
@@ -0,0 +1,134 @@
// Test-only. The hook-harness's overlay logs, removed when a test binary's run ends.
//
// The Overlay writes %LOCALAPPDATA%\FrameLedger\logs\overlay-<pid>-<stamp>.log: the real per-user data folder,
// resolved by SHGetKnownFolderPath and deliberately NOT by the environment (§S21), and the shipped DLL is the one
// under test, so a test cannot point it anywhere else and the DLL gets no switch that could. Measured 2026-09-15:
// that folder held 2506 overlay logs, 2492 of them hook-harness's, left by test runs since 2026-09-06.
//
// So a test binary removes, when its run ends, exactly what it caused: a log CREATED at or after the run started
// whose first line names this build's hook-harness as the image. A game's log names the game and is never touched;
// a log from an earlier run predates the start and stays, the owner's to delete (17_HOOK_ENGINE §Native logging).
#ifndef FL_OVERLAY_LOG_SWEEP_H
#define FL_OVERLAY_LOG_SWEEP_H
#include <windows.h>
#include <fl_ac_rules.h>
#include <string>
namespace fl::testing {
struct SweepCount {
int removed = 0;
int kept = 0; // created during the run but not a harness log, or could not be removed
};
// "# FrameLedger.Overlay build <id> pid <n> layout v<k> image <path>" (dllmain.cpp FlushLog) -> <path>.
inline bool OverlayLogImage(const std::string& firstLine, std::string& image) {
static const char kPrefix[] = "# FrameLedger.Overlay build ";
if (firstLine.rfind(kPrefix, 0) != 0) {
return false;
}
const std::string::size_type at = firstLine.find(" image ");
if (at == std::string::npos) {
return false;
}
image = firstLine.substr(at + 7);
while (!image.empty() && (image.back() == '\r' || image.back() == '\n' || image.back() == ' ')) {
image.pop_back();
}
return !image.empty();
}
// The header's image comes from GetModuleFileNameA, so it is in the ANSI code page.
inline std::wstring WidenAnsi(const std::string& text) {
if (text.empty()) {
return {};
}
const int n = MultiByteToWideChar(CP_ACP, 0, text.data(), static_cast<int>(text.size()), nullptr, 0);
if (n <= 0) {
return {};
}
std::wstring out(static_cast<std::size_t>(n), L'\0');
MultiByteToWideChar(CP_ACP, 0, text.data(), static_cast<int>(text.size()), out.data(), n);
return out;
}
// CMake's $<TARGET_FILE> spells '/', GetModuleFileNameA spells '\'; neither separator nor case tells two paths apart.
inline bool SamePath(std::wstring a, std::wstring b) {
for (wchar_t& ch : a) {
if (ch == L'/') {
ch = L'\\';
}
}
for (wchar_t& ch : b) {
if (ch == L'/') {
ch = L'\\';
}
}
return CompareStringOrdinal(a.c_str(), static_cast<int>(a.size()), b.c_str(), static_cast<int>(b.size()), TRUE) ==
CSTR_EQUAL;
}
// The first line of a file, from its first 1 KiB; empty when it cannot be read.
inline std::string FirstLine(const std::wstring& path) {
HANDLE h = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (h == INVALID_HANDLE_VALUE) {
return {};
}
char buf[1024];
DWORD n = 0;
const BOOL ok = ReadFile(h, buf, sizeof(buf), &n, nullptr);
CloseHandle(h);
if (!ok) {
return {};
}
const std::string text(buf, n);
const std::string::size_type nl = text.find('\n');
return nl == std::string::npos ? text : text.substr(0, nl);
}
// Removes every overlay-*.log directly under `logsDir` that was created at or after `since` and whose header names
// `harness` as the image. Anything else is left where it is.
inline SweepCount SweepHarnessLogs(const std::wstring& logsDir, const FILETIME& since, const std::wstring& harness) {
SweepCount count;
const std::wstring pattern = logsDir + L"\\overlay-*.log";
WIN32_FIND_DATAW fd{};
HANDLE find = FindFirstFileW(pattern.c_str(), &fd);
if (find == INVALID_HANDLE_VALUE) {
return count;
}
do {
if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 || CompareFileTime(&fd.ftCreationTime, &since) < 0) {
continue;
}
const std::wstring path = logsDir + L"\\" + fd.cFileName;
std::string image;
if (!OverlayLogImage(FirstLine(path), image) || !SamePath(WidenAnsi(image), harness)) {
++count.kept;
continue;
}
if (DeleteFileW(path.c_str())) {
++count.removed;
} else {
++count.kept;
}
} while (FindNextFileW(find, &fd));
FindClose(find);
return count;
}
// %LOCALAPPDATA%\FrameLedger\logs, resolved the way the Overlay resolves it.
inline bool RealOverlayLogsDir(std::wstring& out) {
wchar_t base[fl::guard::kMaxRulesPathLen]{};
if (!fl::guard::LocalAppDataDir(base, fl::guard::kMaxRulesPathLen)) {
return false;
}
out = std::wstring(base) + L"\\FrameLedger\\logs";
return true;
}
} // namespace fl::testing
#endif // FL_OVERLAY_LOG_SWEEP_H
@@ -10,6 +10,7 @@ using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Shared.Ipc;
using FrameLedger.Shared.Safety;
using FrameLedger.Testing;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
@@ -121,6 +122,8 @@ public sealed class PipeEndToEndTests : IDisposable
{
File.Exists(Harness).Should().BeTrue("hook-harness.exe must be staged beside the test binary (FrameLedger.DrainFixtures.targets)");
Directory.CreateDirectory(_dataDir);
// The copy's overlay logs are this assembly's to remove when it finishes (17_HOOK_ENGINE §Native logging).
HarnessOverlayLogSweep.Own(_dataDir);
File.Copy(Harness, ConsentedExecutable, overwrite: true);
// The composition logs through Serilog's static logger; in this process nothing configures it, so the
// orchestrator's and the pipe's lines would vanish. A file in the scratch directory is what a hang leaves behind.
@@ -0,0 +1,69 @@
using FluentAssertions;
using FrameLedger.Testing;
namespace FrameLedger.Infrastructure.Tests;
/// <summary>
/// The assembly-end sweep of the hook-harness's overlay logs (<c>17_HOOK_ENGINE</c> §Native logging): it removes this
/// assembly's harness logs from the run, and never a game's log, another assembly's harness log, or an earlier run's.
/// </summary>
public sealed class HarnessOverlayLogSweepTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-sweep-" + Guid.NewGuid().ToString("N"));
public HarnessOverlayLogSweepTests() => Directory.CreateDirectory(_dir);
public void Dispose() => Directory.Delete(_dir, recursive: true);
[Fact]
public void RemovesThisAssemblysHarnessLogsFromTheRunAndNothingElse()
{
DateTime since = DateTime.UtcNow.AddSeconds(-1);
string bin = Path.Combine(_dir, "bin");
string copies = Path.Combine(_dir, "copies");
string[] owned = [bin, copies];
string ours = Plant("overlay-101-20260915-010101.log", Path.Combine(bin, "hook-harness.exe"));
string ourCopy = Plant("overlay-102-20260915-010101.log", Path.Combine(copies, "HOOK-HARNESS-abc.exe"));
string otherAssembly = Plant("overlay-103-20260915-010101.log", @"C:\elsewhere\bin\hook-harness.exe");
string game = Plant("overlay-104-20260915-010101.log", Path.Combine(bin, "title.exe"));
string earlier = Plant("overlay-105-19990101-000000.log", Path.Combine(bin, "hook-harness.exe"));
File.SetCreationTimeUtc(earlier, new DateTime(1999, 1, 1, 0, 0, 0, DateTimeKind.Utc));
string stranger = Path.Combine(_dir, "overlay-106-20260915-010101.log");
File.WriteAllText(stranger, "# a file that is not an overlay log\r\n");
string agent = Path.Combine(_dir, "agent-20260915.log");
File.WriteAllText(agent, Header(Path.Combine(bin, "hook-harness.exe")));
(int removed, int kept) = HarnessOverlayLogSweep.Sweep(_dir, since, image => HarnessOverlayLogSweep.IsHarnessUnder(image, owned));
removed.Should().Be(2);
kept.Should().Be(3, "another assembly's harness, a game and a stranger were created in the window and left");
File.Exists(ours).Should().BeFalse();
File.Exists(ourCopy).Should().BeFalse("a copy under a registered directory is ours, whatever its case");
File.Exists(otherAssembly).Should().BeTrue("a parallel assembly may still read its own log");
File.Exists(game).Should().BeTrue("a game's log is never a test's to remove");
File.Exists(earlier).Should().BeTrue("a log from an earlier run is the owner's");
File.Exists(stranger).Should().BeTrue();
File.Exists(agent).Should().BeTrue("only overlay-*.log is read");
}
[Fact]
public void TheHeaderImageIsReadFromTheOverlaysOwnFirstLine()
{
HarnessOverlayLogSweep.OverlayLogImage(@"# FrameLedger.Overlay build 1a2b pid 42 layout v9 image C:\x\hook-harness.exe" + "\r").Should().Be(@"C:\x\hook-harness.exe");
HarnessOverlayLogSweep.OverlayLogImage("# a stale log planted by guard_test").Should().BeNull();
HarnessOverlayLogSweep.OverlayLogImage(null).Should().BeNull();
HarnessOverlayLogSweep.IsHarnessUnder(@"C:\x\bin\hook-harness.exe", [@"C:/x/bin/"]).Should().BeTrue("separators and a trailing one do not matter");
HarnessOverlayLogSweep.IsHarnessUnder(@"C:\x\binary\hook-harness.exe", [@"C:\x\bin"]).Should().BeFalse("a sibling directory is not under it");
HarnessOverlayLogSweep.IsHarnessUnder(@"C:\x\bin\game.exe", [@"C:\x\bin"]).Should().BeFalse();
HarnessOverlayLogSweep.RealLogsDirectory.Should().EndWith(Path.Combine("FrameLedger", "logs"));
}
private static string Header(string image) => "# FrameLedger.Overlay build test pid 101 layout v9 image " + image + "\n";
private string Plant(string name, string image)
{
string path = Path.Combine(_dir, name);
File.WriteAllText(path, Header(image) + "RING_CREATED\n");
return path;
}
}
+147
View File
@@ -0,0 +1,147 @@
using System.Diagnostics.CodeAnalysis;
using System.Text;
[assembly: AssemblyFixture(typeof(FrameLedger.Testing.HarnessOverlayLogSweep))]
namespace FrameLedger.Testing;
/// <summary>
/// The hook-harness's overlay logs, removed when this test assembly finishes (<c>17_HOOK_ENGINE</c> §Native logging).
/// </summary>
/// <remarks>
/// The Overlay writes <c>%LOCALAPPDATA%\FrameLedger\logs\overlay-&lt;pid&gt;-&lt;stamp&gt;.log</c>: the real data folder,
/// resolved by the shell and deliberately not by the environment (§S21), and the injection tests use the shipped Overlay,
/// so no test can point it elsewhere. Measured 2026-09-15, that folder held 2506 overlay logs, 2492 of them hook-harness's.
/// <c>FrameLedger.DrainFixtures.targets</c> compiles this file into every test project that stages hook-harness, and at the
/// end of the assembly it removes exactly what the assembly caused: an overlay log created after the assembly started
/// whose first line names a hook-harness image this assembly owns — the copy beside its binary, or a copy under a
/// directory a test registered with <see cref="Own"/>. Test assemblies run in parallel with their own copies, so one
/// never removes a log another is about to read. A game's log names the game; a log from an earlier run predates the
/// start and stays.
/// </remarks>
[SuppressMessage("Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "xUnit creates the assembly fixture by reflection")]
internal sealed class HarnessOverlayLogSweep : IDisposable
{
private static readonly Lock _gate = new();
private static readonly List<string> _owned = [];
private readonly DateTime _startedUtc = DateTime.UtcNow;
/// <summary>The Overlay's log directory, resolved the way the Overlay resolves it (the shell's Local AppData).</summary>
public static string RealLogsDirectory =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FrameLedger", "logs");
/// <summary>Registers a directory a test copies hook-harness into, so the copy's logs are this assembly's too.</summary>
public static void Own(string directory)
{
ArgumentException.ThrowIfNullOrWhiteSpace(directory);
lock (_gate)
{
_owned.Add(Path.GetFullPath(directory));
}
}
public void Dispose()
{
string[] owned;
lock (_gate)
{
owned = [AppContext.BaseDirectory, .. _owned];
}
_ = Sweep(RealLogsDirectory, _startedUtc, image => IsHarnessUnder(image, owned));
}
/// <summary>
/// Removes each <c>overlay-*.log</c> directly under <paramref name="logsDirectory"/> created at or after
/// <paramref name="sinceUtc"/> whose header image <paramref name="isOurs"/> accepts. Everything else stays.
/// </summary>
/// <returns>How many were removed, and how many created in the window were left (not ours, or in use).</returns>
public static (int Removed, int Kept) Sweep(string logsDirectory, DateTime sinceUtc, Func<string, bool> isOurs)
{
ArgumentNullException.ThrowIfNull(isOurs);
if (!Directory.Exists(logsDirectory))
{
return (0, 0);
}
int removed = 0;
int kept = 0;
foreach (FileInfo log in new DirectoryInfo(logsDirectory).EnumerateFiles("overlay-*.log"))
{
if (log.CreationTimeUtc < sinceUtc)
{
continue;
}
string? image = OverlayLogImage(FirstLine(log.FullName));
if (image is null || !isOurs(image))
{
kept++;
continue;
}
try
{
log.Delete();
removed++;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
kept++;
}
}
return (removed, kept);
}
/// <summary>The image path of an Overlay log's first line (<c># FrameLedger.Overlay build … image &lt;path&gt;</c>), or null.</summary>
public static string? OverlayLogImage(string? firstLine)
{
const string prefix = "# FrameLedger.Overlay build ";
if (firstLine is null || !firstLine.StartsWith(prefix, StringComparison.Ordinal))
{
return null;
}
int at = firstLine.IndexOf(" image ", StringComparison.Ordinal);
if (at < 0)
{
return null;
}
string image = firstLine[(at + " image ".Length)..].TrimEnd('\r', '\n', ' ');
return image.Length == 0 ? null : image;
}
/// <summary>True for a <c>hook-harness*.exe</c> directly or deeper under one of <paramref name="directories"/>.</summary>
public static bool IsHarnessUnder(string image, IEnumerable<string> directories)
{
ArgumentNullException.ThrowIfNull(image);
ArgumentNullException.ThrowIfNull(directories);
string name = Path.GetFileName(image);
if (!name.StartsWith("hook-harness", StringComparison.OrdinalIgnoreCase) || !name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
return false;
}
string full = Normalised(image);
return directories.Any(directory => full.StartsWith(Normalised(directory) + "\\", StringComparison.OrdinalIgnoreCase));
}
private static string Normalised(string path) => path.Replace('/', '\\').TrimEnd('\\');
// The header's image comes from GetModuleFileNameA (the ANSI code page); Latin-1 reads its bytes without failing.
private static string? FirstLine(string path)
{
try
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var reader = new StreamReader(stream, Encoding.Latin1);
return reader.ReadLine();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
}
+113
View File
@@ -0,0 +1,113 @@
#Requires -Version 7.0
<#
.SYNOPSIS
Fails when a test run left hook-harness overlay logs in the real FrameLedger data folder.
.DESCRIPTION
docs/17_HOOK_ENGINE.md §Native logging. The injection tests use the shipped Overlay, and the Overlay writes its log
to %LOCALAPPDATA%\FrameLedger\logs\overlay-<pid>-<stamp>.log: the real per-user data folder, by design (§S21, not a
parameter). Measured 2026-09-15, that folder held 2506 overlay logs, 2492 of them hook-harness's, left by test runs.
So every test binary that starts hook-harness removes, when its run ends, the logs it caused: the Catch2 listener in
src/native/tests/guard_test.cpp and tests/Shared/HarnessOverlayLogSweep.cs, which FrameLedger.DrainFixtures.targets
compiles into each managed test project that stages the harness. This gate is what makes a missing sweep red: an
overlay log created since the gate started whose first line names a hook-harness image, still there after the tests,
fails it. A game's log names the game and never counts; a log from before the gate never counts.
.PARAMETER SinceUtc
The gate's start. Only logs created at or after it count.
.PARAMETER LogsDirectory
The directory to read. Default: the Overlay's own, %LOCALAPPDATA%\FrameLedger\logs.
.PARAMETER SelfTest
Runs the fixture cases below, in scratch directories, and exits 0 only if every one behaves.
#>
[CmdletBinding()]
param(
[DateTime]$SinceUtc = [DateTime]::UtcNow,
[string]$LogsDirectory = (Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) 'FrameLedger\logs'),
[switch]$SelfTest
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Get-LeftHarnessLog {
param([string]$Directory, [DateTime]$Since)
$left = [System.Collections.Generic.List[string]]::new()
if (-not (Test-Path -LiteralPath $Directory -PathType Container)) { return , $left.ToArray() }
foreach ($file in Get-ChildItem -LiteralPath $Directory -Filter 'overlay-*.log' -File) {
if ($file.CreationTimeUtc -lt $Since) { continue }
$first = $null
try {
$stream = [IO.FileStream]::new($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]'ReadWrite, Delete')
try {
# The image comes from GetModuleFileNameA, in the ANSI code page; Latin-1 reads any byte.
$reader = [IO.StreamReader]::new($stream, [Text.Encoding]::Latin1)
$first = $reader.ReadLine()
}
finally { $stream.Dispose() }
}
catch [IO.IOException] { continue }
if ($null -eq $first) { continue }
$m = [regex]::Match($first, '^# FrameLedger\.Overlay build .*? image (?<image>.+?)\s*$', 'CultureInvariant')
if (-not $m.Success) { continue }
$image = $m.Groups['image'].Value
$name = [IO.Path]::GetFileName($image)
if ($name.StartsWith('hook-harness', [StringComparison]::OrdinalIgnoreCase)) {
$left.Add("$($file.Name) (image $image)")
}
}
return , $left.ToArray()
}
if ($SelfTest) {
$root = Join-Path ([IO.Path]::GetTempPath()) ('fl-artifacts-selftest-' + [guid]::NewGuid().ToString('N'))
$since = [DateTime]::UtcNow.AddSeconds(-1)
$header = '# FrameLedger.Overlay build test pid 101 layout v9 image '
$cases = @(
@{ Name = "a harness log created during the run FAILS"; File = 'overlay-1-20260915-010101.log'; Text = "${header}C:\build\tools\hook-harness\hook-harness.exe`nRING_CREATED`n"; Left = 1 },
@{ Name = "a renamed harness copy's log FAILS"; File = 'overlay-2-20260915-010101.log'; Text = "${header}C:\Temp\fl-pipe-e2e-1\HOOK-HARNESS-fl-pipe-e2e-1.exe`r`n"; Left = 1 },
@{ Name = "a game's log passes"; File = 'overlay-3-20260915-010101.log'; Text = "${header}D:\Games\Title\title.exe`n"; Left = 0 },
@{ Name = 'a harness log from before the run passes'; File = 'overlay-4-19990101-000000.log'; Text = "${header}C:\build\hook-harness.exe`n"; Old = $true; Left = 0 },
@{ Name = 'an overlay-named file with no Overlay header passes'; File = 'overlay-5-20260915-010101.log'; Text = "# planted by guard_test`n"; Left = 0 },
@{ Name = 'a non-overlay log with a harness header passes'; File = 'agent-20260915.log'; Text = "${header}C:\build\hook-harness.exe`n"; Left = 0 },
@{ Name = 'a directory that does not exist passes'; File = $null; Left = 0 }
)
$failed = 0
try {
$i = 0
foreach ($c in $cases) {
$i++
$dir = Join-Path $root "case$i"
if ($c.File) {
New-Item -ItemType Directory -Path $dir -Force | Out-Null
$path = Join-Path $dir $c.File
[IO.File]::WriteAllText($path, $c.Text)
if ($c.ContainsKey('Old')) { [IO.File]::SetCreationTimeUtc($path, [DateTime]::new(1999, 1, 1, 0, 0, 0, [DateTimeKind]::Utc)) }
}
$got = Get-LeftHarnessLog -Directory $dir -Since $since
$ok = $got.Count -eq $c.Left
Write-Host (" {0,-4} {1}" -f ($(if ($ok) { 'ok' } else { 'FAIL' })), $c.Name) -ForegroundColor ($(if ($ok) { 'DarkGray' } else { 'Red' }))
if (-not $ok) { $failed++ }
}
}
finally {
if (Test-Path -LiteralPath $root) { Remove-Item -LiteralPath $root -Recurse -Force }
}
if ($failed -gt 0) { Write-Host "test-artifacts self-test FAILED ($failed)" -ForegroundColor Red; exit 1 }
Write-Host "test-artifacts self-test: $($cases.Count) cases, both directions" -ForegroundColor Green
exit 0
}
$left = Get-LeftHarnessLog -Directory $LogsDirectory -Since $SinceUtc
if ($left.Count -gt 0) {
$left | Select-Object -First 20 | ForEach-Object { Write-Host " $_" -ForegroundColor Red }
if ($left.Count -gt 20) { Write-Host " ... and $($left.Count - 20) more" -ForegroundColor Red }
Write-Host ("test-artifacts: {0} hook-harness overlay log(s) created during this run are still in the data folder. A test binary that starts hook-harness is missing its sweep (17_HOOK_ENGINE §Native logging)." -f $left.Count) -ForegroundColor Red
exit 1
}
Write-Host 'test-artifacts: ok - no hook-harness overlay log from this run is left in the data folder' -ForegroundColor Green
exit 0