Home /Modules/operating-system/os-generate.sleela

os-generate.sleela

lib/operating-system/os-generate.sleela · 592 line(s) · sleela

#sleela 2.5
material;
< os-generate.sleela -- the runnable OS SOURCE GENERATOR for lib/os. Unlike >
< os-build.sleela (which PRINTS the generated artifacts to show the shape), >
< this program WRITES the real Linux-level C/C++ source tree to disk through >
< the os*/file bridge (osMakeDir / openFile / write / close), the same path the >
< split SLOSCreator provider uses. Running it materialises a complete, buildable >
< /os-out tree you can source, copy, commit, or download. >
<  >
< It also closes the loop to the upstream OS parts: it drops the SLDistroSource >
< reference (mearvk/Ubuntu.Determinant.Beta.Restricted, pinned) into the tree as >
< provenance and writes a fetch-upstream.sh that performs the opt-in, pinned, >
< shallow clone of the real distro next to the generated scaffolding. >
<  >
< Build parameters (read from the environment, with Linux defaults): >
< OS_NAME     product name          (default "Determinant") >
< OS_VERSION  version               (default "1.0") >
< OS_ARCH     target arch           (default "amd64") >
< OS_OUT      output root directory (default "/projects/sandbox/os-out") >
<  >
< OS_NAME=Determinant OS_ARCH=arm64 ./impl/build/sleela run lib/operating-system/os-generate.sleela >
<  >
< Requires #sleela 1.5 for the os* built-ins (declared 1.11 for field dispatch). >

< ---- The upstream OS-parts reference (compact mirror of SLDistroSource) -- >
class Upstream {
  < ---- Descriptive metadata (version 1.11 nested-friendly accessors) ---- >
  << Eleven catalogued attributes with getter/setter pairs, so a GUI, loader,
     or catalog can read and (where appropriate) override this record.
     Values are faithful to the subject's real origin where publicly known. >>
  String metaVersion = "1.0.0";
  int metaId = 10960;
  String metaAuthor = "Kiro Agent";
  String metaDate = "2026-10-16";
  String metaCopyright = "SLeeLa project";
  String metaTrademark = "none";
  String metaCorporation = "none";
  < metaOrigin: National | <nation> | International | Galactic >
  String metaOrigin = "International";
  String metaBirthDate = "2026-10-10";
  < metaScienceRating: maturity/robustness on a 1..10 scale >
  int metaScienceRating = 9;
  < metaNationalSchedule: a real, citable instrument or "none" >
  String metaNationalSchedule = "none";

  String getMetaVersion() { return metaVersion; }
  void setMetaVersion(String v) { metaVersion = v; }
  int getMetaId() { return metaId; }
  void setMetaId(int v) { metaId = v; }
  String getAuthor() { return metaAuthor; }
  void setAuthor(String v) { metaAuthor = v; }
  String getDate() { return metaDate; }
  void setDate(String v) { metaDate = v; }
  String getCopyright() { return metaCopyright; }
  void setCopyright(String v) { metaCopyright = v; }
  String getTrademark() { return metaTrademark; }
  void setTrademark(String v) { metaTrademark = v; }
  String getCorporation() { return metaCorporation; }
  void setCorporation(String v) { metaCorporation = v; }
  String getOrigin() { return metaOrigin; }
  void setOrigin(String v) { metaOrigin = v; }
  String getBirthDate() { return metaBirthDate; }
  void setBirthDate(String v) { metaBirthDate = v; }
  int getScienceRating() { return metaScienceRating; }
  void setScienceRating(int v) { metaScienceRating = v; }
  String getNationalSchedule() { return metaNationalSchedule; }
  void setNationalSchedule(String v) { metaNationalSchedule = v; }
  String url;  String branch;  String commit;  String repo;
  void configure() {
    repo = "Ubuntu.Determinant.Beta.Restricted";
    url = "https://github.com/mearvk/Ubuntu.Determinant.Beta.Restricted.git";
    branch = "main";
    commit = "4918080dcf0f52dc771aa1a30b0e0f63495f7a8d";
  }
  String referenceSheet() {
    String s = "# Upstream OS-parts reference (pinned)\n";
    s = s + "repo:   mearvk/" + repo + "\n";
    s = s + "url:    " + url + "\n";
    s = s + "branch: " + branch + "\n";
    s = s + "commit: " + commit + "\n";
    s = s + "parts:  kernel->kernels  installer->installer  desktop->gnome-source"
          + "  filesystem->file-systems  userland->userland\n";
    return s;
  }
  < The opt-in shallow fetch script written into the tree. >
  String fetchScript() {
    String s = "#!/bin/sh\n# fetch-upstream.sh -- opt-in, pinned, shallow clone of the real OS parts\n";
    s = s + "# Downloads the Ubuntu distro NEXT TO this generated tree (upstream/).\n";
    s = s + "set -eu\nDEST=\"$(dirname \"$0\")/upstream/" + repo + "\"\n";
    s = s + "mkdir -p \"$(dirname \"$DEST\")\"\n";
    s = s + "if [ -d \"$DEST/.git\" ]; then echo \"already fetched: $DEST\"; exit 0; fi\n";
    s = s + "git -c http.postBuffer=524288000 -c http.version=HTTP/1.1 clone \\\n";
    s = s + "  --depth 1 --single-branch --branch " + branch + " \\\n";
    s = s + "  " + url + " \"$DEST\"\n";
    s = s + "echo \"fetched " + repo + " (" + branch + ") into $DEST\"\n";
    return s;
  }
}

