Skip to content
Repos

mologram

C++ 11.5 KB275 lines Opens in site

Directory Raw Download

// Docs and process gates (seriousdevelopment): every requirement is traceable to a covering test, every class is described,
// every markdown file is versioned and registered, the README key table equals the registry, the track sheet is fresh, and
// the requirements that are properties of the build (flags, layering, commands, version, socket modes, Premium fallbacks) are checked.
#include <sys/stat.h>

#include <ctime>
#include <filesystem>
#include <fstream>
#include <map>
#include <regex>
#include <set>
#include <sstream>

#include "tttest.hpp"
#include "mologram/ActionRegistry.hpp"
#include "mologram/Config.hpp"
#include "mologram/Daemon.hpp"
#include "mologram/FakeTelegramService.hpp"
#include "mologram/SpecDocument.hpp"
#include "mologram/Version.hpp"
#include "mologram/ui/TgAdapter.hpp"

namespace fs = std::filesystem;
using namespace mologram;

namespace {

std::string root() { return MOLOGRAM_SOURCE_DIR; }

std::string slurp(const std::string& path) {
  std::ifstream in(path);
  std::stringstream ss;
  ss << in.rdbuf();
  return ss.str();
}

std::string trim(const std::string& s) {
  size_t a = s.find_first_not_of(" \t\r\n");
  if (a == std::string::npos) return "";
  return s.substr(a, s.find_last_not_of(" \t\r\n") - a + 1);
}

std::set<std::string> testNames() {
  std::set<std::string> n;
  for (const auto& t : tttest::registry()) n.insert(t.name);
  return n;
}

/// Markdown files of the project (not build output, worktrees, git data, or the owner's prompt.md input file).
std::vector<std::string> markdownFiles() {
  std::vector<std::string> out;
  for (auto it = fs::recursive_directory_iterator(root()); it != fs::recursive_directory_iterator(); ++it) {
    std::string name = it->path().filename().string();
    if (it->is_directory() && (name == "build" || name == ".claude" || name == ".git" || name == "dist")) { it.disable_recursion_pending(); continue; }
    if (!it->is_regular_file() || it->path().extension() != ".md") continue;
    std::string rel = fs::relative(it->path(), root()).string();
    if (rel == "prompt.md") continue;  // the owner's input prompt, not project documentation
    out.push_back(rel);
  }
  std::sort(out.begin(), out.end());
  return out;
}

std::int64_t dayNumber(const std::string& ymd) {
  std::tm tm{};
  tm.tm_year = std::stoi(ymd.substr(0, 4)) - 1900;
  tm.tm_mon = std::stoi(ymd.substr(5, 2)) - 1;
  tm.tm_mday = std::stoi(ymd.substr(8, 2));
  return (std::int64_t)(timegm(&tm) / 86400);
}

}  // namespace

TEST_CASE("docs: every requirement has an acceptance line and a covering test that exists", "[docs][unit]") {
  SpecDocument spec(root() + "/SPEC.md");
  REQUIRE(spec.error().empty());
  REQUIRE(spec.hasTable("trace"));
  std::set<std::string> ids;
  std::regex def(R"((?:^|\n)- ((?:FR|NFR|UX|SEC|OPS|DOC|TRK)-[0-9]+):)");
  const std::string& text = spec.text();
  for (std::sregex_iterator it(text.begin(), text.end(), def), end; it != end; ++it) ids.insert((*it)[1]);
  CHECK(ids.size() >= 65);
  std::set<std::string> seen;
  auto names = testNames();
  std::string readme = slurp(root() + "/README.md"), track = slurp(root() + "/BUILD-TRACK.md");
  size_t gaps = readme.find("## Open gaps");
  REQUIRE(gaps != std::string::npos);
  std::string gapText = readme.substr(gaps);
  int open = 0, partial = 0, covered = 0;
  for (const auto& row : spec.table("trace")) {
    REQUIRE(row.size() == 4u);
    const std::string &id = row[0], &accept = row[1], &status = row[2], &tests = row[3];
    CHECK(seen.insert(id).second);        // exactly one row per requirement
    CHECK(ids.count(id) == 1u);           // the row names a requirement that exists
    CHECK(accept.size() > 20u);
    CHECK((status == "covered" || status == "partial" || status == "open"));
    if (status == "open") {
      open++;
      CHECK(gapText.find(id) != std::string::npos);  // an open requirement is listed as an open gap
      CHECK(track.find(id) != std::string::npos);    // and in the track sheet
      continue;
    }
    (status == "covered" ? covered : partial)++;
    size_t pos = 0;
    int count = 0;
    while (pos <= tests.size()) {
      size_t e = tests.find(" ;; ", pos);
      std::string name = trim(tests.substr(pos, e == std::string::npos ? std::string::npos : e - pos));
      if (!name.empty()) {
        count++;
        if (!names.count(name)) CHECK_EQ(name, std::string("(a test that exists) for ") + id);
      }
      if (e == std::string::npos) break;
      pos = e + 4;
    }
    CHECK(count >= 1);
    if (status == "partial") CHECK(accept.find("Open:") != std::string::npos);  // a partial row says what is open
  }
  for (const auto& id : ids) CHECK(seen.count(id) == 1u);  // no requirement without a row
  CHECK_EQ(open + partial + covered, (int)ids.size());
}

