Files
mesh-host/internal/compose/composed.go
T
jschoubben 86380b66c1 Write each node's declaration at the Version its engine reads
The composer is the node-engine's own build, so a newer composer could hand
an older engine a field its strict decode refuses. The engine's record now
states the declaration Version it reads, and the composer writes node X's
declaration at the lower of its own Version and X's (1 when X states none),
leaving out what that Version lacks: an engine reading 1 gets no
drain-bound and runs on its own default.

Builds: design 47 H2 §813 (12); H-A-416 (2), H-A-419; mesh-contracts feat/47-H2 e6ed560e (the record's declaration-reads)
2026-11-22 01:17:49 +01:00

876 lines
34 KiB
Go

package compose
import (
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"sort"
"strings"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
engcomp "github.com/novox/mesh-host/internal/compositions"
"git.novox.be/novox/mesh-networking/modules/mesh-wireguard/go/overlay"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/declaration"
"github.com/novox/mesh-host/internal/compose/resolution"
"github.com/novox/mesh-host/internal/registryforms"
)
// Compositions is one node's compositions (novox/hq ADR 0539 clauses 1 and 2): its declaration composed over in, as
// the controller composes it, split into each module's composition at the fingerprint fps gives it and the node's own
// (`<node>.node`), by key (engcomp.Key). Each resource says its module, whatever the node reported it reads.
// A module fps gives no fingerprint for is not composed and is named in skipped, so a caller composing one module
// gets that one; but for a module the node runs inside its own composition (Node.InOwn, and the
// private network's always), which fps names at no fingerprint of the new form: its resources go into the node's own,
// their module taken off and their ids still naming it, and its filled paths with them, as the controller's composed
// writer folds them (issue 1126). Each module's Data says whether its manifest declares data. The compositions are unsigned
// (ADR 0593 §6) and not yet by digest (Composed.ByDigest).
func Compositions(in Input, node string, fps map[string]string, mode Mode) (out map[string]engcomp.Composed, skipped []string, err error) {
out, skipped, _, _, err = compositions(in, node, fps, mode, false)
return out, skipped, err
}
// ErrStoodIn is a composition that holds a stand-in for a value the input does not carry (an own secret, a grant's
// sealed copy, a vault box, the certificate, the bus's user list) or a port it does not give: what a send would make,
// never what may be applied.
var ErrStoodIn = errors.New("compose: the composition stands in for what its input does not carry")
// BusUsersStandIn is what a composition says it stood in for when its input carries no bus user list.
const BusUsersStandIn = "the bus's user list"
// CompositionsApplied is Compositions for a node that applies what it composed itself (novox/hq ADR 0547 §2, issue
// 1126): a declaration that stands in for anything (Declared.StoodIn, Foreseen, ForeseenPorts) is refused with
// ErrStoodIn, naming each, so a stand-in is never applied as if it were the value; but for the bus's user list
// (BusUsersStandIn), which the bus node holds out of every apply of a composition it made itself.
func CompositionsApplied(in Input, node string, fps map[string]string) (map[string]engcomp.Composed, []string, error) {
out, skipped, _, _, err := compositions(in, node, fps, Reading, true)
return out, skipped, err
}
// CompositionsShadow is CompositionsApplied for a composition that is compared and never applied (a node's answer to a
// assignment candidate, novox/hq ADR 0559 §4): composed in the Foreseeing mode, so an own secret never issued (a module
// the candidate adds) is a named stand-in rather than an error, and what it stands in for is answered (stood, sorted,
// the bus's user list left out) rather than refused, so the caller judges each stand-in: a value not yet issued for a
// module the candidate adds, or one missing for a module the node runs. A module whose every value is held composes
// as CompositionsApplied composes it: the modes differ only in an own secret never issued.
func CompositionsShadow(in Input, node string, fps map[string]string) (out map[string]engcomp.Composed, skipped, stood []string, err error) {
out, skipped, stood, _, err = compositions(in, node, fps, Foreseeing, false)
return out, skipped, stood, err
}
// CompositionsIn is the node's compositions in mode with what they stand in for answered (stood, sorted, the bus's user
// list left out) rather than refused: CompositionsShadow in Foreseeing, and in Reading what CompositionsApplied refuses
// before it is refused, so a caller that applies refuses each stand-in to the module it is for alone (issue 1126).
func CompositionsIn(in Input, node string, fps map[string]string, mode Mode) (out map[string]engcomp.Composed, skipped, stood []string, err error) {
out, skipped, stood, _, err = compositions(in, node, fps, mode, false)
return out, skipped, stood, err
}
// CompositionsHolding is CompositionsIn with the modules the node leaves out as they run, each with why: one whose claim cannot be
// held or whose credential was refused (issue 1966). Their compositions are not in out, so a caller that applies keeps what it last
// applied of each and says it held, as for any module refused alone.
func CompositionsHolding(in Input, node string, fps map[string]string, mode Mode) (out map[string]engcomp.Composed, skipped, stood []string, held map[string]string, err error) {
return compositions(in, node, fps, mode, false)
}
// Folds says whether a module the node runs inside its own composition (inOwn, Node.InOwn) is folded there at the
// fingerprint fp it is composed at: only at no fingerprint of the new form. At one (src2:) it has a composition of its
// own, composed from its build, so every reader of a build (frombus) takes the build in exactly where this says it is
// not folded (issue 1585: nats on novox, folded by the reader and composed at src2: here, refused for its server
// artifact no build had published).
func Folds(inOwn bool, fp string) bool {
return inOwn && !strings.HasPrefix(fp, meshcatalogclient.SourcePrefix2)
}
func compositions(in Input, node string, fps map[string]string, mode Mode, applied bool) (out map[string]engcomp.Composed, skipped, stood []string, heldBy map[string]string, err error) {
reading := in
reading.Nodes = append([]Node(nil), in.Nodes...)
found := false
inOwn := map[string]bool{}
held := map[string]bool{}
for i := range reading.Nodes {
if reading.Nodes[i].Name == node {
reading.Nodes[i].ReadsModules = true
found = true
for m, ok := range reading.Nodes[i].InOwn {
inOwn[m] = ok
}
for m, ok := range reading.Nodes[i].Held {
held[m] = ok
}
}
}
// The private network's module is built by nobody: no fingerprint of the new form ever names it.
inOwn[overlay.Name] = true
folds := func(module string) bool {
return module != "" && Folds(inOwn[module], fps[module])
}
if !found {
return nil, nil, nil, nil, fmt.Errorf("compose: the mesh has no node %q", node)
}
// A folded module built by a build of the old form (Node.RunsOwn) is left to the node: composed from what runs of it
// (Carried), so what it provides and requires still shapes the rest and what the others read of it (its published
// ports, the paths it owns) is what runs, and its resources are then the ones the node runs.
carried := map[string]bool{}
var runsOwn *engcomp.Composed
for i := range reading.Nodes {
n := &reading.Nodes[i]
if n.Name != node || n.RunsOwn == nil {
continue
}
runsOwn = n.RunsOwn
candidates := map[string]bool{}
for m := range inOwn {
candidates[m] = true
}
for m := range held {
candidates[m] = true
}
for m := range candidates {
// A held module is carried as it runs wherever the node's own runs it, folded or leaving the fold for a
// composition of its own (its want new, its names still unset): its stub is never what the node's own applies,
// and what the node's own applies never drops what runs of it (issue 1126, review of the apply; issue 1945).
heldHere := held[m] && RunsAnyOf(runsOwn, m)
if !folds(m) && !heldHere {
continue
}
man, ok := n.Kept[m]
if !ok {
man, ok = reading.Catalogue[m]
}
if !ok || (!NamesBuild(man) && !held[m]) {
continue
}
carried[m] = true
kept := make(map[string]catalogue.Manifest, len(n.Kept)+1)
for k, v := range n.Kept {
kept[k] = v
}
kept[m] = Carried(man, m, runsOwn)
n.Kept = kept
}
}
// A module composed as what runs of it contributes to the runtime what the runtime serves of it as it runs
// (Node.RunsTools); one of its own account is served by a runtime of its own, from its manifest as before.
for i := range reading.Nodes {
n := &reading.Nodes[i]
if n.Name != node || n.RunsTools == nil {
continue
}
kept := make(map[string]catalogue.Manifest, len(n.Kept))
for m, man := range n.Kept {
if man.Stubbed && man.RunsAs == "" && !keepsProgram(man) {
man.Bundles = runningBundles(n.RunsTools[m], reading.Catalogue[m])
}
kept[m] = man
}
n.Kept = kept
}
isCarried := func(module, id string) bool {
if module == "" {
module, _ = declaration.ModuleGuess(id)
}
return carried[module]
}
d, problems, err := ComposeIn(reading, node, mode)
if err != nil {
return nil, nil, nil, nil, err
}
if len(problems) > 0 {
return nil, nil, nil, nil, fmt.Errorf("compose: %s's declaration is refused by the node-engine's validator: %v", node, problems)
}
for _, x := range d.StoodIn {
// The bus's user list is the bus node's own to follow, written alone and never from a composition the node
// made itself (ADR 0547 §7, §8): its stand-in is held out of the apply, not applied.
if x != BusUsersStandIn {
stood = append(stood, x)
}
}
stood = append(stood, d.Foreseen...)
for _, p := range d.ForeseenPorts {
stood = append(stood, "port "+p)
}
sort.Strings(stood)
stood = slices.Compact(stood) // an own secret is both stood in for and foreseen
if applied && len(stood) > 0 {
return nil, nil, nil, nil, fmt.Errorf("%w on %s: %s", ErrStoodIn, node, strings.Join(stood, ", "))
}
body, err := d.Body()
if err != nil {
return nil, nil, nil, nil, err
}
var envelope struct {
Resources []json.RawMessage `json:"resources"`
Adoption *declaration.Adoption `json:"adoption"`
Filled []string `json:"filled_files"`
Provisioner string `json:"provisioner_account"`
}
if err := json.Unmarshal(body, &envelope); err != nil {
return nil, nil, nil, nil, err
}
// What the tool runner's process runs as, whose slice of each held module the composed process keeps (H-A-306).
var runsRuntime map[string]string
reads := 0
for i := range reading.Nodes {
if reading.Nodes[i].Name == node {
runsRuntime = reading.Nodes[i].RunsRuntime
reads = reading.Nodes[i].DeclarationReads
}
}
var kept []json.RawMessage
keptPaths := map[string]bool{}
foldedPaths := map[string]bool{}
left := map[string]bool{}
for _, raw := range envelope.Resources {
// Written at the lower of this composer's declaration Version and the one the node's engine reads (H-A-416 (2)).
if raw, err = AtDeclarationVersion(raw, reads); err != nil {
return nil, nil, nil, nil, err
}
var head struct {
ID string `json:"id"`
Module string `json:"module"`
Type string `json:"type"`
Path string `json:"path"`
}
if err := json.Unmarshal(raw, &head); err != nil {
return nil, nil, nil, nil, err
}
if isCarried(head.Module, head.ID) {
continue // what the stub composed of it: the node's own carries what runs of it instead
}
if folds(head.Module) {
// Into the node's own, in its place among the node's resources, its module taken off (mesh-controller's
// compositionsOf): the node's own composition is then the controller's, byte for byte.
var fields map[string]json.RawMessage
if err := json.Unmarshal(raw, &fields); err != nil {
return nil, nil, nil, nil, err
}
delete(fields, "module")
if raw, err = json.Marshal(fields); err != nil {
return nil, nil, nil, nil, err
}
if head.Type == string(declaration.TypeFile) {
foldedPaths[head.Path] = true
}
kept = append(kept, raw)
continue
}
if _, ok := fps[head.Module]; head.Module != "" && !ok {
left[head.Module] = true
continue
}
if head.Type == string(declaration.TypeFile) {
keptPaths[head.Path] = true
}
kept = append(kept, raw)
}
// What runs of each carried module, in the node's own composition, each after the resource it runs after.
if len(carried) > 0 {
var err error
if kept, foldedPaths, err = carry(kept, foldedPaths, runsOwn, isCarried); err != nil {
return nil, nil, nil, nil, err
}
for _, p := range runsOwn.Filled {
if foldedPaths[p] && !slices.Contains(envelope.Filled, p) {
envelope.Filled = append(envelope.Filled, p)
}
}
}
// A filled file of a module's own composition goes with that module (SplitComposed); one of a folded module goes with
// the node's own, after them, in the declaration's order; one of a module left out is dropped.
var filled, ownFilled []string
for _, p := range envelope.Filled {
switch {
case foldedPaths[p]:
ownFilled = append(ownFilled, p)
case keptPaths[p]:
filled = append(filled, p)
}
}
out, err = engcomp.Split(node, kept, fps, filled,
engcomp.NodeOwn{Adoption: envelope.Adoption, Provisioner: envelope.Provisioner})
if err != nil {
return nil, nil, nil, nil, err
}
if len(ownFilled) > 0 {
own, err := engcomp.NodeKey(node)
if err != nil {
return nil, nil, nil, nil, err
}
c := out[own]
c.Filled = append(c.Filled, ownFilled...)
out[own] = c
}
if len(held) > 0 && runsRuntime != nil {
// A held module's slice of the runtime process is what runs of it, verbatim, its fingerprint included: a pass that
// holds it for a part withheld composes the runtime as it runs, and writes no new revision for it (design 47 H,
// H-A-303, H-A-306). Taken after Split, which gives each module's words the fingerprint of its want (§519).
for key, c := range out {
for i, raw := range c.Resources {
var head struct {
ID string `json:"id"`
Module string `json:"module"`
Type string `json:"type"`
}
if json.Unmarshal(raw, &head) != nil || runtimeOwner(head.ID, head.Module, head.Type) == "" {
continue
}
if c.Resources[i], err = keepHeldSlices(raw, runsRuntime, held); err != nil {
return nil, nil, nil, nil, err
}
}
out[key] = c
}
}
for key, c := range out {
if held[c.Module] {
delete(out, key) // its stub's: the node keeps what it last applied of it (Node.Held)
continue
}
if m, ok := in.Catalogue[c.Module]; ok && c.Module != "" {
c.Data = len(m.DataItems()) > 0
// The archive its files were rendered from, which the parts check counts as fetched (design 47 G A-481a).
if m.TemplatesDigest != "" {
c.Templates = []string{m.TemplatesDigest}
}
out[key] = c
}
}
for m := range left {
skipped = append(skipped, m)
}
sort.Strings(skipped)
return out, skipped, stood, d.Held, nil
}
// RunsAnyOf says runs (a composition as it runs) holds a resource of module, by its module or the module its id names.
func RunsAnyOf(runs *engcomp.Composed, module string) bool {
if runs == nil {
return false
}
for _, raw := range runs.Resources {
var head struct {
ID string `json:"id"`
Module string `json:"module"`
}
if json.Unmarshal(raw, &head) != nil {
continue
}
owner := head.Module
if owner == "" {
owner, _ = declaration.ModuleGuess(head.ID)
}
if owner == module {
return true
}
}
return false
}
// FilterRunning is the content of the packet filter's file as it runs (the resource `<module>.filtering` of the module that
// loads the filter), nil where none runs: kept as it runs when the holder's allowed does not answer (design 08
// control-verbs §4).
func FilterRunning(running []engcomp.Composed) *string {
for _, c := range running {
for _, raw := range c.Resources {
var r struct {
ID string `json:"id"`
Module string `json:"module"`
Type string `json:"type"`
Content *string `json:"content"`
}
if json.Unmarshal(raw, &r) != nil || r.Type != "file" || r.Content == nil {
continue
}
owner := r.Module
if owner == "" {
owner, _ = declaration.ModuleGuess(r.ID)
}
if owner != "" && r.ID == owner+"."+catalogue.FilteringID() {
return r.Content
}
}
}
return nil
}
// ToolsRunning is, by module, the tools bundles that run on the node (Node.RunsTools): each bundle archive a module's
// resource unpacks at its BundlePath, with what the runtime's own process loads of it and the words it hands it
// (catalogue.RuntimeToolModules, catalogue.RuntimeToolEnv, the mesh's own words left out). A bundle the runtime loads
// nothing of has no Loads: the runtime dropped it, and the composition reads its loads again from the module's build
// (issue 1126, review: shanks had already applied the drop of systemd-resolved). Nil when running holds no runtime process.
func ToolsRunning(running []engcomp.Composed) map[string][]catalogue.Bundle {
type resource struct {
ID string `json:"id"`
Module string `json:"module"`
Type string `json:"type"`
Path string `json:"path"`
Source string `json:"source"`
Digest string `json:"digest"`
Env map[string]string `json:"env"`
}
var env map[string]string
out := map[string][]catalogue.Bundle{}
for _, c := range running {
for _, raw := range c.Resources {
var r resource
if json.Unmarshal(raw, &r) != nil {
continue
}
owner := r.Module
if owner == "" {
owner, _ = declaration.ModuleGuess(r.ID)
}
switch {
case r.Type == "process" && owner != "" && r.ID == owner+"."+resolution.RuntimeProcessID():
// The tool runner's process, by its id alone: `<its module>.runtime` (resolutionRuntimeProcess).
env = r.Env
case r.Type == "archive" && owner != "" && strings.HasPrefix(r.ID, owner+"."+resolution.BundleID("")):
name := strings.TrimPrefix(r.ID, owner+"."+resolution.BundleID(""))
if r.Path == resolution.BundlePath(owner, name) {
out[owner] = append(out[owner], catalogue.Bundle{Name: name, Source: registryforms.Forms.Recorded(r.Source), Digest: r.Digest})
}
}
}
}
if env == nil {
return nil
}
var words map[string]map[string]string
_ = json.Unmarshal([]byte(env[catalogue.RuntimeToolEnv]), &words)
for _, entry := range strings.Split(env[catalogue.RuntimeToolModules], ",") {
module, path, ok := strings.Cut(entry, "=")
if !ok || !strings.HasPrefix(path, catalogue.BundleRoot+"/"+module+"/") {
continue
}
name, load, ok := strings.Cut(strings.TrimPrefix(path, catalogue.BundleRoot+"/"+module+"/"), "/")
bundles := out[module]
i := slices.IndexFunc(bundles, func(b catalogue.Bundle) bool { return b.Name == name })
if !ok || i < 0 {
continue // no archive of it runs: nothing to load
}
var own map[string]string
for w, v := range words[module] {
if w == catalogue.FilesOwnedPaths || w == catalogue.ReadsSecretPlaces || w == engcomp.FingerprintVar {
continue // the mesh's to say, composed again (the fingerprint is the want's, §519)
}
if own == nil {
own = map[string]string{}
}
own[w] = v
}
bundles[i].Loads = append(bundles[i].Loads, load)
bundles[i].Env = own
}
for _, bundles := range out {
sort.Slice(bundles, func(i, j int) bool { return bundles[i].Name < bundles[j].Name })
}
return out
}
// RuntimeRunning is the environment of the tool runner's process as the node runs it (`<its module>.runtime`,
// resolutionRuntimeProcess), or nil when running holds none (Node.RunsRuntime).
func RuntimeRunning(running []engcomp.Composed) map[string]string {
for _, c := range running {
for _, raw := range c.Resources {
var r struct {
ID string `json:"id"`
Module string `json:"module"`
Type string `json:"type"`
Env map[string]string `json:"env"`
}
if json.Unmarshal(raw, &r) == nil && runtimeOwner(r.ID, r.Module, r.Type) != "" && r.Env != nil {
return r.Env
}
}
}
return nil
}
// RuntimesRunning is the environment of each runtime process as the node runs it, by its id: the tool runner's
// (`<its module>.runtime`) and each runtime of a module of its own account (`<module>.own-runtime`), or nil when running
// holds none (Node.RunsRuntimes).
func RuntimesRunning(running []engcomp.Composed) map[string]map[string]string {
var out map[string]map[string]string
for _, c := range running {
for _, raw := range c.Resources {
var r struct {
ID string `json:"id"`
Module string `json:"module"`
Type string `json:"type"`
Env map[string]string `json:"env"`
}
if json.Unmarshal(raw, &r) != nil || r.Env == nil {
continue
}
owner := r.Module
if owner == "" {
owner, _ = declaration.ModuleGuess(r.ID)
}
if runtimeOwner(r.ID, r.Module, r.Type) == "" && (r.Type != "process" || owner == "" ||
r.ID != owner+"."+catalogue.OwnRuntimeID()) {
continue
}
if out == nil {
out = map[string]map[string]string{}
}
out[r.ID] = r.Env
}
}
return out
}
// runtimeOwner is the module of the tool runner's process a resource is (`<its module>.runtime`), or "" when it is none.
func runtimeOwner(id, module, kind string) string {
if kind != "process" {
return ""
}
if module == "" {
module, _ = declaration.ModuleGuess(id)
}
if module == "" || id != module+"."+resolution.RuntimeProcessID() {
return ""
}
return module
}
// keepHeldSlices is the runtime process raw with each held module's slice taken verbatim from what runs (runs, the
// process's environment as it runs): its entries in catalogue.RuntimeToolModules and its words in
// catalogue.RuntimeToolEnv, its fingerprint among them (H-A-306). A held module the running process serves nothing of
// and gives no words keeps what the composition made of it (runningBundles: a drop already applied is undone). raw is
// answered unchanged when nothing differs.
func keepHeldSlices(raw json.RawMessage, runs map[string]string, held map[string]bool) (json.RawMessage, error) {
var fields map[string]json.RawMessage
if err := json.Unmarshal(raw, &fields); err != nil {
return nil, err
}
var env map[string]string
if json.Unmarshal(fields["env"], &env) != nil || env == nil {
return raw, nil
}
ranServed := map[string][]string{}
for _, entry := range servedEntries(runs[catalogue.RuntimeToolModules]) {
module, _, _ := strings.Cut(entry, "=")
ranServed[module] = append(ranServed[module], entry)
}
var ranWords, words map[string]json.RawMessage
_ = json.Unmarshal([]byte(runs[catalogue.RuntimeToolEnv]), &ranWords)
_ = json.Unmarshal([]byte(env[catalogue.RuntimeToolEnv]), &words)
keep := map[string]bool{}
for module, isHeld := range held {
if _, says := ranWords[module]; isHeld && (len(ranServed[module]) > 0 || says) {
keep[module] = true
}
}
if len(keep) == 0 {
return raw, nil
}
var served []string
for _, entry := range servedEntries(env[catalogue.RuntimeToolModules]) {
if module, _, _ := strings.Cut(entry, "="); !keep[module] {
served = append(served, entry)
}
}
for module := range keep {
served = append(served, ranServed[module]...)
if w, says := ranWords[module]; says {
if words == nil {
words = map[string]json.RawMessage{}
}
words[module] = w
} else {
delete(words, module)
}
}
sort.Strings(served)
kept := make(map[string]string, len(env))
for k, v := range env {
kept[k] = v
}
kept[catalogue.RuntimeToolModules] = strings.Join(served, ",")
delete(kept, catalogue.RuntimeToolEnv)
if len(words) > 0 {
body, err := json.Marshal(words)
if err != nil {
return nil, err
}
kept[catalogue.RuntimeToolEnv] = string(body)
}
if maps.Equal(kept, env) {
return raw, nil
}
body, err := json.Marshal(kept)
if err != nil {
return nil, err
}
fields["env"] = body
return json.Marshal(fields)
}
// servedEntries is the entries of a runtime's catalogue.RuntimeToolModules, `<module>=<path>` each; none for "".
func servedEntries(s string) []string {
if s == "" {
return nil
}
return strings.Split(s, ",")
}
// runningBundles is the bundles of a module composed as what runs of it (Node.RunsTools): each that runs, with what the
// runtime loads of it and its words; one the runtime loads nothing of takes its loads and words from the module's build
// (man: its built bundles, else its build's artifacts, catalogue.BundleLoads), so a drop already applied is undone.
func runningBundles(runs []catalogue.Bundle, man catalogue.Manifest) []catalogue.Bundle {
var out []catalogue.Bundle
for _, b := range runs {
if len(b.Loads) == 0 {
for _, built := range man.Bundles {
if built.Name == b.Name {
b.Loads, b.Env, b.Launchers, b.Binary = built.Loads, built.Env, built.Launchers, built.Binary
}
}
if man.Build != nil {
run := resolution.RunByAResource(man)
for _, a := range man.Build.Artifacts {
if a.Kind == catalogue.ArtifactBundle && a.Name == b.Name {
b.Loads, b.Env, b.Binary = catalogue.BundleLoads(man, a, run), a.Env, catalogue.BinaryOf(a)
}
}
}
}
out = append(out, b)
}
return out
}
// NamesBuild says a manifest names what a build makes: its build, or a resource naming an artifact. A node cannot
// compose such a module folded into its own composition: the build of the old form it runs is held by the controller
// alone (issue 1126).
func NamesBuild(m catalogue.Manifest) bool {
if m.Build != nil {
return true
}
for _, r := range m.Resources {
if _, ok := r["artifact"]; ok {
return true
}
}
return false
}
// Stub is m with nothing to build and no resource but its directories: what it provides, requires, serves and grants
// still shape the rest of the composition, the places its own secrets, data and grants name (${dir:…}) still resolve,
// and nothing else of its own is composed (issue 1126: nats's ${dir:mesh-state} on novox). A module refused in a
// node's answer is composed so; a folded one the node runs is Carried.
func Stub(m catalogue.Manifest) catalogue.Manifest {
// The paths it owns stay its manifest's, as the controller tells the holder of node-files them (issue 1126, seed-8).
if m.OwnsPaths == nil {
m.OwnsPaths = resolution.DeclaredPaths(m)
}
m.Build = nil
// What it hands the provisioner is left out as it runs, not refused for want of a plan (catalogue.Manifest.Stubbed).
m.Stubbed = true
// Nor is a template its build kept for its own files handed: a stub carries none of them (issue 1126: novox's node
// refused "postgres: its build kept a template for consumers, which it does not declare" with postgres held). Its
// items stay, and the templates they render through: a held module's contributions to other modules' collections
// (seat contributions, shell blocks, seat data) still reach their collectors.
if m.Handed != nil {
h := *m.Handed
h.Templates = nil
m.Handed = &h
}
var dirs []map[string]any
for _, r := range m.Resources {
if r["type"] == "directory" {
dirs = append(dirs, r)
}
}
m.Resources = dirs
return m
}
// Carried is m, folded into its node's own composition at a build of the old form, as the node runs it (issue 1126,
// C5): nothing to build; its containers and directories those the node's own composition (runs) carries of it, their
// module's word taken off their ids, with the manifest's directories it does not run. So what other modules read of it
// is what runs: the machine ports its containers publish (the filter's rules, the routes reaching it: MachineSide). The
// paths it owns, which the holder of node-files is told, are its manifest's, as for its Stub: the controller composes
// them from the manifest, not from every path a resource of it runs at (issue 1126, seed-8: f1-circuits, snake and
// txt-game on ace, whose manifests leave their directories to the mesh). Its other resources are not taken, since the
// composition makes some of them again from its manifest (its secrets' files) and one id twice is refused; none of them
// is composed into what is applied either way (compositions leaves a carried module's out, and carries the ones that
// run). What it provides, requires, listens on and grants is its manifest's. A module whose resources runs holds none
// of is its Stub, as before.
func Carried(m catalogue.Manifest, module string, runs *engcomp.Composed) catalogue.Manifest {
stub := carried(m, module, runs)
if catalogue.IsToolRunner(m) && (len(stub.Bundles) != 1 || stub.Bundles[0].Binary == "") {
if b, ok := runningProgram(module, runs); ok {
stub.Bundles = []catalogue.Bundle{b}
}
}
return stub
}
// keepsProgram says a held tool runner carries the program it runs (Carried, runningProgram): its one bundle is that
// program, which the tools bundles it serves never replace, or the modules of their own account it runs are held for
// want of it (lead-47 2026-11-16: 40ed063 kept novox's, and the loop over what the runtime serves dropped it again).
func keepsProgram(m catalogue.Manifest) bool {
return catalogue.IsToolRunner(m) && len(m.Bundles) == 1 && m.Bundles[0].Binary != ""
}
// runningProgram is the program bundle of the tool runner as it runs on the node: its process's source, digest and binary.
// A held tool runner keeps it, so a module of its own account is run by the same program the node runs (novox/hq ADR 0259
// §8) and is not held for want of a runtime that runs (lead-47 2026-11-16: novox's tool runner was held for a build the
// catalog half held no entry of, and held the new indexer with it).
func runningProgram(module string, runs *engcomp.Composed) (catalogue.Bundle, bool) {
if runs == nil {
return catalogue.Bundle{}, false
}
for _, raw := range runs.Resources {
var r struct {
ID string `json:"id"`
Module string `json:"module"`
Type string `json:"type"`
Source string `json:"source"`
Digest string `json:"digest"`
Run []string `json:"run"`
}
if json.Unmarshal(raw, &r) != nil || r.Type != "process" || r.Source == "" || r.Digest == "" || len(r.Run) == 0 {
continue
}
owner := r.Module
if owner == "" {
owner, _ = declaration.ModuleGuess(r.ID)
}
binary, ok := strings.CutPrefix(r.Run[0], "./")
if owner != module || !ok || binary == "" || strings.Contains(binary, "/") {
continue
}
return catalogue.Bundle{Name: "program", Source: registryforms.Forms.Recorded(r.Source), Digest: r.Digest, Binary: binary}, true
}
return catalogue.Bundle{}, false
}
func carried(m catalogue.Manifest, module string, runs *engcomp.Composed) catalogue.Manifest {
if runs == nil {
return Stub(m)
}
var taken []map[string]any
runsAny := false
ids := map[string]bool{}
for _, raw := range runs.Resources {
var r map[string]any
if json.Unmarshal(raw, &r) != nil {
continue
}
id, _ := r["id"].(string)
owner, _ := r["module"].(string)
if owner == "" {
owner, _ = declaration.ModuleGuess(id)
}
if owner != module {
continue
}
runsAny = true
if typ := r["type"]; typ != "container" && typ != "directory" {
continue
}
r["id"] = strings.TrimPrefix(id, module+".")
delete(r, "module")
ids[r["id"].(string)] = true
taken = append(taken, r)
}
if !runsAny {
return Stub(m)
}
stub := Stub(m)
for _, r := range stub.Resources {
if id, _ := r["id"].(string); !ids[id] {
taken = append(taken, r)
}
}
stub.Resources = taken
return stub
}
// carry puts into the node's resources (kept, in the declaration's order) the resources of the node's own composition as
// it runs (runs) that belong to a carried module, each after the resource it runs after, or first when that one is
// not among them; a file among them is a folded path.
func carry(kept []json.RawMessage, foldedPaths map[string]bool, runs *engcomp.Composed, carried func(module, id string) bool) ([]json.RawMessage, map[string]bool, error) {
idOf := func(raw json.RawMessage) (string, string, string, string, error) {
var head struct {
ID string `json:"id"`
Module string `json:"module"`
Type string `json:"type"`
Path string `json:"path"`
}
err := json.Unmarshal(raw, &head)
return head.ID, head.Module, head.Type, head.Path, err
}
present := map[string]bool{}
for _, raw := range kept {
if id, module, _, _, err := idOf(raw); err == nil && module == "" {
present[id] = true
}
}
// By the id of the resource of the node's own it runs after, "" for first: the last one before it that is composed.
after := map[string][]json.RawMessage{}
anchor := ""
for _, raw := range runs.Resources {
id, module, typ, path, err := idOf(raw)
if err != nil {
return nil, nil, fmt.Errorf("compose: a resource the node runs in its own composition: %w", err)
}
if !carried(module, id) {
if module == "" && present[id] {
anchor = id
}
continue
}
after[anchor] = append(after[anchor], raw)
if typ == string(declaration.TypeFile) {
foldedPaths[path] = true
}
}
out := make([]json.RawMessage, 0, len(kept)+len(runs.Resources))
out = append(out, after[""]...)
for _, raw := range kept {
out = append(out, raw)
if id, module, _, _, err := idOf(raw); err == nil && module == "" {
out = append(out, after[id]...)
}
}
return out, foldedPaths, nil
}
// drainBoundVersion is the declaration Version a process's drain-bound came with (mesh-sdk declaration, H-A-388 (2)).
const drainBoundVersion = 2
// DeclarationVersionFor is the declaration Version a node's declaration is written at: the lower of this composer's
// own (declaration.Version) and the one its engine states it reads, 1 when it states none (design 47 H2 §813 (12),
// H-A-416 (2), H-A-419).
func DeclarationVersionFor(reads int) int {
if reads < 1 {
reads = 1
}
return min(reads, declaration.Version)
}
// AtDeclarationVersion is a resource as a node whose engine reads Version reads (DeclarationVersionFor): the fields that
// Version lacks left out, so an older engine never meets a field it refuses; a process's drain-bound then takes the
// engine's own default (H-A-416 (2)).
func AtDeclarationVersion(raw json.RawMessage, reads int) (json.RawMessage, error) {
if DeclarationVersionFor(reads) >= drainBoundVersion {
return raw, nil
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(raw, &fields); err != nil {
return nil, err
}
if _, has := fields["drain-bound"]; !has {
return raw, nil
}
delete(fields, "drain-bound")
return json.Marshal(fields)
}