< ---- A compact Linux OS model (OOD aggregate) --------------------------- >
struct OsModel {
  String name; String version; String shape; String arch; String triple;
  String loader; String kernel; String kernelVer; String cmdline;
  String rootfs; String init; String desktop;
}

< ---- The generator: emits each artifact AND writes it to disk ----------- >
class OsGenerator {
  < output root >
  String root;
  < "bytes path" index >
  String manifest;
  int fileCount;
  < field dispatch (1.11) >
  Upstream upstream;

  void configure(String outputRoot) {
    root = outputRoot; manifest = ""; fileCount = 0;
    upstream = new Upstream(); upstream.configure();
    osMakeDir(root);
  }

  int makeDir(String rel) { return osMakeDir(root + rel); }

  < Write one file relative to root; records bytes in the manifest. >
  int writeFile(String rel, String contents) {
    int fd = openFile(root + rel, "w");
    if (fd < 0) { return -1; }
    int n = write(fd, contents);
    close(fd);
    if (n >= 0) {
      String line = "" + n + " " + rel;
      if (manifest == "") { manifest = line; } else { manifest = manifest + "\n" + line; }
      fileCount = fileCount + 1;
    }
    return n;
  }

  String identity(OsModel m) { return m.name + " " + m.version + " (" + m.shape + ", " + m.arch + ")"; }

  OsModel linux(String name, String version, String arch, String kernelVer) {
    OsModel m = new OsModel();
    m.name = name; m.version = version; m.shape = "Linux"; m.arch = arch;
    if (arch == "arm64") { m.triple = "aarch64-unknown-linux-gnu"; }
    else { m.triple = "x86_64-unknown-linux-gnu"; }
    m.loader = "GRUB"; m.kernel = "Linux"; m.kernelVer = kernelVer;
    m.cmdline = "ro quiet splash";
    m.rootfs = "ext4"; m.init = "systemd"; m.desktop = "GNOME Shell";
    return m;
  }

  < Resolve a requested Linux kernel selection to a concrete version (compact >
  < mirror of SLKernelCatalog.resolveLinux). "" / "default" -> the LTS default. >
  String resolveKernel(String sel) {
    if (sel == "" || sel == "default") { return "6.12.0"; }
    if (sel == "latest")  { return "6.18.0"; }
    if (sel == "6.18")    { return "6.18.0"; }
    if (sel == "6.12" || sel == "6.12 LTS") { return "6.12.0"; }
    if (sel == "6.6"  || sel == "6.6 LTS")  { return "6.6.0"; }
    if (sel == "6.1"  || sel == "6.1 LTS")  { return "6.1.0"; }
    if (sel == "5.15" || sel == "5.15 LTS") { return "5.15.0"; }
    < explicit x.y.z passthrough >
    return sel;
  }

