feat(pipeline): the pure pipeline, checked against its goldens
The modules that turn a frozen range into passes and passes into a verdict: :Schema, :Tools (the DENY, git and base lists, a leaf, so the config and the pool both read them), :Plan, :Artifact, :Inventory, :Dispositions, :State, :Normalize, :Stream, :Prompt, :Config, and the URL half of :PgWire. Units, jobs, results, the config and the claude stream stay JSON from end to end, so every key keeps its place; :Text gives JSON values truthiness, get, ==, membership and Str(), and throws Dyn::Error under a name for each kind of unexpected data. Exactness where the bytes are seen: - the stream classifiers are hand-written scanners with case-insensitive folds (the Kelvin sign is a k), Unicode \b and \s, and `.` stopping at \n; the SQL call detection takes `<exe> sql` with any path before it; - config problems carry the JSON scanner's and the UTF-8 decoder's own texts, positions included; - a float total is Neumaier's compensated sum, and the build passes -ffp-contract=off: -march=native would fuse a*b+c; - `crafter-review inventory` and `config` print what the goldens record, byte for byte (the fixture and 14 configs, broken ones included); a message names this binary as the command to run. tests/Goldens: the recorded answers over the fixtures next to them (the commits fixture, a rich versioned series with CRLF, a folded subject, Markdown headings in and out of fences, the code-key rewrites); the suite compares 2304 results as DumpFile writes them, so a key out of order fails too. All agree. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b02de3ceff
commit
741e3a656d
70 changed files with 30565 additions and 21 deletions
116
implementations/Crafter.Review-Artifact.cpp
Normal file
116
implementations/Crafter.Review-Artifact.cpp
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Artifact_impl;
|
||||
import :Artifact;
|
||||
import :Text;
|
||||
import :Crypto;
|
||||
import :Platform;
|
||||
import :Process;
|
||||
import std;
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace Crafter::Review::Artifact {
|
||||
namespace {
|
||||
std::string ReadBytes(const fs::path& path) {
|
||||
std::optional<std::string> bytes = Platform::ReadFile(path);
|
||||
if (!bytes) throw std::runtime_error(std::format("{}: cannot read", path.string()));
|
||||
return std::move(*bytes);
|
||||
}
|
||||
|
||||
// Four decimal digits and a '-' at `at`, as (\d{4})-: the number.
|
||||
std::optional<std::int64_t> FourDigits(std::string_view name, std::size_t at) {
|
||||
std::size_t end = at;
|
||||
for (std::int32_t i = 0; i < 4; ++i) {
|
||||
if (end >= name.size()) return std::nullopt;
|
||||
const auto [c, used] = Dyn::CodePointAt(name, end);
|
||||
if (!Dyn::IsDecimal(c)) return std::nullopt;
|
||||
end += used;
|
||||
}
|
||||
if (end >= name.size() || name[end] != '-') return std::nullopt;
|
||||
return Dyn::ParseInt(name.substr(at, end - at));
|
||||
}
|
||||
}
|
||||
|
||||
std::string Sha256File(const fs::path& path) {
|
||||
return Sha256Hex(ReadBytes(path));
|
||||
}
|
||||
|
||||
std::string ArtifactHash(std::string_view mode, const fs::path& path) {
|
||||
if (mode == "reply") return Sha256File(path);
|
||||
std::string all;
|
||||
for (const std::string& name : PatchFiles(path)) all += ReadBytes(path / name);
|
||||
return Sha256Hex(all);
|
||||
}
|
||||
|
||||
std::vector<std::string> PatchFiles(const fs::path& path) {
|
||||
std::vector<std::string> out;
|
||||
for (const fs::directory_entry& entry : fs::directory_iterator(path)) {
|
||||
std::string name = entry.path().filename().string();
|
||||
if (name.ends_with(".patch")) out.push_back(std::move(name));
|
||||
}
|
||||
std::ranges::sort(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<std::int64_t> PatchNumber(std::string_view name) {
|
||||
if (name.starts_with('v')) {
|
||||
const std::size_t digits = Dyn::DecimalRun(name, 1);
|
||||
if (digits > 0 && 1 + digits < name.size() && name[1 + digits] == '-') {
|
||||
if (const std::optional<std::int64_t> k = FourDigits(name, 2 + digits)) return k;
|
||||
}
|
||||
}
|
||||
return FourDigits(name, 0);
|
||||
}
|
||||
|
||||
std::map<std::int64_t, std::string> PatchTexts(const fs::path& path) {
|
||||
std::map<std::int64_t, std::string> out;
|
||||
for (const std::string& name : PatchFiles(path)) {
|
||||
const std::optional<std::int64_t> k = PatchNumber(name);
|
||||
if (!k) throw Dyn::Error("AttributeError", "'NoneType' object has no attribute 'group'");
|
||||
out[*k] = Dyn::ReadText(path / name);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<std::string> PatchHead(const fs::path& path) {
|
||||
const std::vector<std::string> files = PatchFiles(path);
|
||||
if (files.empty()) return std::nullopt;
|
||||
// open(errors='replace').readline().split(): the first line, universal
|
||||
// newlines and all.
|
||||
const std::string text = Dyn::UniversalNewlines(Dyn::DecodeReplace(ReadBytes(path / files.back())));
|
||||
const std::vector<std::string> first = Dyn::Split(std::string_view(text).substr(0, text.find('\n')));
|
||||
if (first.size() > 1 && first[0] == "From" && Dyn::Length(first[1]) == 40) return first[1];
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::string Git(const fs::path& tree, std::span<const std::string> args) {
|
||||
std::vector<std::string> argv = {"git", "-C", tree.string()};
|
||||
argv.insert(argv.end(), args.begin(), args.end());
|
||||
const Process::Captured run = Process::Run(argv);
|
||||
if (run.returnCode != 0) {
|
||||
const std::string& said = run.err.empty() ? run.out : run.err;
|
||||
throw Dyn::Error("RuntimeError", std::format("git -C {} {}: {}", tree.string(), Dyn::Join(args, " "),
|
||||
Dyn::Strip(Dyn::UniversalNewlines(Dyn::DecodeReplace(said)))));
|
||||
}
|
||||
return Dyn::UniversalNewlines(Dyn::DecodeReplace(run.out));
|
||||
}
|
||||
|
||||
bool IsToplevel(const fs::path& tree) {
|
||||
try {
|
||||
const std::string top = Dyn::Strip(Git(tree, std::array<std::string, 2>{"rev-parse", "--show-toplevel"}));
|
||||
return fs::weakly_canonical(fs::absolute(top)) == fs::weakly_canonical(fs::absolute(tree));
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string TreeHead(const fs::path& tree) {
|
||||
return Dyn::Strip(Git(tree, std::array<std::string, 2>{"rev-parse", "HEAD"}));
|
||||
}
|
||||
|
||||
std::string TreeDirty(const fs::path& tree) {
|
||||
return Dyn::Strip(Git(tree, std::array<std::string, 3>{"status", "--porcelain", "--untracked-files=no"}));
|
||||
}
|
||||
}
|
||||
464
implementations/Crafter.Review-Config.cpp
Normal file
464
implementations/Crafter.Review-Config.cpp
Normal file
|
|
@ -0,0 +1,464 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Config_impl;
|
||||
import :Config;
|
||||
import :Json;
|
||||
import :Text;
|
||||
import :Core;
|
||||
import :Plan;
|
||||
import :Tools;
|
||||
import :PgWire;
|
||||
import :Process;
|
||||
import std;
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace Crafter::Review::Config {
|
||||
namespace {
|
||||
// Keys a consumer's config may still carry, with what replaced them.
|
||||
struct Retired {
|
||||
std::string_view section;
|
||||
std::string_view key;
|
||||
std::string why;
|
||||
};
|
||||
|
||||
std::vector<Retired> RetiredKeys() {
|
||||
return {{
|
||||
"functional", "concurrency",
|
||||
std::format("passes run as many at once as free memory allows, each at its environment's measured cost, and a pass that drives "
|
||||
"the application holds a stack of its own (2026-10-22); for more of them at once bring up more stacks "
|
||||
"(slots.*, `{} slots`)", Invocation()),
|
||||
}};
|
||||
}
|
||||
|
||||
std::string EnvironmentNames(std::string_view separator) {
|
||||
std::vector<std::string> names;
|
||||
for (const Plan::Environment& environment : Plan::Environments) names.emplace_back(environment.name);
|
||||
return Dyn::Join(names, separator);
|
||||
}
|
||||
|
||||
Json EnvironmentTable() {
|
||||
Json table = Json::object();
|
||||
for (const Plan::Environment& environment : Plan::Environments) table[std::string(environment.name)] = true;
|
||||
return table;
|
||||
}
|
||||
|
||||
bool AllStrings(const Json& list) {
|
||||
return list.is_array() && std::ranges::all_of(list, [](const Json& item) { return item.is_string(); });
|
||||
}
|
||||
|
||||
// ^(Bash\([^()]+:\*\)|mcp__[A-Za-z0-9_-]+(__[A-Za-z0-9_-]+)?)$; `$`
|
||||
// also matches before a final newline.
|
||||
bool IsToolEntry(std::string_view tool) {
|
||||
std::string_view body = tool;
|
||||
if (body.ends_with('\n')) body.remove_suffix(1);
|
||||
if (body.starts_with("Bash(") && body.ends_with(":*)") && body.size() > 8) {
|
||||
const std::string_view prefix = body.substr(5, body.size() - 8);
|
||||
return !prefix.contains('(') && !prefix.contains(')');
|
||||
}
|
||||
if (body.starts_with("mcp__") && body.size() > 5) {
|
||||
return std::ranges::all_of(body.substr(5), [](char c) {
|
||||
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-';
|
||||
});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// re.match(r'^https?://', text)
|
||||
bool IsHttpUrl(std::string_view text) {
|
||||
return text.starts_with("http://") || text.starts_with("https://");
|
||||
}
|
||||
|
||||
// An integer or a float, not a bool.
|
||||
bool IsRealNumber(const Json& value) {
|
||||
return value.is_number();
|
||||
}
|
||||
|
||||
bool Positive(const Json& value) {
|
||||
return value.is_number_float() ? value.get<double>() > 0.0 : (value.is_number_unsigned() ? value.get<std::uint64_t>() > 0 : value.get<std::int64_t>() > 0);
|
||||
}
|
||||
|
||||
std::vector<std::string> Merge(Json& destination, const Json& source, const std::string& path) {
|
||||
std::vector<std::string> problems;
|
||||
for (auto it = source.begin(); it != source.end(); ++it) {
|
||||
const std::string& key = it.key();
|
||||
if (!Dyn::Has(destination, key)) {
|
||||
problems.push_back(std::format("unknown key {}{}", path, key));
|
||||
continue;
|
||||
}
|
||||
Json& target = destination[key];
|
||||
if (target.is_object() && it.value().is_object()) {
|
||||
std::ranges::move(Merge(target, it.value(), std::format("{}{}.", path, key)), std::back_inserter(problems));
|
||||
} else {
|
||||
target = it.value();
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// The config's entry for the lens, else its default one.
|
||||
const Json& LensEntry(const Json& config, std::string_view lensFile) {
|
||||
static const Json defaults = Defaults()["lenses"];
|
||||
const Json& lenses = Dyn::Get(config, "lenses");
|
||||
const std::string name = Plan::LensName(lensFile);
|
||||
const Json* entry = lenses.is_object() ? &Dyn::Get(lenses, name) : nullptr;
|
||||
return entry && entry->is_object() ? *entry : defaults.at(name);
|
||||
}
|
||||
|
||||
// A config or a slot file as JSON: the value, or the text that goes
|
||||
// into the "not JSON (...)" problem.
|
||||
std::variant<Json, std::string> LoadJson(const fs::path& path) {
|
||||
try {
|
||||
return Dyn::LoadJsonFile(path);
|
||||
} catch (const std::exception& error) {
|
||||
return std::string(error.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Json Defaults() {
|
||||
Json lenses = Json::object();
|
||||
for (const Plan::Lens& lens : Plan::Lenses) lenses[Plan::LensName(lens.file)] = {{"run", true}, {"environment", lens.env}};
|
||||
return {
|
||||
// The integration branch a range is measured against (e.g.
|
||||
// origin/dev): merge-base HEAD <base>.
|
||||
{"base", nullptr},
|
||||
// upstream: the push delta @{upstream}..HEAD, the base branch only
|
||||
// when HEAD tracks nothing; base: always merge-base HEAD
|
||||
// <base>..HEAD, the whole pull request.
|
||||
{"rangeFrom", "upstream"},
|
||||
// Author and committer emails the freeze accepts; null: the
|
||||
// repository's `git config user.email`.
|
||||
{"authors", nullptr},
|
||||
// forbid | allow: Assisted-by / Co-Authored-By trailers in the
|
||||
// range.
|
||||
{"aiTrailers", "forbid"},
|
||||
// An unsigned commit fails the freeze (else a warning).
|
||||
{"requireSigned", false},
|
||||
// Tracked paths the local stack rewrites in place while the lenses
|
||||
// run.
|
||||
{"allowDirty", Json::array()},
|
||||
// The commands Gate 0 runs by hand, in order (documentation for the
|
||||
// skill; the driver runs none of them).
|
||||
{"gate0", Json::array()},
|
||||
// Per lens: run (false: left out of every run of this repository)
|
||||
// and environment (Plan::Environments).
|
||||
{"lenses", lenses},
|
||||
// The database under test, for every lens whose environment
|
||||
// reaches it. The URL reaches a db pass's broker, never a prompt,
|
||||
// and the dump and the log show it with the password masked.
|
||||
{"supabase", {{"dbUrl", "postgresql://postgres:postgres@127.0.0.1:54322/postgres"}, {"start", nullptr}, {"stop", nullptr}, {"notes", ""}}},
|
||||
// Stacks side by side (2026-10-22): a pass that drives an
|
||||
// application holds one of its own.
|
||||
{"slots", {{"dir", nullptr}, {"start", nullptr}, {"stop", nullptr}, {"memMb", nullptr}, {"startMb", nullptr}}},
|
||||
// The application under test, for every lens whose environment
|
||||
// reaches one.
|
||||
{"functional", {
|
||||
{"appUrl", "http://localhost:8080"},
|
||||
{"readyPath", "/"},
|
||||
{"apiUrls", Json::array()},
|
||||
{"start", nullptr},
|
||||
{"stop", nullptr},
|
||||
{"login", {{"fixtures", Json::array()}, {"notes", ""}}},
|
||||
{"exclude", Json::array()},
|
||||
{"extraTools", Json::array()},
|
||||
{"mcp", {{"command", "npx"}, {"args", nullptr}}},
|
||||
{"notes", ""},
|
||||
}},
|
||||
};
|
||||
}
|
||||
|
||||
Loaded Load(const fs::path& repo, const fs::path& path) {
|
||||
Loaded loaded{Defaults(), {}};
|
||||
Json& config = loaded.config;
|
||||
const fs::path p = path.empty() ? repo / ConfigFile : path;
|
||||
std::vector<std::string> warnings;
|
||||
if (fs::exists(p)) {
|
||||
std::variant<Json, std::string> read = LoadJson(p);
|
||||
if (std::holds_alternative<std::string>(read)) {
|
||||
loaded.problems.push_back(std::format("{}: not JSON ({})", p.string(), std::get<std::string>(read)));
|
||||
return loaded;
|
||||
}
|
||||
Json data = std::move(std::get<Json>(read));
|
||||
if (!data.is_object()) {
|
||||
loaded.problems.push_back(std::format("{}: the top level must be an object", p.string()));
|
||||
return loaded;
|
||||
}
|
||||
for (const Retired& retired : RetiredKeys()) {
|
||||
const Json& section = Dyn::Get(data, retired.section);
|
||||
if (section.is_object() && Dyn::Has(section, retired.key)) {
|
||||
warnings.push_back(std::format("{}.{} is no longer read - remove it from {}: {}", retired.section, retired.key, p.filename().string(), retired.why));
|
||||
data[std::string(retired.section)].erase(std::string(retired.key));
|
||||
}
|
||||
}
|
||||
loaded.problems = Merge(config, data, "");
|
||||
} else if (!path.empty()) {
|
||||
loaded.problems.push_back(std::format("{}: no such file", p.string()));
|
||||
}
|
||||
config["_path"] = fs::exists(p) ? Json(p.string()) : Json();
|
||||
Json warningList = Json::array();
|
||||
for (const std::string& warning : warnings) warningList.push_back(warning);
|
||||
config["_warnings"] = std::move(warningList);
|
||||
std::ranges::move(Validate(config), std::back_inserter(loaded.problems));
|
||||
return loaded;
|
||||
}
|
||||
|
||||
std::vector<std::string> Validate(const Json& config) {
|
||||
std::vector<std::string> out;
|
||||
const Json& trailers = Dyn::At(config, "aiTrailers");
|
||||
if (trailers != "forbid" && trailers != "allow") out.emplace_back("aiTrailers must be 'forbid' or 'allow'");
|
||||
const Json& rangeFrom = Dyn::At(config, "rangeFrom");
|
||||
if (rangeFrom != "upstream" && rangeFrom != "base") out.emplace_back("rangeFrom must be 'upstream' or 'base'");
|
||||
if (rangeFrom == "base" && !Dyn::Truthy(Dyn::At(config, "base"))) out.emplace_back("rangeFrom 'base' needs a base branch");
|
||||
const Json& authors = Dyn::At(config, "authors");
|
||||
if (!authors.is_null() && (!authors.is_array() || !std::ranges::all_of(authors, [](const Json& a) {
|
||||
return a.is_string() && a.get_ref<const std::string&>().contains('@');
|
||||
}))) {
|
||||
out.emplace_back("authors must be null or a list of email addresses");
|
||||
}
|
||||
for (const std::string_view key : {"allowDirty", "gate0"}) {
|
||||
if (!AllStrings(Dyn::At(config, key))) out.push_back(std::format("{} must be a list of strings", key));
|
||||
}
|
||||
const Json environments = EnvironmentTable();
|
||||
Json lenses = Dyn::At(config, "lenses");
|
||||
if (!lenses.is_object()) {
|
||||
out.push_back(std::format("lenses must be an object: {{<lens name>: {{run: bool, environment: {}}}}}", EnvironmentNames("|")));
|
||||
lenses = Json::object();
|
||||
}
|
||||
for (auto it = lenses.begin(); it != lenses.end(); ++it) {
|
||||
const Json& entry = it.value();
|
||||
if (!entry.is_object()) {
|
||||
out.push_back(std::format("lenses.{} must be an object {{run: bool, environment: {}}}", it.key(), EnvironmentNames("|")));
|
||||
continue;
|
||||
}
|
||||
if (!Dyn::Get(entry, "run").is_boolean()) out.push_back(std::format("lenses.{}.run must be true or false", it.key()));
|
||||
if (!Dyn::In(Dyn::Get(entry, "environment"), environments)) out.push_back(std::format("lenses.{}.environment must be one of {}", it.key(), EnvironmentNames(", ")));
|
||||
}
|
||||
auto runs = [](const Json& entry) { return entry.is_object() && Dyn::Get(entry, "run") == true; };
|
||||
if (!lenses.empty() && !std::ranges::any_of(lenses, runs)) out.emplace_back("lenses: every lens is off - at least one must run");
|
||||
for (const Plan::Lens& lens : Plan::Lenses) {
|
||||
const Json& entry = Dyn::Get(lenses, Plan::LensName(lens.file));
|
||||
if (!lens.empirical || !runs(entry)) continue;
|
||||
const Json& name = Dyn::Get(entry, "environment");
|
||||
if (!Dyn::In(name, environments)) continue;
|
||||
if (!Plan::FindEnvironment(name.get_ref<const std::string&>())->app) {
|
||||
std::vector<std::string> withApp;
|
||||
for (const Plan::Environment& environment : Plan::Environments) {
|
||||
if (environment.app) withApp.emplace_back(environment.name);
|
||||
}
|
||||
out.push_back(std::format("lenses.{}: an empirical lens needs an environment with an application under test ({}) - or turn it off", Plan::LensName(lens.file),
|
||||
Dyn::Join(withApp, ", ")));
|
||||
}
|
||||
}
|
||||
const Json& supabase = Dyn::At(config, "supabase");
|
||||
if (!supabase.is_object()) {
|
||||
out.emplace_back("supabase must be an object {dbUrl, start, stop, notes}");
|
||||
} else {
|
||||
if (const std::optional<std::string> problem = PgWire::CheckUrl(Dyn::Get(supabase, "dbUrl"))) out.push_back(std::format("supabase.dbUrl: {}", *problem));
|
||||
for (const std::string_view key : {"start", "stop"}) {
|
||||
const Json& value = Dyn::Get(supabase, key);
|
||||
if (!value.is_null() && !value.is_string()) out.push_back(std::format("supabase.{} must be null or a command line", key));
|
||||
}
|
||||
if (!Dyn::Get(supabase, "notes").is_string()) out.emplace_back("supabase.notes must be text");
|
||||
}
|
||||
const Json& functional = Dyn::At(config, "functional");
|
||||
if (!functional.is_object()) {
|
||||
out.emplace_back("functional must be an object");
|
||||
return out;
|
||||
}
|
||||
// The application's URL matters only to a lens that drives it.
|
||||
const bool drivesApp = std::ranges::any_of(lenses, [&](const Json& entry) {
|
||||
if (!runs(entry)) return false;
|
||||
const Json& name = Dyn::Get(entry, "environment");
|
||||
if (name.is_array() || name.is_object()) throw Dyn::Error("TypeError", std::format("unhashable type: '{}'", Dyn::TypeName(name)));
|
||||
const Plan::Environment* environment = name.is_string() ? Plan::FindEnvironment(name.get_ref<const std::string&>()) : nullptr;
|
||||
return environment && environment->app;
|
||||
});
|
||||
if (drivesApp && !IsHttpUrl(Dyn::StrOr(Dyn::At(functional, "appUrl"), ""))) out.emplace_back("functional.appUrl must be an http(s) URL");
|
||||
if (!AllStrings(Dyn::At(functional, "exclude"))) out.emplace_back("functional.exclude must be a list of globs");
|
||||
const Json& extraTools = Dyn::At(functional, "extraTools");
|
||||
if (!extraTools.is_array() || !std::ranges::all_of(extraTools, [](const Json& x) { return x.is_string() && IsToolEntry(x.get_ref<const std::string&>()); })) {
|
||||
out.emplace_back("functional.extraTools entries must be Bash(<prefix>:*) or mcp__<server>[__<tool>]");
|
||||
} else {
|
||||
std::vector<std::string> dead;
|
||||
for (const Json& tool : extraTools) {
|
||||
if (Tools::Denied(tool.get_ref<const std::string&>())) dead.push_back(tool.get<std::string>());
|
||||
}
|
||||
if (!dead.empty()) {
|
||||
out.push_back(std::format("functional.extraTools: {} - denied to every pass (pool.DENY wins over an allowlist); "
|
||||
"a lens reaches the database through the supabase environment, every call rolled back", Dyn::Join(dead, ", ")));
|
||||
}
|
||||
}
|
||||
const Json& login = Dyn::At(functional, "login");
|
||||
if (!login.is_object() || !(Dyn::Has(login, "fixtures") ? Dyn::At(login, "fixtures").is_array() : true)) out.emplace_back("functional.login must be {fixtures: [paths], notes: text}");
|
||||
const Json& slots = Dyn::At(config, "slots");
|
||||
if (!slots.is_object()) {
|
||||
out.emplace_back("slots must be an object {dir, start, stop, memMb, startMb}");
|
||||
} else if (!Dyn::Get(slots, "dir").is_null()) {
|
||||
const Json& dir = Dyn::At(slots, "dir");
|
||||
bool bad = !dir.is_string();
|
||||
if (!bad) {
|
||||
const std::string& d = dir.get_ref<const std::string&>();
|
||||
const std::vector<std::string> parts = Dyn::Split(Dyn::Replace(d, "\\", "/"), "/");
|
||||
bad = Dyn::Strip(d).empty() || d.starts_with('/') || std::ranges::contains(parts, std::string(".."));
|
||||
}
|
||||
if (bad) out.emplace_back("slots.dir must be null or a directory inside the repository (a relative path)");
|
||||
for (const std::string_view key : {"start", "stop"}) {
|
||||
const Json& value = Dyn::Get(slots, key);
|
||||
if (!value.is_null() && (!value.is_string() || !value.get_ref<const std::string&>().contains("{n}"))) {
|
||||
out.push_back(std::format("slots.{} must be null or a command line with {{n}}, the slot number", key));
|
||||
}
|
||||
}
|
||||
const Json& memMb = Dyn::Get(slots, "memMb");
|
||||
if (!IsRealNumber(memMb) || !Positive(memMb)) {
|
||||
out.push_back(std::format("slots.memMb must be the measured memory of one slot in MB (a number > 0): `{} slots` sizes the slots by it", Invocation()));
|
||||
}
|
||||
const Json& startMb = Dyn::Get(slots, "startMb");
|
||||
if (!startMb.is_null() && (!IsRealNumber(startMb) || !Positive(startMb))) {
|
||||
out.emplace_back("slots.startMb must be null or the measured peak of one slot coming up in MB (a number > 0)");
|
||||
}
|
||||
}
|
||||
const Json& args = Dyn::Get(Dyn::At(functional, "mcp"), "args");
|
||||
if (!args.is_null() && !AllStrings(args)) out.emplace_back("functional.mcp.args must be null or a list of strings");
|
||||
return out;
|
||||
}
|
||||
|
||||
Json Redacted(const Json& config) {
|
||||
Json copy = Json::object();
|
||||
for (auto it = config.begin(); it != config.end(); ++it) {
|
||||
if (!it.key().starts_with('_')) copy[it.key()] = it.value();
|
||||
}
|
||||
if (Dyn::Get(copy, "supabase").is_object() && Dyn::Get(copy["supabase"], "dbUrl").is_string()) {
|
||||
copy["supabase"]["dbUrl"] = PgWire::Redact(copy["supabase"]["dbUrl"].get<std::string>());
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
std::string GitUserEmail(const fs::path& repo) {
|
||||
const Process::Captured run = Process::Run({"git", "-C", repo.string(), "config", "user.email"});
|
||||
return run.returnCode == 0 ? Dyn::Strip(Dyn::UniversalNewlines(Dyn::DecodeReplace(run.out))) : std::string();
|
||||
}
|
||||
|
||||
std::vector<std::string> Authors(const Json& config, const fs::path& repo) {
|
||||
const Json& authors = Dyn::Get(config, "authors");
|
||||
if (Dyn::Truthy(authors)) {
|
||||
std::vector<std::string> out;
|
||||
for (const Json& author : authors) out.push_back(Dyn::Str(author));
|
||||
return out;
|
||||
}
|
||||
const std::string email = GitUserEmail(repo);
|
||||
if (email.empty()) return {};
|
||||
return {email};
|
||||
}
|
||||
|
||||
std::vector<std::string> LensesOff(const Json& config) {
|
||||
std::vector<std::string> out;
|
||||
for (const Plan::Lens& lens : Plan::Lenses) {
|
||||
if (Dyn::Get(LensEntry(config, lens.file), "run") == false) out.emplace_back(lens.file);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Json Environments(const Json& config) {
|
||||
Json out = Json::object();
|
||||
for (const Plan::Lens& lens : Plan::Lenses) {
|
||||
const Json& entry = LensEntry(config, lens.file);
|
||||
out[std::string(lens.file)] = Dyn::Has(entry, "environment") ? Dyn::At(entry, "environment") : Json("none");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Slots SlotStacks(const Json& config, const fs::path& repo) {
|
||||
Slots slots;
|
||||
const Json& dir = Dyn::Get(Dyn::Or(Dyn::Get(config, "slots"), Dyn::EmptyDict()), "dir");
|
||||
if (!Dyn::Truthy(dir) || !fs::is_directory(repo / dir.get<std::string>())) return slots;
|
||||
const std::string d = dir.get<std::string>();
|
||||
std::vector<std::string> names;
|
||||
for (const fs::directory_entry& entry : fs::directory_iterator(repo / d)) names.push_back(entry.path().filename().string());
|
||||
std::ranges::stable_sort(names, {}, [](const std::string& name) { return Dyn::Natural(name); });
|
||||
for (const std::string& n : names) {
|
||||
const fs::path file = repo / d / n / SlotFile;
|
||||
if (!fs::is_regular_file(file)) continue;
|
||||
const std::string rel = Dyn::JoinPath(Dyn::JoinPath(d, n), SlotFile);
|
||||
std::variant<Json, std::string> read = LoadJson(file);
|
||||
if (std::holds_alternative<std::string>(read)) {
|
||||
slots.problems.push_back(std::format("{}: not JSON ({})", rel, std::get<std::string>(read)));
|
||||
continue;
|
||||
}
|
||||
const Json& s = std::get<Json>(read);
|
||||
if (!s.is_object() || !IsHttpUrl(Dyn::StrOr(Dyn::Get(s, "appUrl"), ""))) {
|
||||
slots.problems.push_back(std::format("{}: no appUrl", rel));
|
||||
continue;
|
||||
}
|
||||
const Json& api = Dyn::Or(Dyn::Get(s, "apiUrls"), Dyn::EmptyList());
|
||||
if (!AllStrings(api)) {
|
||||
slots.problems.push_back(std::format("{}: apiUrls must be a list of URLs", rel));
|
||||
continue;
|
||||
}
|
||||
const Json& db = Dyn::Get(s, "dbUrl");
|
||||
if (!db.is_null()) {
|
||||
if (const std::optional<std::string> problem = PgWire::CheckUrl(db)) {
|
||||
slots.problems.push_back(std::format("{}: dbUrl: {}", rel, *problem));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const Json& login = Dyn::Get(s, "login");
|
||||
if (!login.is_null() && (!login.is_string() || !fs::exists(repo / login.get<std::string>()))) {
|
||||
slots.problems.push_back(std::format("{}: login {} is not a file", rel, Dyn::ReprValue(login)));
|
||||
continue;
|
||||
}
|
||||
slots.stacks.push_back({
|
||||
{"id", std::format("slot {}", n)},
|
||||
{"appUrl", Dyn::RStrip(Dyn::At(s, "appUrl").get<std::string>(), "/")},
|
||||
{"apiUrls", api},
|
||||
{"dbUrl", db},
|
||||
{"login", login},
|
||||
{"slot", true},
|
||||
});
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
std::vector<std::string> SlotCommands(const Json& config, std::string_view which, std::span<const std::int64_t> slots) {
|
||||
const Json& command = Dyn::Get(Dyn::Or(Dyn::Get(config, "slots"), Dyn::EmptyDict()), which);
|
||||
if (!Dyn::Truthy(command)) return {};
|
||||
std::vector<std::string> out;
|
||||
for (const std::int64_t n : slots) out.push_back(Dyn::Replace(command.get<std::string>(), "{n}", std::to_string(n)));
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<std::string> LoginFixture(const Json& config, const fs::path& repo) {
|
||||
const Json& login = Dyn::Or(Dyn::Get(Dyn::At(config, "functional"), "login"), Dyn::EmptyDict());
|
||||
for (const Json& fixture : Dyn::Or(Dyn::Get(login, "fixtures"), Dyn::EmptyList())) {
|
||||
if (fs::exists(repo / fixture.get<std::string>())) return fixture.get<std::string>();
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
Json Example() {
|
||||
Json example = Defaults();
|
||||
example["base"] = "origin/main";
|
||||
example["authors"] = {"you@example.com"};
|
||||
example["aiTrailers"] = "forbid";
|
||||
example["gate0"] = {"make check"};
|
||||
Json& functional = example["functional"];
|
||||
functional["appUrl"] = "http://localhost:8080";
|
||||
functional["start"] = "make run";
|
||||
functional["stop"] = "make stop";
|
||||
functional["login"] = {{"fixtures", {".local-stack/test-user.json"}}, {"notes", "the fixture holds a TOTP-verified login"}};
|
||||
functional["exclude"] = {"**/*.test.*", "**/*.spec.*", "docs/**", ".github/**", "*.md"};
|
||||
return example;
|
||||
}
|
||||
|
||||
std::int32_t Main(const fs::path& repo, const fs::path& path) {
|
||||
const Loaded loaded = Load(repo, path);
|
||||
Json shown = Redacted(loaded.config);
|
||||
// The database password masked, as in the dump.
|
||||
shown["_path"] = Dyn::Get(loaded.config, "_path");
|
||||
std::println("{}", DumpFile(shown));
|
||||
for (const Json& warning : Dyn::Or(Dyn::Get(loaded.config, "_warnings"), Dyn::EmptyList())) std::println("warning: {}", Dyn::Str(warning));
|
||||
for (const std::string& problem : loaded.problems) std::println("problem: {}", problem);
|
||||
return loaded.problems.empty() ? 0 : 1;
|
||||
}
|
||||
}
|
||||
|
|
@ -50,6 +50,11 @@ namespace Crafter::Review {
|
|||
return std::format("crafter-review {} (prompt v{})", Version(), PromptVersion);
|
||||
}
|
||||
|
||||
std::string Invocation() {
|
||||
if (Platform::InSandbox()) return "flatpak run net.catcrafts.CrafterReview";
|
||||
return Platform::SelfExe().string();
|
||||
}
|
||||
|
||||
const fs::path& Home() {
|
||||
if (!HomeOverride()) HomeOverride() = FindHome();
|
||||
return *HomeOverride();
|
||||
|
|
|
|||
158
implementations/Crafter.Review-Dispositions.cpp
Normal file
158
implementations/Crafter.Review-Dispositions.cpp
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Dispositions_impl;
|
||||
import :Dispositions;
|
||||
import :Json;
|
||||
import :Text;
|
||||
import :Platform;
|
||||
import std;
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace Crafter::Review::Dispositions {
|
||||
namespace {
|
||||
// A map key, as text: ids are compared by value and type.
|
||||
std::string KeyOf(const Json& value) {
|
||||
return DumpCompactSorted(value);
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> Statuses(std::span<const Json> rows) {
|
||||
std::map<std::string, std::string> out;
|
||||
for (const Json& row : rows) out[KeyOf(Dyn::At(row, "id"))] = Dyn::At(row, "status").get<std::string>();
|
||||
return out;
|
||||
}
|
||||
|
||||
// A string, or Error (TypeError): only a string is concatenated.
|
||||
const std::string& Text(const Json& value) {
|
||||
if (!value.is_string()) throw Dyn::Error("TypeError", std::format("can only concatenate str (not \"{}\") to str", Dyn::TypeName(value)));
|
||||
return value.get_ref<const std::string&>();
|
||||
}
|
||||
|
||||
std::string JoinStrings(const Json& list, std::string_view separator) {
|
||||
std::vector<std::string> parts;
|
||||
for (const Json& item : list) {
|
||||
if (!item.is_string()) throw Dyn::Error("TypeError", std::format("sequence item {}: expected str instance, {} found", parts.size(), Dyn::TypeName(item)));
|
||||
parts.push_back(item.get<std::string>());
|
||||
}
|
||||
return Dyn::Join(parts, separator);
|
||||
}
|
||||
|
||||
std::size_t Len(const Json& value) {
|
||||
return value.is_string() ? Dyn::Length(value.get_ref<const std::string&>()) : value.size();
|
||||
}
|
||||
|
||||
constexpr std::string_view Rules =
|
||||
"Rules: if you detect a finding one of these entries names, STILL REPORT IT and set dischargedBy to its id and its unit id in items:[] - detection never changes, only disposition, and Gate 4 must see it. "
|
||||
"Before setting dischargedBy, VERIFY that entry's grounds against its cited evidence (the repository, the evidence paths when INPUTS names them, the running application for the functional lens). "
|
||||
"If the grounds do not survive, return the finding WITHOUT dischargedBy and set contests {id, why} with the evidence - a contest is a claim and will itself be verified. "
|
||||
"Record that verification inside the finding's evidence field. For a refuted entry you agree with, return a note kind=refutation-verified with its id instead of a finding. "
|
||||
"An entry with no matching finding of yours: ignore it - nothing is owed for it.";
|
||||
}
|
||||
|
||||
std::vector<Json> Load(std::string_view path) {
|
||||
if (path.empty()) return {};
|
||||
const std::optional<std::string> text = Platform::ReadFile(fs::path(path));
|
||||
if (!text) throw Dyn::Error("FileNotFoundError", std::format("[Errno 2] No such file or directory: {}", Dyn::Repr(path)));
|
||||
const Json document = Json::parse(*text);
|
||||
std::vector<Json> out;
|
||||
auto keep = [&](const Json& entry) {
|
||||
if (Dyn::Truthy(entry) && Dyn::Truthy(Dyn::Get(entry, "id"))) out.push_back(entry);
|
||||
};
|
||||
if (document.is_array()) {
|
||||
for (const Json& entry : document) keep(entry);
|
||||
} else {
|
||||
keep(document);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<Json> Classify(std::span<const Json> entries, std::string_view hash, const fs::path& artifact) {
|
||||
std::vector<Json> rows;
|
||||
for (const Json& entry : entries) {
|
||||
if (Dyn::Equal(Dyn::Get(entry, "hash"), Json(hash))) {
|
||||
rows.push_back({{"id", Dyn::At(entry, "id")}, {"status", "in-force"}, {"detail", "hash match"}});
|
||||
continue;
|
||||
}
|
||||
const Json& carry = Dyn::Get(entry, "carry");
|
||||
if (carry.is_boolean() && carry.get<bool>() && Dyn::Truthy(Dyn::Get(entry, "anchors"))) {
|
||||
bool ok = true;
|
||||
std::vector<std::string> details;
|
||||
for (const Json& anchor : Dyn::At(entry, "anchors")) {
|
||||
const std::string& file = Text(Dyn::At(anchor, "file"));
|
||||
const fs::path path = fs::is_directory(artifact) ? artifact / Dyn::BaseName(file) : fs::path(file);
|
||||
std::string text;
|
||||
try {
|
||||
text = Dyn::ReadText(path);
|
||||
} catch (const std::exception&) {
|
||||
ok = false;
|
||||
details.push_back(std::format("{}: unreadable", file));
|
||||
continue;
|
||||
}
|
||||
const std::size_t found = Dyn::Count(text, Text(Dyn::At(anchor, "text")));
|
||||
const Json& recorded = Dyn::Get(anchor, "count");
|
||||
details.push_back(std::format("{}: recorded {} found {}", file, Dyn::Str(recorded), found));
|
||||
if (!Dyn::Equal(Json(found), recorded)) ok = false;
|
||||
}
|
||||
rows.push_back({{"id", Dyn::At(entry, "id")}, {"status", ok ? "carried" : "lapsed"}, {"detail", Dyn::Join(details, "; ")}});
|
||||
} else {
|
||||
rows.push_back({{"id", Dyn::At(entry, "id")}, {"status", "lapsed"}, {"detail", "hash mismatch; carry disabled or no anchors"}});
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
std::vector<Json> InForce(std::span<const Json> entries, std::span<const Json> rows) {
|
||||
const std::map<std::string, std::string> status = Statuses(rows);
|
||||
std::vector<Json> out;
|
||||
for (const Json& entry : entries) {
|
||||
const auto found = status.find(KeyOf(Dyn::At(entry, "id")));
|
||||
if (found != status.end() && (found->second == "in-force" || found->second == "carried")) out.push_back(entry);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Block(std::span<const Json> inForce, std::span<const Json> rows, std::string_view lensFile, std::string_view hash) {
|
||||
std::vector<const Json*> visible;
|
||||
for (const Json& entry : inForce) {
|
||||
const Json& lenses = Dyn::Get(entry, "lenses");
|
||||
if (!Dyn::Equal(Dyn::Get(entry, "kind"), Json("refuted")) || (Dyn::Truthy(lenses) && Dyn::In(Json(lensFile), lenses))) visible.push_back(&entry);
|
||||
}
|
||||
const std::string head = std::format("DISPOSITIONS IN FORCE at hash {} - the register is the authority. Nothing outside this list discharges anything.", hash);
|
||||
if (visible.empty()) return std::format("{}\n(none)", head);
|
||||
const std::map<std::string, std::string> status = Statuses(rows);
|
||||
std::vector<std::string> lines;
|
||||
for (const Json* entry : visible) {
|
||||
const Json& d = *entry;
|
||||
std::vector<std::string> anchorTexts;
|
||||
if (Dyn::Has(d, "anchors")) {
|
||||
for (const Json& anchor : Dyn::At(d, "anchors")) {
|
||||
anchorTexts.push_back(std::format("{} x{}", Dyn::Str(Dyn::At(anchor, "file")), Dyn::Str(Dyn::Get(anchor, "count"))));
|
||||
}
|
||||
}
|
||||
std::string anchors = Dyn::Join(anchorTexts, ", ");
|
||||
if (anchors.empty()) anchors = "none";
|
||||
const auto found = status.find(KeyOf(Dyn::At(d, "id")));
|
||||
const bool carried = found != status.end() && found->second == "carried";
|
||||
std::string tag = std::format("{} [{}", Dyn::Str(Dyn::At(d, "id")), Dyn::Str(Dyn::Get(d, "kind")));
|
||||
if (Dyn::Truthy(Dyn::Get(d, "by"))) tag += std::format(", by {}", Text(Dyn::At(d, "by")));
|
||||
if (Dyn::Truthy(Dyn::Get(d, "boundAt"))) tag += std::format(", bound {}", Text(Dyn::At(d, "boundAt")));
|
||||
if (carried) tag += ", CARRIED to this hash";
|
||||
if (Dyn::Truthy(Dyn::Get(d, "lenses"))) tag += std::format(", lenses: {}", JoinStrings(Dyn::At(d, "lenses"), " "));
|
||||
tag += "]";
|
||||
std::string line = std::format("- {}\n finding: {}\n grounds: {}", tag, Dyn::StrOr(Dyn::Get(d, "finding"), "(unnamed)"),
|
||||
Dyn::StrOr(Dyn::Get(d, "grounds"), "(none recorded)"));
|
||||
if (Dyn::Truthy(Dyn::Get(d, "supersedes"))) line += std::format("\n supersedes: {}", Text(Dyn::At(d, "supersedes")));
|
||||
line += std::format("\n anchors: {}", anchors);
|
||||
if (Dyn::Truthy(Dyn::Get(d, "reaffirmed"))) {
|
||||
line += std::format("\n REAFFIRMED by the owner {}x - final for this binding; a further contest is recorded for Gate 4, it does not block", Len(Dyn::At(d, "reaffirmed")));
|
||||
}
|
||||
if (Dyn::Truthy(Dyn::Get(d, "contestRejected"))) {
|
||||
line += std::format("\n contest REJECTED {}x after re-checking the cited fact - a repeat contest without new evidence is recorded, it does not block",
|
||||
Len(Dyn::At(d, "contestRejected")));
|
||||
}
|
||||
lines.push_back(std::move(line));
|
||||
}
|
||||
return std::format("{}\n{}\n{}", head, Dyn::Join(lines, "\n"), Rules);
|
||||
}
|
||||
}
|
||||
|
|
@ -6,8 +6,12 @@ import :Driver;
|
|||
import :Core;
|
||||
import :Platform;
|
||||
import :Process;
|
||||
import :Inventory;
|
||||
import :Config;
|
||||
import std;
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace Crafter::Review {
|
||||
namespace {
|
||||
constexpr std::string_view Usage =
|
||||
|
|
@ -28,6 +32,11 @@ inventory unit, against a frozen commit range.)";
|
|||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::int32_t UsageError(std::string_view message) {
|
||||
std::println(std::cerr, "{}\ncrafter-review: error: {}", Usage, message);
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
std::int32_t Main(std::span<const std::string_view> args) {
|
||||
|
|
@ -37,12 +46,44 @@ inventory unit, against a frozen commit range.)";
|
|||
// command anyone types.
|
||||
if (!rest.empty() && rest.front() == Process::SuperviseVerb) return Process::SuperviseMain(rest.subspan(1));
|
||||
Platform::Init();
|
||||
if (!rest.empty() && rest.front() == "--version") return PrintVersion();
|
||||
if (!rest.empty() && (rest.front() == "-h" || rest.front() == "--help")) {
|
||||
// The options before the command: --config FILE or --config=FILE, and
|
||||
// any unique prefix of a long option.
|
||||
std::optional<std::string> configPath;
|
||||
std::size_t at = 0;
|
||||
while (at < rest.size() && rest[at].starts_with("--") && rest[at] != "--") {
|
||||
const std::string_view arg = rest[at];
|
||||
const std::size_t equals = arg.find('=');
|
||||
const std::string_view name = arg.substr(0, equals);
|
||||
if (name.size() > 2 && std::string_view("--config").starts_with(name)) {
|
||||
if (equals != std::string_view::npos) {
|
||||
configPath = std::string(arg.substr(equals + 1));
|
||||
} else if (at + 1 < rest.size()) {
|
||||
configPath = std::string(rest[++at]);
|
||||
} else {
|
||||
return UsageError("argument --config: expected one argument");
|
||||
}
|
||||
} else if (name.size() > 2 && std::string_view("--version").starts_with(name)) {
|
||||
return PrintVersion();
|
||||
} else if (name.size() > 2 && std::string_view("--help").starts_with(name)) {
|
||||
std::println("{}", Usage);
|
||||
return 0;
|
||||
} else {
|
||||
return UsageError(std::format("unrecognized arguments: {}", arg));
|
||||
}
|
||||
++at;
|
||||
}
|
||||
if (at < rest.size() && rest[at] == "-h") {
|
||||
std::println("{}", Usage);
|
||||
return 0;
|
||||
}
|
||||
std::println(std::cerr, "{}", Usage);
|
||||
return 3;
|
||||
if (at >= rest.size()) return UsageError("a command is required");
|
||||
const std::string_view command = rest[at];
|
||||
const std::span<const std::string_view> after = rest.subspan(at + 1);
|
||||
if (command == "inventory" && !configPath) return Inventory::Main(after);
|
||||
if (command == "config") {
|
||||
if (!after.empty()) return UsageError(std::format("unrecognized arguments: {}", after.front()));
|
||||
return Config::Main(fs::current_path(), configPath ? fs::path(*configPath) : fs::path());
|
||||
}
|
||||
return UsageError(std::format("argument cmd: invalid choice: '{}'", command));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
293
implementations/Crafter.Review-Inventory.cpp
Normal file
293
implementations/Crafter.Review-Inventory.cpp
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Inventory_impl;
|
||||
import :Inventory;
|
||||
import :Json;
|
||||
import :Text;
|
||||
import :Artifact;
|
||||
import :Plan;
|
||||
import std;
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace Crafter::Review::Inventory {
|
||||
namespace {
|
||||
constexpr std::string_view Usage = R"(Partition a frozen commit range (a `git format-patch` export) into review units for the coverage contract.
|
||||
|
||||
The inventory is MECHANICAL: no agent decides what the units are. Every non-blank line of the artifact belongs to
|
||||
exactly one unit, and the tool fails if that invariant does not hold. Fixed slots are added so that what is NOT in
|
||||
the text still has a row in the coverage matrix.
|
||||
|
||||
crafter-review inventory commits <dir-with-*.patch> > gate-state/inventory-<hash8>.json
|
||||
|
||||
Units (ids):
|
||||
pK:subject commit K's subject
|
||||
pK:msg commit K's message body (before the trailers) - only when non-empty
|
||||
pK:trailers commit K's trailer block - only when non-empty
|
||||
pK:diffstat commit K's diffstat
|
||||
pK:<file>#hdr the diff header of <file> in commit K (mode, rename, blobs)
|
||||
pK:<file>#H hunk H of <file> in commit K; a hunk of a documentation file (DOC_FILE) that holds more than one
|
||||
heading-delimited part is cut into #H.1, #H.2, ... (doc_parts)
|
||||
pK:outside fixed slot: the in-repository users/callers of what commit K changes (outside its diff)
|
||||
pK:absent fixed slot: what a reviewer expects in commit K and does not find
|
||||
whole:* fixed slots (WHOLE_COMMITS)
|
||||
)";
|
||||
|
||||
// re.match(r'\s{0,3}(```|~~~)', body): a fence, indented by three
|
||||
// whitespace characters at most.
|
||||
bool OpensFence(std::string_view body) {
|
||||
std::size_t at = 0;
|
||||
for (std::int32_t i = 0; i < 3 && at < body.size(); ++i) {
|
||||
const auto [c, used] = Dyn::CodePointAt(body, at);
|
||||
if (!Dyn::IsSpace(c)) break;
|
||||
at += used;
|
||||
}
|
||||
const std::string_view rest = body.substr(at);
|
||||
return rest.starts_with("```") || rest.starts_with("~~~");
|
||||
}
|
||||
|
||||
// re.match(r'#{1,6}\s', body): an ATX heading.
|
||||
bool IsHeading(std::string_view body) {
|
||||
std::size_t hashes = 0;
|
||||
while (hashes < body.size() && body[hashes] == '#') ++hashes;
|
||||
if (hashes == 0 || hashes > 6 || hashes >= body.size()) return false;
|
||||
return Dyn::IsSpace(Dyn::CodePointAt(body, hashes).first);
|
||||
}
|
||||
|
||||
// re.match(r'^[A-Z][A-Za-z-]+: ', line): a trailer such as
|
||||
// `Signed-off-by: `.
|
||||
bool IsTrailer(std::string_view line) {
|
||||
if (line.empty() || line[0] < 'A' || line[0] > 'Z') return false;
|
||||
std::size_t at = 1;
|
||||
while (at < line.size() && ((line[at] >= 'A' && line[at] <= 'Z') || (line[at] >= 'a' && line[at] <= 'z') || line[at] == '-')) ++at;
|
||||
return at > 1 && line.substr(at).starts_with(": ");
|
||||
}
|
||||
|
||||
bool AnyNonBlank(std::span<const std::string> lines, std::int64_t from, std::int64_t to) {
|
||||
const auto [a, b] = Dyn::SliceBounds(lines.size(), from, to);
|
||||
return std::any_of(lines.begin() + static_cast<std::ptrdiff_t>(a), lines.begin() + static_cast<std::ptrdiff_t>(b),
|
||||
[](const std::string& line) { return !Dyn::Strip(line).empty(); });
|
||||
}
|
||||
|
||||
std::span<const std::string> Lines(std::span<const std::string> lines, std::int64_t from, std::int64_t to) {
|
||||
const auto [a, b] = Dyn::SliceBounds(lines.size(), from, to);
|
||||
return lines.subspan(a, b - a);
|
||||
}
|
||||
|
||||
Json Unit(std::string id, std::int64_t first, std::int64_t last, std::string excerpt) {
|
||||
return {{"id", std::move(id)}, {"lines", {first, last}}, {"excerpt", std::move(excerpt)}};
|
||||
}
|
||||
|
||||
std::string ReprInts(std::span<const std::int64_t> values) {
|
||||
std::string out = "[";
|
||||
for (std::size_t i = 0; i < values.size(); ++i) out += std::format("{}{}", i ? ", " : "", values[i]);
|
||||
return std::format("{}]", out);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::size_t, std::size_t>> DocParts(std::span<const std::string> lines, std::size_t a, std::size_t b) {
|
||||
std::vector<std::pair<std::size_t, std::size_t>> parts;
|
||||
std::size_t start = a;
|
||||
bool hasBody = false;
|
||||
bool fenced = false;
|
||||
for (std::size_t i = a + 1; i < b; ++i) {
|
||||
const std::string& line = lines[i];
|
||||
// l[:1] in (' ', '+') and l[1:]: the marker and the line after it.
|
||||
const bool isNew = line.starts_with(' ') || line.starts_with('+');
|
||||
const std::string_view body = line.empty() ? std::string_view() : std::string_view(line).substr(Dyn::CodePointAt(line, 0).second);
|
||||
if (isNew && OpensFence(body)) fenced = !fenced;
|
||||
if (isNew && !fenced && IsHeading(body)) {
|
||||
if (hasBody) {
|
||||
parts.emplace_back(start, i);
|
||||
start = i;
|
||||
hasBody = false;
|
||||
}
|
||||
} else if (!Dyn::Strip(line).empty() && !Dyn::Strip(body).empty()) {
|
||||
hasBody = true;
|
||||
}
|
||||
}
|
||||
parts.emplace_back(start, b);
|
||||
return parts;
|
||||
}
|
||||
|
||||
std::string Excerpt(std::span<const std::string> lines) {
|
||||
for (const std::string& line : lines) {
|
||||
const std::string stripped = Dyn::Strip(line);
|
||||
if (!stripped.empty()) return Dyn::Slice(stripped, 0, 90);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
Series PartitionSeries(const fs::path& dir, bool splitDocs) {
|
||||
Series series;
|
||||
series.units = Json::array();
|
||||
Json& units = series.units;
|
||||
std::int64_t offset = 0;
|
||||
for (const std::string& name : Artifact::PatchFiles(dir)) {
|
||||
const std::string text = Dyn::ReadText(dir / name);
|
||||
const std::vector<std::string> lines = Dyn::Split(text, "\n");
|
||||
const auto count = static_cast<std::int64_t>(lines.size());
|
||||
const std::optional<std::int64_t> number = Artifact::PatchNumber(name);
|
||||
const std::string pid = std::format("p{}", number ? *number : -1);
|
||||
const std::int64_t base = offset;
|
||||
std::optional<std::int64_t> subject;
|
||||
for (std::int64_t i = 0; i < count; ++i) {
|
||||
if (lines[static_cast<std::size_t>(i)].starts_with("Subject:")) {
|
||||
subject = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::int64_t body0 = 1;
|
||||
if (subject) {
|
||||
for (std::int64_t i = *subject + 1; i < count; ++i) {
|
||||
if (Dyn::Strip(lines[static_cast<std::size_t>(i)]).empty()) {
|
||||
body0 = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// >= : a body-less commit's first body line IS the '---'.
|
||||
std::int64_t diff0 = count;
|
||||
for (std::int64_t i = body0; i < count; ++i) {
|
||||
if (lines[static_cast<std::size_t>(i)].starts_with("---")) {
|
||||
diff0 = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
units.push_back(Unit(std::format("{}:subject", pid), base + 1, base + body0,
|
||||
subject ? Dyn::Slice(Dyn::Strip(lines[static_cast<std::size_t>(*subject)]), 0, 90) : std::string()));
|
||||
std::int64_t t = diff0;
|
||||
while (t - 1 > body0 && (IsTrailer(lines[static_cast<std::size_t>(t - 1)]) || Dyn::Strip(lines[static_cast<std::size_t>(t - 1)]).empty())) --t;
|
||||
if (AnyNonBlank(lines, body0, t)) {
|
||||
units.push_back(Unit(std::format("{}:msg", pid), base + body0 + 1, base + t, Excerpt(Lines(lines, body0, t))));
|
||||
}
|
||||
if (AnyNonBlank(lines, t, diff0)) {
|
||||
units.push_back(Unit(std::format("{}:trailers", pid), base + t + 1, base + diff0, Excerpt(Lines(lines, t, diff0))));
|
||||
}
|
||||
const std::int64_t statStart = diff0;
|
||||
std::int64_t firstDiff = count;
|
||||
for (std::int64_t i = diff0 + 1; i < count; ++i) {
|
||||
if (lines[static_cast<std::size_t>(i)].starts_with("diff --git")) {
|
||||
firstDiff = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
units.push_back(Unit(std::format("{}:diffstat", pid), base + statStart + 1, base + firstDiff, Excerpt(Lines(lines, statStart, firstDiff))));
|
||||
|
||||
std::string currentFile;
|
||||
std::int64_t hunk = 0;
|
||||
std::optional<std::int64_t> hunkStart;
|
||||
auto closeHunk = [&](std::int64_t upto) {
|
||||
if (!hunkStart) return;
|
||||
std::vector<std::pair<std::size_t, std::size_t>> parts;
|
||||
if (splitDocs && Plan::IsDocPath(currentFile)) {
|
||||
parts = DocParts(lines, static_cast<std::size_t>(*hunkStart), static_cast<std::size_t>(upto));
|
||||
} else {
|
||||
parts = {{static_cast<std::size_t>(*hunkStart), static_cast<std::size_t>(upto)}};
|
||||
}
|
||||
for (std::size_t n = 0; n < parts.size(); ++n) {
|
||||
const auto [s, e] = parts[n];
|
||||
const std::string suffix = parts.size() > 1 ? std::format(".{}", n + 1) : std::string();
|
||||
units.push_back(Unit(std::format("{}:{}#{}{}", pid, currentFile, hunk, suffix), base + static_cast<std::int64_t>(s) + 1,
|
||||
base + static_cast<std::int64_t>(e), Excerpt(Lines(lines, static_cast<std::int64_t>(s), static_cast<std::int64_t>(s) + 1))));
|
||||
}
|
||||
};
|
||||
std::int64_t i = firstDiff;
|
||||
while (i < count) {
|
||||
const std::string& line = lines[static_cast<std::size_t>(i)];
|
||||
if (line.starts_with("diff --git")) {
|
||||
closeHunk(i);
|
||||
hunkStart.reset();
|
||||
currentFile = Dyn::Strip(Dyn::Split(line, " b/").back());
|
||||
hunk = 0;
|
||||
const std::int64_t header = i;
|
||||
std::int64_t j = i + 1;
|
||||
while (j < count && !lines[static_cast<std::size_t>(j)].starts_with("@@") && !lines[static_cast<std::size_t>(j)].starts_with("diff --git")) ++j;
|
||||
units.push_back(Unit(std::format("{}:{}#hdr", pid, currentFile), base + header + 1, base + j, Dyn::Slice(Dyn::Strip(line), 0, 90)));
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
if (line.starts_with("@@")) {
|
||||
closeHunk(i);
|
||||
++hunk;
|
||||
hunkStart = i;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
closeHunk(count);
|
||||
units.push_back(Unit(std::format("{}:outside", pid), 0, 0, "FIXED SLOT: in-repository users/callers of what this commit changes, outside its diff"));
|
||||
units.push_back(Unit(std::format("{}:absent", pid), 0, 0, "FIXED SLOT: what a reviewer expects in this commit and does not find"));
|
||||
series.lines.insert(series.lines.end(), lines.begin(), lines.end());
|
||||
offset += count;
|
||||
}
|
||||
return series;
|
||||
}
|
||||
|
||||
Built Build(std::string_view mode, std::string_view artifact) {
|
||||
if (mode != "commits") throw InvariantError(std::format("inventory: mode {} is not supported here (commits only)", Dyn::Repr(mode)));
|
||||
Series series = PartitionSeries(fs::path(artifact), true);
|
||||
Json& units = series.units;
|
||||
const std::string h8 = Artifact::ArtifactHash("commits", fs::path(artifact)).substr(0, 8);
|
||||
std::map<std::int64_t, std::string> owner;
|
||||
for (const Json& unit : units) {
|
||||
const std::int64_t a = Dyn::At(unit, "lines")[0].get<std::int64_t>();
|
||||
const std::int64_t b = Dyn::At(unit, "lines")[1].get<std::int64_t>();
|
||||
const std::string& id = Dyn::At(unit, "id").get_ref<const std::string&>();
|
||||
for (std::int64_t line = a; line <= b; ++line) {
|
||||
if (line == 0) continue;
|
||||
if (const auto held = owner.find(line); held != owner.end()) {
|
||||
throw InvariantError(std::format("INVARIANT: line {} in both {} and {}", line, held->second, id));
|
||||
}
|
||||
owner[line] = id;
|
||||
}
|
||||
}
|
||||
std::vector<std::int64_t> uncovered;
|
||||
for (std::size_t i = 0; i < series.lines.size(); ++i) {
|
||||
const auto line = static_cast<std::int64_t>(i) + 1;
|
||||
if (!Dyn::Strip(series.lines[i]).empty() && !owner.contains(line)) uncovered.push_back(line);
|
||||
}
|
||||
if (!uncovered.empty()) {
|
||||
const std::span<const std::int64_t> first(uncovered.data(), std::min<std::size_t>(uncovered.size(), 10));
|
||||
throw InvariantError(std::format("INVARIANT: {} non-blank lines in no unit, first: {}", uncovered.size(), ReprInts(first)));
|
||||
}
|
||||
for (const WholeSlot& slot : WholeCommits) units.push_back(Unit(std::string(slot.id), 0, 0, std::format("FIXED SLOT: {}", slot.description)));
|
||||
std::map<std::string, std::int32_t> seen;
|
||||
for (const Json& unit : units) ++seen[Dyn::At(unit, "id").get<std::string>()];
|
||||
Json duplicates = Json::array();
|
||||
for (const auto& [id, times] : seen) {
|
||||
if (times > 1) duplicates.push_back(id);
|
||||
}
|
||||
if (!duplicates.empty()) throw InvariantError(std::format("INVARIANT: duplicate ids {}", Dyn::ReprValue(duplicates)));
|
||||
const std::size_t total = units.size();
|
||||
Built built;
|
||||
built.out = {
|
||||
{"mode", mode},
|
||||
{"artifact", artifact},
|
||||
{"hash8", h8},
|
||||
{"units", std::move(units)},
|
||||
{"invariant", "every non-blank line belongs to exactly one unit; fixed slots have lines [0,0]"},
|
||||
{"count", total},
|
||||
};
|
||||
built.lines = std::move(series.lines);
|
||||
return built;
|
||||
}
|
||||
|
||||
std::int32_t Main(std::span<const std::string_view> args) {
|
||||
if (args.size() != 2 || args[0] != "commits") {
|
||||
std::print(std::cerr, "{}", Usage);
|
||||
return 1;
|
||||
}
|
||||
try {
|
||||
const Built built = Build(args[0], args[1]);
|
||||
std::println("{}", DumpFile(built.out));
|
||||
return 0;
|
||||
} catch (const InvariantError& error) {
|
||||
std::println(std::cerr, "{}", error.what());
|
||||
return 1;
|
||||
} catch (const std::exception& error) {
|
||||
std::println(std::cerr, "inventory: {}", error.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
450
implementations/Crafter.Review-Normalize.cpp
Normal file
450
implementations/Crafter.Review-Normalize.cpp
Normal file
|
|
@ -0,0 +1,450 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Normalize_impl;
|
||||
import :Normalize;
|
||||
import :Json;
|
||||
import :Text;
|
||||
import :Schema;
|
||||
import std;
|
||||
|
||||
namespace Crafter::Review::Normalize {
|
||||
namespace {
|
||||
// A map key or set member, as text: equal values give equal keys. A
|
||||
// list or an object cannot be one (TypeError).
|
||||
std::string KeyOf(const Json& value) {
|
||||
if (value.is_array() || value.is_object()) throw Dyn::Error("TypeError", std::format("unhashable type: '{}'", Dyn::TypeName(value)));
|
||||
return DumpCompactSorted(value);
|
||||
}
|
||||
|
||||
// The key's value, or the fallback when the key is absent.
|
||||
const Json& GetOr(const Json& dict, std::string_view key, const Json& fallback) {
|
||||
return Dyn::Has(dict, key) ? Dyn::At(dict, key) : fallback;
|
||||
}
|
||||
|
||||
// `list + list`
|
||||
Json Concat(const Json& a, const Json& b) {
|
||||
if (!a.is_array() || !b.is_array()) throw Dyn::Error("TypeError", "can only concatenate list (not \"NoneType\") to list");
|
||||
Json out = a;
|
||||
for (const Json& item : b) out.push_back(item);
|
||||
return out;
|
||||
}
|
||||
|
||||
// The hashes a disposition is bound to: this run's, its own and the
|
||||
// ones it was carried from.
|
||||
Json Chain(std::string_view hash, const Json& d) {
|
||||
Json chain = Json::array();
|
||||
auto add = [&](const Json& h) {
|
||||
if (Dyn::Truthy(h)) chain.push_back(h);
|
||||
};
|
||||
add(Json(hash));
|
||||
add(Dyn::Get(d, "hash"));
|
||||
for (const Json& carried : GetOr(d, "carried", Dyn::EmptyList())) add(Dyn::Get(carried, "hash"));
|
||||
return chain;
|
||||
}
|
||||
|
||||
// Reaffirmed by the owner, or a contest of it rejected, on this
|
||||
// binding.
|
||||
bool Settled(std::string_view hash, const Json& d) {
|
||||
const Json chain = Chain(hash, d);
|
||||
const Json records = Concat(GetOr(d, "reaffirmed", Dyn::EmptyList()), GetOr(d, "contestRejected", Dyn::EmptyList()));
|
||||
return std::ranges::any_of(records, [&](const Json& record) { return Dyn::In(Dyn::Get(record, "hash"), chain); });
|
||||
}
|
||||
|
||||
bool In(std::string_view verdict, std::span<const std::string_view> vocabulary) {
|
||||
return std::ranges::contains(vocabulary, verdict);
|
||||
}
|
||||
|
||||
bool InVocabulary(const Json& verdict, std::span<const std::string_view> vocabulary) {
|
||||
return verdict.is_string() && In(verdict.get_ref<const std::string&>(), vocabulary);
|
||||
}
|
||||
|
||||
std::string JoinStrings(std::span<const Json> items, std::string_view separator) {
|
||||
std::vector<std::string> parts;
|
||||
for (const Json& item : items) {
|
||||
if (!item.is_string()) throw Dyn::Error("TypeError", std::format("sequence item {}: expected str instance, {} found", parts.size(), Dyn::TypeName(item)));
|
||||
parts.push_back(item.get<std::string>());
|
||||
}
|
||||
return Dyn::Join(parts, separator);
|
||||
}
|
||||
|
||||
// An ordered map keyed by value (KeyOf): the order of first insertion,
|
||||
// and the last value set.
|
||||
struct OrderedMap {
|
||||
std::vector<std::pair<Json, Json>> items;
|
||||
std::map<std::string, std::size_t> index;
|
||||
|
||||
Json* Find(const Json& key) {
|
||||
const auto found = index.find(KeyOf(key));
|
||||
return found == index.end() ? nullptr : &items[found->second].second;
|
||||
}
|
||||
|
||||
void Set(const Json& key, Json value) {
|
||||
if (Json* existing = Find(key)) {
|
||||
*existing = std::move(value);
|
||||
return;
|
||||
}
|
||||
index[KeyOf(key)] = items.size();
|
||||
items.emplace_back(key, std::move(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Json ResolveId(const Json& id, std::span<const std::string> universe) {
|
||||
if (id.is_string()) {
|
||||
const std::string& text = id.get_ref<const std::string&>();
|
||||
if (std::ranges::contains(universe, text)) return id;
|
||||
std::vector<const std::string*> matches;
|
||||
for (const std::string& candidate : universe) {
|
||||
if (candidate.starts_with(text)) matches.push_back(&candidate);
|
||||
}
|
||||
return matches.size() == 1 ? Json(*matches.front()) : id;
|
||||
}
|
||||
// `s in universe` is false for anything but a str; u.startswith(s)
|
||||
// then raises, unless there is no u to ask.
|
||||
if (universe.empty()) return id;
|
||||
throw Dyn::Error("TypeError", std::format("startswith first arg must be str or a tuple of str, not {}", Dyn::TypeName(id)));
|
||||
}
|
||||
|
||||
Json NormalizeOutput(Json& v, std::span<const Json> inForce, std::string_view lensFile, std::string_view hash, const Json& inventory,
|
||||
std::span<const std::string> allIds) {
|
||||
std::map<std::string, const Json*> byId;
|
||||
for (const Json& d : inForce) byId[KeyOf(Dyn::At(d, "id"))] = &d;
|
||||
auto disposition = [&](const Json& id) -> const Json* {
|
||||
const auto found = byId.find(KeyOf(id));
|
||||
return found == byId.end() ? nullptr : found->second;
|
||||
};
|
||||
Json violations = Json::array();
|
||||
Json contests = Json::array();
|
||||
Json cross = Json::array();
|
||||
Json logs = Json::array();
|
||||
Json findings = Json::array();
|
||||
for (const Json& f : Dyn::Or(Dyn::Get(v, "findings"), Dyn::EmptyList())) {
|
||||
if (!f.is_object()) throw Dyn::Error("TypeError", std::format("'{}' object is not iterable", Dyn::TypeName(f)));
|
||||
Json out = f;
|
||||
bool discharged = false;
|
||||
if (Dyn::Truthy(Dyn::Get(f, "dischargedBy"))) {
|
||||
const Json* d = disposition(Dyn::At(f, "dischargedBy"));
|
||||
if (!d || !Dyn::Truthy(*d)) {
|
||||
logs.push_back(std::format("{}: dischargedBy={} names no disposition in force - treated as undischarged", lensFile, Dyn::Str(Dyn::At(f, "dischargedBy"))));
|
||||
out.erase("dischargedBy");
|
||||
} else {
|
||||
discharged = true;
|
||||
const Json& lenses = Dyn::Get(*d, "lenses");
|
||||
if (Dyn::Truthy(lenses) && !Dyn::In(Json(lensFile), Dyn::At(*d, "lenses"))) {
|
||||
cross.push_back({{"id", Dyn::At(*d, "id")}, {"lens", lensFile}, {"dispositionLenses", Dyn::At(*d, "lenses")}});
|
||||
}
|
||||
}
|
||||
}
|
||||
const Json& c = Dyn::Get(f, "contests");
|
||||
if (Dyn::Truthy(c) && Dyn::Truthy(Dyn::Get(c, "id"))) {
|
||||
const Json* d = disposition(Dyn::At(c, "id"));
|
||||
if (!d || !Dyn::Truthy(*d)) {
|
||||
logs.push_back(std::format("{}: contests id={} names no disposition in force - ignored", lensFile, Dyn::Str(Dyn::At(c, "id"))));
|
||||
out.erase("contests");
|
||||
} else if (Settled(hash, *d)) {
|
||||
discharged = true;
|
||||
out["dischargedBy"] = Dyn::At(*d, "id");
|
||||
contests.push_back({{"id", Dyn::At(*d, "id")}, {"lens", lensFile}, {"why", Dyn::Get(c, "why")},
|
||||
{"outcome", "recorded - entry already reaffirmed/contest-rejected on this binding; finding discharged (owner outranks lens; see Gate 4)"}});
|
||||
} else {
|
||||
discharged = false;
|
||||
out.erase("dischargedBy");
|
||||
contests.push_back({{"id", Dyn::At(*d, "id")}, {"lens", lensFile}, {"why", Dyn::Get(c, "why")},
|
||||
{"outcome", "DISPOSITION CONTESTED - blocks until the contest is verified and the entry reaffirmed, rejected, withdrawn or converted"}});
|
||||
}
|
||||
}
|
||||
out["discharged"] = discharged;
|
||||
findings.push_back(std::move(out));
|
||||
}
|
||||
|
||||
Json coverage;
|
||||
Json missing = Json::array();
|
||||
if (!inventory.is_null()) {
|
||||
std::vector<std::string> ids;
|
||||
for (const Json& unit : inventory) ids.push_back(Dyn::At(unit, "id").get<std::string>());
|
||||
const std::span<const std::string> universe = allIds.empty() ? std::span<const std::string>(ids) : allIds;
|
||||
auto resolveItems = [&](Json& holder) {
|
||||
if (!Dyn::Get(holder, "items").is_array()) return;
|
||||
Json resolved = Json::array();
|
||||
for (const Json& item : holder["items"]) resolved.push_back(ResolveId(item, universe));
|
||||
holder["items"] = std::move(resolved);
|
||||
};
|
||||
for (Json& f : findings) resolveItems(f);
|
||||
// v.get('notes') or []: the notes of the output itself, resolved in
|
||||
// place.
|
||||
Json noNotes = Json::array();
|
||||
Json& notes = Dyn::Truthy(Dyn::Get(v, "notes")) ? v["notes"] : noNotes;
|
||||
for (Json& n : notes) {
|
||||
if (!n.is_object()) throw Dyn::Error("AttributeError", std::format("'{}' object has no attribute 'get'", Dyn::TypeName(n)));
|
||||
resolveItems(n);
|
||||
}
|
||||
OrderedMap byItem;
|
||||
for (const Json& entry : Dyn::Or(Dyn::Get(v, "coverage"), Dyn::EmptyList())) {
|
||||
if (!Dyn::Truthy(entry) || !Dyn::Truthy(Dyn::Get(entry, "item"))) continue;
|
||||
const Json cid = ResolveId(Dyn::At(entry, "item"), universe);
|
||||
if (!byItem.Find(cid)) {
|
||||
Json copy = entry;
|
||||
copy["item"] = cid;
|
||||
byItem.Set(cid, std::move(copy));
|
||||
}
|
||||
}
|
||||
std::vector<Json> unknown;
|
||||
for (const auto& [key, value] : byItem.items) {
|
||||
if (!key.is_string() || !std::ranges::contains(ids, key.get_ref<const std::string&>())) unknown.push_back(key);
|
||||
}
|
||||
if (!unknown.empty()) {
|
||||
const std::span<const Json> shown(unknown.data(), std::min<std::size_t>(unknown.size(), 5));
|
||||
logs.push_back(std::format("{}: coverage names {} id(s) outside this pass's units ({}) - ignored", lensFile, unknown.size(), JoinStrings(shown, ", ")));
|
||||
}
|
||||
for (const std::string& id : ids) {
|
||||
if (!byItem.Find(Json(id))) missing.push_back(id);
|
||||
}
|
||||
std::set<std::string> cited;
|
||||
for (const Json& f : findings) {
|
||||
for (const Json& item : Dyn::Or(Dyn::Get(f, "items"), Dyn::EmptyList())) cited.insert(KeyOf(item));
|
||||
}
|
||||
std::set<std::string> noted;
|
||||
for (const Json& n : notes) {
|
||||
for (const Json& item : Dyn::Or(Dyn::Get(n, "items"), Dyn::EmptyList())) noted.insert(KeyOf(item));
|
||||
}
|
||||
const std::string vocabulary = Dyn::Join(std::vector<std::string>(Schema::CoverageVerdicts.begin(), Schema::CoverageVerdicts.end()), "/");
|
||||
for (const std::string& id : ids) {
|
||||
const Json* c = byItem.Find(Json(id));
|
||||
if (!c || !Dyn::Truthy(*c)) continue;
|
||||
const Json& verdict = Dyn::At(*c, "verdict");
|
||||
const std::string key = KeyOf(Json(id));
|
||||
if (!InVocabulary(verdict, Schema::CoverageVerdicts)) {
|
||||
logs.push_back(std::format("{}: coverage verdict \"{}\" on {} is not in the vocabulary ({}) - kept as given", lensFile, Dyn::Str(verdict), id, vocabulary));
|
||||
}
|
||||
if (verdict == "immaterial" && !noted.contains(key)) {
|
||||
logs.push_back(std::format("{}: immaterial on {} with no note citing it (items:[]) - the reason is not on record", lensFile, id));
|
||||
}
|
||||
if (InVocabulary(verdict, Schema::CoverageBlocking) && !cited.contains(key)) {
|
||||
findings.push_back({
|
||||
{"finding", std::format("coverage: verdict {} on unit {} with no finding written for it (basis: {})", Dyn::Str(verdict), id, Dyn::Str(Dyn::Get(*c, "basis")))},
|
||||
{"evidence", std::format("coverage entry for {}", id)},
|
||||
{"proposedAction", "the lens marked this unit defective and did not write the finding - write it or re-run"},
|
||||
{"items", {id}},
|
||||
{"discharged", false},
|
||||
{"synthesized", true},
|
||||
});
|
||||
logs.push_back(std::format("{}: {} on {} with no finding - synthesized an undischarged finding (fail closed)", lensFile, Dyn::Str(verdict), id));
|
||||
}
|
||||
}
|
||||
coverage = Json::array();
|
||||
const Json empty = "";
|
||||
for (const std::string& id : ids) {
|
||||
const Json* c = byItem.Find(Json(id));
|
||||
if (!c) {
|
||||
coverage.push_back({{"item", id}, {"verdict", "MISSING"}, {"basis", ""}});
|
||||
} else {
|
||||
coverage.push_back({{"item", Dyn::At(*c, "item")}, {"verdict", Dyn::At(*c, "verdict")}, {"basis", GetOr(*c, "basis", empty)}});
|
||||
}
|
||||
}
|
||||
if (!missing.empty()) {
|
||||
const std::span<const Json> shown(&*missing.begin(), std::min<std::size_t>(missing.size(), 8));
|
||||
violations.push_back({{"lens", lensFile}, {"kind", std::format("coverage incomplete: {} of {} units unaddressed ({}{}) - lens treated as NOT RETURNED", missing.size(),
|
||||
ids.size(), JoinStrings(shown, ", "), missing.size() > 8 ? ", ..." : "")}});
|
||||
}
|
||||
}
|
||||
const auto undischarged = std::ranges::count_if(findings, [](const Json& f) { return !Dyn::Truthy(Dyn::At(f, "discharged")); });
|
||||
const std::string derived = undischarged ? "FIX FIRST" : "SEND-READY";
|
||||
const Json& declared = Dyn::Get(v, "verdict");
|
||||
if (Dyn::Truthy(declared) && declared != derived) {
|
||||
if (declared == "SEND-READY") {
|
||||
violations.push_back({{"lens", lensFile}, {"declared", declared}, {"derived", derived},
|
||||
{"kind", "SEND-READY declared over undischarged finding(s) - failed closed to FIX FIRST"}});
|
||||
} else {
|
||||
violations.push_back({{"lens", lensFile}, {"declared", declared}, {"derived", derived},
|
||||
{"kind", "FIX FIRST declared with every finding discharged and no blocking contest (silent veto) - derived pass stands"}});
|
||||
}
|
||||
}
|
||||
return {
|
||||
{"verdict", derived},
|
||||
{"declaredVerdict", declared},
|
||||
{"findings", std::move(findings)},
|
||||
{"notes", Dyn::Or(Dyn::Get(v, "notes"), Dyn::EmptyList())},
|
||||
{"coverage", std::move(coverage)},
|
||||
{"coverageMissing", std::move(missing)},
|
||||
{"undischarged", undischarged},
|
||||
{"contests", std::move(contests)},
|
||||
{"contractViolations", std::move(violations)},
|
||||
{"crossLensDischarges", std::move(cross)},
|
||||
{"normalizeLogs", std::move(logs)},
|
||||
{"summary", Dyn::Get(v, "summary")},
|
||||
};
|
||||
}
|
||||
|
||||
std::vector<Json> Dedupe(std::span<const Json> items) {
|
||||
std::set<std::string> seen;
|
||||
std::vector<Json> out;
|
||||
for (const Json& item : items) {
|
||||
if (seen.insert(DumpCompactSorted(item)).second) out.push_back(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Json MergeParts(std::string_view lens, std::string_view lensFile, std::span<const Json> parts, std::span<const std::string> missingUnits,
|
||||
const Json& stoppedEarly) {
|
||||
// De-duplicated: a reused part carries the notes and findings its
|
||||
// unit-state entry stored, and a note citing two units is stored under
|
||||
// both keys - concatenating the parts doubled it every round
|
||||
// (2026-10-11).
|
||||
std::vector<Json> allFindings;
|
||||
std::vector<Json> allNotes;
|
||||
for (const Json& part : parts) {
|
||||
for (const Json& f : GetOr(part, "findings", Dyn::EmptyList())) allFindings.push_back(f);
|
||||
for (const Json& n : GetOr(part, "notes", Dyn::EmptyList())) allNotes.push_back(n);
|
||||
}
|
||||
const std::vector<Json> findings = Dedupe(allFindings);
|
||||
const std::vector<Json> notes = Dedupe(allNotes);
|
||||
const auto undischarged = std::ranges::count_if(findings, [](const Json& f) { return !Dyn::Truthy(Dyn::Get(f, "discharged")); });
|
||||
auto rank = [](const Json& verdict) {
|
||||
if (InVocabulary(verdict, Schema::CoverageBlocking)) return 2;
|
||||
return verdict == "immaterial" ? 1 : 0;
|
||||
};
|
||||
OrderedMap merged;
|
||||
for (const Json& part : parts) {
|
||||
for (const Json& c : Dyn::Or(Dyn::Get(part, "coverage"), Dyn::EmptyList())) {
|
||||
const Json& item = Dyn::At(c, "item");
|
||||
const Json* previous = merged.Find(item);
|
||||
if (!previous || !Dyn::Truthy(*previous) || rank(Dyn::At(c, "verdict")) >= rank(Dyn::At(*previous, "verdict"))) merged.Set(item, c);
|
||||
}
|
||||
}
|
||||
Json crossLogs = Json::array();
|
||||
for (const Json& f : findings) {
|
||||
if (Dyn::Truthy(Dyn::Get(f, "discharged"))) continue;
|
||||
for (const Json& item : Dyn::Or(Dyn::Get(f, "items"), Dyn::EmptyList())) {
|
||||
const Json* entry = merged.Find(item);
|
||||
if (entry && !InVocabulary(Dyn::At(*entry, "verdict"), Schema::CoverageBlocking)) {
|
||||
const Json& finding = Dyn::Get(f, "finding");
|
||||
const std::string cited = Dyn::Truthy(finding) ? Dyn::Slice(finding.get<std::string>(), 0, 80) : std::string();
|
||||
const std::string was = Dyn::Str(Dyn::At(*entry, "verdict"));
|
||||
merged.Set(item, {{"item", item}, {"verdict", "defect"}, {"basis", std::format("cited by finding: {}", cited)}});
|
||||
crossLogs.push_back(std::format("{}: {} raised to defect - cited by an undischarged finding while its own entry was {}", lens, Dyn::Str(item), was));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Deduplicated, in the order of first appearance.
|
||||
Json missing = Json::array();
|
||||
std::set<std::string> seenMissing;
|
||||
auto addMissing = [&](const Json& id) {
|
||||
if (seenMissing.insert(KeyOf(id)).second) missing.push_back(id);
|
||||
};
|
||||
for (const Json& part : parts) {
|
||||
for (const Json& id : GetOr(part, "coverageMissing", Dyn::EmptyList())) addMissing(id);
|
||||
}
|
||||
for (const std::string& id : missingUnits) addMissing(Json(id));
|
||||
Json violations = Json::array();
|
||||
for (const Json& part : parts) {
|
||||
for (const Json& violation : GetOr(part, "contractViolations", Dyn::EmptyList())) violations.push_back(violation);
|
||||
}
|
||||
if (!missingUnits.empty()) {
|
||||
const std::span<const std::string> shown = missingUnits.first(std::min<std::size_t>(missingUnits.size(), 8));
|
||||
violations.push_back({{"lens", lensFile}, {"kind", std::format("process(es) did not return for unit(s) {}{} - lens treated as NOT RETURNED", Dyn::Join(shown, ", "),
|
||||
missingUnits.size() > 8 ? ", ..." : "")}});
|
||||
}
|
||||
Json contests = Json::array();
|
||||
Json crossDischarges = Json::array();
|
||||
Json normalizeLogs = Json::array();
|
||||
Json partRows = Json::array();
|
||||
Json summary;
|
||||
for (const Json& part : parts) {
|
||||
for (const Json& c : GetOr(part, "contests", Dyn::EmptyList())) contests.push_back(c);
|
||||
for (const Json& c : GetOr(part, "crossLensDischarges", Dyn::EmptyList())) crossDischarges.push_back(c);
|
||||
for (const Json& l : GetOr(part, "normalizeLogs", Dyn::EmptyList())) normalizeLogs.push_back(l);
|
||||
const Json ok = "ok";
|
||||
partRows.push_back({
|
||||
{"label", Dyn::Get(part, "partLabel")},
|
||||
{"kind", Dyn::Get(part, "partKind")},
|
||||
{"unit", Dyn::Get(part, "partUnit")},
|
||||
{"verdict", Dyn::Get(part, "verdict")},
|
||||
{"findings", GetOr(part, "findings", Dyn::EmptyList()).size()},
|
||||
{"status", GetOr(part, "status", ok)},
|
||||
{"reused", Dyn::Get(part, "reused")},
|
||||
{"turns", Dyn::Get(part, "turns")},
|
||||
{"usage", Dyn::Get(part, "usage")},
|
||||
});
|
||||
if (summary.is_null() && Dyn::Truthy(Dyn::Get(part, "summary"))) summary = Dyn::At(part, "summary");
|
||||
}
|
||||
for (const Json& l : crossLogs) normalizeLogs.push_back(l);
|
||||
Json coverage = Json::array();
|
||||
for (const auto& [key, value] : merged.items) coverage.push_back(value);
|
||||
// A lens with unaddressed units is NOT RETURNED (never a pass); real
|
||||
// undischarged findings still read FIX FIRST.
|
||||
const std::string verdict = undischarged ? "FIX FIRST" : (missing.empty() ? "SEND-READY" : "NOT RETURNED");
|
||||
return {
|
||||
{"lens", lens},
|
||||
{"lensFile", lensFile},
|
||||
{"verdict", verdict},
|
||||
{"findings", findings},
|
||||
{"notes", notes},
|
||||
{"coverage", std::move(coverage)},
|
||||
{"coverageMissing", std::move(missing)},
|
||||
{"undischarged", undischarged},
|
||||
{"contests", std::move(contests)},
|
||||
{"contractViolations", std::move(violations)},
|
||||
{"crossLensDischarges", std::move(crossDischarges)},
|
||||
{"normalizeLogs", std::move(normalizeLogs)},
|
||||
{"parts", std::move(partRows)},
|
||||
{"summary", std::move(summary)},
|
||||
{"stoppedEarly", stoppedEarly},
|
||||
};
|
||||
}
|
||||
|
||||
Json Matrix(const Json& inventory, std::span<const Json> results, std::span<const std::string> notReviewed) {
|
||||
auto owned = [](const Json& entry) { return !InVocabulary(Dyn::At(entry, "verdict"), Schema::CoverageUnowned); };
|
||||
Json columns = Json::array();
|
||||
for (const Json& result : results) {
|
||||
if (Dyn::Get(result, "coverage").is_array()) columns.push_back(Dyn::At(result, "lens"));
|
||||
}
|
||||
Json mx = Json::object();
|
||||
const Json empty = "";
|
||||
for (const Json& unit : inventory) {
|
||||
const std::string id = Dyn::At(unit, "id").get<std::string>();
|
||||
Json row = Json::object();
|
||||
for (const Json& result : results) {
|
||||
if (!Dyn::Get(result, "coverage").is_array()) continue;
|
||||
const Json* entry = nullptr;
|
||||
for (const Json& x : Dyn::At(result, "coverage")) {
|
||||
if (Dyn::Equal(Dyn::At(x, "item"), Json(id))) {
|
||||
entry = &x;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const std::string lens = Dyn::At(result, "lens").get<std::string>();
|
||||
row[lens] = entry ? Json{{"verdict", Dyn::At(*entry, "verdict")}, {"basis", GetOr(*entry, "basis", empty)}} : Json{{"verdict", "MISSING"}, {"basis", ""}};
|
||||
}
|
||||
mx[id] = std::move(row);
|
||||
}
|
||||
const std::set<std::string> excused(notReviewed.begin(), notReviewed.end());
|
||||
Json holes = Json::array();
|
||||
for (const Json& unit : inventory) {
|
||||
const std::string id = Dyn::At(unit, "id").get<std::string>();
|
||||
if (excused.contains(id)) continue;
|
||||
const Json& row = mx[id];
|
||||
if (!std::ranges::any_of(row, owned)) holes.push_back(id);
|
||||
}
|
||||
Json defects = Json::object();
|
||||
for (const Json& unit : inventory) {
|
||||
const std::string id = Dyn::At(unit, "id").get<std::string>();
|
||||
Json lenses = Json::array();
|
||||
const Json& row = mx[id];
|
||||
for (auto it = row.begin(); it != row.end(); ++it) {
|
||||
if (InVocabulary(Dyn::At(it.value(), "verdict"), Schema::CoverageBlocking)) lenses.push_back(it.key());
|
||||
}
|
||||
if (!lenses.empty()) defects[id] = std::move(lenses);
|
||||
}
|
||||
Json sortedExcused = Json::array();
|
||||
for (const std::string& id : excused) sortedExcused.push_back(id);
|
||||
return {
|
||||
{"units", inventory.size()},
|
||||
{"lenses", std::move(columns)},
|
||||
{"holes", std::move(holes)},
|
||||
{"notReviewed", std::move(sortedExcused)},
|
||||
{"defects", std::move(defects)},
|
||||
{"matrix", std::move(mx)},
|
||||
};
|
||||
}
|
||||
}
|
||||
60
implementations/Crafter.Review-PgWire.cpp
Normal file
60
implementations/Crafter.Review-PgWire.cpp
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:PgWire_impl;
|
||||
import :PgWire;
|
||||
import :Json;
|
||||
import :Text;
|
||||
import std;
|
||||
|
||||
namespace Crafter::Review::PgWire {
|
||||
Url ParseUrl(std::string_view text) {
|
||||
const Dyn::SplitUrl split = Dyn::UrlSplit(text);
|
||||
Url url;
|
||||
url.scheme = split.scheme;
|
||||
url.host = Dyn::Lower(split.Hostname().value_or(""));
|
||||
const std::optional<std::int32_t> port = split.Port();
|
||||
url.port = port && *port != 0 ? *port : 5432;
|
||||
const std::optional<std::string> user = split.Username();
|
||||
url.user = Dyn::Unquote(user && !user->empty() ? *user : "postgres");
|
||||
url.password = Dyn::Unquote(split.Password().value_or(""));
|
||||
const std::string path = split.path.empty() ? "/" : split.path;
|
||||
const std::string database = Dyn::LStrip(path, "/");
|
||||
url.database = Dyn::Unquote(database.empty() ? "postgres" : database);
|
||||
return url;
|
||||
}
|
||||
|
||||
std::optional<std::string> CheckUrl(const Json& url) {
|
||||
if (!url.is_string() || url.get_ref<const std::string&>().empty()) return "no database URL";
|
||||
Url parsed;
|
||||
try {
|
||||
parsed = ParseUrl(url.get_ref<const std::string&>());
|
||||
} catch (const std::invalid_argument& error) {
|
||||
return std::format("not a URL ({})", error.what());
|
||||
}
|
||||
if (parsed.scheme != "postgres" && parsed.scheme != "postgresql") return "not a postgres:// or postgresql:// URL";
|
||||
if (!std::ranges::contains(Loopback, parsed.host)) {
|
||||
const std::vector<std::string> names(Loopback.begin(), Loopback.end());
|
||||
return std::format("host {} is not this machine ({}): the database under test is a local stack, never a hosted one",
|
||||
parsed.host.empty() ? "(none)" : parsed.host, Dyn::Join(names, ", "));
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::string Redact(std::string_view url) {
|
||||
try {
|
||||
const Dyn::SplitUrl split = Dyn::UrlSplit(url);
|
||||
if (!split.Password()) return std::string(url);
|
||||
const std::string host = split.netloc.substr(split.netloc.rfind('@') + 1);
|
||||
const std::string netloc = std::format("{}:***@{}", split.Username().value_or(""), host);
|
||||
return Dyn::UrlUnsplit(split.scheme, netloc, split.path, split.query, split.fragment);
|
||||
} catch (const std::invalid_argument&) {
|
||||
return "(unparsable URL)";
|
||||
}
|
||||
}
|
||||
|
||||
std::string Where(std::string_view url) {
|
||||
const Url parsed = ParseUrl(url);
|
||||
return std::format("{} on {}:{} as {}", parsed.database, parsed.host, parsed.port, parsed.user);
|
||||
}
|
||||
}
|
||||
680
implementations/Crafter.Review-Plan.cpp
Normal file
680
implementations/Crafter.Review-Plan.cpp
Normal file
|
|
@ -0,0 +1,680 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Plan_impl;
|
||||
import :Plan;
|
||||
import :Json;
|
||||
import :Text;
|
||||
import :Crypto;
|
||||
import std;
|
||||
|
||||
namespace Crafter::Review::Plan {
|
||||
namespace {
|
||||
// The bytes of `p\d+:` at the start of a unit id, where \d is any
|
||||
// Unicode decimal digit, as re.match reads it.
|
||||
std::optional<std::size_t> PkPrefix(std::string_view id) {
|
||||
if (!id.starts_with('p')) return std::nullopt;
|
||||
const std::size_t digits = Dyn::DecimalRun(id, 1);
|
||||
if (digits == 0 || 1 + digits >= id.size() || id[1 + digits] != ':') return std::nullopt;
|
||||
return 2 + digits;
|
||||
}
|
||||
|
||||
// group(1) of ^p\d+:(.+)#[^#]+$: the path between the prefix and the
|
||||
// last '#', which must have something after it. `.` stops at a
|
||||
// newline; [^#] does not.
|
||||
std::optional<std::string_view> FileOfUnit(std::string_view id) {
|
||||
const std::optional<std::size_t> prefix = PkPrefix(id);
|
||||
if (!prefix) return std::nullopt;
|
||||
const std::string_view rest = id.substr(*prefix);
|
||||
const std::size_t hash = rest.rfind('#');
|
||||
if (hash == std::string_view::npos || hash == 0 || hash + 1 >= rest.size()) return std::nullopt;
|
||||
const std::string_view path = rest.substr(0, hash);
|
||||
if (path.contains('\n')) return std::nullopt;
|
||||
return path;
|
||||
}
|
||||
|
||||
bool IsHex(std::string_view text) {
|
||||
return !text.empty() && std::ranges::all_of(text, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); });
|
||||
}
|
||||
|
||||
// ^\d+\.\d+
|
||||
bool StartsWithVersion(std::string_view line) {
|
||||
const std::size_t major = Dyn::DecimalRun(line, 0);
|
||||
if (major == 0 || major >= line.size() || line[major] != '.') return false;
|
||||
return Dyn::DecimalRun(line, major + 1) > 0;
|
||||
}
|
||||
|
||||
// ^(base-commit|prerequisite-patch-id): [0-9a-f]+$
|
||||
bool IsTailLine(std::string_view line) {
|
||||
for (const std::string_view head : {std::string_view("base-commit: "), std::string_view("prerequisite-patch-id: ")}) {
|
||||
if (line.starts_with(head) && IsHex(line.substr(head.size()))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ^index [0-9a-f]+\.\.[0-9a-f]+( \d+)?$ -> group(1) ("" when absent)
|
||||
std::optional<std::string_view> IndexMode(std::string_view line) {
|
||||
if (!line.starts_with("index ")) return std::nullopt;
|
||||
const std::string_view rest = line.substr(6);
|
||||
const std::size_t dots = rest.find("..");
|
||||
if (dots == std::string_view::npos || !IsHex(rest.substr(0, dots))) return std::nullopt;
|
||||
const std::string_view after = rest.substr(dots + 2);
|
||||
const std::size_t space = after.find(' ');
|
||||
if (space == std::string_view::npos) {
|
||||
if (!IsHex(after)) return std::nullopt;
|
||||
return std::string_view();
|
||||
}
|
||||
if (!IsHex(after.substr(0, space))) return std::nullopt;
|
||||
const std::string_view mode = after.substr(space);
|
||||
if (mode.size() < 2 || Dyn::DecimalRun(mode, 1) != mode.size() - 1) return std::nullopt;
|
||||
return mode;
|
||||
}
|
||||
|
||||
// \d+(?:,\d+)? at `at`: the bytes it takes, 0 for no match.
|
||||
std::size_t LineRange(std::string_view text, std::size_t at) {
|
||||
const std::size_t start = Dyn::DecimalRun(text, at);
|
||||
if (start == 0) return 0;
|
||||
std::size_t end = at + start;
|
||||
if (end < text.size() && text[end] == ',') {
|
||||
const std::size_t count = Dyn::DecimalRun(text, end + 1);
|
||||
if (count > 0) end += 1 + count;
|
||||
}
|
||||
return end - at;
|
||||
}
|
||||
|
||||
// ^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@(.*)$ -> group(1)
|
||||
std::optional<std::string_view> HunkTail(std::string_view line) {
|
||||
if (!line.starts_with("@@ -")) return std::nullopt;
|
||||
std::size_t at = 4;
|
||||
const std::size_t old = LineRange(line, at);
|
||||
if (old == 0) return std::nullopt;
|
||||
at += old;
|
||||
if (!line.substr(at).starts_with(" +")) return std::nullopt;
|
||||
at += 2;
|
||||
const std::size_t now = LineRange(line, at);
|
||||
if (now == 0) return std::nullopt;
|
||||
at += now;
|
||||
if (!line.substr(at).starts_with(" @@")) return std::nullopt;
|
||||
return line.substr(at + 3);
|
||||
}
|
||||
|
||||
// Every line start that `head` follows: where the text is cut.
|
||||
// Position 0 is one when the text starts with it, which makes the
|
||||
// first piece empty.
|
||||
std::vector<std::string> SplitBeforeLines(std::string_view text, std::string_view head) {
|
||||
std::vector<std::size_t> cuts;
|
||||
for (std::size_t at = 0; at <= text.size();) {
|
||||
if (text.substr(at).starts_with(head)) cuts.push_back(at);
|
||||
const std::size_t newline = text.find('\n', at);
|
||||
if (newline == std::string_view::npos) break;
|
||||
at = newline + 1;
|
||||
}
|
||||
std::vector<std::string> pieces;
|
||||
std::size_t from = 0;
|
||||
for (const std::size_t cut : cuts) {
|
||||
pieces.emplace_back(text.substr(from, cut - from));
|
||||
from = cut;
|
||||
}
|
||||
pieces.emplace_back(text.substr(from));
|
||||
return pieces;
|
||||
}
|
||||
|
||||
// re.sub(r'^Subject: (\[[^\]]*\]\s*)*', 'Subject: ', line): the
|
||||
// `[PATCH n/m]` tags after `Subject: ` dropped, and the space after
|
||||
// each.
|
||||
std::string StripSubjectTags(std::string_view line) {
|
||||
if (!line.starts_with("Subject: ")) return std::string(line);
|
||||
std::size_t at = 9;
|
||||
while (at < line.size() && line[at] == '[') {
|
||||
const std::size_t close = line.find(']', at + 1);
|
||||
if (close == std::string_view::npos) break;
|
||||
at = close + 1;
|
||||
at += Dyn::SpaceRun(line, at);
|
||||
}
|
||||
return std::format("Subject: {}", line.substr(at));
|
||||
}
|
||||
|
||||
// ^base-commit: [0-9a-f]{40}$
|
||||
bool IsBaseCommit(std::string_view line) {
|
||||
constexpr std::string_view Head = "base-commit: ";
|
||||
return line.size() == Head.size() + 40 && line.starts_with(Head) && IsHex(line.substr(Head.size()));
|
||||
}
|
||||
|
||||
std::int64_t IntItem(const Json& range, std::size_t index) {
|
||||
const Json& value = range.at(index);
|
||||
if (value.is_boolean()) return value.get<bool>() ? 1 : 0;
|
||||
return value.get<std::int64_t>();
|
||||
}
|
||||
|
||||
Json Mechanical(std::string_view name, std::string_view lensFile, const Json& unit, std::string_view text, std::string_view basis) {
|
||||
const std::string id = Dyn::At(unit, "id").get<std::string>();
|
||||
return {
|
||||
{"label", std::format("{}:na:{}", name, id)},
|
||||
{"lens", name},
|
||||
{"lensFile", lensFile},
|
||||
{"kind", "auto-na"},
|
||||
{"unit", id},
|
||||
{"expectedIds", {id}},
|
||||
{"unitSha", Sha(text)},
|
||||
{"basis", basis},
|
||||
};
|
||||
}
|
||||
|
||||
bool Contains(std::span<const std::string> list, std::string_view item) {
|
||||
return std::ranges::contains(list, item);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<ModelTier>& Models() {
|
||||
static std::vector<ModelTier> models = {{"opus", "claude-opus-5-5"}, {"fable", "claude-opus-5-5"}};
|
||||
return models;
|
||||
}
|
||||
|
||||
const std::string& ModelFor(std::string_view tier) {
|
||||
for (const ModelTier& model : Models()) {
|
||||
if (model.tier == tier) return model.id;
|
||||
}
|
||||
throw Dyn::Error("KeyError", Dyn::Repr(tier));
|
||||
}
|
||||
|
||||
bool IsLens(std::string_view file) {
|
||||
return std::ranges::any_of(Lenses, [&](const Lens& lens) { return lens.file == file; });
|
||||
}
|
||||
|
||||
const Lens& LensOf(std::string_view file) {
|
||||
for (const Lens& lens : Lenses) {
|
||||
if (lens.file == file) return lens;
|
||||
}
|
||||
throw Dyn::Error("KeyError", Dyn::Repr(file));
|
||||
}
|
||||
|
||||
const std::vector<Gate>& Gates() {
|
||||
static const std::vector<Gate> gates = {
|
||||
{"Gate 1 — Approach", {"repo-better-solution.md"}},
|
||||
{"Gate 2 — Functional", {FunctionalLens}},
|
||||
{"Gate 3 — Proof", {"repo-bug-prover.md", "repo-security.md"}},
|
||||
};
|
||||
return gates;
|
||||
}
|
||||
|
||||
const Environment* FindEnvironment(std::string_view name) {
|
||||
for (const Environment& environment : Environments) {
|
||||
if (environment.name == name) return &environment;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<std::string> EnvDeps(std::string_view lensFile, std::string_view environment) {
|
||||
const std::string_view fallback = LensOf(lensFile).env;
|
||||
const std::string_view used = environment.empty() ? fallback : environment;
|
||||
if (used == fallback) return {};
|
||||
return {std::format("env={}", used)};
|
||||
}
|
||||
|
||||
Budget BudgetFor(std::string_view kind, std::string_view unitKind, std::string_view lensFile) {
|
||||
if (kind == "whole") return lensFile == FunctionalLens ? Budget{220, 120} : Budget{180, 105};
|
||||
if (unitKind != "code") throw Dyn::Error("KeyError", Dyn::Repr(std::format("block:{}", unitKind)));
|
||||
return lensFile == FunctionalLens ? Budget{90, 60} : Budget{60, 40};
|
||||
}
|
||||
|
||||
std::string_view DefaultEffort() {
|
||||
return Effort;
|
||||
}
|
||||
|
||||
std::string_view UnitKindOf(std::string_view unitId) {
|
||||
if (unitId.starts_with("whole:")) return "slot";
|
||||
const std::optional<std::size_t> prefix = PkPrefix(unitId);
|
||||
if (!prefix) return "text";
|
||||
// `$` also matches before a final newline.
|
||||
std::string_view name = unitId.substr(*prefix);
|
||||
if (name.ends_with('\n')) name.remove_suffix(1);
|
||||
if (name == "subject" || name == "msg" || name == "trailers" || name == "diffstat") return "text";
|
||||
return "code";
|
||||
}
|
||||
|
||||
std::string_view UnitKind(const Json& unit) {
|
||||
return UnitKindOf(Dyn::At(unit, "id").get_ref<const std::string&>());
|
||||
}
|
||||
|
||||
bool IsDocPath(std::string_view path) {
|
||||
auto endsWithMd = [](std::string_view text) {
|
||||
const std::u32string decoded = Dyn::Decode(text);
|
||||
if (decoded.size() < 3) return false;
|
||||
const std::size_t n = decoded.size();
|
||||
return decoded[n - 3] == '.' && Dyn::IgnoreCaseLetter(decoded[n - 2]) == 'm' && Dyn::IgnoreCaseLetter(decoded[n - 1]) == 'd';
|
||||
};
|
||||
return endsWithMd(path) || (path.ends_with('\n') && endsWithMd(path.substr(0, path.size() - 1)));
|
||||
}
|
||||
|
||||
bool IsDocUnit(std::string_view unitId) {
|
||||
const std::optional<std::string_view> path = FileOfUnit(unitId);
|
||||
return path && IsDocPath(*path);
|
||||
}
|
||||
|
||||
// The lens is not consulted (yet): no lens of this pipeline reads a
|
||||
// documentation file since the facts lens was removed.
|
||||
std::string_view KindFor(std::string_view, const Json& unit) {
|
||||
const std::string_view kind = UnitKind(unit);
|
||||
return kind == "code" && IsDocUnit(Dyn::At(unit, "id").get_ref<const std::string&>()) ? "doc" : kind;
|
||||
}
|
||||
|
||||
std::optional<std::string> UnitPath(std::string_view unitId) {
|
||||
const std::optional<std::string_view> path = FileOfUnit(unitId);
|
||||
if (!path) return std::nullopt;
|
||||
return std::string(*path);
|
||||
}
|
||||
|
||||
std::vector<std::string> NotReviewed(const Json& units, std::span<const std::string> lines, std::span<const std::string> lensFiles,
|
||||
std::span<const std::string> exclude) {
|
||||
std::set<std::string> covered;
|
||||
for (const std::string& lensFile : lensFiles) {
|
||||
const LensPlan plan = PlanLens(lensFile, units, lines, {}, exclude);
|
||||
if (Dyn::Truthy(plan.whole)) {
|
||||
for (const Json& id : Dyn::At(plan.whole, "expectedIds")) covered.insert(id.get<std::string>());
|
||||
}
|
||||
for (const Json& block : plan.blocks) {
|
||||
if (Dyn::At(block, "kind") != "auto-na") covered.insert(Dyn::At(block, "unit").get<std::string>());
|
||||
}
|
||||
}
|
||||
std::vector<std::string> out;
|
||||
for (const Json& unit : units) {
|
||||
const std::string& id = Dyn::At(unit, "id").get_ref<const std::string&>();
|
||||
if (!covered.contains(id)) out.push_back(id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<std::string> ExcludedBy(std::string_view path, std::span<const std::string> globs) {
|
||||
for (const std::string& glob : globs) {
|
||||
if (Dyn::FnMatch(path, glob) || (glob.starts_with("**/") && Dyn::FnMatch(path, std::string_view(glob).substr(3)))) return glob;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::string UnitText(std::span<const std::string> lines, const Json& unit) {
|
||||
const Json& range = Dyn::At(unit, "lines");
|
||||
const std::int64_t a = IntItem(range, 0);
|
||||
const std::int64_t b = IntItem(range, 1);
|
||||
if (a == 0) return "";
|
||||
const auto [from, to] = Dyn::SliceBounds(lines.size(), a - 1, b);
|
||||
return Dyn::Join(lines.subspan(from, to - from), "\n");
|
||||
}
|
||||
|
||||
std::string Sha(std::string_view text) {
|
||||
return Sha256Hex(text);
|
||||
}
|
||||
|
||||
std::string LensName(std::string_view lensFile) {
|
||||
return Dyn::Replace(lensFile, ".md", "");
|
||||
}
|
||||
|
||||
std::vector<std::string> ModeLenses() {
|
||||
std::vector<std::string> out;
|
||||
for (const Gate& gate : Gates()) {
|
||||
for (const std::string_view lens : gate.lenses) out.emplace_back(lens);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<Gate> GatesFor(std::span<const std::string> only, std::span<const std::string> without, std::span<const std::string> off) {
|
||||
std::vector<Gate> out;
|
||||
for (const Gate& gate : Gates()) {
|
||||
Gate kept{gate.title, {}};
|
||||
for (const std::string_view lens : gate.lenses) {
|
||||
if (!only.empty() && !Contains(only, lens)) continue;
|
||||
if (Contains(without, lens) || Contains(off, lens)) continue;
|
||||
kept.lenses.push_back(lens);
|
||||
}
|
||||
if (!kept.lenses.empty()) out.push_back(std::move(kept));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
LensPlan PlanLens(std::string_view lensFile, const Json& units, std::span<const std::string> lines, std::span<const std::string> unitsFilter,
|
||||
std::span<const std::string> exclude) {
|
||||
const Lens& lens = LensOf(lensFile);
|
||||
const std::string name = LensName(lensFile);
|
||||
LensPlan plan;
|
||||
if (!lens.whole.empty()) {
|
||||
const Budget budget = BudgetFor("whole", "", lensFile);
|
||||
Json slots = Json::array();
|
||||
for (const Json& unit : units) {
|
||||
const std::string& id = Dyn::At(unit, "id").get_ref<const std::string&>();
|
||||
if (UnitKind(unit) == "slot" && std::ranges::contains(lens.slots, std::string_view(id))) slots.push_back(id);
|
||||
}
|
||||
plan.whole = {
|
||||
{"label", std::format("{}:whole", name)},
|
||||
{"lens", name},
|
||||
{"lensFile", lensFile},
|
||||
{"kind", "whole"},
|
||||
{"unit", nullptr},
|
||||
{"expectedIds", slots},
|
||||
{"model", ModelFor(lens.model)},
|
||||
{"maxTurns", budget.maxTurns},
|
||||
{"timeoutMin", budget.timeoutMin},
|
||||
};
|
||||
}
|
||||
for (const Json& unit : units) {
|
||||
const std::string_view kind = KindFor(lensFile, unit);
|
||||
if (!std::ranges::contains(lens.block, kind)) continue;
|
||||
const std::string& id = Dyn::At(unit, "id").get_ref<const std::string&>();
|
||||
if (!unitsFilter.empty() && !Contains(unitsFilter, id)) continue;
|
||||
const std::string text = UnitText(lines, unit);
|
||||
const std::optional<std::string> path = UnitPath(id);
|
||||
if (!lens.perCommitSlots && (id.ends_with(":outside") || id.ends_with(":absent"))) {
|
||||
// The functional lens judges adjacent flows and what is missing
|
||||
// in its whole pass, not per commit.
|
||||
continue;
|
||||
}
|
||||
if (lensFile == FunctionalLens && path && id.ends_with("#hdr")) {
|
||||
plan.blocks.push_back(Mechanical(name, lensFile, unit, text,
|
||||
"mechanical: a diff header (mode, rename, new or deleted file) carries no behaviour of its own; the hunks of the file do"));
|
||||
continue;
|
||||
}
|
||||
if (lensFile == FunctionalLens && path) {
|
||||
if (const std::optional<std::string> glob = ExcludedBy(*path, exclude)) {
|
||||
plan.blocks.push_back(Mechanical(name, lensFile, unit, text,
|
||||
std::format("mechanical: no runtime behaviour - the file matches functional.exclude ({})", *glob)));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const Budget budget = BudgetFor("block", kind, lensFile);
|
||||
plan.blocks.push_back({
|
||||
{"label", std::format("{}:block:{}", name, id)},
|
||||
{"lens", name},
|
||||
{"lensFile", lensFile},
|
||||
{"kind", "block"},
|
||||
{"unit", id},
|
||||
{"unitKind", kind},
|
||||
{"expectedIds", {id}},
|
||||
{"unitSha", Sha(text)},
|
||||
{"model", ModelFor(lens.model)},
|
||||
{"maxTurns", budget.maxTurns},
|
||||
{"timeoutMin", budget.timeoutMin},
|
||||
});
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
std::optional<std::string> ReuseKey(const Json& job, std::string_view lensFile, std::string_view unitText, std::vector<std::string> deps,
|
||||
std::vector<std::string> inForceIds, std::string_view charterSha, std::int32_t promptVersion,
|
||||
std::string_view ident) {
|
||||
if (!LensOf(lensFile).reuse || Dyn::At(job, "kind") != "block") return std::nullopt;
|
||||
std::ranges::sort(deps);
|
||||
std::ranges::sort(inForceIds);
|
||||
const Json& model = Dyn::Get(job, "model");
|
||||
const std::vector<std::string> parts = {
|
||||
std::string(lensFile),
|
||||
ident.empty() ? Dyn::At(job, "unit").get<std::string>() : std::string(ident),
|
||||
Sha(unitText),
|
||||
Sha(Dyn::Join(deps, "\n")),
|
||||
Dyn::Join(inForceIds, ","),
|
||||
std::string(charterSha),
|
||||
std::to_string(promptVersion),
|
||||
Dyn::Has(job, "model") ? model.get<std::string>() : std::string(),
|
||||
std::string(ReuseKeyEffortSlot),
|
||||
};
|
||||
return Sha(Dyn::Join(parts, "|")).substr(0, 16);
|
||||
}
|
||||
|
||||
std::string CodeNorm(std::string_view text) {
|
||||
std::vector<std::string> lines = Dyn::Split(text, "\n");
|
||||
while (!lines.empty() && lines.back().empty()) lines.pop_back();
|
||||
if (lines.size() >= 2 && lines[lines.size() - 2] == "-- " && StartsWithVersion(lines.back())) {
|
||||
lines.resize(lines.size() - 2);
|
||||
while (!lines.empty() && (lines.back().empty() || IsTailLine(lines.back()))) lines.pop_back();
|
||||
}
|
||||
for (std::string& line : lines) {
|
||||
if (const std::optional<std::string_view> mode = IndexMode(line)) {
|
||||
line = std::format("index{}", *mode);
|
||||
} else if (const std::optional<std::string_view> tail = HunkTail(line)) {
|
||||
line = std::format("@@{}", *tail);
|
||||
}
|
||||
}
|
||||
return Dyn::Join(lines, "\n");
|
||||
}
|
||||
|
||||
PatchParts PartsOf(std::string_view patchText) {
|
||||
const std::vector<std::string> lines = Dyn::Split(patchText, "\n");
|
||||
std::optional<std::size_t> subject;
|
||||
for (std::size_t i = 0; i < lines.size(); ++i) {
|
||||
if (lines[i].starts_with("Subject:")) {
|
||||
subject = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::size_t body0 = 1;
|
||||
if (subject) {
|
||||
for (std::size_t i = *subject + 1; i < lines.size(); ++i) {
|
||||
if (Dyn::Strip(lines[i]).empty()) {
|
||||
body0 = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::size_t diff0 = lines.size();
|
||||
for (std::size_t i = body0; i < lines.size(); ++i) {
|
||||
if (lines[i].starts_with("---")) {
|
||||
diff0 = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::size_t first = lines.size();
|
||||
for (std::size_t i = diff0 + 1; i < lines.size(); ++i) {
|
||||
if (lines[i].starts_with("diff --git")) {
|
||||
first = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
PatchParts parts;
|
||||
for (const std::string& line : lines) {
|
||||
if (IsBaseCommit(line)) {
|
||||
parts.base = Dyn::Split(line)[1];
|
||||
break;
|
||||
}
|
||||
}
|
||||
const std::span<const std::string> code(lines.begin() + static_cast<std::ptrdiff_t>(std::min(first, lines.size())), lines.end());
|
||||
for (const std::string& section : SplitBeforeLines(CodeNorm(Dyn::Join(code, "\n")), "diff --git ")) {
|
||||
const std::string firstLine = Dyn::Split(section, "\n", 1)[0];
|
||||
const std::string path = Dyn::Strip(Dyn::Split(firstLine, " b/").back());
|
||||
if (section.starts_with("diff --git ") && IsDocPath(path)) {
|
||||
// re.split(r'(?m)^@@', section, maxsplit=1)[0].rstrip('\n')
|
||||
std::size_t header = section.size();
|
||||
for (std::size_t at = 0; at < section.size();) {
|
||||
if (std::string_view(section).substr(at).starts_with("@@")) {
|
||||
header = at;
|
||||
break;
|
||||
}
|
||||
const std::size_t newline = section.find('\n', at);
|
||||
if (newline == std::string::npos) break;
|
||||
at = newline + 1;
|
||||
}
|
||||
parts.docs.push_back(Dyn::RStrip(std::string_view(section).substr(0, header), "\n"));
|
||||
} else {
|
||||
parts.code += section;
|
||||
}
|
||||
}
|
||||
std::ranges::sort(parts.docs);
|
||||
const auto [messageFrom, messageTo] = Dyn::SliceBounds(lines.size(), static_cast<std::int64_t>(subject ? *subject : body0), static_cast<std::int64_t>(diff0));
|
||||
std::vector<std::string> message;
|
||||
for (std::size_t i = messageFrom; i < messageTo; ++i) message.push_back(StripSubjectTags(lines[i]));
|
||||
parts.message = Dyn::Join(message, "\n");
|
||||
const auto [bodyFrom, bodyTo] = Dyn::SliceBounds(lines.size(), static_cast<std::int64_t>(body0), static_cast<std::int64_t>(diff0));
|
||||
for (std::size_t i = bodyFrom; i < bodyTo; ++i) {
|
||||
if (!Dyn::Strip(lines[i]).empty()) {
|
||||
parts.hasBody = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
CommitCode CommitCodeOf(const std::map<std::int64_t, std::string>& patches) {
|
||||
CommitCode cc;
|
||||
std::set<std::string> bases;
|
||||
std::vector<std::string> codes;
|
||||
for (const auto& [k, text] : patches) {
|
||||
PatchParts parts = PartsOf(text);
|
||||
cc.body[k] = parts.hasBody;
|
||||
cc.code[k] = Sha(parts.code);
|
||||
cc.docs[k] = std::move(parts.docs);
|
||||
cc.message[k] = Sha(parts.message);
|
||||
if (!parts.base.empty()) bases.insert(parts.base);
|
||||
codes.push_back(cc.code[k]);
|
||||
cc.upto[k] = Sha(Dyn::Join(codes, "\n"));
|
||||
}
|
||||
cc.range = Sha(Dyn::Join(codes, "\n"));
|
||||
cc.base = Dyn::Join(std::vector<std::string>(bases.begin(), bases.end()), ",");
|
||||
return cc;
|
||||
}
|
||||
|
||||
std::pair<std::string, std::vector<std::string>> CodeKeyParts(std::string_view unitId, const CommitCode& cc) {
|
||||
const std::size_t colon = unitId.find(':');
|
||||
if (colon == std::string_view::npos) throw Dyn::Error("ValueError", "not enough values to unpack (expected 2, got 1)");
|
||||
const std::string_view pk = unitId.substr(0, colon);
|
||||
const std::string_view rest = unitId.substr(colon + 1);
|
||||
const std::string_view number = pk.empty() ? pk : pk.substr(1);
|
||||
const std::optional<std::int64_t> k = Dyn::ParseInt(number);
|
||||
if (!k) throw Dyn::Error("ValueError", Dyn::IntError(number));
|
||||
std::vector<std::string> deps = {std::format("base={}", cc.base)};
|
||||
if (rest == "outside" || rest == "absent") {
|
||||
const auto code = cc.code.find(*k);
|
||||
if (code == cc.code.end()) throw Dyn::Error("KeyError", std::to_string(*k));
|
||||
deps.push_back(std::format("commit={}:{}", *k, code->second));
|
||||
deps.push_back(std::format("range={}", cc.range));
|
||||
deps.push_back(std::format("docs={}", Dyn::Join(cc.docs.at(*k), "|")));
|
||||
if (rest == "absent") deps.push_back(std::format("body={}", cc.body.at(*k) ? "yes" : "no"));
|
||||
return {std::format("code:{}", rest), deps};
|
||||
}
|
||||
const std::size_t hash = rest.rfind('#');
|
||||
if (hash == std::string_view::npos) throw Dyn::Error("ValueError", "not enough values to unpack (expected 2, got 1)");
|
||||
const std::string_view tag = rest.substr(hash + 1);
|
||||
return {std::format("code:{}#{}", rest.substr(0, hash), tag == "hdr" ? "hdr" : "hunk"), deps};
|
||||
}
|
||||
|
||||
std::optional<std::string> CodeReuseKey(const Json& job, std::string_view lensFile, std::string_view unitText, const CommitCode& cc,
|
||||
std::span<const std::string> inForceIds, std::string_view charterSha, std::int32_t promptVersion,
|
||||
std::string_view environment) {
|
||||
auto [ident, deps] = CodeKeyParts(Dyn::At(job, "unit").get_ref<const std::string&>(), cc);
|
||||
std::ranges::move(EnvDeps(lensFile, environment), std::back_inserter(deps));
|
||||
return ReuseKey(job, lensFile, CodeNorm(unitText), deps, {inForceIds.begin(), inForceIds.end()}, charterSha, promptVersion, ident);
|
||||
}
|
||||
|
||||
std::optional<std::string> FunctionalReuseKey(const Json& job, std::string_view lensFile, std::string_view unitText, const CommitCode& cc,
|
||||
std::span<const std::string> inForceIds, std::string_view charterSha, std::int32_t promptVersion,
|
||||
std::string_view environment) {
|
||||
auto [ident, deps] = CodeKeyParts(Dyn::At(job, "unit").get_ref<const std::string&>(), cc);
|
||||
deps.push_back(std::format("range={}", cc.range));
|
||||
std::ranges::move(EnvDeps(lensFile, environment), std::back_inserter(deps));
|
||||
return ReuseKey(job, lensFile, CodeNorm(unitText), deps, {inForceIds.begin(), inForceIds.end()}, charterSha, promptVersion,
|
||||
std::format("functional:{}", ident));
|
||||
}
|
||||
|
||||
std::optional<std::string> BlockReuseKey(const Json& job, std::string_view lensFile, std::string_view unitText, const CommitCode& cc,
|
||||
std::span<const std::string> inForceIds, std::string_view charterSha, std::int32_t promptVersion,
|
||||
std::string_view environment) {
|
||||
if (LensOf(lensFile).key == "functional") {
|
||||
return FunctionalReuseKey(job, lensFile, unitText, cc, inForceIds, charterSha, promptVersion, environment);
|
||||
}
|
||||
return CodeReuseKey(job, lensFile, unitText, cc, inForceIds, charterSha, promptVersion, environment);
|
||||
}
|
||||
|
||||
std::optional<std::string> WholeCodeKey(const Json& job, std::string_view lensFile, const CommitCode& cc, std::span<const std::string> inForceIds,
|
||||
std::string_view charterSha, std::int32_t promptVersion, std::string_view environment) {
|
||||
if (!LensOf(lensFile).wholeReuse || Dyn::At(job, "kind") != "whole") return std::nullopt;
|
||||
std::string body;
|
||||
for (const auto& [k, has] : cc.body) {
|
||||
if (!body.empty()) body.push_back(',');
|
||||
body.push_back(has ? 'y' : 'n');
|
||||
}
|
||||
std::vector<std::string> docs;
|
||||
for (const auto& [k, files] : cc.docs) docs.push_back(Dyn::Join(files, "|"));
|
||||
std::vector<std::string> deps = {
|
||||
std::format("base={}", cc.base),
|
||||
std::format("range={}", cc.range),
|
||||
std::format("body={}", body),
|
||||
std::format("docs={}", Dyn::Join(docs, ";")),
|
||||
};
|
||||
std::ranges::move(EnvDeps(lensFile, environment), std::back_inserter(deps));
|
||||
std::vector<std::string> ids(inForceIds.begin(), inForceIds.end());
|
||||
std::ranges::sort(ids);
|
||||
const std::vector<std::string> parts = {
|
||||
std::string(lensFile),
|
||||
"code:whole",
|
||||
Sha(Dyn::Join(deps, "\n")),
|
||||
Dyn::Join(ids, ","),
|
||||
std::string(charterSha),
|
||||
std::to_string(promptVersion),
|
||||
Dyn::Has(job, "model") ? Dyn::Get(job, "model").get<std::string>() : std::string(),
|
||||
std::string(ReuseKeyEffortSlot),
|
||||
};
|
||||
return Sha(Dyn::Join(parts, "|")).substr(0, 16);
|
||||
}
|
||||
|
||||
std::int64_t ReadsOf(const Json& entry) {
|
||||
if (!Dyn::Truthy(entry)) return 0;
|
||||
const Json& reads = Dyn::Get(entry, "reads");
|
||||
if (!Dyn::Truthy(reads)) return 1;
|
||||
if (reads.is_string()) return static_cast<std::int64_t>(Dyn::Length(reads.get_ref<const std::string&>()));
|
||||
return static_cast<std::int64_t>(reads.size());
|
||||
}
|
||||
|
||||
bool ReadIn(const Json& entry, std::string_view hash8, std::int64_t round) {
|
||||
const Json& reads = Dyn::Or(Dyn::Get(entry, "reads"), Dyn::EmptyList());
|
||||
return std::ranges::any_of(reads, [&](const Json& read) {
|
||||
return Dyn::Equal(Dyn::Get(read, "hash"), Json(hash8)) && Dyn::Equal(Dyn::Get(read, "round"), Json(round));
|
||||
});
|
||||
}
|
||||
|
||||
Json Rebind(const Json& entry, std::string_view unitId) {
|
||||
Json out = entry;
|
||||
out["unit"] = unitId;
|
||||
Json coverage = Dyn::At(out, "coverage");
|
||||
if (!coverage.is_object()) throw Dyn::Error("TypeError", std::format("'{}' object is not iterable", Dyn::TypeName(coverage)));
|
||||
coverage["item"] = unitId;
|
||||
out["coverage"] = std::move(coverage);
|
||||
for (const std::string_view field : {std::string_view("findings"), std::string_view("notes")}) {
|
||||
if (!Dyn::Has(out, field)) continue;
|
||||
for (Json& item : out[std::string(field)]) {
|
||||
if (Dyn::Get(item, "items").is_array()) item["items"] = Json::array({unitId});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Json Estimate(std::span<const Json> jobs, std::int64_t prefixBytes, const std::map<std::string, std::int64_t>& lensLayerBytes,
|
||||
std::int64_t tailBytes, double tpb, std::int64_t sysTokens, std::int64_t outPerTurn) {
|
||||
const double prefix = static_cast<double>(prefixBytes) / tpb + static_cast<double>(sysTokens);
|
||||
double cacheRead = 0.0;
|
||||
double cacheWrite = 0.0;
|
||||
double output = 0.0;
|
||||
std::int64_t processes = 0;
|
||||
std::set<std::pair<std::string, std::string>> seen;
|
||||
for (const Json& job : jobs) {
|
||||
const std::string kind = Dyn::At(job, "kind").get<std::string>();
|
||||
if (kind == "auto-na") continue;
|
||||
const std::string lens = Dyn::At(job, "lens").get<std::string>();
|
||||
const auto layer = lensLayerBytes.find(lens);
|
||||
const double lensTokens = static_cast<double>(layer == lensLayerBytes.end() ? 3000 : layer->second) / tpb;
|
||||
const double tail = static_cast<double>(tailBytes) / tpb;
|
||||
const std::int64_t turns = kind == "whole" ? 40 : (Dyn::At(job, "lensFile") == FunctionalLens ? 25 : 10);
|
||||
if (seen.insert({lens, kind}).second) cacheWrite += prefix + lensTokens;
|
||||
cacheWrite += tail + static_cast<double>(turns * 3000);
|
||||
std::vector<double> reads;
|
||||
for (std::int64_t i = 0; i < turns; ++i) reads.push_back(prefix + lensTokens + tail + static_cast<double>(3000 * i));
|
||||
cacheRead += Dyn::Sum(reads);
|
||||
output += static_cast<double>(turns * outPerTurn);
|
||||
++processes;
|
||||
}
|
||||
const double costUnits = 1.25 * cacheWrite + 0.1 * cacheRead + 5.0 * output;
|
||||
const double listUsd = Dyn::Round((6.25 * cacheWrite + 0.5 * cacheRead + 25.0 * output) / 1e6, 2);
|
||||
return {
|
||||
{"cacheRead", cacheRead},
|
||||
{"cacheWrite", cacheWrite},
|
||||
{"output", output},
|
||||
{"processes", processes},
|
||||
{"costUnits", costUnits},
|
||||
{"listUsd", listUsd},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -193,7 +193,7 @@ namespace Crafter::Review::Platform {
|
|||
FileLock::FileLock(const fs::path& lockPath) {
|
||||
std::error_code error;
|
||||
if (lockPath.has_parent_path()) fs::create_directories(lockPath.parent_path(), error);
|
||||
fd = open(lockPath.c_str(), O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
|
||||
fd = open(lockPath.c_str(), O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0666);
|
||||
if (fd < 0) {
|
||||
problem = Dyn::ErrnoText(errno);
|
||||
return;
|
||||
|
|
|
|||
239
implementations/Crafter.Review-Prompt.cpp
Normal file
239
implementations/Crafter.Review-Prompt.cpp
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Prompt_impl;
|
||||
import :Prompt;
|
||||
import :Json;
|
||||
import :Text;
|
||||
import :Core;
|
||||
import :Plan;
|
||||
import :PgWire;
|
||||
import std;
|
||||
|
||||
namespace Crafter::Review::Prompt {
|
||||
const std::string_view GenericVocab =
|
||||
"Coverage vocabulary: clear (you checked this unit by your charter and found nothing - the basis says what you checked it against: the tree ref, the command run, the steps taken in the application and the evidence file), "
|
||||
"defect (a finding with items:[id] exists), immaterial (a note kind=immaterial with items:[id] exists), n/a (the unit carries nothing your charter judges - the basis says why). "
|
||||
"For the functional lens \"clear\" means the behaviour of the unit was exercised in the running application and observed as the code intends, never read as plausible; a unit with no reachable behaviour is n/a with the reason, and a behaviour you could not reach for a reason that is not by design is an `unverified` note with n/a, never clear.";
|
||||
|
||||
const std::string_view WholeFirstRepo =
|
||||
"SCOPE - WHOLE PASS, and it gates the block passes of this lens: judge the range as an APPROACH for THIS repository - is this the right solution at all (an existing mechanism in the repository or its platform, the right layer or component, the right commit shape, compatibility with what users already have installed)? "
|
||||
"Do not review individual hunks; per-block passes of this lens run only if you pass. Return `summary` (5-10 sentences: the approach as you judged it and the constraints the block passes must respect). Cover exactly the units listed below (the whole:* slots).";
|
||||
|
||||
const std::string_view WholeFunctional =
|
||||
"SCOPE - WHOLE PASS, and it gates the block passes of this lens: exercise the range as a USER of the running application named under APPLICATION UNDER TEST. From the code and the commit messages derive every behaviour the range adds, changes or removes and every flow it touches; "
|
||||
"reach each one in the browser, act, observe, and compare what you see with what the code says; then exercise one adjacent flow per shared component, store, RPC or function the range touches. A behaviour that does not do what the code intends, a flow the range breaks, or a promised behaviour the application does not deliver is a finding with the steps and the evidence. "
|
||||
"Do not judge individual hunks in isolation; the block passes of this lens do that and run only if you pass. Return `summary` (5-10 sentences the block passes rest on: how to reach each touched screen, the login used, what was exercised, what the block passes must not touch or change). Cover exactly the units listed below (the whole:* slots).";
|
||||
|
||||
const std::string_view FunctionalBlockHint =
|
||||
"This pass judges ONE hunk in the running application: find the behaviour this hunk changes (what a user does, what the application answers), reach it as a user - the whole pass of this lens says how - exercise it, including the error or empty path the hunk touches, and compare what you observe with what the code says it does. "
|
||||
"A hunk whose change has no reachable behaviour of its own (a type, a helper only other hunks make visible, a test, a build script) is n/a with the reason - never clear. "
|
||||
"The stack (the application, its database, the account) is yours alone while this pass runs, but it is not reset between passes: earlier passes may have left records in it and later ones will see yours - create only what you need, name it with this unit id, never delete or change what you did not create in this pass, and leave the account as you found it.";
|
||||
|
||||
const std::string_view ShotRules =
|
||||
"Take a screenshot (browser_take_screenshot, WITHOUT a filename - the server stores it under this pass's output directory and returns the path; a filename you choose is written into the repository's working tree) of every state a finding or a clear verdict rests on; the returned path is your evidence. browser_snapshot before every action - element refs come from the snapshot and die on navigation. After two failed attempts at the same target, stop and record an `unverified` note saying what blocked you.";
|
||||
|
||||
const std::string_view HintOutside =
|
||||
"Judge the in-repository users and callers of what this commit changes, outside its own diff - at the base (`git -C <tree> show <base>:<path>`) and at HEAD.";
|
||||
const std::string_view HintAbsent =
|
||||
"Judge what a reviewer of this repository expects in this commit and does not find: a commit body at all (a body-less commit has no pK:msg unit), a test, a version or changelog bump, a doc or packaging update, an error path, a migration for existing installs.";
|
||||
|
||||
namespace {
|
||||
// An optional string as the prompt prints it: None when absent.
|
||||
std::string OrNone(const std::optional<std::string>& value) {
|
||||
return value ? *value : "None";
|
||||
}
|
||||
|
||||
// A string, or Error (TypeError): only a string is concatenated.
|
||||
const std::string& Text(const Json& value) {
|
||||
if (!value.is_string()) throw Dyn::Error("TypeError", std::format("can only concatenate str (not \"{}\") to str", Dyn::TypeName(value)));
|
||||
return value.get_ref<const std::string&>();
|
||||
}
|
||||
|
||||
std::string JoinStrings(const Json& list, std::string_view separator) {
|
||||
std::vector<std::string> parts;
|
||||
for (const Json& item : list) parts.push_back(Text(item));
|
||||
return Dyn::Join(parts, separator);
|
||||
}
|
||||
|
||||
std::int64_t IntItem(const Json& range, std::size_t index) {
|
||||
const Json& value = range.at(index);
|
||||
if (value.is_boolean()) return value.get<bool>() ? 1 : 0;
|
||||
return value.get<std::int64_t>();
|
||||
}
|
||||
}
|
||||
|
||||
std::string SystemText() {
|
||||
return Dyn::Replace(Dyn::ReadText(LensDir() / "_common-repo.md"), "{{ARTIFACT_KIND}}", "commit range");
|
||||
}
|
||||
|
||||
std::string Charter(std::string_view lensFile) {
|
||||
return Dyn::ReadText(LensDir() / std::string(lensFile));
|
||||
}
|
||||
|
||||
std::string RunLayer(std::string_view artifactRel, std::string_view base, std::string_view date, std::span<const std::string> trees, std::string_view hash,
|
||||
std::span<const std::string> lines, const Json& units, std::span<const std::string> contextPaths, std::string_view repoName) {
|
||||
std::vector<std::string> inputs;
|
||||
inputs.push_back(std::format("- The frozen artifact (review THIS, at hash {}): the *.patch files in {} - `git format-patch` of the commit range under review, inlined below in sorted order; nothing else in that dir is an input",
|
||||
hash, artifactRel));
|
||||
inputs.push_back(std::format("- Repository under review ({}), checked out at the range HEAD (the last commit of the artifact): {} - file content, history and blame come from this path; spell it exactly like this in every git -C call{}",
|
||||
repoName, Dyn::Join(trees, ", "), !trees.empty() && trees.front() == "." ? " (`.` is the working directory)" : ""));
|
||||
inputs.push_back(base.empty() ? std::string("- Range base: the base-commit line of the last patch")
|
||||
: std::format("- Range base (the state before the first commit; `git -C <tree> show <base>:<path>`): {}", base));
|
||||
if (!contextPaths.empty()) {
|
||||
inputs.push_back(std::format("- Material the artifact discusses (read-only evidence; do not spend turns locating it): {}", Dyn::Join(contextPaths, ", ")));
|
||||
}
|
||||
inputs.push_back("- No mailing list, no network beyond the application under test: what is not on disk or in the running application is unverifiable and becomes a note");
|
||||
inputs.push_back(std::format("- Run date: {}", date));
|
||||
std::vector<std::string> artifact;
|
||||
artifact.reserve(lines.size());
|
||||
for (std::size_t i = 0; i < lines.size(); ++i) artifact.push_back(std::format("{:04d}| {}", i + 1, lines[i]));
|
||||
std::vector<std::string> inventory;
|
||||
for (const Json& unit : units) {
|
||||
const Json& range = Dyn::At(unit, "lines");
|
||||
inventory.push_back(std::format("- {} [{}-{}] {}", Dyn::Str(Dyn::At(unit, "id")), Dyn::Str(range.at(0)), Dyn::Str(range.at(1)), Dyn::Str(Dyn::At(unit, "excerpt"))));
|
||||
}
|
||||
return std::format("INPUTS:\n{}\n\nARTIFACT (frozen, hash {}), inlined with line numbers:\n{}\n\nINVENTORY - {} units, a MECHANICAL partition of the artifact (every non-blank line belongs to exactly one unit; fixed slots with lines 0-0 stand for what is NOT in the text):\n{}",
|
||||
Dyn::Join(inputs, "\n"), hash, Dyn::Join(artifact, "\n"), units.size(), Dyn::Join(inventory, "\n"));
|
||||
}
|
||||
|
||||
std::string AppBlock(const Json& functional, const std::optional<std::string>& loginFixture, const std::optional<std::string>& totpCommand, bool slots) {
|
||||
const Json& f = Dyn::Or(functional, Dyn::EmptyDict());
|
||||
std::vector<std::string> lines = {"APPLICATION UNDER TEST (this lens drives it with the Playwright MCP tools mcp__playwright__*):"};
|
||||
if (slots) {
|
||||
lines.emplace_back("- The application: a stack of this pass's own (the application, its API, its database and a login), one of several the operator brought up side by side from the tree named under INPUTS at the range HEAD; STACK FOR THIS PASS, at the end of the prompt, names its URL, the other origins it answers on and its login (the driver verified each stack answers before the gate started)");
|
||||
} else {
|
||||
lines.push_back(std::format("- The application: {} - served from the tree named under INPUTS at the range HEAD (the driver verified the tree is at that HEAD and that this URL answers before the gate started)",
|
||||
Dyn::Str(Dyn::Get(f, "appUrl"))));
|
||||
if (Dyn::Truthy(Dyn::Get(f, "apiUrls"))) lines.push_back(std::format("- Other local origins you may call (the API, mail): {}", JoinStrings(Dyn::At(f, "apiUrls"), ", ")));
|
||||
if (loginFixture && !loginFixture->empty()) {
|
||||
lines.push_back(std::format("- Login: the fixture {} (JSON: email, password, totpSecret - a throwaway test account on the local stack); read it with the Read tool, and for the one-time code run exactly `{}` (prints a 6-digit code and the seconds left in its window; regenerate when it rolled over)",
|
||||
*loginFixture, OrNone(totpCommand)));
|
||||
} else {
|
||||
lines.emplace_back("- Login: no fixture was found on disk; what the application shows without a session is what you can exercise, and a behaviour behind a login is an `unverified` note with n/a");
|
||||
}
|
||||
}
|
||||
if (Dyn::Truthy(Dyn::Get(Dyn::Or(Dyn::Get(f, "login"), Dyn::EmptyDict()), "notes"))) {
|
||||
lines.push_back(std::format("- Login notes: {}", Text(Dyn::At(Dyn::At(f, "login"), "notes"))));
|
||||
}
|
||||
if (Dyn::Truthy(Dyn::Get(f, "notes"))) lines.push_back(std::format("- Notes from the repository owner: {}", Text(Dyn::At(f, "notes"))));
|
||||
lines.push_back(std::format("- Rules: navigate only to the origins named here; the browser and the stack (the application, its database, the account) are yours alone while this pass runs, but the stack is not reset between passes: earlier passes of this gate may have left records in it and later ones will see what you leave - create only what you need, name it with your unit id, never delete or change what you did not create in this pass, and leave the account as you found it (where the range makes you change its password, an MFA factor, an organisation setting or the subscription, restore it; where you cannot, say so in an `info` note). Never sign up a new account unless the range is about signup. {}",
|
||||
ShotRules));
|
||||
return Dyn::Join(lines, "\n");
|
||||
}
|
||||
|
||||
std::string StackText(const Json& stack, const std::optional<std::string>& totpCommand) {
|
||||
std::vector<std::string> lines = {
|
||||
std::format("STACK FOR THIS PASS ({}, yours alone while this pass runs):", Dyn::Str(Dyn::At(stack, "id"))),
|
||||
std::format("- The application: {}", Dyn::Str(Dyn::At(stack, "appUrl"))),
|
||||
};
|
||||
if (Dyn::Truthy(Dyn::Get(stack, "apiUrls"))) lines.push_back(std::format("- Other local origins you may call (the API, mail): {}", JoinStrings(Dyn::At(stack, "apiUrls"), ", ")));
|
||||
if (Dyn::Truthy(Dyn::Get(stack, "login"))) {
|
||||
lines.push_back(std::format("- Login: the fixture {} (JSON: email, password, totpSecret - a throwaway test account on this stack); read it with the Read tool, and for the one-time code run exactly `{}` (prints a 6-digit code and the seconds left in its window; regenerate when it rolled over)",
|
||||
Dyn::Str(Dyn::At(stack, "login")), OrNone(totpCommand)));
|
||||
} else {
|
||||
lines.emplace_back("- Login: this stack has no login fixture; what the application shows without a session is what you can exercise, and a behaviour behind a login is an `unverified` note with n/a");
|
||||
}
|
||||
return Dyn::Join(lines, "\n");
|
||||
}
|
||||
|
||||
std::string DbBlock(const Json& supabase, std::string_view sqlCommand, const std::optional<std::string>& dbUser, bool withApp,
|
||||
const std::optional<std::string>& checked, std::optional<bool> bypass) {
|
||||
const Json& s = Dyn::Or(supabase, Dyn::EmptyDict());
|
||||
std::string role;
|
||||
if (dbUser && !dbUser->empty()) {
|
||||
role = std::format("The connection is the role `{}`{}", *dbUser,
|
||||
!bypass ? "." : (*bypass ? ", which bypasses row-level security." : ", which row-level security applies to."));
|
||||
} else {
|
||||
role = "The connection's role differs between the stacks: `select current_user` says which is yours, and its pg_roles row whether row-level security applies to it.";
|
||||
}
|
||||
std::vector<std::string> lines = {
|
||||
std::format("DATABASE UNDER TEST (this lens runs SQL against it with the exact command `{}`):", sqlCommand),
|
||||
std::format("- The database: the Postgres of the local Supabase stack the operator brought up from the tree named under INPUTS - a throwaway stack, never a hosted project. Checked by the driver before this gate: {}. {}",
|
||||
checked && !checked->empty() ? *checked : std::string("nothing (a dry run)"), role),
|
||||
std::format("- Run SQL with exactly `{} <<'SQL'`, the statements on the lines after it, and a last line `SQL`. Every call is ONE transaction that the helper rolls back at its end: what a statement writes is seen by the later statements of the same call and by nothing else - not by the application, not by the other passes running at the same time, not by your next call. So a proof goes into one call: set up the state, act, read the outcome. BEGIN, COMMIT, ROLLBACK, END, ABORT, PREPARE TRANSACTION and COPY are refused (SAVEPOINT and ROLLBACK TO are fine); the first statement that fails stops the call.",
|
||||
sqlCommand),
|
||||
"- Acting as a caller of the API: `set local role authenticated;` then `select set_config('request.jwt.claims', '{\"sub\":\"<a user id from auth.users>\",\"role\":\"authenticated\"}', true);` makes row-level security, auth.uid() and auth.jwt() behave as for that signed-in user; `set local role anon` as for a visitor without a session; `set local role service_role` as the service key. Say in your evidence which role each query ran as.",
|
||||
std::format("- Limits: statement_timeout {} s and lock_timeout {} s per statement; at most {} rows of a result are printed. A lock you take (DDL, an UPDATE) holds until your call ends while the other passes and the application wait on it - keep such calls short.",
|
||||
PgWire::StatementTimeoutS, PgWire::LockTimeoutS, PgWire::MaxRows),
|
||||
"- Evidence: the SQL you ran and the lines the helper printed for it - quote both in the finding or the coverage basis. Output that starts `review-gates sql: NO DATABASE` means the database did not answer: what rests on it is unverified, never clear.",
|
||||
};
|
||||
if (withApp) {
|
||||
lines.emplace_back("- Nothing you write here reaches the application: create what the browser must see through the application itself, and use this database to read back what the application persisted and to inspect state no screen shows.");
|
||||
}
|
||||
if (Dyn::Truthy(Dyn::Get(s, "notes"))) lines.push_back(std::format("- Notes from the repository owner: {}", Text(Dyn::At(s, "notes"))));
|
||||
return Dyn::Join(lines, "\n");
|
||||
}
|
||||
|
||||
std::string LensLayer(std::string_view lensFile, std::string_view charterText, std::string_view dispositionsBlock, std::string_view app,
|
||||
std::string_view wholeSummary, std::string_view db) {
|
||||
std::vector<std::string> parts = {std::format("YOUR CHARTER (process/lenses/{}), verbatim:\n\n{}", lensFile, Dyn::Strip(charterText))};
|
||||
if (!app.empty()) parts.emplace_back(app);
|
||||
if (!db.empty()) parts.emplace_back(db);
|
||||
parts.emplace_back(dispositionsBlock);
|
||||
if (!wholeSummary.empty()) {
|
||||
parts.push_back(std::format("The whole pass of this lens on this hash concluded (the constraints your block pass rests on):\n{}", Dyn::Slice(wholeSummary, 0, 2500)));
|
||||
}
|
||||
return Dyn::Join(parts, "\n\n");
|
||||
}
|
||||
|
||||
std::string Tail(const Json& job, const Json& units, std::span<const std::string> lines, std::string_view wholeSummary) {
|
||||
const std::string lensFile = Dyn::At(job, "lensFile").get<std::string>();
|
||||
const Json& kind = Dyn::At(job, "kind");
|
||||
if (kind == "whole") {
|
||||
const std::string_view whole = Plan::LensOf(lensFile).whole;
|
||||
if (whole != "first-repo" && whole != "functional") throw Dyn::Error("KeyError", Dyn::ReprValue(whole.empty() ? Json() : Json(whole)));
|
||||
std::vector<std::string> listed;
|
||||
const Json& expected = Dyn::At(job, "expectedIds");
|
||||
for (const Json& unit : units) {
|
||||
if (Dyn::In(Dyn::At(unit, "id"), expected)) listed.push_back(std::format("- {} [0-0] {}", Dyn::Str(Dyn::At(unit, "id")), Dyn::Str(Dyn::At(unit, "excerpt"))));
|
||||
}
|
||||
return std::format("{}\n{}\nUnits to cover:\n{}", whole == "first-repo" ? WholeFirstRepo : WholeFunctional, GenericVocab, Dyn::Join(listed, "\n"));
|
||||
}
|
||||
const Json* found = nullptr;
|
||||
for (const Json& unit : units) {
|
||||
if (Dyn::Equal(Dyn::At(unit, "id"), Dyn::At(job, "unit"))) {
|
||||
found = &unit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) throw Dyn::Error("StopIteration", "");
|
||||
const Json& u = *found;
|
||||
const std::string id = Dyn::Str(Dyn::At(u, "id"));
|
||||
if (kind == "slot") {
|
||||
const std::string description = Dyn::Replace(Text(Dyn::At(u, "excerpt")), "FIXED SLOT: ", "");
|
||||
return std::format("SCOPE - SLOT PASS, unit \"{}\": this unit has no lines; it stands for a question about the whole artifact: {}. Answer it for your lens. Coverage: exactly this one unit.\n{}",
|
||||
id, description, GenericVocab);
|
||||
}
|
||||
const Json& range = Dyn::At(u, "lines");
|
||||
const std::int64_t a = IntItem(range, 0);
|
||||
const std::int64_t b = IntItem(range, 1);
|
||||
std::string_view hint;
|
||||
if (id.ends_with(":outside")) {
|
||||
hint = HintOutside;
|
||||
} else if (id.ends_with(":absent")) {
|
||||
hint = HintAbsent;
|
||||
} else if (lensFile == Plan::FunctionalLens) {
|
||||
hint = FunctionalBlockHint;
|
||||
}
|
||||
const std::string text = Plan::UnitText(lines, u);
|
||||
const std::string scope = std::format("SCOPE - BLOCK PASS, unit \"{}\" [lines {}-{}]: judge ONLY this unit, with your full attention by your charter - a hunk against the standard - reading the rest of the artifact only as context. Do not re-litigate the approach as a whole{}. Coverage: exactly this one unit.",
|
||||
id, a, b, wholeSummary.empty() ? "" : " - the whole pass of this lens concluded as stated above");
|
||||
return std::format("{}{}\n\nUNIT TEXT (verbatim, lines {}-{}):\n{}\n\n{}", scope, hint.empty() ? std::string() : std::format("\n{}", hint), a, b, text, GenericVocab);
|
||||
}
|
||||
|
||||
std::string BudgetLine(const Json& job) {
|
||||
return std::format("\n\nTool-call budget for this pass: {} (every tool call is one request; the pipeline stops the process at that count and a stopped pass "
|
||||
"returns NOTHING - the unit is then unaddressed and the lens NOT RETURNED). Batch independent reads into one call and return the structured output with margin to spare.",
|
||||
Dyn::Str(Dyn::Get(job, "maxTurns")));
|
||||
}
|
||||
|
||||
std::string SystemPrompt(std::string_view systemText, std::string_view run, std::string_view lens) {
|
||||
return std::format("{}{}{}{}{}", systemText, SepRun, run, SepLens, lens);
|
||||
}
|
||||
|
||||
std::string UserPrompt(std::string_view tail, const Json& job, std::string_view stack) {
|
||||
return std::format("{}{}{}\n\nReturn the structured output described in your instructions.\n", tail, stack.empty() ? std::string() : std::format("\n\n{}", stack),
|
||||
Dyn::Truthy(job) ? BudgetLine(job) : std::string());
|
||||
}
|
||||
}
|
||||
121
implementations/Crafter.Review-Schema.cpp
Normal file
121
implementations/Crafter.Review-Schema.cpp
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Schema_impl;
|
||||
import :Schema;
|
||||
import :Json;
|
||||
import std;
|
||||
|
||||
namespace Crafter::Review::Schema {
|
||||
namespace {
|
||||
template <std::size_t N>
|
||||
Json Strings(const std::array<std::string_view, N>& values) {
|
||||
Json out = Json::array();
|
||||
for (const std::string_view value : values) out.push_back(value);
|
||||
return out;
|
||||
}
|
||||
|
||||
Json String(std::string_view description = {}) {
|
||||
Json out = {{"type", "string"}};
|
||||
if (!description.empty()) out["description"] = description;
|
||||
return out;
|
||||
}
|
||||
|
||||
Json StringList(std::string_view description) {
|
||||
return {{"type", "array"}, {"items", {{"type", "string"}}}, {"description", description}};
|
||||
}
|
||||
|
||||
Json Verdict(std::string_view description) {
|
||||
Json out = {{"type", "string"}, {"enum", Strings(VerdictEnum)}};
|
||||
if (!description.empty()) out["description"] = description;
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
Json Finding() {
|
||||
Json contests = {
|
||||
{"type", "object"},
|
||||
{"additionalProperties", false},
|
||||
{"required", {"id", "why"}},
|
||||
{"properties", {
|
||||
{"id", String()},
|
||||
{"why", String("NEW evidence the disposition's recorded grounds do not survive")},
|
||||
}},
|
||||
};
|
||||
return {
|
||||
{"type", "object"},
|
||||
{"additionalProperties", false},
|
||||
{"required", {"finding", "evidence", "proposedAction", "items"}},
|
||||
{"properties", {
|
||||
{"finding", String("the defect - by your lens's charter question (objective wrongness)")},
|
||||
{"evidence", String("file:line, a verbatim quote, the steps taken in the application and what was observed (a screenshot or snapshot path) - no vibes")},
|
||||
{"proposedAction", String()},
|
||||
{"items", StringList("the INVENTORY unit ids this finding concerns, copied exactly; a finding that spans units lists them all")},
|
||||
{"dischargedBy", String("id of a disposition listed under DISPOSITIONS IN FORCE that discharges this finding (you verified its grounds); omit when none applies")},
|
||||
{"contests", contests},
|
||||
}},
|
||||
};
|
||||
}
|
||||
|
||||
Json Note() {
|
||||
return {
|
||||
{"type", "object"},
|
||||
{"additionalProperties", false},
|
||||
{"required", {"kind", "note", "evidence", "action"}},
|
||||
{"properties", {
|
||||
{"kind", {{"type", "string"}, {"enum", Strings(NoteKinds)}}},
|
||||
{"note", String()},
|
||||
{"evidence", String()},
|
||||
{"action", String("what the orchestrator does with it (bank / record in the manifest / check at push time / nothing)")},
|
||||
{"id", String("refutation-verified only: the disposition id")},
|
||||
{"items", StringList("INVENTORY unit ids this note concerns")},
|
||||
}},
|
||||
};
|
||||
}
|
||||
|
||||
Json Coverage() {
|
||||
return {
|
||||
{"type", "object"},
|
||||
{"additionalProperties", false},
|
||||
{"required", {"item", "verdict", "basis"}},
|
||||
{"properties", {
|
||||
{"item", String("an INVENTORY unit id, verbatim")},
|
||||
{"verdict", {{"type", "string"}, {"enum", Strings(CoverageVerdicts)}}},
|
||||
{"basis", String("what this verdict rests on: the tree ref, the command run, the steps taken in the application and the evidence file - or the literal string \"no record\"")},
|
||||
}},
|
||||
};
|
||||
}
|
||||
|
||||
Json BlockSchema() {
|
||||
return {
|
||||
{"type", "object"},
|
||||
{"additionalProperties", false},
|
||||
{"required", {"verdict", "findings", "notes", "coverage"}},
|
||||
{"properties", {
|
||||
{"verdict", Verdict("FIX FIRST iff any finding is undischarged - the pipeline derives the same and fails closed on disagreement")},
|
||||
{"findings", {{"type", "array"}, {"items", Finding()}}},
|
||||
{"notes", {{"type", "array"}, {"items", Note()}}},
|
||||
{"coverage", {{"type", "array"}, {"items", Coverage()}, {"minItems", 1}, {"maxItems", 1}, {"description", "exactly one entry: the unit this pass covers"}}},
|
||||
}},
|
||||
};
|
||||
}
|
||||
|
||||
Json WholeSchema() {
|
||||
return {
|
||||
{"type", "object"},
|
||||
{"additionalProperties", false},
|
||||
{"required", {"verdict", "findings", "notes", "coverage", "summary"}},
|
||||
{"properties", {
|
||||
{"verdict", Verdict({})},
|
||||
{"findings", {{"type", "array"}, {"items", Finding()}}},
|
||||
{"notes", {{"type", "array"}, {"items", Note()}}},
|
||||
{"coverage", {{"type", "array"}, {"items", Coverage()}, {"description", "one entry per unit you were asked to cover"}}},
|
||||
{"summary", String("5-10 sentences: the range as you judged it and the constraints the block passes must respect (the functional lens: how to reach each touched screen, the login used, what the block passes must not touch)")},
|
||||
}},
|
||||
};
|
||||
}
|
||||
|
||||
std::string SchemaJson(std::string_view kind) {
|
||||
return DumpCompactSorted(kind == "block" ? BlockSchema() : WholeSchema());
|
||||
}
|
||||
}
|
||||
282
implementations/Crafter.Review-State.cpp
Normal file
282
implementations/Crafter.Review-State.cpp
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module;
|
||||
#include <cerrno>
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <unistd.h>
|
||||
|
||||
module Crafter.Review:State_impl;
|
||||
import :State;
|
||||
import :Json;
|
||||
import :Text;
|
||||
import :Platform;
|
||||
import std;
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace Crafter::Review::State {
|
||||
namespace {
|
||||
std::string Formatted(double value, std::int32_t precision) {
|
||||
return std::format("{:.{}f}", value, precision);
|
||||
}
|
||||
|
||||
double AsDouble(const Json& value) {
|
||||
if (value.is_number_float()) return value.get<double>();
|
||||
if (value.is_boolean()) return value.get<bool>() ? 1.0 : 0.0;
|
||||
if (value.is_number_unsigned()) return static_cast<double>(value.get<std::uint64_t>());
|
||||
if (value.is_number_integer()) return static_cast<double>(value.get<std::int64_t>());
|
||||
throw Dyn::Error("TypeError", std::format("unsupported operand type(s) for /: '{}' and 'float'", Dyn::TypeName(value)));
|
||||
}
|
||||
|
||||
// `value or 0` for a number that is summed.
|
||||
Json OrZero(const Json& value) {
|
||||
return Dyn::Truthy(value) ? value : Json(0);
|
||||
}
|
||||
|
||||
// The key's value, or the fallback only when the key is absent.
|
||||
const Json& GetOr(const Json& dict, std::string_view key, const Json& fallback) {
|
||||
return Dyn::Has(dict, key) ? Dyn::At(dict, key) : fallback;
|
||||
}
|
||||
|
||||
std::size_t Len(const Json& value) {
|
||||
return value.is_string() ? Dyn::Length(value.get_ref<const std::string&>()) : value.size();
|
||||
}
|
||||
|
||||
// A string, or Error (TypeError): only a string is concatenated.
|
||||
const std::string& Text(const Json& value) {
|
||||
if (!value.is_string()) throw Dyn::Error("TypeError", std::format("can only concatenate str (not \"{}\") to str", Dyn::TypeName(value)));
|
||||
return value.get_ref<const std::string&>();
|
||||
}
|
||||
|
||||
// f'{value:<width}' of a str.
|
||||
std::string Padded(const Json& value, std::size_t width) {
|
||||
if (!value.is_string()) throw Dyn::Error("TypeError", std::format("unsupported format string passed to {}.__format__", Dyn::TypeName(value)));
|
||||
return Dyn::LJust(value.get_ref<const std::string&>(), width);
|
||||
}
|
||||
}
|
||||
|
||||
Json EmptyState() {
|
||||
return {{"version", 1}, {"entries", Json::object()}, {"personaPass", nullptr}};
|
||||
}
|
||||
|
||||
Json LoadState(const fs::path& path) {
|
||||
if (!path.empty() && fs::exists(path)) {
|
||||
try {
|
||||
return Json::parse(Dyn::ReadText(path));
|
||||
} catch (const std::exception&) {
|
||||
// A damaged file is the empty state.
|
||||
}
|
||||
}
|
||||
return EmptyState();
|
||||
}
|
||||
|
||||
Json MergeState(const Json& disk, const Json& sets, std::span<const std::string> drops, const Json& read) {
|
||||
const bool ok = disk.is_object() && Dyn::Get(disk, "entries").is_object();
|
||||
Json state = {
|
||||
{"version", 1},
|
||||
{"entries", ok ? Dyn::At(disk, "entries") : Json::object()},
|
||||
{"personaPass", ok ? Dyn::Get(disk, "personaPass") : Json()},
|
||||
};
|
||||
Json& entries = state["entries"];
|
||||
for (const std::string& key : drops) entries.erase(key);
|
||||
for (auto it = sets.begin(); it != sets.end(); ++it) {
|
||||
if (std::ranges::contains(drops, it.key())) continue;
|
||||
Json entry = it.value();
|
||||
if (!entry.is_object()) throw Dyn::Error("TypeError", std::format("'{}' object is not iterable", Dyn::TypeName(entry)));
|
||||
if (!read.is_null() && !Dyn::Equal(Dyn::Get(entry, "kind"), Json("whole"))) {
|
||||
// One clean read per round: a second store of the same run, or
|
||||
// the relaunch of an unfinished run, adds nothing.
|
||||
const Json& previous = Dyn::Get(entries, it.key());
|
||||
Json reads = Json::array();
|
||||
if (Dyn::Truthy(previous)) {
|
||||
const Json& stored = Dyn::Get(previous, "reads");
|
||||
if (Dyn::Truthy(stored)) {
|
||||
reads = stored;
|
||||
} else {
|
||||
const Json& hash = Dyn::Get(previous, "hash");
|
||||
const std::string head = Dyn::Truthy(hash) ? Dyn::Slice(Text(hash), 0, 8) : std::string();
|
||||
reads.push_back({{"hash", head}, {"round", 0}, {"run", Dyn::Get(previous, "run")}});
|
||||
}
|
||||
}
|
||||
const bool counted = std::ranges::any_of(reads, [&](const Json& x) {
|
||||
return Dyn::Equal(Dyn::Get(x, "hash"), Dyn::At(read, "hash")) && Dyn::Equal(Dyn::Get(x, "round"), Dyn::At(read, "round"));
|
||||
});
|
||||
if (!counted) reads.push_back(read);
|
||||
entry["reads"] = std::move(reads);
|
||||
}
|
||||
entries[it.key()] = std::move(entry);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
void SaveWhole(const fs::path& path, const Json& state) {
|
||||
const fs::path temp = std::format("{}.tmp", path.string());
|
||||
{
|
||||
std::ofstream out(temp, std::ios::binary | std::ios::trunc);
|
||||
if (!out) throw std::runtime_error(std::format("{}: cannot write", temp.string()));
|
||||
out << DumpFile(state);
|
||||
}
|
||||
fs::rename(temp, path);
|
||||
}
|
||||
|
||||
Json SaveState(const fs::path& path, const Json& sets, std::span<const std::string> drops, const Json& read) {
|
||||
// Without the lock the write is still made; a failed write throws.
|
||||
const Platform::FileLock lock(std::format("{}.lock", path.string()));
|
||||
Json merged = MergeState(LoadState(path), sets, drops, read);
|
||||
Platform::WriteAtomic(path, DumpFile(merged), 0666);
|
||||
return merged;
|
||||
}
|
||||
|
||||
fs::path LockPath(const fs::path& gateDir, std::string_view mode, std::string_view hash8) {
|
||||
return gateDir / std::format(".run-{}-{}.lock", mode, hash8);
|
||||
}
|
||||
|
||||
Json ReadLockInfo(const fs::path& path) {
|
||||
try {
|
||||
const std::string text = Dyn::ReadText(path);
|
||||
const Json info = Dyn::Strip(text).empty() ? Json::object() : Json::parse(text);
|
||||
return info.is_object() ? info : Json::object();
|
||||
} catch (const std::exception&) {
|
||||
return Json::object();
|
||||
}
|
||||
}
|
||||
|
||||
std::string Describe(const Json& info) {
|
||||
if (!Dyn::Truthy(Dyn::Get(info, "pid"))) return "holder not identified yet (it has just started)";
|
||||
const Json unknown = "?";
|
||||
return std::format("pid {} since {}, run {}, scratch {}", Dyn::Str(Dyn::At(info, "pid")), Dyn::Str(GetOr(info, "since", unknown)),
|
||||
Dyn::Str(GetOr(info, "run_n", unknown)), Dyn::Str(GetOr(info, "scratch", unknown)));
|
||||
}
|
||||
|
||||
RunLock::RunLock(const fs::path& gateDir, std::string_view mode, std::string_view hash8) {
|
||||
const fs::path path = LockPath(gateDir, mode, hash8);
|
||||
fd = open(path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
|
||||
if (fd < 0) throw std::runtime_error(std::format("{}: {}", Dyn::ErrnoText(errno), Dyn::Repr(std::string_view(path.string()))));
|
||||
if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
|
||||
const Json info = ReadLockInfo(path);
|
||||
close(fd);
|
||||
fd = -1;
|
||||
throw RunLocked(Describe(info));
|
||||
}
|
||||
}
|
||||
|
||||
RunLock::~RunLock() {
|
||||
if (fd >= 0) close(fd);
|
||||
}
|
||||
|
||||
void RunLock::WriteInfo(const Json& info) {
|
||||
const std::string text = DumpSpaced(info);
|
||||
if (lseek(fd, 0, SEEK_SET) < 0 || ftruncate(fd, 0) != 0) return;
|
||||
std::size_t written = 0;
|
||||
while (written < text.size()) {
|
||||
const ssize_t step = write(fd, text.data() + written, text.size() - written);
|
||||
if (step < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
return;
|
||||
}
|
||||
written += static_cast<std::size_t>(step);
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<Json> LockHolder(const fs::path& gateDir, std::string_view mode, std::string_view hash8) {
|
||||
const fs::path path = LockPath(gateDir, mode, hash8);
|
||||
const std::int32_t handle = open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (handle < 0) return std::nullopt;
|
||||
std::optional<Json> holder;
|
||||
if (flock(handle, LOCK_EX | LOCK_NB) == 0) {
|
||||
flock(handle, LOCK_UN);
|
||||
} else {
|
||||
holder = ReadLockInfo(path);
|
||||
}
|
||||
close(handle);
|
||||
return holder;
|
||||
}
|
||||
|
||||
std::int64_t NextRunNumber(const fs::path& gateDir, std::string_view mode, std::string_view hash8) {
|
||||
std::int64_t n = 1;
|
||||
while (fs::exists(gateDir / std::format("{}-{}-run-{}.json", mode, hash8, n)) || fs::exists(gateDir / std::format("{}-{}-run-{}-test.json", mode, hash8, n))) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
Json UsageTotals(std::span<const Json> records) {
|
||||
Json totals = {
|
||||
{"input", 0}, {"cacheCreation", 0}, {"cacheRead", 0}, {"output", 0}, {"thinking", 0},
|
||||
{"turns", 0}, {"processes", 0}, {"costUsd", 0.0}, {"denials", 0},
|
||||
};
|
||||
const Json zero = 0;
|
||||
for (const Json& record : records) {
|
||||
const Json& usage = Dyn::Or(Dyn::Get(record, "usage"), Dyn::EmptyDict());
|
||||
for (const std::string_view key : {"input", "cacheCreation", "cacheRead", "output", "thinking"}) {
|
||||
totals[std::string(key)] = Dyn::Add(totals[std::string(key)], OrZero(GetOr(usage, key, zero)));
|
||||
}
|
||||
totals["costUsd"] = Dyn::Add(totals["costUsd"], OrZero(Dyn::Get(record, "costUsd")));
|
||||
totals["denials"] = Dyn::Add(totals["denials"], Json(Len(Dyn::Or(Dyn::Get(record, "denials"), Dyn::EmptyList()))));
|
||||
totals["turns"] = Dyn::Add(totals["turns"], OrZero(GetOr(record, "turns", zero)));
|
||||
const Json& status = Dyn::Get(record, "status");
|
||||
const bool counted = !status.is_null() && status != "dry-run" && status != "reused";
|
||||
totals["processes"] = Dyn::Add(totals["processes"], Json(counted ? 1 : 0));
|
||||
}
|
||||
// input + 1.25 * cacheCreation + 0.1 * cacheRead + 5 * output: 5 * an
|
||||
// integer stays an integer until it meets the float, so the dump
|
||||
// prints it the same.
|
||||
const Json& output = totals["output"];
|
||||
const double five = output.is_number_integer() ? static_cast<double>(5 * output.get<std::int64_t>()) : 5.0 * AsDouble(output);
|
||||
double costUnits = AsDouble(totals["input"]) + 1.25 * AsDouble(totals["cacheCreation"]);
|
||||
costUnits = costUnits + 0.1 * AsDouble(totals["cacheRead"]);
|
||||
costUnits = costUnits + five;
|
||||
totals["costUnits"] = costUnits;
|
||||
return totals;
|
||||
}
|
||||
|
||||
std::string Summary(const Json& dump) {
|
||||
std::vector<std::string> lines;
|
||||
std::string overall = std::format("overall: {}", Dyn::Str(Dyn::At(dump, "overall")));
|
||||
if (Dyn::Truthy(Dyn::Get(dump, "stoppedAt"))) overall += std::format(" (stopped at {})", Dyn::Str(Dyn::At(dump, "stoppedAt")));
|
||||
lines.push_back(std::move(overall));
|
||||
for (const Json& result : Dyn::At(dump, "results")) {
|
||||
const Json& parts = Dyn::Or(Dyn::Get(result, "parts"), Dyn::EmptyList());
|
||||
const auto reused = std::ranges::count_if(parts, [](const Json& part) { return Dyn::Truthy(Dyn::Get(part, "reused")); });
|
||||
std::string line = std::format(" {} {} ", Padded(Dyn::At(result, "lens"), 28), Padded(Dyn::At(result, "verdict"), 12));
|
||||
if (Dyn::Truthy(Dyn::Get(result, "resumed"))) line += std::format("[resumed {}] ", Text(Dyn::At(result, "resumed")));
|
||||
line += std::format("findings {} (undischarged {}), notes {}, passes {}", Len(Dyn::At(result, "findings")), Dyn::Str(Dyn::At(result, "undischarged")),
|
||||
Len(Dyn::At(result, "notes")), Len(parts));
|
||||
if (reused) line += std::format(" ({} reused)", reused);
|
||||
if (Dyn::Truthy(Dyn::Get(result, "coverageMissing"))) line += std::format(", missing {}", Len(Dyn::At(result, "coverageMissing")));
|
||||
if (Dyn::Truthy(Dyn::Get(result, "stoppedEarly"))) line += std::format(" <- {}", Text(Dyn::At(result, "stoppedEarly")));
|
||||
lines.push_back(std::move(line));
|
||||
}
|
||||
const Json& coverage = Dyn::Or(Dyn::Get(dump, "coverage"), Dyn::EmptyDict());
|
||||
if (Dyn::Truthy(coverage)) {
|
||||
lines.push_back(std::format("matrix: {} units x {} lenses; holes {}, not reviewed by any lens that runs (messages, diffstats, documentation, the units of a lens the config turns off) {}, units with a defect verdict {}",
|
||||
Dyn::Str(Dyn::At(coverage, "units")), Len(Dyn::At(coverage, "lenses")), Len(Dyn::At(coverage, "holes")),
|
||||
Len(Dyn::Or(Dyn::Get(coverage, "notReviewed"), Dyn::EmptyList())), Len(Dyn::At(coverage, "defects"))));
|
||||
}
|
||||
const Json& usageAll = Dyn::Has(dump, "usage") ? Dyn::At(dump, "usage") : Dyn::EmptyDict();
|
||||
const Json& usage = Dyn::Or(Dyn::Get(usageAll, "run"), Dyn::EmptyDict());
|
||||
if (Dyn::Truthy(usage)) {
|
||||
const Json zero = 0;
|
||||
lines.push_back(std::format("usage: {} processes, {} turns, cache write {}M, cache read {}M, output {}K, cost-units {}M, list cost ${}, denied calls {}, wall {} min, prefix hit rate {}",
|
||||
Dyn::Str(Dyn::At(usage, "processes")), Dyn::Str(Dyn::At(usage, "turns")),
|
||||
Formatted(AsDouble(Dyn::At(usage, "cacheCreation")) / 1e6, 2), Formatted(AsDouble(Dyn::At(usage, "cacheRead")) / 1e6, 2),
|
||||
Formatted(AsDouble(Dyn::At(usage, "output")) / 1e3, 0), Formatted(AsDouble(Dyn::At(usage, "costUnits")) / 1e6, 2),
|
||||
Formatted(AsDouble(Dyn::At(usage, "costUsd")), 2), Dyn::Str(Dyn::At(usage, "denials")),
|
||||
Formatted(AsDouble(GetOr(dump, "wallMin", zero)), 0), Dyn::Str(Dyn::Get(usageAll, "prefixHitRate"))));
|
||||
}
|
||||
const Json& reads = Dyn::Get(dump, "reads");
|
||||
if (Dyn::Truthy(reads)) {
|
||||
std::vector<std::string> owed;
|
||||
const Json& owedBy = Dyn::At(reads, "owed");
|
||||
for (auto it = owedBy.begin(); it != owedBy.end(); ++it) {
|
||||
owed.push_back(std::format("{} {} unit(s) / {} read(s)", it.key(), Dyn::Str(Dyn::At(it.value(), "units")), Dyn::Str(Dyn::At(it.value(), "reads"))));
|
||||
}
|
||||
std::string owedText = Dyn::Join(owed, "; ");
|
||||
if (owedText.empty()) owedText = "none";
|
||||
lines.push_back(std::format("reads: x = {}, round {} on this hash{}; read this run: {}; owed: {}", Dyn::Str(Dyn::At(reads, "x")), Dyn::Str(Dyn::At(reads, "round")),
|
||||
Dyn::Truthy(Dyn::Get(reads, "continued")) ? " (continued)" : "", Dyn::Str(Dyn::Or(Dyn::Get(reads, "readThisRun"), Dyn::EmptyDict())), owedText));
|
||||
}
|
||||
lines.push_back(std::format("dump: {}", Dyn::Str(Dyn::At(dump, "dumpPath"))));
|
||||
return Dyn::Join(lines, "\n");
|
||||
}
|
||||
}
|
||||
374
implementations/Crafter.Review-Stream.cpp
Normal file
374
implementations/Crafter.Review-Stream.cpp
Normal file
|
|
@ -0,0 +1,374 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Stream_impl;
|
||||
import :Stream;
|
||||
import :Json;
|
||||
import :Text;
|
||||
import :PgWire;
|
||||
import std;
|
||||
|
||||
namespace Crafter::Review::Stream {
|
||||
namespace {
|
||||
constexpr std::size_t None = std::u32string_view::npos;
|
||||
|
||||
// An ASCII literal of a re.IGNORECASE pattern at `at`: a letter matches
|
||||
// what re.I lets it match, anything else itself.
|
||||
bool MatchAt(std::u32string_view text, std::size_t at, std::string_view literal) {
|
||||
if (at + literal.size() > text.size()) return false;
|
||||
for (std::size_t i = 0; i < literal.size(); ++i) {
|
||||
const char p = literal[i];
|
||||
const char32_t t = text[at + i];
|
||||
if (p >= 'a' && p <= 'z') {
|
||||
if (Dyn::IgnoreCaseLetter(t) != p) return false;
|
||||
} else if (t != static_cast<char32_t>(static_cast<std::uint8_t>(p))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::size_t FindCi(std::u32string_view text, std::string_view literal, std::size_t from, std::size_t to) {
|
||||
if (to < literal.size()) return None;
|
||||
for (std::size_t at = from; at + literal.size() <= to; ++at) {
|
||||
if (MatchAt(text, at, literal)) return at;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
bool ContainsCi(std::u32string_view text, std::string_view literal) {
|
||||
return FindCi(text, literal, 0, text.size()) != None;
|
||||
}
|
||||
|
||||
// `first.*(second|...)`: `.` stops at \n only, so both on one line. The
|
||||
// first occurrence of `first` on a line leaves the most room after it.
|
||||
bool ThenOnLine(std::u32string_view text, std::string_view first, std::initializer_list<std::string_view> seconds) {
|
||||
std::size_t lineStart = 0;
|
||||
while (lineStart <= text.size()) {
|
||||
std::size_t lineEnd = text.find(U'\n', lineStart);
|
||||
if (lineEnd == None) lineEnd = text.size();
|
||||
const std::size_t at = FindCi(text, first, lineStart, lineEnd);
|
||||
if (at != None) {
|
||||
for (const std::string_view second : seconds) {
|
||||
if (FindCi(text, second, at + first.size(), lineEnd) != None) return true;
|
||||
}
|
||||
}
|
||||
if (lineEnd == text.size()) break;
|
||||
lineStart = lineEnd + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// \b<digits>\b
|
||||
bool WordNumber(std::u32string_view text, std::u32string_view number) {
|
||||
for (std::size_t at = text.find(number); at != None; at = text.find(number, at + 1)) {
|
||||
const bool before = at == 0 || !Dyn::IsWord(text[at - 1]);
|
||||
const bool after = at + number.size() == text.size() || !Dyn::IsWord(text[at + number.size()]);
|
||||
if (before && after) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::size_t Spaces(std::u32string_view text, std::size_t at) {
|
||||
std::size_t end = at;
|
||||
while (end < text.size() && Dyn::IsSpace(text[end])) ++end;
|
||||
return end - at;
|
||||
}
|
||||
|
||||
// (^|[\s;&|(])\S*crafter-review\s+sql(\s|$): this binary's helper,
|
||||
// spelled with any path before it.
|
||||
bool HelperCall(std::u32string_view text) {
|
||||
constexpr std::u32string_view Binary = U"crafter-review";
|
||||
for (std::size_t at = text.find(Binary); at != None; at = text.find(Binary, at + 1)) {
|
||||
const std::size_t gap = Spaces(text, at + Binary.size());
|
||||
if (gap == 0) continue;
|
||||
const std::size_t verb = at + Binary.size() + gap;
|
||||
if (text.substr(verb, 3) != U"sql") continue;
|
||||
if (verb + 3 == text.size() || Dyn::IsSpace(text[verb + 3])) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// A tool_result's content as text: a string, or a list of text blocks.
|
||||
std::string ContentText(const Json& content) {
|
||||
if (content.is_string()) return content.get<std::string>();
|
||||
if (!content.is_array()) return "";
|
||||
std::vector<std::string> texts;
|
||||
for (const Json& block : content) {
|
||||
if (block.is_object() && Dyn::Get(block, "text").is_string()) texts.push_back(Dyn::At(block, "text").get<std::string>());
|
||||
}
|
||||
return Dyn::Join(texts, "\n");
|
||||
}
|
||||
|
||||
// An object key as JSON writes it: a string as it is, null, true and
|
||||
// false as themselves, a number as Dyn::ReprValue prints it.
|
||||
std::string JsonKey(const Json& value) {
|
||||
if (value.is_string()) return value.get<std::string>();
|
||||
if (value.is_null()) return "null";
|
||||
if (value.is_boolean()) return value.get<bool>() ? "true" : "false";
|
||||
if (value.is_number()) return Dyn::ReprValue(value);
|
||||
throw Dyn::Error("TypeError", std::format("unhashable type: '{}'", Dyn::TypeName(value)));
|
||||
}
|
||||
|
||||
// A map key or set member, as text.
|
||||
std::string KeyOf(const Json& value) {
|
||||
if (value.is_array() || value.is_object()) throw Dyn::Error("TypeError", std::format("unhashable type: '{}'", Dyn::TypeName(value)));
|
||||
return DumpCompactSorted(value);
|
||||
}
|
||||
|
||||
const Json& GetOr(const Json& dict, std::string_view key, const Json& fallback) {
|
||||
return Dyn::Has(dict, key) ? Dyn::At(dict, key) : fallback;
|
||||
}
|
||||
|
||||
// `d.get(k, 0) or 0`
|
||||
Json Tokens(const Json& usage, std::string_view key) {
|
||||
const Json zero = 0;
|
||||
const Json& value = GetOr(usage, key, zero);
|
||||
return Dyn::Truthy(value) ? value : zero;
|
||||
}
|
||||
|
||||
// The value as a float: ValueError for text that is no number,
|
||||
// TypeError for anything that is neither.
|
||||
double ToFloat(const Json& value) {
|
||||
if (value.is_number_float()) return value.get<double>();
|
||||
if (value.is_boolean()) return value.get<bool>() ? 1.0 : 0.0;
|
||||
if (value.is_number_unsigned()) return static_cast<double>(value.get<std::uint64_t>());
|
||||
if (value.is_number_integer()) return static_cast<double>(value.get<std::int64_t>());
|
||||
if (value.is_string()) {
|
||||
if (const std::optional<double> parsed = Dyn::ParseFloat(value.get_ref<const std::string&>())) return *parsed;
|
||||
throw Dyn::Error("ValueError", Dyn::FloatError(value.get_ref<const std::string&>()));
|
||||
}
|
||||
throw Dyn::Error("TypeError", std::format("float() argument must be a string or a real number, not '{}'", Dyn::TypeName(value)));
|
||||
}
|
||||
}
|
||||
|
||||
bool IsSqlCall(std::string_view command) {
|
||||
const std::u32string text = Dyn::Decode(command);
|
||||
return HelperCall(text);
|
||||
}
|
||||
|
||||
bool HasAnsweredLine(std::string_view text) {
|
||||
for (std::size_t at = 0; at <= text.size();) {
|
||||
if (text.substr(at).starts_with(PgWire::Answered)) return true;
|
||||
const std::size_t newline = text.find('\n', at);
|
||||
if (newline == std::string_view::npos) break;
|
||||
at = newline + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool LimitText(std::string_view text) {
|
||||
const std::u32string t = Dyn::Decode(text);
|
||||
return ThenOnLine(t, "out of", {"usage"}) || ContainsCi(t, "usage limit") || ContainsCi(t, "quota exceeded") || ContainsCi(t, "rate limit")
|
||||
|| ContainsCi(t, "rate-limit") || ContainsCi(t, "session limit");
|
||||
}
|
||||
|
||||
bool AuthText(std::string_view text) {
|
||||
const std::u32string t = Dyn::Decode(text);
|
||||
return WordNumber(t, U"401") || WordNumber(t, U"403") || ThenOnLine(t, "invalid", {"api key", "token", "credential"})
|
||||
|| ContainsCi(t, "authentication_error") || ContainsCi(t, "authentication error") || ContainsCi(t, "unauthorised") || ContainsCi(t, "unauthorized")
|
||||
|| ThenOnLine(t, "token", {"expired", "revoked"}) || ContainsCi(t, "not logged in") || ContainsCi(t, "/login");
|
||||
}
|
||||
|
||||
bool CreditText(std::string_view text) {
|
||||
const std::u32string t = Dyn::Decode(text);
|
||||
// The last two: OpenRouter's 402.
|
||||
constexpr std::array<std::string_view, 11> Phrases = {
|
||||
"credit balance too low", "credit balance is too low", "add funds",
|
||||
"reached your api usage limits", "reached your specified api usage limits", "reached your workspace api usage limits",
|
||||
"reached your specified workspace api usage limits", "crossed its monthly api usage threshold", "enforced_spend_limit_reached",
|
||||
"insufficient credits", "requires more credits",
|
||||
};
|
||||
return std::ranges::any_of(Phrases, [&](std::string_view phrase) { return ContainsCi(t, phrase); });
|
||||
}
|
||||
|
||||
Json ParseStream(std::string_view text) {
|
||||
Json result;
|
||||
Json rate;
|
||||
Json sessionId;
|
||||
Json init;
|
||||
Json usage = {{"input", 0}, {"cacheCreation", 0}, {"cacheRead", 0}, {"output", 0}};
|
||||
Json first;
|
||||
Json turns = 0;
|
||||
Json toolCalls = Json::object();
|
||||
std::int64_t toolErrors = 0;
|
||||
std::map<std::string, Json> names;
|
||||
std::set<std::string> sqlIds;
|
||||
// The mcp__playwright__* calls and how many the server answered with
|
||||
// an error; the SQL helper's calls and how many reached the database.
|
||||
std::int64_t browserCalls = 0;
|
||||
std::int64_t browserErrors = 0;
|
||||
std::int64_t dbCalls = 0;
|
||||
std::int64_t dbAnswered = 0;
|
||||
for (const std::string& raw : Dyn::Split(text, "\n")) {
|
||||
const std::string line = Dyn::Strip(raw);
|
||||
if (!line.starts_with('{')) continue;
|
||||
Json o;
|
||||
try {
|
||||
o = ParseLoose(line);
|
||||
} catch (const std::exception&) {
|
||||
continue;
|
||||
}
|
||||
if (!o.is_object()) continue;
|
||||
const Json& type = Dyn::Get(o, "type");
|
||||
if (!Dyn::Truthy(sessionId) && Dyn::Get(o, "session_id").is_string()) sessionId = Dyn::At(o, "session_id");
|
||||
if (type == "system" && Dyn::Get(o, "subtype") == "init") {
|
||||
init = o;
|
||||
} else if (type == "result") {
|
||||
result = o;
|
||||
} else if (type == "rate_limit_event") {
|
||||
const Json& info = Dyn::Get(o, "rate_limit_info");
|
||||
if (Dyn::Truthy(info)) rate = info;
|
||||
}
|
||||
const Json& message = Dyn::Get(o, "message");
|
||||
if (!message.is_object() || !Dyn::Truthy(message)) continue;
|
||||
if (type == "assistant") {
|
||||
const Json& u = Dyn::Or(Dyn::Get(message, "usage"), Dyn::EmptyDict());
|
||||
if (Dyn::Truthy(u)) {
|
||||
turns = Dyn::Add(turns, Json(1));
|
||||
usage["input"] = Dyn::Add(usage["input"], Tokens(u, "input_tokens"));
|
||||
usage["cacheCreation"] = Dyn::Add(usage["cacheCreation"], Tokens(u, "cache_creation_input_tokens"));
|
||||
usage["cacheRead"] = Dyn::Add(usage["cacheRead"], Tokens(u, "cache_read_input_tokens"));
|
||||
usage["output"] = Dyn::Add(usage["output"], Tokens(u, "output_tokens"));
|
||||
if (first.is_null()) {
|
||||
first = Json::object();
|
||||
for (const std::string_view key : {"input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens"}) {
|
||||
first[std::string(key)] = Tokens(u, key);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const Json& block : Dyn::Or(Dyn::Get(message, "content"), Dyn::EmptyList())) {
|
||||
if (!block.is_object() || Dyn::Get(block, "type") != "tool_use") continue;
|
||||
const Json& name = Dyn::Get(block, "name");
|
||||
const std::string key = JsonKey(name);
|
||||
toolCalls[key] = Dyn::Add(Dyn::Has(toolCalls, key) ? toolCalls[key] : Json(0), Json(1));
|
||||
names[KeyOf(Dyn::Get(block, "id"))] = name;
|
||||
const Json& input = Dyn::Get(block, "input");
|
||||
const Json command = input.is_object() ? Dyn::Get(Dyn::Or(input, Dyn::EmptyDict()), "command") : Json();
|
||||
if (name == "Bash" && command.is_string() && IsSqlCall(command.get_ref<const std::string&>())) sqlIds.insert(KeyOf(Dyn::Get(block, "id")));
|
||||
}
|
||||
}
|
||||
if (type == "user") {
|
||||
for (const Json& block : Dyn::Or(Dyn::Get(message, "content"), Dyn::EmptyList())) {
|
||||
if (!block.is_object() || Dyn::Get(block, "type") != "tool_result") continue;
|
||||
const bool isError = Dyn::Truthy(Dyn::Get(block, "is_error"));
|
||||
if (isError) ++toolErrors;
|
||||
const std::string id = KeyOf(Dyn::Get(block, "tool_use_id"));
|
||||
const auto named = names.find(id);
|
||||
const std::string name = named == names.end() ? std::string() : Dyn::Str(named->second);
|
||||
if (name.starts_with("mcp__playwright__")) {
|
||||
++browserCalls;
|
||||
if (isError) ++browserErrors;
|
||||
}
|
||||
if (sqlIds.contains(id)) {
|
||||
++dbCalls;
|
||||
if (HasAnsweredLine(ContentText(Dyn::Get(block, "content")))) ++dbAnswered;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Json cost;
|
||||
Json denials = Json::array();
|
||||
Json thinking = 0;
|
||||
if (Dyn::Truthy(result) && Dyn::Get(result, "usage").is_object()) {
|
||||
// The result line's totals are authoritative: stream-json repeats a
|
||||
// turn's usage on every assistant content block, and its
|
||||
// per-message output_tokens are placeholders (2026-09-17 smoke:
|
||||
// summed 2.26M cache reads vs 985K real).
|
||||
const Json& u = Dyn::At(result, "usage");
|
||||
usage = {{"input", Tokens(u, "input_tokens")}, {"cacheCreation", Tokens(u, "cache_creation_input_tokens")},
|
||||
{"cacheRead", Tokens(u, "cache_read_input_tokens")}, {"output", Tokens(u, "output_tokens")}};
|
||||
const Json& details = Dyn::Or(Dyn::Get(u, "output_tokens_details"), Dyn::EmptyDict());
|
||||
thinking = Tokens(details, "thinking_tokens");
|
||||
cost = Dyn::Get(result, "total_cost_usd");
|
||||
for (const Json& d : Dyn::Or(Dyn::Get(result, "permission_denials"), Dyn::EmptyList())) {
|
||||
const Json& input = Dyn::Or(Dyn::Get(d, "tool_input"), Dyn::EmptyDict());
|
||||
const Json& command = Dyn::Get(input, "command");
|
||||
const Json& file = Dyn::Get(input, "file_path");
|
||||
denials.push_back(Dyn::Truthy(command) ? command : (Dyn::Truthy(file) ? file : Dyn::Get(d, "tool_name")));
|
||||
}
|
||||
if (Dyn::IsInt(Dyn::Get(result, "num_turns"))) turns = Dyn::At(result, "num_turns");
|
||||
}
|
||||
usage["thinking"] = thinking;
|
||||
return {
|
||||
{"result", result},
|
||||
{"rateLimit", rate},
|
||||
{"sessionId", sessionId},
|
||||
{"init", init},
|
||||
{"usage", usage},
|
||||
{"firstTurn", first},
|
||||
{"turns", turns},
|
||||
{"toolCalls", toolCalls},
|
||||
{"toolErrors", toolErrors},
|
||||
{"costUsd", cost},
|
||||
{"denials", denials},
|
||||
{"browser", {{"calls", browserCalls}, {"errors", browserErrors}}},
|
||||
{"db", {{"calls", dbCalls}, {"answered", dbAnswered}}},
|
||||
};
|
||||
}
|
||||
|
||||
std::optional<Json> StructuredOutput(const Json& result) {
|
||||
if (!Dyn::Truthy(result)) return std::nullopt;
|
||||
Json inner = Dyn::Get(result, "structured_output");
|
||||
const Json& text = Dyn::Get(result, "result");
|
||||
if (inner.is_null() && text.is_string() && Dyn::Truthy(text)) {
|
||||
try {
|
||||
inner = ParseLoose(text.get_ref<const std::string&>());
|
||||
} catch (const std::exception&) {
|
||||
inner = nullptr;
|
||||
}
|
||||
}
|
||||
if (inner.is_string()) {
|
||||
try {
|
||||
inner = ParseLoose(inner.get<std::string>());
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
if (!inner.is_object() || !Dyn::Get(inner, "findings").is_array()) return std::nullopt;
|
||||
return inner;
|
||||
}
|
||||
|
||||
std::pair<std::string, std::string> Classify(const Json& parsed, std::optional<std::int32_t> exitCode, std::string_view stderrText, bool timedOut) {
|
||||
const Json& result = Dyn::At(parsed, "result");
|
||||
const Json& rate = Dyn::Or(Dyn::At(parsed, "rateLimit"), Dyn::EmptyDict());
|
||||
if (timedOut || exitCode == 124) return {"timeout", "process exceeded its time budget"};
|
||||
// Asked only in its place in the `or`: whether it is asked at all is
|
||||
// part of the classification.
|
||||
auto rejected = [&] { return Dyn::Get(rate, "status") == "rejected"; };
|
||||
if (!Dyn::Truthy(result)) {
|
||||
if (CreditText(stderrText)) return {"credits", "credit balance exhausted (no result line)"};
|
||||
if (rejected() || LimitText(stderrText)) return {"limit", "rate limit (no result line)"};
|
||||
if (AuthText(stderrText)) return {"auth", "authentication failure (no result line)"};
|
||||
return {"error", "no result line - the process did not finish"};
|
||||
}
|
||||
if (Dyn::Truthy(Dyn::Get(result, "is_error"))) {
|
||||
std::vector<std::string> errors;
|
||||
for (const Json& e : Dyn::Or(Dyn::Get(result, "errors"), Dyn::EmptyList())) errors.push_back(Dyn::Str(e));
|
||||
const std::string message = std::format("{} {}", Dyn::StrOr(Dyn::Get(result, "result"), ""), Dyn::Join(errors, " "));
|
||||
const std::string head = Dyn::Slice(message, 0, 200);
|
||||
const Json& status = Dyn::Get(result, "api_error_status");
|
||||
if (CreditText(message)) return {"credits", head};
|
||||
if (Dyn::Equal(status, Json(401)) || Dyn::Equal(status, Json(403)) || AuthText(message)) return {"auth", head};
|
||||
if (Dyn::Equal(status, Json(429)) || LimitText(message) || rejected()) return {"limit", head};
|
||||
const Json& subtype = Dyn::Get(result, "subtype");
|
||||
if (!Dyn::Truthy(subtype)) return {"error", std::format("error: {}", head)};
|
||||
if (!subtype.is_string()) throw Dyn::Error("TypeError", std::format("unsupported operand type(s) for +: '{}' and 'str'", Dyn::TypeName(subtype)));
|
||||
return {"error", std::format("{}: {}", subtype.get<std::string>(), head)};
|
||||
}
|
||||
if (!StructuredOutput(result)) return {"error", "no structured_output in the result envelope"};
|
||||
return {"ok", ""};
|
||||
}
|
||||
|
||||
Json Windows(const Json& rate) {
|
||||
Json out = Json::object();
|
||||
const Json& windows = Dyn::Or(Dyn::Get(Dyn::Or(rate, Dyn::EmptyDict()), "unifiedWindows"), Dyn::EmptyDict());
|
||||
for (auto it = windows.begin(); it != windows.end(); ++it) {
|
||||
const Json& w = it.value();
|
||||
if (!w.is_object()) continue;
|
||||
const Json& u = Dyn::Get(w, "utilization");
|
||||
out[it.key()] = {{"utilization", u.is_null() ? Json() : Json(Dyn::Round(ToFloat(u) * 100.0, 1))}, {"resetsAt", Dyn::Get(w, "resetsAt")}};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
|
@ -205,6 +205,46 @@ namespace Crafter::Review::Dyn {
|
|||
return Encode(std::u32string_view(decoded).substr(static_cast<std::size_t>(from), static_cast<std::size_t>(to - from)));
|
||||
}
|
||||
|
||||
std::pair<char32_t, std::size_t> CodePointAt(std::string_view text, std::size_t at) {
|
||||
return Next(text, at);
|
||||
}
|
||||
|
||||
std::pair<std::size_t, std::size_t> SliceBounds(std::size_t size, std::int64_t start, std::optional<std::int64_t> end) {
|
||||
const auto count = static_cast<std::int64_t>(size);
|
||||
auto clip = [count](std::int64_t index) {
|
||||
if (index < 0) index += count;
|
||||
return std::clamp<std::int64_t>(index, 0, count);
|
||||
};
|
||||
const std::int64_t from = clip(start);
|
||||
const std::int64_t to = end ? clip(*end) : count;
|
||||
return {static_cast<std::size_t>(from), static_cast<std::size_t>(std::max(from, to))};
|
||||
}
|
||||
|
||||
namespace {
|
||||
template <typename Predicate>
|
||||
std::size_t RunOf(std::string_view text, std::size_t at, Predicate matches) {
|
||||
std::size_t end = at;
|
||||
while (end < text.size()) {
|
||||
const auto [c, used] = Next(text, end);
|
||||
if (!matches(c)) break;
|
||||
end += used;
|
||||
}
|
||||
return end - at;
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t DecimalRun(std::string_view text, std::size_t at) {
|
||||
return RunOf(text, at, [](char32_t c) { return IsDecimal(c); });
|
||||
}
|
||||
|
||||
std::size_t SpaceRun(std::string_view text, std::size_t at) {
|
||||
return RunOf(text, at, [](char32_t c) { return IsSpace(c); });
|
||||
}
|
||||
|
||||
std::size_t NonSpaceRun(std::string_view text, std::size_t at) {
|
||||
return RunOf(text, at, [](char32_t c) { return !IsSpace(c); });
|
||||
}
|
||||
|
||||
bool IsSpace(char32_t c) {
|
||||
return std::ranges::binary_search(Unicode::Space, c);
|
||||
}
|
||||
|
|
@ -230,6 +270,10 @@ namespace Crafter::Review::Dyn {
|
|||
return InRuns(Unicode::Printable, c);
|
||||
}
|
||||
|
||||
bool IsWord(char32_t c) {
|
||||
return InRuns(Unicode::Word, c);
|
||||
}
|
||||
|
||||
char IgnoreCaseLetter(char32_t c) {
|
||||
if (c >= 'a' && c <= 'z') return static_cast<char>(c);
|
||||
if (c >= 'A' && c <= 'Z') return static_cast<char>(c - 'A' + 'a');
|
||||
|
|
@ -413,21 +457,305 @@ namespace Crafter::Review::Dyn {
|
|||
return out;
|
||||
}
|
||||
|
||||
std::string LJust(std::string_view text, std::size_t width) {
|
||||
const std::size_t length = Length(text);
|
||||
std::string out(text);
|
||||
if (length < width) out.append(width - length, ' ');
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string ReadText(const std::filesystem::path& path) {
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
if (!in) throw std::runtime_error(std::format("[Errno 2] No such file or directory: {}", Repr(std::string_view(path.string()))));
|
||||
const std::string bytes((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
for (std::size_t at = 0; at < bytes.size();) {
|
||||
const auto [c, used] = Next(bytes, at);
|
||||
if (c == 0xFFFD && (used != 3 || std::string_view(bytes).substr(at, 3) != "\xEF\xBF\xBD")) {
|
||||
throw std::runtime_error(std::format("'utf-8' codec can't decode byte 0x{:02x} in position {}: invalid utf-8 ({})",
|
||||
static_cast<std::uint8_t>(bytes[at]), at, path.string()));
|
||||
}
|
||||
at += used;
|
||||
if (!in || std::filesystem::is_directory(path)) {
|
||||
throw Error("FileNotFoundError", std::format("[Errno 2] No such file or directory: {}", Repr(std::string_view(path.string()))));
|
||||
}
|
||||
const std::string bytes((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
if (const std::optional<std::string> error = Utf8DecodeError(bytes)) throw Error("UnicodeDecodeError", *error);
|
||||
return UniversalNewlines(bytes);
|
||||
}
|
||||
|
||||
std::optional<std::string> Utf8DecodeError(std::string_view bytes) {
|
||||
// The decoder's reasons: a bad lead byte is "invalid start byte"; the
|
||||
// k-th continuation byte out of range is "invalid continuation byte"
|
||||
// over k bytes; the input ending inside a sequence is "unexpected end
|
||||
// of data" over the rest of it.
|
||||
for (std::size_t at = 0; at < bytes.size();) {
|
||||
const auto lead = static_cast<std::uint8_t>(bytes[at]);
|
||||
std::size_t need = 0;
|
||||
std::uint8_t low = 0x80;
|
||||
std::uint8_t high = 0xBF;
|
||||
if (lead < 0x80) {
|
||||
++at;
|
||||
continue;
|
||||
}
|
||||
if (lead >= 0xC2 && lead <= 0xDF) {
|
||||
need = 1;
|
||||
} else if (lead >= 0xE0 && lead <= 0xEF) {
|
||||
need = 2;
|
||||
if (lead == 0xE0) low = 0xA0;
|
||||
if (lead == 0xED) high = 0x9F;
|
||||
} else if (lead >= 0xF0 && lead <= 0xF4) {
|
||||
need = 3;
|
||||
if (lead == 0xF0) low = 0x90;
|
||||
if (lead == 0xF4) high = 0x8F;
|
||||
}
|
||||
std::string_view reason;
|
||||
std::size_t length = 1;
|
||||
if (need == 0) {
|
||||
reason = "invalid start byte";
|
||||
} else {
|
||||
for (std::size_t k = 1; k <= need; ++k) {
|
||||
if (at + k >= bytes.size()) {
|
||||
reason = "unexpected end of data";
|
||||
length = bytes.size() - at;
|
||||
break;
|
||||
}
|
||||
const auto next = static_cast<std::uint8_t>(bytes[at + k]);
|
||||
if (next < low || next > high) {
|
||||
reason = "invalid continuation byte";
|
||||
length = k;
|
||||
break;
|
||||
}
|
||||
low = 0x80;
|
||||
high = 0xBF;
|
||||
}
|
||||
}
|
||||
if (reason.empty()) {
|
||||
at += need + 1;
|
||||
continue;
|
||||
}
|
||||
if (length == 1) return std::format("'utf-8' codec can't decode byte 0x{:02x} in position {}: {}", lead, at, reason);
|
||||
return std::format("'utf-8' codec can't decode bytes in position {}-{}: {}", at, at + length - 1, reason);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
namespace {
|
||||
struct JsonFailure {
|
||||
std::string_view message;
|
||||
std::size_t position;
|
||||
};
|
||||
|
||||
bool IsJsonSpace(char32_t c) {
|
||||
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
|
||||
}
|
||||
|
||||
bool IsJsonDigit(char32_t c) {
|
||||
return c >= '0' && c <= '9';
|
||||
}
|
||||
|
||||
std::int32_t HexDigit(char32_t c) {
|
||||
if (c >= '0' && c <= '9') return static_cast<std::int32_t>(c - '0');
|
||||
if (c >= 'a' && c <= 'f') return static_cast<std::int32_t>(c - 'a' + 10);
|
||||
if (c >= 'A' && c <= 'F') return static_cast<std::int32_t>(c - 'A' + 10);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// A JSON scanner that fails where and why the recorded messages say,
|
||||
// step for step: a string, an object, an array, a number, then any
|
||||
// value. "Expecting value" is a position where no value starts.
|
||||
class JsonScanner {
|
||||
public:
|
||||
explicit JsonScanner(std::u32string_view text) : s(text) {}
|
||||
|
||||
std::optional<JsonFailure> Value(std::size_t idx, std::size_t& next) {
|
||||
if (idx >= s.size()) return JsonFailure{"Expecting value", idx};
|
||||
switch (s[idx]) {
|
||||
case '"':
|
||||
return String(idx + 1, next);
|
||||
case '{':
|
||||
return Object(idx + 1, next);
|
||||
case '[':
|
||||
return Array(idx + 1, next);
|
||||
case 'n':
|
||||
if (Word(idx, U"null", next)) return std::nullopt;
|
||||
break;
|
||||
case 't':
|
||||
if (Word(idx, U"true", next)) return std::nullopt;
|
||||
break;
|
||||
case 'f':
|
||||
if (Word(idx, U"false", next)) return std::nullopt;
|
||||
break;
|
||||
case 'N':
|
||||
if (Word(idx, U"NaN", next)) return std::nullopt;
|
||||
break;
|
||||
case 'I':
|
||||
if (Word(idx, U"Infinity", next)) return std::nullopt;
|
||||
break;
|
||||
case '-':
|
||||
if (Word(idx, U"-Infinity", next)) return std::nullopt;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return Number(idx, next);
|
||||
}
|
||||
|
||||
private:
|
||||
std::u32string_view s;
|
||||
|
||||
bool Word(std::size_t idx, std::u32string_view word, std::size_t& next) const {
|
||||
if (s.substr(idx, word.size()) != word) return false;
|
||||
next = idx + word.size();
|
||||
return true;
|
||||
}
|
||||
|
||||
std::size_t SkipSpace(std::size_t idx) const {
|
||||
while (idx < s.size() && IsJsonSpace(s[idx])) ++idx;
|
||||
return idx;
|
||||
}
|
||||
|
||||
std::optional<JsonFailure> String(std::size_t end, std::size_t& next) const {
|
||||
const std::size_t begin = end - 1;
|
||||
const std::size_t len = s.size();
|
||||
while (true) {
|
||||
std::size_t at = end;
|
||||
char32_t c = 0;
|
||||
for (; at < len; ++at) {
|
||||
c = s[at];
|
||||
if (c == '"' || c == '\\') break;
|
||||
if (c <= 0x1F) return JsonFailure{"Invalid control character at", at};
|
||||
}
|
||||
if (at >= len) return JsonFailure{"Unterminated string starting at", begin};
|
||||
++at;
|
||||
if (c == '"') {
|
||||
next = at;
|
||||
return std::nullopt;
|
||||
}
|
||||
if (at == len) return JsonFailure{"Unterminated string starting at", begin};
|
||||
c = s[at];
|
||||
if (c != 'u') {
|
||||
end = at + 1;
|
||||
if (!std::u32string_view(U"\"\\/bfnrt").contains(c)) return JsonFailure{"Invalid \\escape", end - 2};
|
||||
continue;
|
||||
}
|
||||
++at;
|
||||
end = at + 4;
|
||||
if (end >= len) return JsonFailure{"Invalid \\uXXXX escape", at - 1};
|
||||
std::uint32_t unit = 0;
|
||||
for (; at < end; ++at) {
|
||||
const std::int32_t digit = HexDigit(s[at]);
|
||||
if (digit < 0) return JsonFailure{"Invalid \\uXXXX escape", end - 5};
|
||||
unit = (unit << 4) | static_cast<std::uint32_t>(digit);
|
||||
}
|
||||
if (unit >= 0xD800 && unit <= 0xDBFF && end + 6 < len && s[at] == '\\' && s[at + 1] == 'u') {
|
||||
at += 2;
|
||||
end += 6;
|
||||
std::uint32_t second = 0;
|
||||
for (; at < end; ++at) {
|
||||
const std::int32_t digit = HexDigit(s[at]);
|
||||
if (digit < 0) return JsonFailure{"Invalid \\uXXXX escape", end - 5};
|
||||
second = (second << 4) | static_cast<std::uint32_t>(digit);
|
||||
}
|
||||
if (second < 0xDC00 || second > 0xDFFF) end -= 6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<JsonFailure> Object(std::size_t idx, std::size_t& next) {
|
||||
idx = SkipSpace(idx);
|
||||
if (idx >= s.size() || s[idx] != '}') {
|
||||
while (true) {
|
||||
if (idx >= s.size() || s[idx] != '"') return JsonFailure{"Expecting property name enclosed in double quotes", idx};
|
||||
std::size_t after = 0;
|
||||
if (std::optional<JsonFailure> failure = String(idx + 1, after)) return failure;
|
||||
idx = SkipSpace(after);
|
||||
if (idx >= s.size() || s[idx] != ':') return JsonFailure{"Expecting ':' delimiter", idx};
|
||||
idx = SkipSpace(idx + 1);
|
||||
if (std::optional<JsonFailure> failure = Value(idx, after)) return failure;
|
||||
idx = SkipSpace(after);
|
||||
if (idx < s.size() && s[idx] == '}') break;
|
||||
if (idx >= s.size() || s[idx] != ',') return JsonFailure{"Expecting ',' delimiter", idx};
|
||||
const std::size_t comma = idx;
|
||||
idx = SkipSpace(idx + 1);
|
||||
if (idx < s.size() && s[idx] == '}') return JsonFailure{"Illegal trailing comma before end of object", comma};
|
||||
}
|
||||
}
|
||||
next = idx + 1;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<JsonFailure> Array(std::size_t idx, std::size_t& next) {
|
||||
idx = SkipSpace(idx);
|
||||
if (idx >= s.size() || s[idx] != ']') {
|
||||
while (true) {
|
||||
std::size_t after = 0;
|
||||
if (std::optional<JsonFailure> failure = Value(idx, after)) return failure;
|
||||
idx = SkipSpace(after);
|
||||
if (idx < s.size() && s[idx] == ']') break;
|
||||
if (idx >= s.size() || s[idx] != ',') return JsonFailure{"Expecting ',' delimiter", idx};
|
||||
const std::size_t comma = idx;
|
||||
idx = SkipSpace(idx + 1);
|
||||
if (idx < s.size() && s[idx] == ']') return JsonFailure{"Illegal trailing comma before end of array", comma};
|
||||
}
|
||||
}
|
||||
next = idx + 1;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<JsonFailure> Number(std::size_t start, std::size_t& next) const {
|
||||
const std::size_t len = s.size();
|
||||
std::size_t idx = start;
|
||||
if (s[idx] == '-') {
|
||||
++idx;
|
||||
if (idx >= len) return JsonFailure{"Expecting value", start};
|
||||
}
|
||||
if (s[idx] >= '1' && s[idx] <= '9') {
|
||||
++idx;
|
||||
while (idx < len && IsJsonDigit(s[idx])) ++idx;
|
||||
} else if (s[idx] == '0') {
|
||||
++idx;
|
||||
} else {
|
||||
return JsonFailure{"Expecting value", start};
|
||||
}
|
||||
if (idx + 1 < len && s[idx] == '.' && IsJsonDigit(s[idx + 1])) {
|
||||
idx += 2;
|
||||
while (idx < len && IsJsonDigit(s[idx])) ++idx;
|
||||
}
|
||||
if (idx + 1 < len && (s[idx] == 'e' || s[idx] == 'E')) {
|
||||
const std::size_t exponent = idx;
|
||||
++idx;
|
||||
if (idx + 1 < len && (s[idx] == '-' || s[idx] == '+')) ++idx;
|
||||
while (idx < len && IsJsonDigit(s[idx])) ++idx;
|
||||
if (!IsJsonDigit(s[idx - 1])) idx = exponent;
|
||||
}
|
||||
next = idx;
|
||||
return std::nullopt;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
std::optional<std::string> JsonDecodeError(std::string_view text) {
|
||||
const std::u32string s = Decode(text);
|
||||
JsonScanner scanner(s);
|
||||
std::size_t start = 0;
|
||||
while (start < s.size() && IsJsonSpace(s[start])) ++start;
|
||||
std::size_t end = 0;
|
||||
std::optional<JsonFailure> failure;
|
||||
if (s.starts_with(U'\uFEFF')) {
|
||||
failure = JsonFailure{"Unexpected UTF-8 BOM (decode using utf-8-sig)", 0};
|
||||
} else {
|
||||
failure = scanner.Value(start, end);
|
||||
}
|
||||
if (!failure) {
|
||||
while (end < s.size() && IsJsonSpace(s[end])) ++end;
|
||||
if (end != s.size()) failure = JsonFailure{"Extra data", end};
|
||||
}
|
||||
if (!failure) return std::nullopt;
|
||||
const std::size_t pos = failure->position;
|
||||
const std::u32string_view before = std::u32string_view(s).substr(0, pos);
|
||||
const auto line = std::ranges::count(before, U'\n') + 1;
|
||||
const std::size_t lastNewline = before.rfind(U'\n');
|
||||
const std::size_t column = lastNewline == std::u32string_view::npos ? pos + 1 : pos - lastNewline;
|
||||
return std::format("{}: line {} column {} (char {})", failure->message, line, column, pos);
|
||||
}
|
||||
|
||||
Json LoadJsonFile(const std::filesystem::path& path) {
|
||||
const std::string text = ReadText(path);
|
||||
if (const std::optional<std::string> error = JsonDecodeError(text)) throw Error("JSONDecodeError", *error);
|
||||
return ParseLoose(text);
|
||||
}
|
||||
|
||||
std::string UniversalNewlines(std::string_view text) {
|
||||
if (!text.contains('\r')) return std::string(text);
|
||||
std::string out;
|
||||
|
|
@ -933,6 +1261,29 @@ namespace Crafter::Review::Dyn {
|
|||
return parts;
|
||||
}
|
||||
|
||||
std::string UrlUnsplit(std::string_view scheme, std::string_view netloc, std::string_view path, std::string_view query, std::string_view fragment) {
|
||||
// The schemes that get `//` before an empty netloc.
|
||||
constexpr std::array<std::string_view, 27> UsesNetloc = {
|
||||
"", "ftp", "http", "gopher", "nntp", "telnet", "imap", "wais", "file", "mms", "https", "shttp", "snews", "prospero",
|
||||
"rtsp", "rtsps", "rtspu", "rsync", "svn", "svn+ssh", "sftp", "nfs", "git", "git+ssh", "ws", "wss", "itms-services",
|
||||
};
|
||||
bool hasNetloc = !netloc.empty();
|
||||
if (!hasNetloc && !scheme.empty() && std::ranges::contains(UsesNetloc, scheme) && (path.empty() || path.starts_with('/'))) {
|
||||
hasNetloc = true;
|
||||
}
|
||||
std::string url(path);
|
||||
if (hasNetloc) {
|
||||
if (!url.empty() && !url.starts_with('/')) url.insert(0, "/");
|
||||
url = std::format("//{}{}", netloc, url);
|
||||
} else if (url.starts_with("//")) {
|
||||
url.insert(0, "//");
|
||||
}
|
||||
if (!scheme.empty()) url = std::format("{}:{}", scheme, url);
|
||||
if (!query.empty()) url = std::format("{}?{}", url, query);
|
||||
if (!fragment.empty()) url = std::format("{}#{}", url, fragment);
|
||||
return url;
|
||||
}
|
||||
|
||||
std::string Unquote(std::string_view text) {
|
||||
if (!text.contains('%')) return std::string(text);
|
||||
// Percent sequences become bytes; runs of bytes are decoded as UTF-8
|
||||
|
|
@ -1058,4 +1409,203 @@ namespace Crafter::Review::Dyn {
|
|||
std::string ErrnoText(std::int32_t code) {
|
||||
return std::format("[Errno {}] {}", code, std::strerror(code));
|
||||
}
|
||||
|
||||
Error::Error(std::string_view kind, const std::string& message) : std::runtime_error(message), kind(kind) {}
|
||||
|
||||
const std::string& Error::Kind() const {
|
||||
return kind;
|
||||
}
|
||||
|
||||
bool Truthy(const Json& value) {
|
||||
switch (value.type()) {
|
||||
case Json::value_t::null:
|
||||
return false;
|
||||
case Json::value_t::boolean:
|
||||
return value.get<bool>();
|
||||
case Json::value_t::number_integer:
|
||||
return value.get<std::int64_t>() != 0;
|
||||
case Json::value_t::number_unsigned:
|
||||
return value.get<std::uint64_t>() != 0;
|
||||
case Json::value_t::number_float:
|
||||
// NaN is true: it is not 0.0.
|
||||
return value.get<double>() != 0.0;
|
||||
case Json::value_t::string:
|
||||
return !value.get_ref<const std::string&>().empty();
|
||||
case Json::value_t::array:
|
||||
case Json::value_t::object:
|
||||
return !value.empty();
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const Json& Or(const Json& value, const Json& fallback) {
|
||||
return Truthy(value) ? value : fallback;
|
||||
}
|
||||
|
||||
const Json& EmptyDict() {
|
||||
static const Json empty = Json::object();
|
||||
return empty;
|
||||
}
|
||||
|
||||
const Json& EmptyList() {
|
||||
static const Json empty = Json::array();
|
||||
return empty;
|
||||
}
|
||||
|
||||
bool Has(const Json& dict, std::string_view key) {
|
||||
return dict.is_object() && dict.find(key) != dict.end();
|
||||
}
|
||||
|
||||
const Json& Get(const Json& dict, std::string_view key) {
|
||||
static const Json none;
|
||||
if (!dict.is_object()) throw Error("AttributeError", std::format("'{}' object has no attribute 'get'", TypeName(dict)));
|
||||
const auto found = dict.find(key);
|
||||
return found == dict.end() ? none : *found;
|
||||
}
|
||||
|
||||
const Json& At(const Json& dict, std::string_view key) {
|
||||
if (dict.is_object()) {
|
||||
const auto found = dict.find(key);
|
||||
if (found == dict.end()) throw Error("KeyError", Repr(key));
|
||||
return *found;
|
||||
}
|
||||
if (dict.is_array()) throw Error("TypeError", "list indices must be integers or slices, not str");
|
||||
if (dict.is_string()) throw Error("TypeError", "string indices must be integers, not 'str'");
|
||||
throw Error("TypeError", std::format("'{}' object is not subscriptable", TypeName(dict)));
|
||||
}
|
||||
|
||||
std::string_view TypeName(const Json& value) {
|
||||
switch (value.type()) {
|
||||
case Json::value_t::null:
|
||||
return "NoneType";
|
||||
case Json::value_t::boolean:
|
||||
return "bool";
|
||||
case Json::value_t::number_integer:
|
||||
case Json::value_t::number_unsigned:
|
||||
return "int";
|
||||
case Json::value_t::number_float:
|
||||
return "float";
|
||||
case Json::value_t::string:
|
||||
return "str";
|
||||
case Json::value_t::array:
|
||||
return "list";
|
||||
case Json::value_t::object:
|
||||
return "dict";
|
||||
default:
|
||||
return "bytes";
|
||||
}
|
||||
}
|
||||
|
||||
bool IsInt(const Json& value) {
|
||||
return value.is_boolean() || value.is_number_integer();
|
||||
}
|
||||
|
||||
bool IsNumber(const Json& value) {
|
||||
return value.is_boolean() || value.is_number();
|
||||
}
|
||||
|
||||
std::string Str(const Json& value) {
|
||||
if (value.is_string()) return value.get<std::string>();
|
||||
return ReprValue(value);
|
||||
}
|
||||
|
||||
std::string StrOr(const Json& value, std::string_view fallback) {
|
||||
return Truthy(value) ? Str(value) : std::string(fallback);
|
||||
}
|
||||
|
||||
namespace {
|
||||
// An int of a JSON value: a bool is 0 or 1. Unsigned values beyond
|
||||
// the signed range keep their own type in Equal().
|
||||
std::int64_t IntOf(const Json& value) {
|
||||
if (value.is_boolean()) return value.get<bool>() ? 1 : 0;
|
||||
if (value.is_number_unsigned()) return static_cast<std::int64_t>(value.get<std::uint64_t>());
|
||||
return value.get<std::int64_t>();
|
||||
}
|
||||
|
||||
// An integer equals a float exactly, never by rounding the integer to
|
||||
// a double.
|
||||
bool IntEqualsFloat(const Json& integer, double f) {
|
||||
if (!std::isfinite(f) || f != std::floor(f)) return false;
|
||||
if (integer.is_number_unsigned() && integer.get<std::uint64_t>() > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max())) {
|
||||
if (f < 0.0 || f >= 18446744073709551616.0) return false;
|
||||
return static_cast<std::uint64_t>(f) == integer.get<std::uint64_t>();
|
||||
}
|
||||
if (f < -9223372036854775808.0 || f >= 9223372036854775808.0) return false;
|
||||
return static_cast<std::int64_t>(f) == IntOf(integer);
|
||||
}
|
||||
}
|
||||
|
||||
bool Equal(const Json& a, const Json& b) {
|
||||
if (IsNumber(a) && IsNumber(b)) {
|
||||
if (a.is_number_float() && b.is_number_float()) return a.get<double>() == b.get<double>();
|
||||
if (a.is_number_float()) return IntEqualsFloat(b, a.get<double>());
|
||||
if (b.is_number_float()) return IntEqualsFloat(a, b.get<double>());
|
||||
const bool bigA = a.is_number_unsigned() && a.get<std::uint64_t>() > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max());
|
||||
const bool bigB = b.is_number_unsigned() && b.get<std::uint64_t>() > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max());
|
||||
if (bigA || bigB) return bigA && bigB && a.get<std::uint64_t>() == b.get<std::uint64_t>();
|
||||
return IntOf(a) == IntOf(b);
|
||||
}
|
||||
if (a.type() != b.type()) return false;
|
||||
if (a.is_array()) {
|
||||
if (a.size() != b.size()) return false;
|
||||
for (std::size_t i = 0; i < a.size(); ++i) {
|
||||
if (!Equal(a[i], b[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (a.is_object()) {
|
||||
if (a.size() != b.size()) return false;
|
||||
for (auto it = a.begin(); it != a.end(); ++it) {
|
||||
const auto other = b.find(it.key());
|
||||
if (other == b.end() || !Equal(it.value(), *other)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return a == b;
|
||||
}
|
||||
|
||||
bool In(const Json& item, const Json& container) {
|
||||
if (container.is_array()) {
|
||||
return std::ranges::any_of(container, [&](const Json& element) { return Equal(item, element); });
|
||||
}
|
||||
if (container.is_object()) {
|
||||
if (item.is_array() || item.is_object()) throw Error("TypeError", std::format("unhashable type: '{}'", TypeName(item)));
|
||||
return item.is_string() && container.find(item.get_ref<const std::string&>()) != container.end();
|
||||
}
|
||||
if (container.is_string()) {
|
||||
if (!item.is_string()) throw Error("TypeError", std::format("'in <string>' requires string as left operand, not {}", TypeName(item)));
|
||||
return container.get_ref<const std::string&>().contains(item.get_ref<const std::string&>());
|
||||
}
|
||||
throw Error("TypeError", std::format("argument of type '{}' is not a container or iterable", TypeName(container)));
|
||||
}
|
||||
|
||||
Json Add(const Json& a, const Json& b) {
|
||||
if (!IsNumber(a) || !IsNumber(b)) {
|
||||
throw Error("TypeError", std::format("unsupported operand type(s) for +: '{}' and '{}'", TypeName(a), TypeName(b)));
|
||||
}
|
||||
if (a.is_number_float() || b.is_number_float()) {
|
||||
auto asDouble = [](const Json& value) { return value.is_number_float() ? value.get<double>() : static_cast<double>(IntOf(value)); };
|
||||
return Json(asDouble(a) + asDouble(b));
|
||||
}
|
||||
return Json(IntOf(a) + IntOf(b));
|
||||
}
|
||||
|
||||
double Sum(std::span<const double> values) {
|
||||
if (values.empty()) return 0.0;
|
||||
// sum() starts from the int 0; 0 + x is x (and 0.0 for -0.0).
|
||||
double total = 0.0 + values.front();
|
||||
double compensation = 0.0;
|
||||
for (const double x : values.subspan(1)) {
|
||||
const double t = total + x;
|
||||
if (std::fabs(total) >= std::fabs(x)) {
|
||||
compensation += (total - t) + x;
|
||||
} else {
|
||||
compensation += (x - t) + total;
|
||||
}
|
||||
total = t;
|
||||
}
|
||||
if (compensation != 0.0 && std::isfinite(compensation)) total += compensation;
|
||||
return total;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
71
implementations/Crafter.Review-Tools.cpp
Normal file
71
implementations/Crafter.Review-Tools.cpp
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module Crafter.Review:Tools_impl;
|
||||
import :Tools;
|
||||
import std;
|
||||
|
||||
namespace Crafter::Review::Tools {
|
||||
std::vector<std::string> McpToolNames() {
|
||||
std::vector<std::string> out;
|
||||
for (const std::string_view tool : McpTools) out.push_back(std::format("mcp__{}__{}", McpServer, tool));
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<std::string> McpDeniedToolNames() {
|
||||
std::vector<std::string> out;
|
||||
for (const std::string_view tool : McpDenied) out.push_back(std::format("mcp__{}__{}", McpServer, tool));
|
||||
return out;
|
||||
}
|
||||
|
||||
const std::vector<std::string>& Deny() {
|
||||
static const std::vector<std::string> deny = [] {
|
||||
std::vector<std::string> out = {
|
||||
"Edit", "Write", "MultiEdit", "NotebookEdit", "WebFetch", "WebSearch", "Task", "Agent", "TodoWrite",
|
||||
"Bash(ssh:*)", "Bash(adb:*)", "Bash(rm:*)", "Bash(mv:*)", "Bash(cp:*)", "Bash(git push:*)", "Bash(git commit:*)",
|
||||
"Bash(git checkout:*)", "Bash(git reset:*)", "Bash(git am:*)", "Bash(make:*)", "Bash(npm:*)", "Bash(npx:*)", "Bash(node:*)",
|
||||
"Bash(supabase:*)", "Bash(docker:*)", "Bash(podman:*)", "Bash(psql:*)",
|
||||
};
|
||||
std::ranges::move(McpDeniedToolNames(), std::back_inserter(out));
|
||||
return out;
|
||||
}();
|
||||
return deny;
|
||||
}
|
||||
|
||||
const std::vector<std::string>& BaseAllow() {
|
||||
static const std::vector<std::string> allow = [] {
|
||||
std::vector<std::string> out = {
|
||||
"Read", "Glob", "Grep", "Bash(cat:*)", "Bash(rg:*)", "Bash(grep:*)", "Bash(wc:*)", "Bash(head:*)", "Bash(tail:*)", "Bash(sed -n:*)",
|
||||
"Bash(ls:*)", "Bash(find:*)", "Bash(diff:*)", "Bash(sha256sum:*)", "Bash(sort:*)", "Bash(uniq:*)", "Bash(cut:*)", "Bash(awk:*)",
|
||||
"Bash(echo:*)", "Bash(printf:*)", "Bash(cd:*)", "Bash(python3 -:*)",
|
||||
};
|
||||
for (const std::string_view verb : GitReadOnly) out.push_back(std::format("Bash(git {}:*)", verb));
|
||||
return out;
|
||||
}();
|
||||
return allow;
|
||||
}
|
||||
|
||||
namespace {
|
||||
// re.match(r'^Bash\((.+):\*\)$', tool).group(1): the prefix of a
|
||||
// Bash(<prefix>:*) entry. `.` stops at a newline and `$` also matches
|
||||
// before a final one, so a prefix never holds a newline.
|
||||
std::optional<std::string_view> BashPrefix(std::string_view tool) {
|
||||
std::string_view body = tool;
|
||||
if (body.ends_with('\n')) body.remove_suffix(1);
|
||||
if (body.size() < 9 || !body.starts_with("Bash(") || !body.ends_with(":*)")) return std::nullopt;
|
||||
const std::string_view prefix = body.substr(5, body.size() - 8);
|
||||
if (prefix.contains('\n')) return std::nullopt;
|
||||
return prefix;
|
||||
}
|
||||
}
|
||||
|
||||
bool Denied(std::string_view tool) {
|
||||
if (std::ranges::contains(Deny(), tool)) return true;
|
||||
const std::optional<std::string_view> prefix = BashPrefix(tool);
|
||||
if (!prefix) return false;
|
||||
return std::ranges::any_of(Deny(), [&](const std::string& entry) {
|
||||
const std::optional<std::string_view> denied = BashPrefix(entry);
|
||||
return denied && (*prefix == *denied || prefix->starts_with(std::format("{} ", *denied)));
|
||||
});
|
||||
}
|
||||
}
|
||||
36
interfaces/Crafter.Review-Artifact.cppm
Normal file
36
interfaces/Crafter.Review-Artifact.cppm
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Artifact;
|
||||
import std;
|
||||
|
||||
// The frozen artifact and the tree it was cut from: the hash formula, the
|
||||
// HEAD a format-patch export names, the tree checks.
|
||||
export namespace Crafter::Review::Artifact {
|
||||
std::string Sha256File(const std::filesystem::path& path);
|
||||
// reply: the sha256 of the draft file; series and commits: the sha256 of
|
||||
// the sorted *.patch files concatenated (`cat $(ls *.patch | sort) |
|
||||
// sha256sum`).
|
||||
std::string ArtifactHash(std::string_view mode, const std::filesystem::path& path);
|
||||
// The *.patch names in the directory, sorted by code point.
|
||||
std::vector<std::string> PatchFiles(const std::filesystem::path& path);
|
||||
// K of a format-patch file name, ^(?:v\d+-)?(\d{4})-: 1 for
|
||||
// 0001-x.patch and v2-0001-x.patch; nullopt for a name without one.
|
||||
std::optional<std::int64_t> PatchNumber(std::string_view name);
|
||||
// {K: text} of the export, each patch read as Dyn::ReadText reads a file
|
||||
// (strict UTF-8, universal newlines). Dyn::Error (AttributeError) for a
|
||||
// patch name without a number.
|
||||
std::map<std::int64_t, std::string> PatchTexts(const std::filesystem::path& path);
|
||||
// The commit the last patch was cut from (its `From <sha>` line): the
|
||||
// range HEAD.
|
||||
std::optional<std::string> PatchHead(const std::filesystem::path& path);
|
||||
|
||||
// `git -C <tree> <args>`'s stdout; Dyn::Error (RuntimeError) with git's
|
||||
// message when it fails.
|
||||
std::string Git(const std::filesystem::path& tree, std::span<const std::string> args);
|
||||
bool IsToplevel(const std::filesystem::path& tree);
|
||||
std::string TreeHead(const std::filesystem::path& tree);
|
||||
// Tracked changes only (untracked files never reach a commit); "" when
|
||||
// clean.
|
||||
std::string TreeDirty(const std::filesystem::path& tree);
|
||||
}
|
||||
69
interfaces/Crafter.Review-Config.cppm
Normal file
69
interfaces/Crafter.Review-Config.cppm
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Config;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// The consumer's configuration: `.review-gates/config.json` at the
|
||||
// repository root (`--config` names another file). It holds what the
|
||||
// pipeline must know about THIS repository — who may author its commits,
|
||||
// which branch a range is measured against, which lenses run and the
|
||||
// environment each gets, how its application is started and reached, where
|
||||
// its local database answers, which paths carry no runtime behaviour — and
|
||||
// nothing about any one review. A missing file is the defaults; an unknown
|
||||
// key or a malformed value is a preflight failure, and a retired key a
|
||||
// warning. The config stays the JSON it was read as, keys in their order.
|
||||
export namespace Crafter::Review::Config {
|
||||
constexpr std::string_view ConfigDir = ".review-gates";
|
||||
constexpr std::string_view ConfigFile = ".review-gates/config.json";
|
||||
constexpr std::string_view SlotFile = "slot.json";
|
||||
|
||||
// DEFAULTS, a fresh copy each call.
|
||||
Json Defaults();
|
||||
|
||||
struct Loaded {
|
||||
Json config;
|
||||
std::vector<std::string> problems;
|
||||
};
|
||||
// The defaults, the file's values merged over them, and every problem
|
||||
// Validate finds. A retired key is no problem: it is dropped, and
|
||||
// config["_warnings"] says so and what replaced it — a key the pipeline
|
||||
// stopped reading must not stop a consumer's freeze or run (2026-10-22).
|
||||
// `path` empty: <repo>/.review-gates/config.json.
|
||||
Loaded Load(const std::filesystem::path& repo, const std::filesystem::path& path = {});
|
||||
std::vector<std::string> Validate(const Json& config);
|
||||
// The config for a dump: the database URL with its password masked, no
|
||||
// `_` bookkeeping keys.
|
||||
Json Redacted(const Json& config);
|
||||
// The emails the freeze accepts: the configured list, else the
|
||||
// repository's git identity.
|
||||
std::vector<std::string> Authors(const Json& config, const std::filesystem::path& repo);
|
||||
std::string GitUserEmail(const std::filesystem::path& repo);
|
||||
// The lens files the config turns off (lenses.<name>.run = false), in gate
|
||||
// order.
|
||||
std::vector<std::string> LensesOff(const Json& config);
|
||||
// {lens file: environment} for every lens of the table, as the config
|
||||
// holds it (validated elsewhere).
|
||||
Json Environments(const Json& config);
|
||||
|
||||
struct Slots {
|
||||
// pool.Stacks entries {id, appUrl, apiUrls, dbUrl, login, slot: true},
|
||||
// in slot order.
|
||||
Json stacks = Json::array();
|
||||
std::vector<std::string> problems;
|
||||
};
|
||||
// The slots that are up: slots.dir/<n>/slot.json.
|
||||
Slots SlotStacks(const Json& config, const std::filesystem::path& repo);
|
||||
// slots.start or slots.stop for the slot numbers given, {n} filled.
|
||||
std::vector<std::string> SlotCommands(const Json& config, std::string_view which, std::span<const std::int64_t> slots);
|
||||
// The first login fixture that exists, relative to the repository root.
|
||||
std::optional<std::string> LoginFixture(const Json& config, const std::filesystem::path& repo);
|
||||
// The example a consumer starts from (process/templates/config.json is
|
||||
// this, rendered).
|
||||
Json Example();
|
||||
|
||||
// `crafter-review [--config F] config`: the merged config, its warnings
|
||||
// and its problems; exit 1 when there is a problem.
|
||||
std::int32_t Main(const std::filesystem::path& repo, const std::filesystem::path& path);
|
||||
}
|
||||
|
|
@ -20,6 +20,11 @@ export namespace Crafter::Review {
|
|||
// the first log line of a run and `--version`.
|
||||
std::string DriverLine();
|
||||
|
||||
// How a person runs this binary, for the command lines it prints: `flatpak
|
||||
// run net.catcrafts.CrafterReview` in the Flatpak, the binary's absolute
|
||||
// path otherwise.
|
||||
std::string Invocation();
|
||||
|
||||
// Where the lens texts, the procedure and the templates are: the
|
||||
// directory that holds process/. In this order:
|
||||
// - CRAFTER_REVIEW_HOME, natively only: a host setting must not swap the
|
||||
|
|
|
|||
21
interfaces/Crafter.Review-Dispositions.cppm
Normal file
21
interfaces/Crafter.Review-Dispositions.cppm
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Dispositions;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// The disposition register: which entries are in force (a hash match),
|
||||
// carried (every anchor text still occurs its recorded number of times) or
|
||||
// lapsed, and the DISPOSITIONS IN FORCE prompt block. Entries are the
|
||||
// owner's JSON, kept as it is.
|
||||
export namespace Crafter::Review::Dispositions {
|
||||
// The register's entries with an id; empty `path`: none.
|
||||
std::vector<Json> Load(std::string_view path);
|
||||
// [{id, status, detail}], statuses in-force | carried | lapsed.
|
||||
std::vector<Json> Classify(std::span<const Json> entries, std::string_view hash, const std::filesystem::path& artifact);
|
||||
// The entries the rows say are in force or carried.
|
||||
std::vector<Json> InForce(std::span<const Json> entries, std::span<const Json> rows);
|
||||
// The DISPOSITIONS IN FORCE block for one lens.
|
||||
std::string Block(std::span<const Json> inForce, std::span<const Json> rows, std::string_view lensFile, std::string_view hash);
|
||||
}
|
||||
72
interfaces/Crafter.Review-Inventory.cppm
Normal file
72
interfaces/Crafter.Review-Inventory.cppm
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Inventory;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// The partition of a frozen commit range — a `git format-patch` export — into
|
||||
// review units for the coverage contract. It is MECHANICAL: no agent decides
|
||||
// what the units are. Every non-blank line of the artifact belongs to
|
||||
// exactly one unit, and the inventory fails when that does not hold. Fixed
|
||||
// slots give what is NOT in the text a row of the coverage matrix too.
|
||||
//
|
||||
// Units (ids):
|
||||
// pK:subject commit K's subject
|
||||
// pK:msg commit K's message body (before the trailers), when not empty
|
||||
// pK:trailers commit K's trailer block, when not empty
|
||||
// pK:diffstat commit K's diffstat
|
||||
// pK:<file>#hdr the diff header of <file> in commit K (mode, rename, blobs)
|
||||
// pK:<file>#H hunk H of <file> in commit K; a hunk of a documentation file
|
||||
// that holds more than one heading-delimited part is cut into
|
||||
// #H.1, #H.2, ... (DocParts)
|
||||
// pK:outside fixed slot: the in-repository users and callers of what
|
||||
// commit K changes, outside its diff
|
||||
// pK:absent fixed slot: what a reviewer expects in commit K and does not
|
||||
// find
|
||||
// whole:* fixed slots (WholeCommits)
|
||||
export namespace Crafter::Review::Inventory {
|
||||
struct WholeSlot {
|
||||
std::string_view id;
|
||||
std::string_view description;
|
||||
};
|
||||
constexpr std::array<WholeSlot, 3> WholeCommits = {{
|
||||
{"whole:order", "commit ordering and bisectability — each commit a self-contained step that leaves the repository consistent (no later commit in the range repairs an earlier one, nothing is used before the commit that adds it), the declared base"},
|
||||
{"whole:absent", "what a reviewer of this repository expects the range to contain and it does not — a test, a version/changelog bump, a doc or packaging update, a migration for existing installs, a message for a body-less commit"},
|
||||
{"whole:behaviour", "the user-visible behaviour of the range, exercised end to end in the running application — every behaviour the code and the messages promise, as a user sees it; the flows the range touches and the adjacent flows that share what it changes; what a user expects the range to deliver and does not get"},
|
||||
}};
|
||||
|
||||
// [a, b) is one hunk of a Markdown file, lines[a] its @@ line: its
|
||||
// partition at the headings on the new side of the diff, outside fenced
|
||||
// code blocks, once the part before holds anything but headings.
|
||||
std::vector<std::pair<std::size_t, std::size_t>> DocParts(std::span<const std::string> lines, std::size_t a, std::size_t b);
|
||||
// The first non-blank line, stripped and cut to 90 code points.
|
||||
std::string Excerpt(std::span<const std::string> lines);
|
||||
|
||||
struct Series {
|
||||
// Every patch's lines, one after the other: what unit lines number.
|
||||
std::vector<std::string> lines;
|
||||
// Units ({id, lines, excerpt}), the whole slots not yet among them.
|
||||
Json units;
|
||||
};
|
||||
Series PartitionSeries(const std::filesystem::path& dir, bool splitDocs = true);
|
||||
|
||||
// A partition that broke the invariant.
|
||||
class InvariantError : public std::runtime_error {
|
||||
public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
struct Built {
|
||||
// What `inventory commits <dir>` prints: {mode, artifact, hash8,
|
||||
// units, invariant, count}.
|
||||
Json out;
|
||||
std::vector<std::string> lines;
|
||||
};
|
||||
// `artifact` is kept as it is spelled: the inventory records it so.
|
||||
Built Build(std::string_view mode, std::string_view artifact);
|
||||
|
||||
// `crafter-review inventory commits <dir>`: the partition as indented
|
||||
// JSON on stdout. Exit 1 on a broken invariant or a bad command line.
|
||||
std::int32_t Main(std::span<const std::string_view> args);
|
||||
}
|
||||
|
|
@ -37,6 +37,56 @@ export namespace Crafter::Review {
|
|||
return sorted.dump(-1, ' ', true, nlohmann::json::error_handler_t::replace);
|
||||
}
|
||||
|
||||
// What another program wrote — a line of the claude stream, a shared
|
||||
// file — read leniently: an escaped lone surrogate ("\ud800" with no low
|
||||
// half after it), which nlohmann refuses, is read as U+FFFD.
|
||||
inline Json ParseLoose(std::string_view text) {
|
||||
try {
|
||||
return Json::parse(text);
|
||||
} catch (const nlohmann::json::parse_error&) {
|
||||
auto hexAt = [&](std::size_t at) -> std::int32_t {
|
||||
if (at + 4 > text.size()) return -1;
|
||||
std::int32_t value = 0;
|
||||
for (std::size_t i = at; i < at + 4; ++i) {
|
||||
const char c = text[i];
|
||||
const std::int32_t digit = c >= '0' && c <= '9' ? c - '0' : (c >= 'a' && c <= 'f' ? c - 'a' + 10 : (c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1));
|
||||
if (digit < 0) return -1;
|
||||
value = value * 16 + digit;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
std::string fixed;
|
||||
bool changed = false;
|
||||
for (std::size_t at = 0; at < text.size();) {
|
||||
if (text[at] != '\\' || at + 1 >= text.size()) {
|
||||
fixed.push_back(text[at++]);
|
||||
continue;
|
||||
}
|
||||
if (text[at + 1] != 'u') {
|
||||
fixed.append(text.substr(at, 2));
|
||||
at += 2;
|
||||
continue;
|
||||
}
|
||||
const std::int32_t unit = hexAt(at + 2);
|
||||
const bool high = unit >= 0xD800 && unit <= 0xDBFF;
|
||||
const bool low = unit >= 0xDC00 && unit <= 0xDFFF;
|
||||
if (high && at + 12 <= text.size() && text[at + 6] == '\\' && text[at + 7] == 'u' && hexAt(at + 8) >= 0xDC00 && hexAt(at + 8) <= 0xDFFF) {
|
||||
fixed.append(text.substr(at, 12));
|
||||
at += 12;
|
||||
} else if (high || low) {
|
||||
fixed += "\\ufffd";
|
||||
changed = true;
|
||||
at += 6;
|
||||
} else {
|
||||
fixed.append(text.substr(at, 2));
|
||||
at += 2;
|
||||
}
|
||||
}
|
||||
if (!changed) throw;
|
||||
return Json::parse(fixed);
|
||||
}
|
||||
}
|
||||
|
||||
// On one line, with ", " and ": " between items: where a reader matches
|
||||
// on the bytes, such as the first line of an opencode output, `{"type":
|
||||
// "review_gates_meta", …`, which salvage looks for.
|
||||
|
|
|
|||
41
interfaces/Crafter.Review-Normalize.cppm
Normal file
41
interfaces/Crafter.Review-Normalize.cppm
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Normalize;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// From the raw structured output of a pass to its discharge, its coverage
|
||||
// contract and its derived verdict; the merge of a lens's parts with the
|
||||
// cross-unit rule; the coverage matrix. The structured output is the model's
|
||||
// JSON and stays JSON, with every field the model wrote.
|
||||
export namespace Crafter::Review::Normalize {
|
||||
// An exact id, else the one id of `universe` it is a prefix of, else
|
||||
// itself.
|
||||
Json ResolveId(const Json& id, std::span<const std::string> universe);
|
||||
|
||||
// v: the raw structured output ({verdict, findings, notes, coverage?}).
|
||||
// Its notes get their items resolved in place, and the result holds them.
|
||||
// inventory: the units THIS pass must cover (null: no coverage contract);
|
||||
// allIds: every inventory id, for prefix resolution.
|
||||
Json NormalizeOutput(Json& v, std::span<const Json> inForce, std::string_view lensFile, std::string_view hash, const Json& inventory,
|
||||
std::span<const std::string> allIds);
|
||||
|
||||
// The distinct values of `items`, first occurrence kept, equal when their
|
||||
// canonical JSON is.
|
||||
std::vector<Json> Dedupe(std::span<const Json> items);
|
||||
|
||||
// parts: normalized outputs (each with partLabel, expectedIds);
|
||||
// missingUnits: unit ids whose process never returned. Coverage: one entry
|
||||
// per unit, blocking > immaterial > the rest, a tie to the later part
|
||||
// (the block, the zoomed view). The cross-unit rule: a unit cited by an
|
||||
// undischarged finding whose merged verdict is not blocking is
|
||||
// overwritten with the lens's blocking verdict.
|
||||
Json MergeParts(std::string_view lens, std::string_view lensFile, std::span<const Json> parts, std::span<const std::string> missingUnits,
|
||||
const Json& stoppedEarly = nullptr);
|
||||
|
||||
// Units x every lens that returned coverage; holes (a reviewed-kind unit
|
||||
// no lens owned) and defects. notReviewed: the unit ids no lens that runs
|
||||
// reads, listed, never holes.
|
||||
Json Matrix(const Json& inventory, std::span<const Json> results, std::span<const std::string> notReviewed = {});
|
||||
}
|
||||
67
interfaces/Crafter.Review-PgWire.cppm
Normal file
67
interfaces/Crafter.Review-PgWire.cppm
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:PgWire;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// The database under test: the SQL a lens with the `supabase` environment
|
||||
// runs, and the driver's probe before that lens's gate. The lens runs
|
||||
// `crafter-review sql`, which hands the SQL to the driver's broker: the
|
||||
// database URL, its password included, stays in the driver, and the pass's
|
||||
// process knows the broker's address and its stack's token alone.
|
||||
//
|
||||
// Every call of the helper is ONE transaction that is rolled back at its end,
|
||||
// so the passes of a run share one local database without seeing each
|
||||
// other, and the database must be on this machine (127.0.0.1, localhost,
|
||||
// ::1): the helper never reaches a hosted project.
|
||||
export namespace Crafter::Review::PgWire {
|
||||
// Printed once the database answered; the pool looks for it.
|
||||
constexpr std::string_view Answered = "review-gates sql: connected";
|
||||
// Printed when it did not (exit 2).
|
||||
constexpr std::string_view NoDatabase = "review-gates sql: NO DATABASE";
|
||||
// Retired 2026-10-22: the URL stays in the driver; dropped from every
|
||||
// pass's environment.
|
||||
constexpr std::string_view UrlEnv = "REVIEW_GATES_DB_URL";
|
||||
// `<host>:<port>#<token>`: the driver's broker and the pass's database,
|
||||
// never a URL.
|
||||
constexpr std::string_view BrokerEnv = "REVIEW_GATES_DB";
|
||||
// The broker's last line: the call's exit code. Its NUL is part of it.
|
||||
constexpr std::string_view ExitMark("\x00review-gates-exit ", 19);
|
||||
constexpr std::array<std::string_view, 3> Loopback = {"127.0.0.1", "localhost", "::1"};
|
||||
constexpr std::int32_t StatementTimeoutS = 20;
|
||||
constexpr std::int32_t LockTimeoutS = 3;
|
||||
// Rows printed per statement (all are counted).
|
||||
constexpr std::int32_t MaxRows = 100;
|
||||
// Characters printed per value.
|
||||
constexpr std::int32_t MaxCell = 300;
|
||||
// Characters printed per call; past it, statements still run and print
|
||||
// their tags only.
|
||||
constexpr std::int32_t MaxOutput = 40000;
|
||||
constexpr std::int32_t MaxSql = 200000;
|
||||
constexpr std::int32_t MaxStatements = 200;
|
||||
constexpr std::int32_t ExitOk = 0;
|
||||
constexpr std::int32_t ExitSql = 1;
|
||||
constexpr std::int32_t ExitNoDb = 2;
|
||||
constexpr std::int32_t ExitUsage = 64;
|
||||
|
||||
struct Url {
|
||||
std::string scheme;
|
||||
std::string host;
|
||||
std::int32_t port = 5432;
|
||||
std::string user;
|
||||
std::string password;
|
||||
std::string database;
|
||||
};
|
||||
// The URL's parts with the defaults: port 5432, user postgres, database
|
||||
// postgres. std::invalid_argument with a ValueError text for a URL
|
||||
// Dyn::UrlSplit refuses.
|
||||
Url ParseUrl(std::string_view url);
|
||||
// nullopt when the URL names a Postgres database on this machine, else the
|
||||
// problem. Any JSON value: a config may hold anything.
|
||||
std::optional<std::string> CheckUrl(const Json& url);
|
||||
// The URL with its password replaced, for a log line or a dump.
|
||||
std::string Redact(std::string_view url);
|
||||
// "<database> on <host>:<port> as <user>"
|
||||
std::string Where(std::string_view url);
|
||||
}
|
||||
260
interfaces/Crafter.Review-Plan.cppm
Normal file
260
interfaces/Crafter.Review-Plan.cppm
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Plan;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// The lens table, the unit kinds, pass planning, the mechanical n/a, the
|
||||
// process budgets, the reuse keys and the cost estimate. A unit is the
|
||||
// inventory's object ({id, lines, excerpt}) and a job the object PlanLens
|
||||
// builds, both kept as JSON with their keys in a fixed order: the dump,
|
||||
// progress.json and the prompts are made from them.
|
||||
export namespace Crafter::Review::Plan {
|
||||
constexpr std::string_view FunctionalLens = "repo-functional.md";
|
||||
// The reasoning effort when --effort is not given (2026-10-02: the push
|
||||
// gates run at xhigh).
|
||||
constexpr std::string_view Effort = "xhigh";
|
||||
// Clean reads a code unit of a lens marked `reads` needs before its
|
||||
// verdict is reused, one per round (--reads). 2026-10-06: a static lens
|
||||
// is not deterministic — a second and third read of unchanged code still
|
||||
// found defects; "3 is fine".
|
||||
constexpr std::int32_t Reads = 3;
|
||||
// The key's last slot held the run's effort from 2026-09-22 to
|
||||
// 2026-10-02; it is frozen at the value every stored verdict was built
|
||||
// with, so a clean verdict bought at one effort is reused at any other
|
||||
// (Jorijn, 2026-10-02).
|
||||
constexpr std::string_view ReuseKeyEffortSlot = "max";
|
||||
|
||||
// The model of each lens tier; every lens on Opus 5.5 (2026-09-25), and
|
||||
// `--models fable=claude-fable-5-1` splits them. In table order: opus,
|
||||
// fable.
|
||||
struct ModelTier {
|
||||
std::string tier;
|
||||
std::string id;
|
||||
};
|
||||
std::vector<ModelTier>& Models();
|
||||
// MODELS[tier]; Dyn::Error (KeyError) for an unknown tier.
|
||||
const std::string& ModelFor(std::string_view tier);
|
||||
|
||||
constexpr std::array<std::string_view, 2> ApproachSlots = {"whole:order", "whole:absent"};
|
||||
constexpr std::array<std::string_view, 1> BehaviourSlots = {"whole:behaviour"};
|
||||
constexpr std::array<std::string_view, 1> CodeBlocks = {"code"};
|
||||
|
||||
// One row of LENSES. whole: "" (none), "first-repo" (the approach) or
|
||||
// "functional" (the range exercised in the running application); every
|
||||
// whole pass gates the lens's block passes and covers the slots named in
|
||||
// `slots`. block: the unit kinds the lens zooms into. reuse: per-unit reuse
|
||||
// across hashes; wholeReuse: the clean whole pass carries while the code
|
||||
// of the range is unchanged. key: what a block is keyed on — "code" (its
|
||||
// own hunk and the base; 2026-10-06) or "functional" (its hunk AND the
|
||||
// code of the whole range: what the browser shows for a hunk depends on
|
||||
// every other hunk). reads: the lens's code units need Reads clean reads.
|
||||
// empirical: the lens's evidence is observation, so it needs an
|
||||
// environment with an application under test, and a whole pass that never
|
||||
// used the instrument is not evidence. perCommitSlots false: the lens
|
||||
// judges the per-commit slots in its whole pass. env: the default
|
||||
// environment; a verdict bought in any other carries it in its key.
|
||||
struct Lens {
|
||||
std::string_view file;
|
||||
std::int32_t gate;
|
||||
std::string_view whole;
|
||||
std::span<const std::string_view> slots;
|
||||
std::span<const std::string_view> block;
|
||||
std::string_view model;
|
||||
bool reuse;
|
||||
bool wholeReuse;
|
||||
bool reads;
|
||||
std::string_view key;
|
||||
bool empirical;
|
||||
bool perCommitSlots;
|
||||
std::string_view env;
|
||||
};
|
||||
// In the order the dump and the prompts list them.
|
||||
constexpr std::array<Lens, 4> Lenses = {{
|
||||
{"repo-better-solution.md", 1, "first-repo", ApproachSlots, CodeBlocks, "fable", true, true, true, "code", false, true, "none"},
|
||||
{FunctionalLens, 2, "functional", BehaviourSlots, CodeBlocks, "opus", true, true, false, "functional", true, false, "browser"},
|
||||
{"repo-bug-prover.md", 3, "", {}, CodeBlocks, "opus", true, false, true, "code", false, true, "none"},
|
||||
// The security lens (2026-10-22): does the range's code keep the
|
||||
// protections the repository promises? The bug-prover's shape beside
|
||||
// it in Gate 3: one gate stop for both proofs.
|
||||
{"repo-security.md", 3, "", {}, CodeBlocks, "opus", true, false, true, "code", false, true, "none"},
|
||||
}};
|
||||
bool IsLens(std::string_view file);
|
||||
// LENSES[file]; Dyn::Error (KeyError) for a file that is no lens.
|
||||
const Lens& LensOf(std::string_view file);
|
||||
|
||||
struct Gate {
|
||||
std::string_view title;
|
||||
std::vector<std::string_view> lenses;
|
||||
};
|
||||
const std::vector<Gate>& Gates();
|
||||
|
||||
// What a lens's processes get beyond the read-only tools, by the
|
||||
// consumer's lenses.<name>.environment: mcp, the server rendered into
|
||||
// --mcp-config ("" for none); tools, allowlist entries; app, the lens
|
||||
// drives the application under test; db, the lens runs SQL in the
|
||||
// database under test; memMb, what a pass is admitted at before one is
|
||||
// measured. A new entry must first bring seven things (the environment in
|
||||
// the reuse keys, its prompt texts, its own fail-closed check, validation,
|
||||
// DENY, the opencode refusal, a firing proof); the tests hold the table at
|
||||
// these four until then.
|
||||
//
|
||||
// memMb: the highest peak PSS of a pass's own process tree measured
|
||||
// 2026-10-22 on the first consumer — the claude process alone 158-208 MB;
|
||||
// with the browser 385-840 MB (Chromium 554-568, claude 208, the Playwright
|
||||
// server 112-118, the SQL helper 5-9).
|
||||
constexpr std::int32_t MemNone = 210;
|
||||
constexpr std::int32_t MemBrowser = 840;
|
||||
constexpr std::array<std::string_view, 1> BrowserTools = {"Bash(curl:*)"};
|
||||
struct Environment {
|
||||
std::string_view name;
|
||||
std::string_view mcp;
|
||||
std::span<const std::string_view> tools;
|
||||
bool app;
|
||||
bool db;
|
||||
std::int32_t memMb;
|
||||
};
|
||||
constexpr std::array<Environment, 4> Environments = {{
|
||||
{"none", "", {}, false, false, MemNone},
|
||||
{"browser", "playwright", BrowserTools, true, false, MemBrowser},
|
||||
{"supabase", "", {}, false, true, MemNone},
|
||||
{"browser+supabase", "playwright", BrowserTools, true, true, MemBrowser},
|
||||
}};
|
||||
// nullptr for a name that is no environment.
|
||||
const Environment* FindEnvironment(std::string_view name);
|
||||
|
||||
// The environment in a reuse key: evidence bought in one environment is
|
||||
// never reused in another. The lens's default adds nothing, so every
|
||||
// verdict stored before 2026-10-22 keeps its key. Empty `environment`:
|
||||
// the default.
|
||||
std::vector<std::string> EnvDeps(std::string_view lensFile, std::string_view environment = {});
|
||||
|
||||
// (max_turns, timeout_min) of a pass. Caps are safety nets, never retried
|
||||
// (2026-09-17: a max-turns retry re-buys the whole context). A functional
|
||||
// pass spends turns on the browser and gets more.
|
||||
struct Budget {
|
||||
std::int32_t maxTurns;
|
||||
std::int32_t timeoutMin;
|
||||
};
|
||||
Budget BudgetFor(std::string_view kind, std::string_view unitKind, std::string_view lensFile);
|
||||
|
||||
std::string_view DefaultEffort();
|
||||
// "slot", "code" or "text".
|
||||
std::string_view UnitKind(const Json& unit);
|
||||
std::string_view UnitKindOf(std::string_view unitId);
|
||||
// A hunk, a part of a hunk or the file header of a documentation file.
|
||||
bool IsDocUnit(std::string_view unitId);
|
||||
// `\.md$`, case-insensitively: a documentation file (plan.DOC_PATH and
|
||||
// inventory.DOC_FILE, the same pattern).
|
||||
bool IsDocPath(std::string_view path);
|
||||
// The unit's kind for a lens: a documentation file's units are "doc".
|
||||
std::string_view KindFor(std::string_view lensFile, const Json& unit);
|
||||
// The file a hunk or file-header unit belongs to; nullopt for a slot or a
|
||||
// text unit.
|
||||
std::optional<std::string> UnitPath(std::string_view unitId);
|
||||
// The units no lens of `lensFiles` (the lenses that run) plans a whole or
|
||||
// block pass on. A mechanical n/a is not a reading.
|
||||
std::vector<std::string> NotReviewed(const Json& units, std::span<const std::string> lines, std::span<const std::string> lensFiles,
|
||||
std::span<const std::string> exclude = {});
|
||||
// The first glob of functional.exclude the path matches (`**/` prefixes
|
||||
// match at the root too).
|
||||
std::optional<std::string> ExcludedBy(std::string_view path, std::span<const std::string> globs);
|
||||
std::string UnitText(std::span<const std::string> lines, const Json& unit);
|
||||
// sha256 of the text's UTF-8, in hex.
|
||||
std::string Sha(std::string_view text);
|
||||
// lens_file.replace('.md', '')
|
||||
std::string LensName(std::string_view lensFile);
|
||||
// Every lens of the gates.
|
||||
std::vector<std::string> ModeLenses();
|
||||
// The gates with their lens files. off: the lenses the config turns off;
|
||||
// only keeps (test runs), without drops (an owner ruling); an empty span
|
||||
// filters nothing, and a gate left empty disappears.
|
||||
std::vector<Gate> GatesFor(std::span<const std::string> only = {}, std::span<const std::string> without = {},
|
||||
std::span<const std::string> off = {});
|
||||
|
||||
// The whole job (null when the lens has none) and the block jobs.
|
||||
struct LensPlan {
|
||||
Json whole;
|
||||
std::vector<Json> blocks;
|
||||
};
|
||||
// unitsFilter: --units (empty: every unit); exclude: the functional
|
||||
// lens's path globs.
|
||||
LensPlan PlanLens(std::string_view lensFile, const Json& units, std::span<const std::string> lines,
|
||||
std::span<const std::string> unitsFilter = {}, std::span<const std::string> exclude = {});
|
||||
|
||||
// The model is part of the key (a verdict bought from one model is not
|
||||
// evidence for another); the effort is not. ident replaces the unit id for
|
||||
// a unit that is keyed on its content. nullopt: the job is not reusable.
|
||||
std::optional<std::string> ReuseKey(const Json& job, std::string_view lensFile, std::string_view unitText, std::vector<std::string> deps,
|
||||
std::vector<std::string> inForceIds, std::string_view charterSha, std::int32_t promptVersion,
|
||||
std::string_view ident = {});
|
||||
|
||||
// A code unit's text without what a rewrite of the range changes while
|
||||
// the code stays: the blob ids of an `index` line, the line numbers of a
|
||||
// hunk header, and the tail `git format-patch` appends (base-commit, the
|
||||
// `-- ` signature, the git version), which the inventory hands to a file's
|
||||
// last hunk.
|
||||
std::string CodeNorm(std::string_view text);
|
||||
|
||||
// One format-patch file, cut where the inventory cuts it: whether the
|
||||
// commit has a body, its code (every file section from the first
|
||||
// `diff --git` on, normalised, without documentation files), the base,
|
||||
// the diff headers of the documentation files, the message.
|
||||
struct PatchParts {
|
||||
bool hasBody = false;
|
||||
std::string code;
|
||||
std::string base;
|
||||
std::vector<std::string> docs;
|
||||
std::string message;
|
||||
};
|
||||
PatchParts PartsOf(std::string_view patchText);
|
||||
|
||||
// What the code keys of a range are built from, by commit number K.
|
||||
struct CommitCode {
|
||||
std::map<std::int64_t, bool> body;
|
||||
std::map<std::int64_t, std::string> code;
|
||||
std::map<std::int64_t, std::vector<std::string>> docs;
|
||||
std::map<std::int64_t, std::string> message;
|
||||
std::string range;
|
||||
std::map<std::int64_t, std::string> upto;
|
||||
std::string base;
|
||||
};
|
||||
CommitCode CommitCodeOf(const std::map<std::int64_t, std::string>& patches);
|
||||
|
||||
// (ident, deps) of a code unit: a hunk or a file header is keyed on its
|
||||
// file and its own normalised text, the two per-commit slots on that
|
||||
// commit's position and code, the code of the whole range, its
|
||||
// documentation files, and for `absent` whether it has a body. Every code
|
||||
// unit depends on the base.
|
||||
std::pair<std::string, std::vector<std::string>> CodeKeyParts(std::string_view unitId, const CommitCode& cc);
|
||||
std::optional<std::string> CodeReuseKey(const Json& job, std::string_view lensFile, std::string_view unitText, const CommitCode& cc,
|
||||
std::span<const std::string> inForceIds, std::string_view charterSha, std::int32_t promptVersion,
|
||||
std::string_view environment = {});
|
||||
std::optional<std::string> FunctionalReuseKey(const Json& job, std::string_view lensFile, std::string_view unitText, const CommitCode& cc,
|
||||
std::span<const std::string> inForceIds, std::string_view charterSha, std::int32_t promptVersion,
|
||||
std::string_view environment = {});
|
||||
// By the lens's `key` kind.
|
||||
std::optional<std::string> BlockReuseKey(const Json& job, std::string_view lensFile, std::string_view unitText, const CommitCode& cc,
|
||||
std::span<const std::string> inForceIds, std::string_view charterSha, std::int32_t promptVersion,
|
||||
std::string_view environment = {});
|
||||
// A whole pass that judges the code of the range: the code of every
|
||||
// commit in order, the base, which commits have a body and which
|
||||
// documentation files each touches. No message text and no commit id.
|
||||
std::optional<std::string> WholeCodeKey(const Json& job, std::string_view lensFile, const CommitCode& cc, std::span<const std::string> inForceIds,
|
||||
std::string_view charterSha, std::int32_t promptVersion, std::string_view environment = {});
|
||||
|
||||
// How many clean reads a stored result stands for: one per round that
|
||||
// read its key clean.
|
||||
std::int64_t ReadsOf(const Json& entry);
|
||||
// Was this key already read clean in that round on that hash?
|
||||
bool ReadIn(const Json& entry, std::string_view hash8, std::int64_t round);
|
||||
// A stored result under the id its unit has in THIS artifact.
|
||||
Json Rebind(const Json& entry, std::string_view unitId);
|
||||
|
||||
// Weighted cost-units (input 1, cache write 1.25, cache read 0.1, output
|
||||
// 5) and list USD at opus rates (5 / 6.25 / 0.5 / 25 per M), calibrated on
|
||||
// the 2026-09-17 smoke. lensLayerBytes: {lens name: bytes}.
|
||||
Json Estimate(std::span<const Json> jobs, std::int64_t prefixBytes, const std::map<std::string, std::int64_t>& lensLayerBytes,
|
||||
std::int64_t tailBytes = 1800, double tpb = 3.7, std::int64_t sysTokens = 32000, std::int64_t outPerTurn = 1200);
|
||||
}
|
||||
|
|
@ -76,7 +76,8 @@ export namespace Crafter::Review::Platform {
|
|||
|
||||
// An exclusive flock(2) on `lockPath`, held while the object lives. flock,
|
||||
// not fcntl or OFD locks: every driver on the machine takes flock on the
|
||||
// same side files, and on Linux the two kinds do not exclude each other.
|
||||
// same side files, and on Linux the two kinds do not exclude each other. A
|
||||
// missing lock file is created 0666 less the umask.
|
||||
class FileLock {
|
||||
public:
|
||||
explicit FileLock(const std::filesystem::path& lockPath);
|
||||
|
|
|
|||
73
interfaces/Crafter.Review-Prompt.cppm
Normal file
73
interfaces/Crafter.Review-Prompt.cppm
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Prompt;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// The system text and the layered prompt: the run layer, shared by every
|
||||
// process of the run, then the lens layer, shared per lens, then the tail,
|
||||
// this pass. Byte-identical prefixes are what the shared prompt cache keys
|
||||
// on, so every literal here is fixed to the byte (the goldens hold them).
|
||||
export namespace Crafter::Review::Prompt {
|
||||
constexpr std::string_view SepLens = "\n\n==================== LENS ====================\n\n";
|
||||
constexpr std::string_view SepTail = "\n\n==================== SCOPE OF THIS PASS ====================\n\n";
|
||||
constexpr std::string_view SepRun = "\n\n==================== THIS RUN ====================\n\n";
|
||||
|
||||
extern const std::string_view GenericVocab;
|
||||
// WHOLE_TEXT['first-repo'] and WHOLE_TEXT['functional'].
|
||||
extern const std::string_view WholeFirstRepo;
|
||||
extern const std::string_view WholeFunctional;
|
||||
extern const std::string_view FunctionalBlockHint;
|
||||
extern const std::string_view ShotRules;
|
||||
// KIND_HINTS_REPO
|
||||
extern const std::string_view HintOutside;
|
||||
extern const std::string_view HintAbsent;
|
||||
|
||||
// _common-repo.md with the artifact kind filled in.
|
||||
std::string SystemText();
|
||||
// The lens's charter, read with universal newlines.
|
||||
std::string Charter(std::string_view lensFile);
|
||||
|
||||
// INPUTS, the artifact with line numbers, the inventory. trees: as they
|
||||
// are spelled to the lens; contextPaths may be empty.
|
||||
std::string RunLayer(std::string_view artifactRel, std::string_view base, std::string_view date, std::span<const std::string> trees, std::string_view hash,
|
||||
std::span<const std::string> lines, const Json& units, std::span<const std::string> contextPaths = {},
|
||||
std::string_view repoName = "the repository");
|
||||
|
||||
// APPLICATION UNDER TEST: what the processes of a lens with the browser
|
||||
// environment are told about the running application — from the
|
||||
// consumer's functional config, the login fixture the driver found and the
|
||||
// TOTP helper's exact command. slots: the stacks are the bring-up's
|
||||
// slots, one per pass, and this block, shared by every pass of the lens,
|
||||
// names none of them; the pass's own is in its user message (StackText).
|
||||
// A nullopt fixture or command prints as None.
|
||||
std::string AppBlock(const Json& functional, const std::optional<std::string>& loginFixture = std::nullopt,
|
||||
const std::optional<std::string>& totpCommand = std::nullopt, bool slots = false);
|
||||
// STACK FOR THIS PASS: the slot a pass holds, in its user message, so
|
||||
// the system prompt every pass of the lens shares stays byte-identical.
|
||||
std::string StackText(const Json& stack, const std::optional<std::string>& totpCommand);
|
||||
// DATABASE UNDER TEST: the exact helper command (the URL stays in the
|
||||
// driver's broker, never here), what the driver checked before the gate
|
||||
// (dbUser: the role of the stacks' connections, nullopt when they differ;
|
||||
// bypass: whether that role bypasses row-level security, nullopt says
|
||||
// nothing), what one call is, how to act as an API caller, the limits,
|
||||
// the evidence, the owner's notes.
|
||||
std::string DbBlock(const Json& supabase, std::string_view sqlCommand, const std::optional<std::string>& dbUser, bool withApp = false,
|
||||
const std::optional<std::string>& checked = std::nullopt, std::optional<bool> bypass = std::nullopt);
|
||||
// The charter, the application and database blocks when there are
|
||||
// any, the dispositions, the whole pass's summary.
|
||||
std::string LensLayer(std::string_view lensFile, std::string_view charterText, std::string_view dispositionsBlock, std::string_view app = {},
|
||||
std::string_view wholeSummary = {}, std::string_view db = {});
|
||||
// The scope of one pass: a whole pass's units, a slot's question, or a
|
||||
// block's unit text.
|
||||
std::string Tail(const Json& job, const Json& units, std::span<const std::string> lines, std::string_view wholeSummary = {});
|
||||
std::string BudgetLine(const Json& job);
|
||||
// The appended system prompt of a pass: the common charter text, the run
|
||||
// layer and the lens layer, byte-identical for every pass of a lens in a
|
||||
// run.
|
||||
std::string SystemPrompt(std::string_view systemText, std::string_view run, std::string_view lens);
|
||||
// The stdin user message of a pass: only what differs between passes. A
|
||||
// null job adds no budget line.
|
||||
std::string UserPrompt(std::string_view tail, const Json& job = nullptr, std::string_view stack = {});
|
||||
}
|
||||
32
interfaces/Crafter.Review-Schema.cppm
Normal file
32
interfaces/Crafter.Review-Schema.cppm
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Schema;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// The structured output a pass returns: FINDING, NOTE, COVERAGE and the
|
||||
// verdict. One block schema and one whole schema per run, the union of every
|
||||
// lens's vocabulary, so the tool block ahead of the user message is
|
||||
// byte-identical across lenses and the prompt cache is shared. The bytes are
|
||||
// fixed: SchemaJson() is the schema in DumpCompactSorted's form, and the
|
||||
// goldens hold the descriptions.
|
||||
export namespace Crafter::Review::Schema {
|
||||
constexpr std::array<std::string_view, 10> NoteKinds = {
|
||||
"reserve-answer", "invariant", "pre-existing", "residual-risk", "hold", "info", "immaterial",
|
||||
"send-time-check", "refutation-verified", "unverified",
|
||||
};
|
||||
constexpr std::array<std::string_view, 4> CoverageVerdicts = {"clear", "defect", "immaterial", "n/a"};
|
||||
constexpr std::array<std::string_view, 1> CoverageBlocking = {"defect"};
|
||||
constexpr std::array<std::string_view, 2> CoverageUnowned = {"n/a", "MISSING"};
|
||||
constexpr std::array<std::string_view, 2> VerdictEnum = {"FIX FIRST", "SEND-READY"};
|
||||
|
||||
Json Finding();
|
||||
Json Note();
|
||||
Json Coverage();
|
||||
Json BlockSchema();
|
||||
Json WholeSchema();
|
||||
// The schema of `kind` ("block", anything else the whole one) as it goes
|
||||
// to claude.
|
||||
std::string SchemaJson(std::string_view kind);
|
||||
}
|
||||
73
interfaces/Crafter.Review-State.cppm
Normal file
73
interfaces/Crafter.Review-State.cppm
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:State;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// unit-state.json (per-unit reuse), the run lock, the usage totals and the
|
||||
// stdout summary. unit-state.json is merged on write, because drivers share
|
||||
// one gate-state dir, and one full run per hash holds the hash's lock: every
|
||||
// driver on the machine reads and writes these, so the files, the locks and
|
||||
// the layout do not change.
|
||||
export namespace Crafter::Review::State {
|
||||
// {version: 1, entries: {}, personaPass: null}
|
||||
Json EmptyState();
|
||||
// The file as JSON, whatever its shape, or the empty state when it is
|
||||
// missing or does not parse.
|
||||
Json LoadState(const std::filesystem::path& path);
|
||||
// This run's stores and drops applied to the state on disk — pure. Drops
|
||||
// win over sets; an entry of `sets` that is not a whole pass gets its
|
||||
// clean-read count from the FILE's previous entry (or the one-read
|
||||
// synthesis of an entry stored before the count was kept) plus `read`
|
||||
// unless that (hash, round) is counted already. Garbage on disk is the
|
||||
// empty state. `sets` is an object; a null `read` counts nothing.
|
||||
Json MergeState(const Json& disk, const Json& sets, std::span<const std::string> drops = {}, const Json& read = nullptr);
|
||||
// The whole state written as it is, through `<path>.tmp`.
|
||||
void SaveWhole(const std::filesystem::path& path, const Json& state);
|
||||
// Merge-on-write: the file re-read under `<path>.lock`, this run's deltas
|
||||
// applied (MergeState), written atomically; returns the merged state. Two
|
||||
// drivers on one gate-state dir would otherwise overwrite each other's
|
||||
// stores, and a --no-reuse run would wipe the file from its empty object.
|
||||
Json SaveState(const std::filesystem::path& path, const Json& sets, std::span<const std::string> drops = {}, const Json& read = nullptr);
|
||||
|
||||
// ---- one full run per hash -------------------------------------------------
|
||||
// Another full run holds this hash's lock; what() names the holder.
|
||||
class RunLocked : public std::runtime_error {
|
||||
public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
std::filesystem::path LockPath(const std::filesystem::path& gateDir, std::string_view mode, std::string_view hash8);
|
||||
// The holder's JSON, {} when there is none or it does not parse.
|
||||
Json ReadLockInfo(const std::filesystem::path& path);
|
||||
std::string Describe(const Json& info);
|
||||
|
||||
// An exclusive, non-blocking flock on gate-state/.run-<mode>-<hash8>.lock,
|
||||
// kept for the life of the process: the kernel releases it when the
|
||||
// holder dies, and no child inherits it. The file is never unlinked: an
|
||||
// unlink and re-create would hand two drivers one hash.
|
||||
class RunLock {
|
||||
public:
|
||||
// Throws RunLocked naming the holder.
|
||||
RunLock(const std::filesystem::path& gateDir, std::string_view mode, std::string_view hash8);
|
||||
~RunLock();
|
||||
RunLock(const RunLock&) = delete;
|
||||
RunLock& operator=(const RunLock&) = delete;
|
||||
// The holder's identity, once it knows its run number: one JSON
|
||||
// document, truncated and rewritten.
|
||||
void WriteInfo(const Json& info);
|
||||
|
||||
private:
|
||||
std::int32_t fd = -1;
|
||||
};
|
||||
// Who holds this hash's run lock ({} while the holder has not written
|
||||
// itself yet), nullopt when nobody does: a test or dry run takes no lock
|
||||
// but numbers its scratch dir past a live holder.
|
||||
std::optional<Json> LockHolder(const std::filesystem::path& gateDir, std::string_view mode, std::string_view hash8);
|
||||
std::int64_t NextRunNumber(const std::filesystem::path& gateDir, std::string_view mode, std::string_view hash8);
|
||||
|
||||
// The usage of a set of pass records, summed in the order they come.
|
||||
Json UsageTotals(std::span<const Json> records);
|
||||
// The stdout summary of a run's dump.
|
||||
std::string Summary(const Json& dump);
|
||||
}
|
||||
40
interfaces/Crafter.Review-Stream.cppm
Normal file
40
interfaces/Crafter.Review-Stream.cppm
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Stream;
|
||||
import std;
|
||||
import :Json;
|
||||
|
||||
// The claude CLI's stream-json, parsed, and a pass's status classified from
|
||||
// it. The patterns are hand-written scanners, case-insensitive with Unicode
|
||||
// folding (the Kelvin sign is a k) and Unicode-aware where \b and \s are.
|
||||
//
|
||||
// The stream is split into lines at \n only: the CLI writes U+2028 and \x1c
|
||||
// raw inside a JSON string, and a line cut there would be lost.
|
||||
export namespace Crafter::Review::Stream {
|
||||
// A Bash call of the database helper, alone or in a compound command:
|
||||
// this binary's `<exe> sql`, with any path before it.
|
||||
bool IsSqlCall(std::string_view command);
|
||||
// The helper's ANSWERED line at the start of a line of the result.
|
||||
bool HasAnsweredLine(std::string_view text);
|
||||
// LIMIT_RE, AUTH_RE, CREDIT_RE: a rate limit, an authentication failure,
|
||||
// an organization out of API credit.
|
||||
bool LimitText(std::string_view text);
|
||||
bool AuthText(std::string_view text);
|
||||
bool CreditText(std::string_view text);
|
||||
|
||||
// One pass over the NDJSON: the last result line, the last
|
||||
// rate_limit_event, the first session_id, usage totals, the first turn's
|
||||
// usage, tool-call forensics, system/init, each under its own key.
|
||||
Json ParseStream(std::string_view text);
|
||||
// structured_output, else the result text parsed as JSON, a
|
||||
// double-encoded string decoded; nullopt without a findings array.
|
||||
std::optional<Json> StructuredOutput(const Json& result);
|
||||
// ok | limit | credits | auth | timeout | error, and why.
|
||||
std::pair<std::string, std::string> Classify(const Json& parsed, std::optional<std::int32_t> exitCode, std::string_view stderrText,
|
||||
bool timedOut = false);
|
||||
// {window: {utilization, resetsAt}} from a rate_limit_info: the CLI
|
||||
// reports a fraction (2026-09-17: five_hour 0.2), the pool thresholds are
|
||||
// percents.
|
||||
Json Windows(const Json& rate);
|
||||
}
|
||||
|
|
@ -33,6 +33,19 @@ export namespace Crafter::Review::Dyn {
|
|||
// The code points from start to end: a negative index counts from the
|
||||
// end, and both are clipped to the text.
|
||||
std::string Slice(std::string_view text, std::int64_t start, std::optional<std::int64_t> end = std::nullopt);
|
||||
// The code point at byte `at` and the bytes it takes: U+FFFD and the
|
||||
// length of the invalid sequence where the bytes are no UTF-8.
|
||||
std::pair<char32_t, std::size_t> CodePointAt(std::string_view text, std::size_t at);
|
||||
// [start, end) of a slice of `size` items: a negative index counts from
|
||||
// the end, and both are clipped to the sequence.
|
||||
std::pair<std::size_t, std::size_t> SliceBounds(std::size_t size, std::int64_t start, std::optional<std::int64_t> end = std::nullopt);
|
||||
|
||||
// ---- regex classes, for the hand-written scanners -----------------------
|
||||
// The bytes of the run at `at` of regex \d (Unicode decimal digits), \s
|
||||
// (Unicode whitespace) or \S characters.
|
||||
std::size_t DecimalRun(std::string_view text, std::size_t at);
|
||||
std::size_t SpaceRun(std::string_view text, std::size_t at);
|
||||
std::size_t NonSpaceRun(std::string_view text, std::size_t at);
|
||||
|
||||
// ---- characters ----------------------------------------------------------
|
||||
bool IsSpace(char32_t c);
|
||||
|
|
@ -41,6 +54,8 @@ export namespace Crafter::Review::Dyn {
|
|||
// The digit's value, -1 for a character that is not a decimal digit.
|
||||
std::int32_t DecimalValue(char32_t c);
|
||||
bool IsPrintable(char32_t c);
|
||||
// regex \w: what \b takes for a word character.
|
||||
bool IsWord(char32_t c);
|
||||
// The lowercase ASCII letter `c` matches case-insensitively, or '\0':
|
||||
// ASCII letters, and the four code points outside ASCII that fold onto
|
||||
// one (İ ı → i, ſ → s, K → k).
|
||||
|
|
@ -70,14 +85,27 @@ export namespace Crafter::Review::Dyn {
|
|||
std::size_t Count(std::string_view text, std::string_view sub);
|
||||
std::string Replace(std::string_view text, std::string_view from, std::string_view to);
|
||||
std::string Join(std::span<const std::string> parts, std::string_view separator);
|
||||
// f'{text:<width}' / text.ljust(width): padded with spaces to `width`
|
||||
// code points, where std::format would count display columns.
|
||||
std::string LJust(std::string_view text, std::size_t width);
|
||||
|
||||
// ---- reading text files ----------------------------------------------------
|
||||
// A text file, read whole: strict UTF-8 — an invalid byte throws
|
||||
// std::runtime_error naming the file and the offset — and universal
|
||||
// newlines.
|
||||
// A text file, read whole: strict UTF-8 — invalid bytes throw Error
|
||||
// ("UnicodeDecodeError") with Utf8DecodeError()'s message — and universal
|
||||
// newlines. A file that cannot be opened throws Error ("FileNotFoundError").
|
||||
std::string ReadText(const std::filesystem::path& path);
|
||||
// \r\n and a lone \r become \n, as text mode reads them.
|
||||
std::string UniversalNewlines(std::string_view text);
|
||||
// The message for bytes that are not UTF-8 — "'utf-8' codec can't decode
|
||||
// byte 0xff in position 3: invalid start byte" — nullopt for valid UTF-8.
|
||||
std::optional<std::string> Utf8DecodeError(std::string_view bytes);
|
||||
// The message for text that is no JSON document, with the scanner's
|
||||
// reason and position ("Expecting ',' delimiter: line 3 column 5 (char
|
||||
// 21)"); nullopt for a document LoadJsonFile() takes.
|
||||
std::optional<std::string> JsonDecodeError(std::string_view text);
|
||||
// A JSON file: read as text, then parsed. Throws Error with the message a
|
||||
// "not JSON (...)" problem carries: the decode error, or the JSON error.
|
||||
Json LoadJsonFile(const std::filesystem::path& path);
|
||||
|
||||
// ---- numbers ------------------------------------------------------------------
|
||||
// A float as its shortest digits that round-trip; an exponent below 1e-4
|
||||
|
|
@ -127,6 +155,9 @@ export namespace Crafter::Review::Dyn {
|
|||
// std::invalid_argument with a ValueError message for unbalanced or
|
||||
// invalid brackets.
|
||||
SplitUrl UrlSplit(std::string_view url);
|
||||
// The five parts joined back into a URL: an empty query or fragment gets
|
||||
// no '?' or '#'.
|
||||
std::string UrlUnsplit(std::string_view scheme, std::string_view netloc, std::string_view path, std::string_view query, std::string_view fragment);
|
||||
// unquote(text): %XX sequences decoded as UTF-8, bad bytes replaced.
|
||||
std::string Unquote(std::string_view text);
|
||||
|
||||
|
|
@ -152,4 +183,63 @@ export namespace Crafter::Review::Dyn {
|
|||
// ---- errno texts -------------------------------------------------------------------------
|
||||
// "[Errno 111] Connection refused": an errno as a message prints it.
|
||||
std::string ErrnoText(std::int32_t code);
|
||||
|
||||
// ---- exceptions ------------------------------------------------------------------------------
|
||||
// Data the code does not expect — a key that is absent, a value of the
|
||||
// wrong type, a lookup in something that is no object — throws Error
|
||||
// named for the case (KeyError, TypeError, AttributeError): a caller
|
||||
// catches the names it expects, and anything else fails loudly.
|
||||
class Error : public std::runtime_error {
|
||||
public:
|
||||
Error(std::string_view kind, const std::string& message);
|
||||
const std::string& Kind() const;
|
||||
|
||||
private:
|
||||
std::string kind;
|
||||
};
|
||||
|
||||
// ---- JSON values ---------------------------------------------------------------------------------
|
||||
// The driver's data — units, jobs, results, dispositions, the config, the
|
||||
// claude stream — stays JSON from end to end, so every key keeps its place
|
||||
// and its unknown neighbours. These are the operations on it.
|
||||
//
|
||||
// Truthiness: null, false, 0, 0.0, "", [] and {} are false.
|
||||
bool Truthy(const Json& value);
|
||||
// `value or fallback`. A reference to one of the two, so neither may be a
|
||||
// temporary: name the fallback, or use EmptyDict()/EmptyList().
|
||||
const Json& Or(const Json& value, const Json& fallback);
|
||||
const Json& Or(Json&& value, const Json& fallback) = delete;
|
||||
const Json& Or(const Json& value, Json&& fallback) = delete;
|
||||
// The shared {} and [] that `x or {}` and `x or []` fall back to.
|
||||
const Json& EmptyDict();
|
||||
const Json& EmptyList();
|
||||
// Whether an object has the key; false for anything that is no object.
|
||||
bool Has(const Json& dict, std::string_view key);
|
||||
// The key's value, null when it is absent; Error (AttributeError) on
|
||||
// something that is no object.
|
||||
const Json& Get(const Json& dict, std::string_view key);
|
||||
// The key's value; Error (KeyError) when it is absent.
|
||||
const Json& At(const Json& dict, std::string_view key);
|
||||
// The type name messages use: dict, list, str, int, float, bool, NoneType.
|
||||
std::string_view TypeName(const Json& value);
|
||||
// An integer, a bool included.
|
||||
bool IsInt(const Json& value);
|
||||
// An integer or a float, a bool included.
|
||||
bool IsNumber(const Json& value);
|
||||
// A string as it is, anything else as ReprValue() prints it.
|
||||
std::string Str(const Json& value);
|
||||
// Str() of the value, or of the fallback when the value is falsy.
|
||||
std::string StrOr(const Json& value, std::string_view fallback);
|
||||
// a == b: numbers by value (True == 1 == 1.0), dicts whatever their key
|
||||
// order, a str never equal to a number.
|
||||
bool Equal(const Json& a, const Json& b);
|
||||
// Membership: an element of a list, a key of an object, a substring of a
|
||||
// string (Error when the item is no string there).
|
||||
bool In(const Json& item, const Json& container);
|
||||
// a + b on numbers: int + int stays an int, a float makes a float, a bool
|
||||
// counts as 0 or 1; Error (TypeError) for anything else.
|
||||
Json Add(const Json& a, const Json& b);
|
||||
// A total of floats by Neumaier's compensated summation, so it comes out
|
||||
// to the same last bit as the goldens record it.
|
||||
double Sum(std::span<const double> values);
|
||||
}
|
||||
|
|
|
|||
44
interfaces/Crafter.Review-Tools.cppm
Normal file
44
interfaces/Crafter.Review-Tools.cppm
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
export module Crafter.Review:Tools;
|
||||
import std;
|
||||
|
||||
// The tool lists every pass is started with: what is denied whatever the
|
||||
// allowlist says, the read-only git verbs, the base allowlist, and the
|
||||
// Playwright MCP server's tools by name. A leaf of its own: the config checks
|
||||
// its extra tools against DENY and the pool builds every command line from
|
||||
// these, so with the lists in either of them the two would import each
|
||||
// other.
|
||||
export namespace Crafter::Review::Tools {
|
||||
// The Playwright MCP server, as --mcp-config names it.
|
||||
constexpr std::string_view McpServer = "playwright";
|
||||
constexpr std::array<std::string_view, 24> McpTools = {
|
||||
"browser_navigate", "browser_navigate_back", "browser_snapshot", "browser_click", "browser_type", "browser_fill_form",
|
||||
"browser_select_option", "browser_press_key", "browser_hover", "browser_drag", "browser_drop", "browser_handle_dialog",
|
||||
"browser_wait_for", "browser_take_screenshot", "browser_console_messages", "browser_network_requests", "browser_network_request",
|
||||
"browser_evaluate", "browser_tabs", "browser_resize", "browser_close", "browser_find", "browser_emulate_media", "browser_file_upload",
|
||||
};
|
||||
// browser_run_code_unsafe runs arbitrary Node code in the server's
|
||||
// process.
|
||||
constexpr std::array<std::string_view, 1> McpDenied = {"browser_run_code_unsafe"};
|
||||
|
||||
// mcp__playwright__<tool> for each.
|
||||
std::vector<std::string> McpToolNames();
|
||||
std::vector<std::string> McpDeniedToolNames();
|
||||
|
||||
// Never, whatever the allowlist says: writes, the network beyond the
|
||||
// browser, the agent tools, package managers, stacks, a database client
|
||||
// that commits (psql: the supabase environment's helper is the one way
|
||||
// in, every call rolled back).
|
||||
const std::vector<std::string>& Deny();
|
||||
constexpr std::array<std::string_view, 22> GitReadOnly = {
|
||||
"diff", "log", "show", "grep", "blame", "ls-tree", "ls-files", "cat-file", "rev-parse", "rev-list", "hash-object", "describe",
|
||||
"merge-base", "name-rev", "shortlog", "for-each-ref", "branch", "tag", "status", "worktree list", "remote", "count-objects",
|
||||
};
|
||||
const std::vector<std::string>& BaseAllow();
|
||||
|
||||
// Does Deny() override this allowlist entry? `Bash(psql -h x:*)` falls
|
||||
// under `Bash(psql:*)`, `Bash(psqlx:*)` does not.
|
||||
bool Denied(std::string_view tool);
|
||||
}
|
||||
|
|
@ -6,7 +6,8 @@
|
|||
//
|
||||
// The parts of the Unicode Character Database the driver's output depends
|
||||
// on: whitespace, line breaks, decimal digits, lowercase and uppercase
|
||||
// mappings outside ASCII, and which other code points match an ASCII letter
|
||||
// mappings outside ASCII, what a regular expression's \w counts as a word
|
||||
// character, and which other code points match an ASCII letter
|
||||
// case-insensitively. :Text builds its string functions on these, so a
|
||||
// unit, an excerpt or a key cut from text with an NBSP, a U+2028 or a Kelvin
|
||||
// sign in it always comes out the same.
|
||||
|
|
@ -3878,6 +3879,782 @@ export namespace Crafter::Review::Unicode {
|
|||
{0xe0100, 0xe01ef},
|
||||
}};
|
||||
|
||||
// Word characters (regex \w: alphanumeric or _): what \b takes for a
|
||||
// word character, as runs.
|
||||
constexpr std::array<Run, 771> Word = {{
|
||||
{0x30, 0x39},
|
||||
{0x41, 0x5a},
|
||||
{0x5f, 0x5f},
|
||||
{0x61, 0x7a},
|
||||
{0xaa, 0xaa},
|
||||
{0xb2, 0xb3},
|
||||
{0xb5, 0xb5},
|
||||
{0xb9, 0xba},
|
||||
{0xbc, 0xbe},
|
||||
{0xc0, 0xd6},
|
||||
{0xd8, 0xf6},
|
||||
{0xf8, 0x2c1},
|
||||
{0x2c6, 0x2d1},
|
||||
{0x2e0, 0x2e4},
|
||||
{0x2ec, 0x2ec},
|
||||
{0x2ee, 0x2ee},
|
||||
{0x370, 0x374},
|
||||
{0x376, 0x377},
|
||||
{0x37a, 0x37d},
|
||||
{0x37f, 0x37f},
|
||||
{0x386, 0x386},
|
||||
{0x388, 0x38a},
|
||||
{0x38c, 0x38c},
|
||||
{0x38e, 0x3a1},
|
||||
{0x3a3, 0x3f5},
|
||||
{0x3f7, 0x481},
|
||||
{0x48a, 0x52f},
|
||||
{0x531, 0x556},
|
||||
{0x559, 0x559},
|
||||
{0x560, 0x588},
|
||||
{0x5d0, 0x5ea},
|
||||
{0x5ef, 0x5f2},
|
||||
{0x620, 0x64a},
|
||||
{0x660, 0x669},
|
||||
{0x66e, 0x66f},
|
||||
{0x671, 0x6d3},
|
||||
{0x6d5, 0x6d5},
|
||||
{0x6e5, 0x6e6},
|
||||
{0x6ee, 0x6fc},
|
||||
{0x6ff, 0x6ff},
|
||||
{0x710, 0x710},
|
||||
{0x712, 0x72f},
|
||||
{0x74d, 0x7a5},
|
||||
{0x7b1, 0x7b1},
|
||||
{0x7c0, 0x7ea},
|
||||
{0x7f4, 0x7f5},
|
||||
{0x7fa, 0x7fa},
|
||||
{0x800, 0x815},
|
||||
{0x81a, 0x81a},
|
||||
{0x824, 0x824},
|
||||
{0x828, 0x828},
|
||||
{0x840, 0x858},
|
||||
{0x860, 0x86a},
|
||||
{0x870, 0x887},
|
||||
{0x889, 0x88e},
|
||||
{0x8a0, 0x8c9},
|
||||
{0x904, 0x939},
|
||||
{0x93d, 0x93d},
|
||||
{0x950, 0x950},
|
||||
{0x958, 0x961},
|
||||
{0x966, 0x96f},
|
||||
{0x971, 0x980},
|
||||
{0x985, 0x98c},
|
||||
{0x98f, 0x990},
|
||||
{0x993, 0x9a8},
|
||||
{0x9aa, 0x9b0},
|
||||
{0x9b2, 0x9b2},
|
||||
{0x9b6, 0x9b9},
|
||||
{0x9bd, 0x9bd},
|
||||
{0x9ce, 0x9ce},
|
||||
{0x9dc, 0x9dd},
|
||||
{0x9df, 0x9e1},
|
||||
{0x9e6, 0x9f1},
|
||||
{0x9f4, 0x9f9},
|
||||
{0x9fc, 0x9fc},
|
||||
{0xa05, 0xa0a},
|
||||
{0xa0f, 0xa10},
|
||||
{0xa13, 0xa28},
|
||||
{0xa2a, 0xa30},
|
||||
{0xa32, 0xa33},
|
||||
{0xa35, 0xa36},
|
||||
{0xa38, 0xa39},
|
||||
{0xa59, 0xa5c},
|
||||
{0xa5e, 0xa5e},
|
||||
{0xa66, 0xa6f},
|
||||
{0xa72, 0xa74},
|
||||
{0xa85, 0xa8d},
|
||||
{0xa8f, 0xa91},
|
||||
{0xa93, 0xaa8},
|
||||
{0xaaa, 0xab0},
|
||||
{0xab2, 0xab3},
|
||||
{0xab5, 0xab9},
|
||||
{0xabd, 0xabd},
|
||||
{0xad0, 0xad0},
|
||||
{0xae0, 0xae1},
|
||||
{0xae6, 0xaef},
|
||||
{0xaf9, 0xaf9},
|
||||
{0xb05, 0xb0c},
|
||||
{0xb0f, 0xb10},
|
||||
{0xb13, 0xb28},
|
||||
{0xb2a, 0xb30},
|
||||
{0xb32, 0xb33},
|
||||
{0xb35, 0xb39},
|
||||
{0xb3d, 0xb3d},
|
||||
{0xb5c, 0xb5d},
|
||||
{0xb5f, 0xb61},
|
||||
{0xb66, 0xb6f},
|
||||
{0xb71, 0xb77},
|
||||
{0xb83, 0xb83},
|
||||
{0xb85, 0xb8a},
|
||||
{0xb8e, 0xb90},
|
||||
{0xb92, 0xb95},
|
||||
{0xb99, 0xb9a},
|
||||
{0xb9c, 0xb9c},
|
||||
{0xb9e, 0xb9f},
|
||||
{0xba3, 0xba4},
|
||||
{0xba8, 0xbaa},
|
||||
{0xbae, 0xbb9},
|
||||
{0xbd0, 0xbd0},
|
||||
{0xbe6, 0xbf2},
|
||||
{0xc05, 0xc0c},
|
||||
{0xc0e, 0xc10},
|
||||
{0xc12, 0xc28},
|
||||
{0xc2a, 0xc39},
|
||||
{0xc3d, 0xc3d},
|
||||
{0xc58, 0xc5a},
|
||||
{0xc5d, 0xc5d},
|
||||
{0xc60, 0xc61},
|
||||
{0xc66, 0xc6f},
|
||||
{0xc78, 0xc7e},
|
||||
{0xc80, 0xc80},
|
||||
{0xc85, 0xc8c},
|
||||
{0xc8e, 0xc90},
|
||||
{0xc92, 0xca8},
|
||||
{0xcaa, 0xcb3},
|
||||
{0xcb5, 0xcb9},
|
||||
{0xcbd, 0xcbd},
|
||||
{0xcdd, 0xcde},
|
||||
{0xce0, 0xce1},
|
||||
{0xce6, 0xcef},
|
||||
{0xcf1, 0xcf2},
|
||||
{0xd04, 0xd0c},
|
||||
{0xd0e, 0xd10},
|
||||
{0xd12, 0xd3a},
|
||||
{0xd3d, 0xd3d},
|
||||
{0xd4e, 0xd4e},
|
||||
{0xd54, 0xd56},
|
||||
{0xd58, 0xd61},
|
||||
{0xd66, 0xd78},
|
||||
{0xd7a, 0xd7f},
|
||||
{0xd85, 0xd96},
|
||||
{0xd9a, 0xdb1},
|
||||
{0xdb3, 0xdbb},
|
||||
{0xdbd, 0xdbd},
|
||||
{0xdc0, 0xdc6},
|
||||
{0xde6, 0xdef},
|
||||
{0xe01, 0xe30},
|
||||
{0xe32, 0xe33},
|
||||
{0xe40, 0xe46},
|
||||
{0xe50, 0xe59},
|
||||
{0xe81, 0xe82},
|
||||
{0xe84, 0xe84},
|
||||
{0xe86, 0xe8a},
|
||||
{0xe8c, 0xea3},
|
||||
{0xea5, 0xea5},
|
||||
{0xea7, 0xeb0},
|
||||
{0xeb2, 0xeb3},
|
||||
{0xebd, 0xebd},
|
||||
{0xec0, 0xec4},
|
||||
{0xec6, 0xec6},
|
||||
{0xed0, 0xed9},
|
||||
{0xedc, 0xedf},
|
||||
{0xf00, 0xf00},
|
||||
{0xf20, 0xf33},
|
||||
{0xf40, 0xf47},
|
||||
{0xf49, 0xf6c},
|
||||
{0xf88, 0xf8c},
|
||||
{0x1000, 0x102a},
|
||||
{0x103f, 0x1049},
|
||||
{0x1050, 0x1055},
|
||||
{0x105a, 0x105d},
|
||||
{0x1061, 0x1061},
|
||||
{0x1065, 0x1066},
|
||||
{0x106e, 0x1070},
|
||||
{0x1075, 0x1081},
|
||||
{0x108e, 0x108e},
|
||||
{0x1090, 0x1099},
|
||||
{0x10a0, 0x10c5},
|
||||
{0x10c7, 0x10c7},
|
||||
{0x10cd, 0x10cd},
|
||||
{0x10d0, 0x10fa},
|
||||
{0x10fc, 0x1248},
|
||||
{0x124a, 0x124d},
|
||||
{0x1250, 0x1256},
|
||||
{0x1258, 0x1258},
|
||||
{0x125a, 0x125d},
|
||||
{0x1260, 0x1288},
|
||||
{0x128a, 0x128d},
|
||||
{0x1290, 0x12b0},
|
||||
{0x12b2, 0x12b5},
|
||||
{0x12b8, 0x12be},
|
||||
{0x12c0, 0x12c0},
|
||||
{0x12c2, 0x12c5},
|
||||
{0x12c8, 0x12d6},
|
||||
{0x12d8, 0x1310},
|
||||
{0x1312, 0x1315},
|
||||
{0x1318, 0x135a},
|
||||
{0x1369, 0x137c},
|
||||
{0x1380, 0x138f},
|
||||
{0x13a0, 0x13f5},
|
||||
{0x13f8, 0x13fd},
|
||||
{0x1401, 0x166c},
|
||||
{0x166f, 0x167f},
|
||||
{0x1681, 0x169a},
|
||||
{0x16a0, 0x16ea},
|
||||
{0x16ee, 0x16f8},
|
||||
{0x1700, 0x1711},
|
||||
{0x171f, 0x1731},
|
||||
{0x1740, 0x1751},
|
||||
{0x1760, 0x176c},
|
||||
{0x176e, 0x1770},
|
||||
{0x1780, 0x17b3},
|
||||
{0x17d7, 0x17d7},
|
||||
{0x17dc, 0x17dc},
|
||||
{0x17e0, 0x17e9},
|
||||
{0x17f0, 0x17f9},
|
||||
{0x1810, 0x1819},
|
||||
{0x1820, 0x1878},
|
||||
{0x1880, 0x1884},
|
||||
{0x1887, 0x18a8},
|
||||
{0x18aa, 0x18aa},
|
||||
{0x18b0, 0x18f5},
|
||||
{0x1900, 0x191e},
|
||||
{0x1946, 0x196d},
|
||||
{0x1970, 0x1974},
|
||||
{0x1980, 0x19ab},
|
||||
{0x19b0, 0x19c9},
|
||||
{0x19d0, 0x19da},
|
||||
{0x1a00, 0x1a16},
|
||||
{0x1a20, 0x1a54},
|
||||
{0x1a80, 0x1a89},
|
||||
{0x1a90, 0x1a99},
|
||||
{0x1aa7, 0x1aa7},
|
||||
{0x1b05, 0x1b33},
|
||||
{0x1b45, 0x1b4c},
|
||||
{0x1b50, 0x1b59},
|
||||
{0x1b83, 0x1ba0},
|
||||
{0x1bae, 0x1be5},
|
||||
{0x1c00, 0x1c23},
|
||||
{0x1c40, 0x1c49},
|
||||
{0x1c4d, 0x1c7d},
|
||||
{0x1c80, 0x1c8a},
|
||||
{0x1c90, 0x1cba},
|
||||
{0x1cbd, 0x1cbf},
|
||||
{0x1ce9, 0x1cec},
|
||||
{0x1cee, 0x1cf3},
|
||||
{0x1cf5, 0x1cf6},
|
||||
{0x1cfa, 0x1cfa},
|
||||
{0x1d00, 0x1dbf},
|
||||
{0x1e00, 0x1f15},
|
||||
{0x1f18, 0x1f1d},
|
||||
{0x1f20, 0x1f45},
|
||||
{0x1f48, 0x1f4d},
|
||||
{0x1f50, 0x1f57},
|
||||
{0x1f59, 0x1f59},
|
||||
{0x1f5b, 0x1f5b},
|
||||
{0x1f5d, 0x1f5d},
|
||||
{0x1f5f, 0x1f7d},
|
||||
{0x1f80, 0x1fb4},
|
||||
{0x1fb6, 0x1fbc},
|
||||
{0x1fbe, 0x1fbe},
|
||||
{0x1fc2, 0x1fc4},
|
||||
{0x1fc6, 0x1fcc},
|
||||
{0x1fd0, 0x1fd3},
|
||||
{0x1fd6, 0x1fdb},
|
||||
{0x1fe0, 0x1fec},
|
||||
{0x1ff2, 0x1ff4},
|
||||
{0x1ff6, 0x1ffc},
|
||||
{0x2070, 0x2071},
|
||||
{0x2074, 0x2079},
|
||||
{0x207f, 0x2089},
|
||||
{0x2090, 0x209c},
|
||||
{0x2102, 0x2102},
|
||||
{0x2107, 0x2107},
|
||||
{0x210a, 0x2113},
|
||||
{0x2115, 0x2115},
|
||||
{0x2119, 0x211d},
|
||||
{0x2124, 0x2124},
|
||||
{0x2126, 0x2126},
|
||||
{0x2128, 0x2128},
|
||||
{0x212a, 0x212d},
|
||||
{0x212f, 0x2139},
|
||||
{0x213c, 0x213f},
|
||||
{0x2145, 0x2149},
|
||||
{0x214e, 0x214e},
|
||||
{0x2150, 0x2189},
|
||||
{0x2460, 0x249b},
|
||||
{0x24ea, 0x24ff},
|
||||
{0x2776, 0x2793},
|
||||
{0x2c00, 0x2ce4},
|
||||
{0x2ceb, 0x2cee},
|
||||
{0x2cf2, 0x2cf3},
|
||||
{0x2cfd, 0x2cfd},
|
||||
{0x2d00, 0x2d25},
|
||||
{0x2d27, 0x2d27},
|
||||
{0x2d2d, 0x2d2d},
|
||||
{0x2d30, 0x2d67},
|
||||
{0x2d6f, 0x2d6f},
|
||||
{0x2d80, 0x2d96},
|
||||
{0x2da0, 0x2da6},
|
||||
{0x2da8, 0x2dae},
|
||||
{0x2db0, 0x2db6},
|
||||
{0x2db8, 0x2dbe},
|
||||
{0x2dc0, 0x2dc6},
|
||||
{0x2dc8, 0x2dce},
|
||||
{0x2dd0, 0x2dd6},
|
||||
{0x2dd8, 0x2dde},
|
||||
{0x2e2f, 0x2e2f},
|
||||
{0x3005, 0x3007},
|
||||
{0x3021, 0x3029},
|
||||
{0x3031, 0x3035},
|
||||
{0x3038, 0x303c},
|
||||
{0x3041, 0x3096},
|
||||
{0x309d, 0x309f},
|
||||
{0x30a1, 0x30fa},
|
||||
{0x30fc, 0x30ff},
|
||||
{0x3105, 0x312f},
|
||||
{0x3131, 0x318e},
|
||||
{0x3192, 0x3195},
|
||||
{0x31a0, 0x31bf},
|
||||
{0x31f0, 0x31ff},
|
||||
{0x3220, 0x3229},
|
||||
{0x3248, 0x324f},
|
||||
{0x3251, 0x325f},
|
||||
{0x3280, 0x3289},
|
||||
{0x32b1, 0x32bf},
|
||||
{0x3400, 0x4dbf},
|
||||
{0x4e00, 0xa48c},
|
||||
{0xa4d0, 0xa4fd},
|
||||
{0xa500, 0xa60c},
|
||||
{0xa610, 0xa62b},
|
||||
{0xa640, 0xa66e},
|
||||
{0xa67f, 0xa69d},
|
||||
{0xa6a0, 0xa6ef},
|
||||
{0xa717, 0xa71f},
|
||||
{0xa722, 0xa788},
|
||||
{0xa78b, 0xa7cd},
|
||||
{0xa7d0, 0xa7d1},
|
||||
{0xa7d3, 0xa7d3},
|
||||
{0xa7d5, 0xa7dc},
|
||||
{0xa7f2, 0xa801},
|
||||
{0xa803, 0xa805},
|
||||
{0xa807, 0xa80a},
|
||||
{0xa80c, 0xa822},
|
||||
{0xa830, 0xa835},
|
||||
{0xa840, 0xa873},
|
||||
{0xa882, 0xa8b3},
|
||||
{0xa8d0, 0xa8d9},
|
||||
{0xa8f2, 0xa8f7},
|
||||
{0xa8fb, 0xa8fb},
|
||||
{0xa8fd, 0xa8fe},
|
||||
{0xa900, 0xa925},
|
||||
{0xa930, 0xa946},
|
||||
{0xa960, 0xa97c},
|
||||
{0xa984, 0xa9b2},
|
||||
{0xa9cf, 0xa9d9},
|
||||
{0xa9e0, 0xa9e4},
|
||||
{0xa9e6, 0xa9fe},
|
||||
{0xaa00, 0xaa28},
|
||||
{0xaa40, 0xaa42},
|
||||
{0xaa44, 0xaa4b},
|
||||
{0xaa50, 0xaa59},
|
||||
{0xaa60, 0xaa76},
|
||||
{0xaa7a, 0xaa7a},
|
||||
{0xaa7e, 0xaaaf},
|
||||
{0xaab1, 0xaab1},
|
||||
{0xaab5, 0xaab6},
|
||||
{0xaab9, 0xaabd},
|
||||
{0xaac0, 0xaac0},
|
||||
{0xaac2, 0xaac2},
|
||||
{0xaadb, 0xaadd},
|
||||
{0xaae0, 0xaaea},
|
||||
{0xaaf2, 0xaaf4},
|
||||
{0xab01, 0xab06},
|
||||
{0xab09, 0xab0e},
|
||||
{0xab11, 0xab16},
|
||||
{0xab20, 0xab26},
|
||||
{0xab28, 0xab2e},
|
||||
{0xab30, 0xab5a},
|
||||
{0xab5c, 0xab69},
|
||||
{0xab70, 0xabe2},
|
||||
{0xabf0, 0xabf9},
|
||||
{0xac00, 0xd7a3},
|
||||
{0xd7b0, 0xd7c6},
|
||||
{0xd7cb, 0xd7fb},
|
||||
{0xf900, 0xfa6d},
|
||||
{0xfa70, 0xfad9},
|
||||
{0xfb00, 0xfb06},
|
||||
{0xfb13, 0xfb17},
|
||||
{0xfb1d, 0xfb1d},
|
||||
{0xfb1f, 0xfb28},
|
||||
{0xfb2a, 0xfb36},
|
||||
{0xfb38, 0xfb3c},
|
||||
{0xfb3e, 0xfb3e},
|
||||
{0xfb40, 0xfb41},
|
||||
{0xfb43, 0xfb44},
|
||||
{0xfb46, 0xfbb1},
|
||||
{0xfbd3, 0xfd3d},
|
||||
{0xfd50, 0xfd8f},
|
||||
{0xfd92, 0xfdc7},
|
||||
{0xfdf0, 0xfdfb},
|
||||
{0xfe70, 0xfe74},
|
||||
{0xfe76, 0xfefc},
|
||||
{0xff10, 0xff19},
|
||||
{0xff21, 0xff3a},
|
||||
{0xff41, 0xff5a},
|
||||
{0xff66, 0xffbe},
|
||||
{0xffc2, 0xffc7},
|
||||
{0xffca, 0xffcf},
|
||||
{0xffd2, 0xffd7},
|
||||
{0xffda, 0xffdc},
|
||||
{0x10000, 0x1000b},
|
||||
{0x1000d, 0x10026},
|
||||
{0x10028, 0x1003a},
|
||||
{0x1003c, 0x1003d},
|
||||
{0x1003f, 0x1004d},
|
||||
{0x10050, 0x1005d},
|
||||
{0x10080, 0x100fa},
|
||||
{0x10107, 0x10133},
|
||||
{0x10140, 0x10178},
|
||||
{0x1018a, 0x1018b},
|
||||
{0x10280, 0x1029c},
|
||||
{0x102a0, 0x102d0},
|
||||
{0x102e1, 0x102fb},
|
||||
{0x10300, 0x10323},
|
||||
{0x1032d, 0x1034a},
|
||||
{0x10350, 0x10375},
|
||||
{0x10380, 0x1039d},
|
||||
{0x103a0, 0x103c3},
|
||||
{0x103c8, 0x103cf},
|
||||
{0x103d1, 0x103d5},
|
||||
{0x10400, 0x1049d},
|
||||
{0x104a0, 0x104a9},
|
||||
{0x104b0, 0x104d3},
|
||||
{0x104d8, 0x104fb},
|
||||
{0x10500, 0x10527},
|
||||
{0x10530, 0x10563},
|
||||
{0x10570, 0x1057a},
|
||||
{0x1057c, 0x1058a},
|
||||
{0x1058c, 0x10592},
|
||||
{0x10594, 0x10595},
|
||||
{0x10597, 0x105a1},
|
||||
{0x105a3, 0x105b1},
|
||||
{0x105b3, 0x105b9},
|
||||
{0x105bb, 0x105bc},
|
||||
{0x105c0, 0x105f3},
|
||||
{0x10600, 0x10736},
|
||||
{0x10740, 0x10755},
|
||||
{0x10760, 0x10767},
|
||||
{0x10780, 0x10785},
|
||||
{0x10787, 0x107b0},
|
||||
{0x107b2, 0x107ba},
|
||||
{0x10800, 0x10805},
|
||||
{0x10808, 0x10808},
|
||||
{0x1080a, 0x10835},
|
||||
{0x10837, 0x10838},
|
||||
{0x1083c, 0x1083c},
|
||||
{0x1083f, 0x10855},
|
||||
{0x10858, 0x10876},
|
||||
{0x10879, 0x1089e},
|
||||
{0x108a7, 0x108af},
|
||||
{0x108e0, 0x108f2},
|
||||
{0x108f4, 0x108f5},
|
||||
{0x108fb, 0x1091b},
|
||||
{0x10920, 0x10939},
|
||||
{0x10980, 0x109b7},
|
||||
{0x109bc, 0x109cf},
|
||||
{0x109d2, 0x10a00},
|
||||
{0x10a10, 0x10a13},
|
||||
{0x10a15, 0x10a17},
|
||||
{0x10a19, 0x10a35},
|
||||
{0x10a40, 0x10a48},
|
||||
{0x10a60, 0x10a7e},
|
||||
{0x10a80, 0x10a9f},
|
||||
{0x10ac0, 0x10ac7},
|
||||
{0x10ac9, 0x10ae4},
|
||||
{0x10aeb, 0x10aef},
|
||||
{0x10b00, 0x10b35},
|
||||
{0x10b40, 0x10b55},
|
||||
{0x10b58, 0x10b72},
|
||||
{0x10b78, 0x10b91},
|
||||
{0x10ba9, 0x10baf},
|
||||
{0x10c00, 0x10c48},
|
||||
{0x10c80, 0x10cb2},
|
||||
{0x10cc0, 0x10cf2},
|
||||
{0x10cfa, 0x10d23},
|
||||
{0x10d30, 0x10d39},
|
||||
{0x10d40, 0x10d65},
|
||||
{0x10d6f, 0x10d85},
|
||||
{0x10e60, 0x10e7e},
|
||||
{0x10e80, 0x10ea9},
|
||||
{0x10eb0, 0x10eb1},
|
||||
{0x10ec2, 0x10ec4},
|
||||
{0x10f00, 0x10f27},
|
||||
{0x10f30, 0x10f45},
|
||||
{0x10f51, 0x10f54},
|
||||
{0x10f70, 0x10f81},
|
||||
{0x10fb0, 0x10fcb},
|
||||
{0x10fe0, 0x10ff6},
|
||||
{0x11003, 0x11037},
|
||||
{0x11052, 0x1106f},
|
||||
{0x11071, 0x11072},
|
||||
{0x11075, 0x11075},
|
||||
{0x11083, 0x110af},
|
||||
{0x110d0, 0x110e8},
|
||||
{0x110f0, 0x110f9},
|
||||
{0x11103, 0x11126},
|
||||
{0x11136, 0x1113f},
|
||||
{0x11144, 0x11144},
|
||||
{0x11147, 0x11147},
|
||||
{0x11150, 0x11172},
|
||||
{0x11176, 0x11176},
|
||||
{0x11183, 0x111b2},
|
||||
{0x111c1, 0x111c4},
|
||||
{0x111d0, 0x111da},
|
||||
{0x111dc, 0x111dc},
|
||||
{0x111e1, 0x111f4},
|
||||
{0x11200, 0x11211},
|
||||
{0x11213, 0x1122b},
|
||||
{0x1123f, 0x11240},
|
||||
{0x11280, 0x11286},
|
||||
{0x11288, 0x11288},
|
||||
{0x1128a, 0x1128d},
|
||||
{0x1128f, 0x1129d},
|
||||
{0x1129f, 0x112a8},
|
||||
{0x112b0, 0x112de},
|
||||
{0x112f0, 0x112f9},
|
||||
{0x11305, 0x1130c},
|
||||
{0x1130f, 0x11310},
|
||||
{0x11313, 0x11328},
|
||||
{0x1132a, 0x11330},
|
||||
{0x11332, 0x11333},
|
||||
{0x11335, 0x11339},
|
||||
{0x1133d, 0x1133d},
|
||||
{0x11350, 0x11350},
|
||||
{0x1135d, 0x11361},
|
||||
{0x11380, 0x11389},
|
||||
{0x1138b, 0x1138b},
|
||||
{0x1138e, 0x1138e},
|
||||
{0x11390, 0x113b5},
|
||||
{0x113b7, 0x113b7},
|
||||
{0x113d1, 0x113d1},
|
||||
{0x113d3, 0x113d3},
|
||||
{0x11400, 0x11434},
|
||||
{0x11447, 0x1144a},
|
||||
{0x11450, 0x11459},
|
||||
{0x1145f, 0x11461},
|
||||
{0x11480, 0x114af},
|
||||
{0x114c4, 0x114c5},
|
||||
{0x114c7, 0x114c7},
|
||||
{0x114d0, 0x114d9},
|
||||
{0x11580, 0x115ae},
|
||||
{0x115d8, 0x115db},
|
||||
{0x11600, 0x1162f},
|
||||
{0x11644, 0x11644},
|
||||
{0x11650, 0x11659},
|
||||
{0x11680, 0x116aa},
|
||||
{0x116b8, 0x116b8},
|
||||
{0x116c0, 0x116c9},
|
||||
{0x116d0, 0x116e3},
|
||||
{0x11700, 0x1171a},
|
||||
{0x11730, 0x1173b},
|
||||
{0x11740, 0x11746},
|
||||
{0x11800, 0x1182b},
|
||||
{0x118a0, 0x118f2},
|
||||
{0x118ff, 0x11906},
|
||||
{0x11909, 0x11909},
|
||||
{0x1190c, 0x11913},
|
||||
{0x11915, 0x11916},
|
||||
{0x11918, 0x1192f},
|
||||
{0x1193f, 0x1193f},
|
||||
{0x11941, 0x11941},
|
||||
{0x11950, 0x11959},
|
||||
{0x119a0, 0x119a7},
|
||||
{0x119aa, 0x119d0},
|
||||
{0x119e1, 0x119e1},
|
||||
{0x119e3, 0x119e3},
|
||||
{0x11a00, 0x11a00},
|
||||
{0x11a0b, 0x11a32},
|
||||
{0x11a3a, 0x11a3a},
|
||||
{0x11a50, 0x11a50},
|
||||
{0x11a5c, 0x11a89},
|
||||
{0x11a9d, 0x11a9d},
|
||||
{0x11ab0, 0x11af8},
|
||||
{0x11bc0, 0x11be0},
|
||||
{0x11bf0, 0x11bf9},
|
||||
{0x11c00, 0x11c08},
|
||||
{0x11c0a, 0x11c2e},
|
||||
{0x11c40, 0x11c40},
|
||||
{0x11c50, 0x11c6c},
|
||||
{0x11c72, 0x11c8f},
|
||||
{0x11d00, 0x11d06},
|
||||
{0x11d08, 0x11d09},
|
||||
{0x11d0b, 0x11d30},
|
||||
{0x11d46, 0x11d46},
|
||||
{0x11d50, 0x11d59},
|
||||
{0x11d60, 0x11d65},
|
||||
{0x11d67, 0x11d68},
|
||||
{0x11d6a, 0x11d89},
|
||||
{0x11d98, 0x11d98},
|
||||
{0x11da0, 0x11da9},
|
||||
{0x11ee0, 0x11ef2},
|
||||
{0x11f02, 0x11f02},
|
||||
{0x11f04, 0x11f10},
|
||||
{0x11f12, 0x11f33},
|
||||
{0x11f50, 0x11f59},
|
||||
{0x11fb0, 0x11fb0},
|
||||
{0x11fc0, 0x11fd4},
|
||||
{0x12000, 0x12399},
|
||||
{0x12400, 0x1246e},
|
||||
{0x12480, 0x12543},
|
||||
{0x12f90, 0x12ff0},
|
||||
{0x13000, 0x1342f},
|
||||
{0x13441, 0x13446},
|
||||
{0x13460, 0x143fa},
|
||||
{0x14400, 0x14646},
|
||||
{0x16100, 0x1611d},
|
||||
{0x16130, 0x16139},
|
||||
{0x16800, 0x16a38},
|
||||
{0x16a40, 0x16a5e},
|
||||
{0x16a60, 0x16a69},
|
||||
{0x16a70, 0x16abe},
|
||||
{0x16ac0, 0x16ac9},
|
||||
{0x16ad0, 0x16aed},
|
||||
{0x16b00, 0x16b2f},
|
||||
{0x16b40, 0x16b43},
|
||||
{0x16b50, 0x16b59},
|
||||
{0x16b5b, 0x16b61},
|
||||
{0x16b63, 0x16b77},
|
||||
{0x16b7d, 0x16b8f},
|
||||
{0x16d40, 0x16d6c},
|
||||
{0x16d70, 0x16d79},
|
||||
{0x16e40, 0x16e96},
|
||||
{0x16f00, 0x16f4a},
|
||||
{0x16f50, 0x16f50},
|
||||
{0x16f93, 0x16f9f},
|
||||
{0x16fe0, 0x16fe1},
|
||||
{0x16fe3, 0x16fe3},
|
||||
{0x17000, 0x187f7},
|
||||
{0x18800, 0x18cd5},
|
||||
{0x18cff, 0x18d08},
|
||||
{0x1aff0, 0x1aff3},
|
||||
{0x1aff5, 0x1affb},
|
||||
{0x1affd, 0x1affe},
|
||||
{0x1b000, 0x1b122},
|
||||
{0x1b132, 0x1b132},
|
||||
{0x1b150, 0x1b152},
|
||||
{0x1b155, 0x1b155},
|
||||
{0x1b164, 0x1b167},
|
||||
{0x1b170, 0x1b2fb},
|
||||
{0x1bc00, 0x1bc6a},
|
||||
{0x1bc70, 0x1bc7c},
|
||||
{0x1bc80, 0x1bc88},
|
||||
{0x1bc90, 0x1bc99},
|
||||
{0x1ccf0, 0x1ccf9},
|
||||
{0x1d2c0, 0x1d2d3},
|
||||
{0x1d2e0, 0x1d2f3},
|
||||
{0x1d360, 0x1d378},
|
||||
{0x1d400, 0x1d454},
|
||||
{0x1d456, 0x1d49c},
|
||||
{0x1d49e, 0x1d49f},
|
||||
{0x1d4a2, 0x1d4a2},
|
||||
{0x1d4a5, 0x1d4a6},
|
||||
{0x1d4a9, 0x1d4ac},
|
||||
{0x1d4ae, 0x1d4b9},
|
||||
{0x1d4bb, 0x1d4bb},
|
||||
{0x1d4bd, 0x1d4c3},
|
||||
{0x1d4c5, 0x1d505},
|
||||
{0x1d507, 0x1d50a},
|
||||
{0x1d50d, 0x1d514},
|
||||
{0x1d516, 0x1d51c},
|
||||
{0x1d51e, 0x1d539},
|
||||
{0x1d53b, 0x1d53e},
|
||||
{0x1d540, 0x1d544},
|
||||
{0x1d546, 0x1d546},
|
||||
{0x1d54a, 0x1d550},
|
||||
{0x1d552, 0x1d6a5},
|
||||
{0x1d6a8, 0x1d6c0},
|
||||
{0x1d6c2, 0x1d6da},
|
||||
{0x1d6dc, 0x1d6fa},
|
||||
{0x1d6fc, 0x1d714},
|
||||
{0x1d716, 0x1d734},
|
||||
{0x1d736, 0x1d74e},
|
||||
{0x1d750, 0x1d76e},
|
||||
{0x1d770, 0x1d788},
|
||||
{0x1d78a, 0x1d7a8},
|
||||
{0x1d7aa, 0x1d7c2},
|
||||
{0x1d7c4, 0x1d7cb},
|
||||
{0x1d7ce, 0x1d7ff},
|
||||
{0x1df00, 0x1df1e},
|
||||
{0x1df25, 0x1df2a},
|
||||
{0x1e030, 0x1e06d},
|
||||
{0x1e100, 0x1e12c},
|
||||
{0x1e137, 0x1e13d},
|
||||
{0x1e140, 0x1e149},
|
||||
{0x1e14e, 0x1e14e},
|
||||
{0x1e290, 0x1e2ad},
|
||||
{0x1e2c0, 0x1e2eb},
|
||||
{0x1e2f0, 0x1e2f9},
|
||||
{0x1e4d0, 0x1e4eb},
|
||||
{0x1e4f0, 0x1e4f9},
|
||||
{0x1e5d0, 0x1e5ed},
|
||||
{0x1e5f0, 0x1e5fa},
|
||||
{0x1e7e0, 0x1e7e6},
|
||||
{0x1e7e8, 0x1e7eb},
|
||||
{0x1e7ed, 0x1e7ee},
|
||||
{0x1e7f0, 0x1e7fe},
|
||||
{0x1e800, 0x1e8c4},
|
||||
{0x1e8c7, 0x1e8cf},
|
||||
{0x1e900, 0x1e943},
|
||||
{0x1e94b, 0x1e94b},
|
||||
{0x1e950, 0x1e959},
|
||||
{0x1ec71, 0x1ecab},
|
||||
{0x1ecad, 0x1ecaf},
|
||||
{0x1ecb1, 0x1ecb4},
|
||||
{0x1ed01, 0x1ed2d},
|
||||
{0x1ed2f, 0x1ed3d},
|
||||
{0x1ee00, 0x1ee03},
|
||||
{0x1ee05, 0x1ee1f},
|
||||
{0x1ee21, 0x1ee22},
|
||||
{0x1ee24, 0x1ee24},
|
||||
{0x1ee27, 0x1ee27},
|
||||
{0x1ee29, 0x1ee32},
|
||||
{0x1ee34, 0x1ee37},
|
||||
{0x1ee39, 0x1ee39},
|
||||
{0x1ee3b, 0x1ee3b},
|
||||
{0x1ee42, 0x1ee42},
|
||||
{0x1ee47, 0x1ee47},
|
||||
{0x1ee49, 0x1ee49},
|
||||
{0x1ee4b, 0x1ee4b},
|
||||
{0x1ee4d, 0x1ee4f},
|
||||
{0x1ee51, 0x1ee52},
|
||||
{0x1ee54, 0x1ee54},
|
||||
{0x1ee57, 0x1ee57},
|
||||
{0x1ee59, 0x1ee59},
|
||||
{0x1ee5b, 0x1ee5b},
|
||||
{0x1ee5d, 0x1ee5d},
|
||||
{0x1ee5f, 0x1ee5f},
|
||||
{0x1ee61, 0x1ee62},
|
||||
{0x1ee64, 0x1ee64},
|
||||
{0x1ee67, 0x1ee6a},
|
||||
{0x1ee6c, 0x1ee72},
|
||||
{0x1ee74, 0x1ee77},
|
||||
{0x1ee79, 0x1ee7c},
|
||||
{0x1ee7e, 0x1ee7e},
|
||||
{0x1ee80, 0x1ee89},
|
||||
{0x1ee8b, 0x1ee9b},
|
||||
{0x1eea1, 0x1eea3},
|
||||
{0x1eea5, 0x1eea9},
|
||||
{0x1eeab, 0x1eebb},
|
||||
{0x1f100, 0x1f10c},
|
||||
{0x1fbf0, 0x1fbf9},
|
||||
{0x20000, 0x2a6df},
|
||||
{0x2a700, 0x2b739},
|
||||
{0x2b740, 0x2b81d},
|
||||
{0x2b820, 0x2cea1},
|
||||
{0x2ceb0, 0x2ebe0},
|
||||
{0x2ebf0, 0x2ee5d},
|
||||
{0x2f800, 0x2fa1d},
|
||||
{0x30000, 0x3134a},
|
||||
{0x31350, 0x323af},
|
||||
}};
|
||||
|
||||
// re.IGNORECASE: code points outside ASCII that match an ASCII
|
||||
// letter of a pattern, sorted.
|
||||
constexpr std::array<Fold, 4> IgnoreCase = {{
|
||||
|
|
|
|||
|
|
@ -10,4 +10,16 @@ export import :Crypto;
|
|||
export import :Platform;
|
||||
export import :Process;
|
||||
export import :Core;
|
||||
export import :Schema;
|
||||
export import :Tools;
|
||||
export import :Plan;
|
||||
export import :Artifact;
|
||||
export import :Inventory;
|
||||
export import :Dispositions;
|
||||
export import :State;
|
||||
export import :Normalize;
|
||||
export import :PgWire;
|
||||
export import :Stream;
|
||||
export import :Prompt;
|
||||
export import :Config;
|
||||
export import :Driver;
|
||||
|
|
|
|||
40
project.cpp
40
project.cpp
|
|
@ -13,7 +13,7 @@ using namespace Crafter;
|
|||
namespace {
|
||||
// The umbrella, then the partitions in import order: each after the ones
|
||||
// it imports, which is also the order the module map in AGENTS.md uses.
|
||||
constexpr std::array<std::string_view, 9> Interfaces = {
|
||||
constexpr std::array<std::string_view, 21> Interfaces = {
|
||||
"interfaces/Crafter.Review",
|
||||
"interfaces/Crafter.Review-Unicode",
|
||||
"interfaces/Crafter.Review-Json",
|
||||
|
|
@ -22,24 +22,54 @@ namespace {
|
|||
"interfaces/Crafter.Review-Platform",
|
||||
"interfaces/Crafter.Review-Process",
|
||||
"interfaces/Crafter.Review-Core",
|
||||
"interfaces/Crafter.Review-Schema",
|
||||
"interfaces/Crafter.Review-Tools",
|
||||
"interfaces/Crafter.Review-Plan",
|
||||
"interfaces/Crafter.Review-Artifact",
|
||||
"interfaces/Crafter.Review-Inventory",
|
||||
"interfaces/Crafter.Review-Dispositions",
|
||||
"interfaces/Crafter.Review-State",
|
||||
"interfaces/Crafter.Review-Normalize",
|
||||
"interfaces/Crafter.Review-PgWire",
|
||||
"interfaces/Crafter.Review-Stream",
|
||||
"interfaces/Crafter.Review-Prompt",
|
||||
"interfaces/Crafter.Review-Config",
|
||||
"interfaces/Crafter.Review-Driver",
|
||||
};
|
||||
constexpr std::array<std::string_view, 6> Implementations = {
|
||||
constexpr std::array<std::string_view, 18> Implementations = {
|
||||
"implementations/Crafter.Review-Text",
|
||||
"implementations/Crafter.Review-Crypto",
|
||||
"implementations/Crafter.Review-Platform",
|
||||
"implementations/Crafter.Review-Process",
|
||||
"implementations/Crafter.Review-Core",
|
||||
"implementations/Crafter.Review-Schema",
|
||||
"implementations/Crafter.Review-Tools",
|
||||
"implementations/Crafter.Review-Plan",
|
||||
"implementations/Crafter.Review-Artifact",
|
||||
"implementations/Crafter.Review-Inventory",
|
||||
"implementations/Crafter.Review-Dispositions",
|
||||
"implementations/Crafter.Review-State",
|
||||
"implementations/Crafter.Review-Normalize",
|
||||
"implementations/Crafter.Review-PgWire",
|
||||
"implementations/Crafter.Review-Stream",
|
||||
"implementations/Crafter.Review-Prompt",
|
||||
"implementations/Crafter.Review-Config",
|
||||
"implementations/Crafter.Review-Driver",
|
||||
};
|
||||
|
||||
// With -march=native clang would fuse a multiply and an add: a cost
|
||||
// estimate, a usage total or a memory threshold must come out to the
|
||||
// same last bit on every machine, as the goldens record it.
|
||||
constexpr std::string_view NoContraction = "-ffp-contract=off";
|
||||
|
||||
// One per directory under tests/, each an ordinary main() that links the
|
||||
// library: exit 0 passes, nonzero fails, 77 skips.
|
||||
constexpr std::array<std::string_view, 4> Tests = {
|
||||
constexpr std::array<std::string_view, 5> Tests = {
|
||||
"Crypto",
|
||||
"Text",
|
||||
"Platform",
|
||||
"Process",
|
||||
"Goldens",
|
||||
};
|
||||
|
||||
// The version the binary reports: CI sets it from the tag, a checkout
|
||||
|
|
@ -218,6 +248,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
|||
ApplyStandardArgs(*ReviewLib, args);
|
||||
ReviewLib->type = ConfigurationType::LibraryStatic;
|
||||
ReviewLib->dependencies = { network };
|
||||
ReviewLib->compileFlags.emplace_back(NoContraction);
|
||||
// Backslash-escaped quotes: the define travels through the shell before
|
||||
// it reaches clang, which must still see a string literal.
|
||||
ReviewLib->defines.push_back({"CRAFTER_REVIEW_VERSION", std::format("\\\"{}\\\"", Version())});
|
||||
|
|
@ -234,6 +265,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
|||
ApplyStandardArgs(cfg, args);
|
||||
cfg.type = ConfigurationType::Executable;
|
||||
cfg.dependencies = { ReviewLib.get() };
|
||||
cfg.compileFlags.emplace_back(NoContraction);
|
||||
{
|
||||
std::array<fs::path, 0> interfaces = {};
|
||||
std::array<fs::path, 1> implementations = { "implementations/main" };
|
||||
|
|
@ -241,7 +273,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
|||
}
|
||||
|
||||
for (const std::string_view test : Tests) {
|
||||
cfg.AddTest(test).Dependencies({ ReviewLib.get() });
|
||||
cfg.AddTest(test).Dependencies({ ReviewLib.get() }).CompileFlag(std::string(NoContraction));
|
||||
}
|
||||
|
||||
LintRules::AddLiteRules(cfg);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH 1/2] add the greeting module
|
||||
|
||||
---
|
||||
hello.py | 9 +++++++++
|
||||
1 file changed, 9 insertions(+)
|
||||
create mode 100644 hello.py
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
new file mode 100644
|
||||
index 0000000..a1b2c3d
|
||||
--- /dev/null
|
||||
+++ b/hello.py
|
||||
@@ -0,0 +1,9 @@
|
||||
+"""Greetings."""
|
||||
+
|
||||
+
|
||||
+def greet():
|
||||
+ return "hello"
|
||||
+
|
||||
+
|
||||
+def farewell():
|
||||
+ return "bye"
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH 2/2] greet by name and document it
|
||||
|
||||
The greeting takes a name now and the farewell mirrors it; the README
|
||||
documents both calls. Callers that pass nothing still get the old text.
|
||||
|
||||
The format follows the greeting spec [1].
|
||||
|
||||
[1] https://example.org/greeting-spec
|
||||
---
|
||||
README.md | 4 ++++
|
||||
hello.py | 8 ++++++--
|
||||
2 files changed, 10 insertions(+), 2 deletions(-)
|
||||
create mode 100644 README.md
|
||||
|
||||
diff --git a/README.md b/README.md
|
||||
new file mode 100644
|
||||
index 0000000..d4e5f6a
|
||||
--- /dev/null
|
||||
+++ b/README.md
|
||||
@@ -0,0 +1,4 @@
|
||||
+# hello
|
||||
+
|
||||
+Call `greet(name)` or `farewell(name)`; without a name both return the
|
||||
+plain text.
|
||||
diff --git a/hello.py b/hello.py
|
||||
index a1b2c3d..b7c8d9e 100644
|
||||
--- a/hello.py
|
||||
+++ b/hello.py
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Greetings."""
|
||||
|
||||
|
||||
-def greet():
|
||||
- return "hello"
|
||||
+def greet(name=None):
|
||||
+ if name is None:
|
||||
+ return "hello"
|
||||
+ return "hello " + name
|
||||
|
||||
|
||||
@@ -7,3 +11,5 @@ def greet():
|
||||
-def farewell():
|
||||
- return "bye"
|
||||
+def farewell(name=None):
|
||||
+ if name is None:
|
||||
+ return "bye"
|
||||
+ return "bye " + name
|
||||
|
||||
base-commit: 9999999999999999999999999999999999999999
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH 1/2] add the greeting module
|
||||
|
||||
---
|
||||
hello.py | 9 +++++++++
|
||||
1 file changed, 9 insertions(+)
|
||||
create mode 100644 hello.py
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
new file mode 100644
|
||||
index 0000000..a1b2c3d
|
||||
--- /dev/null
|
||||
+++ b/hello.py
|
||||
@@ -0,0 +1,9 @@
|
||||
+"""Greetings."""
|
||||
+
|
||||
+
|
||||
+def greet():
|
||||
+ return "hello"
|
||||
+
|
||||
+
|
||||
+def farewell():
|
||||
+ return "bye"
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH 2/2] greet by name and document it
|
||||
|
||||
The greeting takes a name now and the farewell mirrors it; the README
|
||||
documents both calls. Callers that pass nothing still get the old text.
|
||||
|
||||
The format follows the greeting spec [1].
|
||||
|
||||
[1] https://example.org/greeting-spec
|
||||
---
|
||||
README.md | 4 ++++
|
||||
hello.py | 8 ++++++--
|
||||
2 files changed, 10 insertions(+), 2 deletions(-)
|
||||
create mode 100644 README.md
|
||||
|
||||
diff --git a/README.md b/README.md
|
||||
new file mode 100644
|
||||
index 0000000..d4e5f6a
|
||||
--- /dev/null
|
||||
+++ b/README.md
|
||||
@@ -0,0 +1,4 @@
|
||||
+# hello
|
||||
+
|
||||
+Call `greet(name)` or `farewell(name)`; without a name both return the
|
||||
+plain text.
|
||||
diff --git a/hello.py b/hello.py
|
||||
index a1b2c3d..b7c8d9e 100644
|
||||
--- a/hello.py
|
||||
+++ b/hello.py
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Greetings."""
|
||||
|
||||
|
||||
-def greet():
|
||||
- return "hello"
|
||||
+def greet(name=None):
|
||||
+ if name is None:
|
||||
+ return "hello"
|
||||
+ return "hi " + name
|
||||
|
||||
|
||||
@@ -7,3 +11,5 @@ def greet():
|
||||
-def farewell():
|
||||
- return "bye"
|
||||
+def farewell(name=None):
|
||||
+ if name is None:
|
||||
+ return "bye"
|
||||
+ return "bye " + name
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH 1/2] add the greeting module
|
||||
|
||||
---
|
||||
hello.py | 9 +++++++++
|
||||
1 file changed, 9 insertions(+)
|
||||
create mode 100644 hello.py
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
new file mode 100644
|
||||
index 0000000..a1b2c3d
|
||||
--- /dev/null
|
||||
+++ b/hello.py
|
||||
@@ -0,0 +1,9 @@
|
||||
+"""Greetings."""
|
||||
+
|
||||
+
|
||||
+def greet():
|
||||
+ return "hello"
|
||||
+
|
||||
+
|
||||
+def farewell():
|
||||
+ return "bye"
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH 2/2] greet by name and document it
|
||||
|
||||
The greeting takes a name now and the farewell mirrors it; the README
|
||||
documents both calls. Callers that pass nothing still get the old text.
|
||||
|
||||
The format follows the greeting spec [1].
|
||||
|
||||
[1] https://example.org/greeting-spec
|
||||
---
|
||||
README.md | 4 ++++
|
||||
hello.py | 8 ++++++--
|
||||
2 files changed, 10 insertions(+), 2 deletions(-)
|
||||
create mode 100644 README.md
|
||||
|
||||
diff --git a/README.md b/README.md
|
||||
new file mode 100644
|
||||
index 0000000..d4e5f6a
|
||||
--- /dev/null
|
||||
+++ b/README.md
|
||||
@@ -0,0 +1,4 @@
|
||||
+# hello
|
||||
+
|
||||
+Call `greet(name)` or `farewell(name)`; without a name both return the
|
||||
+plain text.
|
||||
diff --git a/hello.py b/hello.py
|
||||
index a1b2c3d..b7c8d9e 100644
|
||||
--- a/hello.py
|
||||
+++ b/hello.py
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Greetings, by name."""
|
||||
|
||||
|
||||
-def greet():
|
||||
- return "hello"
|
||||
+def greet(name=None):
|
||||
+ if name is None:
|
||||
+ return "hello"
|
||||
+ return "hello " + name
|
||||
|
||||
|
||||
@@ -7,3 +11,5 @@ def greet():
|
||||
-def farewell():
|
||||
- return "bye"
|
||||
+def farewell(name=None):
|
||||
+ if name is None:
|
||||
+ return "bye"
|
||||
+ return "bye " + name
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH 1/2] add the greeting module
|
||||
|
||||
---
|
||||
hello.py | 9 +++++++++
|
||||
1 file changed, 9 insertions(+)
|
||||
create mode 100644 hello.py
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
new file mode 100644
|
||||
index 0000000..a1b2c3d
|
||||
--- /dev/null
|
||||
+++ b/hello.py
|
||||
@@ -0,0 +1,9 @@
|
||||
+"""Greetings."""
|
||||
+
|
||||
+
|
||||
+def greet():
|
||||
+ return "hello"
|
||||
+
|
||||
+
|
||||
+def farewell():
|
||||
+ return "bye"
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH 2/2] greet by name and document it
|
||||
|
||||
The greeting takes a name now and the farewell mirrors it; the README
|
||||
documents both calls. Callers that pass nothing still get the old text.
|
||||
|
||||
The format follows the greeting spec [1].
|
||||
|
||||
[1] https://example.org/greeting-spec
|
||||
---
|
||||
README.md | 4 ++++
|
||||
hello.py | 8 ++++++--
|
||||
2 files changed, 10 insertions(+), 2 deletions(-)
|
||||
create mode 100644 README.md
|
||||
|
||||
diff --git a/README.md b/README.md
|
||||
new file mode 100644
|
||||
index 0000000..d4e5f6a
|
||||
--- /dev/null
|
||||
+++ b/README.md
|
||||
@@ -0,0 +1,4 @@
|
||||
+# hello
|
||||
+
|
||||
+Use `greet(name)` or `farewell(name)`; without a name both return the
|
||||
+plain text.
|
||||
diff --git a/hello.py b/hello.py
|
||||
index a1b2c3d..b7c8d9e 100644
|
||||
--- a/hello.py
|
||||
+++ b/hello.py
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Greetings."""
|
||||
|
||||
|
||||
-def greet():
|
||||
- return "hello"
|
||||
+def greet(name=None):
|
||||
+ if name is None:
|
||||
+ return "hello"
|
||||
+ return "hello " + name
|
||||
|
||||
|
||||
@@ -7,3 +11,5 @@ def greet():
|
||||
-def farewell():
|
||||
- return "bye"
|
||||
+def farewell(name=None):
|
||||
+ if name is None:
|
||||
+ return "bye"
|
||||
+ return "bye " + name
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH 1/2] add the greeting module
|
||||
|
||||
---
|
||||
hello.py | 9 +++++++++
|
||||
1 file changed, 9 insertions(+)
|
||||
create mode 100644 hello.py
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
new file mode 100644
|
||||
index 0000000..a1b2c3d
|
||||
--- /dev/null
|
||||
+++ b/hello.py
|
||||
@@ -0,0 +1,9 @@
|
||||
+"""Greetings."""
|
||||
+
|
||||
+
|
||||
+def greet():
|
||||
+ return "hello"
|
||||
+
|
||||
+
|
||||
+def farewell():
|
||||
+ return "bye"
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH 2/2] greet by name and document it
|
||||
|
||||
The greeting takes a name now and the farewell mirrors it; the README
|
||||
documents both calls. Callers that pass nothing still get the old text.
|
||||
|
||||
The format follows the greeting spec [1].
|
||||
|
||||
[1] https://example.org/greeting-spec
|
||||
---
|
||||
README.md | 4 ++++
|
||||
hello.py | 8 ++++++--
|
||||
2 files changed, 10 insertions(+), 2 deletions(-)
|
||||
create mode 100644 README.md
|
||||
|
||||
diff --git a/README.md b/README.md
|
||||
new file mode 100644
|
||||
index 0000000..d4e5f6a
|
||||
--- /dev/null
|
||||
+++ b/README.md
|
||||
@@ -0,0 +1,4 @@
|
||||
+# hello
|
||||
+
|
||||
+Call `greet(name)` or `farewell(name)`; without a name both return the
|
||||
+plain text.
|
||||
diff --git a/hello.py b/hello.py
|
||||
index a1b2c3d..b7c8d9e 100755
|
||||
--- a/hello.py
|
||||
+++ b/hello.py
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Greetings."""
|
||||
|
||||
|
||||
-def greet():
|
||||
- return "hello"
|
||||
+def greet(name=None):
|
||||
+ if name is None:
|
||||
+ return "hello"
|
||||
+ return "hello " + name
|
||||
|
||||
|
||||
@@ -7,3 +11,5 @@ def greet():
|
||||
-def farewell():
|
||||
- return "bye"
|
||||
+def farewell(name=None):
|
||||
+ if name is None:
|
||||
+ return "bye"
|
||||
+ return "bye " + name
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH 1/2] add the greeting module
|
||||
|
||||
---
|
||||
hello.py | 9 +++++++++
|
||||
1 file changed, 9 insertions(+)
|
||||
create mode 100644 hello.py
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
new file mode 100644
|
||||
index 0000000..a1b2c3d
|
||||
--- /dev/null
|
||||
+++ b/hello.py
|
||||
@@ -0,0 +1,9 @@
|
||||
+"""Greetings."""
|
||||
+
|
||||
+
|
||||
+def greet():
|
||||
+ return "hello"
|
||||
+
|
||||
+
|
||||
+def farewell():
|
||||
+ return "bye"
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH 2/2] greet by name and document it
|
||||
|
||||
---
|
||||
README.md | 4 ++++
|
||||
hello.py | 8 ++++++--
|
||||
2 files changed, 10 insertions(+), 2 deletions(-)
|
||||
create mode 100644 README.md
|
||||
|
||||
diff --git a/README.md b/README.md
|
||||
new file mode 100644
|
||||
index 0000000..d4e5f6a
|
||||
--- /dev/null
|
||||
+++ b/README.md
|
||||
@@ -0,0 +1,4 @@
|
||||
+# hello
|
||||
+
|
||||
+Call `greet(name)` or `farewell(name)`; without a name both return the
|
||||
+plain text.
|
||||
diff --git a/hello.py b/hello.py
|
||||
index a1b2c3d..b7c8d9e 100644
|
||||
--- a/hello.py
|
||||
+++ b/hello.py
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Greetings."""
|
||||
|
||||
|
||||
-def greet():
|
||||
- return "hello"
|
||||
+def greet(name=None):
|
||||
+ if name is None:
|
||||
+ return "hello"
|
||||
+ return "hello " + name
|
||||
|
||||
|
||||
@@ -7,3 +11,5 @@ def greet():
|
||||
-def farewell():
|
||||
- return "bye"
|
||||
+def farewell(name=None):
|
||||
+ if name is None:
|
||||
+ return "bye"
|
||||
+ return "bye " + name
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH 1/2] add the greeting module
|
||||
|
||||
---
|
||||
hello.py | 9 +++++++++
|
||||
1 file changed, 9 insertions(+)
|
||||
create mode 100644 hello.py
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
new file mode 100644
|
||||
index 0000000..a1b2c3d
|
||||
--- /dev/null
|
||||
+++ b/hello.py
|
||||
@@ -0,0 +1,9 @@
|
||||
+"""Greetings."""
|
||||
+
|
||||
+
|
||||
+def greet():
|
||||
+ return "hello"
|
||||
+
|
||||
+
|
||||
+def farewell():
|
||||
+ return "bye"
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH 2/2] greet by name and document it
|
||||
|
||||
The greeting takes a name now and the farewell mirrors it; the README
|
||||
documents both calls. Callers that pass nothing still get the old text.
|
||||
|
||||
The format follows the greeting spec [1].
|
||||
|
||||
[1] https://example.org/greeting-spec
|
||||
---
|
||||
README.md | 4 ++++
|
||||
hello.py | 8 ++++++--
|
||||
2 files changed, 10 insertions(+), 2 deletions(-)
|
||||
create mode 100644 README.md
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
index a1b2c3d..b7c8d9e 100644
|
||||
--- a/hello.py
|
||||
+++ b/hello.py
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Greetings."""
|
||||
|
||||
|
||||
-def greet():
|
||||
- return "hello"
|
||||
+def greet(name=None):
|
||||
+ if name is None:
|
||||
+ return "hello"
|
||||
+ return "hello " + name
|
||||
|
||||
|
||||
@@ -7,3 +11,5 @@ def greet():
|
||||
-def farewell():
|
||||
- return "bye"
|
||||
+def farewell(name=None):
|
||||
+ if name is None:
|
||||
+ return "bye"
|
||||
+ return "bye " + name
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
From bcdef0123456789abcd000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH 1/3] add the greeting module
|
||||
|
||||
---
|
||||
hello.py | 9 +++++++++
|
||||
1 file changed, 9 insertions(+)
|
||||
create mode 100644 hello.py
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
new file mode 100644
|
||||
index 1234567..89abcde
|
||||
--- /dev/null
|
||||
+++ b/hello.py
|
||||
@@ -2,0 +3,9 @@
|
||||
+"""Greetings."""
|
||||
+
|
||||
+
|
||||
+def greet():
|
||||
+ return "hello"
|
||||
+
|
||||
+
|
||||
+def farewell():
|
||||
+ return "bye"
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.55.0
|
||||
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
From cdef0123456789abcd0000000000000000000000 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH 2/3] greet by name and document it
|
||||
|
||||
greet() takes a name now and the farewell mirrors it; the README
|
||||
documents both calls. Callers that pass nothing still get the old text.
|
||||
|
||||
The format follows the greeting spec [1].
|
||||
|
||||
[1] https://example.org/greeting-spec
|
||||
---
|
||||
README.md | 4 ++++
|
||||
hello.py | 8 ++++++--
|
||||
2 files changed, 10 insertions(+), 2 deletions(-)
|
||||
create mode 100644 README.md
|
||||
|
||||
diff --git a/README.md b/README.md
|
||||
new file mode 100644
|
||||
index 1234567..89abcde
|
||||
--- /dev/null
|
||||
+++ b/README.md
|
||||
@@ -2,0 +3,4 @@
|
||||
+# hello
|
||||
+
|
||||
+Call `greet(name)` or `farewell(name)`; without a name both return the
|
||||
+plain text.
|
||||
diff --git a/hello.py b/hello.py
|
||||
index 1234567..89abcde 100644
|
||||
--- a/hello.py
|
||||
+++ b/hello.py
|
||||
@@ -3,9 +3,13 @@
|
||||
"""Greetings."""
|
||||
|
||||
|
||||
-def greet():
|
||||
- return "hello"
|
||||
+def greet(name=None):
|
||||
+ if name is None:
|
||||
+ return "hello"
|
||||
+ return "hello " + name
|
||||
|
||||
|
||||
@@ -9,3 +13,5 @@ def greet():
|
||||
-def farewell():
|
||||
- return "bye"
|
||||
+def farewell(name=None):
|
||||
+ if name is None:
|
||||
+ return "bye"
|
||||
+ return "bye " + name
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.55.0
|
||||
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH 1/2] add the greeting module
|
||||
|
||||
---
|
||||
hello.py | 9 +++++++++
|
||||
1 file changed, 9 insertions(+)
|
||||
create mode 100644 hello.py
|
||||
|
||||
diff --git a/hello.py b/hello.py
|
||||
new file mode 100644
|
||||
index 0000000..a1b2c3d
|
||||
--- /dev/null
|
||||
+++ b/hello.py
|
||||
@@ -0,0 +1,9 @@
|
||||
+"""Greetings."""
|
||||
+
|
||||
+
|
||||
+def greet():
|
||||
+ return "hello"
|
||||
+
|
||||
+
|
||||
+def farewell():
|
||||
+ return "bye"
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
|
||||
From: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH 2/2] greet by name and document it
|
||||
|
||||
The greeting takes a name now and the farewell mirrors it; the README
|
||||
documents both calls. Callers that pass nothing still get the old text.
|
||||
|
||||
The format follows the greeting spec [1].
|
||||
|
||||
[1] https://example.org/greeting-spec
|
||||
---
|
||||
README.md | 4 ++++
|
||||
hello.py | 8 ++++++--
|
||||
2 files changed, 10 insertions(+), 2 deletions(-)
|
||||
create mode 100644 README.md
|
||||
|
||||
diff --git a/README.md b/README.md
|
||||
new file mode 100644
|
||||
index 0000000..d4e5f6a
|
||||
--- /dev/null
|
||||
+++ b/README.md
|
||||
@@ -0,0 +1,4 @@
|
||||
+# hello
|
||||
+
|
||||
+Call `greet(name)` or `farewell(name)`; without a name both return the
|
||||
+plain text.
|
||||
diff --git a/hello.py b/hello.py
|
||||
index a1b2c3d..b7c8d9e 100644
|
||||
--- a/hello.py
|
||||
+++ b/hello.py
|
||||
@@ -1,9 +1,13 @@
|
||||
"""Greetings."""
|
||||
|
||||
|
||||
-def greet():
|
||||
- return "hello"
|
||||
+def greet(name=None):
|
||||
+ if name is None:
|
||||
+ return "hello"
|
||||
+ return "hello " + name
|
||||
|
||||
|
||||
@@ -7,3 +11,5 @@ def greet():
|
||||
-def farewell():
|
||||
- return "bye"
|
||||
+def farewell(name=None):
|
||||
+ if name is None:
|
||||
+ return "bye"
|
||||
+ return "bye " + name
|
||||
|
||||
base-commit: 0000000000000000000000000000000000000000
|
||||
--
|
||||
2.51.0
|
||||
|
||||
5
tests/Goldens/fixture/dispositions/0001-a.patch
Normal file
5
tests/Goldens/fixture/dispositions/0001-a.patch
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
x
|
||||
ANCHOR TEXT
|
||||
y
|
||||
ANCHOR TEXT
|
||||
CRLF
|
||||
23519
tests/Goldens/fixture/pipeline.json
Normal file
23519
tests/Goldens/fixture/pipeline.json
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,60 @@
|
|||
From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001
|
||||
From: Jörijn Tester <tester@example.com>
|
||||
Date: Wed, 24 Sep 2026 10:00:00 +0200
|
||||
Subject: [PATCH v2 1/3] [RFC] add the docs and a tool, with a subject long enough to
|
||||
be folded onto a second line by git
|
||||
|
||||
The docs explain the tool. A non-breaking space sits in this line,
|
||||
|
||||
and the line before holds nothing else.
|
||||
|
||||
Signed-off-by: Jörijn Tester <tester@example.com>
|
||||
Co-Authored-By: Someone <someone@example.com>
|
||||
---
|
||||
docs/guide.md | 22 ++++++++++++++++++++++
|
||||
tool.py | 4 ++++
|
||||
2 files changed, 26 insertions(+)
|
||||
create mode 100644 docs/guide.md
|
||||
create mode 100755 tool.py
|
||||
|
||||
diff --git a/docs/guide.md b/docs/guide.md
|
||||
new file mode 100644
|
||||
index 0000000..1234567
|
||||
--- /dev/null
|
||||
+++ b/docs/guide.md
|
||||
@@ -0,0 +1,22 @@
|
||||
+# Guide
|
||||
+## Straight after the title
|
||||
+
|
||||
+Intro text.
|
||||
+
|
||||
+## Install
|
||||
+
|
||||
+Run the installer.
|
||||
+
|
||||
+```sh
|
||||
+# not a heading, inside a fence
|
||||
+make install
|
||||
+```
|
||||
+
|
||||
+####### seven hashes are no heading
|
||||
+#nospace is no heading either
|
||||
+ ~~~
|
||||
+## inside a fence indented by three
|
||||
+ ~~~
|
||||
+ ~~~
|
||||
+## a fence indented by four is none
|
||||
+Done.
|
||||
diff --git a/tool.py b/tool.py
|
||||
new file mode 100755
|
||||
index 0000000..89abcde
|
||||
--- /dev/null
|
||||
+++ b/tool.py
|
||||
@@ -0,0 +1,4 @@
|
||||
+#!/usr/bin/env python3
|
||||
+import sys
|
||||
+print("é ünïcödé – a dash, and a line long enough that its excerpt is cut at ninety code points …")
|
||||
+sys.exit(0)
|
||||
--
|
||||
2.55.0
|
||||
|
||||
40
tests/Goldens/fixture/rich/v2-0002-rename-the-tool.patch
Normal file
40
tests/Goldens/fixture/rich/v2-0002-rename-the-tool.patch
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001
|
||||
From: Jörijn Tester <tester@example.com>
|
||||
Date: Wed, 24 Sep 2026 10:05:00 +0200
|
||||
Subject: [PATCH v2 2/3] rename the tool
|
||||
|
||||
---
|
||||
README.md | 2 --
|
||||
tool.py => bin/tool.py | 4 ++--
|
||||
2 files changed, 2 insertions(+), 4 deletions(-)
|
||||
delete mode 100644 README.md
|
||||
rename tool.py => bin/tool.py (80%)
|
||||
mode change 100755 => 100644
|
||||
|
||||
diff --git a/README.md b/README.md
|
||||
deleted file mode 100644
|
||||
index 1111111..0000000
|
||||
--- a/README.md
|
||||
+++ /dev/null
|
||||
@@ -1,2 +0,0 @@
|
||||
-# Old
|
||||
-text
|
||||
diff --git a/tool.py b/bin/tool.py
|
||||
similarity index 80%
|
||||
rename from tool.py
|
||||
rename to bin/tool.py
|
||||
old mode 100755
|
||||
new mode 100644
|
||||
index 89abcde..fedcba9
|
||||
--- a/tool.py
|
||||
+++ b/bin/tool.py
|
||||
@@ -1 +1 @@
|
||||
-#!/usr/bin/env python3
|
||||
+#!/usr/bin/python3
|
||||
@@ -3,2 +3,2 @@ import sys
|
||||
-print("é ünïcödé – a dash")
|
||||
+print("ascii")
|
||||
sys.exit(0)
|
||||
--
|
||||
2.55.0
|
||||
|
||||
26
tests/Goldens/fixture/rich/v2-0003-add-tests.patch
Normal file
26
tests/Goldens/fixture/rich/v2-0003-add-tests.patch
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
From 3333333333333333333333333333333333333333 Mon Sep 17 00:00:00 2001
|
||||
From: Jörijn Tester <tester@example.com>
|
||||
Date: Wed, 24 Sep 2026 10:10:00 +0200
|
||||
Subject: [PATCH v2 3/3] add tests
|
||||
|
||||
Reviewed-by: Someone <someone@example.com>
|
||||
---
|
||||
tests/test_tool.py | 3 +++
|
||||
1 file changed, 3 insertions(+)
|
||||
create mode 100644 tests/test_tool.py
|
||||
|
||||
diff --git a/tests/test_tool.py b/tests/test_tool.py
|
||||
new file mode 100644
|
||||
index 0000000..1111111
|
||||
--- /dev/null
|
||||
+++ b/tests/test_tool.py
|
||||
@@ -0,0 +1,3 @@
|
||||
+def test_tool():
|
||||
+ assert True # x
y
|
||||
+ pass
|
||||
|
||||
base-commit: 0123456789abcdef0123456789abcdef01234567
|
||||
prerequisite-patch-id: abcdef0123456789abcdef0123456789abcdef01
|
||||
--
|
||||
2.55.0
|
||||
|
||||
1
tests/Goldens/fixture/slots/fixture.json
Normal file
1
tests/Goldens/fixture/slots/fixture.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{}
|
||||
1
tests/Goldens/fixture/slots/slots/1/slot.json
Normal file
1
tests/Goldens/fixture/slots/slots/1/slot.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"appUrl": "http://localhost:8081/", "apiUrls": ["http://a"], "dbUrl": "postgresql://u:p@127.0.0.1:1/x", "login": "fixture.json"}
|
||||
1
tests/Goldens/fixture/slots/slots/10/slot.json
Normal file
1
tests/Goldens/fixture/slots/slots/10/slot.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"appUrl": "https://h:8443"}
|
||||
1
tests/Goldens/fixture/slots/slots/2/slot.json
Normal file
1
tests/Goldens/fixture/slots/slots/2/slot.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"appUrl": "ftp://x"}
|
||||
1
tests/Goldens/fixture/slots/slots/3/slot.json
Normal file
1
tests/Goldens/fixture/slots/slots/3/slot.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{nope
|
||||
1
tests/Goldens/fixture/slots/slots/4/slot.json
Normal file
1
tests/Goldens/fixture/slots/slots/4/slot.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"appUrl": "http://x", "apiUrls": [1]}
|
||||
1
tests/Goldens/fixture/slots/slots/5/slot.json
Normal file
1
tests/Goldens/fixture/slots/slots/5/slot.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"appUrl": "http://x", "dbUrl": "postgresql://u@db.example.com/x"}
|
||||
1
tests/Goldens/fixture/slots/slots/6/slot.json
Normal file
1
tests/Goldens/fixture/slots/slots/6/slot.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"appUrl": "http://x", "login": "missing.json"}
|
||||
1
tests/Goldens/fixture/slots/slots/7/slot.json
Normal file
1
tests/Goldens/fixture/slots/slots/7/slot.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"appUrl": "http://x", "login": 5}
|
||||
1
tests/Goldens/fixture/slots/slots/x/slot.json
Normal file
1
tests/Goldens/fixture/slots/slots/x/slot.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
[]
|
||||
5
tests/Goldens/fixture/stream-success.jsonl
Normal file
5
tests/Goldens/fixture/stream-success.jsonl
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
{"type":"system","subtype":"init","cwd":"/home/jorijn/repos/example","session_id":"11111111-2222-4333-8444-555555555555","tools":["Bash","Glob","Grep","Read","StructuredOutput"],"mcp_servers":[],"model":"claude-opus-5","permissionMode":"default","slash_commands":[],"apiKeySource":"none","claude_code_version":"2.1.263","output_style":"default","agents":["claude","claude-code-guide","Explore","general-purpose","Plan"],"skills":[],"plugins":[],"capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","msg_lifecycle_v1"],"analytics_disabled":true,"product_feedback_disabled":true,"uuid":"685017ca-8568-4652-9e23-830f5da1970d","messaging_socket_path":"/run/user/1000/cc-socks/254300.sock","fast_mode_state":"off","fast_mode_disabled_reason":"unknown"}
|
||||
{"type":"assistant","message":{"model":"claude-opus-5","id":"msg_011Cf7xXggLZUyvd46RvtTQK","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_012DoTWyn2Zsw7bzvkYnA6bq","name":"StructuredOutput","input":{"coverage":[{"item":"R1","verdict":"clear","basis":"fixture"}],"findings":[],"notes":[],"verdict":"SEND-READY"},"caller":{"type":"direct"}}],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":8630,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":8630},"output_tokens":25,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"11111111-2222-4333-8444-555555555555","uuid":"27b4e645-8830-4ed3-80e7-3b9b72786291","timestamp":"2026-09-16T23:07:12.378Z","request_id":"req_011Cf7xXgFnbpSD2d9VNWVBQ"}
|
||||
{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_012DoTWyn2Zsw7bzvkYnA6bq","type":"tool_result","content":"Structured output provided successfully"}]},"parent_tool_use_id":null,"session_id":"11111111-2222-4333-8444-555555555555","uuid":"5ac21f12-5a67-4ed3-88bd-699742874b2b","timestamp":"2026-09-16T23:07:12.385Z","tool_use_result":"Structured output provided successfully"}
|
||||
{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1789614000,"rateLimitType":"five_hour","overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false,"unifiedWindows":{"five_hour":{"utilization":0.2,"resetsAt":1789614000},"seven_day":{"utilization":0.38,"resetsAt":1789783200}}},"uuid":"56cea5e6-f4ec-4c14-a61d-2d21e1faa9e7","session_id":"11111111-2222-4333-8444-555555555555"}
|
||||
{"duration_api_ms":1916,"stop_reason":"tool_use","session_id":"11111111-2222-4333-8444-555555555555","total_cost_usd":0.090135,"usage":{"input_tokens":2,"cache_creation_input_tokens":8630,"cache_read_input_tokens":0,"output_tokens":153,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":8630,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[],"speed":"standard"},"modelUsage":{"claude-opus-5":{"inputTokens":2,"outputTokens":153,"cacheReadInputTokens":0,"cacheCreationInputTokens":8630,"webSearchRequests":0,"costUSD":0.090135,"contextWindow":1000000,"maxOutputTokens":64000,"thinkingTokens":0,"canonicalModel":"claude-opus-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"unknown","subagent_stats":{"spawned":0,"requested":{"background":0,"foreground":0,"unset":0},"started_in_background":0,"max_depth":0,"spawned_by_subagents":0,"completed":0,"failed":0,"killed":{"parent":0,"user":0,"system":0},"refused":{"depth_limit":0,"concurrency_limit":0,"budget":0},"by_type":{}},"is_error":false,"num_turns":2,"subtype":"success","api_error_status":null,"result":"{\"coverage\":[{\"item\":\"R1\",\"verdict\":\"clear\",\"basis\":\"fixture\"}],\"findings\":[],\"notes\":[],\"verdict\":\"SEND-READY\"}","structured_output":{"coverage":[{"item":"R1","verdict":"clear","basis":"fixture"}],"findings":[],"notes":[],"verdict":"SEND-READY"},"ttft_ms":1972,"type":"result","duration_ms":1984,"uuid":"7f3d8d6f-23df-4f6e-8114-ae6caddd353b","ttft_stream_ms":913,"time_to_request_ms":71,"first_content_frame_ms":913,"queued_turn_count":0}
|
||||
431
tests/Goldens/main.cpp
Normal file
431
tests/Goldens/main.cpp
Normal file
|
|
@ -0,0 +1,431 @@
|
|||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// The pure pipeline against the goldens: fixture/pipeline.json holds the
|
||||
// recorded answers over the fixtures next to it — the inventory, the plans,
|
||||
// the keys, the prompts, the normalized results, the stream, the config.
|
||||
// Each result is compared as DumpFile writes it, so a key out of place fails
|
||||
// as surely as a wrong value: the dump, the shared files and the prompts are
|
||||
// made of these. A deliberate change edits the goldens in the same commit.
|
||||
|
||||
import std;
|
||||
import Crafter.Review;
|
||||
namespace fs = std::filesystem;
|
||||
using namespace Crafter::Review;
|
||||
|
||||
namespace {
|
||||
std::int32_t Failures = 0;
|
||||
std::int32_t Checks = 0;
|
||||
|
||||
void Check(bool cond, std::string_view what) {
|
||||
++Checks;
|
||||
if (!cond) {
|
||||
std::println(std::cerr, "FAIL: {}", what);
|
||||
++Failures;
|
||||
}
|
||||
}
|
||||
|
||||
// Where two texts part, for the failure message.
|
||||
std::string Parting(std::string_view got, std::string_view want) {
|
||||
std::size_t at = 0;
|
||||
while (at < got.size() && at < want.size() && got[at] == want[at]) ++at;
|
||||
auto window = [&](std::string_view text) { return Dyn::Repr(text.substr(at > 40 ? at - 40 : 0, 120)); };
|
||||
return std::format("at byte {}: got {} want {}", at, window(got), window(want));
|
||||
}
|
||||
|
||||
void Same(std::string_view got, std::string_view want, std::string_view what) {
|
||||
Check(got == want, got == want ? std::string(what) : std::format("{}: {}", what, Parting(got, want)));
|
||||
}
|
||||
|
||||
void SameJson(const Json& got, const Json& want, std::string_view what) {
|
||||
Same(DumpFile(got), DumpFile(want), what);
|
||||
}
|
||||
|
||||
std::vector<std::string> Strings(const Json& array) {
|
||||
std::vector<std::string> out;
|
||||
if (array.is_null()) return out;
|
||||
for (const Json& item : array) out.push_back(item.get<std::string>());
|
||||
return out;
|
||||
}
|
||||
|
||||
Json ToJson(const std::vector<std::string>& values) {
|
||||
Json out = Json::array();
|
||||
for (const std::string& value : values) out.push_back(value);
|
||||
return out;
|
||||
}
|
||||
|
||||
Json Optional(const std::optional<std::string>& value) {
|
||||
return value ? Json(*value) : Json();
|
||||
}
|
||||
|
||||
std::optional<std::string> OptionalString(const Json& value) {
|
||||
if (value.is_null()) return std::nullopt;
|
||||
return value.get<std::string>();
|
||||
}
|
||||
|
||||
Json CommitCodeJson(const Plan::CommitCode& cc) {
|
||||
Json body = Json::object();
|
||||
Json code = Json::object();
|
||||
Json docs = Json::object();
|
||||
Json message = Json::object();
|
||||
Json upto = Json::object();
|
||||
for (const auto& [k, v] : cc.body) body[std::to_string(k)] = v;
|
||||
for (const auto& [k, v] : cc.code) code[std::to_string(k)] = v;
|
||||
for (const auto& [k, v] : cc.docs) docs[std::to_string(k)] = ToJson(v);
|
||||
for (const auto& [k, v] : cc.message) message[std::to_string(k)] = v;
|
||||
for (const auto& [k, v] : cc.upto) upto[std::to_string(k)] = v;
|
||||
return {{"body", body}, {"code", code}, {"docs", docs}, {"msg", message}, {"range", cc.range}, {"upto", upto}, {"base", cc.base}};
|
||||
}
|
||||
|
||||
void CheckSeries(const std::string& name, const Json& golden) {
|
||||
const std::string dir = golden.at("dir").get<std::string>();
|
||||
const Inventory::Built built = Inventory::Build("commits", dir);
|
||||
SameJson(built.out, golden.at("inventory"), std::format("{}: inventory", name));
|
||||
SameJson(ToJson(built.lines), golden.at("lines"), std::format("{}: lines", name));
|
||||
Same(Artifact::ArtifactHash("commits", dir), golden.at("hash").get<std::string>(), std::format("{}: artifact hash", name));
|
||||
const Plan::CommitCode cc = Plan::CommitCodeOf(Artifact::PatchTexts(dir));
|
||||
SameJson(CommitCodeJson(cc), golden.at("commitCode"), std::format("{}: commit_code", name));
|
||||
const Json& units = built.out.at("units");
|
||||
for (auto it = golden.at("codeKeyParts").begin(); it != golden.at("codeKeyParts").end(); ++it) {
|
||||
const auto [ident, deps] = Plan::CodeKeyParts(it.key(), cc);
|
||||
SameJson(Json::array({ident, ToJson(deps)}), it.value(), std::format("{}: code_key_parts {}", name, it.key()));
|
||||
}
|
||||
std::map<std::string, Json> blocksByLens;
|
||||
std::map<std::string, Json> wholeByLens;
|
||||
const std::vector<std::string> exclude = {"**/*.test.*", "docs/**", "tests/**"};
|
||||
for (const Plan::Lens& lens : Plan::Lenses) {
|
||||
const Plan::LensPlan plan = Plan::PlanLens(lens.file, units, built.lines, {}, exclude);
|
||||
Json blocks = Json::array();
|
||||
for (const Json& block : plan.blocks) blocks.push_back(block);
|
||||
blocksByLens[std::string(lens.file)] = blocks;
|
||||
wholeByLens[std::string(lens.file)] = plan.whole;
|
||||
}
|
||||
for (auto it = golden.at("keys").begin(); it != golden.at("keys").end(); ++it) {
|
||||
const std::vector<std::string> tag = Dyn::Split(it.key(), "|");
|
||||
const std::string& lensFile = tag[0];
|
||||
const std::string environment = tag[1] == "None" ? std::string() : tag[1];
|
||||
const std::vector<std::string> ids = tag[2].empty() ? std::vector<std::string>() : Dyn::Split(tag[2], ",");
|
||||
Json keys = Json::object();
|
||||
for (const Json& job : blocksByLens[lensFile]) {
|
||||
if (job.at("kind") != "block") continue;
|
||||
const std::string unit = job.at("unit").get<std::string>();
|
||||
const Json* found = nullptr;
|
||||
for (const Json& u : units) {
|
||||
if (u.at("id") == unit) found = &u;
|
||||
}
|
||||
keys[unit] = Optional(Plan::BlockReuseKey(job, lensFile, Plan::UnitText(built.lines, *found), cc, ids, std::string(64, 'c'), 1, environment));
|
||||
}
|
||||
SameJson(keys, it.value(), std::format("{}: block keys {}", name, it.key()));
|
||||
const Json& whole = wholeByLens[lensFile];
|
||||
const Json wholeKey = whole.is_null() ? Json() : Optional(Plan::WholeCodeKey(whole, lensFile, cc, ids, std::string(64, 'c'), 1, environment));
|
||||
SameJson(wholeKey, golden.at("wholeKeys").at(it.key()), std::format("{}: whole key {}", name, it.key()));
|
||||
}
|
||||
if (!golden.contains("plans")) return;
|
||||
Same(Artifact::PatchHead(dir).value_or("None"), golden.at("head").is_null() ? "None" : golden.at("head").get<std::string>(), std::format("{}: patch_head", name));
|
||||
SameJson(ToJson(Artifact::PatchFiles(dir)), golden.at("patchFiles"), std::format("{}: patch_files", name));
|
||||
for (const auto& [k, text] : Artifact::PatchTexts(dir)) {
|
||||
const Plan::PatchParts parts = Plan::PartsOf(text);
|
||||
SameJson(Json::array({parts.hasBody, parts.code, parts.base, ToJson(parts.docs), parts.message}), golden.at("patchParts").at(std::to_string(k)),
|
||||
std::format("{}: patch_parts {}", name, k));
|
||||
}
|
||||
for (std::size_t i = 0; i < units.size(); ++i) {
|
||||
const Json& want = golden.at("units").at(i);
|
||||
const std::string id = units[i].at("id").get<std::string>();
|
||||
const std::string text = Plan::UnitText(built.lines, units[i]);
|
||||
Same(Plan::UnitKind(units[i]), want.at("kind").get<std::string>(), std::format("{}: unit_kind {}", name, id));
|
||||
Check(Plan::IsDocUnit(id) == want.at("doc").get<bool>(), std::format("{}: is_doc_unit {}", name, id));
|
||||
SameJson(Optional(Plan::UnitPath(id)), want.at("path"), std::format("{}: unit_path {}", name, id));
|
||||
Same(text, want.at("text").get<std::string>(), std::format("{}: unit_text {}", name, id));
|
||||
Same(Plan::CodeNorm(text), want.at("norm").get<std::string>(), std::format("{}: code_norm {}", name, id));
|
||||
}
|
||||
std::vector<std::string> all;
|
||||
std::vector<std::string> statics;
|
||||
for (const Plan::Lens& lens : Plan::Lenses) {
|
||||
all.emplace_back(lens.file);
|
||||
if (lens.file != Plan::FunctionalLens) statics.emplace_back(lens.file);
|
||||
}
|
||||
const std::vector<std::string> functional = {std::string(Plan::FunctionalLens)};
|
||||
SameJson(ToJson(Plan::NotReviewed(units, built.lines, all)), golden.at("notReviewed").at("all"), std::format("{}: not_reviewed all", name));
|
||||
SameJson(ToJson(Plan::NotReviewed(units, built.lines, statics)), golden.at("notReviewed").at("static"), std::format("{}: not_reviewed static", name));
|
||||
SameJson(ToJson(Plan::NotReviewed(units, built.lines, functional, exclude)), golden.at("notReviewed").at("functional"), std::format("{}: not_reviewed functional", name));
|
||||
std::vector<Json> jobs;
|
||||
for (const Plan::Lens& lens : Plan::Lenses) {
|
||||
for (const bool excluded : {false, true}) {
|
||||
const Plan::LensPlan plan = Plan::PlanLens(lens.file, units, built.lines, {}, excluded ? std::span<const std::string>(exclude) : std::span<const std::string>());
|
||||
Json blocks = Json::array();
|
||||
for (const Json& block : plan.blocks) blocks.push_back(block);
|
||||
const std::string key = std::format("{}{}", lens.file, excluded ? ":exclude" : "");
|
||||
SameJson(Json{{"whole", plan.whole}, {"blocks", blocks}}, golden.at("plans").at(key), std::format("{}: plan_lens {}", name, key));
|
||||
if (!excluded) {
|
||||
if (!plan.whole.is_null()) jobs.push_back(plan.whole);
|
||||
jobs.insert(jobs.end(), plan.blocks.begin(), plan.blocks.end());
|
||||
}
|
||||
}
|
||||
}
|
||||
SameJson(Plan::Estimate(jobs, 123457, {{"repo-better-solution", 4100}, {"repo-functional", 9000}}), golden.at("estimate"), std::format("{}: estimate", name));
|
||||
}
|
||||
|
||||
void CheckPlan(const Json& g) {
|
||||
for (const Json& entry : g.at("unitIds")) {
|
||||
const std::string id = entry.at("id").get<std::string>();
|
||||
Same(Plan::UnitKindOf(id), entry.at("kind").get<std::string>(), std::format("unit_kind {}", Dyn::Repr(id)));
|
||||
Check(Plan::IsDocUnit(id) == entry.at("doc").get<bool>(), std::format("is_doc_unit {}", Dyn::Repr(id)));
|
||||
SameJson(Optional(Plan::UnitPath(id)), entry.at("path"), std::format("unit_path {}", Dyn::Repr(id)));
|
||||
}
|
||||
for (const Json& entry : g.at("excludedBy")) {
|
||||
const std::vector<std::string> globs = Strings(entry.at(1));
|
||||
SameJson(Optional(Plan::ExcludedBy(entry.at(0).get<std::string>(), globs)), entry.at(2), std::format("excluded_by {}", DumpCompactSorted(entry)));
|
||||
}
|
||||
for (const Json& entry : g.at("gates")) {
|
||||
const Json& args = entry.at(0);
|
||||
const std::vector<std::string> only = args.contains("only") ? Strings(args.at("only")) : std::vector<std::string>();
|
||||
const std::vector<std::string> without = args.contains("without") ? Strings(args.at("without")) : std::vector<std::string>();
|
||||
const std::vector<std::string> off = args.contains("off") ? Strings(args.at("off")) : std::vector<std::string>();
|
||||
Json got = Json::array();
|
||||
for (const Plan::Gate& gate : Plan::GatesFor(only, without, off)) {
|
||||
Json lenses = Json::array();
|
||||
for (const std::string_view lens : gate.lenses) lenses.push_back(lens);
|
||||
got.push_back(Json::array({gate.title, lenses}));
|
||||
}
|
||||
SameJson(got, entry.at(1), std::format("gates_for {}", DumpCompactSorted(args)));
|
||||
}
|
||||
for (const Json& entry : g.at("codeNorm")) {
|
||||
Same(Plan::CodeNorm(entry.at(0).get<std::string>()), entry.at(1).get<std::string>(), std::format("code_norm {}", Dyn::Repr(entry.at(0).get<std::string>())));
|
||||
}
|
||||
SameJson(Optional(Plan::ReuseKey({{"kind", "block"}, {"unit", "U"}}, "repo-bug-prover.md", "T", {"d", "b"}, {"w2", "w1"}, "cs", 1)), g.at("reuseKey"), "reuse_key");
|
||||
for (const Json& entry : g.at("readsOf")) Check(Plan::ReadsOf(entry.at(0)) == entry.at(1).get<std::int64_t>(), std::format("reads_of {}", DumpCompactSorted(entry.at(0))));
|
||||
for (const Json& entry : g.at("readIn")) {
|
||||
Check(Plan::ReadIn(entry.at(0), entry.at(1).get<std::string>(), entry.at(2).get<std::int64_t>()) == entry.at(3).get<bool>(), std::format("read_in {}", DumpCompactSorted(entry)));
|
||||
}
|
||||
SameJson(Plan::Rebind(g.at("rebind").at(0), "p2:hello.py#3"), g.at("rebind").at(1), "rebind");
|
||||
}
|
||||
|
||||
void CheckPrompts(const Json& g, const Json& series) {
|
||||
const Json& p = g.at("prompts");
|
||||
Same(Prompt::SepRun, p.at("separators").at(0).get<std::string>(), "SEP_RUN");
|
||||
Same(Prompt::SepLens, p.at("separators").at(1).get<std::string>(), "SEP_LENS");
|
||||
Same(Prompt::SepTail, p.at("separators").at(2).get<std::string>(), "SEP_TAIL");
|
||||
Same(Prompt::GenericVocab, p.at("genericVocab").get<std::string>(), "GENERIC_VOCAB");
|
||||
Same(Prompt::WholeFirstRepo, p.at("wholeText").at("first-repo").get<std::string>(), "WHOLE_TEXT first-repo");
|
||||
Same(Prompt::WholeFunctional, p.at("wholeText").at("functional").get<std::string>(), "WHOLE_TEXT functional");
|
||||
Same(Prompt::FunctionalBlockHint, p.at("blockHint").get<std::string>(), "FUNCTIONAL_BLOCK_HINT");
|
||||
Same(Prompt::ShotRules, p.at("shotRules").get<std::string>(), "SHOT_RULES");
|
||||
Same(Prompt::HintOutside, p.at("kindHints").at("outside").get<std::string>(), "KIND_HINTS_REPO outside");
|
||||
Same(Prompt::HintAbsent, p.at("kindHints").at("absent").get<std::string>(), "KIND_HINTS_REPO absent");
|
||||
Same(Prompt::SystemText(), p.at("systemText").get<std::string>(), "system_text");
|
||||
for (auto it = p.at("charterSha").begin(); it != p.at("charterSha").end(); ++it) {
|
||||
Same(Plan::Sha(Prompt::Charter(it.key())), it.value().get<std::string>(), std::format("charter sha {}", it.key()));
|
||||
}
|
||||
for (const Json& entry : p.at("runLayer")) {
|
||||
const Json& s = series.at(entry.at("series").get<std::string>());
|
||||
const Json& args = entry.at("args");
|
||||
const std::vector<std::string> trees = Strings(args.at("trees"));
|
||||
const std::vector<std::string> context = Strings(args.at("context_paths"));
|
||||
const std::vector<std::string> lines = Strings(s.at("lines"));
|
||||
Same(Prompt::RunLayer(args.at("artifact_rel").get<std::string>(), args.at("base").get<std::string>(), args.at("date").get<std::string>(), trees,
|
||||
s.at("hash").get<std::string>(), lines, s.at("inventory").at("units"), context, args.at("repo_name").get<std::string>()),
|
||||
entry.at("text").get<std::string>(), std::format("run_layer {} {}", entry.at("series").get<std::string>(), DumpCompactSorted(args)));
|
||||
}
|
||||
for (const Json& entry : p.at("appBlock")) {
|
||||
Same(Prompt::AppBlock(entry.at("functional"), OptionalString(entry.at("fixture")), OptionalString(entry.at("totp")), entry.at("slots").get<bool>()),
|
||||
entry.at("text").get<std::string>(), std::format("app_block {}", DumpCompactSorted(entry.at("functional"))));
|
||||
}
|
||||
for (const Json& entry : p.at("stackText")) {
|
||||
Same(Prompt::StackText(entry.at("stack"), OptionalString(entry.at("totp"))), entry.at("text").get<std::string>(), "stack_text");
|
||||
}
|
||||
for (const Json& entry : p.at("dbBlock")) {
|
||||
const std::optional<bool> bypass = entry.at("bypass").is_null() ? std::nullopt : std::optional<bool>(entry.at("bypass").get<bool>());
|
||||
Same(Prompt::DbBlock(entry.at("supabase"), "/app/bin/crafter-review sql", OptionalString(entry.at("user")), entry.at("withApp").get<bool>(),
|
||||
OptionalString(entry.at("checked")), bypass),
|
||||
entry.at("text").get<std::string>(), std::format("db_block {}", DumpCompactSorted(entry.at("supabase"))));
|
||||
}
|
||||
for (const Json& entry : p.at("lensLayer")) {
|
||||
const std::string lensFile = entry.at("lensFile").get<std::string>();
|
||||
Same(Prompt::LensLayer(lensFile, Prompt::Charter(lensFile), "DISPOSITIONS BLOCK", OptionalString(entry.at("app")).value_or(""),
|
||||
OptionalString(entry.at("summary")).value_or(""), OptionalString(entry.at("db")).value_or("")),
|
||||
entry.at("text").get<std::string>(), std::format("lens_layer {}", lensFile));
|
||||
}
|
||||
for (const Json& entry : p.at("tails")) {
|
||||
const Json& s = series.at(entry.at("series").get<std::string>());
|
||||
const Json& plan = s.at("plans").at(entry.at("plan").get<std::string>());
|
||||
const Json* job = plan.at("whole").is_object() && plan.at("whole").at("label") == entry.at("label") ? &plan.at("whole") : nullptr;
|
||||
for (const Json& block : plan.at("blocks")) {
|
||||
if (block.at("label") == entry.at("label")) job = █
|
||||
}
|
||||
const std::vector<std::string> lines = Strings(s.at("lines"));
|
||||
Same(Prompt::Tail(*job, s.at("inventory").at("units"), lines, OptionalString(entry.at("summary")).value_or("")), entry.at("text").get<std::string>(),
|
||||
std::format("tail {} {}", entry.at("series").get<std::string>(), entry.at("label").get<std::string>()));
|
||||
}
|
||||
for (const Json& entry : p.at("userPrompt")) {
|
||||
Same(Prompt::UserPrompt(entry.at("tail").get<std::string>(), entry.at("job"), OptionalString(entry.at("stack")).value_or("")), entry.at("text").get<std::string>(),
|
||||
std::format("user_prompt {}", DumpCompactSorted(entry.at("job"))));
|
||||
}
|
||||
Same(Prompt::SystemPrompt("S", "R", "L"), p.at("systemPrompt").get<std::string>(), "system_prompt");
|
||||
}
|
||||
|
||||
void CheckDispositions(const Json& g) {
|
||||
const Json& d = g.at("dispositions");
|
||||
const std::vector<Json> entries(d.at("entries").begin(), d.at("entries").end());
|
||||
const std::vector<Json> rows = Dispositions::Classify(entries, "H1", d.at("dir").get<std::string>());
|
||||
SameJson(Json(rows), d.at("rows"), "dispositions classify");
|
||||
const std::vector<Json> inForce = Dispositions::InForce(entries, rows);
|
||||
SameJson(Json(inForce), d.at("inForce"), "dispositions in_force");
|
||||
for (auto it = d.at("blocks").begin(); it != d.at("blocks").end(); ++it) {
|
||||
Same(Dispositions::Block(inForce, rows, it.key(), "H1"), it.value().get<std::string>(), std::format("dispositions block {}", it.key()));
|
||||
}
|
||||
Same(Dispositions::Block({}, {}, Plan::FunctionalLens, "H9"), d.at("empty").get<std::string>(), "dispositions block (none)");
|
||||
const std::vector<Json> two(entries.begin() + 1, entries.begin() + 3);
|
||||
SameJson(Json(Dispositions::Classify(two, "H9", fs::path(d.at("dir").get<std::string>()) / "0001-a.patch")), d.at("rowsFile"), "dispositions classify (a file)");
|
||||
}
|
||||
|
||||
void CheckNormalize(const Json& g) {
|
||||
std::int32_t n = 0;
|
||||
for (const Json& entry : g.at("normalize")) {
|
||||
Json v = entry.at("v");
|
||||
const std::vector<Json> inForce(entry.at("inForce").begin(), entry.at("inForce").end());
|
||||
const std::vector<std::string> allIds = Strings(entry.at("allIds"));
|
||||
const Json result = Normalize::NormalizeOutput(v, inForce, entry.at("lensFile").get<std::string>(), entry.at("hash").get<std::string>(), entry.at("inventory"), allIds);
|
||||
SameJson(result, entry.at("result"), std::format("normalize case {}", n));
|
||||
SameJson(v, entry.at("vAfter"), std::format("normalize case {}: the output's notes after", n));
|
||||
++n;
|
||||
}
|
||||
for (const Json& entry : g.at("resolveId")) {
|
||||
SameJson(Normalize::ResolveId(entry.at(0), Strings(entry.at(1))), entry.at(2), std::format("resolve_id {}", DumpCompactSorted(entry.at(0))));
|
||||
}
|
||||
n = 0;
|
||||
for (const Json& entry : g.at("merge")) {
|
||||
const std::vector<Json> parts(entry.at("parts").begin(), entry.at("parts").end());
|
||||
SameJson(Normalize::MergeParts(entry.at("lens").get<std::string>(), entry.at("lensFile").get<std::string>(), parts, Strings(entry.at("missing")), entry.at("stopped")),
|
||||
entry.at("result"), std::format("merge_parts case {}", n++));
|
||||
}
|
||||
n = 0;
|
||||
for (const Json& entry : g.at("matrix")) {
|
||||
const std::vector<Json> results(entry.at("results").begin(), entry.at("results").end());
|
||||
SameJson(Normalize::Matrix(entry.at("inventory"), results, Strings(entry.at("notReviewed"))), entry.at("result"), std::format("matrix case {}", n++));
|
||||
}
|
||||
for (const Json& entry : g.at("dedupe")) {
|
||||
const std::vector<Json> items(entry.at(0).begin(), entry.at(0).end());
|
||||
SameJson(Json(Normalize::Dedupe(items)), entry.at(1), "dedupe");
|
||||
}
|
||||
}
|
||||
|
||||
void CheckStream(const Json& g) {
|
||||
const Json& s = g.at("stream");
|
||||
std::map<std::string, Json> parsed;
|
||||
for (auto it = s.at("streams").begin(); it != s.at("streams").end(); ++it) {
|
||||
parsed[it.key()] = Stream::ParseStream(it.value().get<std::string>());
|
||||
SameJson(parsed[it.key()], s.at("parsed").at(it.key()), std::format("parse_stream {}", it.key()));
|
||||
const std::optional<Json> structured = Stream::StructuredOutput(parsed[it.key()].at("result"));
|
||||
SameJson(structured ? *structured : Json(), s.at("structured").at(it.key()), std::format("structured_output {}", it.key()));
|
||||
}
|
||||
for (const Json& entry : s.at("classify")) {
|
||||
const std::optional<std::int32_t> code = entry.at(1).is_null() ? std::nullopt : std::optional<std::int32_t>(entry.at(1).get<std::int32_t>());
|
||||
const auto [status, reason] = Stream::Classify(parsed.at(entry.at(0).get<std::string>()), code, entry.at(2).get<std::string>(), entry.at(3).get<bool>());
|
||||
SameJson(Json::array({status, reason}), entry.at(4), std::format("classify {} {}", entry.at(0).get<std::string>(), DumpCompactSorted(entry.at(2))));
|
||||
}
|
||||
for (const Json& entry : s.at("windows")) SameJson(Stream::Windows(entry.at(0)), entry.at(1), std::format("windows {}", DumpCompactSorted(entry.at(0))));
|
||||
for (const Json& entry : s.at("structuredOf")) {
|
||||
const std::optional<Json> structured = Stream::StructuredOutput(entry.at(0));
|
||||
SameJson(structured ? *structured : Json(), entry.at(1), std::format("structured_output {}", DumpCompactSorted(entry.at(0))));
|
||||
}
|
||||
for (const Json& entry : g.at("patterns")) {
|
||||
const std::string text = entry.at(0).get<std::string>();
|
||||
Check(Stream::LimitText(text) == entry.at(1).get<bool>(), std::format("LIMIT_RE {}", Dyn::Repr(text)));
|
||||
Check(Stream::AuthText(text) == entry.at(2).get<bool>(), std::format("AUTH_RE {}", Dyn::Repr(text)));
|
||||
Check(Stream::CreditText(text) == entry.at(3).get<bool>(), std::format("CREDIT_RE {}", Dyn::Repr(text)));
|
||||
Check(Stream::IsSqlCall(text) == entry.at(4).get<bool>(), std::format("SQL_CALL {}", Dyn::Repr(text)));
|
||||
Check(Stream::HasAnsweredLine(text) == entry.at(5).get<bool>(), std::format("ANSWERED_LINE {}", Dyn::Repr(text)));
|
||||
}
|
||||
}
|
||||
|
||||
void CheckState(const Json& g) {
|
||||
const Json& s = g.at("state");
|
||||
std::int32_t n = 0;
|
||||
for (const Json& entry : s.at("merge")) {
|
||||
SameJson(State::MergeState(entry.at("disk"), entry.at("sets"), Strings(entry.at("drops")), entry.at("read")), entry.at("result"), std::format("merge_state case {}", n++));
|
||||
}
|
||||
n = 0;
|
||||
for (const Json& entry : s.at("usage")) {
|
||||
const std::vector<Json> records(entry.at(0).begin(), entry.at(0).end());
|
||||
SameJson(State::UsageTotals(records), entry.at(1), std::format("usage_totals case {}", n++));
|
||||
}
|
||||
for (const Json& entry : s.at("describe")) Same(State::Describe(entry.at(0)), entry.at(1).get<std::string>(), std::format("_describe {}", DumpCompactSorted(entry.at(0))));
|
||||
n = 0;
|
||||
for (const Json& entry : s.at("summary")) Same(State::Summary(entry.at(0)), entry.at(1).get<std::string>(), std::format("summary case {}", n++));
|
||||
}
|
||||
|
||||
std::string Spelled(std::string text, const fs::path& repo) {
|
||||
text = Dyn::Replace(text, repo.string(), "<repo>");
|
||||
return Dyn::Replace(text, std::format("`{} slots`", Invocation()), "`<invocation> slots`");
|
||||
}
|
||||
|
||||
void CheckConfig(const Json& g) {
|
||||
const Json& c = g.at("config");
|
||||
const fs::path scratch = fs::temp_directory_path() / std::format("crafter-review-goldens-{}", Platform::PublishedPid());
|
||||
for (const Json& entry : c.at("cases")) {
|
||||
const std::string name = entry.at("name").get<std::string>();
|
||||
const fs::path repo = scratch / name;
|
||||
fs::remove_all(repo);
|
||||
fs::create_directories(repo);
|
||||
if (!entry.at("body").is_null()) {
|
||||
fs::create_directories(repo / ".review-gates");
|
||||
std::ofstream(repo / ".review-gates" / "config.json", std::ios::binary) << entry.at("body").get<std::string>();
|
||||
}
|
||||
const Config::Loaded loaded = Config::Load(repo);
|
||||
std::vector<std::string> problems;
|
||||
for (const std::string& problem : loaded.problems) problems.push_back(Spelled(problem, repo));
|
||||
SameJson(ToJson(problems), entry.at("problems"), std::format("config {}: problems", name));
|
||||
SameJson(Json::parse(Spelled(DumpFile(Config::Redacted(loaded.config)), repo)), entry.at("config"), std::format("config {}: redacted", name));
|
||||
const Json& path = Dyn::Get(loaded.config, "_path");
|
||||
SameJson(path.is_null() ? Json() : Json(Spelled(path.get<std::string>(), repo)), entry.at("path"), std::format("config {}: _path", name));
|
||||
Check(Dyn::Has(loaded.config, "_path") == entry.at("hasPath").get<bool>(), std::format("config {}: _path present", name));
|
||||
std::vector<std::string> warnings;
|
||||
for (const Json& warning : Dyn::Or(Dyn::Get(loaded.config, "_warnings"), Dyn::EmptyList())) warnings.push_back(Spelled(warning.get<std::string>(), repo));
|
||||
SameJson(ToJson(warnings), entry.at("warnings"), std::format("config {}: warnings", name));
|
||||
SameJson(ToJson(Config::LensesOff(loaded.config)), entry.at("lensesOff"), std::format("config {}: lenses_off", name));
|
||||
SameJson(Config::Environments(loaded.config), entry.at("environments"), std::format("config {}: environments", name));
|
||||
}
|
||||
{
|
||||
const fs::path repo = scratch / "missing";
|
||||
fs::create_directories(repo);
|
||||
std::vector<std::string> problems;
|
||||
for (const std::string& problem : Config::Load(repo, repo / "none.json").problems) problems.push_back(Spelled(problem, repo));
|
||||
SameJson(ToJson(problems), c.at("missing"), "config --config to a missing file");
|
||||
}
|
||||
fs::remove_all(scratch);
|
||||
SameJson(Config::Defaults(), c.at("defaults"), "config DEFAULTS");
|
||||
SameJson(Config::Example(), c.at("example"), "config example()");
|
||||
SameJson(ToJson(Config::Validate(Config::Example())), c.at("exampleProblems"), "config validate(example())");
|
||||
for (const Json& entry : c.at("denied")) Check(Tools::Denied(entry.at(0).get<std::string>()) == entry.at(1).get<bool>(), std::format("denied {}", Dyn::Repr(entry.at(0).get<std::string>())));
|
||||
const Config::Slots slots = Config::SlotStacks({{"slots", {{"dir", "slots"}}}}, c.at("slotStacks").at("dir").get<std::string>());
|
||||
SameJson(slots.stacks, c.at("slotStacks").at("stacks"), "slot_stacks stacks");
|
||||
SameJson(ToJson(slots.problems), c.at("slotStacks").at("problems"), "slot_stacks problems");
|
||||
const std::array<std::int64_t, 2> oneThree = {1, 3};
|
||||
const std::array<std::int64_t, 1> one = {1};
|
||||
const std::array<std::int64_t, 1> two = {2};
|
||||
SameJson(ToJson(Config::SlotCommands({{"slots", {{"start", "up {n} {n}"}}}}, "start", oneThree)), c.at("slotCommands").at(0), "slot_commands start");
|
||||
SameJson(ToJson(Config::SlotCommands({{"slots", Json::object()}}, "stop", one)), c.at("slotCommands").at(1), "slot_commands none");
|
||||
SameJson(ToJson(Config::SlotCommands(Json::object(), "start", two)), c.at("slotCommands").at(2), "slot_commands no slots");
|
||||
for (const Json& entry : c.at("checkUrl")) SameJson(Optional(PgWire::CheckUrl(entry.at(0))), entry.at(1), std::format("check_url {}", DumpCompactSorted(entry.at(0))));
|
||||
for (const Json& entry : c.at("redact")) Same(PgWire::Redact(entry.at(0).get<std::string>()), entry.at(1).get<std::string>(), std::format("redact {}", entry.at(0).get<std::string>()));
|
||||
for (const Json& entry : c.at("where")) Same(PgWire::Where(entry.at(0).get<std::string>()), entry.at(1).get<std::string>(), std::format("where {}", entry.at(0).get<std::string>()));
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
SetHome(fs::current_path());
|
||||
const Json g = Dyn::LoadJsonFile(fs::current_path() / "tests" / "Goldens" / "fixture" / "pipeline.json");
|
||||
Same(Schema::SchemaJson("block"), g.at("schema").at("block").get<std::string>(), "schema block");
|
||||
Same(Schema::SchemaJson("whole"), g.at("schema").at("whole").get<std::string>(), "schema whole");
|
||||
for (auto it = g.at("series").begin(); it != g.at("series").end(); ++it) CheckSeries(it.key(), it.value());
|
||||
CheckPlan(g);
|
||||
CheckPrompts(g, g.at("series"));
|
||||
CheckDispositions(g);
|
||||
CheckNormalize(g);
|
||||
CheckStream(g);
|
||||
CheckState(g);
|
||||
CheckConfig(g);
|
||||
std::println("{} checks against the goldens", Checks);
|
||||
if (Failures) std::println(std::cerr, "{} failed", Failures);
|
||||
return Failures ? 1 : 0;
|
||||
}
|
||||
Loading…
Reference in a new issue