#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-
#
# Copyright (C) 2003 - 2026 Qore Technologies, s.r.o.
#
# Computes precise source and artifact dependencies for incremental AOT builds.

%modern
%requires json

# The cache version, rather than this helper's mtime, is the graph-semantics
# contract.  Bump it whenever source summaries or graph construction change;
# command/output and orchestration-only edits must not make every large consumer
# rescan all of its sources on the next otherwise-no-op build.
const CACHE_VERSION = 39;
#! The sidecar beside a batch stamp that dates the group's last shared parse.
/** The batch stamp cannot date it: the build tool also uses the stamp for
    ordering, so recipes that publish nothing touch it.  qore-qo-batch-bootstrap
    advances this file only when a shared parse has published the whole group.
*/
const BATCH_PUBLICATION_SUFFIX = ".publication";
#! The sidecar carrying a member's declaration contract, beside its object.
/** qcc's content-preserving description of what a consumer compiles AGAINST,
    with the lowering artifacts left out: the same source parsed in a whole-group
    batch and standalone against shells publishes the same bytes here, where its
    `.compile-contract.stamp` legitimately differs.  That is what makes it the
    right thing for both a folded-constant dependency edge and the planner's
    generation token to watch, and both do.
*/
const DeclarationContractSuffix = ".aggregate-contract.stamp";
#! The sidecar carrying the body contracts a member publishes.
/** What the declaration contract deliberately leaves out, and the only reason
    leaving it out is safe.  `--link-qo` compares a consumer's recorded import hash
    against the provider's published body-contract hash and fails the aggregate with
    "qo-link hash mismatch" when they differ, so a consumer that BAKED one has to be
    rebuilt when it moves -- and the declaration contract cannot say that it did.

    A consumer records this as a dependency only when it baked one.  On one real
    875-source group 856 objects PUBLISH a body contract while only 280 consume one,
    from 25 providers; watching it per consumer is what keeps the other 576 out of
    the cascade that folding these hashes into the declaration contract would cause.
*/
const BodyContractSuffix = ".body-contract.stamp";
#! The sidecar naming the body-contract rows a member baked, beside its object.
/** A provider publishes one body contract for every symbol it has one for, and a consumer
    links against only the ones it baked.  Watching the whole stamp made a consumer stale
    whenever ANY of the provider's body hashes moved -- and they move for every symbol a
    group parse proves more about than a standalone one, so switching a provider between
    the two compile modes rebuilt every consumer of it however little they took.  qcc
    writes this beside the object (`import` rows naming the provider stamp and the symbol),
    and the generation token digests only those rows of the provider's stamp.
*/
const BodyContractImportsSuffix = ".body-contract-imports";
#! The sidecar naming the sources an object's code needs declared wherever it is loaded.
/** Parse commit runs the initializers of what a compile preloads, and code they reach in a
    preloaded object registers only in a Program declaring every class and function it calls.
    Those providers are not build dependencies -- a late-bound call bakes nothing of its target
    -- so no depfile names them.  qcc writes this beside the object (`require` rows naming a
    provider source), and a preload set is closed over it as well as over the depfiles.
*/
const LoadRequiresSuffix = ".load-requires";
const SOURCE_SYMBOL_CACHE_VERSION = 1;
const SOURCE_SUMMARY_KEYS = (
    "provides",
    "classes",
    "enums",
    "hashdecls",
    "functions",
    "parse_defines",
    "inheritance_mentions",
    "hard_mentions",
    "decl_type_mentions",
    "hash_type_mentions",
    "enum_type_mentions",
    "call_ref_classes",
    "call_ref_functions",
    "constructed_decl_type_mentions",
    "new_hash_type_mentions",
    "new_object_mentions",
    "class_for_name_mentions",
    "create_object_mentions",
    "static_call_mentions",
    "param_default_static_call_mentions",
    "static_ref_mentions",
    "includes",
    "parse_define_consumers",
);

hashdecl SourceOrderContext {
    list<string> inputs;
    list<string> source_content_digests;
    list<string> outputs;
    hash<string, bool> parse_defines;
}

hashdecl SourceOrderGraph {
    list<hash<string, bool>> outgoing;
    list<hash<string, bool>> incoming;
    list<hash<string, bool>> required;
    list<hash<string, list<string>>> summaries;
}

#! The strongly connected components of the required-edge graph.
/** A required edge that closes a cycle cannot be expressed as a build edge, so
    every member of one component must be compiled and published as a single
    atomic generation. This hashdecl is that decomposition: \c members is the
    partition, \c predecessors is the condensed DAG, and \c component_keys names
    each component by content rather than by node numbering so the same
    component keeps its identity when the source list is reordered.
*/
hashdecl SourceOrderComponents {
    #! component index -> member node indexes, ascending
    list<list<int>> members;
    #! node index -> component index
    list<int> component_of;
    #! component index -> direct predecessor component indexes, ascending
    list<list<int>> predecessors;
    #! component index -> stable component key derived from the member outputs
    list<string> component_keys;
    #! deterministic topological order of the condensed DAG
    list<int> topological_order;
}

class SourceSymbolManifestGenerator {
    private {
        Regex class_re = new Regex("\\b(?:public\\s+|private\\s+|abstract\\s+|final\\s+)*class\\s+([A-Za-z_][A-Za-z0-9_]*)\\b", RE_Global);
        Regex class_inherits_re = new Regex(
            "\\b(?:public\\s+|private\\s+|abstract\\s+|final\\s+)*class\\s+"
            "[A-Za-z_][A-Za-z0-9_]*\\b[^\\{;]*\\binherits\\s+([^\\{;]+)", RE_Global);
        Regex enum_re = new Regex(
            "\\b(?:public\\s+|private\\s+)*enum\\s+([A-Za-z_][A-Za-z0-9_]*)\\b", RE_Global);
        Regex hashdecl_re = new Regex("\\bhashdecl\\s+([A-Za-z_][A-Za-z0-9_]*)\\b", RE_Global);
        Regex sub_re = new Regex("\\b(?:[\\w:*<>]+\\s+)*sub\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\(", RE_Global);
        Regex const_re = new Regex("\\bconst\\s+([A-Za-z_][A-Za-z0-9_]*)\\b", RE_Global);
        Regex const_init_re = new Regex(
            "\\bconst\\s+[A-Za-z_][A-Za-z0-9_]*\\s*=\\s*(.*?);", RE_Global | RE_DotAll);
        Regex static_decl_re = new Regex(
            "\\bstatic[ \\t]+([^;{}]+);", RE_Global | RE_DotAll);
        Regex global_group_re = new Regex("(?<![-A-Za-z0-9_])(?:our|thread_local)\\b\\s*\\(", RE_Global);
        Regex global_scalar_re = new Regex(
            "(?<![-A-Za-z0-9_])(?:our|thread_local)\\b\\s+(?!\\()"
            "(?:(?:\\*?[A-Za-z_][A-Za-z0-9_:]*(?:[ \\t]*<[A-Za-z0-9_:<>,* \\t]+>)?)\\s+)+"
            "\\*?([A-Za-z_][A-Za-z0-9_]*)\\b", RE_Global);
        Regex global_name_re = new Regex("\\*?([A-Za-z_][A-Za-z0-9_]*)\\s*$");
        Regex namespace_event_re = new Regex(
            "\\b(?:public\\s+|private\\s+|internal\\s+)*namespace\\s+"
            "([A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*)\\s*\\{|[{}]", RE_Global);
        Regex conditional_re = new Regex("^%(ifn?def)[ \\t]+([A-Za-z_][A-Za-z0-9_]*)\\b");
        Regex conditional_scan_re = new Regex(
            "^[ \\t]*%(ifn?def)[ \\t]+([A-Za-z_][A-Za-z0-9_]*)\\b", RE_Global | RE_MultiLine);
        Regex include_re = new Regex("^[ \\t]*%include[ \\t]+([^ \\t\\r\\n#]+)", RE_Global | RE_MultiLine);
        Regex parse_define_re = new Regex(
            "^[ \\t]*%define[ \\t]+([A-Za-z_][A-Za-z0-9_]*)\\b", RE_Global | RE_MultiLine);
        Regex parse_define_consumer_re = new Regex(
            "^[ \\t]*%ifn?def[ \\t]+([A-Za-z_][A-Za-z0-9_]*)\\b", RE_Global | RE_MultiLine);
        Regex call_ref_re = new Regex(
            "\\\\[ \\t]*([A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*)[ \\t]*\\(", RE_Global);
        Regex static_call_re = new Regex(
            "\\b([A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*)::"
            "([A-Za-z_][A-Za-z0-9_]*)[ \\t]*\\(", RE_Global);
        Regex static_ref_re = new Regex(
            "\\b([A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*)::"
            "([A-Za-z_][A-Za-z0-9_]*)\\b(?![ \\t]*\\()", RE_Global);
        Regex new_object_re = new Regex(
            "\\bnew[ \\t]+([A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*)[ \\t]*\\(", RE_Global);
        Regex new_hash_re = new Regex("\\bnew[ \\t]+hash\\b", RE_Global);
        Regex create_object_re = new Regex(
            "\\bcreate_object[ \\t]*\\([ \\t]*[\"']"
            "([A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*)[\"']", RE_Global);
        Regex class_for_name_re = new Regex(
            "\\b(?:Reflection::)?Class::forName[ \\t]*\\([ \\t]*[\"']"
            "([A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*)[\"']", RE_Global);
        Regex qual_re = new Regex(
            "\\b([A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*)\\b", RE_Global);
        Regex token_re = new Regex("\\b([A-Za-z_][A-Za-z0-9_]*)\\b", RE_Global);
        Regex decl_type_re = new Regex(
            "^[ \\t]*(?:public|private|internal|static|our|thread_local)?[ \\t]*\\*?[ \\t]*"
            "([A-Za-z_][A-Za-z0-9_:]*)[ \\t]+[A-Za-z_][A-Za-z0-9_]*\\b");
        Regex constructed_decl_type_re = new Regex(
            "^(?:(?:public|private|internal)[ \\t]*\\{[ \\t]*)?"
            "(?:(?:public|private|internal|static|our|thread_local)[ \\t]+)*\\*?[ \\t]*"
            "([A-Za-z_][A-Za-z0-9_:]*(?:[ \\t]*<[A-Za-z0-9_:<>,* \\t]+>)?)[ \\t]+"
            "[A-Za-z_][A-Za-z0-9_]*[ \\t]*\\([ \\t]*\\)[ \\t]*(?:;|=)");
        Regex param_type_re = new Regex(
            "[(,][ \\t]*\\*?[ \\t]*([A-Za-z_][A-Za-z0-9_:]*)[ \\t]+"
            "[A-Za-z_][A-Za-z0-9_]*\\b", RE_Global);
        Regex qualified_ref_re = new Regex(
            "\\b[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)+\\b", RE_Global);
        Regex paren_re = new Regex("[()]", RE_Global);
        Regex case_re = new Regex("\\bcase\\b", RE_Global);
        Regex hash_token_re = new Regex("\\bhash\\b", RE_Global);
        Regex enum_token_re = new Regex("\\benum\\b", RE_Global);
        hash<string, bool> callable_modifiers = (
            "public": True, "private": True, "internal": True, "static": True,
            "abstract": True, "final": True, "synchronized": True, "deprecated": True,
        );
        hash<string, bool> non_callable_names = (
            "if": True, "for": True, "while": True, "switch": True, "catch": True,
            "foreach": True, "map": True, "foldl": True, "foldr": True,
        );
        hash<string, bool> non_type_prefixes = (
            "return": True, "throw": True, "new": True, "case": True,
        );
        # A regex literal is matched BEFORE the comment alternatives: `#`, `//` and quotes are ordinary
        # characters inside one, and masking `if (line =~ /^#/ || !line.length()) {` as a comment swallowed
        # the block's opening brace.  The brace depth then desynchronised for the rest of the file and every
        # declaration after that point was recorded in the manifest without its namespace -- which made a
        # deferred type render as `hash<SlaInfo>` where the same type resolved live renders as
        # `hash<OMQ::SlaInfo>`, so the two compile modes published different signatures for it.
        # `=~` / `!~` is what disambiguates the leading `/` from division.
        string mask_pattern = "(?:(?:=~|!~)\\s*(?:(?:s|tr|t)/(?:\\\\[\\s\\S]|[^/\\\\\\n])*"
            "/(?:\\\\[\\s\\S]|[^/\\\\\\n])*/[A-Za-z]*"
            "|[A-Za-z]*/(?:\\\\[\\s\\S]|[^/\\\\\\n])*/[A-Za-z]*)|"
            "\"(?:\\\\[\\s\\S]|[^\"\\\\])*\"|'(?:\\\\[\\s\\S]|[^'\\\\])*'|"
            "(?<!\\\\)//[^\\n]*|(?<!\\$)#[^\\n]*|/\\*[\\s\\S]*?\\*/)";
    }

    private string maskSource(string text, bool preserve_strings = False) {
        return regex_subst(text, mask_pattern, string sub(hash<RegexMatchInfo> match) {
            if (preserve_strings && match.match
                    && (match.match.getByte(0) == 0x22 || match.match.getByte(0) == 0x27)) {
                return match.match;
            }
            return regex_subst(match.match, "[^\\n]", " ", RE_Global);
        }, RE_Global);
    }

    private bool active(list<hash<auto>> stack) {
        foreach hash<auto> frame in (stack) {
            if (!frame.active) {
                return False;
            }
        }
        return True;
    }

    private int directiveOffset(string line) {
        for (int offset = 0; offset < line.size(); ++offset) {
            int byte = line.getByte(offset);
            if (byte != 0x20 && byte != 0x09) {
                return byte == 0x25 ? offset : -1;
            }
        }
        return -1;
    }

    private string applyConditionals(string code, hash<string, bool> true_defines) {
        if (code.find("%ifdef") < 0 && code.find("%ifndef") < 0) {
            return code;
        }
        hash<string, bool> known_true = (
            "QoreStandaloneQo": True,
            "QorusStandaloneQo": True,
        );
        foreach string define in (true_defines.keys()) {
            known_true{define} = True;
        }
        bool has_known_conditional = False;
        list<*string> conditional_groups = conditional_scan_re.extractGroups(code) ?? ();
        for (int index = 1; index < conditional_groups.size(); index += 2) {
            if (exists conditional_groups[index] && exists known_true{conditional_groups[index]}) {
                has_known_conditional = True;
                break;
            }
        }
        if (!has_known_conditional) {
            return code;
        }
        list<string> input_lines = code.split("\n");
        list<string> output_lines = ();
        list<hash<auto>> stack = ();
        int last = input_lines.size() - 1;
        for (int index = 0; index < input_lines.size(); ++index) {
            if (index == last && !input_lines[index] && code.endsWith("\n")) {
                break;
            }
            string line = input_lines[index] + (index < last ? "\n" : "");
            int directive_offset = directiveOffset(line);
            if (directive_offset < 0) {
                push output_lines, active(stack) ? line : (line.endsWith("\n") ? "\n" : "");
                continue;
            }
            string directive_line = line.substr(directive_offset);
            *list<*string> conditional = conditional_re.extractGroups(directive_line);
            if (conditional) {
                bool parent_active = active(stack);
                string directive = conditional[0];
                string symbol = conditional[1];
                bool known = exists known_true{symbol};
                if (known) {
                    bool condition = directive == "ifndef" ? False : True;
                    push stack, (
                        "known": True,
                        "parent_active": parent_active,
                        "condition": condition,
                        "active": parent_active && condition,
                    );
                    push output_lines, line.endsWith("\n") ? "\n" : "";
                } else {
                    push stack, (
                        "known": False,
                        "parent_active": parent_active,
                        "condition": True,
                        "active": parent_active,
                    );
                    push output_lines, parent_active ? line : (line.endsWith("\n") ? "\n" : "");
                }
                continue;
            }
            if (directive_line =~ /^%else\b/ && stack) {
                hash<auto> frame = pop stack;
                if (frame.known) {
                    frame.active = frame.parent_active && !frame.condition;
                    push output_lines, line.endsWith("\n") ? "\n" : "";
                } else {
                    frame.active = frame.parent_active;
                    push output_lines, frame.parent_active ? line : (line.endsWith("\n") ? "\n" : "");
                }
                push stack, frame;
                continue;
            }
            if (directive_line =~ /^%endif\b/ && stack) {
                hash<auto> frame = pop stack;
                push output_lines, !frame.known && active(stack)
                    ? line : (line.endsWith("\n") ? "\n" : "");
                continue;
            }
            push output_lines, active(stack) ? line : (line.endsWith("\n") ? "\n" : "");
        }
        return join("", output_lines);
    }

    private list<string> splitTopLevel(string text, int separator = 0x2c) {
        list<string> parts = ();
        int start = 0;
        int angle = 0;
        int paren = 0;
        int bracket = 0;
        int brace = 0;
        for (int offset = 0; offset < text.size(); ++offset) {
            int byte = text.getByte(offset);
            switch (byte) {
                case 0x3c: ++angle; break;
                case 0x3e: if (angle) --angle; break;
                case 0x28: ++paren; break;
                case 0x29: if (paren) --paren; break;
                case 0x5b: ++bracket; break;
                case 0x5d: if (bracket) --bracket; break;
                case 0x7b: ++brace; break;
                case 0x7d: if (brace) --brace; break;
                default:
                    if (byte == separator && !angle && !paren && !bracket && !brace) {
                        push parts, text.substr(start, offset - start);
                        start = offset + 1;
                    }
            }
        }
        push parts, text.substr(start);
        return parts;
    }

    private int findBalancedClose(string code, int open_pos) {
        int depth = 0;
        for (int offset = open_pos; offset < code.size(); ++offset) {
            int byte = code.getByte(offset);
            if (byte == 0x28) {
                ++depth;
            } else if (byte == 0x29 && !--depth) {
                return offset;
            }
        }
        return -1;
    }

    private list<hash<auto>> globalNames(string code) {
        list<hash<auto>> consumed = ();
        list<hash<auto>> names = ();
        foreach hash<RegexMatchInfo> match in (global_group_re.extractDetailed(code) ?? ()) {
            int match_offset = match.offset;
            int match_length = match.length;
            int relative_open = code.substr(match_offset, match_length).find("(");
            if (relative_open < 0) {
                continue;
            }
            int open_pos = match_offset + relative_open;
            int close_pos = findBalancedClose(code, open_pos);
            if (close_pos < 0) {
                continue;
            }
            push consumed, ("start": match_offset, "end": close_pos + 1);
            string body = code.substr(open_pos + 1, close_pos - open_pos - 1);
            foreach string entry in (splitTopLevel(body)) {
                string candidate = trim(entry);
                if (!candidate) {
                    continue;
                }
                int equals = candidate.find("=");
                if (equals >= 0) {
                    candidate = trim(candidate.substr(0, equals));
                }
                *list<hash<RegexMatchInfo>> name_matches = global_name_re.extractDetailed(candidate);
                if (name_matches && name_matches[0].groups && exists name_matches[0].groups[0]) {
                    push names, ("name": name_matches[0].groups[0], "offset": match_offset);
                }
            }
        }
        foreach hash<RegexMatchInfo> match in (global_scalar_re.extractDetailed(code) ?? ()) {
            *string capture = match.groups ? match.groups[0] : NOTHING;
            if (!exists capture) {
                continue;
            }
            bool in_consumed = False;
            foreach hash<auto> range in (consumed) {
                if (match.offset >= range.start && match.offset < range.end) {
                    in_consumed = True;
                    break;
                }
            }
            if (!in_consumed) {
                push names, ("name": capture, "offset": match.offset);
            }
        }
        return names;
    }

    private string childNamespace(string parent, string child) {
        if (child.startsWith("::")) {
            child = child.substr(2);
        }
        return !parent || child.find("::") >= 0 ? child : parent + "::" + child;
    }

    private list<hash<auto>> namespaceRanges(string code) {
        list<hash<auto>> ranges = ();
        list<hash<auto>> frames = ();
        int brace_depth = 0;
        int last = 0;
        foreach hash<RegexMatchInfo> match in (namespace_event_re.extractDetailed(code) ?? ()) {
            int match_offset = match.offset;
            int match_length = match.length;
            *string namespace_name = match.groups ? match.groups[0] : NOTHING;
            string current_namespace = frames ? frames[-1].namespace : "";
            if (match_offset > last) {
                push ranges, (
                    "start": last,
                    "end": match_offset,
                    "namespace": current_namespace,
                );
            }
            if (exists namespace_name) {
                ++brace_depth;
                push frames, (
                    "depth": brace_depth,
                    "namespace": childNamespace(current_namespace, namespace_name),
                );
            } else if (code.getByte(match_offset) == 0x7b) {
                ++brace_depth;
            } else if (brace_depth) {
                --brace_depth;
                while (frames && frames[-1].depth > brace_depth) {
                    pop frames;
                }
            }
            last = match_offset + match_length;
        }
        if (last < code.size()) {
            push ranges, (
                "start": last,
                "end": code.size(),
                "namespace": frames ? frames[-1].namespace : "",
            );
        }
        return ranges;
    }

    private string namespaceAt(list<hash<auto>> ranges, int offset) {
        int low = 0;
        int high = ranges.size() - 1;
        while (low <= high) {
            int middle = (low + high) / 2;
            hash<auto> range = ranges[middle];
            if (offset < range.start) {
                high = middle - 1;
            } else if (offset >= range.end) {
                low = middle + 1;
            } else {
                return range.namespace;
            }
        }
        return "";
    }

    private list<string> qualifiedCaptures(Regex pattern, string code, list<hash<auto>> ranges) {
        list<string> values = ();
        foreach hash<RegexMatchInfo> match in (pattern.extractDetailed(code) ?? ()) {
            *string capture = match.groups ? match.groups[0] : NOTHING;
            if (exists capture) {
                push values, qualify(namespaceAt(ranges, match.offset), capture);
            }
        }
        return values;
    }

    private string qualify(string namespace_name, string name) {
        return namespace_name ? namespace_name + "::" + name : name;
    }

    private string simpleName(string name) {
        int separator = name.rfind("::");
        return separator < 0 ? name : name.substr(separator + 2);
    }

    private hash<string, bool> captureSet(Regex pattern, string code, bool simple = False) {
        hash<string, bool> values = {};
        foreach *string value in (pattern.extractGroups(code) ?? ()) {
            if (exists value) {
                values{simple ? simpleName(value) : value} = True;
            }
        }
        return values;
    }

    private addSet(reference<hash<string, bool>> target, hash<string, bool> source) {
        foreach string value in (source.keys()) {
            target{value} = True;
        }
    }

    private hash<string, bool> collectProvides(string code) {
        hash<string, bool> values = {};
        foreach Regex pattern in ((class_re, enum_re, hashdecl_re, sub_re, const_re)) {
            addSet(\values, captureSet(pattern, code));
        }
        foreach hash<auto> info in (globalNames(code)) {
            values{info.name} = True;
        }
        return values;
    }

    private string stripIncludeDelimiters(string value) {
        int start = 0;
        int end = value.size();
        while (start < end && (value.getByte(start) == 0x22 || value.getByte(start) == 0x27
                || value.getByte(start) == 0x3c || value.getByte(start) == 0x3e)) {
            ++start;
        }
        while (end > start && (value.getByte(end - 1) == 0x22 || value.getByte(end - 1) == 0x27
                || value.getByte(end - 1) == 0x3c || value.getByte(end - 1) == 0x3e)) {
            --end;
        }
        return value.substr(start, end - start);
    }

    private hash<string, bool> collectIncludes(string code) {
        hash<string, bool> values = {};
        foreach *string value in (include_re.extractGroups(code) ?? ()) {
            if (exists value) {
                string name = stripIncludeDelimiters(value);
                if (name) {
                    values{name} = True;
                }
            }
        }
        return values;
    }

    private hash<string, bool> collectMentions(string code) {
        hash<string, bool> values = {};
        for (int offset = 0; offset < code.size();) {
            int byte = code.getByte(offset);
            if (!alphaByte(byte)) {
                ++offset;
                continue;
            }
            int start = offset++;
            while (offset < code.size() && identByte(code.getByte(offset))) {
                ++offset;
            }
            values{code.substr(start, offset - start)} = True;
        }
        return values;
    }