  < The foreign-executable (cross-OS) policy header for the Linux shape: a >
  < Linux image can run Windows .exe via binfmt_misc + Wine, and cross-arch ELF >
  < via QEMU-user. Compact mirror of SLExecutableTranslator for the Linux host. >
  String execTranslateHeader(OsModel m) {
    String h = "/* exec_translate.h - foreign-executable policy for " + m.shape + " (generated by SLeeLa lib/os) */\n";
    h = h + "#ifndef EXEC_TRANSLATE_H\n#define EXEC_TRANSLATE_H\n\n";
    h = h + "#define OS_HOST_SHAPE   \"" + m.shape + "\"\n";
    h = h + "#define OS_HAS_BINFMT   1   /* Linux FS-level interpreter (binfmt_misc) */\n";
    h = h + "#define OS_FOREIGN_EXE  \"Wine (Win32 compatibility layer)\"\n";
    h = h + "#define OS_FOREIGN_ARCH \"QEMU-user (cross-arch ELF)\"\n\n";
    h = h + "/* binfmt_misc registration template: bind a foreign extension to an\n";
    h = h + "   interpreter so the filesystem runs it on exec(). Example (Windows PE):\n";
    h = h + "     echo ':winexe:E::exe::/usr/bin/wine:OC' > /proc/sys/fs/binfmt_misc/register */\n";
    h = h + "#define OS_BINFMT_REGISTER \"/proc/sys/fs/binfmt_misc/register\"\n";
    h = h + "\n#endif /* EXEC_TRANSLATE_H */\n";
    return h;
  }

  < The foreign-executable compatibility loader for the Linux shape: load the >
  < OS components (binfmt_misc + Wine/Darling/QEMU + guest libraries) so this >
  < Linux OS runs Windows .exe and macOS executables. Compact mirror of >
  < SLCompatLoaderEmitter for the Linux host (runs Windows + macOS guests). >
  String compatLoaderC(OsModel m) {
    String c = "/* compat_loader.c - foreign-executable compatibility loader for " + m.name + " */\n";
    c = c + "/* Host OS: Linux. Loads binfmt_misc interpreters + translation runtimes\n";
    c = c + "   + guest libraries so this OS can run other families' executables. */\n";
    c = c + "extern int binfmt_register(const char *rule);\n";
    c = c + "extern int runtime_load(const char *runtime);\n";
    c = c + "extern int libs_provide(const char *libset);\n";
    c = c + "extern int run_foreign(const char *runtime, const char *path);\n\n";
    c = c + "int compat_load_all(void) {\n";
    c = c + "    /* Linux runs Windows via wine + binfmt_misc + win32-libs */\n";
    c = c + "    binfmt_register(\"exe -> wine\");\n";
    c = c + "    runtime_load(\"wine\");\n";
    c = c + "    libs_provide(\"win32-libs\");\n";
    c = c + "    /* Linux runs macOS via darling + binfmt_misc + darwin-libs */\n";
    c = c + "    binfmt_register(\"app -> darling\");\n";
    c = c + "    runtime_load(\"darling\");\n";
    c = c + "    libs_provide(\"darwin-libs\");\n";
    c = c + "    return 0;\n}\n\n";
    c = c + "/* Run a foreign executable; empty runtime => binfmt routes it. */\n";
    c = c + "int compat_run(const char *runtime, const char *path) {\n";
    c = c + "    if (runtime == 0 || runtime[0] == 0) return run_foreign(\"\", path);\n";
    c = c + "    return run_foreign(runtime, path);\n}\n";
    return c;
  }

  String compatConf(OsModel m) {
    String s = "# compat.conf - foreign-executable routes for " + m.name + " (host Linux)\n";
    s = s + "host = Linux\n";
    s = s + "route = Linux runs Windows via wine + binfmt_misc + win32-libs\n";
    s = s + "route = Linux runs macOS via darling + binfmt_misc + darwin-libs\n";
    return s;
  }

  < The minimum-boot base-driver series table for the Linux shape, plugging >
  < into os/base_drivers.h. Compact mirror of SLBaseDriverEmitter for Linux. >
  String baseDriversTableC(OsModel m) {
    String c = "/* base_drivers_table.c - minimum-boot driver series for " + m.name + " */\n";
    c = c + "/* Plugs into os/base_drivers.h; the kernel brings these up in class order. */\n";
    c = c + "#include \"base_drivers.h\"\n\n";
    c = c + "static const sleela_driver k_series[] = {\n";
    c = c + "    { SL_DRV_BUS, \"pci + acpi\", SL_PHASE_BOOT, SL_ORIGIN_INTREE },\n";
    c = c + "    { SL_DRV_STORAGE, \"ahci + nvme + virtio_blk\", SL_PHASE_BOOT, SL_ORIGIN_INTREE },\n";
    c = c + "    { SL_DRV_DISPLAY, \"efifb / drm fbdev\", SL_PHASE_BOOT, SL_ORIGIN_INTREE },\n";
    c = c + "    { SL_DRV_KEYBOARD, \"atkbd + usbhid\", SL_PHASE_BOOT, SL_ORIGIN_INTREE },\n";
    c = c + "    { SL_DRV_MOUSE, \"usbhid\", SL_PHASE_EARLY, SL_ORIGIN_INTREE },\n";
    c = c + "    { SL_DRV_USB, \"xhci_hcd\", SL_PHASE_EARLY, SL_ORIGIN_INTREE },\n";
    c = c + "    { SL_DRV_AUDIO, \"snd_hda_intel\", SL_PHASE_EARLY, SL_ORIGIN_INTREE },\n";
    c = c + "};\n\n";
    c = c + "const sleela_driver *sleela_base_drivers(void) { return k_series; }\n";
    c = c + "size_t sleela_base_driver_count(void) { return sizeof(k_series)/sizeof(k_series[0]); }\n";
    c = c + "const char *sleela_os_host_family(void) { return \"Linux\"; }\n";
    return c;
  }

