diff --git a/AGENTS.template.md b/AGENTS.template.md
index 8de5ac4..97c0a8b 100644
--- a/AGENTS.template.md
+++ b/AGENTS.template.md
@@ -9,14 +9,12 @@ Crafter.Debug lets an agent inspect and drive an app while it runs. `project.cpp
| Configuration | Holds |
|---|---|
| `Crafter.Debug.Core` (static) | What the app and the client share. Partitions:
• `:Value`: JSON value with its own parser and printer
• `:Reflect`: aggregate members and scoped-enum names, without ``
• `:Codec`: encode, decode, describe
• `:Result`: Error, Result, Async
• `:Protocol`: envelope, codes, versions, base64
• `:BuildInfo`: source id and client path, generated
• `:Discovery`: instance files and the lifetime lock |
-| `Crafter.Debug.Cli` (static) | The client's logic:
• `:Client`: `Cli::Run`, with the transport injected
• `:Quic`: `ConnectQuic`, the transport `main` injects |
+| `Crafter.Debug.Cli` (static) | The client's logic: `Cli::Run`, with the transport injected. |
| `crafter.debug-cli` (executable) | `crafter-debug`: `main.cpp` plus the transport. |
-| `Crafter.Debug` (static, returned) | What an app links. Partitions:
• `:Registry`: commands, watches, samples, Group
• `:Timeline`: Log, Check, Emit
• `:Condition`: what wait and pause --when evaluate
• `:Session`: serving requests, Pump, Advance
• `:Transport`: the QUIC listener, exporting nothing |
+| `Crafter.Debug` (static, returned) | What an app links. Partitions:
• `:Registry`: commands, watches, samples, Group
• `:Timeline`: Log, Check, Emit
• `:Condition`: what wait and pause --when evaluate
• `:Session`: serving requests, Pump, Advance |
The client is one of the library's dependencies only so that a consumer's debug build compiles it in the same pass.
-**The wire:** QUIC on 127.0.0.1, ALPN `crafter-debug/1`, through Crafter.Network. One request per stream the client opens: the request object and a FIN; back come zero or more stream lines (`{"entry": ...}`), then the reply (`{"result"}` or `{"error"}`) and a FIN. Every object is one line of JSON. `implementations/Crafter.Debug-Transport.cpp` opens with the rules on who may hold which lock.
-
`tooling/` is a separate project, `Crafter.Debug.Build`. Consumers load it with `#pragma crafter dependency ... project "tooling/project.cpp"`. Its `Debug::Use` adds the library under the consumer's flag and writes the consumer's `build/crafter-debug` launcher at load time.
`tooling/AGENTS.consumer.md` is the only notes file consumers get, and it covers both driving the app and coding with it. Crafter.Build merges a dependency's notes only when that dependency is in the build:
@@ -36,17 +34,12 @@ Tests run inside the Flatpak sandbox, where:
Every `flatpak run` is its own sandbox with its own pid namespace.
-**Crafter.Network** comes from forgejo, unpinned, so every load `git pull`s it. `--local` takes `../Crafter.Network` instead.
-
-The transport needs Network's callback API (`OnRecieve`, `SendAsync`, `OnClosed`, `ListenerQUIC` with a bind address and `Port()`) and its fix that lets stopped streams finish before `~ClientQUIC` closes. Both are on Network's `master` from 79a2f12 on, so a `../Crafter.Network` older than that does not build the transport.
-
## Build and test commands
```bash
flatpak run --die-with-parent net.catcrafts.CrafterBuild # the library, core, client
flatpak run --die-with-parent net.catcrafts.CrafterBuild test # every test
flatpak run --die-with-parent net.catcrafts.CrafterBuild test 'Should*Client*'
-flatpak run --die-with-parent net.catcrafts.CrafterBuild test --local # with ../Crafter.Network
cd examples/Basic && flatpak run --die-with-parent net.catcrafts.CrafterBuild --debug-api # a consumer's debug build
```
@@ -57,7 +50,7 @@ A test's own output appears only when it fails. To see its PASS lines, run the b
**Registration:** tests are declared in `project.cpp`, and only when this is the top-level project:
- `coreTests` link the core;
- `libraryTests` link the library;
-- `ShouldRunClientCommands` and `ShouldServeOverQuic` link the library and the client. The second listens for real and drives the session over loopback with the client's own transport.
+- `ShouldRunClientCommands` links the library and the client.
**Shape of a test:**
- Name it `Should`.
@@ -66,8 +59,6 @@ A test's own output appears only when it fails. To see its PASS lines, run the b
**Session tests** use `Session({ .listen = false })` and hand requests to `Session::Handle` through a fake `Detail::Exchange`. Pump from the test's own thread, or from one thread playing the app.
-**A listening session** needs `ThreadPool::Start()` with a worker first, `CRAFTER_DEBUG_DIR` set, and `std::_Exit` at the end after `std::fflush(stdout)`: msquic's teardown at exit waits for connections. Run it 30 times in a row before trusting it; one transport race showed in 4 runs of 30.
-
**Files and discovery:**
- Temporary files go under `fs::temp_directory_path() / "crafter-debug-"`.
- Discovery tests set `CRAFTER_DEBUG_DIR` there.
@@ -96,7 +87,7 @@ A test's own output appears only when it fails. To see its PASS lines, run the b
## Design rules
1. **Release builds never link Crafter.Debug.** Consumers gate it through `Debug::Use` and their own define. The library has no no-op mode.
-2. **No thread of Crafter.Debug's own, and nothing ever blocks one.** Transport threads only queue work or answer from the session's own state; the Pump thread runs app code; `Detail::Exchange::Reply` and `Stream` never block. The thread pool belongs to the host app. Network's own threads are ListenerQUIC's accept loop and msquic's workers. The one thread Crafter.Debug starts is the timer that ends the process 200 ms after `quit --force` has sent its reply.
+2. **No thread of Crafter.Debug's own, and nothing ever blocks one.** Transport threads only queue work or answer from the session's own state; the Pump thread runs app code; `Detail::Exchange::Reply` and `Stream` never block. The thread pool belongs to the host app.
3. **App code runs only on the Pump thread:** handlers, getters, setters, and condition evaluation. Never hold the session mutex while calling it, since app code logs, and logging re-enters the session.
4. **Nothing the Flatpak compiles runs on the host.** The launcher is POSIX sh and starts the client with `flatpak run`. On older hosts, the bundled libc++ and the runtime's glibc do not load.
5. **The client is built with the app.** `debug.hello`, the ALPN `crafter-debug/1` and the discovery record's `protocol` and `sourceId` are frozen. Bump `protocolVersion` on any wire change.
@@ -114,8 +105,6 @@ A test's own output appears only when it fails. To see its PASS lines, run the b
## Security
- **Debug builds only.** The session listens on 127.0.0.1, and every request must carry the instance's 128-bit token.
-- **TLS** uses Crafter.Network's per-user self-signed certificate, which the client does not check. The token is what proves who asks.
-- **Size limits:** a request is at most 1 MiB, answered with an error past that. A `log --follow` client more than 8 MiB behind is reset.
- **Discovery files** are 0600 in a 0700 directory.
- **Debuggers:** the session calls `prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY)`, so a debugger the agent starts can attach. That is another reason it never ships in a release build.
@@ -128,6 +117,3 @@ A test's own output appears only when it fails. To see its PASS lines, run the b
- **A consumer's `#ifdef`'d `import Crafter.Debug;`** is harmless in its plain builds.
- **`project.cpp` regenerates `build/generated//Crafter.Debug.Core-BuildInfo.cpp`** when the sources or the client's path change. `crafter-build clean` removes it, and the next load writes it again.
- **The launcher is written by `Debug::Use` while crafter-build loads the consumer,** not by the build. A plain build keeps an existing launcher; a fresh plain build writes the stub.
-- **A consumer that depends on Crafter.Network itself** must name it exactly as `project.cpp` here does (same URL, no pin, same args). Otherwise the graph holds two Crafter.Network configurations, and crafter-build refuses with "module … built twice".
-- **`debug.log`'s `last` of 0 means no backlog**, as `tail -n 0` does. A `TimelineQuery`'s `last` of 0 means all.
-- **Answer before you raise a flag the main loop acts on.** The loop may end the Session at once. A reply given before the connections close is delivered; one given after is not. `quit` replies first, then sets `QuitRequested`.
diff --git a/README.md b/README.md
index 5481d6b..ade6e0d 100644
--- a/README.md
+++ b/README.md
@@ -56,27 +56,23 @@ extern "C" Configuration CrafterBuildProject(std::span a
if (arg != "--debug-api") depArgs.emplace_back(arg);
}
// ...give depArgs to every other dependency too...
- const bool debugApi = Debug::Use(cfg, { .enabled = opts.Has("--debug-api"), .flag = "--debug-api",
- .define = "MYAPP_DEBUG_API", .args = depArgs });
- // ...your sources, plus the debug-only ones when debugApi...
+ Debug::Use(cfg, { .enabled = opts.Has("--debug-api"), .flag = "--debug-api",
+ .define = "MYAPP_DEBUG_API", .args = depArgs });
+ // ...
}
```
**What `Use` does with the flag:**
-- **Flag on, native Linux target:** it adds the define and the library, from the checkout the pragma names, writes `build/crafter-debug`, and returns true.
-- **Otherwise:** it adds nothing and returns false, and release builds never link Crafter.Debug. Until a debug build has run, `build/crafter-debug` is a stub that says to build one.
-
-Add your debug-only sources when `Use` returns true, not when the flag is on: a non-Linux target with the flag gets neither the library nor the define.
+- **Flag on, native Linux target:** it adds the define and the library, from the checkout the pragma names, and writes `build/crafter-debug`.
+- **Otherwise:** it adds nothing, and release builds never link Crafter.Debug. Until a debug build has run, `build/crafter-debug` is a stub that says to build one.
A dependency that two paths in the build graph share must get the **same arg list on both**. Otherwise crafter-build refuses the graph with "module … built twice". Build one `depArgs` and give it to every dependency, as above.
-That includes Crafter.Network, which Crafter.Debug takes from `https://forgejo.catcrafts.net/Catcrafts/Crafter.Network.git`, unpinned (with `--local`, from `../Crafter.Network`). If your project depends on Crafter.Network too, name it the same way. A project that pins its own Crafter.Network to a commit can't add Crafter.Debug yet.
-
**2. In `main`**, start a session and pump it once per frame. Gate the parts the agent should be able to pause:
```cpp
import MyApp.DebugShim; // see "Without #ifdefs" below
-ThreadPool::Start(); // the session's transport needs a pool worker
+ThreadPool::Start(); // the session's transport runs on the pool
#ifdef MYAPP_DEBUG_API
Debug::Session debug({ .name = "MyApp" });
MyApp::RegisterDebug(); // your commands and watches
@@ -88,7 +84,7 @@ while (running && !Debug::QuitRequested()) {
}
```
-The `Session` must be destroyed before `main` returns and before `ThreadPool::Stop()`, because msquic waits for open connections at exit. A stack object in `main`, as above, does that. It needs the pool started with at least one worker (`Start(1)` starts none) and throws without one.
+The `Session` must be destroyed before `main` returns and before `ThreadPool::Stop()`, because msquic waits for open connections at exit. A stack object in `main`, as above, does that.
**3. Register what the agent needs** in debug-only source files, which `project.cpp` adds only under the flag. See "The app side" below.
@@ -323,8 +319,6 @@ cd examples/Basic && crafter-build --debug-api -r
- **Library and core tests** run in-process, against a `Session` built with `listen = false` and a fake transport.
- **`ShouldRunClientCommands`** runs the real client against a real session that way.
-- **`ShouldServeOverQuic`** runs a listening session and drives it over loopback with the client's own QUIC transport. It covers discovery, calls, `log --follow`, wrong tokens, oversized requests, parallel requests, and shutdown with a client connected.
-- **Crafter.Network** comes from forgejo, or from `../Crafter.Network` with `--local`.
- **`AGENTS.template.md`** has the conventions.
Licensed LGPL-3.0-only; the examples are MIT.
diff --git a/examples/Basic/AGENTS.template.md b/examples/Basic/AGENTS.template.md
index 058abd3..246dd41 100644
--- a/examples/Basic/AGENTS.template.md
+++ b/examples/Basic/AGENTS.template.md
@@ -1,17 +1,3 @@
# Basic
-A Crafter.Debug example: a headless simulation of balls dropped onto a floor slab, 60 ticks a second.
-
-- **Plain build:** `crafter-build`, run with `crafter-build -r`. It simulates ten seconds as fast as it can and prints how many balls ended up below the floor.
-- **Debug build:** this project's debug flag is `--debug-api` and its define `BASIC_DEBUG_API`. The build adds Crafter.Debug, and the app runs in real time until an agent tells it to quit.
-
-## Layout
-
-- `interfaces/Basic.World.cppm`, `implementations/Basic.World.cpp`: the simulation.
-- `interfaces/Basic.DebugShim.cppm`: Crafter.Debug's frame-loop and timeline calls, in every build. In the plain build they are stand-ins that do nothing, so the simulation and `main` need no `#ifdef`.
-- `interfaces/Basic.DebugCommands.cppm`, `implementations/Basic.DebugCommands.cpp`: the commands and watches, compiled only when `Debug::Use` added Crafter.Debug.
-- `implementations/main.cpp`: the loop, with the session under the define.
-
-## Working on Crafter.Debug from here
-
-`project.cpp` loads Crafter.Debug from this checkout (`#pragma crafter dependency "../.."`), so a change there shows up in the next build here.
+A Crafter.Debug example. Build with `crafter-build --debug-api` to include the debug server.
diff --git a/examples/Basic/implementations/Basic.DebugCommands.cpp b/examples/Basic/implementations/Basic.DebugCommands.cpp
deleted file mode 100644
index 83a84ac..0000000
--- a/examples/Basic/implementations/Basic.DebugCommands.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-// SPDX-License-Identifier: MIT
-// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-
-module Basic.DebugCommands;
-import std;
-import Crafter.Debug;
-import Basic.World;
-namespace Debug = Crafter::Debug;
-
-namespace Basic {
- struct SpawnArgs {
- Debug::Required y;
- float x = 0;
- float vy = 0;
- float radius = 0.1f;
- };
-
- struct BallArgs {
- Debug::Required id;
- };
-}
-
-void Basic::RegisterDebug(World& world) {
- // Commands run on the main thread, between ticks, so they touch the
- // world as the simulation does.
- Debug::Command("World_Spawn", "Drop a ball from height y (m), moving at vy (m/s, up is positive); returns its id.",
- [&world](const SpawnArgs& args) -> Debug::Result {
- if (args.radius <= 0) return Debug::Error{ "BadRadius", "radius must be above 0" };
- if (*args.y - args.radius <= world.floor.top) {
- return Debug::Error{ "BelowFloor", std::format("y must clear the floor's top ({} m) by the radius", world.floor.top) };
- }
- return world.Spawn(args.x, *args.y, args.vy, args.radius);
- });
- Debug::Command("World_Reset", "Remove every ball and drop the scene's five again.", [&world] { world.Reset(); });
- Debug::Command("World_Clear", "Remove every ball.", [&world] { world.Clear(); });
- Debug::Command("Ball_Get", "One ball's position, velocity and state.", [&world](const BallArgs& args) -> Debug::Result {
- if (const Ball* ball = world.Find(*args.id)) return *ball;
- return Debug::Error{ "NoBall", std::format("no ball {}; `get balls` lists them", *args.id) };
- });
-
- Debug::Watch("physics.gravity", world.physics.gravity, { .min = -50, .max = 0, .help = "m/s^2" });
- Debug::Watch("physics.restitution", world.physics.restitution, { .min = 0, .max = 1, .help = "share of speed kept by a bounce" });
- Debug::Watch("physics.substeps", world.physics.substeps, { .min = 1, .max = 16, .help = "collision checks per tick" });
- Debug::Watch("floor.top", world.floor.top, { .help = "m" });
- Debug::Watch("floor.thickness", world.floor.thickness, { .min = 0.01, .max = 10, .help = "m" });
- Debug::Watch("world.time", [&world] { return world.Time(); }, { .help = "simulated seconds since the last reset" });
- Debug::Watch("world.count", [&world] { return world.Balls().size(); }, { .help = "balls in the scene" });
- Debug::Watch("world.lost", [&world] { return world.Lost(); }, { .help = "balls below the floor" });
- Debug::Watch("world.fastest", [&world] { return world.Fastest(); }, { .help = "m/s, last tick" });
- Debug::Watch("balls", [&world] { return std::vector(world.Balls().begin(), world.Balls().end()); });
-}
diff --git a/examples/Basic/implementations/Basic.World.cpp b/examples/Basic/implementations/Basic.World.cpp
deleted file mode 100644
index 14459f5..0000000
--- a/examples/Basic/implementations/Basic.World.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-// SPDX-License-Identifier: MIT
-// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-
-module Basic.World;
-import std;
-import Basic.DebugShim;
-namespace Debug = Crafter::Debug;
-
-void Basic::World::Reset() {
- Clear();
- constexpr std::array heights = { 1, 3, 8, 20, 60 };
- for (std::size_t i = 0; i < heights.size(); ++i) {
- Spawn(static_cast(i) - 2.0f, heights[i], 0, 0.1f);
- }
-}
-
-void Basic::World::Clear() {
- balls.clear();
- time = 0;
- fastest = 0;
-}
-
-std::int32_t Basic::World::Spawn(float x, float y, float vy, float radius) {
- const std::int32_t id = nextId++;
- balls.push_back({ .id = id, .x = x, .y = y, .vy = vy, .radius = radius });
- Debug::Log("world", "ball {} dropped from {:.1f} m", id, y);
- return id;
-}
-
-void Basic::World::Tick(float dt) {
- const std::int32_t steps = std::max(1, physics.substeps);
- const float h = dt / static_cast(steps);
- const float bottom = floor.top - floor.thickness;
- fastest = 0;
- for (Ball& ball : balls) {
- for (std::int32_t step = 0; step < steps; ++step) {
- ball.vy += physics.gravity * h;
- ball.x += ball.vx * h;
- ball.y += ball.vy * h;
- if (ball.lost) continue;
- // A falling ball that overlaps the slab bounces off its top.
- if (ball.vy < 0 && ball.y - ball.radius < floor.top && ball.y + ball.radius > bottom) {
- const float speed = -ball.vy;
- ball.y = floor.top + ball.radius;
- ball.vy = speed * physics.restitution;
- if (speed > 1) Debug::Emit("Bounce", BounceEvent{ .ball = ball.id, .speed = speed });
- }
- }
- if (!ball.lost && !Debug::Check(ball.y + ball.radius >= bottom, "physics", "ball {} is below the floor: y {:.2f} m, vy {:.1f} m/s", ball.id, ball.y, ball.vy)) {
- ball.lost = true;
- }
- fastest = std::max(fastest, std::hypot(ball.vx, ball.vy));
- }
- Debug::Sample("solver.fastest", fastest);
- time += dt;
-}
-
-const Basic::Ball* Basic::World::Find(std::int32_t id) const {
- const auto found = std::ranges::find(balls, id, &Ball::id);
- return found == balls.end() ? nullptr : &*found;
-}
-
-std::int32_t Basic::World::Lost() const {
- return static_cast(std::ranges::count(balls, true, &Ball::lost));
-}
diff --git a/examples/Basic/implementations/main.cpp b/examples/Basic/implementations/main.cpp
index 0118182..a931796 100644
--- a/examples/Basic/implementations/main.cpp
+++ b/examples/Basic/implementations/main.cpp
@@ -1,58 +1,16 @@
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-// A headless simulation at 60 ticks a second. The plain build simulates ten
-// seconds as fast as it can and prints what happened; the debug build runs in
-// real time, serving Crafter.Debug, until an agent says quit.
import std;
-import Basic.DebugShim;
-import Basic.World;
#ifdef BASIC_DEBUG_API
-import Crafter.Thread;
-import Basic.DebugCommands;
+import Crafter.Debug;
#endif
-namespace Debug = Crafter::Debug;
-using Clock = std::chrono::steady_clock;
-
-namespace {
- constexpr float dt = 1.0f / 60.0f;
-
-#ifdef BASIC_DEBUG_API
- constexpr bool realTime = true;
-#else
- constexpr bool realTime = false;
-#endif
-}
int main() {
- Basic::World world;
- world.Reset();
-
#ifdef BASIC_DEBUG_API
- // The session's transport runs on Crafter.Thread's pool. An app that
- // already uses the pool starts it as usual; this one only needs it here.
- Crafter::ThreadPool::Start();
- Debug::Session debug({ .name = "basic" });
- Basic::RegisterDebug(world);
- std::println("basic: running; drive it with ./build/crafter-debug, stop it with ./build/crafter-debug quit");
+ std::println("basic: debug build, Crafter.Debug {}", Crafter::Debug::Version());
+#else
+ std::println("basic: plain build");
#endif
-
- const auto tick = std::chrono::duration_cast(std::chrono::duration(dt));
- Clock::time_point next = Clock::now();
- while (!Debug::QuitRequested() && (realTime || world.Time() < 10.0)) {
- Debug::Pump();
- if (Debug::Advance()) world.Tick(dt);
- if constexpr (realTime) {
- next += tick;
- // After a stop in a debugger, carry on from now instead of
- // racing to catch up.
- if (Clock::now() - next > std::chrono::seconds(1)) next = Clock::now();
- std::this_thread::sleep_until(next);
- }
- }
-
- std::println("basic: {:.1f} s simulated; {} balls, {} below the floor", world.Time(), world.Balls().size(), world.Lost());
- for (const Basic::Ball& ball : world.Balls()) {
- if (ball.lost) std::println(" ball {} fell through the floor", ball.id);
- }
+ return 0;
}
diff --git a/examples/Basic/interfaces/Basic.DebugCommands.cppm b/examples/Basic/interfaces/Basic.DebugCommands.cppm
deleted file mode 100644
index da9c73d..0000000
--- a/examples/Basic/interfaces/Basic.DebugCommands.cppm
+++ /dev/null
@@ -1,14 +0,0 @@
-// SPDX-License-Identifier: MIT
-// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-
-// What an agent can call and read in a debug build. project.cpp compiles
-// this module only when Debug::Use added Crafter.Debug, so the plain build
-// has none of it.
-export module Basic.DebugCommands;
-import Basic.World;
-
-export namespace Basic {
- // Registers the commands and watches on `world`, which must outlive the
- // Session.
- void RegisterDebug(World& world);
-}
diff --git a/examples/Basic/interfaces/Basic.DebugShim.cppm b/examples/Basic/interfaces/Basic.DebugShim.cppm
deleted file mode 100644
index ec79d73..0000000
--- a/examples/Basic/interfaces/Basic.DebugShim.cppm
+++ /dev/null
@@ -1,26 +0,0 @@
-// SPDX-License-Identifier: MIT
-// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-
-// Crafter.Debug's frame-loop and timeline calls, in every build: the real
-// ones under --debug-api, and in a plain build stand-ins that do nothing, so
-// the simulation and main need no #ifdef around them. This is one of the
-// app's own sources, so the define Debug::Use adds reaches it.
-export module Basic.DebugShim;
-import std;
-#ifdef BASIC_DEBUG_API
-export import Crafter.Debug;
-#else
-export namespace Crafter::Debug {
- inline void Pump() {}
- inline bool Advance() { return true; }
- inline bool Paused() { return false; }
- inline std::uint32_t TakeSteps() { return 0; }
- inline bool QuitRequested() { return false; }
- template void Log(A&&...) {}
- template void LogWarn(A&&...) {}
- template void LogError(A&&...) {}
- template bool Check(bool ok, A&&...) { return ok; }
- template void Emit(A&&...) {}
- template void Sample(std::string_view, const T&) {}
-}
-#endif
diff --git a/examples/Basic/interfaces/Basic.World.cppm b/examples/Basic/interfaces/Basic.World.cppm
deleted file mode 100644
index 3ec2b06..0000000
--- a/examples/Basic/interfaces/Basic.World.cppm
+++ /dev/null
@@ -1,66 +0,0 @@
-// SPDX-License-Identifier: MIT
-// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-
-// Balls dropped onto a floor slab, in two dimensions, at a fixed step. y is
-// up, in metres; the slab's top is at floor.top and it is floor.thickness
-// thick.
-export module Basic.World;
-import std;
-
-export namespace Basic {
- struct Ball {
- std::int32_t id = 0;
- float x = 0;
- float y = 0;
- float vx = 0;
- float vy = 0;
- float radius = 0.1f;
- // Below the floor, and so out of the scene for good.
- bool lost = false;
- };
-
- struct Physics {
- float gravity = -9.81f;
- // The share of its speed a ball keeps when it bounces.
- float restitution = 0.6f;
- // Collision checks per tick.
- std::int32_t substeps = 1;
- };
-
- struct Floor {
- float top = 0;
- float thickness = 0.1f;
- };
-
- // What `wait --event Bounce` waits for, sent for bounces faster than 1 m/s.
- struct BounceEvent {
- std::int32_t ball = 0;
- float speed = 0;
- };
-
- class World {
- public:
- Physics physics;
- Floor floor;
-
- // Removes every ball and drops the scene's five.
- void Reset();
- void Clear();
- // Returns the new ball's id.
- std::int32_t Spawn(float x, float y, float vy, float radius);
- void Tick(float dt);
-
- const std::deque& Balls() const { return balls; }
- const Ball* Find(std::int32_t id) const;
- double Time() const { return time; }
- std::int32_t Lost() const;
- // The fastest ball's speed in the last tick, in m/s.
- float Fastest() const { return fastest; }
-
- private:
- std::deque balls;
- std::int32_t nextId = 1;
- double time = 0;
- float fastest = 0;
- };
-}
diff --git a/examples/Basic/project.cpp b/examples/Basic/project.cpp
index c3fc25d..dba5ef5 100644
--- a/examples/Basic/project.cpp
+++ b/examples/Basic/project.cpp
@@ -24,15 +24,10 @@ extern "C" Configuration CrafterBuildProject(std::span a
for (const std::string_view arg : args) {
if (arg != "--debug-api") depArgs.emplace_back(arg);
}
- const bool debugApi = Debug::Use(cfg, { .enabled = opts.Has("--debug-api"), .flag = "--debug-api", .define = "BASIC_DEBUG_API", .args = depArgs });
+ Debug::Use(cfg, { .enabled = opts.Has("--debug-api"), .flag = "--debug-api", .define = "BASIC_DEBUG_API", .args = depArgs });
- std::vector interfaces = { "interfaces/Basic.DebugShim", "interfaces/Basic.World" };
- std::vector implementations = { "implementations/Basic.World", "implementations/main" };
- // The agent's commands and watches, in debug builds only.
- if (debugApi) {
- interfaces.emplace_back("interfaces/Basic.DebugCommands");
- implementations.emplace_back("implementations/Basic.DebugCommands");
- }
+ std::array interfaces = {};
+ std::array implementations = { "implementations/main" };
cfg.GetInterfacesAndImplementations(interfaces, implementations);
return cfg;
}
diff --git a/implementations/Crafter.Debug-Session.cpp b/implementations/Crafter.Debug-Session.cpp
index 932f163..d4df4b3 100644
--- a/implementations/Crafter.Debug-Session.cpp
+++ b/implementations/Crafter.Debug-Session.cpp
@@ -269,9 +269,6 @@ namespace Crafter::Debug {
bool armedOnCheck = false;
bool armedTrap = false;
std::string pauseReason;
- // The frame the pause began at. Frames go on counting while paused,
- // so the current one says nothing about when it stopped.
- std::uint64_t pausedAt = 0;
bool shutDown = false;
// The Pump thread's own.
@@ -336,12 +333,11 @@ namespace Crafter::Debug {
}
void PauseNow(std::string reason, bool trap) {
+ paused.store(true);
{
std::lock_guard lock(mutex);
pauseReason = reason;
- pausedAt = frame.load();
}
- paused.store(true);
Detail::Timeline::Instance().Append(Detail::MakeEntry(EntryKind::Pause, "debug", std::format("paused: {}", reason), std::source_location::current()));
if (trap && TracerAttached()) ::raise(SIGTRAP);
}
@@ -433,7 +429,6 @@ namespace Crafter::Debug {
{
std::lock_guard lock(mutex);
status.Set("pauseReason", Value(pauseReason));
- if (paused.load()) status.Set("pausedAt", Value(pausedAt));
status.Set("queued", Value(jobs.size()));
status.Set("waiting", Value(waiters.size()));
status.Set("following", Value(followers.size()));
@@ -620,7 +615,7 @@ namespace Crafter::Debug {
waiter.kind = WaitKind::Paused;
if (paused.load()) {
std::lock_guard lock(mutex);
- return exchange->Reply(MakeReply(Object({ { "frame", Value(frame.load()) }, { "pausedAt", Value(pausedAt) }, { "reason", Value(pauseReason) } })));
+ return exchange->Reply(MakeReply(Object({ { "frame", Value(frame.load()) }, { "reason", Value(pauseReason) } })));
}
}
std::lock_guard lock(mutex);
@@ -919,13 +914,11 @@ namespace Crafter::Debug {
case WaitKind::Paused:
if (paused.load()) {
std::string reason;
- std::uint64_t since = 0;
{
std::lock_guard lock(mutex);
reason = pauseReason;
- since = pausedAt;
}
- waiter.exchange->Reply(MakeReply(Object({ { "frame", Value(current) }, { "pausedAt", Value(since) }, { "reason", Value(reason) } })));
+ waiter.exchange->Reply(MakeReply(Object({ { "frame", Value(current) }, { "reason", Value(reason) } })));
done = true;
}
break;
diff --git a/implementations/Crafter.Debug.Cli-Client.cpp b/implementations/Crafter.Debug.Cli-Client.cpp
index 3cbb467..6e03563 100644
--- a/implementations/Crafter.Debug.Cli-Client.cpp
+++ b/implementations/Crafter.Debug.Cli-Client.cpp
@@ -360,15 +360,10 @@ namespace {
const bool alive = std::ranges::any_of(env.list(), [&](const Instance& candidate) { return candidate.record.instanceId == instance->record.instanceId; });
if (!alive) {
Err() << std::format("crafter-debug: {} has exited\n", instance->record.name);
- return exitNoInstance;
+ } else {
+ Err() << std::format("crafter-debug: cannot reach {} on port {}: {}\n", instance->record.name, instance->record.port, why);
}
- // Its lock says it lives, yet not even the handshake is
- // answered: the whole process is stopped, by a debugger most
- // likely, or its network threads are stuck.
- Err() << std::format("crafter-debug: {} is alive but not answering on port {} ({}): stopped in a debugger, or hung.\n",
- instance->record.name, instance->record.port, why);
- PrintAttach(true);
- return exitTimeout;
+ return exitNoInstance;
}
// A request that got no reply. The app may be gone, stopped in a
@@ -403,8 +398,7 @@ namespace {
void PrintAttach(bool toErr) {
std::ostream& stream = toErr ? Err() : Out();
const InstanceRecord& record = instance->record;
- const std::string lldb = env.lldb ? env.lldb() : std::string();
- const std::string debugger = lldb.empty() ? std::string("gdb") : lldb;
+ const std::string debugger = env.haveLldb && env.haveLldb() ? "lldb" : "gdb";
if (!record.flatpakInstance.empty()) {
stream << std::format(" attach (on the host): flatpak enter {} {} -p {}\n", record.flatpakInstance, debugger, record.pid);
stream << std::format(" check whether a debugger holds it: flatpak enter {} grep State /proc/{}/status (t = stopped by a tracer)\n", record.flatpakInstance, record.pid);
@@ -480,11 +474,8 @@ namespace {
const Value& s = *result;
const bool paused = s.Find("paused")->AsBool();
const std::string reason = s.Find("pauseReason") ? s.Find("pauseReason")->AsString() : std::string();
- const Value* pausedAt = s.Find("pausedAt");
Out() << std::format("{} frame {} {:.1f} fps {}\n", s.Find("name")->AsString(), s.Find("frame")->Dump(), s.Find("fps")->AsNumber(),
- !paused ? std::string("running")
- : pausedAt != nullptr ? std::format("PAUSED since frame {} ({})", pausedAt->Dump(), reason)
- : std::format("PAUSED ({})", reason));
+ paused ? std::format("PAUSED ({})", reason) : std::string("running"));
std::string armed;
if (const Value* when = s.Find("armed")->Find("when")) armed += std::format(" pause armed: when '{}'", when->AsString());
if (s.Find("armed")->Find("onCheck") != nullptr) armed += " pause armed: on the next failing check";
@@ -712,11 +703,7 @@ namespace {
} else if (const Value* event = r.Find("event")) {
Out() << std::format("{} at frame {}: {}\n", event->AsString(), r.Find("frame")->Dump(), Display(*r.Find("payload")));
} else if (const Value* reason = r.Find("reason")) {
- // When it stopped, not when this wait looked: frames go on
- // counting while paused.
- const Value* pausedAt = r.Find("pausedAt");
- const std::string since = pausedAt != nullptr ? pausedAt->Dump() : r.Find("frame")->Dump();
- Out() << std::format("paused at frame {}{}: {}\n", since, since != r.Find("frame")->Dump() ? std::format(" (now {})", r.Find("frame")->Dump()) : std::string(), reason->AsString());
+ Out() << std::format("paused at frame {}: {}\n", r.Find("frame")->Dump(), reason->AsString());
} else {
Out() << std::format("frame {}\n", r.Find("frame")->Dump());
}
@@ -891,19 +878,13 @@ namespace {
for (std::size_t i = 0; i < args.size(); ++i) {
const std::string_view arg = args[i];
if (!options.command.empty()) {
- // Global flags go anywhere, as agents write them: `wait
- // --paused --timeout 60s`. No command has options of these
- // names, but for `call --json '{...}'`, its arguments as JSON.
- const bool callArguments = options.command == "call" && arg == "--json" && i + 1 < args.size() && args[i + 1].starts_with('{');
- if (arg == "--json" && !callArguments) {
+ // Global flags may follow the command too, before its own.
+ if (arg == "--json") {
options.json = true;
continue;
}
- if (arg != "--timeout" && arg != "-i" && arg != "--instance") {
- options.rest.emplace_back(arg);
- if (callArguments) options.rest.emplace_back(args[++i]);
- continue;
- }
+ options.rest.emplace_back(arg);
+ continue;
}
if ((arg == "-i" || arg == "--instance") && i + 1 < args.size()) {
options.instance = args[++i];
@@ -916,9 +897,6 @@ namespace {
return exitUsage;
}
options.timeout = *timeout;
- } else if (arg == "--timeout" || arg == "-i" || arg == "--instance") {
- *env.err << std::format("crafter-debug: {} needs a value\n", arg);
- return exitUsage;
} else if (arg == "-h" || arg == "--help") {
*env.out << usage;
return exitOk;
diff --git a/implementations/Crafter.Debug.Cli-Quic.cpp b/implementations/Crafter.Debug.Cli-Quic.cpp
deleted file mode 100644
index 2ac607d..0000000
--- a/implementations/Crafter.Debug.Cli-Quic.cpp
+++ /dev/null
@@ -1,163 +0,0 @@
-// SPDX-License-Identifier: LGPL-3.0-only
-// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-
-module Crafter.Debug.Cli:Quic_impl;
-import std;
-import Crafter.Network;
-import Crafter.Debug.Core;
-import :Client;
-import :Quic;
-
-using namespace Crafter::Debug;
-using namespace Crafter::Debug::Cli;
-using Crafter::ClientQUIC;
-using Crafter::QUICClientCredentials;
-using Crafter::QUICStream;
-using Clock = std::chrono::steady_clock;
-
-namespace {
- QUICClientCredentials Credentials() {
- QUICClientCredentials credentials;
- // The app serves a per-user development certificate. What
- // authenticates is the token in each request, which only this user
- // can read.
- credentials.insecureNoServerValidation = true;
- // A port nobody answers on fails in seconds, not at msquic's 10.
- credentials.settings.handshakeIdleTimeoutMs = 3'000;
- // Keep-alives under the idle timeout hold a quiet `log --follow` or
- // a long `wait` open; an app that died is noticed within the timeout.
- credentials.settings.idleTimeoutMs = 10'000;
- credentials.settings.keepAliveIntervalMs = 2'000;
- return credentials;
- }
-
- // What a request's callbacks, on msquic's worker, hand the thread that
- // waits for its reply.
- struct Inbox {
- std::mutex mutex;
- std::condition_variable changed;
- std::string partial;
- std::deque lines;
- bool ended = false;
- bool clean = false;
-
- void Add(std::span data) {
- {
- std::lock_guard lock(mutex);
- partial.append(data.data(), data.size());
- std::size_t start = 0;
- for (std::size_t newline = partial.find('\n'); newline != std::string::npos; newline = partial.find('\n', start)) {
- lines.emplace_back(partial, start, newline - start);
- start = newline + 1;
- }
- partial.erase(0, start);
- }
- changed.notify_all();
- }
-
- void End(bool wasClean) {
- {
- std::lock_guard lock(mutex);
- ended = true;
- clean = wasClean;
- }
- changed.notify_all();
- }
- };
-
- std::string Abbreviated(std::string_view text) {
- return text.size() <= 200 ? std::string(text) : std::format("{}...", text.substr(0, 200));
- }
-
- class QuicConnection final : public Connection {
- public:
- explicit QuicConnection(std::uint16_t port) : port(port) {}
-
- std::expected Call(const Value& request, std::chrono::milliseconds timeout,
- const std::function& onLine) override {
- const Clock::time_point deadline = Clock::now() + timeout;
- if (!client) {
- try {
- client = std::make_unique(std::string("127.0.0.1"), port, std::string(alpn), Credentials());
- } catch (const std::exception& error) {
- return std::unexpected(CallError{ CallError::Kind::Unreachable, error.what() });
- }
- }
- auto result = Send(request, deadline, onLine);
- // A lost connection is not reused: the next call dials again.
- // After Send, whose stream must go before its connection.
- if (!result && result.error().kind == CallError::Kind::Unreachable) client.reset();
- return result;
- }
-
- private:
- std::uint16_t port;
- std::unique_ptr client;
-
- std::expected Send(const Value& request, Clock::time_point deadline,
- const std::function& onLine) {
- const auto inbox = std::make_shared();
- QUICStream stream;
- try {
- stream = client->OpenStream();
- } catch (const std::exception& error) {
- return std::unexpected(CallError{ CallError::Kind::Unreachable, error.what() });
- }
- stream.OnRecieve([inbox](std::span data) { inbox->Add(data); },
- [inbox](bool clean) { inbox->End(clean); });
- std::string text = request.Dump();
- text += '\n';
- try {
- stream.SendSync(text.data(), static_cast(text.size()), true);
- } catch (const std::exception& error) {
- return std::unexpected(CallError{ CallError::Kind::Unreachable, error.what() });
- }
-
- std::unique_lock lock(inbox->mutex);
- for (;;) {
- if (!inbox->lines.empty()) {
- const std::string line = std::move(inbox->lines.front());
- inbox->lines.pop_front();
- // Not under the lock: onLine prints, and the callbacks
- // that fill the inbox must not wait for a terminal.
- lock.unlock();
- Value value;
- try {
- value = Value::Parse(line);
- } catch (const ParseError& error) {
- stream.Abort();
- return std::unexpected(CallError{ CallError::Kind::Broken, std::format("{} in {}", error.what(), Abbreviated(line)) });
- }
- if (!value.IsObject()) {
- stream.Abort();
- return std::unexpected(CallError{ CallError::Kind::Broken, std::format("not an object: {}", Abbreviated(line)) });
- }
- // The reply is the object with a result or an error;
- // anything before it is a stream line.
- if (value.Find("result") != nullptr || value.Find("error") != nullptr) return value;
- if (onLine && !onLine(value)) {
- stream.Abort();
- Value stopped = Value::MakeObject();
- stopped.Set("ended", Value("stopped by the client"));
- return MakeReply(std::move(stopped));
- }
- lock.lock();
- continue;
- }
- if (inbox->ended) {
- if (inbox->clean) return std::unexpected(CallError{ CallError::Kind::Broken, "the app ended the request without a reply" });
- return std::unexpected(CallError{ CallError::Kind::Unreachable, "the connection to the app was lost" });
- }
- if (inbox->changed.wait_until(lock, deadline) == std::cv_status::timeout && inbox->lines.empty() && !inbox->ended) {
- lock.unlock();
- stream.Abort();
- return std::unexpected(CallError{ CallError::Kind::TimedOut, "no reply in time" });
- }
- }
- }
- };
-}
-
-std::unique_ptr Crafter::Debug::Cli::ConnectQuic(const InstanceRecord& instance) {
- return std::make_unique(instance.port);
-}
diff --git a/implementations/main.cpp b/implementations/main.cpp
index d0e4f57..011d3d5 100644
--- a/implementations/main.cpp
+++ b/implementations/main.cpp
@@ -1,35 +1,26 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-// crafter-debug: Cli::Run with the QUIC transport.
+// crafter-debug: Cli::Run with the real transport.
import std;
-import Crafter.Thread;
import Crafter.Debug.Core;
import Crafter.Debug.Cli;
using namespace Crafter::Debug;
-int main(int argc, char** argv) {
- // Crafter.Network reports some failures through the pool. One request
- // at a time needs one worker.
- Crafter::ThreadPool::Start(2);
- const std::vector args(argv + 1, argv + argc);
- std::int32_t code = 0;
- {
- Cli::Environment environment;
- environment.connect = Cli::ConnectQuic;
- environment.lldb = [] {
- for (const char* path : { "/app/bin/lldb", "/usr/bin/lldb" }) {
- if (std::filesystem::exists(path)) return std::string(path);
- }
- return std::string();
- };
- // Run closes its connections before it returns.
- code = Cli::Run(args, environment);
- }
- std::cout.flush();
- std::cerr.flush();
- std::fflush(nullptr);
- // Not through exit: msquic's teardown at exit waits for connections,
- // and the pool's workers would need stopping first.
- std::_Exit(code);
+namespace {
+ // Until the QUIC transport lands: every call reports it unreachable.
+ class Unbuilt : public Cli::Connection {
+ public:
+ std::expected Call(const Value&, std::chrono::milliseconds, const std::function&) override {
+ return std::unexpected(Cli::CallError{ Cli::CallError::Kind::Unreachable, "this client was built without its transport" });
+ }
+ };
+}
+
+int main(int argc, char** argv) {
+ const std::vector args(argv + 1, argv + argc);
+ Cli::Environment environment;
+ environment.connect = [](const InstanceRecord&) -> std::unique_ptr { return std::make_unique(); };
+ environment.haveLldb = [] { return std::filesystem::exists("/app/bin/lldb") || std::filesystem::exists("/usr/bin/lldb"); };
+ return Cli::Run(args, environment);
}
diff --git a/interfaces/Crafter.Debug.Cli-Client.cppm b/interfaces/Crafter.Debug.Cli-Client.cppm
index 02d56d4..5d8dd09 100644
--- a/interfaces/Crafter.Debug.Cli-Client.cppm
+++ b/interfaces/Crafter.Debug.Cli-Client.cppm
@@ -58,10 +58,8 @@ export namespace Crafter::Debug::Cli {
std::ostream* err = &std::cerr;
// Where a screenshot without -o goes, relative paths included.
std::filesystem::path cwd = std::filesystem::current_path();
- // Where lldb is here, for the attach command `debugger` prints: its
- // absolute path, since `flatpak enter` runs a command without the
- // sandbox's PATH, which /app/bin is on. Empty for none: gdb then.
- std::function lldb;
+ // Whether `lldb` exists here, for the attach command `debugger` prints.
+ std::function haveLldb;
};
std::int32_t Run(std::span args, Environment& environment);
diff --git a/interfaces/Crafter.Debug.Cli-Quic.cppm b/interfaces/Crafter.Debug.Cli-Quic.cppm
deleted file mode 100644
index 6018f8c..0000000
--- a/interfaces/Crafter.Debug.Cli-Quic.cppm
+++ /dev/null
@@ -1,16 +0,0 @@
-// SPDX-License-Identifier: LGPL-3.0-only
-// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-
-// The client's transport: a Connection over QUIC to an instance's port on
-// 127.0.0.1, one stream per request. The library's :Transport describes the
-// wire.
-export module Crafter.Debug.Cli:Quic;
-import std;
-import Crafter.Debug.Core;
-import :Client;
-
-export namespace Crafter::Debug::Cli {
- // Connects on the first call and keeps the connection for later ones,
- // reconnecting after one is lost. Needs Crafter.Thread's pool running.
- std::unique_ptr ConnectQuic(const InstanceRecord& instance);
-}
diff --git a/interfaces/Crafter.Debug.Cli.cppm b/interfaces/Crafter.Debug.Cli.cppm
index 8e83d7a..0d33b6c 100644
--- a/interfaces/Crafter.Debug.Cli.cppm
+++ b/interfaces/Crafter.Debug.Cli.cppm
@@ -1,8 +1,6 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-// The crafter-debug client, as a library so tests can run it in process:
-// the program (:Client) and its QUIC transport (:Quic).
+// The crafter-debug client, as a library so tests can run it in process.
export module Crafter.Debug.Cli;
export import :Client;
-export import :Quic;
diff --git a/interfaces/Crafter.Debug.Core-Codec.cppm b/interfaces/Crafter.Debug.Core-Codec.cppm
index 9e38323..5c6c23c 100644
--- a/interfaces/Crafter.Debug.Core-Codec.cppm
+++ b/interfaces/Crafter.Debug.Core-Codec.cppm
@@ -192,20 +192,7 @@ export namespace Crafter::Debug {
template
struct Codec {
- static Value Encode(T value) {
- // A float as the shortest decimal that reads back as it: 0.1f
- // widened is 0.10000000149011612, which is what an agent would
- // otherwise read for every float.
- if constexpr (sizeof(T) < sizeof(double)) {
- if (std::isfinite(value)) {
- std::array text{};
- const auto written = std::to_chars(text.data(), text.data() + text.size(), value);
- double shortest = 0;
- if (written.ec == std::errc() && std::from_chars(text.data(), written.ptr, shortest).ec == std::errc()) return Value(shortest);
- }
- }
- return Value(static_cast(value));
- }
+ static Value Encode(T value) { return Value(static_cast(value)); }
static void Decode(const Value& value, T& out, DecodeContext& context) {
if (value.IsNumber()) {
diff --git a/project.cpp b/project.cpp
index 6e03b38..422d9d8 100644
--- a/project.cpp
+++ b/project.cpp
@@ -14,7 +14,8 @@
// Debug::Use (tooling/), which also writes their launcher.
//
// The library and the client talk QUIC through Crafter.Network, which comes
-// from forgejo, or with --local from the checkout beside this one.
+// from forgejo, with --local from the checkout beside this one, or from the
+// project.cpp $CRAFTER_DEBUG_NETWORK names (a Network worktree).
import std;
import Crafter.Build;
namespace fs = std::filesystem;
@@ -38,6 +39,9 @@ namespace {
// than one module built twice.
Configuration* Network(std::span args) {
const std::vector forwarded(args.begin(), args.end());
+ if (const char* local = std::getenv("CRAFTER_DEBUG_NETWORK"); local != nullptr && *local != '\0') {
+ return LocalProject({ .projectFile = local, .args = forwarded });
+ }
if (std::ranges::find(args, std::string_view("--local")) != args.end()) {
return LocalProject({ .projectFile = Root().parent_path() / "Crafter.Network" / "project.cpp", .args = forwarded });
}
@@ -168,7 +172,7 @@ extern "C" Configuration CrafterBuildProject(std::span a
cli.mtune = cfg.mtune;
cli.sysroot = cfg.sysroot;
cli.debug = cfg.debug;
- cli.dependencies = { &core, network };
+ cli.dependencies = { &core };
client.dependencies = { &cli };
{
@@ -192,8 +196,8 @@ extern "C" Configuration CrafterBuildProject(std::span a
core.GetInterfacesAndImplementations(interfaces, implementations);
}
{
- std::array interfaces = { "interfaces/Crafter.Debug.Cli-Client", "interfaces/Crafter.Debug.Cli-Quic", "interfaces/Crafter.Debug.Cli" };
- std::array implementations = { "implementations/Crafter.Debug.Cli-Client", "implementations/Crafter.Debug.Cli-Quic" };
+ std::array interfaces = { "interfaces/Crafter.Debug.Cli-Client", "interfaces/Crafter.Debug.Cli" };
+ std::array implementations = { "implementations/Crafter.Debug.Cli-Client" };
cli.GetInterfacesAndImplementations(interfaces, implementations);
}
{
@@ -228,7 +232,6 @@ extern "C" Configuration CrafterBuildProject(std::span a
for (const std::string_view test : coreTests) cfg.AddTest(test).Dependencies({ &core });
for (const std::string_view test : libraryTests) cfg.AddTest(test).Dependencies({ &cfg });
cfg.AddTest("ShouldRunClientCommands").Dependencies({ &cfg, &cli });
- cfg.AddTest("ShouldServeOverQuic").Dependencies({ &cfg, &cli });
}
return cfg;
}
diff --git a/tests/ShouldPauseAndStep/main.cpp b/tests/ShouldPauseAndStep/main.cpp
index 0a2b973..f17aafd 100644
--- a/tests/ShouldPauseAndStep/main.cpp
+++ b/tests/ShouldPauseAndStep/main.cpp
@@ -92,17 +92,7 @@ int main() {
const Value pausedReply = ResultOf(*waitPaused);
const Value* reason = pausedReply.Find("reason");
Check(reason != nullptr && reason->AsString().find("counter >= 3") != std::string::npos, "wait --paused replies with the reason");
- // Frames go on while paused: a wait that comes later must still say
- // when the pause began, not the frame it looked at.
- const std::uint64_t pausedAt = pausedReply.Find("pausedAt")->AsInteger();
- for (std::int32_t frame = 0; frame < 5; ++frame) Pump();
- const Value later = ResultOf(*Send("debug.wait", R"({"paused": true})"));
- const Value statusWhilePaused = ResultOf(*Send("debug.status"));
- Check(later.Find("pausedAt")->AsInteger() == static_cast(pausedAt) && later.Find("frame")->AsInteger() >= static_cast(pausedAt) + 5
- && statusWhilePaused.Find("pausedAt")->AsInteger() == static_cast(pausedAt),
- std::format("a later wait and status say when the pause began (frame {}), not the frame now", pausedAt));
Send("debug.resume");
- Check(ResultOf(*Send("debug.status")).Find("pausedAt") == nullptr, "status has no pausedAt once resumed");
Check(ResultOf(*Send("debug.pause", R"({"onCheck": true})")).Find("armed")->AsString() == "onCheck", "pause --on-check arms");
Check(Advance(), "running before the check fails");
diff --git a/tests/ShouldResolveWatchPaths/main.cpp b/tests/ShouldResolveWatchPaths/main.cpp
index 3a48747..23a95fd 100644
--- a/tests/ShouldResolveWatchPaths/main.cpp
+++ b/tests/ShouldResolveWatchPaths/main.cpp
@@ -51,7 +51,7 @@ int main() {
});
Watch("score", [] { return 1234; });
- Check(registry().Resolve("physics.gravity").value.AsNumber() == -9.81, "a variable watch reads the variable, a float as its shortest decimal");
+ Check(registry().Resolve("physics.gravity").value.AsNumber() == static_cast(-9.81F), "a variable watch reads the variable");
Check(registry().Resolve("bodies[1].pos.y").value.AsNumber() == 4, "a path reads into a watched value");
Check(registry().Resolve("bodies[1]").value.Find("id")->AsInteger() == 2, "an index reads an item");
diff --git a/tests/ShouldRoundTripAggregates/main.cpp b/tests/ShouldRoundTripAggregates/main.cpp
index f6e0abe..be30d8e 100644
--- a/tests/ShouldRoundTripAggregates/main.cpp
+++ b/tests/ShouldRoundTripAggregates/main.cpp
@@ -6,9 +6,7 @@
// maps, a scoped enum, Required) through Value and its text, with no
// hand-written serialization. Fields the input leaves out keep their default
// member initializers, null clears an optional, and an enum also accepts its
-// integer. A float encodes as its shortest decimal, 0.1 rather than the
-// 0.10000000149011612 it widens to, which every float watch used to show.
-// Guards the reflection that command arguments and results rely on.
+// integer. Guards the reflection that command arguments and results rely on.
import std;
import Crafter.Debug.Core;
using namespace Crafter::Debug;
@@ -76,13 +74,6 @@ int main() {
Check(!partial.target.has_value(), "null clears an optional");
Check(partial.mode == Game::Mode::Build, "an enum accepts its integer");
- Check(Encode(0.1F).Dump() == "0.1" && Encode(-9.81F).Dump() == "-9.81" && Encode(4.0F).Dump() == "4.0",
- std::format("a float reads as its shortest decimal ({}, {})", Encode(0.1F).Dump(), Encode(-9.81F).Dump()));
- float tenth = 0;
- DecodeContext tenthContext;
- Decode(Value::Parse(Encode(0.1F).Dump()), tenth, tenthContext);
- Check(tenthContext.Ok() && tenth == 0.1F && Encode(0.1).Dump() == "0.1", "and decodes to the same float; a double is unchanged");
-
float nan = 0;
DecodeContext nanContext;
Decode(Encode(std::numeric_limits::quiet_NaN()), nan, nanContext);
diff --git a/tests/ShouldRunClientCommands/main.cpp b/tests/ShouldRunClientCommands/main.cpp
index 2817e04..4694e7c 100644
--- a/tests/ShouldRunClientCommands/main.cpp
+++ b/tests/ShouldRunClientCommands/main.cpp
@@ -85,7 +85,7 @@ namespace {
environment.out = &out;
environment.err = &err;
environment.cwd = fs::temp_directory_path() / "crafter-debug-ShouldRunClientCommands";
- environment.lldb = [] { return std::string(); };
+ environment.haveLldb = [] { return false; };
const std::int32_t code = Cli::Run(args, environment);
return { code, out.str(), err.str() };
}
@@ -161,10 +161,6 @@ int main() {
Check(r.code == 0 && Has(r.out, "'score >= 1' held at frame"), "wait for a condition");
r = Run({ "--timeout", "100ms", "wait", "score < 0" }, instances);
Check(r.code == 5 && Has(r.err, "was not true within"), "a wait that times out exits 5 and says what the paths were");
- r = Run({ "wait", "score < 0", "--timeout", "100ms" }, instances);
- Check(r.code == 5 && Has(r.err, "was not true within"), std::format("global flags also go after the command's own ({})", r.err));
- r = Run({ "wait", "--frames", "1", "--timeout" }, instances);
- Check(r.code == 2 && Has(r.err, "--timeout needs a value"), "a global flag without its value is a usage error");
r = Run({ "log", "--last", "5" }, instances);
Check(r.code == 0 && Has(r.out, "AGENT"), "log shows the agent's actions");
@@ -182,12 +178,6 @@ int main() {
} catch (const ParseError&) {
}
Check(r.code == 0 && json, "--json prints JSON");
- r = Run({ "status", "--json" }, instances);
- Check(r.code == 0 && r.out.starts_with("{"), "--json after the command too");
- r = Run({ "call", "Player_SetAim", "--json", R"({"slot": 4, "yaw": 5})" }, instances);
- Check(r.code == 0 && Has(r.out, R"({"slot":4,"yaw":5.0})"), std::format("call takes its arguments as JSON ({})", r.out + r.err));
- r = Run({ "call", "Player_SetAim", "--json", R"({"slot": 4})", "yaw=7", "--json" }, instances);
- Check(r.code == 0 && Has(r.out, R"({"slot":4,"yaw":7.0})"), std::format("JSON arguments with key=value on top, and --json after them ({})", r.out + r.err));
r = Run({ "stauts" }, instances);
Check(r.code == 2 && Has(r.err, "did you mean 'status'"), "a mistyped command name gets a suggestion");
diff --git a/tests/ShouldServeOverQuic/main.cpp b/tests/ShouldServeOverQuic/main.cpp
deleted file mode 100644
index 9b39170..0000000
--- a/tests/ShouldServeOverQuic/main.cpp
+++ /dev/null
@@ -1,275 +0,0 @@
-// SPDX-License-Identifier: LGPL-3.0-only
-// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
-
-// The QUIC transport end to end: a Session that listens for real, reached
-// over loopback by the client's own code, as crafter-debug reaches it. What
-// the in-process tests can't see:
-// - discovery lists the instance with its port, token, protocol, source and
-// client, and drops it once the Session is gone;
-// - status, call, get and set work through the client, and log --follow
-// streams lines as they are logged, then ends;
-// - a wrong token is refused, a request that isn't JSON is answered, and
-// one over 1 MiB is answered with an error instead of being buffered;
-// - requests in parallel, on streams of one connection and on separate
-// connections, each get their own reply;
-// - destroying the Session answers a waiting follower and closes promptly
-// with a client still connected, and a client then finds the port dead
-// within seconds;
-// - an instance alive by its lock but silent at its port, as one a
-// debugger holds, is reported as such with how to attach, not as gone.
-#include
-#include
-import std;
-import Crafter.Thread;
-import Crafter.Network;
-import Crafter.Debug;
-import Crafter.Debug.Cli;
-using namespace Crafter::Debug;
-namespace fs = std::filesystem;
-using namespace std::chrono_literals;
-
-namespace {
- std::int32_t failures = 0;
-
- void Check(bool ok, std::string_view what) {
- std::println("{} {}", ok ? "PASS" : "FAIL", what);
- if (!ok) ++failures;
- }
-
- bool Has(const std::string& text, std::string_view part) {
- return text.find(part) != std::string::npos;
- }
-
- struct AddArgs {
- Required a;
- std::int32_t b = 0;
- };
-
- struct Ran {
- std::int32_t code = 0;
- std::string out;
- std::string err;
- };
-
- // crafter-debug, with its real transport, against the discovery
- // directory the test set.
- Ran Run(std::vector args) {
- std::ostringstream out;
- std::ostringstream err;
- Cli::Environment environment;
- environment.connect = Cli::ConnectQuic;
- environment.out = &out;
- environment.err = &err;
- environment.lldb = [] { return std::string(); };
- const std::int32_t code = Cli::Run(args, environment);
- return { code, out.str(), err.str() };
- }
-
- // A request sent by hand, on its own stream: what came back, and how
- // the stream ended.
- struct Received {
- std::mutex mutex;
- std::condition_variable changed;
- std::string bytes;
- bool ended = false;
- bool clean = false;
- };
-
- struct Raw {
- std::shared_ptr received = std::make_shared();
- Crafter::QUICStream stream;
-
- bool Wait(std::chrono::milliseconds limit) {
- std::unique_lock lock(received->mutex);
- return received->changed.wait_for(lock, limit, [&] { return received->ended; });
- }
-
- std::string Bytes() {
- std::lock_guard lock(received->mutex);
- return received->bytes;
- }
- };
-
- std::unique_ptr Send(Crafter::ClientQUIC& client, std::string request) {
- auto raw = std::make_unique();
- raw->stream = client.OpenStream();
- const std::shared_ptr received = raw->received;
- raw->stream.OnRecieve(
- [received](std::span data) {
- {
- std::lock_guard lock(received->mutex);
- received->bytes.append(data.data(), data.size());
- }
- received->changed.notify_all();
- },
- [received](bool clean) {
- {
- std::lock_guard lock(received->mutex);
- received->ended = true;
- received->clean = clean;
- }
- received->changed.notify_all();
- });
- raw->stream.SendAsync(request.data(), static_cast(request.size()), true, {});
- return raw;
- }
-
- std::string Request(std::string_view token, std::string_view method, std::string_view params = "{}") {
- return std::format(R"({{"token":"{}","method":"{}","params":{},"timeoutMs":5000}})", token, method, params) + "\n";
- }
-
- Crafter::QUICClientCredentials Insecure() {
- Crafter::QUICClientCredentials credentials;
- credentials.insecureNoServerValidation = true;
- return credentials;
- }
-}
-
-int main() {
- std::thread([] {
- std::this_thread::sleep_for(50s);
- std::println("FAIL the test hung");
- std::fflush(stdout);
- std::_Exit(1);
- }).detach();
-
- const fs::path dir = fs::temp_directory_path() / "crafter-debug-ShouldServeOverQuic";
- fs::remove_all(dir);
- fs::create_directories(dir);
- ::setenv("CRAFTER_DEBUG_DIR", dir.c_str(), 1);
-
- Crafter::ThreadPool::Start(4);
-
- Command("Math_Add", "Add two numbers.", [](const AddArgs& args) { return *args.a + args.b; });
- float speed = 1.5f;
- Watch("speed", speed);
-
- auto session = std::make_unique(SessionOptions{ .name = "quic-test" });
-
- std::atomic pumping = true;
- std::thread app([&] {
- std::uint32_t frame = 0;
- while (pumping) {
- Pump();
- if (++frame % 10 == 0) Log("tick", "tick {}", frame);
- std::this_thread::sleep_for(2ms);
- }
- });
-
- // ---- discovery ----
- const std::vector live = ListInstances();
- Check(live.size() == 1, "discovery lists the listening session");
- if (live.size() != 1) {
- pumping = false;
- app.join();
- std::fflush(stdout);
- std::_Exit(1);
- }
- const InstanceRecord record = live.front().record;
- Check(record.name == "quic-test" && record.port != 0 && record.token == session->Token(), "the record names it, its port and its token");
- Check(record.protocol == protocolVersion && record.sourceId == Detail::SourceId() && record.client == Detail::ClientPath(),
- "the record carries the protocol, source id and client path");
-
- // ---- the client, over QUIC ----
- Ran r = Run({ "status" });
- Check(r.code == 0 && Has(r.out, "quic-test frame"), std::format("status ({})", r.out + r.err));
- r = Run({ "call", "Math_Add", "a=2", "b=3" });
- Check(r.code == 0 && Has(r.out, "5"), std::format("call ({})", r.out + r.err));
- r = Run({ "call", "Math_Ad", "a=2" });
- Check(r.code == 6 && Has(r.err, "Math_Add"), std::format("an unknown command suggests the right one ({})", r.err));
- r = Run({ "get", "speed" });
- Check(r.code == 0 && Has(r.out, "1.5"), std::format("get ({})", r.out + r.err));
- r = Run({ "set", "speed", "4" });
- Check(r.code == 0, std::format("set ({})", r.out + r.err));
- r = Run({ "get", "speed" });
- Check(r.code == 0 && Has(r.out, "4"), std::format("get after set ({})", r.out + r.err));
-
- const auto followStart = std::chrono::steady_clock::now();
- r = Run({ "log", "--follow", "--for", "1s", "--cat", "tick" });
- const auto followTook = std::chrono::steady_clock::now() - followStart;
- Check(r.code == 0 && Has(r.out, "tick") && Has(r.err, "(follow ended)"), std::format("log --follow streams, then ends ({})", r.err));
- Check(followTook >= 900ms && followTook < 5s, std::format("the follow lasted its --for ({} ms)", std::chrono::duration_cast(followTook).count()));
-
- // ---- in parallel, on separate connections ----
- {
- std::vector callers;
- std::vector results(6);
- for (std::size_t i = 0; i < results.size(); ++i) {
- callers.emplace_back([&results, i] {
- const std::string a = std::format("a={}", 100 * (i + 1));
- results[i] = Run({ "call", "Math_Add", a, "b=1" });
- });
- }
- for (std::thread& caller : callers) caller.join();
- bool all = true;
- for (std::size_t i = 0; i < results.size(); ++i) {
- all = all && results[i].code == 0 && Has(results[i].out, std::format("{}", 100 * (i + 1) + 1));
- }
- Check(all, "six clients at once each get their own answer");
- }
-
- // ---- by hand: what the client never sends ----
- auto client = std::make_unique(std::string("127.0.0.1"), record.port, std::string(alpn), Insecure());
- {
- std::unique_ptr wrong = Send(*client, Request("not-the-token", "debug.status"));
- Check(wrong->Wait(5s) && Has(wrong->Bytes(), "Unauthorized"), std::format("a wrong token is refused ({})", wrong->Bytes()));
-
- std::unique_ptr garbage = Send(*client, "this is not json\n");
- Check(garbage->Wait(5s) && Has(garbage->Bytes(), "InvalidRequest"), std::format("a request that isn't JSON is answered ({})", garbage->Bytes()));
-
- std::unique_ptr huge = Send(*client, std::string(std::size_t{ 2 } << 20, ' '));
- Check(huge->Wait(10s) && Has(huge->Bytes(), "InvalidRequest") && Has(huge->Bytes(), "at most"),
- std::format("a request over 1 MiB is answered with an error ({})", huge->Bytes().substr(0, 200)));
-
- std::vector> parallel;
- for (std::int32_t i = 0; i < 8; ++i) {
- parallel.push_back(Send(*client, Request(record.token, "Math_Add", std::format(R"({{"a":{},"b":1000}})", i))));
- }
- bool all = true;
- for (std::int32_t i = 0; i < 8; ++i) {
- all = all && parallel[i]->Wait(5s) && Has(parallel[i]->Bytes(), std::format(R"({{"result":{}}})", 1000 + i));
- }
- Check(all, "eight streams of one connection at once each get their own answer");
- }
-
- // ---- the end, with a follower waiting ----
- std::unique_ptr follower = Send(*client, Request(record.token, "debug.log", R"({"follow":true,"forMs":60000,"last":0})"));
- bool following = false;
- for (std::int32_t attempt = 0; attempt < 100 && !following; ++attempt) {
- std::unique_ptr status = Send(*client, Request(record.token, "debug.status"));
- following = status->Wait(5s) && Has(status->Bytes(), R"("following":1)");
- if (!following) std::this_thread::sleep_for(20ms);
- }
- Check(following, "the follower is registered");
- pumping = false;
- app.join();
-
- const auto endStart = std::chrono::steady_clock::now();
- session.reset();
- const auto endTook = std::chrono::steady_clock::now() - endStart;
- Check(endTook < 3s, std::format("the Session ends promptly with a client connected ({} ms)", std::chrono::duration_cast(endTook).count()));
- Check(follower->Wait(5s) && Has(follower->Bytes(), "ShuttingDown") && !Has(follower->Bytes(), "Math_Add"),
- std::format("the follower, with no backlog, is told the app is shutting down ({})", follower->Bytes().substr(0, 400)));
- Check(ListInstances().empty(), "discovery forgets the session");
- follower.reset();
- client.reset();
-
- const auto deadStart = std::chrono::steady_clock::now();
- const std::unique_ptr dead = Cli::ConnectQuic(record);
- const auto reply = dead->Call(Value::Parse(Request(record.token, "debug.status")), 5s, {});
- const auto deadTook = std::chrono::steady_clock::now() - deadStart;
- Check(!reply && reply.error().kind == Cli::CallError::Kind::Unreachable && deadTook < 5s,
- std::format("a client finds the port dead in {} ms", std::chrono::duration_cast(deadTook).count()));
-
- // Alive by its lock, with nothing answering at its port: what a client
- // sees of an app a debugger holds.
- {
- const Registration stopped(InstanceRecord{ .name = "held", .port = record.port, .token = "t", .protocol = protocolVersion, .sourceId = std::string(Detail::SourceId()) });
- const Ran held = Run({ "status" });
- Check(held.code == 5 && Has(held.err, "alive but not answering") && Has(held.err, "attach"),
- std::format("an app alive but silent is reported as held, with how to attach (exit {}: {})", held.code, held.err));
- }
-
- std::fflush(stdout);
- std::_Exit(failures == 0 ? 0 : 1);
-}
diff --git a/tooling/interfaces/Crafter.Debug.Build.cppm b/tooling/interfaces/Crafter.Debug.Build.cppm
index 0c2aee6..d2c773b 100644
--- a/tooling/interfaces/Crafter.Debug.Build.cppm
+++ b/tooling/interfaces/Crafter.Debug.Build.cppm
@@ -6,9 +6,8 @@
// #pragma crafter dependency "https://forgejo.catcrafts.net/Catcrafts/Crafter.Debug.git" project "tooling/project.cpp"
// import Crafter.Debug.Build;
// ...
-// const bool debugApi = Debug::Use(cfg, { .enabled = opts.Has("--debug-api"), .flag = "--debug-api",
-// .define = "MYAPP_DEBUG_API", .args = depArgs });
-// if (debugApi) { /* add the debug-only sources */ }
+// Debug::Use(cfg, { .enabled = opts.Has("--debug-api"), .flag = "--debug-api",
+// .define = "MYAPP_DEBUG_API", .args = depArgs });
//
// crafter-build builds this module for the host and links it into the
// consumer's project.so, the way Crafter.LintRules gets in, so Use runs each
@@ -165,12 +164,9 @@ export namespace Crafter::Debug {
};
// Adds Crafter.Debug to `cfg` when options.enabled, and writes the
- // launcher; see the comment at the top. Returns whether it added the
- // library and the define, which is when the consumer adds its debug-only
- // sources: not for every build with the flag, since a target other than
- // native Linux gets neither. `at` defaults to the call site, which is how
- // Use finds the consumer's directory.
- bool Use(Configuration& cfg, const UseOptions& options, std::source_location at = std::source_location::current()) {
+ // launcher; see the comment at the top. `at` defaults to the call site,
+ // which is how Use finds the consumer's directory.
+ void Use(Configuration& cfg, const UseOptions& options, std::source_location at = std::source_location::current()) {
const fs::path launcher = fs::path(at.file_name()).parent_path() / "build" / "crafter-debug";
// Only for the project crafter-build was pointed at: a consumer loaded
// as someone else's dependency has no agent driving it from its own
@@ -178,18 +174,17 @@ export namespace Crafter::Debug {
const bool topLevel = IsTopLevelProject();
if (!options.enabled || !NativeLinux(cfg.target)) {
if (topLevel && !fs::exists(launcher)) WriteIfChanged(launcher, StubText(options.flag));
- return false;
+ return;
}
Configuration* library = LocalProject({ .projectFile = Checkout() / "project.cpp", .args = options.args });
cfg.dependencies.push_back(library);
if (!options.define.empty()) cfg.defines.push_back({ options.define, "" });
- if (!topLevel) return true;
+ if (!topLevel) return;
const auto client = std::ranges::find(library->dependencies, std::string_view("crafter.debug-cli"),
[](const Configuration* dependency) { return std::string_view(dependency->name); });
if (client == library->dependencies.end()) {
throw std::runtime_error(std::format("Crafter.Debug: {} declares no crafter.debug-cli client", (Checkout() / "project.cpp").string()));
}
WriteIfChanged(launcher, LauncherText((*client)->BinDir() / (*client)->outputName, CurrentSandbox(), options.flag));
- return true;
}
}