    private hash<string, bool> collectUnqualifiedMentions(string code) {
        string unqualified = regex_subst(code,
            "\\b[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)+\\b",
            string sub (hash<RegexMatchInfo> match) {
                return strmul(" ", match.length);
            }, RE_Global);
        hash<string, bool> result = captureSet(token_re, unqualified);
        return result;
    }

    private list<string> angleArgs(string code, Regex token_pattern) {
        list<string> values = ();
        foreach hash<RegexMatchInfo> match in (token_pattern.extractDetailed(code) ?? ()) {
            int pos = match.offset + match.length;
            while (pos < code.size() && (code.getByte(pos) == 0x20 || code.getByte(pos) == 0x09
                    || code.getByte(pos) == 0x0a || code.getByte(pos) == 0x0d)) {
                ++pos;
            }
            if (pos >= code.size() || code.getByte(pos) != 0x3c) {
                continue;
            }
            int start = ++pos;
            int depth = 1;
            while (pos < code.size()) {
                int byte = code.getByte(pos);
                if (byte == 0x3c) {
                    ++depth;
                } else if (byte == 0x3e && !--depth) {
                    push values, code.substr(start, pos - start);
                    ++pos;
                    break;
                }
                ++pos;
            }
        }
        return values;
    }

    private hash<string, bool> collectAngleMentions(string code, Regex token_pattern) {
        hash<string, bool> values = {};
        foreach string args in (angleArgs(code, token_pattern)) {
            addSet(\values, collectMentions(args));
        }
        return values;
    }

    private hash<string, bool> collectNewHashTypeMentions(string code) {
        hash<string, bool> values = {};
        foreach hash<RegexMatchInfo> match in (new_hash_re.extractDetailed(code) ?? ()) {
            int pos = match.offset + match.length;
            while (pos < code.size() && (code.getByte(pos) == 0x20 || code.getByte(pos) == 0x09)) {
                ++pos;
            }
            if (pos >= code.size() || code.getByte(pos) != 0x3c) {
                continue;
            }
            int start = ++pos;
            int depth = 1;
            while (pos < code.size()) {
                int byte = code.getByte(pos);
                if (byte == 0x3c) {
                    ++depth;
                } else if (byte == 0x3e && !--depth) {
                    addSet(\values, collectMentions(code.substr(start, pos - start)));
                    break;
                }
                ++pos;
            }
        }
        return values;
    }

    private hash<string, bool> collectDeclTypeMentions(string code) {
        hash<string, bool> values = {};
        foreach string line in (code.split("\n")) {
            if (line.find("(") >= 0 || line.find(";") >= 0 || line.find("=") >= 0) {
                *list<*string> declaration = decl_type_re.extractGroups(line);
                if (declaration && exists declaration[0]) {
                    values{simpleName(declaration[0])} = True;
                }
            }
            if (line.find("(") >= 0 || line.find(",") >= 0) {
                foreach *string value in (param_type_re.extractGroups(line) ?? ()) {
                    if (exists value) {
                        values{simpleName(value)} = True;
                    }
                }
            }
        }
        return values;
    }

    private hash<string, bool> collectConstructedDeclTypeMentions(string code) {
        hash<string, bool> values = {};
        foreach string line in (code.split("\n")) {
            if (line.find("(") < 0 || line.find(")") < 0) {
                continue;
            }
            *list<*string> declaration = constructed_decl_type_re.extractGroups(trim(line));
            if (declaration && exists declaration[0]) {
                addSet(\values, collectMentions(declaration[0]));
            }
        }
        return values;
    }

    private hash<auto> collectCallRefMentions(string code) {
        hash<string, bool> class_mentions = {};
        hash<string, bool> function_mentions = {};
        foreach *string path in (call_ref_re.extractGroups(code) ?? ()) {
            if (!exists path) {
                continue;
            }
            list<string> parts = path.split("::");
            if (parts.size() == 1) {
                function_mentions{parts[0]} = True;
            } else {
                for (int index = 0; index < parts.size() - 1; ++index) {
                    class_mentions{parts[index]} = True;
                }
                function_mentions{parts[-1]} = True;
            }
        }
        return ("classes": class_mentions, "functions": function_mentions);
    }

    private hash<string, bool> collectStaticCallMentions(string code) {
        hash<string, bool> values = {};
        foreach hash<RegexMatchInfo> match in (static_call_re.extractDetailed(code) ?? ()) {
            *string capture = match.groups ? match.groups[0] : NOTHING;
            if (exists capture) {
                values{simpleName(capture)} = True;
            }
        }
        return values;
    }

    private bool asciiSpace(int byte) {
        return byte == 0x20 || byte == 0x09 || byte == 0x0a || byte == 0x0d
            || byte == 0x0b || byte == 0x0c;
    }

    private bool identByte(int byte) {
        return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x5a)
            || (byte >= 0x61 && byte <= 0x7a) || byte == 0x5f;
    }

    private bool alphaByte(int byte) {
        return (byte >= 0x41 && byte <= 0x5a) || (byte >= 0x61 && byte <= 0x7a) || byte == 0x5f;
    }

    private bool callableDeclaration(string code, int open_pos, int close_pos) {
        int tail = close_pos + 1;
        while (tail < code.size() && asciiSpace(code.getByte(tail))) {
            ++tail;
        }
        if (tail >= code.size() || (code.getByte(tail) != 0x7b && code.getByte(tail) != 0x3a
                && code.getByte(tail) != 0x3b)) {
            return False;
        }

        int search_start = max(0, open_pos - 4096);
        string header = code.substr(search_start, open_pos - search_start);
        int header_start = -1;
        foreach string delimiter in ((";", "{", "}")) {
            header_start = max(header_start, header.rfind(delimiter));
        }
        header_start += search_start + 1;
        int name_end = open_pos;
        while (name_end > header_start && asciiSpace(code.getByte(name_end - 1))) {
            --name_end;
        }
        int name_start = name_end;
        while (name_start > header_start && identByte(code.getByte(name_start - 1))) {
            --name_start;
        }
        if (name_start == name_end || !alphaByte(code.getByte(name_start))) {
            return False;
        }
        string name = code.substr(name_start, name_end - name_start);
        string prefix = trim(code.substr(header_start, name_start - header_start));
        if (name == "constructor") {
            if (!prefix) {
                return True;
            }
            foreach string word in (prefix.splitRegex("\\s+")) {
                if (!exists callable_modifiers{word}) {
                    return False;
                }
            }
            return True;
        }
        if (exists non_callable_names{name}) {
            return False;
        }
        if (prefix =~ /\\bsub\\s*$/) {
            return True;
        }
        if (!prefix) {
            return code.getByte(tail) == 0x7b || code.getByte(tail) == 0x3a;
        }
        if (prefix.endsWith("::")) {
            return False;
        }
        foreach string invalid in (("=", ".", "?", "!", "+", "/", "-", "%", "&", "|",
                "[", "]", "(", ")", "@", "\\")) {
            if (prefix.find(invalid) >= 0) {
                return False;
            }
        }
        string first_word = prefix.splitRegex("\\s+")[0];
        return !exists non_type_prefixes{first_word};
    }

    private int lowerBound(list<int> values, int target) {
        int low = 0;
        int high = values.size();
        while (low < high) {
            int middle = (low + high) / 2;
            if (values[middle] < target) {
                low = middle + 1;
            } else {
                high = middle;
            }
        }
        return low;
    }

    private hash<string, bool> collectParamDefaultStaticCallMentions(string code) {
        hash<string, bool> values = {};
        list<int> static_positions = ();
        foreach hash<RegexMatchInfo> match in (static_call_re.extractDetailed(code) ?? ()) {
            push static_positions, match.offset;
        }
        if (!static_positions) {
            return values;
        }
        list<int> stack = ();
        foreach hash<RegexMatchInfo> match in (paren_re.extractDetailed(code) ?? ()) {
            if (code.getByte(match.offset) == 0x28) {
                push stack, match.offset;
                continue;
            }
            if (!stack) {
                continue;
            }
            int open_pos = pop stack;
            int match_index = lowerBound(static_positions, open_pos);
            if (match_index >= static_positions.size() || static_positions[match_index] >= match.offset
                    || !callableDeclaration(code, open_pos, match.offset)) {
                continue;
            }
            foreach string parameter in (splitTopLevel(code.substr(open_pos + 1,
                    match.offset - open_pos - 1))) {
                list<string> parts = splitTopLevel(parameter, 0x3d);
                if (parts.size() < 2) {
                    continue;
                }
                addSet(\values, collectStaticCallMentions(join("=", parts[1..])));
            }
        }
        return values;
    }

    private hash<string, bool> collectStaticRefMentions(string code) {
        hash<string, bool> values = {};
        foreach hash<RegexMatchInfo> match in (static_ref_re.extractDetailed(code) ?? ()) {
            *string capture = match.groups ? match.groups[0] : NOTHING;
            if (exists capture) {
                values{simpleName(capture)} = True;
            }
        }
        return values;
    }

    private list<string> caseExpressions(string code) {
        list<string> expressions = ();
        foreach hash<RegexMatchInfo> match in (case_re.extractDetailed(code) ?? ()) {
            int pos = match.offset + match.length;
            while (pos < code.size() && asciiSpace(code.getByte(pos))) {
                ++pos;
            }
            int start = pos;
            int paren = 0;
            int bracket = 0;
            int brace = 0;
            while (pos < code.size()) {
                int byte = code.getByte(pos);
                int next = pos + 1 < code.size() ? code.getByte(pos + 1) : -1;
                if (byte == 0x28) ++paren;
                else if (byte == 0x29 && paren) --paren;
                else if (byte == 0x5b) ++bracket;
                else if (byte == 0x5d && bracket) --bracket;
                else if (byte == 0x7b) ++brace;
                else if (byte == 0x7d && brace) --brace;
                else if (byte == 0x3a && next != 0x3a
                        && !(pos && code.getByte(pos - 1) == 0x3a)
                        && !paren && !bracket && !brace) {
                    push expressions, code.substr(start, pos - start);
                    break;
                } else if ((byte == 0x3b || byte == 0x0a) && !paren && !bracket && !brace) {
                    break;
                }
                ++pos;
            }
        }
        return expressions;
    }

    private hash<string, bool> collectInheritanceMentions(string code) {
        hash<string, bool> values = {};
        foreach *string bases in (class_inherits_re.extractGroups(code) ?? ()) {
            if (!exists bases) {
                continue;
            }
            foreach string name in (captureSet(qual_re, bases).keys()) {
                values{simpleName(name)} = True;
            }
        }
        return values;
    }

    private hash<string, bool> collectHardMentions(string code) {
        hash<string, bool> values = {};
        foreach hash<RegexMatchInfo> match in (const_init_re.extractDetailed(code) ?? ()) {
            *string expression = match.groups ? match.groups[0] : NOTHING;
            if (exists expression) {
                addSet(\values, collectUnqualifiedMentions(expression));
            }
        }
        foreach hash<RegexMatchInfo> match in (static_decl_re.extractDetailed(code) ?? ()) {
            *string declaration = match.groups ? match.groups[0] : NOTHING;
            if (!exists declaration) {
                continue;
            }
            int expression_offset = declaration.find("=");
            if (expression_offset < 0) {
                expression_offset = declaration.find("(");
            }
            if (expression_offset >= 0) {
                addSet(\values, collectUnqualifiedMentions(
                    declaration.substr(expression_offset + 1)));
            }
        }
        foreach string expression in (caseExpressions(code)) {
            addSet(\values, collectMentions(expression));
        }
        return values;
    }

    hash<string, list<string>> scanDependencySummary(string source,
            hash<string, bool> true_defines = {}) {
        int started = clock_getmicros_monotonic();
        string text = ReadOnlyFile::readTextFile(source);
        string code = applyConditionals(maskSource(text), true_defines);
        string literal_code = applyConditionals(maskSource(text, True), true_defines);
        int masking_done = clock_getmicros_monotonic();
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) stderr.printf("summary mask=%d us\n", masking_done - started);
        hash<auto> call_refs = collectCallRefMentions(code);
        int call_refs_done = clock_getmicros_monotonic();
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) stderr.printf("summary refs=%d us\n", call_refs_done - masking_done);
        hash<string, bool> provides = collectProvides(code);
        hash<string, bool> inheritance = collectInheritanceMentions(code);
        hash<string, bool> hard = collectHardMentions(code);
        int hard_done = clock_getmicros_monotonic();
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) stderr.printf("summary hard=%d us\n", hard_done - call_refs_done);
        hash<string, bool> declarations = collectDeclTypeMentions(code);
        hash<string, bool> constructed = collectConstructedDeclTypeMentions(code);
        int declarations_done = clock_getmicros_monotonic();
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) stderr.printf("summary declarations=%d us\n", declarations_done - hard_done);
        hash<string, bool> hash_types = collectAngleMentions(code, hash_token_re);
        hash<string, bool> enum_types = collectAngleMentions(code, enum_token_re);
        hash<string, bool> new_hash_types = collectNewHashTypeMentions(code);
        int angle_done = clock_getmicros_monotonic();
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) stderr.printf("summary angles=%d us\n", angle_done - declarations_done);
        hash<string, bool> param_defaults = collectParamDefaultStaticCallMentions(code);
        int params_done = clock_getmicros_monotonic();
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) stderr.printf("summary params=%d us\n", params_done - angle_done);
        hash<string, list<string>> summary = (
            "provides": sort(provides.keys()),
            "classes": sort(captureSet(class_re, code).keys()),
            "enums": sort(captureSet(enum_re, code).keys()),
            "hashdecls": sort(captureSet(hashdecl_re, code).keys()),
            "functions": sort(captureSet(sub_re, code).keys()),
            "parse_defines": sort(captureSet(parse_define_re, code).keys()),
            "inheritance_mentions": sort(inheritance.keys()),
            "hard_mentions": sort(hard.keys()),
            "decl_type_mentions": sort(declarations.keys()),
            "hash_type_mentions": sort(hash_types.keys()),
            "enum_type_mentions": sort(enum_types.keys()),
            "call_ref_classes": sort(call_refs.classes.keys()),
            "call_ref_functions": sort(call_refs.functions.keys()),
            "constructed_decl_type_mentions": sort(constructed.keys()),
            "new_hash_type_mentions": sort(new_hash_types.keys()),
            "new_object_mentions": sort(captureSet(new_object_re, code, True).keys()),
            "class_for_name_mentions": sort(captureSet(class_for_name_re, literal_code, True).keys()),
            "create_object_mentions": sort(captureSet(create_object_re, literal_code, True).keys()),
            "static_call_mentions": sort(collectStaticCallMentions(code).keys()),
            "param_default_static_call_mentions": sort(param_defaults.keys()),
            "static_ref_mentions": sort(collectStaticRefMentions(code).keys()),
            "includes": sort(collectIncludes(code).keys()),
            "parse_define_consumers": sort(captureSet(parse_define_consumer_re, code).keys()),
        );
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) {
            int completed = clock_getmicros_monotonic();
            stderr.printf("summary timing us: mask=%d refs=%d hard=%d declarations=%d angles=%d params=%d rest=%d\n",
                masking_done - started, call_refs_done - masking_done, hard_done - call_refs_done,
                declarations_done - hard_done, angle_done - declarations_done, params_done - angle_done,
                completed - params_done);
        }
        return summary;
    }

    hash<string, list<string>> scanDependencySummaryForContext(string source, string context_path) {
        return scanDependencySummary(source, contextDefines(context_path));
    }

    private hash<string, bool> contextDefines(string path) {
        hash<string, bool> defines = {};
        foreach string line in (ReadOnlyFile::readTextFile(path).split("\n")) {
            if (!line.startsWith("parse_define=")) {
                continue;
            }
            string value = line.substr(13);
            int equals = value.find("=");
            string name = equals >= 0 ? value.substr(0, equals) : value;
            if (name) {
                defines{name} = True;
            }
        }
        return defines;
    }

    private addProvider(reference<hash<string, hash<string, bool>>> providers,
            string symbol, string source) {
        providers{symbol}{source} = True;
    }

    private hash<auto> scanSourceSymbols(string input, hash<string, bool> true_defines) {
        int started = clock_getmicros_monotonic();
        string source = realpath(input);
        string text = ReadOnlyFile::readTextFile(input);
        int read_done = clock_getmicros_monotonic();
        string code = maskSource(text);
        int mask_done = clock_getmicros_monotonic();
        code = applyConditionals(code, true_defines);
        int condition_done = clock_getmicros_monotonic();
        list<string> classes = ();
        list<string> hashdecls = ();
        list<string> functions = ();
        list<string> globals = ();
        list<hash<auto>> ranges = namespaceRanges(code);
        classes = qualifiedCaptures(class_re, code, ranges);
        hashdecls = qualifiedCaptures(hashdecl_re, code, ranges);
        functions = qualifiedCaptures(sub_re, code, ranges);
        foreach hash<auto> info in (globalNames(code)) {
            push globals, qualify(namespaceAt(ranges, info.offset), info.name);
        }
        return (
            "source": source,
            "classes": classes,
            "hashdecls": hashdecls,
            "functions": functions,
            "globals": globals,
            "timing": (
                "read": read_done - started,
                "mask": mask_done - read_done,
                "condition": condition_done - mask_done,
                "extract": clock_getmicros_monotonic() - condition_done,
            ),
        );
    }

    private runScanWorker(Queue work, Queue results, hash<string, bool> true_defines) {
        SourceSymbolManifestGenerator scanner();
        while (True) {
            hash<auto> task = work.get();
            if (!exists task.input) {
                return;
            }
            try {
                results.push((
                    "index": task.index,
                    "result": scanner.scanSourceSymbols(task.input, true_defines),
                ));
            } catch (hash<ExceptionInfo> ex) {
                results.push(("error": ex));
            }
        }
    }

    private submitScanWorker(ThreadPool pool, Queue work, Queue results,
            hash<string, bool> true_defines) {
        pool.submit(sub() {
            runScanWorker(work, results, true_defines);
        });
    }

    private list<hash<auto>> scanSourceSymbolResults(list<string> inputs,
            hash<string, bool> true_defines) {
        list<hash<auto>> results_by_index = ();
        for (int index = 0; index < inputs.size(); ++index) {
            push results_by_index, {};
        }
        if (!inputs) {
            return results_by_index;
        }
        hash<string, int> timing = ("read": 0, "mask": 0, "condition": 0, "extract": 0);
        int thread_count = ENV.QORE_QO_SOURCE_ORDER_THREADS
            ? ENV.QORE_QO_SOURCE_ORDER_THREADS.toInt()
            : 4;
        thread_count = max(1, min(thread_count, inputs.size()));
        ThreadPool pool(max_threads: thread_count);
        Queue work();
        Queue results();
        for (int index = 0; index < inputs.size(); ++index) {
            work.push(("index": index, "input": inputs[index]));
        }
        for (int index = 0; index < thread_count; ++index) {
            work.push(("input": NOTHING));
            submitScanWorker(pool, work, results, true_defines);
        }
        pool.stopWait();
        for (int index = 0; index < inputs.size(); ++index) {
            hash<auto> envelope = results.get();
            if (envelope.error) {
                throw envelope.error.err, envelope.error.desc, envelope.error.arg;
            }
            hash<auto> result = envelope.result;
            foreach string stage in (timing.keys()) {
                timing{stage} += result.timing{stage};
            }
            results_by_index[envelope.index] = result;
        }
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) {
            stderr.printf("scan timing us: read=%d mask=%d condition=%d extract=%d\n",
                timing{"read"}, timing{"mask"}, timing{"condition"}, timing{"extract"});
        }
        return results_by_index;
    }

    private bool sourceSymbolResultValid(auto value) {
        if (value.typeCode() != NT_HASH) {
            return False;
        }
        hash<auto> result = value;
        if (!exists result.source || result.source.typeCode() != NT_STRING) {
            return False;
        }
        foreach string key in (("classes", "hashdecls", "functions", "globals")) {
            if (!exists result{key} || result{key}.typeCode() != NT_LIST) {
                return False;
            }
            foreach auto item in (result{key}) {
                if (item.typeCode() != NT_STRING) {
                    return False;
                }
            }
        }
        return True;
    }

    private string manifestFromResults(list<hash<auto>> results) {
        hash<string, hash<string, bool>> classes = {};
        hash<string, hash<string, bool>> hashdecls = {};
        hash<string, hash<string, bool>> functions = {};
        hash<string, hash<string, bool>> globals = {};
        foreach hash<auto> result in (results) {
            foreach string name in (result.classes) {
                addProvider(\classes, name, result.source);
            }
            foreach string name in (result.hashdecls) {
                addProvider(\hashdecls, name, result.source);
            }
            foreach string name in (result.functions) {
                addProvider(\functions, name, result.source);
            }
            foreach string name in (result.globals) {
                addProvider(\globals, name, result.source);
            }
        }
        list<string> lines = ("format=1",);
        foreach hash<auto> kind in (("name": "class", "providers": classes),
                ("name": "hashdecl", "providers": hashdecls),
                ("name": "function", "providers": functions),
                ("name": "global", "providers": globals)) {
            foreach string symbol in (sort(kind.providers.keys())) {
                list<string> sources = sort(kind.providers{symbol}.keys());
                if (sources.size() == 1) {
                    push lines, sprintf("%s\t%s\t%s", kind.name, symbol, sources[0]);
                }
            }
        }
        return join("\n", lines) + "\n";
    }

    private string fileDigest(string path) {
        return digest("sha256", ReadOnlyFile::readBinaryFile(path)).toHex();
    }

    private hash<auto> fileRecord(string path) {
        hash<StatInfo> info = hstat(path);
        return (
            "path": absoluteNormalized(path),
            "size": info.size,
            "sha256": fileDigest(path),
        );
    }

    private saveCache(string cache_path, list<string> inputs,
            hash<string, bool> true_defines, list<hash<auto>> records,
            list<hash<auto>> results) {
        hash<auto> data = (
            "version": SOURCE_SYMBOL_CACHE_VERSION,
            "inputs": inputs,
            "parse_defines": sort(true_defines.keys()),
            "input_records": records,
            "source_symbols": results,
        );
        mkdir(dirname(cache_path), 0777, True);
        string temporary = sprintf("%s.%d.tmp", cache_path, getpid());
        try {
            {
                File file();
                file.open2(temporary, O_CREAT | O_TRUNC | O_WRONLY, 0666, "UTF-8");
                file.write(make_json(data));
            }
            rename(temporary, cache_path);
        } catch (hash<ExceptionInfo> ex) {
            try { unlink(temporary); } catch (hash<ExceptionInfo> ignored) {}
        }
    }

    string generate(string context_path, list<string> inputs) {
        hash<string, bool> true_defines = contextDefines(context_path);
        return manifestFromResults(scanSourceSymbolResults(inputs, true_defines));
    }

    #! Generates a manifest while rescanning only sources changed since the cache.
    string generateCached(string context_path, list<string> inputs, string cache_path) {
        hash<string, bool> true_defines = contextDefines(context_path);
        list<hash<auto>> records = ();
        list<hash<auto>> results = ();
        bool cache_valid = False;
        *hash<StatInfo> cache_info = hstat(cache_path);
        try {
            if (exists cache_info) {
                auto raw = parse_json(ReadOnlyFile::readTextFile(cache_path));
                hash<auto> data = raw;
                *hash<StatInfo> context_info = hstat(context_path);
                if (data.version == SOURCE_SYMBOL_CACHE_VERSION
                        && data.inputs == inputs
                        && data.parse_defines == sort(true_defines.keys())
                        && data.input_records.typeCode() == NT_LIST
                        && data.input_records.size() == inputs.size()
                        && data.source_symbols.typeCode() == NT_LIST
                        && data.source_symbols.size() == inputs.size()
                        && exists context_info
                        && context_info.mtime < cache_info.mtime) {
                    cache_valid = True;
                    for (int index = 0; index < inputs.size(); ++index) {
                        auto raw_record = data.input_records[index];
                        auto raw_result = data.source_symbols[index];
                        if (raw_record.typeCode() != NT_HASH
                                || !sourceSymbolResultValid(raw_result)) {
                            cache_valid = False;
                            break;
                        }
                        hash<auto> record = raw_record;
                        hash<auto> result = raw_result;
                        if (record.path != absoluteNormalized(inputs[index])) {
                            cache_valid = False;
                            break;
                        }
                        push records, record;
                        push results, result;
                    }
                }
            }
        } catch (hash<ExceptionInfo> ignored) {
            cache_valid = False;
        }

        bool inspected = False;
        if (cache_valid) {
            for (int index = 0; index < inputs.size(); ++index) {
                *hash<StatInfo> info = hstat(inputs[index]);
                if (!exists info) {
                    cache_valid = False;
                    break;
                }
                if (records[index].size == info.size && info.mtime < cache_info.mtime) {
                    continue;
                }
                inspected = True;
                hash<auto> record = fileRecord(inputs[index]);
                if (record.size != records[index].size
                        || record.sha256 != records[index].sha256) {
                    results[index] = scanSourceSymbols(inputs[index], true_defines);
                }
                records[index] = record;
            }
        }
        if (!cache_valid) {
            results = scanSourceSymbolResults(inputs, true_defines);
            records = ();
            foreach string input in (inputs) {
                push records, fileRecord(input);
            }
            inspected = True;
        }
        if (inspected) {
            # Replacing the cache advances its observation time even when a
            # touched source retained identical content.
            saveCache(cache_path, inputs, true_defines, records, results);
        }
        return manifestFromResults(results);
    }
}