  < The resolved download URLs for the Linux build, by phase (compile|iso). >
  < Mirror of SLDownloadSet.downloadManifest for the Linux shape. >
  String downloadsConf(OsModel m) {
    String s = "# downloads.conf - related download URLs for " + m.name + " (resolved pre-build)\n";
    s = s + "# format: <kind> <phase> <url>\n";
    s = s + "package-repo compile http://archive.ubuntu.com/ubuntu\n";
    s = s + "kernel-src   compile https://cdn.kernel.org/pub/linux/kernel\n";
    s = s + "upstream     compile https://github.com/mearvk/Ubuntu.Determinant.Beta.Restricted.git\n";
    s = s + "firmware-src iso     https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git\n";
    s = s + "runtime-wine iso     https://dl.winehq.org/wine-builds\n";
    s = s + "runtime-qemu iso     https://www.qemu.org/download\n";
    return s;
  }

  < The support-URL table: for each component, the prioritized mirrors tried if >
  < the primary 404s (authoritative -> official-mirror -> college/edu -> archive). >
  < Compact mirror of SLSupportDownloader for the Linux build. >
  String supportUrlsConf(OsModel m) {
    String s = "# support-urls.conf - fallback mirrors if a primary URL 404s\n";
    s = s + "# order by likelihood of a final/college reference: authoritative > official > college > archive\n";
    s = s + "[package]\n";
    s = s + "authoritative http://archive.ubuntu.com/ubuntu\n";
    s = s + "official-mirror http://mirror.ubuntu.com/ubuntu\n";
    s = s + "college https://mirrors.mit.edu/ubuntu\n";
    s = s + "archive https://web.archive.org/web/2id_/http://archive.ubuntu.com/ubuntu\n";
    s = s + "[kernel]\n";
    s = s + "authoritative https://cdn.kernel.org/pub/linux/kernel\n";
    s = s + "official-mirror https://mirrors.kernel.org/pub/linux/kernel\n";
    s = s + "college https://mirror.math.princeton.edu/pub/kernel/linux/kernel\n";
    s = s + "archive https://web.archive.org/web/2id_/https://cdn.kernel.org/pub/linux/kernel\n";
    s = s + "[firmware]\n";
    s = s + "authoritative https://git.kernel.org/.../linux-firmware.git\n";
    s = s + "official-mirror https://kernel.googlesource.com/.../linux-firmware\n";
    s = s + "college https://mirrors.edge.kernel.org/pub/linux/kernel/firmware\n";
    s = s + "archive https://web.archive.org/web/2id_/.../linux-firmware.git\n";
    return s;
  }

