package main import ( "encoding/json" "fmt" "os" "path/filepath" "regexp" "slices" "sort" "strings" "testing" . "claude-licence-manager/internal/licences" ) // design 39 bus-and-switch §1: the module moves to the new form whole — no `reads`, no old `state`, no `prepare` // step — and asks for each state it keeps by template; its two logs are in the `logs` section with their bounds, the // form the runtime on main issues (C3). func TestTheManifestKeepsNoOldForm(t *testing.T) { raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json")) if err != nil { t.Fatal(err) } var m map[string]json.RawMessage if err := json.Unmarshal(raw, &m); err != nil { t.Fatal(err) } for _, old := range []string{"reads", "state"} { if _, ok := m[old]; ok { t.Errorf("the manifest keeps the old section %q", old) } } var resources []struct { ID string `json:"id"` } _ = json.Unmarshal(m["resources"], &resources) for _, r := range resources { if r.ID == "prepare" { t.Error("the manifest keeps the run-once step prepare") } } var requires []json.RawMessage _ = json.Unmarshal(m["requires"], &requires) kept := map[string]string{} for _, r := range requires { var e struct{ Name, Template string } if json.Unmarshal(r, &e) == nil { kept[e.Name] = e.Template } } for name, template := range map[string]string{"licences": "state", "bindings": "state", "leases": "state", "offered": "state", "usage": "", "audit": "", "carried": "state", "conditions": "state"} { if kept[name] != template { t.Errorf("bus-state entry %s is %q in requires, want %q", name, kept[name], template) } } var logs []json.RawMessage _ = json.Unmarshal(m["logs"], &logs) declared := logsSection(logs) for name, bounds := range map[string]map[string]float64{"usage": {"max-age-days": 35, "max-mib": 256}, "audit": {"max-mib": 64}} { l, ok := declared[name] if !ok { t.Errorf("the log %s is not in the logs section", name) continue } for k, v := range bounds { if l[k] != v { t.Errorf("the log %s has %s %v, want %v", name, k, l[k], v) } } } } // issued is what the manager's own runtime is issued from its manifest (design 39 bus-and-switch C1): its account, the // states it keeps (`requires` by template), the logs it keeps (the `logs` section, the form the runtime on main issues, // C3; a log asked for by template in `requires` is issued nothing), what it may ask (`invokes`) and say (`emits`). type issued struct { RunsAs, SecretsOwner string OwnSecrets map[string]string Resources []map[string]any States, Logs map[string]bool Invokes, Emits map[string]bool } func manifestIssued(t testing.TB) issued { t.Helper() raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json")) if err != nil { t.Fatal(err) } var m struct { RunsAs string `json:"runs-as"` SecretsOwner string `json:"secrets-owner"` OwnSecrets map[string]string `json:"own-secrets"` Requires []json.RawMessage `json:"requires"` Logs []json.RawMessage `json:"logs"` Resources []map[string]any `json:"resources"` Invokes []string `json:"invokes"` Emits []string `json:"emits"` } if err := json.Unmarshal(raw, &m); err != nil { t.Fatal(err) } out := issued{RunsAs: m.RunsAs, SecretsOwner: m.SecretsOwner, OwnSecrets: m.OwnSecrets, Resources: m.Resources, States: map[string]bool{}, Logs: map[string]bool{}, Invokes: map[string]bool{}, Emits: map[string]bool{}} for _, r := range m.Requires { var e struct{ Name, Storage string } if json.Unmarshal(r, &e) != nil { continue } if e.Storage == "key-value" { out.States[e.Name] = true } } for name := range logsSection(m.Logs) { out.Logs[name] = true } for _, k := range m.Invokes { out.Invokes[k] = true } for _, e := range m.Emits { out.Emits[e] = true } return out } // logsSection is the manifest's `logs` section by name: each a name alone or {name, max-age-days, max-mib}. func logsSection(logs []json.RawMessage) map[string]map[string]any { out := map[string]map[string]any{} for _, l := range logs { var name string if json.Unmarshal(l, &name) == nil { out[name] = map[string]any{} continue } var e map[string]any if json.Unmarshal(l, &e) == nil { if n, _ := e["name"].(string); n != "" { out[n] = e } } } return out } // mayAsk is whether the manager's own account may ask key: a module tool asked on one node (`.@`) // is invoked as `.`. // emits is whether the manifest names the event key's family: the key itself, or a family it extends by further parts, // as binding.changed. extends binding.changed (design 47 G A-134). func (i issued) emits(key string) bool { for k := key; k != ""; { if i.Emits[k] { return true } dot := strings.LastIndex(k, ".") if dot < 0 { break } k = k[:dot] } return false } func (i issued) mayAsk(key string) bool { k, _, _ := strings.Cut(key, "@") return i.Invokes[k] } // design 39 bus-and-switch C1: the manager runs as an account of its own, which it makes and which owns what it places // on its machine and its secrets, reaching the bus as itself; and that account is issued every ask its code makes, // since its runtime is not the machine's tool runner. func TestTheManagerRunsAsItsOwnAccount(t *testing.T) { m := manifestIssued(t) if m.RunsAs != Publisher { t.Fatalf("the manager runs as %q, not as its own account %s", m.RunsAs, Publisher) } if m.SecretsOwner != Publisher || m.OwnSecrets["broker"] == "" { t.Errorf("its secrets belong to %q and its own broker secret is %q: both are its account's", m.SecretsOwner, m.OwnSecrets["broker"]) } made := false for _, r := range m.Resources { switch r["type"] { case "user": made = made || r["name"] == Publisher case "directory", "file": if r["owner"] != Publisher { t.Errorf("resource %v is owned by %v, not by the manager's account", r["id"], r["owner"]) } } } if !made { t.Errorf("the manager does not make its account: no user resource named %s", Publisher) } files, _ := filepath.Glob("../*/*.go") shared, _ := filepath.Glob("../../internal/*/*.go") files = append(files, shared...) asked := regexp.MustCompile(`stdio\.Ask\("([^"]+)"`) for _, f := range files { if strings.HasSuffix(f, "_test.go") { continue } src, err := os.ReadFile(f) if err != nil { t.Fatal(err) } for _, k := range asked.FindAllStringSubmatch(string(src), -1) { if !m.mayAsk(k[1]) { t.Errorf("%s asks %s, which the manifest's invokes do not name", f, k[1]) } } } } // design 39 parts §9, §10: the carry-over has left the module whole. Its manifest requires neither the store database // nor the secret grant-key, contributes and binds nothing and has no secrets section; no word of its code names the // database's address or grant.key; its go.mod requires no postgres driver; the tool licences_carried is gone, and the // state carried stays as the carry-over's record. func TestTheCarryOverHasLeft(t *testing.T) { raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json")) if err != nil { t.Fatal(err) } var m map[string]json.RawMessage if err := json.Unmarshal(raw, &m); err != nil { t.Fatal(err) } for _, gone := range []string{"contributes", "binds", "secrets"} { if _, ok := m[gone]; ok { t.Errorf("the manifest keeps %q", gone) } } var requires []json.RawMessage _ = json.Unmarshal(m["requires"], &requires) carried := false for _, r := range requires { var bare string if json.Unmarshal(r, &bare) == nil { t.Errorf("the manifest requires %q", bare) } var e struct{ Name string } if json.Unmarshal(r, &e) == nil && e.Name == "carried" { carried = true } } if !carried { t.Error("the state carried, the carry-over's record, is gone") } var tools []string _ = json.Unmarshal(m["tools"], &tools) if slices.Contains(tools, "licences_carried") { t.Error("the manifest keeps the tool licences_carried") } var resources []struct{ ID string } _ = json.Unmarshal(m["resources"], &resources) for _, r := range resources { if r.ID == "database-url" { t.Error("the manifest keeps the resource database-url") } } words := []string{"DATABASE_URL" + "_FILE", "MESH_LICENCE_KEY" + "_FILE"} err = filepath.WalkDir(moduleDir, func(path string, d os.DirEntry, err error) error { if err != nil || d.IsDir() { return err } switch filepath.Ext(path) { case ".go", ".json", ".mod", ".sum": default: if filepath.Base(filepath.Dir(path)) != "files" { return nil // a built binary is no code of the module } } src, err := os.ReadFile(path) if err != nil { return err } for _, w := range words { if strings.Contains(string(src), w) { t.Errorf("%s names %s", path, w) } } if filepath.Base(path) == "go.mod" && strings.Contains(string(src), "github.com/jackc/pgx") { t.Errorf("%s requires the postgres driver", path) } return nil }) if err != nil { t.Fatal(err) } } // design 39 parts §1 to §4, §6 to §8: the module is four parts in one manifest. Its artifacts are exactly the manager // bundle, the tools bundle and the templates archive, with their words; its resources exactly the account, its // directory and the settings file, in that order; no process or container resource, no run-once step, no bus account // of its own and no runtime-health; its tools are the four reading ones and the three acting ones; files/ holds only // the settings template. func TestTheModuleIsFourParts(t *testing.T) { raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json")) if err != nil { t.Fatal(err) } var m map[string]any if err := json.Unmarshal(raw, &m); err != nil { t.Fatal(err) } same := func(what string, got, want any) { t.Helper() g, _ := json.Marshal(got) w, _ := json.Marshal(want) if string(g) != string(w) { t.Errorf("%s is %s, want %s", what, g, w) } } build, _ := m["build"].(map[string]any) same("build.artifacts", build["artifacts"], []map[string]any{ {"name": "manager", "kind": "bundle", "language": "go", "system": "arch", "from": "cmd/manager", "binary": "claude-licence-manager", "loads": []string{"claude-licence-manager"}, "env": map[string]string{"MESH_LICENCE_STATE": "${dir:state}", "MESH_LICENCE_SETTINGS": "${dir:state}/settings.json"}}, {"name": "tools", "kind": "bundle", "language": "go", "system": "arch", "from": "cmd/tools", "binary": "claude-licence-manager-tools", "loads": []string{"claude-licence-manager-tools"}}, {"name": "files", "kind": "archive", "from": "files"}, }) same("resources", m["resources"], []map[string]any{ {"id": "account", "type": "user", "name": Publisher, "shell": "/usr/bin/nologin", "home": "/var/lib/" + Publisher}, {"id": "state", "type": "directory", "mode": "0700", "owner": Publisher, "place": ".", "unknown": "program"}, {"id": "settings", "type": "file", "path": "${dir:state}/settings.json", "mode": "0600", "owner": Publisher, "takes-config": []string{"cadence_minutes", "floor_minutes", "failures_to_notify", "cooldown_hours", "refresh_warn_days", "switch_auto", "switch_at_pct", "room_below_pct", "warn_at_pct", "usage_minutes", "usage_stale_minutes"}, "merge": "json", "template": "files/settings.json"}, }) tools, _ := m["tools"].([]any) var names []string for _, n := range tools { names = append(names, fmt.Sprint(n)) } sort.Strings(names) same("tools", names, []string{"licences_conditions", "licences_kept", "licences_read_usage", "licences_resync", "licences_settings", "licences_switch_now", "licences_switches"}) same("runs-as", m["runs-as"], Publisher) same("secrets-owner", m["secrets-owner"], Publisher) same("own-secrets", m["own-secrets"], map[string]string{"broker": "${dir:state}/broker"}) if _, ok := m["runtime-health"]; ok { t.Error("the manifest adds runtime-health: the node-engine's judgement that the runtime is alive is its health") } var walk func(path string, v any) walk = func(path string, v any) { switch v := v.(type) { case map[string]any: for k, e := range v { if k == "bus" || k == "run-once" { t.Errorf("the manifest says %s at %s", k, path) } if k == "type" && (e == "process" || e == "container") { t.Errorf("the manifest has a %v resource at %s", e, path) } walk(path+"."+k, e) } case []any: for i, e := range v { walk(fmt.Sprintf("%s[%d]", path, i), e) } } } walk("", m) files, _ := os.ReadDir(filepath.Join(moduleDir, "files")) var templates []string for _, f := range files { templates = append(templates, f.Name()) } same("files/", templates, []string{"settings.json"}) } // design 39 parts §2, §4: the manager bundle registers the seat's ten verbs under the seat and the three acting tools // under the module, and nothing more. func TestTheManagerRegistersTheVerbsAndTheActs(t *testing.T) { var names []string for _, tool := range tools() { names = append(names, tool.Name) } sort.Strings(names) var want []string for _, v := range []string{"licences", "bindings", "bind", "switch", "release", "refresh", "usage", "adopt", "current", "public-key"} { want = append(want, Seat+"."+v) } want = append(want, "licences_read_usage", "licences_resync", "licences_switch_now") sort.Strings(want) if !slices.Equal(names, want) { t.Fatalf("the manager bundle registers %v, not %v", names, want) } }