string sub absoluteNormalized(string path) {
    return absolute_path(path) ? path : getcwd() + DirSep + path;
}

string sub canonical(string path) {
    path = absoluteNormalized(path);
    if (exists hstat(path)) {
        return realpath(path);
    }
    string parent = dirname(path);
    return (is_dir(parent) ? realpath(parent) : parent) + DirSep + basename(path);
}

hash<SourceOrderContext> sub parseContext(string path) {
    list<string> inputs = ();
    list<string> source_content_digests = ();
    list<string> outputs = ();
    hash<string, bool> parse_defines = {};
    foreach string line in (ReadOnlyFile::readTextFile(path).split("\n")) {
        if (line.startsWith("input=")) {
            push inputs, line.substr(6);
        } else if (line.startsWith("source_content_digest=")) {
            push source_content_digests, line.substr(22);
        } else if (line.startsWith("output=")) {
            push outputs, line.substr(7);
        } else if (line.startsWith("parse_define=")) {
            string value = line.substr(13);
            int equals = value.find("=");
            string name = equals >= 0 ? value.substr(0, equals) : value;
            if (name) {
                parse_defines{name} = True;
            }
        }
    }
    if (inputs.size() != outputs.size()) {
        throw "SOURCE-ORDER-CONTEXT-ERROR", sprintf(
            "context has %d inputs but %d outputs: %s", inputs.size(), outputs.size(), path);
    }
    if (source_content_digests && source_content_digests.size() != inputs.size()) {
        throw "SOURCE-ORDER-CONTEXT-ERROR", sprintf(
            "context has %d inputs but %d source-content digests: %s",
            inputs.size(), source_content_digests.size(), path);
    }
    return new hash<SourceOrderContext>((
        "inputs": inputs,
        "source_content_digests": source_content_digests,
        "outputs": outputs,
        "parse_defines": parse_defines,
    ));
}

class SourceOrderEngine {
    private {
        Regex compile_contract_re = new Regex(
            "((?:\\\\[\\s\\S]|[^\\s])+\\.compile-contract\\.stamp)", RE_Global);
        #! Every content prerequisite a depfile names.
        /** The other half of what a compile records.  A reference that uses a
            declaration only as a TYPE leaves no compile contract -- qcc records a
            provider's contract only when the consumer folds its value or bakes its
            link-time hash -- but it does leave a content dependency here.  A parse
            resolving against shells needs those providers too, or the type it
            cannot see is deferred to a placeholder it then cannot construct.

            Two spellings reach this, and the difference is granularity, not kind.
            `.sha256` is the provider's source-content digest, which is what qcc
            records for a provider outside the build group -- or for any provider
            at all without `--depfile-declaration-contract-stamps`.
            `.qo.aggregate-contract.stamp` is the provider's DECLARATION contract,
            which that option records for a group member instead: a folded constant
            consumes the provider's declarations and nothing else, so watching its
            source bytes rebuilt every consumer for a comment.

            Neither may be spelled `.compile-contract.stamp`: that suffix is how
            collectDepfileContractEdges() recognises a REQUIRED edge, and reusing
            it here would promote every content reference to an ordering edge and
            collapse the component decomposition -- measured on one 875-source
            group as 820 components becoming 435, one of them with 441 members.
        */
        Regex source_content_re = new Regex(
            "((?:\\\\[\\s\\S]|[^\\s])+(?:\\.sha256|\\.aggregate-contract\\.stamp))",
            RE_Global);
        #! Every provider body contract a depfile names.
        /** Recorded only by a consumer that baked a provider's body-contract hash,
            which `--link-qo` validates and the declaration contract cannot describe.
            Kept apart from the other content prerequisites because it answers a
            different question -- what this consumer LINKS against, rather than what
            it compiled against -- and because the preload closure has no use for it:
            a body-baked provider is already reached over the compile-contract edge
            recorded for the same provider.
        */
        Regex body_contract_re = new Regex(
            "((?:\\\\[\\s\\S]|[^\\s])+\\.body-contract\\.stamp)", RE_Global);
        #! Every whitespace-separated make prerequisite, escapes included.
        /** Scanning depfiles a byte at a time from Qore made a whole-group
            currency pass the most expensive thing the build ran: 7.8 MB of
            depfiles in one 868-source group is 8 million loop iterations, and the
            pass reads every member's depfile.  The same shape as
            compile_contract_re, which has always scanned the same text at C
            speed.
        */
        Regex depfile_input_re = new Regex(
            "((?:\\\\[\\s\\S]|[^\\s])+)", RE_Global);
        hash<string, string> contract_digests = {};
        #! Body-contract digests by provider member output, computed once per process.
        hash<string, string> body_contract_digests = {};
        #! A provider's body-contract rows by symbol, parsed once per process; see bodyContractRows().
        hash<string, hash<string, list<string>>> body_contract_rows = {};
        #! Providers whose body-contract stamp could not be read as rows; see bodyContractRows().
        hash<string, bool> body_contract_unparsed = {};
        #! Canonical forms of depfile paths, resolved once per process.
        hash<string, string> canonical_paths = {};
        #! Group members by object basename, indexed once per process.
        /** contentDependencyOutputs() maps a `.sha256` prerequisite back to the member
            whose object shares its mangled stem, and the preload-set closure calls it once
            per round.  Rebuilding the index over every output on each call would walk the
            whole group several times for a set that never changes.
        */
        *hash<string, string> outputs_by_stem;
        #! Group members by canonical source path, indexed once per process; see loadRequirementOutputs().
        *hash<string, string> outputs_by_source;
        #! Depfile prerequisites by depfile path, parsed once per process.
        hash<string, list<string>> depfile_inputs = {};
        #! Build inputs from outside the group by member output, filtered once.
        hash<string, list<string>> external_inputs = {};
        #! Modification times of paths outside the group, stat'ed once.
        /** One 868-source group names 116k dependency references that resolve to
            1.9k distinct paths, and currency compares each against every member
            stamp: without this the pass makes sixty times the stat calls it
            needs.
        */
        hash<string, date> external_times = {};
        #! Paths outside the group that do not exist; a missing input is not current.
        hash<string, bool> external_absent = {};
        #! What each component publishes to its consumers, by component key.
        hash<string, list<hash<auto>>> component_provides = {};
        #! Member source-content digests by member output, read once per process.
        hash<string, string> content_digests = {};
        *string loaded_graph_context;
        *hash<SourceOrderGraph> loaded_graph;
        #! The depfile-derived required edges the loaded graph was built from.
        /** The summary half of the graph is a function of source content, which
            every token already covers.  The depfile half is not: the build
            writes it, so it is the one part of the graph that can transition
            while a component is being compiled.  Keeping it lets a publication
            state which graph it was planned against.
        */
        *list<list<int>> depfile_contract_edges;
        #! True when those edges were read from a frozen snapshot, not the depfiles.
        bool depfile_edges_frozen = False;
        #! The name of that edge set, computed on first use.
        /** Most commands -- currency probes above all, which a large group runs
            once per object -- never need it, and naming the set costs a digest
            over every edge.  Deriving it lazily keeps that off the hot path.
        */
        *string depfile_edge_generation;
    }

    private list<hash<string, bool>> emptyGraph(int count) {
        list<hash<string, bool>> graph = ();
        for (int index = 0; index < count; ++index) {
            push graph, {};
        }
        return graph;
    }

    private addEdge(reference<list<hash<string, bool>>> outgoing,
            reference<list<hash<string, bool>>> incoming,
            reference<list<hash<string, bool>>> required, int provider, int consumer,
            bool is_required = False) {
        if (provider == consumer) {
            return;
        }
        string consumer_key = string(consumer);
        string provider_key = string(provider);
        if (!exists outgoing[provider]{consumer_key}) {
            outgoing[provider]{consumer_key} = True;
            incoming[consumer]{provider_key} = True;
        }
        if (is_required) {
            required[provider]{consumer_key} = True;
        }
    }

    private addProvider(reference<hash<string, list<int>>> providers, string symbol,
            int source) {
        if (!exists providers{symbol}) {
            providers{symbol} = ();
        } else {
            foreach int existing in (providers{symbol}) {
                if (existing == source) {
                    return;
                }
            }
        }
        push providers{symbol}, source;
    }

    private hash<string, bool> stringSet(list<string> values) {
        hash<string, bool> result = {};
        foreach string value in (values) {
            result{value} = True;
        }
        return result;
    }

    #! The one source declaring each symbol among the given provider kinds.
    /** A symbol two sources declare -- as the same kind or as two of the given kinds -- has
        no entry: which one a mention names cannot be told from the summaries.  Other kinds
        are not consulted: a mention that can only name a class is not ambiguous because some
        source declares a constant of the same name.
    */
    private hash<string, int> uniqueKindProviders(hash<string, list<int>> providers,
            *hash<string, list<int>> other_providers) {
        hash<string, int> result = {};
        hash<string, bool> symbols = stringSet(keys providers);
        if (other_providers) {
            symbols += stringSet(keys other_providers);
        }
        foreach string symbol in (keys symbols) {
            hash<string, bool> sources = {};
            foreach int source in (providers{symbol} ?? ()) {
                sources{string(source)} = True;
            }
            foreach int source in (other_providers{symbol} ?? ()) {
                sources{string(source)} = True;
            }
            if (sources.size() == 1) {
                result{symbol} = (keys sources)[0].toInt();
            }
        }
        return result;
    }

    #! Adds an edge from the unique provider of each mentioned symbol to \a consumer.
    /** A consumer that declares the symbol itself has no edge to add: its unique provider is
        itself, and addEdge() does not add a self edge.
    */
    private addKindEdges(reference<list<hash<string, bool>>> outgoing,
            reference<list<hash<string, bool>>> incoming,
            reference<list<hash<string, bool>>> required, int consumer, *list<string> mentions,
            hash<string, int> unique, bool is_required = False) {
        foreach string symbol in (mentions) {
            *int provider = unique{symbol};
            if (exists provider) {
                addEdge(\outgoing, \incoming, \required, provider, consumer, is_required);
            }
        }
    }