  < The resilient fetch script: each component tries its mirrors in priority >
  < order and falls through on 404/failure to the next. Mirror of >
  < SLDownloadSet.supportFetchScript (compile phase). >
  String fetchResilientSh(OsModel m) {
    String s = "#!/bin/sh\n# fetch-downloads-resilient.sh - 404-tolerant fetch with mirror fallback\n";
    s = s + "# order: authoritative -> official-mirror -> college/edu -> archive\nset -eu\nmkdir -p downloads\n\n";
    s = s + "fetch_package() {\n";
    s = s + "  curl -fsSL --retry 2 -o downloads/package.payload \"http://archive.ubuntu.com/ubuntu\" && return 0\n";
    s = s + "  curl -fsSL --retry 2 -o downloads/package.payload \"http://mirror.ubuntu.com/ubuntu\" && return 0\n";
    s = s + "  curl -fsSL --retry 2 -o downloads/package.payload \"https://mirrors.mit.edu/ubuntu\" && return 0\n";
    s = s + "  curl -fsSL --retry 2 -o downloads/package.payload \"https://web.archive.org/web/2id_/http://archive.ubuntu.com/ubuntu\" && return 0\n";
    s = s + "  echo 'all package mirrors failed' >&2; return 1\n}\n";
    s = s + "fetch_kernel() {\n";
    s = s + "  git clone --depth 1 \"https://cdn.kernel.org/pub/linux/kernel\" downloads/kernel-src && return 0\n";
    s = s + "  git clone --depth 1 \"https://mirrors.kernel.org/pub/linux/kernel\" downloads/kernel-src && return 0\n";
    s = s + "  git clone --depth 1 \"https://mirror.math.princeton.edu/pub/kernel/linux/kernel\" downloads/kernel-src && return 0\n";
    s = s + "  echo 'all kernel mirrors failed' >&2; return 1\n}\n";
    s = s + "fetch_upstream() {\n";
    s = s + "  git clone --depth 1 \"https://github.com/mearvk/Ubuntu.Determinant.Beta.Restricted.git\" downloads/upstream && return 0\n";
    s = s + "  git clone --depth 1 \"https://gitlab.com/mearvk/Ubuntu.Determinant.Beta.Restricted.git\" downloads/upstream && return 0\n";
    s = s + "  echo 'all upstream mirrors failed' >&2; return 1\n}\n";
    s = s + "fetch_package; fetch_kernel; fetch_upstream\n";
    s = s + "echo 'resilient downloads complete'\n";
    return s;
  }

  < The opt-in fetch script for the related downloads (compile-phase sources). >
  String fetchDownloadsSh(OsModel m) {
    String s = "#!/bin/sh\n# fetch-downloads.sh - retrieve the related downloads (generated by SLeeLa lib/os)\n";
    s = s + "set -eu\nmkdir -p downloads\n";
    s = s + "# compile-phase sources\n";
    s = s + "git clone --depth 1 https://github.com/mearvk/Ubuntu.Determinant.Beta.Restricted.git downloads/upstream || true\n";
    s = s + "git clone --depth 1 https://cdn.kernel.org/pub/linux/kernel downloads/kernel-src || true\n";
    s = s + "curl -fsSL -o downloads/package-index \"http://archive.ubuntu.com/ubuntu/dists/stable/Release\" || true\n";
    s = s + "# iso-phase payloads\n";
    s = s + "git clone --depth 1 https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git downloads/firmware || true\n";
    s = s + "echo \"downloads complete\"\n";
    return s;
  }

  < The global settings header + the kernel command line settings file. >
  String osConf(OsModel m) {
    String s = "# os.conf - global OS settings (generated by SLeeLa lib/os)\n";
    s = s + "name = " + m.name + "\nversion = " + m.version + "\n";
    s = s + "shape = " + m.shape + "\narch = " + m.arch + "\n";
    s = s + "kernel = " + m.kernel + " " + m.kernelVer + "\n";
    s = s + "# per-layer settings: config/swap.conf, config/filesystems.txt,\n";
    s = s + "# config/downloads.conf, kernel/base-drivers/base-drivers.conf,\n";
    s = s + "# userspace/os-loader/services.conf, userspace/compat-loader/compat.conf\n";
    return s;
  }
  String cmdlineConf(OsModel m) {
    String s = "# cmdline.conf - kernel command line (generated by SLeeLa lib/os)\n";
    s = s + "cmdline = " + m.cmdline + "\n";
    return s;
  }

  String baseDriversConf(OsModel m) {
    String s = "# base-drivers.conf - minimum-boot driver series for " + m.name + " (host Linux)\n";
    s = s + "# format: <class> <driver> <phase>\n";
    s = s + "bus pci+acpi boot\nstorage ahci+nvme boot\ndisplay efifb boot\nkeyboard atkbd+usbhid boot\n";
    s = s + "mouse usbhid early\nusb xhci_hcd early\naudio snd_hda_intel early\n";
    s = s + "# driver source policy: unknown=permissive (taint), foreign=bridge-only\n";
    s = s + "# cross-OS bridge: Linux + Windows network driver -> ndiswrapper; gpu -> none\n";
    return s;
  }