TEST_CASE("docs: every class in include/ is described in DESIGN.md", "[docs][unit]") {
  std::string design = slurp(root() + "/DESIGN.md");
  REQUIRE(!design.empty());
  std::regex cls(R"((?:^|\n)(?:class|struct) ([A-Za-z0-9_]+)(?: final)?\s*(?::[^{;]*)?\{)");
  int classes = 0;
  for (auto& e : fs::recursive_directory_iterator(root() + "/include")) {
    if (!e.is_regular_file() || e.path().extension() != ".hpp") continue;
    std::string text = slurp(e.path().string());
    for (std::sregex_iterator it(text.begin(), text.end(), cls), end; it != end; ++it) {
      std::string name = (*it)[1];
      classes++;
      if (design.find("| `" + name + "` |") == std::string::npos) CHECK_EQ(name, std::string("(described in DESIGN.md) ") + e.path().filename().string());
    }
  }
  CHECK(classes >= 90);
}

TEST_CASE("docs: markdown files carry a versioned header and are in the doc register; runbooks are drilled", "[docs][unit]") {
  SpecDocument reg(root() + "/docs/DOC-REGISTER.md");
  REQUIRE(reg.error().empty());
  REQUIRE(reg.hasTable("docs"));
  std::set<std::string> registered;
  for (const auto& row : reg.table("docs")) {
    REQUIRE(row.size() == 4u);
    registered.insert(row[0]);
    CHECK(fs::exists(root() + "/" + row[0]));
    CHECK(!row[1].empty());
    CHECK(!row[2].empty());
  }
  std::regex head(R"(^<!-- doc: (.+?) \| version: ([0-9]+\.[0-9]+(?:\.[0-9]+)?) \| updated: ([0-9]{4}-[0-9]{2}-[0-9]{2}) -->$)");
  auto files = markdownFiles();
  CHECK(files.size() >= 20u);
  for (const auto& rel : files) {
    std::ifstream in(root() + "/" + rel);
    std::string first;
    std::getline(in, first);
    std::smatch m;
    if (!std::regex_match(first, m, head)) { CHECK_EQ(rel, std::string("(a versioned header on line 1)")); continue; }
    CHECK_EQ(std::string(m[1]), rel);
    if (!registered.count(rel)) CHECK_EQ(rel, std::string("(listed in docs/DOC-REGISTER.md)"));
  }
  // a runbook that was never drilled fails the ops gate (seriousdevelopment)
  int runbooks = 0;
  for (auto& e : fs::directory_iterator(root() + "/docs/runbooks")) {
    if (e.path().extension() != ".md") continue;
    runbooks++;
    std::string t = slurp(e.path().string());
    size_t p = t.find("## Last drilled");
    REQUIRE(p != std::string::npos);
    std::regex date(R"(\n\s*([0-9]{4}-[0-9]{2}-[0-9]{2}))");
    std::smatch dm;
    std::string tail = t.substr(p);
    if (!std::regex_search(tail, dm, date)) CHECK_EQ(e.path().filename().string(), std::string("(a drill date)"));
  }
  CHECK(runbooks >= 6);
}

TEST_CASE("docs: the build track sheet is not stale (7 days)", "[docs][unit]") {
  std::string track = slurp(root() + "/BUILD-TRACK.md");
  std::smatch m;
  std::regex head(R"(updated: ([0-9]{4}-[0-9]{2}-[0-9]{2}))");
  REQUIRE(std::regex_search(track, m, head));
  std::int64_t age = (std::int64_t)(std::time(nullptr) / 86400) - dayNumber(m[1]);
  if (age > 7) CHECK_EQ(std::string("BUILD-TRACK.md updated ") + std::string(m[1]), std::string("at most 7 days ago (STALE: update the track sheet)"));
  CHECK(age >= 0);
}