    private hash<SourceOrderGraph> buildGraphFromSummaries(list<string> inputs,
            list<hash<string, list<string>>> summaries) {
        int count = inputs.size();
        list<hash<string, bool>> provides_by_source = ();
        hash<string, list<int>> provider_sources = {};
        hash<string, list<int>> class_provider_sources = {};
        hash<string, list<int>> enum_provider_sources = {};
        hash<string, list<int>> hashdecl_provider_sources = {};
        hash<string, list<int>> function_provider_sources = {};
        hash<string, list<int>> parse_define_provider_sources = {};

        for (int index = 0; index < count; ++index) {
            hash<string, list<string>> summary = summaries[index];
            hash<string, bool> provides = stringSet(summary.provides);
            push provides_by_source, provides;
            foreach string symbol in (summary.provides) {
                addProvider(\provider_sources, symbol, index);
            }
            foreach string symbol in (summary.classes) {
                addProvider(\class_provider_sources, symbol, index);
            }
            foreach string symbol in (summary.enums) {
                addProvider(\enum_provider_sources, symbol, index);
            }
            foreach string symbol in (summary.hashdecls) {
                addProvider(\hashdecl_provider_sources, symbol, index);
            }
            foreach string symbol in (summary.functions) {
                addProvider(\function_provider_sources, symbol, index);
            }
            foreach string symbol in (summary.parse_defines) {
                addProvider(\parse_define_provider_sources, symbol, index);
            }
        }

        hash<string, int> unique_provider = {};
        foreach string symbol in (provider_sources.keys()) {
            if (provider_sources{symbol}.size() == 1) {
                unique_provider{symbol} = provider_sources{symbol}[0];
            }
        }
        hash<string, bool> provider_symbols = stringSet(unique_provider.keys());
        # A mention that can only name one KIND of declaration resolves among the sources declaring that kind.
        # Requiring the name to be unique across every kind let an unrelated declaration hide the provider: a
        # class constant `QorusDataTypeCatalogue::Map` made `class OmqMap inherits Map` record no edge to the
        # source declaring `OMQ::Map`, so the preload closure of every consumer of OmqMap left its base out and
        # the compile failed with "cannot resolve base class '::OMQ::Map' for class 'OmqMap'".
        hash<string, int> unique_classes = uniqueKindProviders(class_provider_sources);
        hash<string, int> unique_enums = uniqueKindProviders(enum_provider_sources);
        hash<string, int> unique_hashdecls = uniqueKindProviders(hashdecl_provider_sources);
        hash<string, int> unique_functions = uniqueKindProviders(function_provider_sources);
        # a type name can be a class or a hashdecl, and only one source may declare either
        hash<string, int> unique_class_or_hashdecl = uniqueKindProviders(class_provider_sources,
            hashdecl_provider_sources);
        hash<string, int> unique_parse_defines = {};
        foreach string symbol in (parse_define_provider_sources.keys()) {
            if (parse_define_provider_sources{symbol}.size() == 1) {
                unique_parse_defines{symbol} = parse_define_provider_sources{symbol}[0];
            }
        }

        hash<string, list<int>> basename_sources = {};
        for (int index = 0; index < count; ++index) {
            addProvider(\basename_sources, basename(inputs[index]), index);
        }
        hash<string, int> unique_basenames = {};
        foreach string name in (basename_sources.keys()) {
            if (basename_sources{name}.size() == 1) {
                unique_basenames{name} = basename_sources{name}[0];
            }
        }

        list<hash<string, bool>> outgoing = emptyGraph(count);
        list<hash<string, bool>> incoming = emptyGraph(count);
        list<hash<string, bool>> required = emptyGraph(count);
        for (int consumer = 0; consumer < count; ++consumer) {
            hash<string, list<string>> summary = summaries[consumer];
            hash<string, bool> local_provides = provides_by_source[consumer];

            addKindEdges(\outgoing, \incoming, \required, consumer, summary.inheritance_mentions,
                unique_classes, True);
            foreach string symbol in (summary.hard_mentions) {
                if (!exists provider_symbols{symbol} || exists local_provides{symbol}) {
                    continue;
                }
                addEdge(\outgoing, \incoming, \required,
                    unique_provider{symbol}, consumer, True);
            }

            addKindEdges(\outgoing, \incoming, \required, consumer, summary.decl_type_mentions,
                unique_class_or_hashdecl);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.hash_type_mentions,
                unique_hashdecls);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.enum_type_mentions,
                unique_enums, True);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.call_ref_functions,
                unique_functions, True);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.call_ref_classes,
                unique_classes);
            addKindEdges(\outgoing, \incoming, \required, consumer,
                summary.constructed_decl_type_mentions, unique_class_or_hashdecl);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.new_hash_type_mentions,
                unique_hashdecls);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.new_object_mentions,
                unique_classes);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.class_for_name_mentions,
                unique_classes);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.create_object_mentions,
                unique_classes);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.static_call_mentions,
                unique_classes);
            addKindEdges(\outgoing, \incoming, \required, consumer,
                summary.param_default_static_call_mentions, unique_classes, True);
            # `Scope::name` names a class's static member or an enum's member
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.static_ref_mentions,
                unique_classes);
            addKindEdges(\outgoing, \incoming, \required, consumer, summary.static_ref_mentions,
                unique_enums, True);

            foreach string included in (summary.includes) {
                string name = basename(included);
                if (exists unique_basenames{name} && unique_basenames{name} != consumer) {
                    addEdge(\outgoing, \incoming, \required,
                        unique_basenames{name}, consumer, True);
                }
            }
            foreach string symbol in (summary.parse_define_consumers) {
                if (exists unique_parse_defines{symbol}
                        && unique_parse_defines{symbol} != consumer) {
                    addEdge(\outgoing, \incoming, \required,
                        unique_parse_defines{symbol}, consumer, True);
                }
            }
        }
        return new hash<SourceOrderGraph>((
            "outgoing": outgoing,
            "incoming": incoming,
            "required": required,
            "summaries": summaries,
        ));
    }

    private runSummaryWorker(Queue work, Queue results,
            hash<string, bool> true_defines) {
        SourceSymbolManifestGenerator scanner();
        while (True) {
            hash<auto> task = work.get();
            if (!exists task.source) {
                return;
            }
            try {
                results.push((
                    "index": task.index,
                    "summary": scanner.scanDependencySummary(task.source, true_defines),
                ));
            } catch (hash<ExceptionInfo> ex) {
                results.push(("error": ex));
            }
        }
    }

    private submitSummaryWorker(ThreadPool pool, Queue work, Queue results,
            hash<string, bool> true_defines) {
        pool.submit(sub() {
            runSummaryWorker(work, results, true_defines);
        });
    }

    private list<hash<string, list<string>>> scanSummaries(list<string> inputs,
            hash<string, bool> true_defines) {
        list<hash<string, list<string>>> summaries = ();
        for (int index = 0; index < inputs.size(); ++index) {
            push summaries, {};
        }
        if (!inputs) {
            return summaries;
        }
        int thread_count = ENV.QORE_QO_SOURCE_ORDER_THREADS
            ? ENV.QORE_QO_SOURCE_ORDER_THREADS.toInt()
            : 4;
        thread_count = max(1, min(thread_count, inputs.size()));
        ThreadPool pool(max_threads: thread_count);
        Queue work();
        Queue results();
        for (int index = 0; index < inputs.size(); ++index) {
            work.push(("index": index, "source": inputs[index]));
        }
        for (int index = 0; index < thread_count; ++index) {
            work.push(("source": NOTHING));
            submitSummaryWorker(pool, work, results, true_defines);
        }
        pool.stopWait();
        for (int index = 0; index < inputs.size(); ++index) {
            hash<auto> envelope = results.get();
            if (exists envelope.error) {
                throw envelope.error.err, envelope.error.desc, envelope.error.arg;
            }
            summaries[envelope.index] = envelope.summary;
        }
        return summaries;
    }

    private bool sourceSummaryValid(auto value) {
        if (value.typeCode() != NT_HASH) {
            return False;
        }
        hash<auto> summary = value;
        foreach string key in (SOURCE_SUMMARY_KEYS) {
            if (!exists summary{key} || summary{key}.typeCode() != NT_LIST) {
                return False;
            }
            foreach auto item in (summary{key}) {
                if (item.typeCode() != NT_STRING) {
                    return False;
                }
            }
        }
        return True;
    }

    private hash<string, list<string>> typedSummary(hash<auto> summary) {
        hash<string, list<string>> result = {};
        foreach string key in (SOURCE_SUMMARY_KEYS) {
            result{key} = summary{key};
        }
        return result;
    }

    private list<list<int>> graphToLists(list<hash<string, bool>> graph) {
        list<list<int>> result = ();
        foreach hash<string, bool> edges in (graph) {
            list<int> values = ();
            foreach string value in (edges.keys()) {
                push values, value.toInt();
            }
            push result, sort(values);
        }
        return result;
    }

    private list<hash<string, bool>> listsToGraph(list<auto> values, int count) {
        list<hash<string, bool>> graph = emptyGraph(count);
        for (int provider = 0; provider < count; ++provider) {
            foreach int consumer in (values[provider]) {
                graph[provider]{string(consumer)} = True;
            }
        }
        return graph;
    }

    private string fileDigest(string path) {
        return digest("sha256", ReadOnlyFile::readBinaryFile(path)).toHex();
    }

    private hash<auto> fileRecord(string path) {
        hash<StatInfo> info = hstat(path);
        return (
            "path": absoluteNormalized(path),
            "size": info.size,
            "sha256": fileDigest(path),
        );
    }

    private list<hash<auto>> fileRecords(list<string> paths) {
        list<hash<auto>> records = ();
        foreach string path in (paths) {
            push records, fileRecord(path);
        }
        return records;
    }

    private saveGraphCache(string cache_file, list<string> inputs, list<string> outputs,
            hash<string, bool> true_defines, hash<SourceOrderGraph> graph,
            *list<hash<auto>> input_records = NOTHING) {
        hash<auto> data = (
            "version": CACHE_VERSION,
            "inputs": inputs,
            "outputs": outputs,
            "parse_defines": sort(true_defines.keys()),
            "input_records": input_records ?? fileRecords(inputs),
            "source_summaries": graph.summaries,
            "outgoing": graphToLists(graph.outgoing),
            "incoming": graphToLists(graph.incoming),
            "required": graphToLists(graph.required),
        );
        string temporary = sprintf("%s.%d.tmp", cache_file, getpid());
        try {
            {
                File file();
                file.open2(temporary, O_CREAT | O_TRUNC | O_WRONLY, 0666, "UTF-8");
                file.write(make_json(data));
            }
            rename(temporary, cache_file);
        } catch (hash<ExceptionInfo> ex) {
            try {
                if (exists hlstat(temporary)) {
                    unlink(temporary);
                }
            } catch (hash<ExceptionInfo> ignored) {
            }
        }
    }

    private *hash<SourceOrderGraph> loadGraphCache(string cache_file, string context_path,
            list<string> inputs, list<string> outputs,
            hash<string, bool> true_defines) {
        try {
            int started = clock_getmicros_monotonic();
            *hash<StatInfo> cache_info = hstat(cache_file);
            if (!exists cache_info) {
                return NOTHING;
            }
            string cache_text = ReadOnlyFile::readTextFile(cache_file);
            int read_done = clock_getmicros_monotonic();
            auto raw_data = parse_json(cache_text);
            int parse_done = clock_getmicros_monotonic();
            if (raw_data.typeCode() != NT_HASH) {
                return NOTHING;
            }
            hash<auto> data = raw_data;
            if (data.version != CACHE_VERSION || data.inputs != inputs
                    || data.outputs != outputs
                    || data.parse_defines != sort(true_defines.keys())) {
                return NOTHING;
            }
            foreach string key in (("outgoing", "incoming", "required",
                    "input_records", "source_summaries")) {
                if (!exists data{key} || data{key}.typeCode() != NT_LIST
                        || data{key}.size() != inputs.size()) {
                    return NOTHING;
                }
            }
            *hash<StatInfo> context_info = hstat(context_path);
            if (!exists context_info || context_info.mtime >= cache_info.mtime) {
                return NOTHING;
            }

            list<int> inspect = ();
            for (int index = 0; index < inputs.size(); ++index) {
                auto raw_record = data.input_records[index];
                if (raw_record.typeCode() != NT_HASH) {
                    return NOTHING;
                }
                hash<auto> old_record = raw_record;
                *hash<StatInfo> info = hstat(inputs[index]);
                if (!exists info || old_record.path != absoluteNormalized(inputs[index])) {
                    return NOTHING;
                }
                if (old_record.size != info.size || info.mtime >= cache_info.mtime) {
                    push inspect, index;
                }
            }
            int stat_done = clock_getmicros_monotonic();

            hash<SourceOrderGraph> graph = new hash<SourceOrderGraph>((
                "outgoing": listsToGraph(data.outgoing, inputs.size()),
                "incoming": listsToGraph(data.incoming, inputs.size()),
                "required": listsToGraph(data.required, inputs.size()),
                "summaries": (),
            ));
            if (ENV.QORE_QO_SOURCE_ORDER_TIMING) {
                int graph_done = clock_getmicros_monotonic();
                stderr.printf("cache read=%d us parse=%d us validate+stat=%d us graph=%d us\n",
                    read_done - started, parse_done - read_done, stat_done - parse_done,
                    graph_done - stat_done);
            }
            if (!inspect) {
                return graph;
            }

            list<hash<string, list<string>>> summaries = ();
            foreach auto raw_summary in (data.source_summaries) {
                if (!sourceSummaryValid(raw_summary)) {
                    return NOTHING;
                }
                hash<auto> summary = raw_summary;
                push summaries, typedSummary(summary);
            }
            graph.summaries = summaries;
            list<hash<auto>> records = ();
            foreach hash<auto> record in (data.input_records) {
                push records, record;
            }
            bool graph_changed = False;
            SourceSymbolManifestGenerator scanner();
            foreach int index in (inspect) {
                hash<auto> record = fileRecord(inputs[index]);
                hash<auto> old_record = data.input_records[index];
                if (record.size != old_record.size || record.sha256 != old_record.sha256) {
                    hash<string, list<string>> summary =
                        scanner.scanDependencySummary(inputs[index], true_defines);
                    if (summary != summaries[index]) {
                        summaries[index] = summary;
                        graph_changed = True;
                    }
                }
                records[index] = record;
            }
            if (graph_changed) {
                graph = buildGraphFromSummaries(inputs, summaries);
            }
            saveGraphCache(cache_file, inputs, outputs, true_defines, graph, records);
            return graph;
        } catch (hash<ExceptionInfo> ex) {
            return NOTHING;
        }
    }

    #! Every prerequisite a make depfile records, unescaped, parsed once per process.
    /** A whole-group currency pass asks for the same depfile once per member of
        the component that names it, and several passes can run in one helper
        invocation, so the parse is memoized on the depfile path.  Nothing in one
        invocation rewrites a depfile it also reads: freezing and compiling are
        separate processes by construction.
    */
    private list<string> parseMakeDepfileInputs(string path) {
        *list<string> cached = depfile_inputs{path};
        if (exists cached) {
            return cached;
        }
        list<string> values = ();
        string text = ReadOnlyFile::readTextFile(path);
        int colon = text.find(":");
        if (colon < 0) {
            depfile_inputs{path} = values;
            return values;
        }
        foreach *string value in (depfile_input_re.extractGroups(
                text.substr(colon + 1)) ?? ()) {
            if (!exists value) {
                continue;
            }
            if (value.find("\\") >= 0) {
                value = regex_subst(value, "\\\\([\\s\\S])",
                    string sub (hash<RegexMatchInfo> match) {
                        return match.groups[0] == "\n" ? "" : match.groups[0];
                    }, RE_Global);
            }
            if (value == "") {
                continue;
            }
            push values, value;
        }
        depfile_inputs{path} = values;
        return values;
    }

    #! The modification time of a build input outside the group, or NOTHING.
    /** Memoized: the same toolchain, module and include paths appear in every
        member's depfile, and currency compares each of them against every member
        stamp.
    */
    private *date externalInputTime(string path) {
        if (external_absent{path}) {
            return NOTHING;
        }
        *date cached = external_times{path};
        if (exists cached) {
            return cached;
        }
        *hash<StatInfo> info = hstat(path);
        if (!exists info) {
            external_absent{path} = True;
            return NOTHING;
        }
        external_times{path} = info.mtime;
        return info.mtime;
    }

    #! The group members whose content \a outputs were compiled against.
    /** Maps each content prerequisite back to the member it names: a
        `<mangled source>.sha256` digest sidecar by its mangled stem, and a
        `<member object>.aggregate-contract.stamp` declaration contract by the
        member object it is a sidecar of.  Entries naming files outside the group
        (the toolchain, loaded modules, stubs) are skipped rather than guessed at.
    */
    list<string> contentDependencyOutputs(hash<SourceOrderContext> context_info,
            softlist<string> outputs) {
        if (!exists outputs_by_stem) {
            hash<string, string> index = {};
            foreach string output in (context_info.outputs) {
                index{basename(output)} = output;
            }
            outputs_by_stem = index;
        }
        hash<string, string> by_stem = outputs_by_stem;
        hash<string, bool> seen = {};
        list<string> rv = ();
        foreach string output in (outputs) {
            string depfile = output + ".d";
            if (!is_file(depfile)) {
                continue;
            }
            foreach string dependency in (parseMakeDepfileContentInputs(depfile)) {
                string stem = basename(dependency);
                if (stem.endsWith(DeclarationContractSuffix)) {
                    stem = stem.substr(0,
                        stem.size() - DeclarationContractSuffix.size());
                } else {
                    stem = stem.substr(0, stem.size() - 7) + ".qo";
                }
                *string member = by_stem{stem};
                if (!exists member || seen{member}) {
                    continue;
                }
                seen{member} = True;
                push rv, member;
            }
        }
        return rv;
    }

    #! The group members whose declarations the code in \a outputs needs wherever it is loaded.
    /** Read from each object's load-requires sidecar, which names provider SOURCES; a source
        outside the group, or one the sidecar spells in a form no member matches, is skipped.
        An object without the sidecar -- compiled by a qcc that did not write it, or requiring
        nothing -- contributes nothing, which is what the closure saw before it existed.
    */
    list<string> loadRequirementOutputs(hash<SourceOrderContext> context_info,
            softlist<string> outputs) {
        if (!exists outputs_by_source) {
            hash<string, string> index = {};
            for (int i = 0; i < context_info.inputs.size(); ++i) {
                index{canonicalCached(context_info.inputs[i])} = context_info.outputs[i];
            }
            outputs_by_source = index;
        }
        hash<string, string> by_source = outputs_by_source;
        hash<string, bool> seen = {};
        list<string> rv = ();
        foreach string output in (outputs) {
            string path = output + LoadRequiresSuffix;
            if (!is_file(path)) {
                continue;
            }
            *list<list<string>> rows = parseLengthPrefixedRows(path);
            foreach list<string> row in (rows) {
                if (row[0] != "require" || row.size() != 2) {
                    continue;
                }
                *string member = by_source{canonicalCached(row[1])};
                if (!exists member || member == output || seen{member}) {
                    continue;
                }
                seen{member} = True;
                push rv, member;
            }
        }
        return rv;
    }

    private list<string> parseMakeDepfileContentInputs(string path) {
        return parseMakeDepfileMatches(path, source_content_re);
    }

    private list<string> parseMakeDepfileContractInputs(string path) {
        return parseMakeDepfileMatches(path, compile_contract_re);
    }

    private list<string> parseMakeDepfileBodyContractInputs(string path) {
        return parseMakeDepfileMatches(path, body_contract_re);
    }

    #! The provider members whose BODY contracts \a output was linked against.
    /** Empty for all but the consumers that baked one, which is what makes carrying
        these in the generation token affordable.
    */
    list<string> bodyContractDependencyOutputs(string output) {
        string depfile = output + ".d";
        if (!is_file(depfile)) {
            return ();
        }
        hash<string, bool> seen = {};
        list<string> rv = ();
        foreach string dependency in (parseMakeDepfileBodyContractInputs(depfile)) {
            string member = dependency.substr(0,
                dependency.size() - BodyContractSuffix.size());
            if (seen{member}) {
                continue;
            }
            seen{member} = True;
            push rv, member;
        }
        return sort(rv);
    }

    #! The body-contract rows \a output baked, as provider member output -> symbols.
    /** NOTHING when the member has no readable record of them: an object compiled before
        qcc recorded its rows, or one whose record is not in the format this reads.  The
        caller then watches the whole provider stamp, which is what every consumer did
        before the rows were recorded -- so a tree built by an older qcc keeps its
        publications rather than rebuilding every consumer of a body contract at once.
    */
    private *hash<string, hash<string, bool>> bodyContractImports(string output) {
        string path = output + BodyContractImportsSuffix;
        if (!is_file(path)) {
            return;
        }
        *list<list<string>> rows = parseLengthPrefixedRows(path);
        if (!exists rows) {
            return;
        }
        hash<string, hash<string, bool>> rv = {};
        foreach list<string> row in (rows) {
            if (row[0] != "import" || row.size() != 3 || row[1].size() <= BodyContractSuffix.size()
                    || row[1].substr(-BodyContractSuffix.size()) != BodyContractSuffix) {
                return;
            }
            string provider = absoluteNormalized(row[1].substr(0, row[1].size() - BodyContractSuffix.size()));
            rv{provider}{row[2]} = True;
        }
        return rv;
    }

    #! Splits a length-prefixed contract file into rows, each the row kind followed by its fields.
    /** The format qcc writes contracts and their sidecars in: a `format=N` header line,
        then one row per line, `<kind>\t<n>:<field><n>:<field>...`, where n is the field's
        length in BYTES -- a field can hold any byte, a newline included.  The file is read
        as ISO-8859-1, one character per byte, so those lengths are this string's offsets.

        @return NOTHING if the file is not in that shape
    */
    private static *list<list<string>> parseLengthPrefixedRows(string path) {
        string text = ReadOnlyFile::readTextFile(path, "ISO-8859-1");
        int pos = text.find("\n");
        if (pos < 0 || text.substr(0, 7) != "format=") {
            return;
        }
        ++pos;
        int len = text.size();
        list<list<string>> rows = ();
        while (pos < len) {
            int tab = text.find("\t", pos);
            if (tab < 0) {
                return;
            }
            list<string> row = (text.substr(pos, tab - pos),);
            pos = tab + 1;
            while (pos < len && text[pos] != "\n") {
                int colon = text.find(":", pos);
                if (colon <= pos) {
                    return;
                }
                string digits = text.substr(pos, colon - pos);
                if (digits !~ /^[0-9]+$/) {
                    return;
                }
                int field_len = digits.toInt();
                if (colon + 1 + field_len > len) {
                    return;
                }
                push row, text.substr(colon + 1, field_len);
                pos = colon + 1 + field_len;
            }
            if (pos >= len) {
                return;
            }
            # the row's newline
            ++pos;
            push rows, row;
        }
        return rows;
    }

    #! A provider's body-contract rows, each re-serialized, by the symbol it describes.
    /** Both row kinds are kept for a symbol: `body` is the Qore path's hash and `native-body`
        a fast entry's, and `--link-qo` validates either.  NOTHING when the stamp is missing
        or not in the length-prefixed shape.
    */
    private *hash<string, list<string>> bodyContractRows(string output) {
        *hash<string, list<string>> cached = body_contract_rows{output};
        if (exists cached || body_contract_unparsed{output}) {
            return cached;
        }
        string path = output + BodyContractSuffix;
        *list<list<string>> rows = is_file(path) ? parseLengthPrefixedRows(path) : NOTHING;
        if (!exists rows) {
            body_contract_unparsed{output} = True;
            return;
        }
        hash<string, list<string>> rv = {};
        foreach list<string> row in (rows) {
            if (row.size() < 2) {
                body_contract_unparsed{output} = True;
                return;
            }
            string serialized = row[0] + "\t" + foldl $1 + $2, (map sprintf("%d:%s", $1.size(), $1), row[1..]);
            if (!rv{row[1]}) {
                rv{row[1]} = ();
            }
            push rv{row[1]}, serialized;
        }
        body_contract_rows{output} = rv;
        return rv;
    }

    #! The part of one provider's body contract that \a symbols were linked against.
    /** A symbol the provider no longer publishes a body contract for contributes a marker
        rather than nothing, so its disappearance moves the digest: `--link-qo` fails an
        import it can no longer match as surely as one whose hash moved.  Falls back to the
        whole stamp when the stamp cannot be read as rows.
    */
    private string memberBodyContractRowsDigest(string output, hash<string, bool> symbols) {
        *hash<string, list<string>> rows = bodyContractRows(output);
        if (!exists rows) {
            return memberBodyContractDigest(output);
        }
        list<string> parts = ();
        foreach string symbol in (sort(keys symbols)) {
            *list<string> symbol_rows = rows{symbol};
            if (symbol_rows) {
                parts += sort(symbol_rows);
            } else {
                push parts, sprintf("missing\t%d:%s", symbol.size(), symbol);
            }
        }
        return "rows:" + digest("sha256", binary(join("\n", parts))).toHex();
    }

    #! The body contract one provider member publishes, digested once per process.
    private string memberBodyContractDigest(string output) {
        *string cached = body_contract_digests{output};
        if (exists cached) {
            return cached;
        }
        string path = output + BodyContractSuffix;
        string result = is_file(path)
            ? digest("sha256", ReadOnlyFile::readBinaryFile(path)).toHex()
            : "";
        body_contract_digests{output} = result;
        return result;
    }

    private list<string> parseMakeDepfileMatches(string path, Regex re) {
        list<string> values = ();
        string text = ReadOnlyFile::readTextFile(path);
        foreach *string value in (re.extractGroups(text) ?? ()) {
            if (!exists value) {
                continue;
            }
            if (value.find("\\") >= 0) {
                value = regex_subst(value, "\\\\([\\s\\S])",
                    string sub (hash<RegexMatchInfo> match) {
                        return match.groups[0] == "\n" ? "" : match.groups[0];
                    }, RE_Global);
            }
            push values, value;
        }
        return values;
    }

    #! The required edges the group's current depfiles record, as node pairs.
    /** Each pair is \c (provider, consumer): qcc records the compile contract of
        every provider a source was actually compiled against, so a consumer's
        depfile names its providers.  These edges are the part of the graph the
        build writes, which is why they are collected separately from the
        content-derived summary edges rather than folded straight into it.

        \a consumers limits the scan to the depfiles of those nodes, keyed by node
        index; every member depfile is read when it is not given.
    */
    private list<list<int>> collectDepfileContractEdges(list<string> outputs,
            *hash<string, bool> consumers) {
        const string Suffix = ".compile-contract.stamp";
        hash<string, int> output_indexes = {};
        for (int index = 0; index < outputs.size(); ++index) {
            output_indexes{outputs[index]} = index;
            output_indexes{absoluteNormalized(outputs[index])} = index;
        }
        *hash<string, int> canonical_output_indexes;
        list<list<int>> edges = ();
        for (int consumer = 0; consumer < outputs.size(); ++consumer) {
            if (exists consumers && !exists consumers{string(consumer)}) {
                continue;
            }
            string depfile = outputs[consumer] + ".d";
            if (!is_file(depfile)) {
                continue;
            }
            foreach string dependency in (parseMakeDepfileContractInputs(depfile)) {
                string provider_output = dependency.substr(0,
                    dependency.size() - Suffix.size());
                *int provider = output_indexes{provider_output};
                if (!exists provider) {
                    provider = output_indexes{absoluteNormalized(provider_output)};
                }
                if (!exists provider) {
                    if (!exists canonical_output_indexes) {
                        canonical_output_indexes = {};
                        for (int index = 0; index < outputs.size(); ++index) {
                            canonical_output_indexes{canonical(outputs[index])} = index;
                        }
                    }
                    provider = canonical_output_indexes{canonical(provider_output)};
                }
                if (!exists provider) {
                    continue;
                }
                if (provider != consumer) {
                    push edges, (provider, consumer);
                }
            }
        }
        return edges;
    }

    private applyContractEdges(list<list<int>> edges,
            reference<hash<SourceOrderGraph>> graph) {
        foreach list<int> edge in (edges) {
            addEdge(\graph.outgoing, \graph.incoming, \graph.required,
                edge[0], edge[1], True);
        }
    }

    #! Names one depfile-derived edge set by content rather than by node numbering.
    /** Like a component key, this has to survive a context whose source list was
        reordered, so the edges are named by the output paths they connect and
        not by the node indexes CMake happened to emit.
    */
    private string contractEdgeGeneration(list<list<int>> edges,
            list<string> outputs) {
        list<string> normalized = ();
        foreach string output in (outputs) {
            push normalized, absoluteNormalized(output);
        }
        list<string> lines = ();
        foreach list<int> edge in (edges) {
            push lines, normalized[edge[0]] + "\t" + normalized[edge[1]];
        }
        return "graph-" + digest("sha256",
            join("\n", sort(lines)) + "\n").toHex().substr(0, 16);
    }

    #! Names the context's output list, so a snapshot cannot outlive its context.
    private string outputsDigest(list<string> outputs) {
        list<string> normalized = ();
        foreach string output in (outputs) {
            push normalized, absoluteNormalized(output);
        }
        return digest("sha256", join("\n", normalized) + "\n").toHex();
    }

    #! Names the group's last whole-group publication, or NOTHING without a stamp.
    /** A shared parse is the only operation that rewrites every depfile in the
        group at once, so the moment it published is the marker that says which
        whole-group edge set a snapshot was frozen from.

        That marker is the publication sidecar beside the batch stamp, never the
        batch stamp itself.  The stamp is also the build tool's ordering token, so
        it is touched by runs that publish nothing: CMake's Makefile generator
        duplicates the bootstrap recipe into every independent target that depends
        on the stamp, and the copy that loses the race to the group lock finds the
        tree the winner published current and touches the stamp so the members do
        not stay older than their dependencies.  That touch can land after the
        coordinator's final freeze, which would leave a snapshot naming a
        publication the group no longer reports -- and every later build would
        discard an edge set that is still exact.

        A batch stamp with no publication sidecar names generation 0: the group
        has published nothing this helper can date, so any snapshot carrying a
        dated generation is discarded rather than trusted.
    */
    private *int batchStampGeneration(*string batch_stamp) {
        if (!batch_stamp) {
            return NOTHING;
        }
        *hash<StatInfo> info = hstat(batch_stamp + BATCH_PUBLICATION_SUFFIX);
        if (!exists info) {
            return 0;
        }
        return get_duration_microseconds(info.mtime - 1970-01-01Z);
    }

    #! Freezes the current depfile-derived edge set as one named generation.
    /** This is the transition point the build schedules against.  Every helper
        invocation that runs while part of a group is compiling reads this file
        instead of the live depfiles, so the decomposition, component numbering,
        preload closures and publication targets a worker resolves cannot be
        changed by another worker's compile.

        Freezing deliberately reads the live depfiles: it is only ever performed
        by the group coordinator, between phases, with no compile in flight.

        The snapshot outlives the build that wrote it -- it is an ordinary file in
        the script directory -- so it also records which whole-group publication
        it was frozen from.  Without that, a recipe scheduled ahead of the next
        build's first freeze applies the previous build's edge set, and the
        coordinator's freeze then makes its publication a graph transition.

        \return the name of the frozen generation.
    */
    string writeGraphSnapshot(string snapshot_path,
            hash<SourceOrderContext> context_info, *string batch_stamp) {
        list<list<int>> edges = collectDepfileContractEdges(context_info.outputs);
        string generation = contractEdgeGeneration(edges, context_info.outputs);
        hash<auto> snapshot = {
            # Format 3 dates the whole-group publication the edge set was read
            # from by the batch publication sidecar.  An earlier snapshot dated it
            # by the batch stamp, which the build tool also touches for ordering,
            # so its generation cannot be compared against this one; and a format 1
            # snapshot names no publication at all.  Neither is applied: both may
            # predate a shared parse that superseded them.
            "format": 3,
            "generation": generation,
            "outputs_digest": outputsDigest(context_info.outputs),
        };
        *int batch_generation = batchStampGeneration(batch_stamp);
        if (exists batch_generation) {
            snapshot += {
                "batch_stamp": absoluteNormalized(batch_stamp),
                "batch_stamp_generation": batch_generation,
            };
        }
        snapshot.edges = edges;
        atomicWriteIfChanged(snapshot_path, make_json(snapshot) + "\n");
        return generation;
    }

    #! The frozen edge set, or NOTHING when there is none to apply.
    /** A missing or unreadable snapshot is not an error: the first build of a
        group has none, and every caller outside a build step wants the live
        graph anyway.  Falling back to a live scan is exactly what those callers
        did before a snapshot existed.

        A snapshot whose \c outputs_digest no longer matches is discarded rather
        than trusted: the context's source list only changes through a CMake
        reconfigure, which starts a new build whose first freeze replaces it.

        A snapshot frozen before the group's current whole-group publication is
        discarded for the same reason: the shared parse that produced that
        publication rewrote every depfile in the group, so the frozen edge set
        describes a graph it superseded.  That publication is dated by the sidecar
        beside the batch stamp rather than by the stamp, which recipes that publish
        nothing also touch.  A build tool is free to schedule an
        object recipe before this build's first freeze -- any target that depends
        on the object stamps rather than on the group's order targets does
        exactly that -- and applying the previous build's edge set there produces
        a compile the coordinator's freeze then refuses to publish.
    */
    private *list<list<int>> loadGraphSnapshot(list<string> outputs) {
        *string snapshot_path = ENV.QORE_QCC_GRAPH_SNAPSHOT;
        if (!snapshot_path || !is_file(snapshot_path)) {
            return NOTHING;
        }
        try {
            auto data = parse_json(ReadOnlyFile::readTextFile(snapshot_path));
            if (data.typeCode() != NT_HASH) {
                return NOTHING;
            }
            hash<auto> snapshot = data;
            if (snapshot.format != 3 || snapshot.edges.typeCode() != NT_LIST
                    || snapshot.outputs_digest != outputsDigest(outputs)) {
                return NOTHING;
            }
            if (exists snapshot.batch_stamp
                    && snapshot.batch_stamp_generation
                        != batchStampGeneration(snapshot.batch_stamp)) {
                return NOTHING;
            }
            list<list<int>> edges = ();
            foreach auto raw_edge in (snapshot.edges) {
                if (raw_edge.typeCode() != NT_LIST || raw_edge.size() != 2) {
                    return NOTHING;
                }
                int provider = raw_edge[0];
                int consumer = raw_edge[1];
                if (provider < 0 || provider >= outputs.size()
                        || consumer < 0 || consumer >= outputs.size()) {
                    return NOTHING;
                }
                push edges, (provider, consumer);
            }
            return edges;
        } catch (hash<ExceptionInfo> ex) {
            return NOTHING;
        }
    }

    #! The content-derived half of the graph, before any depfile edge is applied.
    private hash<SourceOrderGraph> loadSummaryGraph(string context_path,
            hash<SourceOrderContext> context_info) {
        string cache_file = context_path + ".source-order-v2.json";
        *hash<SourceOrderGraph> cached = loadGraphCache(cache_file, context_path,
            context_info.inputs, context_info.outputs, context_info.parse_defines);
        hash<SourceOrderGraph> graph;
        if (exists cached) {
            graph = cached;
        } else {
            list<hash<string, list<string>>> summaries = scanSummaries(
                context_info.inputs, context_info.parse_defines);
            graph = buildGraphFromSummaries(context_info.inputs, summaries);
            saveGraphCache(cache_file, context_info.inputs, context_info.outputs,
                context_info.parse_defines, graph);
        }
        return graph;
    }

    private hash<SourceOrderGraph> loadOrBuildGraph(string context_path,
            hash<SourceOrderContext> context_info) {
        string graph_context = absoluteNormalized(context_path);
        if (exists loaded_graph_context && exists loaded_graph
                && loaded_graph_context == graph_context) {
            return loaded_graph;
        }
        hash<SourceOrderGraph> graph = loadSummaryGraph(context_path, context_info);
        int depfile_started = clock_getmicros_monotonic();
        # One JSON read replaces reading and scanning every member depfile in the
        # group.  That is not only what makes the graph immutable for the
        # duration of a build step: a large group runs a currency probe per
        # object, and each of those probes used to rescan every depfile, which
        # is quadratic in the source count for a build that compiles nothing.
        *list<list<int>> frozen = loadGraphSnapshot(context_info.outputs);
        depfile_contract_edges = exists frozen
            ? frozen
            : collectDepfileContractEdges(context_info.outputs);
        depfile_edges_frozen = exists frozen;
        depfile_edge_generation = NOTHING;
        applyContractEdges(depfile_contract_edges, \graph);
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) {
            stderr.printf("depfile contract edges=%d us (%s)\n",
                clock_getmicros_monotonic() - depfile_started,
                exists frozen ? "frozen snapshot" : "live scan");
        }
        loaded_graph_context = graph_context;
        loaded_graph = graph;
        return graph;
    }

    #! The identity of the depfile-derived edge set the loaded graph was built from.
    /** Loading the graph is what produces the edge set, so the graph is loaded
        first rather than making every caller remember to do so.
    */
    string graphGeneration(string context_path,
            hash<SourceOrderContext> context_info) {
        loadOrBuildGraph(context_path, context_info);
        if (!exists depfile_edge_generation) {
            depfile_edge_generation = contractEdgeGeneration(
                depfile_contract_edges ?? (), context_info.outputs);
        }
        return depfile_edge_generation;
    }

    private bool requiredEdge(hash<SourceOrderGraph> graph, int provider,
            int consumer) {
        return exists graph.required[provider]{string(consumer)};
    }

    private hash<string, bool> collectPrerequisites(int target,
            hash<SourceOrderGraph> graph) {
        hash<string, bool> prerequisites = {};
        list<list<int>> stack = ();
        foreach string provider_key in (graph.incoming[target].keys()) {
            push stack, (target, provider_key.toInt());
        }
        while (stack) {
            list<int> edge = pop stack;
            int consumer = edge[0];
            int provider = edge[1];
            string provider_key = string(provider);
            if (!requiredEdge(graph, provider, consumer)
                    || exists prerequisites{provider_key}) {
                continue;
            }
            prerequisites{provider_key} = True;
            foreach string next_provider in (graph.incoming[provider].keys()) {
                push stack, (provider, next_provider.toInt());
            }
        }
        return prerequisites;
    }

    private int minimumNode(hash<string, bool> nodes, *int excluded = NOTHING) {
        int result = -1;
        foreach string node_key in (nodes.keys()) {
            int node = node_key.toInt();
            if ((exists excluded && node == excluded)
                    || (result >= 0 && node >= result)) {
                continue;
            }
            result = node;
        }
        return result;
    }

    private list<int> topoSubset(hash<string, bool> nodes,
            hash<SourceOrderGraph> graph, int target) {
        list<int> incoming_count = ();
        for (int index = 0; index < graph.outgoing.size(); ++index) {
            push incoming_count, 0;
        }
        foreach string provider_key in (nodes.keys()) {
            int provider = provider_key.toInt();
            foreach string consumer_key in (graph.outgoing[provider].keys()) {
                int consumer = consumer_key.toInt();
                if (exists nodes{consumer_key} && requiredEdge(graph, provider, consumer)) {
                    ++incoming_count[consumer];
                }
            }
        }
        hash<string, bool> ready = {};
        foreach string node_key in (nodes.keys()) {
            if (!incoming_count[node_key.toInt()]) {
                ready{node_key} = True;
            }
        }
        hash<string, bool> remaining = nodes;
        list<int> order = ();
        while (remaining) {
            int node = minimumNode(ready);
            if (node >= 0) {
                remove ready{string(node)};
                if (!exists remaining{string(node)}) {
                    continue;
                }
            } else {
                node = minimumNode(remaining, target);
                if (node < 0) {
                    node = minimumNode(remaining);
                }
            }
            string node_key = string(node);
            remove remaining{node_key};
            push order, node;
            list<int> consumers = ();
            foreach string consumer_key in (graph.outgoing[node].keys()) {
                push consumers, consumer_key.toInt();
            }
            foreach int consumer in (sort(consumers)) {
                string consumer_key = string(consumer);
                if (!exists remaining{consumer_key}
                        || !requiredEdge(graph, node, consumer)) {
                    continue;
                }
                --incoming_count[consumer];
                if (!incoming_count[consumer]) {
                    ready{consumer_key} = True;
                }
            }
        }
        return order;
    }

    list<int> directOrder(string context_path, hash<SourceOrderContext> context_info,
            int target) {
        hash<SourceOrderGraph> graph = loadOrBuildGraph(context_path, context_info);
        list<int> order = ();
        foreach string provider_key in (graph.incoming[target].keys()) {
            int provider = provider_key.toInt();
            if (requiredEdge(graph, provider, target)) {
                push order, provider;
            }
        }
        return sort(order);
    }

    private list<list<int>> directOrders(hash<SourceOrderGraph> graph, int count) {
        list<list<int>> result = ();
        for (int target = 0; target < count; ++target) {
            list<int> order = ();
            foreach string provider_key in (graph.incoming[target].keys()) {
                int provider = provider_key.toInt();
                if (requiredEdge(graph, provider, target)) {
                    push order, provider;
                }
            }
            push result, sort(order);
        }
        return result;
    }

    list<list<int>> allDirectOrders(string context_path,
            hash<SourceOrderContext> context_info) {
        return directOrders(loadOrBuildGraph(context_path, context_info),
            context_info.inputs.size());
    }

    private list<list<int>> buildDirectOrders(hash<SourceOrderGraph> graph, int count) {
        hash<string, bool> nodes = {};
        for (int index = 0; index < count; ++index) {
            nodes{string(index)} = True;
        }
        list<int> order = topoSubset(nodes, graph, -1);
        list<int> rank = ();
        for (int index = 0; index < order.size(); ++index) {
            push rank, 0;
        }
        for (int index = 0; index < order.size(); ++index) {
            rank[order[index]] = index;
        }

        list<list<int>> result = ();
        for (int target = 0; target < count; ++target) {
            list<int> providers = ();
            foreach string provider_key in (graph.incoming[target].keys()) {
                int provider = provider_key.toInt();
                # A required edge that points backwards in the deterministic
                # order belongs to a dependency cycle. CMake target cycles are
                # invalid, so retain every forward edge and leave the cyclic
                # edge to qore-qo-incremental's locked prerequisite handling.
                if (requiredEdge(graph, provider, target)
                        && rank[provider] < rank[target]) {
                    push providers, provider;
                }
            }
            push result, sort(providers);
        }
        return result;
    }

    list<list<int>> allBuildDirectOrders(string context_path,
            hash<SourceOrderContext> context_info) {
        return buildDirectOrders(loadOrBuildGraph(context_path, context_info),
            context_info.inputs.size());
    }

    list<int> prerequisiteOrder(string context_path,
            hash<SourceOrderContext> context_info, int target) {
        hash<SourceOrderGraph> graph = loadOrBuildGraph(context_path, context_info);
        hash<string, bool> prerequisites = collectPrerequisites(target, graph);
        if (!prerequisites) {
            return ();
        }
        hash<string, bool> nodes = prerequisites;
        nodes{string(target)} = True;
        list<int> result = ();
        foreach int node in (topoSubset(nodes, graph, target)) {
            if (node != target) {
                push result, node;
            }
        }
        return result;
    }

    #! Successor lists over required edges only, ascending.
    private list<list<int>> requiredSuccessors(hash<SourceOrderGraph> graph) {
        list<list<int>> successors = ();
        for (int provider = 0; provider < graph.outgoing.size(); ++provider) {
            list<int> consumers = ();
            foreach string consumer_key in (graph.outgoing[provider].keys()) {
                int consumer = consumer_key.toInt();
                if (requiredEdge(graph, provider, consumer)) {
                    push consumers, consumer;
                }
            }
            push successors, sort(consumers);
        }
        return successors;
    }

    #! Tarjan's strongly connected components over the required-edge graph.
    /** Iterative by construction: an object group holds thousands of sources
        and a recursive walk would be bounded by the interpreter stack rather
        than by the graph.
    */
    private list<list<int>> tarjanComponents(list<list<int>> successors) {
        int count = successors.size();
        list<int> node_index = ();
        list<int> low = ();
        list<bool> on_stack = ();
        for (int node = 0; node < count; ++node) {
            push node_index, -1;
            push low, 0;
            push on_stack, False;
        }
        int next_index = 0;
        list<int> component_stack = ();
        list<list<int>> raw = ();
        for (int root = 0; root < count; ++root) {
            if (node_index[root] >= 0) {
                continue;
            }
            node_index[root] = next_index;
            low[root] = next_index;
            ++next_index;
            push component_stack, root;
            on_stack[root] = True;
            list<hash<auto>> frames = (("node": root, "position": 0),);
            while (frames) {
                int top = frames.size() - 1;
                int node = frames[top].node;
                int position = frames[top].position;
                if (position < successors[node].size()) {
                    frames[top].position = position + 1;
                    int consumer = successors[node][position];
                    if (node_index[consumer] < 0) {
                        node_index[consumer] = next_index;
                        low[consumer] = next_index;
                        ++next_index;
                        push component_stack, consumer;
                        on_stack[consumer] = True;
                        push frames, ("node": consumer, "position": 0);
                    } else if (on_stack[consumer] && node_index[consumer] < low[node]) {
                        low[node] = node_index[consumer];
                    }
                    continue;
                }
                pop frames;
                if (frames) {
                    int parent = frames[frames.size() - 1].node;
                    if (low[node] < low[parent]) {
                        low[parent] = low[node];
                    }
                }
                if (low[node] != node_index[node]) {
                    continue;
                }
                list<int> members = ();
                while (True) {
                    int member = pop component_stack;
                    on_stack[member] = False;
                    push members, member;
                    if (member == node) {
                        break;
                    }
                }
                push raw, sort(members);
            }
        }
        return raw;
    }

    #! Names a component by its member outputs rather than by node numbering.
    /** The key has to survive a context whose source list was reordered:
        component membership is a property of the graph, but node indexes are a
        property of the order CMake happened to emit.
    */
    private string componentKey(list<int> members, list<string> outputs) {
        list<string> paths = ();
        foreach int member in (members) {
            push paths, absoluteNormalized(outputs[member]);
        }
        return "scc-"
            + digest("sha256", join("\n", sort(paths)) + "\n").toHex().substr(0, 16);
    }

    #! A deterministic topological order over the condensed DAG.
    /** The condensation of a directed graph is acyclic by construction, so a
        Kahn sweep that cannot place every component means the decomposition
        itself is wrong. That is a defect in this tool rather than a property of
        the sources, so it is reported instead of worked around.
    */
    private list<int> condensationOrder(int count, list<list<int>> predecessors,
            list<hash<string, bool>> successor_sets) {
        list<int> pending = ();
        for (int component = 0; component < count; ++component) {
            push pending, predecessors[component].size();
        }
        hash<string, bool> ready = {};
        for (int component = 0; component < count; ++component) {
            if (!pending[component]) {
                ready{string(component)} = True;
            }
        }
        list<int> order = ();
        while (ready) {
            int component = minimumNode(ready);
            remove ready{string(component)};
            push order, component;
            list<int> consumers = ();
            foreach string consumer_key in (successor_sets[component].keys()) {
                push consumers, consumer_key.toInt();
            }
            foreach int consumer in (sort(consumers)) {
                --pending[consumer];
                if (!pending[consumer]) {
                    ready{string(consumer)} = True;
                }
            }
        }
        if (order.size() != count) {
            throw "SOURCE-ORDER-COMPONENT-ERROR", sprintf(
                "the condensation of %d strongly connected components is cyclic; only "
                "%d could be ordered", count, order.size());
        }
        return order;
    }

    private hash<SourceOrderComponents> buildComponents(hash<SourceOrderGraph> graph,
            list<string> outputs) {
        int count = outputs.size();
        list<list<int>> successors = requiredSuccessors(graph);
        # Index components by their lowest member so the numbering is a function
        # of the graph alone and not of Tarjan's discovery order.
        list<list<int>> members = sort(tarjanComponents(successors),
            int sub (list<int> left, list<int> right) {
                return left[0] < right[0] ? -1 : (left[0] > right[0] ? 1 : 0);
            });
        list<int> component_of = ();
        for (int node = 0; node < count; ++node) {
            push component_of, -1;
        }
        list<string> component_keys = ();
        list<hash<string, bool>> predecessor_sets = ();
        list<hash<string, bool>> successor_sets = ();
        for (int component = 0; component < members.size(); ++component) {
            foreach int member in (members[component]) {
                component_of[member] = component;
            }
            push component_keys, componentKey(members[component], outputs);
            push predecessor_sets, {};
            push successor_sets, {};
        }
        for (int provider = 0; provider < count; ++provider) {
            int provider_component = component_of[provider];
            foreach int consumer in (successors[provider]) {
                int consumer_component = component_of[consumer];
                if (provider_component == consumer_component) {
                    continue;
                }
                predecessor_sets[consumer_component]{string(provider_component)} = True;
                successor_sets[provider_component]{string(consumer_component)} = True;
            }
        }
        list<list<int>> predecessors = ();
        for (int component = 0; component < members.size(); ++component) {
            list<int> values = ();
            foreach string predecessor_key in (predecessor_sets[component].keys()) {
                push values, predecessor_key.toInt();
            }
            push predecessors, sort(values);
        }
        return new hash<SourceOrderComponents>((
            "members": members,
            "component_of": component_of,
            "predecessors": predecessors,
            "component_keys": component_keys,
            "topological_order": condensationOrder(members.size(), predecessors,
                successor_sets),
        ));
    }

    hash<SourceOrderComponents> sourceComponents(string context_path,
            hash<SourceOrderContext> context_info) {
        return buildComponents(loadOrBuildGraph(context_path, context_info),
            context_info.outputs);
    }

    #! Computes every configure-time graph view from one cache load.
    /** Large object groups used to start this helper three times and reload,
        validate, and augment the same graph independently for the direct-edge,
        build-edge, and SCC maps.  Keeping the views in one plan also guarantees
        that CMake cannot observe maps from different source snapshots.
    */
    hash<auto> cmakePlan(string context_path,
            hash<SourceOrderContext> context_info) {
        hash<SourceOrderGraph> graph = loadOrBuildGraph(context_path, context_info);
        return (
            "direct_orders": directOrders(graph, context_info.inputs.size()),
            "build_direct_orders": buildDirectOrders(graph, context_info.inputs.size()),
            "components": buildComponents(graph, context_info.outputs),
        );
    }

    #! Every transitive predecessor component, in dependency order.
    list<int> componentPrerequisites(hash<SourceOrderComponents> components,
            int component) {
        hash<string, bool> reached = {};
        list<int> stack = (component,);
        while (stack) {
            int current = pop stack;
            foreach int predecessor in (components.predecessors[current]) {
                string predecessor_key = string(predecessor);
                if (exists reached{predecessor_key}) {
                    continue;
                }
                reached{predecessor_key} = True;
                push stack, predecessor;
            }
        }
        list<int> order = ();
        foreach int candidate in (components.topological_order) {
            if (exists reached{string(candidate)}) {
                push order, candidate;
            }
        }
        return order;
    }

    #! The member objects a parse of \a selected must resolve its references against.
    /** Every member of every transitive predecessor of \a selected, plus every
        member reached over a CONTENT dependency from anything already in the
        closure, minus the members the parse compiles itself.  Preloading one of
        those would read the generation this compile replaces -- and worse, a
        `.qo` carries the declarations it was compiled against, so preloading a
        CONSUMER of one of these sources brings that source's own declarations
        back and the parse can no longer make them.

        Two dependency edges reach a preload, and both are needed:

          * PREREQUISITES, the members reachable over required edges -- recorded
            when a compile folds a provider's value or bakes its link-time hash;
            and
          * CONTENT dependencies, the providers a compile recorded only as a
            source-content or declaration digest.  Neither a reference that uses
            another source's declaration purely as a TYPE nor one that folds a
            constant leaves a required edge, so prerequisites alone leave that
            provider out of the parse entirely.  A type then resolves to a
            deferred placeholder, and an initializer that has to CONSTRUCT it at
            parse commit gets nothing:

              RUNTIME-TYPE-ERROR: <return statement> expects type
                'object<::OmqMap>', but got no value instead

            while a folded constant leaves the preloaded sibling that aliased it
            holding a serialized reference to a constant nothing declares:

              sibling .qo cross-resolution failed: AOT cannot deserialize value
                for class constant 'QorusTypeInfoRestClass::QorusDataTypeInfo':
                cannot resolve const_ref 'QorusDataTypeCatalogue::Info'

        The closure has to be taken over both together, and over the preloaded
        members as well as the compiled ones: a shell added for either reason
        brings its own unmet requirements, and preloading a class whose base is
        absent fails the parse just as surely ("cannot resolve base class ... for
        class ...").

        And a preloaded member is not only declared: parse commit runs initializers,
        and code they reach in a preloaded object is that object's source-stripped IR,
        which registers only in a Program declaring every class and function it calls.
        A late-bound call leaves no dependency of either kind -- it bakes nothing of its
        target -- so the closure also follows each member's LOAD REQUIREMENTS, the
        providers qcc records beside the object (see LoadRequiresSuffix).  Without them
        a whole-group parse happened to record the provider as a content dependency and
        a standalone compile of the same source did not, so the first standalone compile
        of a caller left every later preload of it without its callee:

              AOT-SOURCE-IR-ERROR: ... cannot resolve the call to
                'StepPhasePolicy::validate()': class 'StepPhasePolicy' is not
                declared in this Program

        These are not ordering edges.  Widening the preload set leaves the
        decomposition alone: it neither merges components nor changes what the
        build considers stale.

        \param components the decomposition the parse is planned against
        \param context_info the group's sources and objects
        \param selected the components the parse compiles itself

        \return the preload member outputs, in dependency order
    */
    list<string> componentPreloadOutputs(hash<SourceOrderComponents> components,
            hash<SourceOrderContext> context_info, softlist<int> selected) {
        hash<string, bool> compiled = {};
        foreach int resolved in (selected) {
            foreach int node in (components.members[resolved]) {
                compiled{context_info.outputs[node]} = True;
            }
        }
        hash<string, list<int>> reached = preloadProviderEdges(components, context_info, selected);
        list<string> preload = ();
        foreach int candidate in (components.topological_order) {
            if (!exists reached{string(candidate)}) {
                continue;
            }
            foreach int node in (components.members[candidate]) {
                string output = context_info.outputs[node];
                if (!compiled{output}) {
                    push preload, output;
                }
            }
        }
        return preload;
    }

    #! Every component a parse of \a selected resolves against, with its providers.
    /** The relation componentPreloadOutputs() closes over: required edges, content
        dependencies and load requirements together, walked from the compiled components
        through everything they preload.  Keyed by component; the compiled components are
        included.
    */
    private hash<string, list<int>> preloadProviderEdges(hash<SourceOrderComponents> components,
            hash<SourceOrderContext> context_info, softlist<int> selected) {
        hash<string, int> component_of_output = {};
        for (int component = 0; component < components.members.size(); ++component) {
            foreach int node in (components.members[component]) {
                component_of_output{context_info.outputs[node]} = component;
            }
        }
        hash<string, list<int>> reached = {};
        list<int> pending = ();
        foreach int resolved in (selected) {
            string resolved_key = string(resolved);
            if (!exists reached{resolved_key}) {
                reached{resolved_key} = ();
                push pending, resolved;
            }
        }
        # A breadth-first walk over DIRECT predecessors reaches every transitive
        # one, so the closure stays linear in the graph rather than resolving a
        # transitive prerequisite set per component.
        while (pending) {
            int component = pop pending;
            hash<string, bool> providers = {};
            foreach int provider in (components.predecessors[component]) {
                providers{string(provider)} = True;
            }
            list<string> member_outputs = ();
            foreach int node in (components.members[component]) {
                push member_outputs, context_info.outputs[node];
            }
            foreach string output in (contentDependencyOutputs(context_info, member_outputs)
                    + loadRequirementOutputs(context_info, member_outputs)) {
                *int provider = component_of_output{output};
                if (exists provider && provider != component) {
                    providers{string(provider)} = True;
                }
            }
            list<int> provider_list = ();
            foreach string provider_key in (keys providers) {
                int provider = provider_key.toInt();
                push provider_list, provider;
                if (!exists reached{provider_key}) {
                    reached{provider_key} = ();
                    push pending, provider;
                }
            }
            reached{string(component)} = sort(provider_list);
        }
        return reached;
    }

    #! The part of \a selected one parse can compile with nothing preloaded between its members.
    /** A parse resolves what it does not compile from `.qo` shells, and a shell is what its
        source compiled to against the PREVIOUS generation of everything it depends on.  So
        when a compiled member reaches another compiled member through a preloaded one --
        Y preloads X, and X was compiled against Z, which this parse recompiles -- X brings
        back what it saw of Z, and the parse's own Z is shadowed by it:

          INVALID-MEMBER: 'type' is not a registered member of class 'ReleaseScriptMetadata'

        Making the set convex by compiling X as well was measured to take most of a real
        group into every parse, whatever was edited.  Leaving members OUT instead costs
        nothing the build would not do anyway: a member left out is still stale and is
        compiled by the next pass, after X -- if what it preloads went stale with Z -- has
        been recompiled against the new Z.

        Members are taken in dependency order, providers first, and each is kept only if it
        neither reaches nor is reached from an already-kept member through a preloaded one.
        The relation includes content dependencies, which are not ordering edges and can
        form cycles between components, so removing every offending member at once could
        leave nothing; the first member is always kept.  A path from a member back to ITSELF
        through what it preloads is not a reason to leave it out: that is a standalone
        compile of it, which is what the build does without a partial parse.

        \return the kept components, in the order \a selected lists them
    */
    list<int> convexComponentSubset(hash<SourceOrderComponents> components,
            hash<SourceOrderContext> context_info, softlist<int> selected) {
        hash<string, list<int>> providers = preloadProviderEdges(components, context_info, selected);
        hash<string, list<int>> consumers = {};
        foreach hash<auto> i in (providers.pairIterator()) {
            foreach int provider in (i.value) {
                string provider_key = string(provider);
                if (!consumers{provider_key}) {
                    consumers{provider_key} = ();
                }
                push consumers{provider_key}, i.key.toInt();
            }
        }
        hash<string, bool> wanted = {};
        foreach int component in (selected) {
            wanted{string(component)} = True;
        }
        hash<string, bool> kept = {};
        hash<string, bool> deferred = {};
        foreach int candidate in (components.topological_order) {
            string candidate_key = string(candidate);
            if (!wanted{candidate_key}) {
                continue;
            }
            # a member that preloads one left out would compile against what that member was, and go stale
            # again as soon as the next pass compiles it
            if (kept && (reachesThroughPreload(candidate, providers, kept)
                    || reachesThroughPreload(candidate, consumers, kept)
                    || reachesAny(candidate, providers, kept, deferred))) {
                deferred{candidate_key} = True;
                continue;
            }
            kept{candidate_key} = True;
        }
        list<int> rv = ();
        foreach int component in (selected) {
            if (kept{string(component)}) {
                push rv, component;
            }
        }
        return rv;
    }

    #! The order in which standalone compiles of \a selected see each other's new objects.
    /** Standalone compiles run one at a time, and each preloads the objects of what it resolves
        against.  When a component it preloads is ALSO in the stale set, the compile reads that
        provider's previous object unless the provider was compiled first.  The topological order
        alone does not guarantee that: it follows required edges only, and a provider reached
        solely over a content dependency or a load requirement -- a class used as a type, a
        folded constant -- is preloaded without being ordered.  A consumer that calls a static
        method it has just started calling with a new signature then resolves the call eagerly
        against the stale shell's variants (on Qorus, `OMQ::QonsoleReferenceScope` named without
        its namespace reaches the preloaded class rather than a deferred import):

          PARSE-TYPE-ERROR: no variant matching
            'QonsoleReferenceScope::runAuxiliary(string, code<auto()>, string)' can be found;
            the following variants were tested:
              QonsoleReferenceScope::runAuxiliary(string purpose, code<auto()> task)

        So a component is taken only once nothing still pending is reachable through what it
        preloads, directly or through current components in between.  The relation includes
        every required predecessor, so the result stays a topological order.  Content
        dependencies can form cycles between components; a cycle among pending components has
        no order that serves all of them, and it is broken at the first pending component in
        topological order, whose required predecessors have all been taken by then.

        \return \a selected, providers first
    */
    list<int> preloadCompileOrder(hash<SourceOrderComponents> components,
            hash<SourceOrderContext> context_info, softlist<int> selected) {
        hash<string, list<int>> providers = preloadProviderEdges(components, context_info, selected);
        hash<string, bool> pending = {};
        foreach int component in (selected) {
            pending{string(component)} = True;
        }
        list<int> rv = ();
        while (pending) {
            *int chosen;
            *int first_pending;
            foreach int candidate in (components.topological_order) {
                string candidate_key = string(candidate);
                if (!pending{candidate_key}) {
                    continue;
                }
                if (!exists first_pending) {
                    first_pending = candidate;
                }
                # a path back to the candidate itself is a cycle through its own preloads, which any
                # standalone compile of it has
                hash<string, bool> others = pending - candidate_key;
                if (!reachesAny(candidate, providers, {}, others)) {
                    chosen = candidate;
                    break;
                }
            }
            @assert(exists first_pending);
            if (!exists chosen) {
                chosen = first_pending;
            }
            push rv, chosen;
            remove pending{string(chosen)};
        }
        return rv;
    }

    #! True if a member of \a targets is reached from \a start over \a edges without crossing \a kept.
    private static bool reachesAny(int start, hash<string, list<int>> edges, hash<string, bool> kept,
            hash<string, bool> targets) {
        if (!targets) {
            return False;
        }
        hash<string, bool> seen = {string(start): True};
        list<int> pending = (start,);
        while (pending) {
            int node = pop pending;
            foreach int next in (edges{string(node)} ?? ()) {
                string next_key = string(next);
                if (targets{next_key}) {
                    return True;
                }
                if (!kept{next_key} && !seen{next_key}) {
                    seen{next_key} = True;
                    push pending, next;
                }
            }
        }
        return False;
    }

    #! True if a member of \a kept is reached from \a start over \a edges through a node outside it.
    /** A neighbour in \a kept is compiled by the same parse, so reaching it directly is not a
        preload at all; reaching \a start again is a cycle through its own preloads, which a
        standalone compile of it has as well.
    */
    private static bool reachesThroughPreload(int start, hash<string, list<int>> edges,
            hash<string, bool> kept) {
        string start_key = string(start);
        hash<string, bool> seen = {start_key: True};
        list<int> pending = ();
        foreach int next in (edges{start_key} ?? ()) {
            string next_key = string(next);
            if (!kept{next_key} && !seen{next_key}) {
                seen{next_key} = True;
                push pending, next;
            }
        }
        while (pending) {
            int node = pop pending;
            foreach int next in (edges{string(node)} ?? ()) {
                string next_key = string(next);
                if (kept{next_key}) {
                    return True;
                }
                if (!seen{next_key}) {
                    seen{next_key} = True;
                    push pending, next;
                }
            }
        }
        return False;
    }

    #! Every component a rebuild of \a seeds would leave stale, seeds included.
    /** A compile rewrites its member's compile contract, and every component
        that consumes it is published against that contract, so rebuilding one
        component invalidates its whole transitive consumer closure.  The stale
        set alone therefore understates the work a rebuild entails -- by a factor
        of the group size when the seed is a widely required source -- which is
        why it cannot be the quantity a batch-versus-standalone decision is made
        from.

        The condensation is acyclic, so the closure is a plain reachability over
        the reversed edge set and needs no cycle guard beyond the visited index.
    */
    list<int> componentRebuildClosure(hash<SourceOrderComponents> components,
            list<int> seeds) {
        list<list<int>> consumers = ();
        for (int component = 0; component < components.members.size(); ++component) {
            push consumers, ();
        }
        for (int consumer = 0; consumer < components.predecessors.size(); ++consumer) {
            foreach int predecessor in (components.predecessors[consumer]) {
                push consumers[predecessor], consumer;
            }
        }
        hash<string, bool> reached = {};
        list<int> stack = ();
        foreach int seed in (seeds) {
            string seed_key = string(seed);
            if (exists reached{seed_key}) {
                continue;
            }
            reached{seed_key} = True;
            push stack, seed;
        }
        while (stack) {
            int current = pop stack;
            foreach int consumer in (consumers[current]) {
                string consumer_key = string(consumer);
                if (exists reached{consumer_key}) {
                    continue;
                }
                reached{consumer_key} = True;
                push stack, consumer;
            }
        }
        list<int> order = ();
        foreach int candidate in (components.topological_order) {
            if (exists reached{string(candidate)}) {
                push order, candidate;
            }
        }
        return order;
    }

    #! The build's content identity for one member source.
    /** The configure-time digest sidecar is authoritative when present: it is
        what the build itself treats as the source content, and it records the
        same sha256 this would otherwise compute. Hashing the input directly is
        the fallback for a context configured without sidecars.
    */
    private string memberContentDigest(hash<SourceOrderContext> context_info, int node) {
        string key = context_info.outputs[node];
        *string cached = content_digests{key};
        if (exists cached) {
            return cached;
        }
        string result = memberContentDigestImpl(context_info, node);
        content_digests{key} = result;
        return result;
    }

    private string memberContentDigestImpl(hash<SourceOrderContext> context_info,
            int node) {
        if (context_info.source_content_digests) {
            string sidecar = context_info.source_content_digests[node];
            if (is_file(sidecar)) {
                foreach string line in (ReadOnlyFile::readTextFile(sidecar).split("\n")) {
                    if (line.startsWith("sha256=")) {
                        return line.substr(7);
                    }
                }
            }
        }
        return fileDigest(context_info.inputs[node]);
    }

    #! The published interface a consumer depends on, for one provider member.
    /** The declaration contract is qcc's content-preserving description of the
        part of a provider that its consumers compile against, which is why a
        comment-only provider edit leaves it byte-identical. Using it -- rather
        than the provider's source digest -- is what keeps such an edit from
        rebuilding every transitive consumer.

        It is preferred over the COMPILE contract, which was what this read
        before, because a compile contract also carries the lowering artifacts:
        native rows and body-contract hashes, which are outputs of the
        interprocedural summary pass over the batch being lowered.  An 875-source
        parse derives richer summaries than a 1-source parse, so a source
        recompiled standalone against shells publishes a different compile
        contract from the one the group's own parse published for it -- legitimately,
        and with no declaration having changed.  Watching that made every FIRST
        incremental build after a full build walk the whole consumer closure of
        whatever was edited: one comment appended to a source with a closure of 13
        rebuilt 13 objects in 23 qcc invocations, where the same edit built a
        second time from the state that left needed 1.

        A consumer that BAKED a provider's body-contract hash must still be rebuilt
        when that hash moves, or the aggregate link fails with "qo-link hash
        mismatch".  A declaration contract does not carry body-contract hashes, so
        this digest does not see such a move; the generation carries the rows the
        consumer baked separately, in its "body-contracts" (see
        memberBodyContractRowsDigest()).  See design/qcc-incremental-scc-scheduler.md.
    */
    private string memberContractDigest(string output) {
        *string cached = contract_digests{output};
        if (exists cached) {
            return cached;
        }
        string result = "";
        foreach string path in ((output + DeclarationContractSuffix,
                output + ".compile-contract.stamp",
                output + ".content.stamp")) {
            if (is_file(path)) {
                result = digest("sha256", ReadOnlyFile::readBinaryFile(path)).toHex();
                break;
            }
        }
        contract_digests{output} = result;
        return result;
    }

    #! An identity over only the sources of \a component's own members.
    /** This is what a publication compare-and-swap must compare, and the full
        generation token is not: a compile rewrites its own depfile, the depfile
        contributes required edges to the graph, and those edges decide which
        components are predecessors. Comparing full tokens across a compile would
        therefore compare identities computed from two different graphs and
        report that the inputs moved on every build that changes a depfile.

        A component's member sources are the only part of its identity an agent
        outside the build can change while qcc is reading them, so they are the
        only part a "did this move under me" check may look at.

        The component key is deliberately absent from the preimage. It is a
        digest of the same member output paths the preimage already names, so it
        adds no identity -- but it does make an internal graph transition that
        changed component membership indistinguishable from an external source
        edit, which is the one thing this token exists to tell apart. A caller
        that addresses its component by key already holds membership fixed;
        a caller whose key no longer resolves is told that specifically.
    */
    string componentSourceToken(hash<SourceOrderComponents> components,
            hash<SourceOrderContext> context_info, int component) {
        list<hash<auto>> members = ();
        foreach int node in (components.members[component]) {
            push members, (
                "output": absoluteNormalized(context_info.outputs[node]),
                "content_digest": memberContentDigest(context_info, node),
            );
        }
        members = sort(members, int sub (hash<auto> left, hash<auto> right) {
            return left.output < right.output ? -1 : (left.output > right.output ? 1 : 0);
        });
        return digest("sha256", make_json((
            "format": 1,
            "members": members,
        ))).toHex();
    }

    #! The generation manifest and token of one component.
    /** The manifest is the token's preimage. It names the component, the source
        content digest of every member, and the published contract digest of
        every member of every direct predecessor component.

        The two halves are deliberately different kinds of identity. A member's
        own source bytes decide whether the component must be recompiled, so
        those are hashed directly. A predecessor contributes only the interface
        its consumers compile against, so it contributes its compile contract:
        that is what makes a provider edit that changes no declaration a no-op
        for its consumers, while a declaration change propagates -- the
        predecessor is rebuilt first, its contract moves, and every consumer's
        token moves with it.

        Members and prerequisites are ordered by output path rather than by node
        index, so reordering the context source list cannot change a token.
    */
    #! What one component publishes to its consumers, computed once per process.
    /** A hub component appears in the prerequisite list of every component that
        consumes it -- 400 of them in one 868-source group -- and the list it
        contributes is the same every time.  Recomputing it per consumer made a
        whole-group currency pass spend most of its time re-deriving identical
        contract digests, and the sorts around them.  The key, not the index:
        component numbering is a function of the graph, which a compile in the
        same process can change.
    */
    private list<hash<auto>> componentProvides(hash<SourceOrderComponents> components,
            hash<SourceOrderContext> context_info, int component) {
        string key = components.component_keys[component];
        *list<hash<auto>> cached = component_provides{key};
        if (exists cached) {
            return cached;
        }
        list<hash<auto>> provided = ();
        foreach int node in (components.members[component]) {
            push provided, (
                "output": absoluteNormalized(context_info.outputs[node]),
                "contract_digest": memberContractDigest(context_info.outputs[node]),
            );
        }
        provided = sortByOutput(provided);
        component_provides{key} = provided;
        return provided;
    }

    #! Sorts manifest entries by output path, without sorting what cannot move.
    /** Most components have one member and most prerequisite lists one entry, and
        a comparator call through a closure is not free at that size.
    */
    private list<hash<auto>> sortByOutput(list<hash<auto>> entries) {
        if (entries.size() < 2) {
            return entries;
        }
        return sort(entries, int sub (hash<auto> left, hash<auto> right) {
            return left.output < right.output ? -1 : (left.output > right.output ? 1 : 0);
        });
    }

    hash<auto> componentGeneration(hash<SourceOrderComponents> components,
            hash<SourceOrderContext> context_info, int component) {
        list<hash<auto>> members = ();
        foreach int node in (components.members[component]) {
            push members, (
                "input": absoluteNormalized(context_info.inputs[node]),
                "output": absoluteNormalized(context_info.outputs[node]),
                "content_digest": memberContentDigest(context_info, node),
            );
        }
        members = sortByOutput(members);
        # What this component LINKS against, as opposed to what it compiled against.
        #
        # A predecessor contributes its declaration contract above, which says
        # nothing about body contracts -- deliberately, because that is what makes it
        # identical between a whole-group parse and a standalone one.  `--link-qo`
        # does compare body contracts, so a member that baked one has to watch it, or
        # the aggregate link fails with "qo-link hash mismatch" naming an object the
        # build had no recorded reason to rebuild.
        #
        # Only the members that baked one record the dependency, so this is empty for
        # most components: on one 875-source group, 856 objects publish a body
        # contract and 280 consume one.  It is listed apart from the prerequisites
        # because a body-baked provider need not be a predecessor of this component at
        # all -- and because the two answer different questions about it.
        #
        # What each member linked against is the rows it baked, not the provider's whole
        # stamp, so the digest covers the union of those rows over the members.  A member
        # that names a provider without recording its rows makes the whole stamp the
        # component's dependency on it, as it was before the rows were recorded.
        hash<string, string> body_providers = {};
        hash<string, hash<string, bool>> body_symbols = {};
        hash<string, bool> body_whole = {};
        foreach int node in (components.members[component]) {
            string member_output = context_info.outputs[node];
            list<string> body_outputs = bodyContractDependencyOutputs(member_output);
            if (!body_outputs) {
                continue;
            }
            *hash<string, hash<string, bool>> imports = bodyContractImports(member_output);
            foreach string provider in (body_outputs) {
                string canonical_provider = absoluteNormalized(provider);
                if (!exists body_providers{canonical_provider}) {
                    body_providers{canonical_provider} = provider;
                }
                *hash<string, bool> symbols = imports{canonical_provider};
                if (symbols) {
                    body_symbols{canonical_provider} += symbols;
                } else {
                    body_whole{canonical_provider} = True;
                }
            }
        }
        list<hash<auto>> body_contracts = ();
        foreach hash<auto> i in (body_providers.pairIterator()) {
            push body_contracts, (
                "output": i.key,
                "body_contract_digest": body_whole{i.key}
                    ? memberBodyContractDigest(i.value)
                    : memberBodyContractRowsDigest(i.value, body_symbols{i.key}),
            );
        }
        body_contracts = sortByOutput(body_contracts);
        list<hash<auto>> prerequisites = ();
        foreach int predecessor in (components.predecessors[component]) {
            push prerequisites, (
                "scc": components.component_keys[predecessor],
                "provides": componentProvides(components, context_info, predecessor),
            );
        }
        if (prerequisites.size() > 1) {
            prerequisites = sort(prerequisites, int sub (hash<auto> left, hash<auto> right) {
                return left.scc < right.scc ? -1 : (left.scc > right.scc ? 1 : 0);
            });
        }
        # An empty list is omitted rather than recorded, so a group with no baked
        # body contracts -- and every group built before this was published --
        # produces exactly the manifest it produced before, and no token moves.
        hash<auto> preimage = (
            "format": 1,
            "scc": components.component_keys[component],
            "members": members,
            "prerequisites": prerequisites,
        );
        if (body_contracts) {
            preimage."body-contracts" = body_contracts;
        }
        string manifest = make_json(preimage);
        return (
            "manifest": manifest,
            "token": digest("sha256", manifest).toHex(),
        );
    }

    #! Generation manifests and tokens for every component.
    hash<string, hash<auto>> allComponentGenerations(
            hash<SourceOrderComponents> components,
            hash<SourceOrderContext> context_info) {
        hash<string, hash<auto>> generations = {};
        for (int component = 0; component < components.members.size(); ++component) {
            generations{string(component)} =
                componentGeneration(components, context_info, component);
        }
        return generations;
    }

    #! Every artifact one member publishes, in a fixed order.
    /** artifactCurrentImpl(), the staging set in qore-qo-incremental, and
        _QORE_QCC_OBJECT_ARTIFACT_PATHS() in QoreMacros.cmake must agree on this
        list; the lock file is deliberately absent because it is transient.
    */
    list<string> memberArtifacts(string output) {
        return (
            output,
            output + ".d",
            output + ".idx.json",
            output + ".status.json",
            output + ".content.stamp",
            output + ".compile-contract.stamp",
            output + ".aggregate-contract.stamp",
            output + ".stamp",
            output + ".source.manifest.json",
            output + ".source-parse-defines",
        );
    }

    #! The directory holding one object group's published generation records.
    /** Every member of a component shares one output directory, so the group's
        own output directory is the only location that needs no extra
        configuration to agree between the helper, CMake, and the pruner.

        A group configured with no sources has no components and so no records,
        but CMake still asks for the path at configure time; deriving it from the
        context keeps that a well-defined answer instead of an indexing error.
    */
    string generationDir(hash<SourceOrderContext> context_info, string context_path) {
        string base = context_info.outputs
            ? dirname(absoluteNormalized(context_info.outputs[0]))
            : dirname(absoluteNormalized(context_path));
        return base + DirSep + ".qcc-scc";
    }

    string generationRecordPath(hash<SourceOrderContext> context_info,
            string context_path, hash<SourceOrderComponents> components, int component) {
        return generationDir(context_info, context_path) + DirSep
            + components.component_keys[component] + ".generation.json";
    }

    string generationLockPath(hash<SourceOrderContext> context_info,
            string context_path, hash<SourceOrderComponents> components, int component) {
        return generationDir(context_info, context_path) + DirSep
            + components.component_keys[component] + ".lock";
    }

    private *hash<auto> readGenerationRecord(string path) {
        try {
            if (!is_file(path)) {
                return NOTHING;
            }
            auto data = parse_json(ReadOnlyFile::readTextFile(path));
            if (data.typeCode() != NT_HASH) {
                return NOTHING;
            }
            hash<auto> record = data;
            return record.format == 1 && record.generation.typeCode() == NT_STRING
                ? record : NOTHING;
        } catch (hash<ExceptionInfo> ex) {
            return NOTHING;
        }
    }

    #! canonical() for a depfile path, resolved once per distinct path per process.
    private string canonicalCached(string path) {
        *string cached = canonical_paths{path};
        if (exists cached) {
            return cached;
        }
        string result = canonical(path);
        canonical_paths{path} = result;
        return result;
    }

    #! Build inputs a member's depfile records that the generation token does not cover.
    /** The token is a digest over the source content of the component and its
        transitive predecessors, so every in-context source, digest sidecar, and
        sibling artifact is already accounted for by comparing tokens. Keeping
        those paths in an mtime comparison would be worse than redundant: all
        members of one component are published together in a single flush, so one
        member's contract stamp is routinely newer than another member's success
        stamp, which would make the pair permanently stale. What remains -- the
        toolchain, loaded modules, stubs, and includes from outside the group --
        has no content identity in the manifest and is still compared by mtime.
    */
    private list<string> externalDepfileInputs(string output,
            hash<SourceOrderContext> context_info,
            reference<*hash<string, bool>> covered) {
        if (!exists covered) {
            covered = {};
            for (int index = 0; index < context_info.outputs.size(); ++index) {
                list<string> paths = memberArtifacts(context_info.outputs[index]);
                # Covered, but deliberately not a member artifact: the generation
                # token accounts for it by content, so comparing it by mtime would be
                # worse than redundant -- a provider's body contract is routinely
                # newer than a consumer's success stamp, which would make the pair
                # permanently stale.  It is not in memberArtifacts() because a
                # publication must not be held to have produced one: a build
                # configured without --depfile-declaration-contract-stamps never asks
                # for one, and every generation published before it existed is still
                # complete.
                push paths, context_info.outputs[index] + BodyContractSuffix;
                push paths, context_info.inputs[index];
                if (context_info.source_content_digests) {
                    push paths, context_info.source_content_digests[index];
                }
                foreach string path in (paths) {
                    covered{path} = True;
                    covered{absoluteNormalized(path)} = True;
                    covered{canonical(path)} = True;
                }
            }
        }
        *list<string> cached = external_inputs{output};
        if (exists cached) {
            return cached;
        }
        list<string> external = ();
        foreach string dependency in (parseMakeDepfileInputs(output + ".d")) {
            if (exists covered{dependency}
                    || exists covered{absoluteNormalized(dependency)}) {
                continue;
            }
            # The covered set indexes every path three ways -- as written, made
            # absolute, and canonical -- so a lookup that tries only the first two
            # can miss a path it holds.  absoluteNormalized() prepends the working
            # directory and nothing else: it does not collapse a `..`, and it does
            # not resolve a symlink, so the same file spelled either way reaches
            # here looking foreign.
            #
            # What follows for a group source that looks foreign is not a
            # near-miss.  It stops being accounted for by content and is compared
            # by mtime instead, against the rule that an input must be strictly
            # OLDER than the stamp -- and a source written in the same filesystem
            # tick as the artifacts is then permanently stale, with a build that
            # rebuilds it every time and never converges.
            #
            # qcc canonicalises what it writes, so this is a guard rather than a
            # daily occurrence; a build tree reached through a symlink is how it
            # would happen.  The realpath is memoised because a whole-group currency
            # pass resolves the same 1.9k distinct paths once per member otherwise.
            if (exists covered{canonicalCached(dependency)}) {
                continue;
            }
            push external, dependency;
        }
        external_inputs{output} = external;
        return external;
    }

    #! Every build input from outside the group that any member's depfile records.
    /** The union of externalDepfileInputs() over the group, sorted.  This is what
        the build tool has to watch for the group as a whole: a member records a
        module or an include only in its own depfile, and a standalone compile that
        adds one after the group's last shared parse is the only record of it.
    */
    list<string> groupExternalInputs(hash<SourceOrderContext> context_info) {
        *hash<string, bool> covered;
        hash<string, bool> inputs = {};
        foreach string output in (context_info.outputs) {
            if (!is_file(output + ".d")) {
                continue;
            }
            foreach string dependency in (externalDepfileInputs(output, context_info,
                    \covered)) {
                inputs{dependency} = True;
            }
        }
        return sort(keys inputs);
    }

    #! The group context's modification time, or NOTHING when it does not exist.
    /** The context is a configure-time artifact rewritten only when its content
        changes, so its modification time is the group's build-input generation.
        It is deliberately not part of the source token -- it carries no source
        content -- and qcc fingerprints it by content rather than recording it as
        a depfile input, so neither the token comparison nor externalDepfileInputs()
        can observe a transition.  This is the one comparison that does.
    */
    private *date contextGenerationTime(string context_path) {
        return hstat(context_path).mtime;
    }

    #! True when \a record still covers \a generation despite a differing token.
    /** A generation token names three things, and only one of them is a plain
        comparison.

        The component's MEMBERS are its own identity and carry no build state, so
        they are compared exactly; that is what still catches a source edit.

        Its PREREQUISITES come from the dependency graph, so the token is only
        comparable against one computed from the same graph -- the same reason
        componentSourceToken() exists for the publication compare-and-swap.  A
        compile rewrites its own depfile, depfile entries are what produce required
        edges, and a component's predecessors come from its own depfile: so compiling
        a component is itself enough to move the graph its record was published
        against.

        It routinely does.  A whole-group parse resolves cross-member references it
        can see in its own parse and records a compile-contract prerequisite for
        each; the same source compiled standalone against shells defers more of them
        and records fewer.  On one real 875-source group the two forms of one
        member's depfile carry 45 and 28 contract edges, so the FIRST standalone
        compile after a group parse drops prerequisites -- and comparing the token it
        published against a token computed from the graph its own compile produced
        then reports it stale immediately after building it.  The coordinator sees a
        pass leave stale exactly what it compiled, calls the plan non-convergent, and
        reparses the whole group.  That was invisible while a mode transition also
        invalidated the consumer closure, because the next pass then had different
        work to do and the loop moved on.

        Its BODY CONTRACTS come from its members' own depfiles rather than from the
        graph, but the asymmetry is the same and for the same reason: a compile
        decides what it links against, so one it stopped baking is not a reason to
        rebuild it, while one it started baking -- or one whose hash moved -- is.

        So: a prerequisite or body contract the CURRENT generation names must appear
        in the record with the same digest; one the record names and the current
        generation does not is the compile's own doing and is forgiven.  A
        prerequisite is only forgiven that way when the graph actually moved, because
        on an unchanged graph a prerequisite set that shrank did not come from this
        component's compile.

        A prerequisite the compile GAINED is never forgiven here, and does not need
        to be: publication computes the record from the component's own depfile
        edges as the compile left them (see publishedGraphView()), so the record
        already names it.
    */
    private bool recordCoversCurrentGeneration(hash<auto> record,
            hash<auto> generation, string context_path,
            hash<SourceOrderContext> context_info) {
        if (record.manifest.typeCode() != NT_HASH) {
            return False;
        }
        hash<auto> current = parse_json(generation.manifest);
        if (make_json(record.manifest.members) != make_json(current.members)) {
            return False;
        }

        bool graph_moved = record.graph_generation.typeCode() == NT_STRING
            && record.graph_generation != graphGeneration(context_path, context_info);
        if (!graph_moved) {
            if (make_json(record.manifest.prerequisites)
                    != make_json(current.prerequisites)) {
                return False;
            }
        } else {
            hash<string, string> published = {};
            foreach hash<auto> prerequisite in (record.manifest.prerequisites ?? ()) {
                foreach hash<auto> provided in (prerequisite.provides ?? ()) {
                    published{provided.output} = provided.contract_digest;
                }
            }
            foreach hash<auto> prerequisite in (current.prerequisites ?? ()) {
                foreach hash<auto> provided in (prerequisite.provides ?? ()) {
                    *string was = published{provided.output};
                    if (!exists was || was != provided.contract_digest) {
                        return False;
                    }
                }
            }
        }

        hash<string, string> published_bodies = {};
        foreach hash<auto> body in (record.manifest."body-contracts" ?? ()) {
            published_bodies{body.output} = body.body_contract_digest;
        }
        foreach hash<auto> body in (current."body-contracts" ?? ()) {
            *string was = published_bodies{body.output};
            if (!exists was || was != body.body_contract_digest) {
                return False;
            }
        }
        return True;
    }

    #! True when the published generation of \a component matches its sources.
    /** One token comparison validates the component's entire transitive source
        closure, because the token is a Merkle digest over that closure. The
        remaining checks confirm the publication is complete, that the group
        context has not moved since publication, and that no external build input
        has moved since it was published.

        A token that does not match is not automatically stale: see
        recordCoversCurrentGeneration() for the parts of the token that are not a
        plain comparison -- what a compile is entitled to have changed about its own
        prerequisites and its own baked body contracts.
    */
    private bool generationCurrentImpl(hash<SourceOrderContext> context_info,
            string context_path, hash<SourceOrderComponents> components, int component,
            *string bootstrap_stamp, reference<*hash<string, bool>> covered,
            bool check_external_dependencies, *date context_time) {
        try {
            *hash<auto> record = readGenerationRecord(
                generationRecordPath(context_info, context_path, components, component));
            if (!exists record) {
                return False;
            }
            hash<auto> generation =
                componentGeneration(components, context_info, component);
            if (record.generation != generation.token
                    && !recordCoversCurrentGeneration(record, generation,
                        context_path, context_info)) {
                return False;
            }
            *hash<StatInfo> bootstrap_info;
            if (exists bootstrap_stamp) {
                bootstrap_info = hstat(bootstrap_stamp);
                if (!exists bootstrap_info) {
                    return False;
                }
            }
            foreach int member in (components.members[component]) {
                string output = context_info.outputs[member];
                foreach string path in (memberArtifacts(output)) {
                    if (!is_file(path)) {
                        return False;
                    }
                }
                date stamp_time = hstat(output + ".stamp").mtime;
                if (exists bootstrap_info && bootstrap_info.mtime > stamp_time) {
                    return False;
                }
                # A context newer than the publication is a generation transition
                # that the whole group has to cross together.  Comparing it here
                # keeps the decision at full timestamp resolution and in one
                # authority; the bootstrap helper used to ask the shell for it
                # with "-nt", which busybox ash answers from st_mtime alone, so a
                # transition published inside the same second as the tree it
                # supersedes was invisible on Alpine and Make ran the standalone
                # rule once per source.
                if (exists context_time && context_time > stamp_time) {
                    return False;
                }
                if (check_external_dependencies) {
                    foreach string dependency in (externalDepfileInputs(output,
                            context_info, \covered)) {
                        *date dependency_time = externalInputTime(dependency);
                        if (!exists dependency_time || dependency_time >= stamp_time) {
                            return False;
                        }
                    }
                }
            }
        } catch (hash<ExceptionInfo> ex) {
            return False;
        }
        return True;
    }

    #! True when the published generation of \a component matches its sources.
    /** \a check_external_dependencies compares depfile inputs from outside the
        group -- the toolchain, loaded modules, stubs, includes -- by mtime.  A
        recipe running behind the group coordinator asks it not to: the
        coordinator's plan target takes those same files as build dependencies,
        so the build tool has already decided the question, and answering it a
        second time with a different rule is what let a recipe conclude that its
        component was stale after the coordinator concluded the whole group was
        current.  Two schedulers with two criteria is how a group ends up with
        one compile per object running at once.
    */
    bool generationCurrent(hash<SourceOrderContext> context_info,
            string context_path, hash<SourceOrderComponents> components, int component,
            *string bootstrap_stamp, bool check_external_dependencies = True) {
        *hash<string, bool> covered;
        return generationCurrentImpl(context_info, context_path, components, component,
            bootstrap_stamp, \covered, check_external_dependencies,
            contextGenerationTime(context_path));
    }

    #! True when every component is current, sharing the group-wide covered-path index.
    /** externalDepfileInputs() canonicalizes every artifact path in the group the
        first time it is called.  Recreating that index for each component makes
        a whole-group currency check quadratic in the source count. */
    bool allGenerationsCurrent(hash<SourceOrderContext> context_info,
            string context_path, hash<SourceOrderComponents> components,
            *string bootstrap_stamp) {
        *hash<string, bool> covered;
        *date context_time = contextGenerationTime(context_path);
        for (int component = 0; component < components.members.size(); ++component) {
            if (!generationCurrentImpl(context_info, context_path, components,
                    component, bootstrap_stamp, \covered, True, context_time)) {
                return False;
            }
        }
        return True;
    }

    #! Stale components in dependency order, sharing the group-wide covered-path index.
    /** This is the planning counterpart to allGenerationsCurrent().  A large
        incremental build must decide once, before per-object recipes occupy the
        build tool's worker slots, whether the stale closure is small enough for
        individual compiles or should use the shared-parse batch.  Returning the
        components in condensation-DAG order also lets a small plan compile every
        predecessor before its consumers without recursively traversing the same
        closure from every member recipe.
    */
    list<int> staleGenerations(hash<SourceOrderContext> context_info,
            string context_path, hash<SourceOrderComponents> components,
            *string bootstrap_stamp, bool check_external_dependencies) {
        *hash<string, bool> covered;
        *date context_time = contextGenerationTime(context_path);
        list<int> stale = ();
        foreach int component in (components.topological_order) {
            if (!generationCurrentImpl(context_info, context_path, components,
                    component, bootstrap_stamp, \covered,
                    check_external_dependencies, context_time)) {
                push stale, component;
            }
        }
        return stale;
    }

    #! The graph a compile of \a component leaves behind, when it is not the frozen one.
    /** A frozen snapshot is what makes a pass plannable: every helper in it resolves
        the same decomposition, preloads and publication targets, and a compile's
        depfile rewrite is crossed at the next freeze rather than mid-pass.  But a
        record computed from that graph describes the component's prerequisites as
        they were BEFORE its compile, and the compile has just written what it really
        depended on.

        That differs whenever the component switches compile mode.  A whole-group
        parse resolves some cross-member references inside its own parse; the same
        source compiled standalone resolves them against preloaded objects and
        records a contract edge to each one it used.  The first standalone compile
        after a group parse can therefore add a prerequisite the frozen graph lacks.
        Its record then omits it, the next freeze reads the edge from the depfile,
        and recordCoversCurrentGeneration() -- which forgives a prerequisite the
        compile dropped but never one it gained -- finds the component stale right
        after building it.  The coordinator sees a pass leave stale exactly what it
        compiled and reparses the whole group: on Qorus, every incremental build.

        So the record is computed from the frozen graph with this component's own
        depfile edges replaced by the live ones.  Only its own: the edges INTO its
        members are the ones its compile wrote and the ones its prerequisites come
        from, while every other depfile is exactly what the next freeze will read
        unless another compile rewrites it, which is that compile's publication to
        account for.  Reading only this component's depfiles also keeps a
        publication from paying for a whole-group depfile scan.

        When the compile's edges change the decomposition itself -- it closed a cycle
        through a consumer, so the component the pass planned no longer exists -- no
        such record is meaningful.  The frozen graph's record is kept, and the next
        pass finds the merged component unpublished and builds it with the parse a
        multi-member component needs.

        \return NOTHING when the frozen graph already describes the compile, or when
        the live edges change the component's membership; otherwise \c components,
        \c component (its index there) and \c graph_generation.
    */
    private *hash<auto> publishedGraphView(string context_path,
            hash<SourceOrderContext> context_info, hash<SourceOrderComponents> components,
            int component) {
        loadOrBuildGraph(context_path, context_info);
        if (!depfile_edges_frozen) {
            return NOTHING;
        }
        hash<string, bool> members = map {string($1): True},
            components.members[component];
        list<list<int>> edges = ();
        foreach list<int> edge in (depfile_contract_edges) {
            if (!exists members{string(edge[1])}) {
                push edges, edge;
            }
        }
        edges += collectDepfileContractEdges(context_info.outputs, members);
        string generation = contractEdgeGeneration(edges, context_info.outputs);
        if (generation == graphGeneration(context_path, context_info)) {
            return NOTHING;
        }
        hash<SourceOrderGraph> graph = loadSummaryGraph(context_path, context_info);
        applyContractEdges(edges, \graph);
        hash<SourceOrderComponents> live = buildComponents(graph, context_info.outputs);
        string key = components.component_keys[component];
        for (int index = 0; index < live.component_keys.size(); ++index) {
            if (live.component_keys[index] == key) {
                return (
                    "components": live,
                    "component": index,
                    "graph_generation": generation,
                );
            }
        }
        return NOTHING;
    }

    #! Publishes the generation record for \a component; the build's commit point.
    /** \a expected is the SOURCE token the caller computed before it compiled
        (see componentSourceToken()). When it no longer matches, an agent outside
        the build rewrote a member source while qcc was reading it, so the
        artifacts on disk describe neither generation: nothing is published and
        the caller is told to rebuild rather than left to discover a lie later.
        This compare-and-swap on one identity replaces the per-file before/after
        snapshot comparison that the retry loop used to drive.

        \a expected_graph is the depfile-edge generation the caller planned
        against. A mismatch is not an external edit: it means the build's own
        dependency graph moved between planning and publication, so the compile
        may have used a preload that the current graph would not have chosen.
        That is reported as its own condition rather than as moved sources,
        because the two have entirely different causes and remedies.

        The record itself stores the full generation token, recomputed here, so it
        names the graph the artifacts were actually published against -- including
        the edges the compile just wrote to its own members' depfiles, which a frozen
        graph does not have yet: see publishedGraphView().

        \return \c "published", \c "moved" when \a expected no longer holds,
        \c "graph-transition" when \a expected_graph no longer holds, or
        \c "incomplete: PATH" naming the first artifact the component did not
        leave behind.
    */
    string publishGeneration(hash<SourceOrderContext> context_info,
            string context_path, hash<SourceOrderComponents> components, int component,
            *string expected, *string expected_graph = NOTHING) {
        if (exists expected
                && expected != componentSourceToken(components, context_info,
                    component)) {
            return "moved";
        }
        if (exists expected_graph
                && expected_graph != graphGeneration(context_path, context_info)) {
            return "graph-transition";
        }
        string graph_generation = graphGeneration(context_path, context_info);
        hash<auto> generation;
        *hash<auto> view = publishedGraphView(context_path, context_info, components,
            component);
        if (exists view) {
            generation = componentGeneration(view.components, context_info,
                view.component);
            graph_generation = view.graph_generation;
        } else {
            generation = componentGeneration(components, context_info, component);
        }
        list<string> outputs = ();
        foreach int member in (components.members[component]) {
            foreach string path in (memberArtifacts(context_info.outputs[member])) {
                if (!is_file(path)) {
                    # Naming the artifact matters: a compile mode that does not
                    # emit one sidecar cannot publish a generation at all, and
                    # "incomplete" alone does not say which mode is at fault.
                    return "incomplete: " + path;
                }
            }
            push outputs, absoluteNormalized(context_info.outputs[member]);
        }
        atomicWriteIfChanged(
            generationRecordPath(context_info, context_path, components, component),
            make_json((
                "format": 1,
                "scc": components.component_keys[component],
                "generation": generation.token,
                # Which dependency graph the artifacts were published against.
                # Currency deliberately does not compare it: a depfile edge set
                # that changed elsewhere in the group is not a reason to
                # recompile this component. It is recorded so a completed build
                # can be checked for having published one coherent graph.
                "graph_generation": graph_generation,
                "members": sort(outputs),
                "manifest": parse_json(generation.manifest),
            )) + "\n");
        return "published";
    }

    #! True when the component that publishes \a target is current.
    /** Member currency is a property of the component, never of nine files
        compared against their inputs one at a time: the members of a cyclic
        component are published as one generation, so asking the question per
        file cannot describe the answer.
    */
    bool artifactCurrent(string context_path, hash<SourceOrderContext> context_info,
            int target, *string bootstrap_stamp) {
        hash<SourceOrderComponents> components = sourceComponents(context_path,
            context_info);
        return generationCurrent(context_info, context_path, components,
            components.component_of[target], bootstrap_stamp);
    }

    bool batchArtifactCurrent(string context_path,
            hash<SourceOrderContext> context_info, int target,
            string bootstrap_stamp) {
        return artifactCurrent(context_path, context_info, target, bootstrap_stamp);
    }
}