  < Swap configuration for the Linux shape: a zstd-compressed swap at 1.0x RAM >
  < with a conservative swappiness. Mirror of SLSwapConfig.emitLinux (file kind >
  < here; a builder can switch to zram/zswap via SLSwapConfig). >
  String swapConf(OsModel m) {
    String s = "# swap.conf - paging configuration for " + m.name + " (generated by SLeeLa lib/os)\n";
    s = s + "kind = file\n";
    s = s + "size = 1.0x RAM\n";
    s = s + "# vm.swappiness governs reclaim aggressiveness (0..100)\n";
    s = s + "vm.swappiness = 60\n";
    s = s + "# /etc/fstab entry:\n";
    s = s + "/swapfile none swap sw 0 0\n";
    return s;
  }

  < The filesystem (file-table) type note for the Linux shape: the chosen root >
  < filesystem plus the catalogue of still-used table types a builder can pick. >
  String filesystemsConf(OsModel m) {
    String s = "# filesystems.txt - file-table types for " + m.name + " (generated by SLeeLa lib/os)\n";
    s = s + "root = ext4            # default Linux root (journaling)\n";
    s = s + "esp  = fat32           # EFI System Partition (FAT required)\n";
    s = s + "# Still-used table types available via SLFilesystemCatalog:\n";
    s = s + "#   FAT    : fat12 fat16 fat32 vfat exfat\n";
    s = s + "#   Windows: ntfs refs\n";
    s = s + "#   ext    : ext2 ext3 ext4\n";
    s = s + "#   Linux  : xfs btrfs f2fs jfs reiserfs\n";
    s = s + "#   cross  : zfs\n";
    s = s + "#   Apple  : apfs hfs+\n";
    s = s + "#   Unix   : ufs\n";
    s = s + "#   optical: iso9660 udf\n";
    s = s + "#   pseudo : squashfs tmpfs swap overlayfs\n";
    s = s + "#   network: nfs smb cifs\n";
    return s;
  }

  < The executable file-type table for Linux (compact mirror of >
  < SLExecutableTypes.emitExecTypesHeader for the Linux shape). >
  String execTypesHeader(OsModel m) {
    String h = "/* exec_types.h - executable file types for " + m.shape + " (generated by SLeeLa lib/os) */\n";
    h = h + "#ifndef EXEC_TYPES_H\n#define EXEC_TYPES_H\n\n";
    h = h + "#define OS_EXEC_SHAPE   \"" + m.shape + "\"\n";
    h = h + "#define OS_EXEC_USESBIT 1   /* POSIX exec bit (chmod +x) governs */\n\n";
    h = h + "/* NULL-terminated table of executable extensions (\"\" = no-ext ELF binary). */\n";
    h = h + "static const char *const os_exec_types[] = {\n";
    h = h + "    \"\", \".sh\", \".bin\", \".run\", \".AppImage\", \".elf\", \".so\", \".ko\",\n";
    h = h + "    0\n};\n\n";
    h = h + "/* True if `ext` (with dot, \"\" for none) names an executable file type. */\n";
    h = h + "static int os_is_executable_ext(const char *ext) {\n";
    h = h + "    for (const char *const *p = os_exec_types; *p; ++p) {\n";
    h = h + "        const char *a = *p, *b = ext; while (*a && *a == *b) { ++a; ++b; }\n";
    h = h + "        if (*a == 0 && *b == 0) return 1;\n";
    h = h + "    }\n    return 0;\n}\n\n";
    h = h + "#endif /* EXEC_TYPES_H */\n";
    return h;
  }

  < ---- the emitted Linux-level sources -------------------------------- >
  String configHeader(OsModel m) {
    String h = "/* os_config.h - generated by SLeeLa lib/os from " + identity(m) + " */\n";
    h = h + "#ifndef OS_CONFIG_H\n#define OS_CONFIG_H\n\n";
    h = h + "#define OS_NAME     \"" + m.name + "\"\n";
    h = h + "#define OS_VERSION  \"" + m.version + "\"\n";
    h = h + "#define OS_SHAPE    \"" + m.shape + "\"\n";
    h = h + "#define OS_ARCH     \"" + m.arch + "\"\n";
    h = h + "#define OS_TRIPLE   \"" + m.triple + "\"\n";
    h = h + "#define OS_LOADER   \"" + m.loader + "\"\n";
    h = h + "#define OS_KERNEL     \"" + m.kernel + "\"\n";
    h = h + "#define OS_KERNEL_VER \"" + m.kernelVer + "\"\n";
    h = h + "#define OS_CMDLINE  \"" + m.cmdline + "\"\n";
    h = h + "#define OS_ROOTFS   \"" + m.rootfs + "\"\n";
    h = h + "#define OS_INIT     \"" + m.init + "\"\n";
    h = h + "#define OS_DESKTOP  \"" + m.desktop + "\"\n";
    h = h + "\n#endif /* OS_CONFIG_H */\n";
    return h;
  }