TEST_CASE("docs: the README key table equals the action registry", "[docs][unit]") {
  SpecDocument readme(root() + "/README.md");
  REQUIRE(readme.error().empty());
  REQUIRE(readme.hasTable("readme_keys"));
  const auto& rows = readme.table("readme_keys");
  const auto& acts = ActionRegistry::all();
  REQUIRE(rows.size() == acts.size());
  for (size_t i = 0; i < acts.size(); i++) {
    REQUIRE(rows[i].size() == 3u);
    CHECK_EQ(rows[i][0], acts[i].id);
    CHECK_EQ(rows[i][1], acts[i].defaultKey);
    CHECK_EQ(rows[i][2], acts[i].menu);
  }
}

TEST_CASE("build: warning flags, UI layering and the Makefile commands (NFR-03, NFR-04, OPS-01)", "[docs][unit]") {
  std::string cmake = slurp(root() + "/CMakeLists.txt");
  CHECK(cmake.find("-Wall -Wextra -Wpedantic -Werror") != std::string::npos);
  std::regex target(R"(add_(?:library|executable)\(([A-Za-z0-9_]+))");
  int targets = 0;
  for (std::sregex_iterator it(cmake.begin(), cmake.end(), target), end; it != end; ++it) {
    std::string name = (*it)[1];
    targets++;
    if (cmake.find("target_compile_options(" + name + " PRIVATE ${MOLOGRAM_WARN})") == std::string::npos) CHECK_EQ(name, std::string("(compiled with MOLOGRAM_WARN)"));
  }
  CHECK(targets >= 8);
  // NFR-04: only src/tapi and include/mologram/tapi may include tapi headers; the UI and media never do
  std::regex inc(R"(#\s*include\s*[<"]tapi/)");
  int scanned = 0;
  for (const char* dir : {"src", "include"}) {
    for (auto& e : fs::recursive_directory_iterator(root() + "/" + dir)) {
      if (!e.is_regular_file()) continue;
      std::string rel = fs::relative(e.path(), root()).string();
      if (rel.rfind("src/tapi/", 0) == 0 || rel.rfind("include/mologram/tapi/", 0) == 0) continue;
      scanned++;
      std::string t = slurp(e.path().string());
      if (std::regex_search(t, inc)) CHECK_EQ(rel, std::string("(no tapi include outside src/tapi)"));
    }
  }
  CHECK(scanned > 50);
  std::string mk = slurp(root() + "/Makefile");
  for (const char* t : {"build", "test", "run", "clean", "check", "image", "up", "down", "logs", "dist"}) {
    std::regex line(std::string("\n") + t + ":");
    if (!std::regex_search(mk, line)) CHECK_EQ(std::string(t), std::string("(a Makefile target)"));
  }
}

TEST_CASE("version: VERSION, the generated header and the changelog agree (OPS-04)", "[docs][unit]") {
  std::string v = trim(slurp(root() + "/VERSION"));
  CHECK_EQ(v, std::string(MOLOGRAM_VERSION));
  std::string log = slurp(root() + "/CHANGELOG.md");
  std::regex row(R"(\n\| ([0-9]+\.[0-9]+\.[0-9]+) \|)");
  std::string last;
  for (std::sregex_iterator it(log.begin(), log.end(), row), end; it != end; ++it) last = (*it)[1];
  CHECK_EQ(last, v);
}

TEST_CASE("socket permissions: the socket is 0600 and the directory 0700 (SEC-03)", "[docs][integration]") {
  char t[] = "/tmp/mologram-perm-XXXXXX";
  std::string base = mkdtemp(t);
  std::string dir = base + "/run", sock = dir + "/m.sock";
  {
    FakeTelegramService svc;
    Daemon daemon(svc, sock);
    REQUIRE(daemon.start().empty());
    struct stat s{};
    REQUIRE(::stat(sock.c_str(), &s) == 0);
    CHECK_EQ((int)(s.st_mode & 0777), 0600);
    REQUIRE(::stat(dir.c_str(), &s) == 0);
    CHECK_EQ((int)(s.st_mode & 0777), 0700);
  }
  std::error_code ec;
  fs::remove_all(base, ec);
}

TEST_CASE("premium content stays readable without Premium (FR-65)", "[docs][unit]") {
  Message m;
  m.id = 5; m.text = "made with premium"; m.date = 1730800000; m.effectId = 99;
  Reaction r; r.customEmojiId = 4242; r.count = 3; m.reactions.push_back(r);
  m.hasPoll = false;
  ttgui::TgMessage t = ui::TgAdapter::message(m, 1730800100);
  CHECK_EQ(t.text, std::string("made with premium"));  // the text and a missing effect never hide the message
  REQUIRE(t.reactions.size() == 1u);
  CHECK(!t.reactions[0].emoji.empty());                // a custom emoji reaction shows a fallback glyph
  CHECK_EQ(t.reactions[0].count, 3);
}
37.3ms