sub atomicWriteIfChanged(string path, string content) {
    if (is_file(path) && ReadOnlyFile::readTextFile(path) == content) {
        return;
    }
    mkdir(dirname(path), 0777, True);
    string temporary = sprintf("%s.%d.tmp", path, getpid());
    on_error try { unlink(temporary); } catch (hash<ExceptionInfo> ex) {}
    {
        File file();
        file.open2(temporary, O_CREAT | O_TRUNC | O_WRONLY, 0666, "UTF-8");
        file.write(content);
    }
    rename(temporary, path);
}

#! \a path escaped as a make depfile target or prerequisite.
string sub makeDepfilePath(string path) {
    return replace(replace(replace(path, "$", "$$"), "#", "\\#"), " ", "\\ ");
}

#! One make depfile rule: \a target depends on every path in \a inputs.
/** Spaces and \c # are backslash-escaped and \c $ is doubled, which is what
    both make and CMake's depfile reader expect of a prerequisite.
*/
string sub makeDepfile(string target, list<string> inputs) {
    string text = makeDepfilePath(target) + ":";
    foreach string input in (inputs) {
        text += " \\\n    " + makeDepfilePath(input);
    }
    return text + "\n";
}

string sub cmakeQuote(string value) {
    string result;
    for (int offset = 0; offset < value.size(); ++offset) {
        int byte = value.getByte(offset);
        if (byte == 0x5c || byte == 0x22) {
            result += "\\";
        }
        result += chr(byte);
    }
    return result;
}