  String bootUnit(OsModel m) {
    String c = "/* os_boot.c - early boot path, generated for " + identity(m) + " */\n";
    c = c + "#include \"os_config.h\"\n";
    c = c + "extern int firmware_handoff(const char *loader);\n";
    c = c + "extern int kernel_start(const char *cmdline);\n";
    c = c + "extern int mount_rootfs(const char *fs);\n";
    c = c + "extern int start_init(const char *init);\n\n";
    c = c + "int os_boot(void) {\n";
    c = c + "    if (firmware_handoff(OS_LOADER) != 0) return 1;\n";
    c = c + "    if (kernel_start(OS_CMDLINE)   != 0) return 2;\n";
    c = c + "    if (mount_rootfs(OS_ROOTFS)    != 0) return 3;\n";
    c = c + "    return start_init(OS_INIT);\n";
    c = c + "}\n";
    return c;
  }

  String osImage(OsModel m) {
    String s = "// os_image.cpp - composes the boot chain, generated for " + identity(m) + "\n";
    s = s + "#include <string>\nnamespace sleela_os {\n";
    s = s + "class OsImage {\npublic:\n";
    s = s + "  std::string name   = \"" + m.name + "\";\n";
    s = s + "  std::string loader = \"" + m.loader + "\";\n";
    s = s + "  std::string kernel = \"" + m.kernel + "\";\n";
    s = s + "  std::string rootfs = \"" + m.rootfs + "\";\n";
    s = s + "  std::string init   = \"" + m.init + "\";\n";
    s = s + "  int assemble() {\n";
    s = s + "    if (!firmwareHandoff(loader)) return 1;\n";
    s = s + "    if (!kernelStart())           return 2;\n";
    s = s + "    if (!mountRootfs(rootfs))     return 3;\n";
    s = s + "    startInit(init);\n    return 0;\n  }\n";
    s = s + "private:\n";
    s = s + "  bool firmwareHandoff(const std::string&);\n";
    s = s + "  bool kernelStart();\n";
    s = s + "  bool mountRootfs(const std::string&);\n";
    s = s + "  void startInit(const std::string&);\n";
    s = s + "};\n} // namespace sleela_os\n";
    return s;
  }

  String osLoaderC(OsModel m) {
    String c = "/* os_loader.c - PID 1 / service manager for " + m.name + " */\n";
    c = c + "extern int start_manager(const char *manager);\n";
    c = c + "extern int start_service(const char *unit);\n";
    c = c + "extern int start_session(void);\n\n";
    c = c + "int os_loader_main(void) {\n";
    c = c + "    if (start_manager(\"" + m.init + "\") != 0) return 1;\n";
    c = c + "    start_service(\"systemd-udevd\");\n";
    c = c + "    start_service(\"systemd-networkd\");\n";
    c = c + "    start_service(\"systemd-journald\");\n";
    c = c + "    start_session();  /* -> desktop (" + m.desktop + ") */\n";
    c = c + "    for (;;) { /* reap children; PID 1 never exits */ }\n";
    c = c + "}\n";
    return c;
  }

  String isoRecipe(OsModel m) {
    String iso = m.name + "-" + m.version + "-" + m.arch + ".iso";
    String r = "#!/bin/sh\n# gen-iso.sh for " + identity(m) + "\nset -eu\n";
    r = r + "STAGE=staging/rootfs\nOUT=" + iso + "\n";
    r = r + "cc  -c os/os_boot.c  -o \"$STAGE/boot/os_boot.o\"\n";
    r = r + "c++ -c os/os_image.cpp -o \"$STAGE/boot/os_image.o\"\n";
    r = r + "install-loader --loader " + m.loader + " --esp \"$STAGE/boot/efi\"\n";
    r = r + "xorriso -as mkisofs -V " + m.name + "-" + m.version
          + " -o \"$OUT\" -e boot/efi/EFI/BOOT/BOOTX64.EFI -no-emul-boot -J -R \"$STAGE\"\n";
    return r;
  }