sub usage(*string error = NOTHING, bool success = False) {
    if (exists error) {
        stderr.printf("%s: %s\n", get_script_name(), error);
    }
    string name = get_script_name();
    string text = sprintf(
        "usage: %s [--direct|--build-map|--artifact-current] CONTEXT TARGET_OUTPUT\n"
        "       %s --batch-artifact-current STAMP CONTEXT TARGET_OUTPUT\n"
        "       %s --direct-map-cmake PREFIX CONTEXT\n"
        "       %s --build-direct-map-cmake PREFIX CONTEXT\n"
        "       %s --source-symbol-manifest FILE CONTEXT\n"
        "       %s --scc-map-cmake PREFIX CONTEXT\n"
        "       %s --cmake-plan GROUP CONTEXT\n"
        "       %s --scc-generation-map FILE CONTEXT\n"
        "       %s [--scc-publish-set|--scc-current-set|--scc-preload-set|--scc-convex-set\n"
        "           |--scc-order-set] CONTEXT KEY_FILE\n"
        "       %s [--scc-map|--scc-publish-all|--scc-generation-dir\n"
        "           |--scc-current-all|--scc-stale|--scc-source-stale]\n"
        "           [--batch-stamp STAMP] [--rebuild-closure] CONTEXT\n"
        "       %s --scc-for CONTEXT TARGET_OUTPUT\n"
        "       %s [--scc-members|--scc-prerequisites|--scc-preload\n"
        "           |--scc-generation|--scc-generation-token|--scc-source-token\n"
        "           |--scc-record|--scc-lock|--scc-compile-plan]\n"
        "           [--batch-stamp STAMP] CONTEXT SCC\n"
        "       %s --scc-current [--batch-stamp STAMP] [--source-deps-only]\n"
        "           CONTEXT SCC\n"
        "       %s --scc-publish [--expect TOKEN] [--expect-graph GENERATION]\n"
        "           CONTEXT SCC\n"
        "       %s --scc-graph-generation CONTEXT\n"
        "       %s --scc-freeze-graph SNAPSHOT [--batch-stamp STAMP] CONTEXT\n"
        "       %s --scc-external-inputs STAMP CONTEXT\n"
        "\n"
        "SCC selects a strongly connected component of the required-edge graph by\n"
        "its index or by its key. Only a key is stable across a build: component\n"
        "indexes are a function of the graph, which the build's own depfiles\n"
        "change.\n"
        "\n"
        "--scc-convex-set prints the keys of the components in KEY_FILE that one\n"
        "parse can compile together: a component is left out when something it\n"
        "would preload was itself compiled against another listed component, whose\n"
        "previous declarations the preloaded object would bring back.  What is left\n"
        "out stays stale for the next pass.\n"
        "\n"
        "--scc-order-set prints the keys in KEY_FILE in the order standalone\n"
        "compiles of them must run: a component follows every listed component it\n"
        "preloads, over content dependencies and load requirements as well as\n"
        "required edges, so no compile reads a listed provider's previous object.\n"
        "\n"
        "Exit 75 means the member sources moved away from the --expect source\n"
        "token -- an agent outside the build edited them. Exit 76 means the\n"
        "dependency graph moved away from --expect-graph, or that a component key\n"
        "no longer names a component; the compiled artifacts are not publishable\n"
        "in either case, but only 75 implicates anything outside the build.\n"
        "\n"
        "--source-deps-only leaves build inputs from outside the group to the\n"
        "build tool, which is what a recipe running behind the group coordinator\n"
        "wants: the coordinator already took those files as dependencies, and a\n"
        "second, stricter answer is what makes recipes compile behind its back.\n"
        "\n"
        "--rebuild-closure prefixes a stale listing with a rebuild-closure row\n"
        "naming how many components a rebuild of the stale set would leave stale,\n"
        "and how many components the group has.  --all-members lists every member\n"
        "of each stale component rather than one representative, which is what a\n"
        "caller compiling the stale set in one parse needs.\n"
        "Compiling a component rewrites its compile contract, so its consumers go\n"
        "stale too: the stale set is what must be rebuilt first, the closure is\n"
        "what will be rebuilt in total, and only the closure can decide whether a\n"
        "shared parse is cheaper than standalone compiles.\n"
        "\n"
        "--scc-freeze-graph records the current depfile-derived edge set as one\n"
        "named generation and prints its name. While QORE_QCC_GRAPH_SNAPSHOT names\n"
        "a readable snapshot for the current context, every command reads the graph\n"
        "from it instead of from the live depfiles, so a compile cannot change the\n"
        "decomposition another builder resolved against.\n"
        "\n"
        "--batch-stamp given to --scc-freeze-graph records which whole-group\n"
        "publication the snapshot was frozen from, dated by the STAMP.publication\n"
        "sidecar that qore-qo-batch-bootstrap advances when a shared parse has\n"
        "published the group -- not by the stamp, which the build tool also touches\n"
        "for ordering. A later shared parse rewrites every depfile in the group, so\n"
        "a snapshot naming an older publication is discarded for a live scan: the\n"
        "file outlives the build that wrote it, and a recipe the build tool\n"
        "scheduled ahead of the next freeze must not apply the previous build's\n"
        "edge set.\n"
        "\n"
        "--scc-external-inputs writes STAMP.d, a make depfile whose one rule names\n"
        "STAMP and every build input from outside the group that any member's\n"
        "depfile records -- the toolchain, loaded modules, stubs and includes.  The\n"
        "file is rewritten only when that set changes.\n",
        name, name, name, name, name, name, name, name, name, name, name, name, name,
        name, name, name);
    if (success) {
        printf("%s", text);
    } else {
        stderr.printf("%s", text);
    }
    exit(success ? 0 : 2);
}

#! Resolves an SCC selector, which is either a component index or a component key.
int sub findComponent(hash<SourceOrderComponents> components, string selector) {
    if (selector =~ /^[0-9]+$/) {
        int index = selector.toInt();
        return index < components.members.size() ? index : -1;
    }
    for (int component = 0; component < components.component_keys.size(); ++component) {
        if (components.component_keys[component] == selector) {
            return component;
        }
    }
    return -1;
}

#! Emits one dependency map as CMake variables.
string sub dependencyMapCMake(list<list<int>> orders, list<string> outputs,
        string prefix) {
    list<string> lines = ();
    for (int target = 0; target < orders.size(); ++target) {
        list<string> dependencies = ();
        foreach int provider in (orders[target]) {
            push dependencies, cmakeQuote(outputs[provider]);
        }
        push lines, sprintf("set(%s_%d \"%s\")", prefix, target,
            join(";", dependencies));
    }
    return join("\n", lines) + "\n";
}

#! Emits the component decomposition as CMake variables.
/** CMake needs the decomposition at configure time to declare one target per
    component and to register each component's generation record as an expected
    managed output. The project's minimum CMake version predates string(JSON),
    so the helper emits set() lines the way --direct-map-cmake does rather than
    making the build parse JSON.
*/
string sub componentMapCMake(SourceOrderEngine engine,
        hash<SourceOrderComponents> components, hash<SourceOrderContext> context_info,
        string context_path, string prefix) {
    list<string> lines = ();
    int count = components.members.size();
    push lines, sprintf("set(%s_COUNT \"%d\")", prefix, count);
    push lines, sprintf("set(%s_GENERATION_DIR \"%s\")", prefix,
        cmakeQuote(engine.generationDir(context_info, context_path)));
    list<string> records = ();
    list<string> locks = ();
    for (int component = 0; component < count; ++component) {
        push records, cmakeQuote(
            engine.generationRecordPath(context_info, context_path, components,
                component));
        push locks, cmakeQuote(
            engine.generationLockPath(context_info, context_path, components,
                component));
        list<string> outputs = ();
        list<string> predecessors = ();
        foreach int node in (components.members[component]) {
            push outputs, cmakeQuote(context_info.outputs[node]);
        }
        foreach int predecessor in (components.predecessors[component]) {
            push predecessors, string(predecessor);
        }
        push lines, sprintf("set(%s_KEY_%d \"%s\")", prefix, component,
            components.component_keys[component]);
        push lines, sprintf("set(%s_OUTPUTS_%d \"%s\")", prefix, component,
            join(";", outputs));
        push lines, sprintf("set(%s_PREDECESSORS_%d \"%s\")", prefix, component,
            join(";", predecessors));
    }
    push lines, sprintf("set(%s_RECORDS \"%s\")", prefix, join(";", records));
    push lines, sprintf("set(%s_LOCKS \"%s\")", prefix, join(";", locks));
    return join("\n", lines) + "\n";
}

#! The published generation of every component in the group, as stable text.
/** This is the object set's single identity. Every consumer of the set -- each
    qo-link aggregate, each script aggregate, each generated native registration
    aggregate, and the final native link -- takes this file as a qcc manifest
    input, so a consumer may skip only while its own manifest names the same
    completed generations. Sampling member files one at a time cannot express
    that: the members of one component are published together, and nine
    per-member sidecars do not say which generation they belong to.
*/
string sub componentGenerationMap(SourceOrderEngine engine,
        hash<SourceOrderComponents> components, hash<SourceOrderContext> context_info) {
    hash<string, hash<auto>> generations =
        engine.allComponentGenerations(components, context_info);
    hash<string, string> tokens = {};
    for (int component = 0; component < components.members.size(); ++component) {
        tokens{components.component_keys[component]} =
            generations{string(component)}.token;
    }
    list<string> lines = ("format=1",);
    foreach string key in (sort(tokens.keys())) {
        push lines, sprintf("generation=%s %s", key, tokens{key});
    }
    return join("\n", lines) + "\n";
}