  String makefile(OsModel m) {
    String mk = "# Makefile - generated for " + identity(m) + "\n";
    mk = mk + "CC ?= cc\nCXX ?= c++\n\n";
    mk = mk + "all: os iso\n\n";
    mk = mk + "os: build/os_boot.o build/os_image.o build/os_loader.o\n\n";
    mk = mk + "build/%.o: os/%.c\n\t@mkdir -p build\n\t$(CC) -c $< -o $@\n\n";
    mk = mk + "build/os_image.o: os/os_image.cpp\n\t@mkdir -p build\n\t$(CXX) -c $< -o $@\n\n";
    mk = mk + "iso: os\n\tsh tools/gen-iso.sh\n\n";
    mk = mk + "upstream:\n\tsh fetch-upstream.sh\n\n";
    mk = mk + ".PHONY: all os iso upstream\n";
    return mk;
  }

  String buildSh(OsModel m) {
    String s = "#!/bin/sh\n# build.sh - compile the generated " + m.shape + " OS sources\nset -eu\n";
    s = s + "make all\n";
    return s;
  }

  < ---- materialise the whole tree ------------------------------------- >
  void generate(OsModel m) {
    makeDir("");
    makeDir("/os");
    makeDir("/userspace");
    makeDir("/userspace/os-loader");
    makeDir("/tools");
    makeDir("/upstream");

    < The OS itself (real Linux-level C/C++). >
    writeFile("/os/os_config.h", configHeader(m));
    writeFile("/os/os_boot.c",   bootUnit(m));
    writeFile("/os/os_image.cpp", osImage(m));
    writeFile("/os/exec_types.h", execTypesHeader(m));
    writeFile("/os/exec_translate.h", execTranslateHeader(m));
    writeFile("/userspace/os-loader/os_loader.c", osLoaderC(m));
    makeDir("/userspace/compat-loader");
    writeFile("/userspace/compat-loader/compat_loader.c", compatLoaderC(m));
    writeFile("/userspace/compat-loader/compat.conf", compatConf(m));
    makeDir("/config");
    writeFile("/config/os.conf", osConf(m));
    writeFile("/config/cmdline.conf", cmdlineConf(m));
    writeFile("/config/downloads.conf", downloadsConf(m));
    writeFile("/config/support-urls.conf", supportUrlsConf(m));
    writeFile("/fetch-downloads.sh", fetchDownloadsSh(m));
    writeFile("/fetch-downloads-resilient.sh", fetchResilientSh(m));
    writeFile("/config/swap.conf", swapConf(m));
    writeFile("/config/filesystems.txt", filesystemsConf(m));
    makeDir("/kernel");
    makeDir("/kernel/base-drivers");
    writeFile("/kernel/base-drivers/base_drivers_table.c", baseDriversTableC(m));
    writeFile("/kernel/base-drivers/base-drivers.conf", baseDriversConf(m));

    < Build tooling + ISO recipe. >
    writeFile("/tools/gen-iso.sh", isoRecipe(m));
    writeFile("/Makefile", makefile(m));
    writeFile("/build.sh", buildSh(m));

    < Upstream provenance + the opt-in fetch script (closes the loop). >
    writeFile("/upstream/DISTRO.reference", upstream.referenceSheet());
    writeFile("/fetch-upstream.sh", upstream.fetchScript());

    < Self-describing manifest, written last. >
    String md = "# Generated OS source tree\n\n";
    md = md + "Model: " + identity(m) + "\n\n";
    md = md + "Upstream parts: see upstream/DISTRO.reference (fetch with: sh fetch-upstream.sh)\n\n";
    md = md + "Files written: " + fileCount + "\n\n## Index (bytes path)\n\n" + manifest + "\n";
    writeFile("/MANIFEST.md", md);
  }

  < Read a build parameter from the environment, or fall back to a default. >
  String param(String envName, String fallback) {
    String v = osGetEnv(envName);
    if (v == "") { return fallback; }
    return v;
  }

  void main() {
    String outRoot = param("OS_OUT", "/projects/sandbox/os-out");
    configure(outRoot);

    OsModel os = linux(param("OS_NAME", "Determinant"),
                       param("OS_VERSION", "1.0"),
                       param("OS_ARCH", "amd64"),
                       resolveKernel(param("OS_KERNEL_VER", "default")));

    print("================================================================");
    print("  SLeeLa OS generator -> " + identity(os));
    print("  kernel: " + os.kernel + " " + os.kernelVer);
    print("  output root: " + outRoot);
    print("================================================================");

    generate(os);

    print("wrote " + fileCount + " files to " + outRoot);
    print("");
    print(manifest);
    print("");
    print("next:");
    print("  cd " + outRoot + " && sh build.sh        # compile the generated OS sources");
    print("  cd " + outRoot + " && sh fetch-upstream.sh # opt-in: download the real OS parts");
    print("done");
  }
}