hash<auto> sub componentMapData(SourceOrderEngine engine,
        hash<SourceOrderComponents> components, hash<SourceOrderContext> context_info) {
    hash<string, hash<auto>> generations =
        engine.allComponentGenerations(components, context_info);
    list<hash<auto>> entries = ();
    for (int component = 0; component < components.members.size(); ++component) {
        list<hash<auto>> members = ();
        foreach int node in (components.members[component]) {
            push members, (
                "index": node,
                "input": context_info.inputs[node],
                "output": context_info.outputs[node],
            );
        }
        list<string> predecessors = ();
        foreach int predecessor in (components.predecessors[component]) {
            push predecessors, components.component_keys[predecessor];
        }
        list<string> prerequisites = ();
        foreach int prerequisite in (engine.componentPrerequisites(components, component)) {
            push prerequisites, components.component_keys[prerequisite];
        }
        push entries, (
            "index": component,
            "scc": components.component_keys[component],
            "generation": generations{string(component)}.token,
            "members": members,
            "predecessors": predecessors,
            "prerequisites": prerequisites,
        );
    }
    return (
        "format": 1,
        "components": entries,
        "topological_order": components.topological_order,
    );
}

int sub findTarget(list<string> outputs, string target_output) {
    string target = canonical(target_output);
    for (int index = 0; index < outputs.size(); ++index) {
        if (canonical(outputs[index]) == target) {
            return index;
        }
    }
    return -1;
}

int sub main() {
    int started = clock_getmicros_monotonic();
    if (ARGV.size() == 3 && ARGV[0] == "--source-summary") {
        SourceSymbolManifestGenerator scanner();
        printf("%s\n", make_json(scanner.scanDependencySummaryForContext(ARGV[1], ARGV[2])));
        return 0;
    }

    bool direct = False;
    bool build_map = False;
    bool artifact_current = False;
    bool cmake_plan = False;
    *string component_command;
    *string component_map_prefix;
    *string component_generation_map;
    *string graph_snapshot_output;
    *string external_inputs_stamp;
    *string expected_generation;
    *string expected_graph_generation;
    *string direct_map_prefix;
    *string build_direct_map_prefix;
    *string source_symbol_manifest;
    *string batch_bootstrap_stamp;
    bool source_deps_only = False;
    bool rebuild_closure = False;
    #! Emit every member of a stale component rather than one representative.
    /** A caller that compiles components one at a time wants the representative:
        building any member builds the component.  A caller that compiles the
        stale set in ONE parse has to name every member, because the parse is the
        unit that publishes them.
    */
    bool all_members = False;
    list<string> positional = ();
    for (int index = 0; index < ARGV.size(); ++index) {
        string arg = ARGV[index];
        if (arg == "-h" || arg == "--help") {
            usage(NOTHING, True);
        } else if (arg == "--direct") {
            direct = True;
        } else if (arg == "--build-map") {
            build_map = True;
        } else if (arg == "--artifact-current") {
            artifact_current = True;
        } else if (arg == "--cmake-plan") {
            cmake_plan = True;
        } else if (arg == "--source-deps-only") {
            source_deps_only = True;
        } else if (arg == "--rebuild-closure") {
            rebuild_closure = True;
        } else if (arg == "--all-members") {
            all_members = True;
        } else if (arg == "--scc-map" || arg == "--scc-for" || arg == "--scc-members"
                || arg == "--scc-prerequisites" || arg == "--scc-generation"
                || arg == "--scc-generation-token" || arg == "--scc-generation-dir"
                || arg == "--scc-current" || arg == "--scc-publish"
                || arg == "--scc-publish-all" || arg == "--scc-record"
                || arg == "--scc-lock" || arg == "--scc-preload"
                || arg == "--scc-current-all" || arg == "--scc-source-token"
                || arg == "--scc-stale" || arg == "--scc-source-stale"
                || arg == "--scc-compile-plan" || arg == "--scc-graph-generation"
                || arg == "--scc-publish-set" || arg == "--scc-current-set"
                || arg == "--scc-preload-set" || arg == "--scc-convex-set"
                || arg == "--scc-order-set") {
            string requested = arg.substr(6);
            if (exists component_command && component_command != requested) {
                usage(sprintf("--scc-%s conflicts with --scc-%s",
                    requested, component_command));
            }
            component_command = requested;
        } else if (arg == "--direct-map-cmake"
                || arg == "--build-direct-map-cmake"
                || arg == "--source-symbol-manifest"
                || arg == "--batch-artifact-current"
                || arg == "--scc-map-cmake"
                || arg == "--scc-generation-map"
                || arg == "--scc-freeze-graph"
                || arg == "--scc-external-inputs") {
            if (++index >= ARGV.size()) {
                usage(sprintf("argument expected after %s", arg));
            }
            if (arg == "--direct-map-cmake") {
                direct_map_prefix = ARGV[index];
            } else if (arg == "--scc-map-cmake") {
                component_map_prefix = ARGV[index];
            } else if (arg == "--build-direct-map-cmake") {
                build_direct_map_prefix = ARGV[index];
            } else if (arg == "--source-symbol-manifest") {
                source_symbol_manifest = ARGV[index];
            } else if (arg == "--scc-generation-map") {
                component_generation_map = ARGV[index];
            } else if (arg == "--scc-freeze-graph") {
                graph_snapshot_output = ARGV[index];
            } else if (arg == "--scc-external-inputs") {
                external_inputs_stamp = ARGV[index];
            } else {
                batch_bootstrap_stamp = ARGV[index];
            }
        } else if (arg == "--expect" || arg == "--expect-graph"
                || arg == "--batch-stamp") {
            if (++index >= ARGV.size()) {
                usage(sprintf("argument expected after %s", arg));
            }
            if (arg == "--expect") {
                expected_generation = ARGV[index];
            } else if (arg == "--expect-graph") {
                expected_graph_generation = ARGV[index];
            } else {
                batch_bootstrap_stamp = ARGV[index];
            }
        } else if (arg.startsWith("--expect=")) {
            expected_generation = arg.substr(9);
        } else if (arg.startsWith("--expect-graph=")) {
            expected_graph_generation = arg.substr(15);
        } else if (arg.startsWith("--batch-stamp=")) {
            batch_bootstrap_stamp = arg.substr(14);
        } else if (arg.startsWith("--scc-map-cmake=")) {
            component_map_prefix = arg.substr(16);
        } else if (arg.startsWith("--direct-map-cmake=")) {
            direct_map_prefix = arg.substr(19);
        } else if (arg.startsWith("--build-direct-map-cmake=")) {
            build_direct_map_prefix = arg.substr(25);
        } else if (arg.startsWith("--source-symbol-manifest=")) {
            source_symbol_manifest = arg.substr(25);
        } else if (arg.startsWith("--scc-generation-map=")) {
            component_generation_map = arg.substr(21);
        } else if (arg.startsWith("--scc-freeze-graph=")) {
            graph_snapshot_output = arg.substr(19);
        } else if (arg.startsWith("--scc-external-inputs=")) {
            external_inputs_stamp = arg.substr(22);
        } else if (arg.startsWith("--batch-artifact-current=")) {
            batch_bootstrap_stamp = arg.substr(25);
        } else if (arg.startsWith("-")) {
            usage("unrecognized argument: " + arg);
        } else {
            push positional, arg;
        }
    }
    if (!positional) {
        usage("context is required");
    }
    if (cmake_plan && positional.size() != 2) {
        usage("--cmake-plan requires a group and a context argument");
    }
    string context_path = cmake_plan ? positional[1] : positional[0];
    hash<SourceOrderContext> context_info = parseContext(context_path);
    if (ENV.QORE_QO_SOURCE_ORDER_TIMING) {
        stderr.printf("main argument+context=%d us\n", clock_getmicros_monotonic() - started);
    }

    if (cmake_plan) {
        string group = positional[0];
        if (group !~ /^[A-Za-z_][A-Za-z0-9_]*$/) {
            usage(sprintf("invalid CMake group identifier: %y", group));
        }
        SourceOrderEngine engine();
        hash<auto> plan = engine.cmakePlan(context_path, context_info);
        hash<SourceOrderComponents> components = plan.components;
        string output_dir = dirname(context_path);
        atomicWriteIfChanged(output_dir + DirSep + "direct-deps.cmake",
            dependencyMapCMake(plan.direct_orders, context_info.outputs,
                "QORE_QCC_DIRECT_DEPS_" + group));
        atomicWriteIfChanged(output_dir + DirSep + "build-deps.cmake",
            dependencyMapCMake(plan.build_direct_orders, context_info.outputs,
                "QORE_QCC_BUILD_DEPS_" + group));
        atomicWriteIfChanged(output_dir + DirSep + "scc-map.cmake",
            componentMapCMake(engine, components, context_info, context_path,
                "QORE_QCC_SCC_" + group));
        string symbols = output_dir + DirSep + "source-symbols.manifest";
        SourceSymbolManifestGenerator generator();
        atomicWriteIfChanged(symbols,
            generator.generateCached(context_path, context_info.inputs,
                symbols + ".cache"));
        return 0;
    }

    if (exists source_symbol_manifest) {
        if (positional.size() != 1) {
            usage("--source-symbol-manifest accepts only a context argument");
        }
        SourceSymbolManifestGenerator generator();
        list<string> inputs = ENV.QORE_QO_SOURCE_ORDER_INPUT
            ? (ENV.QORE_QO_SOURCE_ORDER_INPUT,)
            : context_info.inputs;
        atomicWriteIfChanged(source_symbol_manifest,
            generator.generateCached(context_path, inputs,
                source_symbol_manifest + ".cache"));
        return 0;
    }

    SourceOrderEngine engine();
    if (exists external_inputs_stamp) {
        if (positional.size() != 1) {
            usage("--scc-external-inputs accepts only a context argument");
        }
        atomicWriteIfChanged(external_inputs_stamp + ".d",
            makeDepfile(external_inputs_stamp, engine.groupExternalInputs(context_info)));
        return 0;
    }
    if (exists graph_snapshot_output) {
        if (positional.size() != 1) {
            usage("--scc-freeze-graph accepts only a context argument");
        }
        # Freezing reads the live depfiles by definition, so it must run where
        # no compile is in flight: the group coordinator performs it between
        # phases, and the whole-group batch -- which holds the group lock and
        # rewrites every depfile -- runs without a snapshot at all.
        printf("%s\n",
            engine.writeGraphSnapshot(graph_snapshot_output, context_info,
                batch_bootstrap_stamp));
        return 0;
    }
    if (exists component_generation_map) {
        if (positional.size() != 1) {
            usage("--scc-generation-map accepts only a context argument");
        }
        atomicWriteIfChanged(component_generation_map,
            componentGenerationMap(engine,
                engine.sourceComponents(context_path, context_info), context_info));
        return 0;
    }
    if (exists component_map_prefix) {
        if (positional.size() != 1) {
            usage("--scc-map-cmake accepts only a context argument");
        }
        if (component_map_prefix !~ /^[A-Za-z_][A-Za-z0-9_]*$/) {
            usage(sprintf("invalid CMake variable prefix: %y", component_map_prefix));
        }
        printf("%s", componentMapCMake(engine,
            engine.sourceComponents(context_path, context_info), context_info,
            context_path, component_map_prefix));
        return 0;
    }
    if (exists component_command) {
        hash<SourceOrderComponents> components =
            engine.sourceComponents(context_path, context_info);
        if (component_command == "map" || component_command == "publish-all"
                || component_command == "generation-dir"
                || component_command == "current-all" || component_command == "stale"
                || component_command == "source-stale"
                || component_command == "graph-generation") {
            if (positional.size() != 1) {
                usage(sprintf("--scc-%s accepts only a context argument",
                    component_command));
            }
            switch (component_command) {
                case "map":
                    printf("%s\n",
                        make_json(componentMapData(engine, components, context_info)));
                    return 0;
                case "generation-dir":
                    printf("%s\n", engine.generationDir(context_info, context_path));
                    return 0;
                case "graph-generation":
                    printf("%s\n", engine.graphGeneration(context_path, context_info));
                    return 0;
                case "current-all":
                    # One invocation for the whole group: a per-output probe
                    # would reload and rescan the graph once per source, which
                    # for a large group costs more than the compile it guards.
                    return engine.allGenerationsCurrent(context_info, context_path,
                        components, batch_bootstrap_stamp) ? 0 : 1;
                case "stale":
                case "source-stale": {
                    # One group-wide currency pass.  Each row contains enough
                    # information for the coordinator to build one representative
                    # member without another graph scan.  The source-only mode is
                    # used behind CMake's dependency barrier: CMake and the batch
                    # target already track toolchain/module/stub depfiles, so
                    # reparsing every member depfile here would duplicate that
                    # work on every one-source incremental build.
                    list<int> stale = engine.staleGenerations(context_info,
                        context_path, components, batch_bootstrap_stamp,
                        component_command == "stale");
                    # How much of the group a rebuild of that set actually
                    # reaches.  Emitted only on request, and ahead of the rows,
                    # so a caller that only wants the stale set keeps the output
                    # it has always parsed.
                    if (rebuild_closure) {
                        # The group's component count rides along: the coordinator
                        # scales its "the closure is the whole group anyway"
                        # decision to the group, and asking for the count
                        # separately would mean a second graph scan.
                        printf("rebuild-closure\t%d\t%d\n",
                            engine.componentRebuildClosure(components, stale).size(),
                            components.members.size());
                    }
                    foreach int component in (stale) {
                        list<int> members = all_members
                            ? components.members[component]
                            : (components.members[component][0],);
                        foreach int member in (members) {
                            printf("%d\t%s\t%d\t%s\t%s\n", component,
                                components.component_keys[component],
                                components.members[component].size(),
                                context_info.inputs[member],
                                context_info.outputs[member]);
                        }
                    }
                    return 0;
                }
                case "publish-all":
                    # A whole-group compile republishes every component at once,
                    # so every generation record has to be committed together;
                    # a partial sweep would leave components claiming a
                    # generation the group no longer has.
                    for (int component = 0; component < components.members.size();
                            ++component) {
                        string result = engine.publishGeneration(context_info,
                            context_path, components, component, NOTHING);
                        if (result != "published") {
                            stderr.printf("%s: cannot publish component %s: %s\n",
                                get_script_name(),
                                components.component_keys[component], result);
                            return result == "moved" ? 75 : 1;
                        }
                    }
                    return 0;
            }
        }
        if (component_command == "publish-set" || component_command == "current-set"
                || component_command == "preload-set" || component_command == "convex-set"
                || component_command == "order-set") {
            # A shared parse over PART of a group publishes exactly the
            # components it compiled.  Naming them in a file rather than on the
            # command line keeps a subset of any size addressable, and resolving
            # them all in one process is what keeps the cost of a partial batch
            # proportional to the partial batch.
            if (positional.size() != 2) {
                usage(sprintf("--scc-%s requires a context and a file naming "
                    "component keys", component_command));
            }
            list<int> selected = ();
            foreach string line in (
                    ReadOnlyFile::readTextFile(positional[1]).split("\n")) {
                string key = trim(line);
                if (!key) {
                    continue;
                }
                int resolved = findComponent(components, key);
                if (resolved < 0) {
                    # As for a single component: a key the current graph does not
                    # name is a transition, and the caller's answer to it is to
                    # re-resolve rather than to fail the build.
                    stderr.printf("%s: component %s is not present in the current "
                        "dependency graph %s; the decomposition changed since it "
                        "was resolved\n", get_script_name(), key,
                        engine.graphGeneration(context_path, context_info));
                    return 76;
                }
                push selected, resolved;
            }
            if (component_command == "preload-set") {
                foreach string output in (
                        engine.componentPreloadOutputs(components, context_info, selected)) {
                    printf("%s\n", output);
                }
                return 0;
            }
            if (component_command == "order-set") {
                foreach int component in (
                        engine.preloadCompileOrder(components, context_info, selected)) {
                    printf("%s\n", components.component_keys[component]);
                }
                return 0;
            }
            if (component_command == "convex-set") {
                foreach int component in (
                        engine.convexComponentSubset(components, context_info, selected)) {
                    printf("%s\n", components.component_keys[component]);
                }
                return 0;
            }
            if (component_command == "current-set") {
                foreach int resolved in (selected) {
                    if (!engine.generationCurrent(context_info, context_path,
                            components, resolved, batch_bootstrap_stamp,
                            !source_deps_only)) {
                        return 1;
                    }
                }
                return 0;
            }
            foreach int resolved in (selected) {
                string result = engine.publishGeneration(context_info,
                    context_path, components, resolved, NOTHING);
                if (result != "published") {
                    stderr.printf("%s: cannot publish component %s: %s\n",
                        get_script_name(), components.component_keys[resolved],
                        result);
                    return result == "moved" ? 75 : 1;
                }
            }
            return 0;
        }
        if (positional.size() != 2) {
            usage(sprintf("--scc-%s requires a context and a %s argument",
                component_command,
                component_command == "for" ? "target output" : "component"));
        }
        int component;
        if (component_command == "for") {
            int target = findTarget(context_info.outputs, positional[1]);
            if (target < 0) {
                stderr.printf("%s: target output not present in context: %s\n",
                    get_script_name(), positional[1]);
                return 1;
            }
            component = components.component_of[target];
        } else {
            component = findComponent(components, positional[1]);
            if (component < 0) {
                # A key that no longer names a component is a graph transition,
                # not a bad argument: the build's own depfiles changed the SCC
                # decomposition since the caller resolved its identity. An index
                # that does not resolve really is a bad argument, because an
                # index is never a durable name for a component.
                if (positional[1] =~ /^[0-9]+$/) {
                    stderr.printf("%s: no such strongly connected component: %s\n",
                        get_script_name(), positional[1]);
                    return 1;
                }
                stderr.printf("%s: component %s is not present in the current "
                    "dependency graph %s; the decomposition changed since it was "
                    "resolved\n", get_script_name(), positional[1],
                    engine.graphGeneration(context_path, context_info));
                return 76;
            }
        }
        switch (component_command) {
            case "for":
                printf("%d\t%s\t%d\n", component, components.component_keys[component],
                    components.members[component].size());
                return 0;
            case "members":
                foreach int node in (components.members[component]) {
                    printf("%s\t%s\n", context_info.inputs[node],
                        context_info.outputs[node]);
                }
                return 0;
            case "preload":
                # Everything this component's parse must resolve against, in
                # dependency order, and deliberately not the component's own
                # members: a component compiles its own members together, so
                # preloading a sibling would mean reading the generation this
                # compile is about to replace.
                foreach string output in (
                        engine.componentPreloadOutputs(components, context_info, component)) {
                    printf("%s\n", output);
                }
                return 0;
            case "prerequisites":
                foreach int prerequisite in (
                        engine.componentPrerequisites(components, component)) {
                    printf("%d\t%s\n", prerequisite, components.component_keys[prerequisite]);
                }
                return 0;
            case "generation":
                printf("%s\n",
                    engine.componentGeneration(components, context_info, component).manifest);
                return 0;
            case "generation-token":
                printf("%s\n",
                    engine.componentGeneration(components, context_info, component).token);
                return 0;
            case "source-token":
                printf("%s\n",
                    engine.componentSourceToken(components, context_info, component));
                return 0;
            case "record":
                printf("%s\n", engine.generationRecordPath(context_info, context_path,
                    components, component));
                return 0;
            case "lock":
                printf("%s\n", engine.generationLockPath(context_info, context_path,
                    components, component));
                return 0;
            case "compile-plan":
                # One locked standalone-compile snapshot replaces separate
                # current/token/preload/direct queries.  Every one of those
                # queries otherwise reloads the same large graph and rescans
                # every member depfile in a fresh Qore process.
                if (components.members[component].size() != 1) {
                    stderr.printf("%s: component %s has %d members; use the shared batch\n",
                        get_script_name(), components.component_keys[component],
                        components.members[component].size());
                    return 1;
                }
                if (engine.generationCurrent(context_info, context_path, components,
                        component, batch_bootstrap_stamp, !source_deps_only)) {
                    printf("current\t1\n");
                    return 0;
                }
                printf("current\t0\n");
                printf("source-token\t%s\n",
                    engine.componentSourceToken(components, context_info, component));
                # The graph this plan's preload and prerequisite closure were
                # selected from. Publication refuses to commit against a
                # different one, so the compile cannot be published as if it had
                # been planned from the graph that superseded it.
                printf("graph-generation\t%s\n",
                    engine.graphGeneration(context_path, context_info));
                foreach string output in (
                        engine.componentPreloadOutputs(components, context_info, component)) {
                    printf("preload\t%s\n", output);
                }
                int member = components.members[component][0];
                foreach int provider in (
                        engine.directOrder(context_path, context_info, member)) {
                    printf("direct\t%s\n", context_info.outputs[provider]);
                }
                return 0;
            case "current":
                return engine.generationCurrent(context_info, context_path, components,
                    component, batch_bootstrap_stamp, !source_deps_only) ? 0 : 1;
            case "publish": {
                string result = engine.publishGeneration(context_info, context_path,
                    components, component, expected_generation,
                    expected_graph_generation);
                if (result == "published") {
                    return 0;
                }
                if (result == "graph-transition") {
                    stderr.printf("%s: cannot publish component %s: planned against "
                        "dependency graph %s but the current graph is %s\n",
                        get_script_name(), components.component_keys[component],
                        expected_graph_generation,
                        engine.graphGeneration(context_path, context_info));
                    return 76;
                }
                stderr.printf("%s: cannot publish component %s: %s\n",
                    get_script_name(), components.component_keys[component], result);
                # 75 is the build's established "member sources moved, this
                # attempt is not publishable" signal; 76 is its internal
                # counterpart above; anything else is a real failure.
                return result == "moved" ? 75 : 1;
            }
        }
    }
    if (exists direct_map_prefix || exists build_direct_map_prefix) {
        if (positional.size() != 1) {
            usage("direct-map output accepts only a context argument");
        }
        string map_prefix = exists build_direct_map_prefix
            ? build_direct_map_prefix : direct_map_prefix;
        if (map_prefix !~ /^[A-Za-z_][A-Za-z0-9_]*$/) {
            usage(sprintf("invalid CMake variable prefix: %y", map_prefix));
        }
        int order_started = clock_getmicros_monotonic();
        list<list<int>> orders = exists build_direct_map_prefix
            ? engine.allBuildDirectOrders(context_path, context_info)
            : engine.allDirectOrders(context_path, context_info);
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) {
            stderr.printf("main direct orders=%d us\n",
                clock_getmicros_monotonic() - order_started);
        }
        int output_started = clock_getmicros_monotonic();
        printf("%s", dependencyMapCMake(orders, context_info.outputs, map_prefix));
        if (ENV.QORE_QO_SOURCE_ORDER_TIMING) {
            stderr.printf("main direct output=%d us\n",
                clock_getmicros_monotonic() - output_started);
        }
        return 0;
    }

    if (positional.size() != 2) {
        usage("target output is required unless --direct-map-cmake is used");
    }
    int target = findTarget(context_info.outputs, positional[1]);
    if (target < 0) {
        stderr.printf("%s: target output not present in context: %s\n",
            get_script_name(), positional[1]);
        return 1;
    }
    if (build_map) {
        foreach int index in (engine.prerequisiteOrder(context_path, context_info, target)) {
            printf("%s\t%s\n", context_info.inputs[index], context_info.outputs[index]);
        }
        return 0;
    }
    if (exists batch_bootstrap_stamp) {
        return engine.batchArtifactCurrent(context_path, context_info, target,
            batch_bootstrap_stamp) ? 0 : 1;
    }
    if (artifact_current) {
        return engine.artifactCurrent(context_path, context_info, target) ? 0 : 1;
    }
    list<int> order = direct
        ? engine.directOrder(context_path, context_info, target)
        : engine.prerequisiteOrder(context_path, context_info, target);
    foreach int index in (order) {
        printf("%s\n", context_info.outputs[index]);
    }
    return 0;
}

try {
    return main();
} catch (hash<ExceptionInfo> ex) {
    stderr.printf("%s: %s: %s\n", get_script_name(), ex.err, ex.desc);
    return 1;
}
