Compare commits

..
Author SHA1 Message Date
jschoubben 998c773420 mesh-vault: pin the group's mesh-sdk head 3f7957e (issue 774) 2026-10-27 23:02:51 +01:00
jschoubben f7e90cb049 mesh-vault: account_retire refuses while the controller holds the lease or before the wants are read whole, as the passes do (issue 774, review round 1) 2026-10-27 23:00:54 +01:00
jschoubben 98cae719bd mesh-vault: pin the group's mesh-sdk head d688f10 (issue 774) 2026-10-27 22:52:33 +01:00
jschoubben 92cabc6fb2 mesh-vault: prove the vault whole on a real bus mints only from the lease write, and try a failed mint again at the pass; adopt the operator key before the watches open (issue 774, ADR 0561 §1-§4) 2026-10-27 22:48:58 +01:00
jschoubben f1cdabbb0d mesh-vault: tell where modules stand and which node holds the bus from the catalogue's placement first, so the vault does not depend on the controller's assignments for them (issue 774, ADR 0549 §3, §5) 2026-10-27 22:45:18 +01:00
jschoubben 6bc56a4ce3 mesh-vault: serve issue-account, the hand path that mints one wanted account now, and record a rotation at most once per loaded list's revision; a covered account still never rotates in place (issue 774, ADR 0561 §4, §9) 2026-10-27 22:42:57 +01:00
jschoubben 0754c2c3ae mesh-vault: retire an account the grants part no longer wants only within ADR 0230's bounds, keeping its value, and re-enable it when wanted again; account_retire for a person past the bound (issue 774, ADR 0561 §2) 2026-10-27 22:39:13 +01:00
jschoubben d422479180 mesh-vault: mint only while the controller's lease is handed away, read afresh before each mint, and say in vault_status what is held back and why (issue 774, ADR 0561 §3, §9) 2026-10-27 22:35:08 +01:00
jschoubben d0bba2d364 mesh-vault: mint each account the grants part wants and the vault holds no value or adopted hash for, in the controller's shape, hashed before account-issued and secret-changed (issue 774, ADR 0561 §1, §2, §4) 2026-10-27 22:33:44 +01:00
76 changed files with 2137 additions and 4232 deletions
-1
View File
@@ -41,4 +41,3 @@ checks/placement/placement
# Built by their modules' build step (issue 1577), never committed.
modules/forticlient/cmd/forticlient-tools/forticlient-tools
modules/networkmanager/uplink-tools
checks/words/words
+6 -12
View File
@@ -1,4 +1,4 @@
// Package nobinaries refuses a compiled program anywhere in the repository (issue 1577; first a checks/ binary slipped past a modules/-only rule): it is build output, made by the module's build step,
// Package nobinaries refuses a compiled program under modules/ (issue 1577): it is build output, made by the module's build step,
// and `go build` in a module's folder writes one beside go.mod where `git add -A` takes it.
package nobinaries
@@ -27,10 +27,10 @@ func Kind(head []byte) string {
return ""
}
// Files are the files of the catalogue's root that the change holds, anywhere: the tracked ones when the root is a git
// checkout (an ignored binary a local build left is not the change's), else every file there but .git's.
// Files are the files of the catalogue's root that the change holds under modules/: the tracked ones when the root is a git
// checkout (an ignored binary a local build left is not the change's), else every file there.
func Files(root string) ([]string, error) {
cmd := exec.Command("git", "-C", root, "ls-files", "-z")
cmd := exec.Command("git", "-C", root, "ls-files", "-z", "--", "modules")
if out, err := cmd.Output(); err == nil && len(out) > 0 {
var files []string
for _, f := range strings.Split(strings.TrimRight(string(out), "\x00"), "\x00") {
@@ -41,16 +41,10 @@ func Files(root string) ([]string, error) {
return files, nil
}
var files []string
err := filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
if err != nil {
err := filepath.WalkDir(filepath.Join(root, "modules"), func(p string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() || !d.Type().IsRegular() {
return err
}
if d.IsDir() && d.Name() == ".git" {
return filepath.SkipDir
}
if d.IsDir() || !d.Type().IsRegular() {
return nil
}
rel, _ := filepath.Rel(root, p)
files = append(files, rel)
return nil
+2 -37
View File
@@ -2,7 +2,6 @@ package nobinaries
import (
"os"
"os/exec"
"path/filepath"
"testing"
)
@@ -17,7 +16,6 @@ func TestFindNamesEachCompiledProgramAndNothingElse(t *testing.T) {
"modules/e/short": []byte("\x7f"),
"modules/f/empty": {},
"modules/g/Foo.class": {0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52}, // Java, not Mach-O
"checks/words/words": []byte("\x7fELF\x02\x01\x01\x00rest"), // outside modules/ too
}
var names []string
for f, b := range files {
@@ -34,8 +32,8 @@ func TestFindNamesEachCompiledProgramAndNothingElse(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(got) != 4 {
t.Fatalf("found %v; wanted modules/a/a, modules/b/cmd/b/b.exe and modules/c/c and checks/words/words only", got)
if len(got) != 3 {
t.Fatalf("found %v; wanted modules/a/a, modules/b/cmd/b/b.exe and modules/c/c only", got)
}
}
@@ -54,36 +52,3 @@ func TestTheCatalogueHoldsNoCompiledProgram(t *testing.T) {
t.Errorf("%s: a compiled program is build output: remove it and add it to .gitignore (issue 1577)", f)
}
}
// A compiled program outside modules/ is refused too (a binary under checks/ slipped past the modules/-only rule): Files holds
// every tracked file of a git checkout and every file of a plain folder, and Find names the binary in both.
func TestAProgramUnderChecksIsRefused(t *testing.T) {
for _, git := range []bool{true, false} {
root := t.TempDir()
p := filepath.Join(root, "checks", "words", "words")
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte("\x7fELF\x02\x01\x01\x00rest"), 0o644); err != nil {
t.Fatal(err)
}
if git {
for _, args := range [][]string{{"init", "-q"}, {"add", "-A"}} {
if out, err := exec.Command("git", append([]string{"-C", root}, args...)...).CombinedOutput(); err != nil {
t.Fatalf("git %v: %v: %s", args, err, out)
}
}
}
files, err := Files(root)
if err != nil {
t.Fatal(err)
}
found, err := Find(root, files)
if err != nil {
t.Fatal(err)
}
if len(found) != 1 {
t.Errorf("git=%v: found %v; wanted checks/words/words (ELF)", git, found)
}
}
}
+5 -1
View File
@@ -1 +1,5 @@
# every tracked file of the repository (git ls-files, no path limit): the whole tree, so this package's verdict is never kept.
# What these tests read outside their package, as paths from the repository's root (a glob, or a directory read whole;
# ? before a path whose absence is read). mesh-build-go hashes them into the package's digest, so its verdict is kept
# until one of them changes (issue 1936). An empty list, or a line matching nothing, keeps nothing.
# every file under modules/ (git ls-files and a walk).
modules
-8
View File
@@ -206,9 +206,6 @@ func excerpt(s string, from, to int) string {
return strings.Join(strings.Fields(s[a:b]), " ")
}
// modulePath matches a string that is only a module or import path ("git.example.org/org/repo/go/pkg").
var modulePath = regexp.MustCompile(`^[a-z0-9.-]+\.[a-z]+/[A-Za-z0-9_./-]+$`)
// goStrings returns a Go file's string literals, adjacent ones joined across `+` as the program joins them.
func goStrings(path, rel string) ([]text, error) {
src, err := os.ReadFile(path)
@@ -234,11 +231,6 @@ func goStrings(path, rel string) ([]text, error) {
if err != nil {
v = lit
}
if modulePath.MatchString(v) {
// An import path or another module path names code, not words an agent reads.
cur, joining = nil, false
continue
}
if cur != nil && joining {
cur.s += v
} else {
@@ -23,7 +23,7 @@ import (
// manifest's.
const NamesFileEnv = "MESH_ARTIFACT_STORE_NAMES_FILE"
// CatalogueModules and CatalogueModule are the catalog's tools these definitions are read through.
// CatalogueModules and CatalogueModule are the catalogue's tools these definitions are read through.
const (
CatalogueModules = "mesh-catalog.catalog_modules"
CatalogueModule = "mesh-catalog.catalog_module"
@@ -143,21 +143,21 @@ func PinsIn(manifest json.RawMessage, names StoreNames) []pinned {
return out
}
// Definitions is what the catalog's definitions pin in the store, and what of them could not be read.
// Definitions is what the catalogue's definitions pin in the store, and what of them could not be read.
type Definitions struct {
// Pins are by Key(repository, digest).
Pins map[string][]Pin
// Read is how many definitions were read; Unread says, per module, why its definition was not.
Read int
Unread map[string]string
// NotAsked says why the catalog could not be asked at all, when it could not.
// NotAsked says why the catalogue could not be asked at all, when it could not.
NotAsked string
// NamesNotRead says why the store's older names could not be read, when they could not.
NamesNotRead string
Names StoreNames
}
// Catalogue reads the definitions through the catalog's tools, and keeps each definition it read by its
// Catalogue reads the definitions through the catalogue's tools, and keeps each definition it read by its
// module and commit, which never change together.
type Catalogue struct {
Ask Asking
@@ -171,21 +171,21 @@ type catalogueEntry struct {
Commit string `json:"commit"`
}
// Read asks the catalog for every module and reads each definition, bounded by DefinitionsTimeout.
// Read asks the catalogue for every module and reads each definition, bounded by DefinitionsTimeout.
func (c *Catalogue) Read(ctx context.Context, names StoreNames) *Definitions {
defs := &Definitions{Pins: map[string][]Pin{}, Unread: map[string]string{}, Names: names}
if c == nil || c.Ask == nil {
defs.NotAsked = "this bundle has no way to ask the catalog"
defs.NotAsked = "this bundle has no way to ask the catalogue"
return defs
}
raw, err := c.Ask(CatalogueModules, map[string]any{})
if err != nil {
defs.NotAsked = "the catalog's modules could not be asked: " + err.Error()
defs.NotAsked = "the catalogue's modules could not be asked: " + err.Error()
return defs
}
answer, output, ok := answerOf(raw)
if !ok {
defs.NotAsked = "the catalog refused its modules: " + lastLine(output)
defs.NotAsked = "the catalogue refused its modules: " + lastLine(output)
return defs
}
var list struct {
@@ -193,7 +193,7 @@ func (c *Catalogue) Read(ctx context.Context, names StoreNames) *Definitions {
Error string `json:"error"`
}
if err := json.Unmarshal(answer, &list); err != nil || list.Error != "" || list.Modules == nil {
defs.NotAsked = "the catalog's modules answer is not readable: " + firstOf(list.Error, errText(err), lastLine(output))
defs.NotAsked = "the catalogue's modules answer is not readable: " + firstOf(list.Error, errText(err), lastLine(output))
return defs
}
c.mu.Lock()
@@ -54,7 +54,7 @@ func Tools(s *Store, c Controller, cat *Catalogue) []stdio.Tool {
Name: "artifact_store_references",
Description: "What the controller's records say of each manifest the artifact store holds: kept (a definition " +
"names it, or one of the five most recent builds of a module the mesh holds), named by a definition (no " +
"record names it, and a definition in the catalog pins it by digest, under the store's current name or " +
"record names it, and a definition in the catalogue pins it by digest, under the store's current name or " +
"an older one: the module is said), the holder of a kept archive, " +
"eligible (the mesh made it and keeps it for no reason), the holder of an eligible archive, let go yet present, " +
"a named document the controller keeps under a tag, or unrecorded — no record names it. A platform manifest " +
+2 -2
View File
@@ -45,8 +45,8 @@ whenever the node's tool runtime collects the module's tools:
| file | holds |
|---|---|
| `managed-mcp.json` | the tool servers every session loads: the mesh's console as `mesh` (with a `timeout` of 660000 ms, mesh_wait's longest wait and a minute, so the agent's one-minute default does not cut a wait, issue 1871), and the servers set in this module's `mcp_servers` setting. **Exclusive**: a server not listed here does not load — not one added with `claude mcp add`, not a project's `.mcp.json`, not a plugin's |
| `managed-settings.json` | the keys set in this module's `managed_settings` setting — at the controller's terminal alone (hq issue 340) — under the mesh's own keys: the repositories' attribution convention, the claude.ai connectors kept beside the managed servers, the key-helper while the node holds an API-key licence, git's credential file while the node holds the forge's read credential (below), and the two that name the `nox-mesh` marketplace and enable its plugin, and `CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT` (660000) in `env` beside the operator's own, the mesh's key winning |
| `managed-mcp.json` | the tool servers every session loads: the mesh's console as `mesh`, and the servers set in this module's `mcp_servers` setting. **Exclusive**: a server not listed here does not load — not one added with `claude mcp add`, not a project's `.mcp.json`, not a plugin's |
| `managed-settings.json` | the keys set in this module's `managed_settings` setting — at the controller's terminal alone (hq issue 340) — under the mesh's own keys: the repositories' attribution convention, the claude.ai connectors kept beside the managed servers, the key-helper while the node holds an API-key licence, git's credential file while the node holds the forge's read credential (below), and the two that name the `nox-mesh` marketplace and enable its plugin |
| `CLAUDE.md` | how a session on this mesh works, this node's name and role, the conventions, the **"instead of" table** — then the instruction sections registered for every node and for this one |
| `marketplace/` | the `nox-mesh` plugin (hq ADR 0216): the skills, subagents, commands and output styles registered for every node and for this one, offered in a session as `nox-mesh:<name>` — and the **guard on the agent's shell** (`guard/`), the mesh's own hook and the plugin's only one (hq issue 340). Replaced whole, staged beside and swapped in |
@@ -83,20 +83,6 @@ func TestTheRendererWritesWhatTheTypeScriptOneWrote(t *testing.T) {
for k := range MarketplaceKeys() {
delete(m, k)
}
// The wait bound is new since the TypeScript (issue 1871), and is held below.
if env, ok := m["env"].(map[string]any); ok {
delete(env, "CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT")
if len(env) == 0 {
delete(m, "env")
}
}
}
if m, ok := a.(map[string]any); ok && file == "managed-mcp.json" {
if servers, ok := m["mcpServers"].(map[string]any); ok {
if entry, ok := servers["mesh"].(map[string]any); ok {
delete(entry, "timeout")
}
}
}
_ = json.Unmarshal([]byte(want[file]), &b)
if !reflect.DeepEqual(a, b) {
@@ -118,21 +104,6 @@ func TestASettingCannotReplaceTheMeshsOwnEntryAndABadNameIsLeftOut(t *testing.T)
if mcp.MCPServers["mesh"]["url"] != "http://127.0.0.1:4270/mcp" || mcp.MCPServers["bad name"] != nil {
t.Fatalf("%v", mcp.MCPServers)
}
// The entry bounds a call by mesh_wait's longest wait and the idle bound is laid over the operator's env
// (issue 1871): a session's wait is not cut at the agent's one-minute default.
if mcp.MCPServers["mesh"]["timeout"] != float64(660000) {
t.Errorf("the mesh entry's timeout is %v", mcp.MCPServers["mesh"]["timeout"])
}
for _, held := range []map[string]any{nil, {"CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT": "1", "FOO": "bar"}} {
var m struct {
Env map[string]any `json:"env"`
}
got := Render(Facts{Console: "x"}, Settings{ManagedSettings: map[string]any{"env": held}}, nil, "/h", nil, Config{})
_ = json.Unmarshal([]byte(got["managed-settings.json"]), &m)
if m.Env["CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT"] != "660000" || (held != nil && m.Env["FOO"] != "bar") {
t.Errorf("env %v rendered as %v", held, m.Env)
}
}
if !reflect.DeepEqual(Render(Facts{Console: "x"}, Settings{}, nil, "/h", nil, Config{}), Render(Facts{Console: "x"}, Settings{}, nil, "/h", nil, Config{})) {
t.Fatal("rendering is not deterministic")
}
@@ -4,9 +4,9 @@ package main
// the file under the agent's managed directory did not change by a byte when the module moved to Go;
// a test holds it to that renderer's own output (testdata/rendered-by-typescript.json).
func instructionsText(node, role string) string {
return "# This machine is a node of a Novox mesh\n\nWritten by the mesh's `claude-code` module. Edit the module's settings or the catalog, never this file:\nit is rewritten whenever the module renders.\n\n## Who this node is\n\n- **Node:** `" +
return "# This machine is a node of a Novox mesh\n\nWritten by the mesh's `claude-code` module. Edit the module's settings or the catalogue, never this file:\nit is rewritten whenever the module renders.\n\n## Who this node is\n\n- **Node:** `" +
node +
"`\n- **Role:** " +
role +
"\n- The other nodes, their roles and what runs where: ask the controller (`mesh-controller.nodes`,\n `mesh-controller.node`). Nothing here lists them, because a copy drifts.\n\n## How a session on this mesh works\n\nThe console is the only way to the mesh: the MCP server named `mesh`. It offers five tools, and\neverything else is an address you find and call through them:\n\n- `mesh_search` — words in, matching addresses out. `mesh_describe` — one address's arguments.\n- `mesh_call` — call an address. A seat the mesh holds once is `<seat>.<verb>` (the mesh's own verbs\n are `mesh-controller.<verb>`: `status`, `plan`, `node`, `assign`, `push`, `settings`);\n a module on a machine is `<node>/<module>.<tool>`.\n- `mesh_overview` and `mesh_machine` — the mesh's seats and machines, and what one machine runs.\n\n- **Symptom first.** For an error, a failing service or anything unexpected, search the record with the\n literal text before forming a hypothesis: the records module's `records_search`, then\n `records_read`.\n- **Ask the mesh before changing it**, and change it through the controller's verbs or the catalog.\n- **A licence** through the `anthropic-licence-manager` seat's verbs. Never edit the agent's credentials\n file by hand, never print or ask for a token.\n\n## Hard rules\n\n- A file the mesh manages is changed through the verb or the catalog that owns it, never on disk. If\n unsure, `mesh-controller.plan` for the node says what the mesh writes there.\n- Never write to a store's database by hand; schema changes are numbered migrations.\n- Never push to a main branch: a branch, a pull request, and a human approval for every merge.\n- The mesh creates no symlinks, and nobody else does either.\n- A package is declared in a module, never installed by hand.\n\n## Conventions\n\n- Commit messages are concise, in the imperative, about why.\n- Test before pushing: nodes update unattended.\n- The playbooks in the record say how research, decisions, designs, issues and hand-offs are done.\n"
"\n- The other nodes, their roles and what runs where: ask the controller (`mesh-controller.nodes`,\n `mesh-controller.node`). Nothing here lists them, because a copy drifts.\n\n## How a session on this mesh works\n\nThe console is the only way to the mesh: the MCP server named `mesh`. It offers five tools, and\neverything else is an address you find and call through them:\n\n- `mesh_search` — words in, matching addresses out. `mesh_describe` — one address's arguments.\n- `mesh_call` — call an address. A seat the mesh holds once is `<seat>.<verb>` (the mesh's own verbs\n are `mesh-controller.<verb>`: `status`, `plan`, `node`, `assign`, `push`, `settings`);\n a module on a machine is `<node>/<module>.<tool>`.\n- `mesh_overview` and `mesh_machine` — the mesh's seats and machines, and what one machine runs.\n\n- **Symptom first.** For an error, a failing service or anything unexpected, search the record with the\n literal text before forming a hypothesis: the records module's `records_search`, then\n `records_read`.\n- **Ask the mesh before changing it**, and change it through the controller's verbs or the catalogue.\n- **A licence** through the `anthropic-licence-manager` seat's verbs. Never edit the agent's credentials\n file by hand, never print or ask for a token.\n\n## Hard rules\n\n- A file the mesh manages is changed through the verb or the catalogue that owns it, never on disk. If\n unsure, `mesh-controller.plan` for the node says what the mesh writes there.\n- Never write to a store's database by hand; schema changes are numbered migrations.\n- Never push to a main branch: a branch, a pull request, and a human approval for every merge.\n- The mesh creates no symlinks, and nobody else does either.\n- A package is declared in a module, never installed by hand.\n\n## Conventions\n\n- Commit messages are concise, in the imperative, about why.\n- Test before pushing: nodes update unattended.\n- The playbooks in the record say how research, decisions, designs, issues and hand-offs are done.\n"
}
+1 -24
View File
@@ -22,7 +22,6 @@ import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
)
@@ -99,27 +98,6 @@ func jsonFile(v any) string {
return b.String()
}
// MeshWaitBoundMillis is how long the agent may wait on the mesh's console for one call: mesh_wait's longest
// wait (600 s, mesh-tools node-tools console.WaitLongest) plus a minute's margin. The agent bounds an HTTP
// server's request by the largest of 60 s, the server entry's "timeout" and MCP_TIMEOUT, and a call that
// receives nothing for CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT (5 minutes by default) is aborted
// (code.claude.com/docs/en/mcp.md). Without these every mesh_wait ended "The operation timed out." at a
// minute, whatever its timeout (issue 1871).
const MeshWaitBoundMillis = 660000
// meshWaitEnv lays the idle bound into the environment the settings give every session, the mesh's key winning
// over the operator's, like the forge's keys.
func meshWaitEnv(managed map[string]any) {
env := map[string]any{}
if held, ok := managed["env"].(map[string]any); ok {
for k, v := range held {
env[k] = v
}
}
env["CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT"] = strconv.Itoa(MeshWaitBoundMillis)
managed["env"] = env
}
// Render composes the three files. registered — what was registered through this module and applies
// here — is laid over the servers the operator set in its settings; config is the rest of what was
// registered (ADR 0216): its settings laid over the operator's `managed_settings`, its instruction sections
@@ -141,7 +119,7 @@ func RenderWithMesh(facts Facts, settings Settings, binding *Binding, helperPath
servers[name] = entry
}
}
servers[meshEntry] = map[string]any{"type": "http", "url": facts.Console, "timeout": MeshWaitBoundMillis}
servers[meshEntry] = map[string]any{"type": "http", "url": facts.Console}
// The operator's `managed_settings` (ADR 0213), set at the controller's terminal alone: nothing registered
// through this module's tools is laid over it (novox/hq issue 340).
@@ -165,7 +143,6 @@ func RenderWithMesh(facts Facts, settings Settings, binding *Binding, helperPath
managed[key] = entries
}
forgeEnv(managed, facts.ForgeCredentials)
meshWaitEnv(managed)
if binding != nil && binding.Kind == "api-key" {
managed["apiKeyHelper"] = helperPath
}
@@ -32,11 +32,11 @@
"withKey": {
"managed-mcp.json": "{\n \"mcpServers\": {\n \"anton\": {\n \"type\": \"stdio\",\n \"command\": \"node\",\n \"args\": [\n \"/a/b.js\"\n ],\n \"env\": {}\n },\n \"docs\": {\n \"type\": \"stdio\",\n \"command\": \"docs-mcp\",\n \"args\": [\n \"--x\"\n ]\n },\n \"mesh\": {\n \"type\": \"http\",\n \"url\": \"http://127.0.0.1:4270/mcp\"\n },\n \"search\": {\n \"type\": \"http\",\n \"url\": \"https://s.example/mcp\"\n }\n }\n}\n",
"managed-settings.json": "{\n \"attribution\": {\n \"commit\": \"\",\n \"pr\": \"\"\n },\n \"allowAllClaudeAiMcps\": true,\n \"apiKeyHelper\": \"/state/api-key-helper\"\n}\n",
"CLAUDE.md": "# This machine is a node of a Novox mesh\n\nWritten by the mesh's `claude-code` module. Edit the module's settings or the catalog, never this file:\nit is rewritten whenever the module renders.\n\n## Who this node is\n\n- **Node:** `workstation`\n- **Role:** the laptop\n- The other nodes, their roles and what runs where: ask the controller (`mesh-controller.nodes`,\n `mesh-controller.node`). Nothing here lists them, because a copy drifts.\n\n## How a session on this mesh works\n\nThe console is the only way to the mesh: the MCP server named `mesh`. It offers five tools, and\neverything else is an address you find and call through them:\n\n- `mesh_search` — words in, matching addresses out. `mesh_describe` — one address's arguments.\n- `mesh_call` — call an address. A seat the mesh holds once is `<seat>.<verb>` (the mesh's own verbs\n are `mesh-controller.<verb>`: `status`, `plan`, `node`, `assign`, `push`, `settings`);\n a module on a machine is `<node>/<module>.<tool>`.\n- `mesh_overview` and `mesh_machine` — the mesh's seats and machines, and what one machine runs.\n\n- **Symptom first.** For an error, a failing service or anything unexpected, search the record with the\n literal text before forming a hypothesis: the records module's `records_search`, then\n `records_read`.\n- **Ask the mesh before changing it**, and change it through the controller's verbs or the catalog.\n- **A licence** through the `anthropic-licence-manager` seat's verbs. Never edit the agent's credentials\n file by hand, never print or ask for a token.\n\n## Hard rules\n\n- A file the mesh manages is changed through the verb or the catalog that owns it, never on disk. If\n unsure, `mesh-controller.plan` for the node says what the mesh writes there.\n- Never write to a store's database by hand; schema changes are numbered migrations.\n- Never push to a main branch: a branch, a pull request, and a human approval for every merge.\n- The mesh creates no symlinks, and nobody else does either.\n- A package is declared in a module, never installed by hand.\n\n## Conventions\n\n- Commit messages are concise, in the imperative, about why.\n- Test before pushing: nodes update unattended.\n- The playbooks in the record say how research, decisions, designs, issues and hand-offs are done.\n"
"CLAUDE.md": "# This machine is a node of a Novox mesh\n\nWritten by the mesh's `claude-code` module. Edit the module's settings or the catalogue, never this file:\nit is rewritten whenever the module renders.\n\n## Who this node is\n\n- **Node:** `workstation`\n- **Role:** the laptop\n- The other nodes, their roles and what runs where: ask the controller (`mesh-controller.nodes`,\n `mesh-controller.node`). Nothing here lists them, because a copy drifts.\n\n## How a session on this mesh works\n\nThe console is the only way to the mesh: the MCP server named `mesh`. It offers five tools, and\neverything else is an address you find and call through them:\n\n- `mesh_search` — words in, matching addresses out. `mesh_describe` — one address's arguments.\n- `mesh_call` — call an address. A seat the mesh holds once is `<seat>.<verb>` (the mesh's own verbs\n are `mesh-controller.<verb>`: `status`, `plan`, `node`, `assign`, `push`, `settings`);\n a module on a machine is `<node>/<module>.<tool>`.\n- `mesh_overview` and `mesh_machine` — the mesh's seats and machines, and what one machine runs.\n\n- **Symptom first.** For an error, a failing service or anything unexpected, search the record with the\n literal text before forming a hypothesis: the records module's `records_search`, then\n `records_read`.\n- **Ask the mesh before changing it**, and change it through the controller's verbs or the catalogue.\n- **A licence** through the `anthropic-licence-manager` seat's verbs. Never edit the agent's credentials\n file by hand, never print or ask for a token.\n\n## Hard rules\n\n- A file the mesh manages is changed through the verb or the catalogue that owns it, never on disk. If\n unsure, `mesh-controller.plan` for the node says what the mesh writes there.\n- Never write to a store's database by hand; schema changes are numbered migrations.\n- Never push to a main branch: a branch, a pull request, and a human approval for every merge.\n- The mesh creates no symlinks, and nobody else does either.\n- A package is declared in a module, never installed by hand.\n\n## Conventions\n\n- Commit messages are concise, in the imperative, about why.\n- Test before pushing: nodes update unattended.\n- The playbooks in the record say how research, decisions, designs, issues and hand-offs are done.\n"
},
"plain": {
"managed-mcp.json": "{\n \"mcpServers\": {\n \"mesh\": {\n \"type\": \"http\",\n \"url\": \"http://127.0.0.1:4270/mcp\"\n }\n }\n}\n",
"managed-settings.json": "{\n \"attribution\": {\n \"commit\": \"\",\n \"pr\": \"\"\n },\n \"allowAllClaudeAiMcps\": true\n}\n",
"CLAUDE.md": "# This machine is a node of a Novox mesh\n\nWritten by the mesh's `claude-code` module. Edit the module's settings or the catalog, never this file:\nit is rewritten whenever the module renders.\n\n## Who this node is\n\n- **Node:** `workstation`\n- **Role:** not stated — set it in this module's settings for the node\n- The other nodes, their roles and what runs where: ask the controller (`mesh-controller.nodes`,\n `mesh-controller.node`). Nothing here lists them, because a copy drifts.\n\n## How a session on this mesh works\n\nThe console is the only way to the mesh: the MCP server named `mesh`. It offers five tools, and\neverything else is an address you find and call through them:\n\n- `mesh_search` — words in, matching addresses out. `mesh_describe` — one address's arguments.\n- `mesh_call` — call an address. A seat the mesh holds once is `<seat>.<verb>` (the mesh's own verbs\n are `mesh-controller.<verb>`: `status`, `plan`, `node`, `assign`, `push`, `settings`);\n a module on a machine is `<node>/<module>.<tool>`.\n- `mesh_overview` and `mesh_machine` — the mesh's seats and machines, and what one machine runs.\n\n- **Symptom first.** For an error, a failing service or anything unexpected, search the record with the\n literal text before forming a hypothesis: the records module's `records_search`, then\n `records_read`.\n- **Ask the mesh before changing it**, and change it through the controller's verbs or the catalog.\n- **A licence** through the `anthropic-licence-manager` seat's verbs. Never edit the agent's credentials\n file by hand, never print or ask for a token.\n\n## Hard rules\n\n- A file the mesh manages is changed through the verb or the catalog that owns it, never on disk. If\n unsure, `mesh-controller.plan` for the node says what the mesh writes there.\n- Never write to a store's database by hand; schema changes are numbered migrations.\n- Never push to a main branch: a branch, a pull request, and a human approval for every merge.\n- The mesh creates no symlinks, and nobody else does either.\n- A package is declared in a module, never installed by hand.\n\n## Conventions\n\n- Commit messages are concise, in the imperative, about why.\n- Test before pushing: nodes update unattended.\n- The playbooks in the record say how research, decisions, designs, issues and hand-offs are done.\n"
"CLAUDE.md": "# This machine is a node of a Novox mesh\n\nWritten by the mesh's `claude-code` module. Edit the module's settings or the catalogue, never this file:\nit is rewritten whenever the module renders.\n\n## Who this node is\n\n- **Node:** `workstation`\n- **Role:** not stated — set it in this module's settings for the node\n- The other nodes, their roles and what runs where: ask the controller (`mesh-controller.nodes`,\n `mesh-controller.node`). Nothing here lists them, because a copy drifts.\n\n## How a session on this mesh works\n\nThe console is the only way to the mesh: the MCP server named `mesh`. It offers five tools, and\neverything else is an address you find and call through them:\n\n- `mesh_search` — words in, matching addresses out. `mesh_describe` — one address's arguments.\n- `mesh_call` — call an address. A seat the mesh holds once is `<seat>.<verb>` (the mesh's own verbs\n are `mesh-controller.<verb>`: `status`, `plan`, `node`, `assign`, `push`, `settings`);\n a module on a machine is `<node>/<module>.<tool>`.\n- `mesh_overview` and `mesh_machine` — the mesh's seats and machines, and what one machine runs.\n\n- **Symptom first.** For an error, a failing service or anything unexpected, search the record with the\n literal text before forming a hypothesis: the records module's `records_search`, then\n `records_read`.\n- **Ask the mesh before changing it**, and change it through the controller's verbs or the catalogue.\n- **A licence** through the `anthropic-licence-manager` seat's verbs. Never edit the agent's credentials\n file by hand, never print or ask for a token.\n\n## Hard rules\n\n- A file the mesh manages is changed through the verb or the catalogue that owns it, never on disk. If\n unsure, `mesh-controller.plan` for the node says what the mesh writes there.\n- Never write to a store's database by hand; schema changes are numbered migrations.\n- Never push to a main branch: a branch, a pull request, and a human approval for every merge.\n- The mesh creates no symlinks, and nobody else does either.\n- A package is declared in a module, never installed by hand.\n\n## Conventions\n\n- Commit messages are concise, in the imperative, about why.\n- Test before pushing: nodes update unattended.\n- The playbooks in the record say how research, decisions, designs, issues and hand-offs are done.\n"
}
}
-9
View File
@@ -312,15 +312,6 @@ read-only. With a `user` it adds the teams that user is in and its effective rig
listing those above read: the check that a build key's user, `nox-builder` in `builders`, reads and pushes nothing. The
tools' token lacks `read:organization` (the forge answers 403), so the read goes with the administrator's login, GET only.
### Two settings have named tools, and a retargeted pull request is judged again
`gitea_api` refuses a repository's settings and a pull request's base (guard.ts). Issue 1422 note 7 gave each its tool:
`gitea_default_branch_set` (owner, repo, branch, why) and `gitea_pull_base_set` (owner, repo, number, base, why). Both
act as the tools' account, need a reason, refuse a branch the repository does not have, and answer the value before and
after; a default must also be a branch a protection rule guards, and only an open pull request has its base changed.
A pull request's announced head is kept under `owner/repo#number@base`, so a retarget (same head, new base) is
announced again into the new base by the next poll instead of being skipped as already announced.
### The merging account writes the repositories the mesh delivers
`mesh-tools` sets every commit status and merges; outside the organisation it only reads (above), so a pull request of
-24
View File
@@ -834,30 +834,6 @@ export class GiteaClient {
return (raw ?? []).map((b) => ({ name: String(b?.name ?? ""), commit: String(b?.commit?.id ?? ""), protected: Boolean(b?.protected) }));
}
/** One branch as the forge keeps it: whether a protection rule guards it; null when the repository has no such branch. */
async branchState(owner: string, repo: string, branch: string): Promise<{ protected: boolean } | null> {
try {
const b = await this.request<any>(`${repoPath(owner, repo)}/branches/${pathSegments("branch", branch)}`);
return { protected: Boolean(b?.protected) };
} catch (err) {
if (/: 404 /.test(err instanceof Error ? err.message : "")) return null;
throw err;
}
}
/** Make a branch the repository's default (issue 1422): what the forge shows, clones and opens pull requests against. */
async setDefaultBranch(owner: string, repo: string, branch: string): Promise<GiteaRepo> {
return GiteaClient.mapRepo(await this.request<any>(repoPath(owner, repo), { method: "PATCH", body: JSON.stringify({ default_branch: branch }) }));
}
/** Change the branch an open pull request merges into (issue 1422). The head stays; the forge recomputes the diff. */
async setPullBase(owner: string, repo: string, index: number, base: string): Promise<GiteaPull> {
indexOf(index);
return GiteaClient.mapPull(
await this.request<any>(`${repoPath(owner, repo)}/pulls/${index}`, { method: "PATCH", body: JSON.stringify({ base }) }),
);
}
async deleteBranch(owner: string, repo: string, branch: string): Promise<void> {
await this.request(`${repoPath(owner, repo)}/branches/${pathSegments("branch", branch)}`, { method: "DELETE" });
}
-2
View File
@@ -12,8 +12,6 @@
// forge as themselves;
// - `gitea_branch_protection_set` lets no person push and no administrator merge past a rule, and on main keeps
// the tools' account the only one that merges; it requires no status, as no rule of the mesh does (ADR 0534 §5);
// - `gitea_default_branch_set` and `gitea_pull_base_set` are the two settings gitea_api refuses, as named tools: a branch that
// exists (and, for a default, that a rule guards), a stated reason, the tools' account, the value before and after (issue 1422);
// - `gitea_merge_pull_request` merges only into a branch that refuses its push, only a head whose mesh/check passed
// against the trunk's head, approved by the operator where the branch requires no status (ADR 0534 §4), and only
// that head;
+66 -67
View File
@@ -53,9 +53,8 @@ import { announce, keepWatermark, readWatermark } from "./announce.js";
import { mergeTool } from "./merge.js";
import { GiteaAdmin, GiteaClient, movedSince } from "./client.js";
import { keepMainRules, mainRulesStep } from "./mainrules.js";
import { CHECK_CONTEXT, CHECK_STATUS, REPO_CHECK_CONTEXT, commentFor, composedGate, groupGateStatus, headKey, maintained,
requiredOf, statusesFor, writesGate, type Announced, type Checked, repoCheckFacts } from "./pulls.js";
import { actOn, announceNewHeads, startPass } from "./watch.js";
import { CHECK_CONTEXT, CHECK_STATUS, REPO_CHECK_CONTEXT, commentFor, composedGate, groupGateStatus, headsToAnnounce, maintained,
requiredOf, statusesFor, writesGate, type Announced, type Checked, repoCheckFacts, reposToLook } from "./pulls.js";
import { GateWriter } from "./gate.js";
import { HOOK_PATH, HOOK_PORT, Pace, claimHead, ensureSystemHook, eventsTool, keptSecret, receiver, type ForgeEvent } from "./webhook.js";
import { keepSiblings, noteComposed, noteVerdict, readSiblings, siblingsFile, siblingsOf, weighSiblings } from "./siblings.js";
@@ -139,7 +138,12 @@ async function pollMerged(client: GiteaClient): Promise<void> {
// Closed unmerged (novox/hq ADR 0239): announced once, since the watching began, so its delivery stops.
const closedKey = `closed:${repo.full_name}#${pull.number}`;
if (!pull.merged && pull.state === "closed" && !announced.has(closedKey)) {
if (primedMerges && !!pull.updated_at && !!since && pull.updated_at > since) await announceClosed(client, repo, pull);
if (primedMerges && !!pull.updated_at && !!since && pull.updated_at > since) {
await announce("pull.closed", { owner: repo.owner, repo: repo.name, number: pull.number, title: pull.title,
head: pull.head, head_sha: pull.head_sha, base: pull.base, html_url: pull.html_url });
console.log(`[gitea] announced ${repo.full_name}#${pull.number} closed unmerged`);
await siblingMoves(client, repo.full_name, pull.number);
}
announced.add(closedKey);
continue;
}
@@ -164,23 +168,6 @@ async function pollMerged(client: GiteaClient): Promise<void> {
type RepoOf = { owner: string; name: string; full_name: string; clone_url?: string };
type PullOf = Awaited<ReturnType<GiteaClient["listPullRequests"]>>[number];
/** A pull request closed without a merge, announced once (ADR 0239): by its event, or by the start's pass. */
async function announceClosed(client: GiteaClient, repo: RepoOf, pull: PullOf): Promise<boolean> {
const closedKey = `closed:${repo.full_name}#${pull.number}`;
if (pull.merged || pull.state !== "closed" || announced.has(closedKey)) return false;
announced.add(closedKey);
try {
await announce("pull.closed", { owner: repo.owner, repo: repo.name, number: pull.number, title: pull.title,
head: pull.head, head_sha: pull.head_sha, base: pull.base, html_url: pull.html_url });
} catch (err) {
announced.delete(closedKey);
throw err;
}
console.log(`[gitea] announced ${repo.full_name}#${pull.number} closed unmerged`);
await siblingMoves(client, repo.full_name, pull.number);
return true;
}
/** **A merge, announced once, whichever path saw it first** (novox/hq issue 729): the poll or the forge's event. */
async function announceMerge(client: GiteaClient, repo: RepoOf, pull: PullOf): Promise<boolean> {
if (!pull.merged || !pull.merge_commit_sha || announced.has(pull.merge_commit_sha)) return false;
@@ -256,7 +243,7 @@ let heads: Announced = {};
let primedPulls = false;
/** **A head, announced once, whichever path saw it first** (novox/hq issue 729): the poll or the forge's event. */
async function announceHead(client: GiteaClient, repo: RepoOf, pull: OpenOf): Promise<boolean> {
const key = headKey(repo.full_name, pull.number, pull.base);
const key = `${repo.full_name}#${pull.number}`;
const sha = String(pull.head_sha ?? "");
const before = heads[key];
// Claimed before the first wait, so the other path finds it taken while this one is still announcing.
@@ -294,18 +281,43 @@ async function alreadyChecked(client: GiteaClient, repo: RepoOf, pull: OpenOf):
}
let lastPullLook = "";
/** The pass over every open pull request: run at the start and when the receiver listens, never on a timer (issue 1422). */
async function passPulls(client: GiteaClient): Promise<void> {
// **A sweep now and then looks at every repository** (novox/hq issue 347), whatever moved: the floor is a
// heuristic, and a heuristic that misses is caught by the next sweep rather than never.
const SWEEP_MS = 10 * 60_000;
let lastSweep = 0;
async function pollPulls(client: GiteaClient): Promise<void> {
const began = new Date().toISOString();
const floor = lastPullLook ? new Date(Date.parse(lastPullLook) - MARGIN_MS).toISOString() : "";
const dayAgo = new Date(Date.now() - 24 * 3600_000).toISOString();
for (const repo of await client.listAllRepos()) {
// Every open pull request, paged (novox/hq issue 579).
const open = await client.listOpenPullsSince(repo.owner, repo.name, "");
await announceNewHeads(repo.full_name, open, heads, primedPulls, dayAgo, {
alreadyChecked: (pull) => alreadyChecked(client, repo, pull),
announceHead: (pull) => announceHead(client, repo, pull),
missed: (what) => pace.miss(what),
});
// A pull request opened, reopened or retargeted moves its own update time and not its repository's: the
// pull requests updated since the floor are found by their own (issue 347). A search that fails is a sweep.
let sweep = Date.now() - lastSweep >= SWEEP_MS;
let updated: { owner: string; name: string; updated_at?: string }[] = [];
if (floor && !sweep) {
try {
updated = await client.searchOpenPulls(floor);
} catch (err) {
console.error(`[gitea] the pull requests updated lately could not be searched, so every repository is looked at — ${err instanceof Error ? err.message : err}`);
sweep = true;
}
}
if (sweep) lastSweep = Date.now();
for (const repo of reposToLook(await client.listAllRepos(), floor, updated, sweep)) {
// Every open pull request updated since the floor, paged (novox/hq issue 579): the newest 20 alone left a head
// beyond them unannounced. A sweep and the first pass read every page.
const open = await client.listOpenPullsSince(repo.owner, repo.name, sweep ? "" : floor);
for (const pull of headsToAnnounce(repo.full_name, open, heads)) {
const key = `${repo.full_name}#${pull.number}`;
const fresh = primedPulls || (!!pull.updated_at && pull.updated_at > dayAgo);
// The first look after a start remembers nothing: a head the forge already shows a merge check of was announced.
if (fresh && !primedPulls && await alreadyChecked(client, repo, pull)) {
heads[key] = String(pull.head_sha);
continue;
}
if (fresh) {
if (await announceHead(client, repo, pull)) pace.miss(`${key} at ${String(pull.head_sha).slice(0, 8)}`);
} else heads[key] = String(pull.head_sha);
}
if (await trunksMoved(client, repo.owner, repo.name)) changedTrunks = true;
}
if (changedTrunks) keepTrunks();
@@ -485,9 +497,6 @@ const checks = new CheckStatuses({
/** How fast the polls look: 30 s until the forge's events are heard, five minutes while they are; and what
* gitea_events says of them (webhook.ts). */
const pace = new Pace();
/** Asks the pass over every repository again, shortly and once (set where the pass is made): an event that could not be
* acted on is not lost until the next start. */
let catchUp: () => void = () => {};
if (!gitea) pace.unheard("the forge is not watched: no way to a token", false);
// The states this module keeps and which others may read, said on the bus before it serves (novox/hq ADR 0495 clause 2).
@@ -513,15 +522,22 @@ registerModuleTools("gitea", () => [eventsTool(pace), ...readAllTools(readAll),
gates,
}), mergeTool(gitea, { gates })] : [])]);
/** What the forge's event asks of the announcer at once (issue 729, 1422): see watch.ts. */
const actOnEvent = (client: GiteaClient, event: ForgeEvent): Promise<void> => actOn<RepoOf, PullOf>(event, {
getRepo: (o, r) => client.getRepo(o, r),
getPull: (o, r, n) => client.getPullRequest(o, r, n) as Promise<PullOf & { state?: string; merged?: boolean }>,
announceHead: (repo, pull) => announceHead(client, repo, pull as OpenOf),
announceMerge: (repo, pull) => announceMerge(client, repo, pull),
announceClosed: (repo, pull) => announceClosed(client, repo, pull),
siblingMoves: (full, n) => siblingMoves(client, full, n),
});
/** What the forge's event asks of the announcer at once (issue 729): a new head is announced, and a merge. */
async function actOn(client: GiteaClient, event: ForgeEvent): Promise<void> {
const b = event.body as { owner?: string; repo?: string; number?: number };
if (!b.owner || !b.repo || !b.number) return;
if (event.name === "forge.pull-request.closed") {
// Closed unmerged is a sibling's move; a merge is weighed with its announcement below (ADR 0382 §5).
if (!(event.body as { merged?: boolean }).merged) await siblingMoves(client, `${b.owner}/${b.repo}`, b.number);
return;
}
const head = ["forge.pull-request.opened", "forge.pull-request.synchronized", "forge.pull-request.reopened"].includes(event.name);
const merged = event.name === "forge.pull-request.merged";
if (!head && !merged) return;
const [repo, pull] = await Promise.all([client.getRepo(b.owner, b.repo), client.getPullRequest(b.owner, b.repo, b.number)]);
if (head && pull.state === "open") await announceHead(client, repo, pull);
if (merged) await announceMerge(client, repo, pull);
}
/**
* **The receiver, and the forge's one system webhook pointing at it** (issue 729). The secret is minted and kept beside
@@ -547,12 +563,7 @@ async function listenForForge(client: GiteaClient): Promise<boolean> {
// A repository made, or one not yet seen readable, is granted read before anything acts on it (readall.ts).
await Promise.resolve().then(() => readAll().onEvent(event)).catch((err) =>
console.error(`[gitea] whether the mesh's accounts read the repository of ${event.name} could not be settled — ${err instanceof Error ? err.message : err}`));
try {
await actOnEvent(client, event);
} catch (err) {
catchUp();
throw err;
}
await actOn(client, event);
} });
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
@@ -601,9 +612,9 @@ if (gitea) {
// polls slow to every five minutes and announce only what no event said (Pace); otherwise they keep 30 s.
// **Not awaited** (novox/hq issue 1726): the receiver's set-up asks the forge's admin API, and the runtime kills a bundle
// whose import has not ended in its 10 s handshake and never starts it again; a forge slow to answer while every bundle
// of the node starts left gitea_commit_status, gitea_merge_pull_request and gitea_events served nowhere. The pass below
// runs again once it is listening, so nothing said before is missed; listenForForge says its own failure.
const listenOk = listenForForge(client);
// of the node starts left gitea_commit_status, gitea_merge_pull_request and gitea_events served nowhere. Until it is
// listening, Pace keeps the polls at 30 s, so nothing is missed meanwhile; listenForForge says its own failure.
void listenForForge(client);
// The start's one pass over every repository (readall.ts), not awaited for the same reason. A forge not answering yet
// is asked again, a minute apart, until one pass has run; after that only the forge's events grant.
// An account of the list the forge does not hold yet (the forge-account provider makes nox-builder and nox-agent when
@@ -635,20 +646,8 @@ if (gitea) {
// Only while the setting keep-main-rules is true (mainrules.ts); false, the default, leaves every repository's rule as set.
tick(mainRulesStep(keepMainRules(), () => GiteaAdmin.fromEnv().ensureMainMerges("novox"), (line) => console.log(line)), 600_000);
tick(() => pollRepos(client), 60_000);
// **No timer asks the forge for pull requests or merges** (issue 1422): the forge's events announce them. One pass over
// every repository runs at the start and again once the receiver listens, so what happened while the module was away or
// not yet listening is announced; passes run one at a time, a failed one is asked again a minute later.
let passes: Promise<void> = Promise.resolve();
const pass = (): Promise<void> => (passes = passes.catch(() => {}).then(() =>
startPass(async () => { await pollMerged(client); await passPulls(client); }, { retryMs: 60_000 })));
void pass();
let catchUpAsked = false;
catchUp = () => {
if (catchUpAsked) return;
catchUpAsked = true;
setTimeout(() => { catchUpAsked = false; void pass(); }, 30_000);
};
void listenOk.then((ok) => (ok ? pass() : undefined));
tick(() => pollMerged(client), () => pace.every());
tick(() => pollPulls(client), () => pace.every());
// Bound again until they hold, and not awaited (bind.ts, issue 1793): the runtime kills a bundle that has not answered its
// handshake in 10 s, so the import must end while a refused bind is still asked again.
bindInBackground([
+2 -8
View File
@@ -141,19 +141,13 @@ export function planText(plan: ChangePlan): string {
return lines.join("\n");
}
/** The heads already announced, keyed by `headKey`, so a restart announces nothing twice. */
/** The heads already announced, keyed `owner/repo#number`, so a restart announces nothing twice. */
export type Announced = Record<string, string>;
/** The key a pull request's announced head is kept under: `owner/repo#number@base`. The base is in it because a pull
* request retargeted keeps its head, and a head judged into one base is not judged into another (issue 1422, de-spiegel #6). */
export function headKey(full: string, number: number, base?: string): string {
return `${full}#${number}@${base ?? ""}`;
}
/** Which open pull requests have a head not yet announced. A pull request merged or closed is not
* open and is never asked about. */
export function headsToAnnounce(full: string, pulls: GiteaPull[], announced: Announced): GiteaPull[] {
return pulls.filter((p) => p.state === "open" && !!p.head_sha && announced[headKey(full, p.number, p.base)] !== p.head_sha);
return pulls.filter((p) => p.state === "open" && !!p.head_sha && announced[`${full}#${p.number}`] !== p.head_sha);
}
/** A pull request the forge found updated, by its repository: what `searchOpenPulls` answers. */
+4 -67
View File
@@ -34,12 +34,6 @@ const state = {
// refuses it the rules' list, as gitea's reqAdmin does, and it reads a branch's protection from the branch.
admin: false,
lastCommit: "2026-01-01T00:00:00Z",
// The repository's default branch and pull request 7's base, as the forge keeps them (issue 1422 note 7).
defaultBranch: "main",
base: "main",
prState: "open",
// Branches the forge answers 404 for; "scratch" exists but no protection rule guards it.
absent: ["nope"],
// The pull request's head; the head the merge commit joined (the same, unless a test says otherwise) — the forge's
// record of the pull request keeps saying `head` either way, as it would in the race issue 381 is about; and the
// merge commit's own sha.
@@ -72,10 +66,7 @@ beforeEach(() => {
state.statuses = judgedAt(TRUNK);
state.trunk = TRUNK;
state.emitted = [];
state.rules = [protectedMain(), { rule_name: "release/*", enable_push: false }];
state.defaultBranch = "main";
state.base = "main";
state.prState = "open";
state.rules = [protectedMain()];
state.admin = false;
state.head = REVIEWED;
state.landed = "";
@@ -107,22 +98,12 @@ const server = createServer(async (req, res) => {
state.asked.push(`${method} ${path}${url.search}`);
if (method !== "GET") state.sent.push({ method, path, body });
const repo = "/repos/novox/mesh-catalog";
if (method === "GET" && path === repo) return json(res, 200, { full_name: "novox/mesh-catalog", default_branch: state.defaultBranch });
if (method === "PATCH" && path === repo) {
if (body?.default_branch) state.defaultBranch = body.default_branch;
return json(res, 200, { full_name: "novox/mesh-catalog", default_branch: state.defaultBranch });
}
if (method === "PATCH" && path === `${repo}/pulls/7`) {
if (body?.base) state.base = body.base;
return json(res, 201, { number: 7, title: "x", state: state.prState, merged: false, head: { ref: "feat/x", sha: state.head },
base: { ref: state.base }, html_url: "http://fake/7" });
}
if (method === "GET" && path === repo) return json(res, 200, { full_name: "novox/mesh-catalog", default_branch: "main" });
if (path.startsWith(`${repo}/branch_protections`) && !state.admin) {
return json(res, 403, { message: "user should be an owner or a collaborator with admin write of a repository" });
}
if (method === "GET" && path === `${repo}/branch_protections`) return json(res, 200, state.rules);
const branch = method === "GET" && path.startsWith(`${repo}/branches/`) ? decodeURIComponent(path.slice(`${repo}/branches/`.length)) : null;
if (branch !== null && state.absent.includes(branch)) return json(res, 404, { message: "branch does not exist" });
if (branch !== null) {
// As the forge says it to any reader of the code: the rule that covers the branch, as the forge matches it.
const rule = (state.rules as any[]).find((r) => ruleCovers(String(r.rule_name ?? r.branch_name), branch));
@@ -144,8 +125,8 @@ const server = createServer(async (req, res) => {
return json(res, 200, [{ commit: { committer: { date: state.lastCommit } } }]);
}
if (method === "GET" && path === `${repo}/pulls/7`) {
return json(res, 200, { number: 7, title: "x", state: state.merged ? "closed" : state.prState, merged: state.merged,
head: { ref: "feat/x", sha: state.head }, base: { ref: state.base }, html_url: "http://fake/7",
return json(res, 200, { number: 7, title: "x", state: state.merged ? "closed" : "open", merged: state.merged,
head: { ref: "feat/x", sha: state.head }, base: { ref: "main" }, html_url: "http://fake/7",
merge_commit_sha: state.merged ? state.mergeCommit : null });
}
if (method === "GET" && path === `${repo}/git/commits/${state.mergeCommit}`) {
@@ -828,47 +809,3 @@ test("gitea_merge_pull_request judges a main requiring mesh/repo-check alone on
state.statuses = [judgedAt(TRUNK)[1]];
assert.equal(((await merge()) as Record<string, unknown>).merged, true);
});
// Issue 1422 note 7: the two settings gitea_api refuses (ADR 0266) have named tools, held to the same guard as
// gitea_branch_protection_set: the tools' account, a stated reason, a branch that exists and that a rule guards.
test("gitea_default_branch_set answers the default before and after, and refuses a branch that is missing, unguarded or unexplained", async () => {
const set = (args: Record<string, unknown>) =>
tool("gitea_default_branch_set").run({ owner: "novox", repo: "mesh-catalog", why: "the trunk was recorded as unknown", ...args });
await assert.rejects(set({ branch: "nope" }), /no branch nope/);
await assert.rejects(set({ branch: "scratch" }), /no protection rule/);
await assert.rejects(set({ branch: "release/1", why: " " }), /why/);
await assert.rejects(set({ branch: ".." }), /dot segment|not a branch/);
assert.deepEqual(writes(), []);
assert.deepEqual(await set({ branch: "release/1" }), { branch: "release/1", before: "main", after: "release/1", changed: true,
why: "the trunk was recorded as unknown" });
assert.deepEqual(writes(), ["PATCH /repos/novox/mesh-catalog"]);
assert.deepEqual(state.sent[0].body, { default_branch: "release/1" });
assert.equal(state.defaultBranch, "release/1");
state.sent = [];
assert.equal(((await set({ branch: "release/1" })) as any).changed, false, "already the default: nothing is sent");
assert.deepEqual(writes(), []);
});
test("gitea_pull_base_set answers the base before and after, and refuses a base that is missing, a closed pull request or no reason", async () => {
const set = (args: Record<string, unknown>) =>
tool("gitea_pull_base_set").run({ owner: "novox", repo: "mesh-catalog", number: 7, why: "it was opened against the wrong trunk", ...args });
await assert.rejects(set({ base: "nope" }), /no branch nope/);
await assert.rejects(set({ base: "release/1", why: "" }), /why/);
await assert.rejects(set({ base: "release/1", number: 0 }), /pull request's number/);
state.prState = "closed";
await assert.rejects(set({ base: "release/1" }), /not open/);
state.prState = "open";
assert.deepEqual(writes(), []);
assert.deepEqual(await set({ base: "release/1" }), { number: 7, before: "main", after: "release/1", changed: true,
why: "it was opened against the wrong trunk" });
assert.deepEqual(writes(), ["PATCH /repos/novox/mesh-catalog/pulls/7"]);
assert.deepEqual(state.sent[0].body, { base: "release/1" });
assert.equal(state.base, "release/1");
});
test("the two new tools are named for what mesh_search is asked, and gitea_api still refuses both settings", () => {
assert.match(tool("gitea_default_branch_set").description, /default branch/i);
assert.match(tool("gitea_pull_base_set").description, /pull request.s base/i);
assert.ok("refused" in judgeApiCall("PATCH", "/repos/a/b", { default_branch: "x" }));
assert.ok("refused" in judgeApiCall("PATCH", "/repos/a/b/pulls/7", { base: "x" }));
});
+2 -2
View File
@@ -45,7 +45,7 @@ test("a new head beyond the newest 20 open pull requests is announced, exactly o
const { headsToAnnounce } = await import("../pulls.ts");
// 25 open, every head announced before; #3 — the 23rd most recently updated — got a new head.
const announced: Record<string, string> = {};
for (let n = 1; n <= 25; n++) announced[`novox/hq#${n}@main`] = sha(n, "a");
for (let n = 1; n <= 25; n++) announced[`novox/hq#${n}`] = sha(n, "a");
const { client, server, asked } = await serve(25, { 3: sha(3, "b") });
try {
// The fault: the newest 20 alone do not hold it.
@@ -58,7 +58,7 @@ test("a new head beyond the newest 20 open pull requests is announced, exactly o
const open = await client.listOpenPullsSince("novox", "hq", "");
for (const p of headsToAnnounce("novox/hq", open, announced)) {
said.push(`#${p.number}@${p.head_sha}`);
announced[`novox/hq#${p.number}@${p.base}`] = String(p.head_sha);
announced[`novox/hq#${p.number}`] = String(p.head_sha);
}
}
assert.deepEqual(said, [`#3@${sha(3, "b")}`], "the new head past the newest 20, announced once over two passes");
+2 -13
View File
@@ -8,27 +8,16 @@ import { createServer } from "node:http";
test("each open pull request's new head is announced once, and nothing closed or merged", async () => {
const { headsToAnnounce } = await import("../pulls.ts");
const pulls = [
{ number: 1, title: "a", state: "open", merged: false, head_sha: "aaa", base: "main", html_url: "" },
{ number: 1, title: "a", state: "open", merged: false, head_sha: "aaa", html_url: "" },
{ number: 2, title: "b", state: "open", merged: false, head_sha: "bbb", html_url: "" },
{ number: 3, title: "c", state: "closed", merged: true, head_sha: "ccc", html_url: "" },
{ number: 4, title: "d", state: "open", merged: false, html_url: "" },
];
const announced = { "novox/mesh-catalog#1@main": "aaa", "novox/mesh-catalog#2@": "old" };
const announced = { "novox/mesh-catalog#1": "aaa", "novox/mesh-catalog#2": "old" };
assert.deepEqual(headsToAnnounce("novox/mesh-catalog", pulls, announced).map((p) => p.number), [2],
"only a head not announced, of a pull request that is open");
});
test("a pull request retargeted keeps its head and is announced again, into its new base (de-spiegel #6)", async () => {
const { headsToAnnounce, headKey } = await import("../pulls.ts");
const was = { number: 6, title: "a", state: "open", merged: false, head_sha: "aaa", base: "old-trunk", html_url: "" };
const announced: Record<string, string> = { [headKey("novox/de-spiegel", 6, "old-trunk")]: "aaa" };
assert.deepEqual(headsToAnnounce("novox/de-spiegel", [was], announced), [], "the same head into the same base is announced once");
const retargeted = { ...was, base: "main" };
assert.deepEqual(headsToAnnounce("novox/de-spiegel", [retargeted], announced).map((p) => p.number), [6],
"the same head into a new base is judged afresh");
assert.notEqual(headKey("novox/de-spiegel", 6, "main"), headKey("novox/de-spiegel", 6, "old-trunk"));
});
test("a verdict is the head commit's status; an error is the forge's error, never a success", async () => {
const { statusFor, commentFor, CHECK_CONTEXT } = await import("../pulls.ts");
const base = { owner: "novox", repo: "mesh-catalog", number: 7, commit: "0123456789abcdef", id: "build-1", on: "laptop" };
-1
View File
@@ -539,7 +539,6 @@ test("the tools register once there is a way to a token, and the first call mint
"gitea_list_branches",
"gitea_delete_branch",
"gitea_branch_protection_get", "gitea_team_rights", "gitea_branch_protection_set",
"gitea_default_branch_set", "gitea_pull_base_set",
"gitea_note_append", "gitea_delivery_view", "gitea_commit_statuses", "gitea_open_pulls", "gitea_commit_trees", "gitea_contains",
"gitea_list_labels", "gitea_create_label",
"gitea_api",
-73
View File
@@ -1,73 +0,0 @@
import assert from "node:assert/strict";
import { mock, test } from "node:test";
import type { GiteaPull } from "../client.ts";
// **No poll of the forge** (issue 1422, notes 10 and 11): the forge's events announce heads and merges; a pass runs once at
// the start and when the receiver listens.
const edited = (base: string) => ({ name: "forge.pull-request.edited", body: { owner: "novox", repo: "hq", number: 7, base, merged: false } });
function deps() {
const calls: string[] = [];
return { calls, d: {
getRepo: async () => ({ r: 1 }),
getPull: async () => ({ state: "open", base: "trunk" }) as any,
announceHead: async () => { calls.push("head"); },
announceMerge: async () => { calls.push("merge"); },
announceClosed: async () => { calls.push("closed"); },
siblingMoves: async () => { calls.push("siblings"); },
} };
}
test("an edited event announces the head into the base it now has, without a poll", async () => {
const { actOn } = await import("../watch.ts");
const { calls, d } = deps();
await actOn(edited("trunk"), d);
assert.deepEqual(calls, ["head"]);
});
test("a close without a merge is announced by its event, a merged close is left to the merge event", async () => {
const { actOn } = await import("../watch.ts");
const { calls, d } = deps();
await actOn({ name: "forge.pull-request.closed", body: { owner: "novox", repo: "hq", number: 7, merged: false } }, d);
assert.deepEqual(calls, ["closed", "siblings"]);
calls.length = 0;
await actOn({ name: "forge.pull-request.closed", body: { owner: "novox", repo: "hq", number: 7, merged: true } }, d);
assert.deepEqual(calls, []);
});
test("no timer polls after the start: one pass ends and nothing is scheduled; a failed one is asked again", async () => {
const { startPass } = await import("../watch.ts");
mock.timers.enable({ apis: ["setTimeout", "setInterval"] });
try {
let runs = 0;
await startPass(async () => { runs++; }, { retryMs: 60_000, log: () => {} });
mock.timers.tick(24 * 3600_000);
assert.equal(runs, 1, "a day later the forge was not asked again");
let tries = 0;
const retried = startPass(async () => { if (++tries < 2) throw new Error("forge down"); }, { retryMs: 60_000, log: () => {} });
await Promise.resolve(); await Promise.resolve();
mock.timers.tick(60_000);
await retried;
assert.equal(tries, 2);
} finally {
mock.timers.reset();
}
});
test("a start pass announces a head nobody announced, and only remembers one the forge shows a check of", async () => {
const { announceNewHeads } = await import("../watch.ts");
const pull = (n: number, sha: string): GiteaPull => ({ number: n, state: "open", head_sha: sha, base: "main",
updated_at: new Date().toISOString() } as unknown as GiteaPull);
const announced: number[] = [], said: string[] = [];
const heads: Record<string, string> = {};
await announceNewHeads("novox/hq", [pull(1, "a".repeat(40)), pull(2, "b".repeat(40))], heads, false,
new Date(Date.now() - 24 * 3600_000).toISOString(), {
alreadyChecked: async (p) => p.number === 2,
announceHead: async (p) => { announced.push(p.number); return true; },
missed: (w) => said.push(w),
});
assert.deepEqual(announced, [1]);
assert.equal(heads["novox/hq#2@main"], "b".repeat(40), "the checked head is remembered, not announced");
assert.equal(said.length, 1);
});
+11 -7
View File
@@ -251,8 +251,7 @@ test("a forge that never delivers is said loudly once, and unhealthy, when the p
assert.equal(r.healthy, true);
assert.equal(r.verified.count, 1);
assert.equal(r.verified.last.event, "push");
assert.equal(r.polls.every_seconds, null);
assert.equal(r.polls.hearing, true);
assert.equal(r.polls.every_seconds, 300);
assert.match(said.join("\n"), /heard again/);
});
@@ -315,19 +314,24 @@ test("without a receiver by configuration the polls alone watch, healthy; a rece
assert.match(r.why, /403/);
});
test("nothing is paced: the report says no timer asks the forge, and a miss is still counted and said", async () => {
test("the polls look every 30 s until events are heard, every five minutes while they are, and 30 s again on a miss", async () => {
const { Pace } = await import("../webhook.ts");
let now = 1_000_000;
const said: string[] = [];
const pace = new Pace(() => now, (l) => said.push(l));
assert.equal((pace as any).every, undefined, "no pace to ask");
assert.equal((pace.report() as any).polls.every_seconds, null);
assert.equal(pace.every(), 30_000, "no delivery yet");
pace.heard();
assert.equal(pace.every(), 300_000, "a delivery heard");
now += 11 * 60_000;
assert.equal(pace.every(), 30_000, "ten minutes without a delivery");
pace.heard();
assert.equal((pace.report() as any).polls.hearing, true);
now += 1000;
pace.miss("novox/hq#7 at aaaaaaaa");
assert.equal((pace.report() as any).polls.hearing, false, "the pass found what no event said");
assert.equal(pace.every(), 30_000, "the poll found what no event said");
assert.match(said.join("\n"), /MISSED novox\/hq#7/);
now += 1000;
pace.heard();
assert.equal(pace.every(), 300_000, "the next delivery");
});
// Issue 1079: a pull request's edit event carries its description, so mesh-delivery reads a Reviewed-by line written after
+1 -56
View File
@@ -488,61 +488,6 @@ function allGiteaTools(gitea: GiteaClient, admin?: () => GiteaAdmin): ToolDefini
},
},
// ---- Two settings gitea_api refuses (issue 1422 note 7; guard.ts), each its own named tool ----
{
name: "gitea_default_branch_set",
description: "Set a repository's default branch — the branch the forge shows, clones and opens pull requests against, and the one gitea_api never writes a file to. Refused when the branch does not exist, when no protection rule guards it (a default nothing protects would open it to direct writes), or when no reason (why) is given; acts as the tools' account, so the forge refuses it where that account is no administrator of the repository. Answers the default branch before and after.",
input: {
owner: { type: "string", description: "the repository owner" },
repo: { type: "string", description: "the repository name" },
branch: { type: "string", description: "the branch to make the default; it must exist and be guarded by a protection rule" },
why: { type: "string", description: "why, in a sentence: kept in the call's record" },
},
run: async (args) => {
const owner = String(args.owner), repo = String(args.repo), branch = String(args.branch ?? "").trim();
const why = String(args.why ?? "").trim();
if (!branch) throw new Error("name the branch to make the default");
if (!why) throw new Error("say why (why): a default branch is changed for a reason, which the call's record keeps");
pathSegments("branch", branch);
const state = await gitea.branchState(owner, repo, branch);
if (!state) throw new Refused(`${owner}/${repo} has no branch ${branch}, so it cannot be the default branch. Nothing was sent`);
if (!state.protected) {
throw new Refused(`no protection rule guards ${branch} of ${owner}/${repo}: a default branch nothing protects takes direct writes ` +
`(gitea_branch_protection_set guards it first). Nothing was sent`);
}
const before = String((await gitea.getRepo(owner, repo)).default_branch ?? "");
if (before === branch) return { branch, before, after: before, changed: false, why };
const after = String((await gitea.setDefaultBranch(owner, repo, branch)).default_branch ?? "");
return { branch, before, after, changed: before !== after, why };
},
},
{
name: "gitea_pull_base_set",
description: "Change an open pull request's base — the branch it merges into — keeping its head. The checks were judged against the base it had, so the pull request is announced again into the new one. Refused when the base branch does not exist, when the pull request is not open, or when no reason (why) is given; acts as the tools' account. Answers the pull request's base before and after.",
input: {
owner: { type: "string", description: "the repository owner" },
repo: { type: "string", description: "the repository name" },
number: { type: "number", description: "the pull request's number" },
base: { type: "string", description: "the branch it should merge into; it must exist" },
why: { type: "string", description: "why, in a sentence: kept in the call's record" },
},
run: async (args) => {
const owner = String(args.owner), repo = String(args.repo), number = Number(args.number);
const base = String(args.base ?? "").trim(), why = String(args.why ?? "").trim();
if (!Number.isInteger(number) || number < 1) throw new Error(`${args.number} is not a pull request's number`);
if (!base) throw new Error("name the base branch");
if (!why) throw new Error("say why (why): a pull request's base is changed for a reason, which the call's record keeps");
pathSegments("branch", base);
if (!(await gitea.branchState(owner, repo, base))) throw new Refused(`${owner}/${repo} has no branch ${base}, so a pull request cannot merge into it. Nothing was sent`);
const had = await gitea.getPullRequest(owner, repo, number);
if (had.state !== "open" || had.merged) throw new Refused(`${owner}/${repo}#${number} is not open, so its base is not changed. Nothing was sent`);
const before = String(had.base ?? "");
if (before === base) return { number, before, after: before, changed: false, why };
const after = String((await gitea.setPullBase(owner, repo, number, base)).base ?? "");
return { number, before, after, changed: before !== after, why };
},
},
// ---- A delivery's note, view and statuses (novox/hq ADR 0239), asked by mesh-delivery ----
{
name: "gitea_note_append",
@@ -637,7 +582,7 @@ function allGiteaTools(gitea: GiteaClient, admin?: () => GiteaAdmin): ToolDefini
},
{
name: "gitea_commit_trees",
description: "A commit's trees from the forge's one recursive listing: the root tree, and the tree of every directory that holds a module.json (the root as an empty name), each by its git hash. What the forge bridge puts in a merge's message (novox/hq ADR 0437 §5). With paths, {directory: [path relative to it]}, the answer also carries paths, {directory: {path: git object id}} of each named file or directory at the commit (novox/hq ADR 0499 §3); a path the commit lacks fails naming the directory and the path. The commit is a full 40-hex sha. With listed, [directory], the answer also carries listed, {directory: {name: git blob id}} of the files directly under each (the catalog's placement files, novox/hq ADR 0549 §2). A listing the forge cut is refused, never answered in part. Reads only.",
description: "A commit's trees from the forge's one recursive listing: the root tree, and the tree of every directory that holds a module.json (the root as an empty name), each by its git hash. What the forge bridge puts in a merge's message (novox/hq ADR 0437 §5). With paths, {directory: [path relative to it]}, the answer also carries paths, {directory: {path: git object id}} of each named file or directory at the commit (novox/hq ADR 0499 §3); a path the commit lacks fails naming the directory and the path. The commit is a full 40-hex sha. With listed, [directory], the answer also carries listed, {directory: {name: git blob id}} of the files directly under each (the catalogue's placement files, novox/hq ADR 0549 §2). A listing the forge cut is refused, never answered in part. Reads only.",
input: {
owner: { type: "string", description: "the repository owner" },
repo: { type: "string", description: "the repository name" },
-87
View File
@@ -1,87 +0,0 @@
// What the forge's events ask of the announcer, and the one pass at a start (issue 1422, notes 10 and 11). Nothing polls the
// forge: a head or merge is announced when its event is heard, and a pass over every repository runs once when the module
// starts and again when the receiver is listening, so what happened while it was down is announced too.
//
// Apart from index.ts, which has side effects at import, so these are tested with the announcers injected.
import type { GiteaPull, GiteaRepo } from "./client.js";
import type { Announced } from "./pulls.js";
import { headKey, headsToAnnounce } from "./pulls.js";
import type { ForgeEvent } from "./webhook.js";
export interface ActDeps<R, P> {
getRepo(owner: string, repo: string): Promise<R>;
getPull(owner: string, repo: string, number: number): Promise<P & { state?: string; merged?: boolean }>;
announceHead(repo: R, pull: P): Promise<unknown>;
announceMerge(repo: R, pull: P): Promise<unknown>;
announceClosed(repo: R, pull: P): Promise<unknown>;
siblingMoves(full: string, number: number): Promise<unknown>;
}
const HEAD_EVENTS = ["forge.pull-request.opened", "forge.pull-request.synchronized", "forge.pull-request.reopened"];
/**
* What the forge's event asks of the announcer at once: a new head is announced, a merge, a close without a merge, and a
* pull request retargeted (an edit: the head is announced into the base it now has — the base is in the head's key, so an
* edit that changed nothing about the base announces nothing).
*/
export async function actOn<R, P>(event: ForgeEvent, d: ActDeps<R, P>): Promise<void> {
const b = event.body as { owner?: string; repo?: string; number?: number; merged?: boolean };
if (!b.owner || !b.repo || !b.number) return;
const edited = event.name === "forge.pull-request.edited";
const closed = event.name === "forge.pull-request.closed";
const head = HEAD_EVENTS.includes(event.name) || edited;
const merged = event.name === "forge.pull-request.merged";
if (!head && !merged && !closed) return;
if (closed && b.merged) return; // a merge is weighed with its own event (ADR 0382 §5)
const [repo, pull] = await Promise.all([d.getRepo(b.owner, b.repo), d.getPull(b.owner, b.repo, b.number)]);
if (closed) {
await d.announceClosed(repo, pull);
await d.siblingMoves(`${b.owner}/${b.repo}`, b.number);
return;
}
if (head && pull.state === "open") await d.announceHead(repo, pull);
if (merged) await d.announceMerge(repo, pull);
}
/**
* The one pass at a start, and its retry: run now; if it fails, say so and run again after `retryMs`, until one pass has
* ended. A retry of a failed pass, never a poll: after a pass has ended nothing is scheduled.
*/
export function startPass(run: () => Promise<void>, opts: { retryMs: number; log?: (l: string) => void }): Promise<void> {
const log = opts.log ?? ((l) => console.error(`[gitea] ${l}`));
return run().catch((err) => {
log(`the pass over every repository failed, asked again in ${opts.retryMs / 1000} s — ${err instanceof Error ? err.message : err}`);
return new Promise<void>((resolve) => setTimeout(() => resolve(startPass(run, opts)), opts.retryMs));
});
}
export interface HeadDeps {
/** Whether the forge shows a merge check of the head: only an announced head has one. */
alreadyChecked(pull: GiteaPull): Promise<boolean>;
/** Announce it; true when it was this call that announced it (not an event before it). */
announceHead(pull: GiteaPull): Promise<boolean>;
/** Told of a head this pass announced that no event had. */
missed(what: string): void;
}
/**
* The heads of one repository's open pull requests a pass announces. A head is announced when it is new and fresh (moved in
* the last day); at the first pass after a start (`primed` false) one the forge shows a merge check of was announced
* already, and is only remembered.
*/
export async function announceNewHeads(full: string, open: GiteaPull[], heads: Announced, primed: boolean, dayAgo: string, d: HeadDeps): Promise<void> {
for (const pull of headsToAnnounce(full, open, heads)) {
const key = headKey(full, pull.number, pull.base);
const fresh = primed || (!!pull.updated_at && pull.updated_at > dayAgo);
if (fresh && !primed && await d.alreadyChecked(pull)) {
heads[key] = String(pull.head_sha);
continue;
}
if (fresh) {
if (await d.announceHead(pull)) d.missed(`${key} at ${String(pull.head_sha).slice(0, 8)}`);
} else heads[key] = String(pull.head_sha);
}
}
export type { GiteaRepo };
+22 -19
View File
@@ -3,7 +3,7 @@
// with a secret it mints and keeps beside its token; the receiver refuses whatever is unsigned or does not verify, and
// publishes each event, trimmed, on the module's events as forge.<kind>.<action> (forge.pull-request.opened, forge.push, …),
// on the shared EVENTS path its other events take; its own stream (ADR 0363) is a follow-up once issue 725 ships.
// No poll is the safety net (issue 1422); the announced-heads and announced-merges records keep anything from
// The polls stay as the safety net, slowed; the announced-heads and announced-merges records keep anything from
// being announced twice, whichever path saw it first.
//
// The secret is never logged: lines say it was minted or reused and where it is kept, never what it is.
@@ -144,7 +144,7 @@ export interface ReceiverOptions {
publish: (event: ForgeEvent) => Promise<void>;
/** Acts on it at once, beside publishing it (the announcer). */
act?: (event: ForgeEvent) => Promise<void>;
/** Told of every verified delivery — its kind (X-Gitea-Event) and its delivery id — so the module knows events are
/** Told of every verified delivery — its kind (X-Gitea-Event) and its delivery id — so the polls know events are
* heard, and the module can say when it last heard one. */
heard?: (kind: string, delivery: string) => void;
/** Told of every refused delivery, with the reason and where it came from. */
@@ -242,7 +242,7 @@ export function receiver(opts: ReceiverOptions): Server & { idle(): Promise<void
await opts.publish(event);
if (opts.act) await opts.act(event);
} catch (err) {
log(`a forge event ${event.name} could not be published or acted on; the pass over every repository is asked again shortly — ${err instanceof Error ? err.message : err}`);
log(`a forge event ${event.name} could not be published or acted on; the polls catch it — ${err instanceof Error ? err.message : err}`);
}
});
});
@@ -276,13 +276,14 @@ export interface HookState {
export const SILENT_AFTER = 10 * 60_000;
/**
* **Whether the forge's events are heard** (issues 729, 1422). Nothing polls the forge, so there is no pace: a delivery
* heard within the last ten minutes, and none missed since, is `hearing`.
* **How fast the polls look, and whether the forge's events are heard** (issue 729): every five minutes only while the
* forge's events are heard — a verified delivery within the last ten minutes, and none missed since. Until the first
* delivery, after ten minutes without one, or once the poll found something no event said, every thirty seconds.
*
* It also keeps what `gitea_events` says: where the receiver listens, the hook as ensured, the verified and refused
* deliveries, and the finds of the pass over every repository (at the start and when the receiver listens) that no event said. **A forge whose events stop is said** (issue 729): once the receiver
* deliveries, and the polls' finds no event said. **A forge whose events stop is said** (issue 729): once the receiver
* listens and the hook is ensured, when nothing verified for ten minutes — since the start, or since the last delivery —
* and a pass has found at least two heads or merges no event said in that quiet (one could be a pass beating an
* and the poll has found at least two heads or merges no event said in that quiet (one could be the poll beating an
* event by a second), it is logged loudly once per silent spell, and the module's events are said unhealthy until a
* delivery verifies. Deliveries refused since the last verified one are said unhealthy too.
*/
@@ -317,7 +318,7 @@ export class Pace {
this.notHeard = null;
}
/** No events are listened for, and why: by configuration (`fails` false), or because the receiver could not listen
* or the hook could not be ensured (`fails` true, said unhealthy). Only the pass at the start watches. */
* or the hook could not be ensured (`fails` true, said unhealthy). The polls alone watch. */
unheard(why: string, fails = true): void {
this.notHeard = why;
this.notHeardFails = fails;
@@ -336,10 +337,10 @@ export class Pace {
this.refusedSpell++;
this.lastRefused = { at: this.now(), reason, from };
}
/** The pass over every repository found a head or merge no forge event announced. */
/** The poll found a head or merge no forge event announced. */
miss(what: string): void {
const t = this.now();
if (this.hearing()) this.log(`THE FORGE'S EVENTS MISSED ${what}: the pass over every repository found it`);
if (this.hearing()) this.log(`THE FORGE'S EVENTS MISSED ${what}: the poll found it, so the polls look every 30 s again until the next event`);
this.missed = t;
this.missCount++;
this.lastMiss = { at: t, what };
@@ -354,8 +355,8 @@ export class Pace {
this.log(`THE FORGE'S EVENTS ARE NOT HEARD: ${this.last ? `no delivery verified since the last at ` +
`${new Date(this.last).toISOString()}` : "no delivery ever verified since the start"}, ${minutes} min, from the ` +
`system webhook at ${this.hook?.url}${refusedSince ? `; ${refusedSince} refused since, the last because ` +
`${this.lastRefused?.reason}` : ""}; the pass found ${what}; nothing else watches the forge ` +
`(novox/hq issue 729, 1422)`);
`${this.lastRefused?.reason}` : ""}; the poll found ${what} — the polls alone watch the forge, every 30 s ` +
`(novox/hq issue 729)`);
}
}
/** Whether a delivery was refused after the last verified one (or with none verified). */
@@ -366,6 +367,9 @@ export class Pace {
const t = this.now();
return this.last > 0 && t - this.last < 10 * 60_000 && this.last > this.missed;
}
every(): number {
return this.hearing() ? 5 * 60_000 : 30_000;
}
private expecting(): boolean {
return this.where !== null && this.hook !== null;
}
@@ -379,14 +383,14 @@ export class Pace {
if (this.silentSince) {
state = "unhealthy";
why = `${this.last ? `no delivery verified since the last at ${iso(this.last)}` : `the forge has never delivered an ` +
`event since the start at ${iso(this.started)}`}, while the pass found ${this.missCount} head(s) or merge(s) no ` +
`event since the start at ${iso(this.started)}`}, while the poll found ${this.missCount} head(s) or merge(s) no ` +
`event said, the last ${this.lastMiss?.what} at ${iso(this.lastMiss?.at ?? t)}`;
} else if (refusedSince) {
state = "unhealthy";
why = `${refusedSince} deliveries refused ${this.last ? `since the last verified one at ${iso(this.last)}` :
"and none verified"}, the last at ${iso(this.lastRefused?.at ?? t)} because ${this.lastRefused?.reason}`;
} else if (!this.expecting()) {
why = this.notHeard ? `no events are listened for, so only the pass at the start watches the forge: ${this.notHeard}` :
why = this.notHeard ? `no events are listened for, so the polls alone watch the forge: ${this.notHeard}` :
"the receiver is not listening yet";
if (this.notHeard && this.notHeardFails) state = "unhealthy";
} else if (this.hearing()) {
@@ -394,7 +398,7 @@ export class Pace {
} else if (this.last === 0) {
why = `no delivery heard yet; the forge is said silent if the poll finds what no event said ${SILENT_AFTER / 60_000} min after the start`;
} else {
why = `the last delivery was at ${iso(this.last)}; nothing polls the forge, so what happens meanwhile is announced at the next start or when the receiver listens again`;
why = `the last delivery was at ${iso(this.last)}; the polls look every 30 s until the next`;
}
return {
healthy: state !== "unhealthy", state, why,
@@ -403,8 +407,7 @@ export class Pace {
hook: this.hook,
verified: { count: this.verifiedCount, last: this.lastVerified && { ...this.lastVerified, at: iso(this.lastVerified.at) } },
refused: { count: this.refusedCount, since_verified: refusedSince, last: this.lastRefused && { ...this.lastRefused, at: iso(this.lastRefused.at) } },
polls: { every_seconds: null, note: "no timer asks the forge; one pass at the start and when the receiver listens (issue 1422)",
hearing: this.hearing(), found_unsaid: this.missCount,
polls: { every_seconds: this.every() / 1000, hearing: this.hearing(), found_unsaid: this.missCount,
last_found: this.lastMiss && { ...this.lastMiss, at: iso(this.lastMiss.at) } },
silent: this.silentSince ? { since: iso(this.silentSince) } : null,
};
@@ -499,8 +502,8 @@ export function eventsTool(pace: Pace): { name: string; description: string; inp
name: "gitea_events",
description: "Whether the forge's events reach the mesh (novox/hq issue 729): where the receiver listens, the " +
"system webhook as ensured at the start (its id, url, events, kind, and what it replaced), how many deliveries " +
"verified and the last one's time and event, how many were refused and the last reason, whether " +
"events are heard (nothing polls; one pass runs at the start), and how many heads or merges that pass found that no event said. Unhealthy when the " +
"verified and the last one's time and event, how many were refused and the last reason, how often the polls look " +
"and whether events are heard, and how many heads or merges the poll found that no event said. Unhealthy when the " +
"forge has delivered nothing that verified for ten minutes (since the start or since the last delivery) while the " +
"poll found what no event said, when deliveries were refused since the last verified one, or when the receiver " +
"could not listen or the webhook could not be made.",
+3 -3
View File
@@ -66,7 +66,7 @@ CREATE TABLE IF NOT EXISTS module_version (
PRIMARY KEY (module, commit_sha)
);
-- What the catalog considers this module to be now. Separate from module_version because a
-- What the catalogue considers this module to be now. Separate from module_version because a
-- module has many versions and exactly one current one, and "current" is a decision rather than
-- a consequence of being newest.
CREATE TABLE IF NOT EXISTS module_current (
@@ -144,7 +144,7 @@ export class Graph {
const url = env["DATABASE_URL"] ?? readMaybe(env["DATABASE_URL_FILE"]);
if (!url) {
throw new Error(
"no DATABASE_URL: the catalog holds the module graph and cannot hold it in memory, " +
"no DATABASE_URL: the catalogue holds the module graph and cannot hold it in memory, " +
"because a graph that disappears on restart is not a record of anything",
);
}
@@ -246,7 +246,7 @@ export class Graph {
}
}
/** Every module the catalog holds, with the commit it considers current. */
/** Every module the catalogue holds, with the commit it considers current. */
async modules(): Promise<{ module: string; commit: string; repository: string; path: string }[]> {
const { rows } = await this.pool.query(
`SELECT c.module, c.commit_sha, v.repository, v.path
+2 -2
View File
@@ -12,7 +12,7 @@ export function getCatalogueTools(graph: Graph): ToolDefinition[] {
{
name: "catalog_modules",
description:
"Every module this mesh holds, with the commit the catalog considers current and where it came from.",
"Every module this mesh holds, with the commit the catalogue considers current and where it came from.",
input: {},
run: async () => ({ modules: await graph.modules() }),
},
@@ -28,7 +28,7 @@ export function getCatalogueTools(graph: Graph): ToolDefinition[] {
const module = String(args.module ?? "");
if (!module) return { error: "name a module" };
const found = await graph.show(module, args.commit ? String(args.commit) : undefined);
return found ? { module: found } : { error: `the catalog holds no ${module}` };
return found ? { module: found } : { error: `the catalogue holds no ${module}` };
},
},
{
@@ -184,7 +184,7 @@ func (call Call) level() (Level, error) {
case call.Module != "":
return Level{}, fmt.Errorf("a module's own value is set for one node, and no node is named: there is no "+
"module value for the whole mesh (novox/hq ADR 0348 §3); name the node, or set mesh config for the "+
"predefined key %s's value falls back to, or change its default in the catalog", call.Module)
"predefined key %s's value falls back to, or change its default in the catalogue", call.Module)
case call.Node != "":
return Level{Kind: LevelNode, Node: call.Node}, nil
}
@@ -27,7 +27,7 @@ func (c *Config) sources() (Sources, error) {
}); err != nil {
return s, fmt.Errorf("the assignments cannot be read: %w", err)
}
// And every module the catalog's placement names on a node (ADR 0549 §3): until ADR 0547's third milestone both
// And every module the catalogue's placement names on a node (ADR 0549 §3): until ADR 0547's third milestone both
// sources stand (ADR 0549 §5), so a pair either names is resolved, and none loses its values while the two differ.
// Placement that cannot be read yet (the indexer's state not on the bus) leaves the assignments alone, said.
standing := map[string]bool{}
@@ -57,7 +57,7 @@ func (c *Config) sources() (Sources, error) {
}
return nil
}); err != nil {
problems = append(problems, fmt.Sprintf("the catalog's placement cannot be read, so the assignments alone are resolved: %v", err))
problems = append(problems, fmt.Sprintf("the catalogue's placement cannot be read, so the assignments alone are resolved: %v", err))
}
if err := c.each(DeclaredConfigRead, func(key string, raw []byte) error {
m, err := ParseModuleDeclarations(raw)
@@ -411,9 +411,6 @@ func (h *Holder) approval(d *Delivery, now time.Time) (string, func()) {
}
}
check := h.checkAt(members)
if !h.checkGates() {
check = unansweredWords(check) // asked with no verdict only past its bound (verdictWaits)
}
ask := composeMergeAsk(sdk.AskingID(id, asking), d, group, members, heads, check, now)
taken := []*Delivery{}
var reads []memberRead
@@ -1,11 +1,6 @@
package main
import (
"encoding/json"
"time"
sdk "git.novox.be/novox/mesh-sdk/go/delivery"
)
import "time"
var t0 = time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
@@ -32,24 +27,3 @@ func statusOn(w *world, repo, commit string) string {
defer w.forge.mu.Unlock()
return w.forge.statuses[repo+"@"+commit+" mesh/delivery"]
}
// checkerSays puts the checker's verdict at these heads together into its verdicts bucket, as captured on the bus
// (mesh-delivery-checker, key `<group>.<heads hash>`).
func checkerSays(w *world, group, state, failed string, heads ...sdk.Head) {
checkerSaysWith(w, group, state, failed, nil, heads...)
}
// checkerSaysWith is checkerSays with more of the verdict's fields (its composition); the state "gone" deletes the key.
func checkerSaysWith(w *world, group, state, failed string, more map[string]any, heads ...sdk.Head) {
hash, _ := sdk.HeadsHash(heads)
if state == "gone" {
w.h.CheckerVerdictChanged(group+"."+hash, nil)
return
}
v := map[string]any{"v": 1, "group": group, "heads": hash, "state": state, "failed": map[string]string{"words": failed}}
for k, x := range more {
v[k] = x
}
value, _ := json.Marshal(v)
w.h.CheckerVerdictChanged(group+"."+hash, value)
}
@@ -57,8 +57,6 @@ type Holder struct {
// catchUp asks the next look to weigh again the newest merge of each repository against source.main (SourceCatchUp).
catchUp bool
// seeded are the repositories source.main was found to name, or was seeded with, since this owner started (seedTrunks).
seeded map[string]bool
mu sync.Mutex
deliveries map[string]*Delivery
@@ -79,10 +77,7 @@ type Holder struct {
unchecked map[string]unchecked
// checker are the checker's verdicts by the hash of the heads they judged, as its verdicts bucket holds them
// (onestatus.go, issue 1302); runningSince when this owner first saw each running (ADR 0548 §2, turns.go).
checker map[string]checkerVerdict
// verdictGone is when the checker's verdict at a heads hash was taken away (its key deleted): the Approve's wait for a
// verdict counts its bound from then, as from a check that starts again (verdictWaits).
verdictGone map[string]time.Time
checker map[string]checkerVerdict
runningSince map[string]time.Time
// unmergeableSince is when the forge first said a group's member does not merge now, by group and member (issue 1275,
// group_merge.go): within forgeMergeGrace that is the forge still working out mergeability, asked again shortly.
@@ -146,7 +141,7 @@ func (h *Holder) init() {
h.lostRead = map[string]time.Time{}
h.unchecked = map[string]unchecked{}
h.checker = map[string]checkerVerdict{}
h.runningSince, h.turnsHeld, h.verdictGone = map[string]time.Time{}, map[string]sdk.Turn{}, map[string]time.Time{}
h.runningSince, h.turnsHeld = map[string]time.Time{}, map[string]sdk.Turn{}
h.reach = map[string]sdk.Reach{}
h.started = h.Now()
}
@@ -345,15 +340,13 @@ func (h *Holder) pullUpdated(p PullEvent) (isNew bool) {
// Announced again: nothing new — but for a delivery whose verdict is out of date, the announcement is its
// check asked again against the trunk's head (the merge tool's ask, novox/hq ADR 0323 §5), and its bound
// runs from now (§7). The base head it was announced with is kept, for a check this owner asks after it.
if p.BaseSHA != "" {
d.BaseSHA, d.BaseSHAAt = p.BaseSHA, now
if p.BaseSHA != "" && d.BaseSHA != p.BaseSHA {
d.BaseSHA = p.BaseSHA
h.keep(d)
}
// A delivery made from its verdict before its head was heard (issue 1726) holds none of what an announcement
// carries: filled from this one, so its base is known and the operator is asked.
h.fillFromAnnouncement(d, p)
// A pull request retargeted to another base (review of issue 1422): what it merges into is the forge's word now.
h.retarget(d, p)
// The review record, corrected in the description without a push, is read again (ADR 0421 §5).
if by, at := ReviewIn(p.Body); p.Body != "" && (by != d.ReviewedBy || at != d.ReviewedAt) {
d.ReviewedBy, d.ReviewedAt = by, at
@@ -443,7 +436,7 @@ func (h *Holder) fillFromAnnouncement(d *Delivery, p PullEvent) {
d.ReviewedBy, d.ReviewedAt = ReviewIn(p.Body)
d.PushedBy = PushedIn(p.Body)
if p.BaseSHA != "" {
d.BaseSHA, d.BaseSHAAt = p.BaseSHA, h.Now()
d.BaseSHA = p.BaseSHA
}
d.Number = p.Number
h.Logf("[mesh-delivery] %s: its pull request's announcement filled its base (%s), branch and title", d.ID, p.Base)
@@ -455,27 +448,6 @@ func (h *Holder) fillFromAnnouncement(d *Delivery, p PullEvent) {
h.Poke()
}
// retarget takes the base a live, unmerged delivery's pull request was announced again with when it differs from the one
// kept: into main it is asked and merged as any other, and source.main may be seeded from it (seedTrunks); out of main an
// ask nobody answered yet is taken back, and the next look says it is not asked (ready.go). A delivery whose base is not yet
// known is fillFromAnnouncement's. Said in the log. Under the lock.
func (h *Holder) retarget(d *Delivery, p PullEvent) {
if p.Base == "" || d.Base == "" || p.Base == d.Base || d.State.Final() || d.MergedAs != "" ||
(d.Ready != nil && d.Ready.Merged != nil) {
return
}
from := d.Base
d.Base = p.Base
if r := d.Ready; r != nil {
r.OtherBase = ""
if r.AskID != "" && r.Approved == nil {
h.cancels = append(h.cancels, h.withdrawAsk(r.AskID, fmt.Sprintf("%s was retargeted from %s to %s", d.ID, from, p.Base)))
}
}
h.Logf("[mesh-delivery] %s: its pull request was retargeted from %s to %s", d.ID, from, p.Base)
h.keep(d)
}
// PullEdited takes a pull request's edit (novox/hq issue 1079): its description is read again for the review record, the
// `after:` lines and the issues it names, exactly as an announcement reads them. An Approve ask still unanswered whose words
// the new record changes is withdrawn and asked again with it read, without a word on the pull request: nothing was
@@ -583,9 +555,6 @@ func (h *Holder) freshAnnouncement(p PullEvent, now time.Time, startedOver strin
Title: p.Title, Base: p.Base, Branch: p.Head, HTMLURL: p.HTMLURL, CloneURL: p.CloneURL, Paths: p.Paths,
PathsTruncated: p.PathsTruncated, Removed: p.Removed, ModuleDirs: p.ModuleDirs, ModuleDirsSaid: p.ModuleDirsSaid,
After: AfterIn(p.Body), Issues: IssuesIn(p.Title + "\n" + p.Body), Created: now, BaseSHA: p.BaseSHA}
if p.BaseSHA != "" {
d.BaseSHAAt = now
}
d.ReviewedBy, d.ReviewedAt = ReviewIn(p.Body)
d.PushedBy = PushedIn(p.Body)
why := fmt.Sprintf("%s#%d's head announced", d.Repository, d.Number)
@@ -1,7 +1,6 @@
package main
import (
"strings"
"testing"
"time"
@@ -49,86 +48,6 @@ func TestStartingWritesTheNewestMergeOfEachRepositoryNotYetInSourceMain(t *testi
t.Fatalf("a second catch-up moved source.main again: %d moves, then %d", n, len(w.source.moves))
}
// Issue 1422: a repository never merged through the gate gets main's head as the forge announced its open pull request
// with, once, beside the others; a pull request into another base, or one announced with no base head (the forge could
// not read it), seeds nothing; a head source.main holds is never replaced.
const never, trunkN, trunkM = "novox/never-merged", "eeee000000000000000000000000000000000001", "eeee000000000000000000000000000000000002"
s := newWorld(t)
s.source.main = &sdk.Source{V: sdk.Version, Group: "before", Heads: map[string]string{i1726Repo: i1726Merge1}}
other := pr("novox/other-base", 6, "f1f1000000000000000000000000000000000001", "fix/c", "a.go")
other.Base, other.BaseSHA = "nox-mesh", trunkM
s.h.PullUpdated(other)
unread := pr("novox/unread", 2, "f2f2000000000000000000000000000000000002", "fix/d", "a.go")
s.h.PullUpdated(unread)
seed := pr(never, 4, "f3f3000000000000000000000000000000000003", "fix/e", "a.go")
seed.BaseSHA = trunkN
s.h.PullUpdated(seed)
s.settleAll()
if h := s.source.main.Heads; h[never] != trunkN || h[i1726Repo] != i1726Merge1 || h["novox/other-base"] != "" || h["novox/unread"] != "" || len(s.source.moves) != 1 {
t.Fatalf("source.main is %v after %d moves; wanted %s seeded at %s, the catalogue kept and nothing else, in one move", h, len(s.source.moves), never, trunkN)
}
if !strings.Contains(s.logs(), "seeded with "+trunkN[:12]) {
t.Errorf("the seed was not said: %s", s.logs())
}
again := pr(never, 5, "f4f4000000000000000000000000000000000004", "fix/f", "a.go")
again.BaseSHA = trunkM
s.h.PullUpdated(again)
s.h.SourceCatchUp()
s.settleAll()
if got := s.source.main.Heads[never]; got != trunkN || len(s.source.moves) != 1 {
t.Fatalf("a seeded head was replaced by %s (%d moves)", got, len(s.source.moves))
}
// The freshest announcement's base head is the seed, not the newest delivery's: #4, made first, is announced again after #5
// with main's head moved on.
const trunkF = "eeee000000000000000000000000000000000003"
f := newWorld(t)
first := pr(never, 4, "f5f5000000000000000000000000000000000005", "fix/g", "a.go")
first.BaseSHA = trunkN
f.h.PullUpdated(first)
f.later(time.Minute)
second := pr(never, 5, "f6f6000000000000000000000000000000000006", "fix/h", "a.go")
second.BaseSHA = trunkM
f.h.PullUpdated(second)
f.later(time.Minute)
first.BaseSHA = trunkF
f.h.PullUpdated(first)
f.settleAll()
if got := f.source.main.Heads[never]; got != trunkF {
t.Fatalf("seeded with %s; wanted %s, the base head of the latest announcement", got, trunkF)
}
// A green pull request retargeted from nox-mesh to main is seeded and asked; one retargeted from main to nox-mesh has
// its ask taken back and is not merged (review round 2).
retarget := func(from, to string) (*world, int) {
w := newWorld(t)
w.op.auto = false
p := pr(never, 7, readyHead, "feat/x", "src/a.go")
p.Base, p.BaseSHA = from, trunkN
w.h.PullUpdated(p)
w.h.Checked(judgedAt(never, 7, readyHead, "pass", "t1t1t1t1t1t1"))
open := openPull(never, 7, readyHead)
open.Base = from
w.forge.open = []OpenPull{open}
w.h.SeeOpenPulls()
w.settleAll()
before := len(w.op.open())
p.Base, open.Base = to, to
w.forge.open = []OpenPull{open}
w.h.PullUpdated(p)
w.h.SeeOpenPulls()
w.settleAll()
w.later(2 * time.Minute)
w.settleAll()
return w, before
}
if r, before := retarget("nox-mesh", "main"); before != 0 || r.source.main == nil || r.source.main.Heads[never] != trunkN || len(r.op.open()) != 1 {
t.Fatalf("retargeted to main: %d asks before, source.main %+v, open asks %v; wanted none before, then seeded at %s and asked", before, r.source.main, r.op.open(), trunkN)
}
if r, before := retarget("main", "nox-mesh"); before != 1 || len(r.op.open()) != 0 || len(r.forge.merges) != 0 || !strings.Contains(r.logs(), "retargeted") {
t.Fatalf("retargeted to nox-mesh: %d asks before, open asks %v, merges %v; wanted one before, then none and the retarget said", before, r.op.open(), r.forge.merges)
}
o := newWorld(t)
o.source.main = &sdk.Source{V: sdk.Version, Group: "newer", Heads: map[string]string{i1726Repo: i1726Merge2}}
o.h.PullUpdated(pr(i1726Repo, 471, head2, "fix/b", "modules/app/b.go"))
@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"reflect"
"regexp"
"sort"
"strings"
"time"
@@ -525,75 +524,6 @@ func (h *Holder) settleForgeMerges() []func() {
return out
}
// trunkHead is a full commit id as the forge names a branch's head.
var trunkHead = regexp.MustCompile(`^[0-9a-f]{40}$`)
// seedTrunks gives source.main the trunk head of a repository it names none of (issue 1422): one never merged through the
// gate, whose open pull requests the checker could otherwise never judge. The head is the base_sha of the latest announcement of
// any open pull request into main (gitea.pull.updated; ADR 0323; lastAnnounced), the trunk's freshest head the gate heard. It is
// added in one compare-and-set write that never replaces a head source.main holds, so a merge always wins; the first merge
// through the gate moves it as any other. source.main is per repository and names main's head only (ADR 0484 §11, MergeBranch):
// a pull request into another base seeds nothing. A repository is weighed once per start after it was found or seeded.
// Under the lock; the writing happens outside it.
func (h *Holder) seedTrunks() []func() {
newest := map[string]*Delivery{}
for _, d := range h.deliveries {
if h.seeded[d.Repository] || d.Base != MergeBranch || !trunkHead.MatchString(d.BaseSHA) || d.State.Final() || d.MergedAs != "" {
continue
}
if o := newest[d.Repository]; o == nil || lastAnnounced(d).After(lastAnnounced(o)) {
newest[d.Repository] = d
}
}
var out []func()
for repository, d := range newest {
id, head, group := d.ID, d.BaseSHA, firstOf(d.Branch, d.Repository)
out = append(out, func() {
seeded := false
err := h.Source.Move(func(prev *sdk.Source) (sdk.Source, bool) {
seeded = false
next := sdk.Source{Group: group, Heads: map[string]string{}}
if prev != nil {
if prev.Heads[repository] != "" {
return *prev, false // named already: never replaced
}
next.Group = prev.Group
for r, held := range prev.Heads {
next.Heads[r] = held
}
}
next.Heads[repository] = head
seeded = true
return next, true
})
h.mu.Lock()
defer h.mu.Unlock()
if err != nil {
h.Logf("[mesh-delivery] %s: source.main names no trunk head of %s, and it cannot be seeded yet: %v; asked again in %s", id, repository, err, askAgainAfter)
h.again("source.main, seeded with the trunk head of a repository it names none of")
return
}
if h.seeded == nil {
h.seeded = map[string]bool{}
}
h.seeded[repository] = true
if seeded {
h.Logf("[mesh-delivery] source.main named no trunk head of %s: seeded with %s, main's head as the forge announced %s with, so its pull requests are judged (issue 1422)", repository, shortOf(head, 12), id)
}
})
}
return out
}
// lastAnnounced is when the forge last announced a delivery's head with its base head: BaseSHAAt, or when the gate made it
// for one kept before that was written.
func lastAnnounced(d *Delivery) time.Time {
if !d.BaseSHAAt.IsZero() {
return d.BaseSHAAt
}
return d.Created
}
// replayLate is how long after its merge a merge heard only from the forge's word is a replay: the forge announces a merge
// within seconds, so one heard this late was replayed from the bus's history, and the source already holds what came after.
const replayLate = 15 * time.Minute
@@ -66,9 +66,6 @@ type Delivery struct {
// BaseSHA is the base branch's head the forge last announced its head with (ADR 0323): sent with a check this
// owner asks, for a verdict no build judges to name its trunk commit.
BaseSHA string `json:"base_sha,omitempty"`
// BaseSHAAt is when the forge last announced its head with BaseSHA: the freshest of a repository's announcements gives
// source.main its trunk head when it names none (seedTrunks, issue 1422). Zero for one kept before it was written.
BaseSHAAt time.Time `json:"base_sha_at,omitzero"`
// AskedAgain is when its head was announced again while its verdict was out of date — the merge tool's ask of
// its check against the trunk's head (ADR 0323 §5) — and no verdict has come since: its one-hour bound runs from
// then. Nil while nothing is asked, and cleared by a verdict or another move of its trunk.
@@ -8,7 +8,6 @@ import (
"sort"
"strings"
"time"
_ "time/tzdata" // the operator's zone is known whatever this machine has installed
sdk "git.novox.be/novox/mesh-sdk/go/delivery"
)
@@ -58,12 +57,6 @@ type checkerVerdict struct {
Machine string `json:"machine,omitempty"`
Words string `json:"words,omitempty"`
} `json:"failed,omitzero"`
// Composition is what the check of the machines' composition made of it (mesh-sdk delivery.Composition): its state
// not-run says the composition, and with it a placement change's answers from its nodes, was not judged.
Composition *struct {
State string `json:"state"`
Words string `json:"words,omitempty"`
} `json:"composition,omitempty"`
}
// CheckerVerdictChanged takes a key of the checker's verdicts bucket (`<group>.<heads hash>`) put or deleted (an empty
@@ -82,13 +75,9 @@ func (h *Holder) CheckerVerdictChanged(key string, value []byte) {
if h.runningSince == nil {
h.runningSince = map[string]time.Time{}
}
if h.verdictGone == nil {
h.verdictGone = map[string]time.Time{}
}
if len(value) == 0 || string(value) == "null" {
delete(h.checker, hash)
delete(h.runningSince, hash)
h.verdictGone[hash] = h.Now()
h.Poke()
return
}
@@ -104,7 +93,6 @@ func (h *Holder) CheckerVerdictChanged(key string, value []byte) {
h.runningSince[v.Heads] = h.Now() // a check starts: a merge it holds says since when (ADR 0548 §2)
} else if v.State != checkerRunning {
delete(h.runningSince, v.Heads)
delete(h.verdictGone, v.Heads)
}
h.checker[v.Heads] = v
h.Poke()
@@ -341,11 +329,11 @@ func (h *Holder) checkAt(members []*Delivery) checkSaid {
if ok {
switch v.State {
case checkerPass:
return checkSaid{Key: checkSaidPass, Words: "passed its check" + notComposed(v, members)}
return checkSaid{Key: checkSaidPass, Words: "passed its check"}
case checkerRunning:
words := "its check has no verdict yet: it is running"
if since, held := h.runningSince[hash]; held && !since.IsZero() {
words += " (since " + clockSaid(since) + ")"
words += " (since " + since.UTC().Format("15:04") + " UTC)"
}
return checkSaid{Key: checkSaidRunning, Words: words}
default:
@@ -383,31 +371,3 @@ func (h *Holder) checkAt(members []*Delivery) checkSaid {
}
return checkSaid{Key: checkSaidNone, Words: "its check has no verdict yet"}
}
// notComposed is what a passing verdict adds when its composition was not judged (mesh-sdk delivery.CompositionNotRun): a
// placement change's pass then holds no node's answer to its placement (ADR 0559 §5), which the ask says. Empty otherwise.
func notComposed(v checkerVerdict, members []*Delivery) string {
if v.Composition == nil || v.Composition.State != sdk.CompositionNotRun {
return ""
}
why := firstOf(oneLine(v.Composition.Words), "it was not run")
for _, m := range members {
for _, p := range m.Paths {
if strings.HasPrefix(p, "placement/") && strings.HasSuffix(p, ".json") {
return ", but its composition was not judged (" + why + "), so no node answered its placement"
}
}
}
return ", but its composition was not judged (" + why + ")"
}
// operatorZone is the zone the operator reads times in, as the messenger says them (its time-zone setting).
var operatorZone = func() *time.Location {
if loc, err := time.LoadLocation("Europe/Brussels"); err == nil {
return loc
}
return time.UTC
}()
// clockSaid is a time of day as the operator reads it: in their zone, named ("00:35 CET").
func clockSaid(t time.Time) string { return t.In(operatorZone).Format("15:04 MST") }
@@ -294,7 +294,6 @@ func (h *Holder) readyAsks(now time.Time) []func() {
asks = append(asks, h.turnWrites()...) // the merge turns, after the holds of this look (ADR 0548 §3)
asks = append(asks, h.settleMerges()...)
asks = append(asks, h.settleForgeMerges()...)
asks = append(asks, h.seedTrunks()...)
asks = append(asks, h.withdrawnKeys()...)
asks = append(h.cancels, asks...)
h.cancels = nil
@@ -447,75 +446,9 @@ func (h *Holder) ungatedWaits(d *Delivery) string {
}
}
}
if h.covering(d) == nil {
return h.verdictWaits(d)
}
return ""
}
// askCheckBound is how long an Approve waits for the check's verdict at its heads while the check gates no merge: past it,
// the operator is asked anyway, and the ask says the check has not answered. The checker's own step bound is 30 minutes
// and a check runs several steps; an hour covers a whole check.
const askCheckBound = time.Hour
// waitsCheckBeforeAsking is how the wait for the check's verdict begins, as `show` and the delivery's wait say it.
const waitsCheckBeforeAsking = "waits its check before asking the operator's Approve: "
// verdictWaits is why an Approve is not asked yet while the check gates no merge: the check at the heads the ask would cover
// has no verdict (the operator, 2026-10-27 23:54: "if you don't want me to approve it, don't send the approval request").
// A pass or a failure is asked (a failure in its words: the operator may still merge it), and so is a check that has not
// answered within askCheckBound of the heads becoming ready, which the ask says. For a group the check is the one of all its
// heads together; for a placement change it ends only once every node it places answered (ADR 0559 §5). Under the lock.
func (h *Holder) verdictWaits(d *Delivery) string {
members := h.askMembers(d)
c := h.checkAt(members)
if c.Key == checkSaidPass || c.Key == checkSaidFail {
return ""
}
until := h.waitSince(d, members).Add(askCheckBound)
if !h.Now().Before(until) {
return ""
}
h.lookAt(until, "an Approve that waits its check, asked anyway at its bound")
return waitsCheckBeforeAsking + c.Words + "; asked anyway at " + clockSaid(until) + " if it has not answered"
}
// waitSince is when the wait for a verdict began, the moment the bound of verdictWaits counts from: the latest of the
// heads becoming ready (a member with no ready run yet, such as one re-pushed or settled ready by an event this look has
// not reached, became ready now), the check at those heads starting again, and its verdict being taken away. Under the lock.
func (h *Holder) waitSince(d *Delivery, members []*Delivery) time.Time {
now := h.Now()
since := time.Time{}
later := func(t time.Time) {
if t.After(since) {
since = t
}
}
for _, m := range append([]*Delivery{d}, members...) {
if m.Ready == nil {
return now
}
later(m.Ready.Seen)
}
if hash, err := sdk.HeadsHash(headsOf(members)); err == nil {
later(h.runningSince[hash])
later(h.verdictGone[hash])
}
if since.IsZero() || since.After(now) {
return now
}
return since
}
// unansweredWords is the check's words in an ask made past askCheckBound with no verdict: it says the check has not answered.
func unansweredWords(c checkSaid) checkSaid {
if c.Key == checkSaidPass || c.Key == checkSaidFail {
return c
}
c.Words += ", and has given none in " + strconv.Itoa(int(askCheckBound.Minutes())) + " minutes, so the operator is asked anyway"
return c
}
// waitsForReview is how a hold for a review begins, as the delivery's state and its mesh/delivery status say it.
const waitsForReview = "waits for a review at "
@@ -1,6 +1,7 @@
package main
import (
"encoding/json"
"errors"
"sort"
"strings"
@@ -69,42 +70,27 @@ func TestAnApprovedPullRequestIsMergedThroughTheMergeTool(t *testing.T) {
}
// 1733: the Approve's ask says the check's state at the heads it names, read from the checker's verdict there: "passed
// its check" only when it passed. While the check gates no merge, the ask waits for the check's verdict (the operator,
// 2026-10-27 23:54: "if you don't want me to approve it, don't send the approval request"): a pass or a failure is asked,
// the failure in its words; with no verdict nothing is asked and the delivery says it waits its check, until the bound,
// past which it is asked anyway, saying so, and asked again in new words once the check passes. The verdict is the
// checker's verdicts bucket value as captured on the bus (mesh-delivery-checker, `<group>.<heads hash>`).
// its check" only when it passed. While the check gates no merge, the ask is made before any verdict, says that Approve
// merges before the check ends, and is asked again in new words once the check passes or fails; a running check is no
// new word.
for _, row := range []struct {
name, state, failed, then, path string
gated bool
notComposed bool
after time.Duration
asks, open int
want, not []string
name, state, failed string
gated bool
asks int
want, not []string
}{
{name: "gated, passed", gated: true, state: "pass", asks: 1,
want: []string{"app#7 Fix it passed its check. Approve merges it into main at " + readyHead[:12] + ";"},
not: []string{"before its check ends", "no verdict yet"}},
{name: "ungated, no verdict", asks: 0, want: []string{waitsCheckBeforeAsking + "its check has no verdict yet; asked anyway at 15:00 CEST if"}},
{name: "ungated, running", state: "running", asks: 0, want: []string{waitsCheckBeforeAsking + "its check has no verdict yet: it is running"}},
{name: "ungated, running past its bound", state: "running", after: askCheckBound, asks: 1,
want: []string{"its check has no verdict yet: it is running", "has given none in 60 minutes, so the operator is asked anyway",
"Approve merges it into main at " + readyHead[:12] + " now, before its check ends"}, not: []string{"passed"}},
{name: "ungated, past its bound, then passed", state: "running", after: askCheckBound, then: "pass", asks: 2,
want: []string{"passed its check. Approve merges it into main at " + readyHead[:12] + ";"}, not: []string{"before its check ends", "anyway"}},
{name: "ungated, passed", state: "pass", asks: 1,
{name: "ungated, no verdict", asks: 1,
want: []string{"its check has no verdict yet", "Approve merges it into main at " + readyHead[:12] + " now, before its check ends"},
not: []string{"passed"}},
{name: "ungated, running", state: "running", asks: 1,
want: []string{"its check has no verdict yet", "before its check ends"}, not: []string{"passed"}},
{name: "ungated, then passed", state: "pass", asks: 2,
want: []string{"passed its check. Approve merges it into main at " + readyHead[:12] + ";"}, not: []string{"before its check ends"}},
// A pass that turns back into a check with no verdict (a check started again, its verdict taken away) past the bound
// withdraws the ask, and the bound counts again from that moment: nothing is asked at once as unanswered.
{name: "ungated, passed, running again past its bound", state: "pass", after: askCheckBound, then: "running", asks: 1, open: -1,
want: []string{waitsCheckBeforeAsking + "its check has no verdict yet: it is running (since 15:00 CEST); asked anyway at 16:00 CEST"}},
{name: "ungated, passed, its verdict gone past its bound", state: "pass", after: askCheckBound, then: "gone", asks: 1, open: -1,
want: []string{waitsCheckBeforeAsking + "its check has no verdict yet; asked anyway at 16:00 CEST"}},
// A placement change's pass with its composition not judged holds no node's answer, and the ask says so (ADR 0559 §5).
{name: "ungated, placement passed uncomposed", state: "pass", path: "placement/node-a.json", notComposed: true, asks: 1,
want: []string{"passed its check, but its composition was not judged (the assigner is not running), so no node answered its placement"}},
{name: "ungated, failed", state: "fail", failed: "TestThing: wanted 1, got 2", asks: 1,
want: []string{"its check failed: TestThing: wanted 1, got 2", "although its check failed"}, not: []string{"passed", "anyway"}},
{name: "ungated, then failed", state: "fail", failed: "TestThing: wanted 1, got 2", asks: 2,
want: []string{"its check failed: TestThing: wanted 1, got 2", "although its check failed"}, not: []string{"passed"}},
} {
t.Run(row.name, func(t *testing.T) {
v := newWorld(t)
@@ -112,46 +98,26 @@ func TestAnApprovedPullRequestIsMergedThroughTheMergeTool(t *testing.T) {
ungated(v)
}
v.op.auto = false
p := pr("novox/app", 7, readyHead, "feat/x", firstOf(row.path, "src/a.go"))
p := pr("novox/app", 7, readyHead, "feat/x", "src/a.go")
p.Title = "Fix it"
v.h.PullUpdated(p)
head := headOf("novox/app", 7, readyHead)
put := func() {
hash, _ := sdk.HeadsHash([]sdk.Head{headOf("novox/app", 7, readyHead)})
value, _ := json.Marshal(map[string]any{"v": 1, "group": "g", "heads": hash, "state": row.state,
"failed": map[string]string{"words": row.failed}})
v.h.CheckerVerdictChanged("g."+hash, value)
}
if row.gated {
v.h.Checked(judgedAt("novox/app", 7, readyHead, "pass", "t1t1t1t1t1t1"))
}
v.settleAll()
if !row.gated && row.state != "" {
var more map[string]any
if row.notComposed {
more = map[string]any{"composition": map[string]string{"state": "not-run", "words": "the assigner is not running"}}
}
checkerSaysWith(v, "g", row.state, row.failed, more, head)
v.settleAll()
}
if row.after > 0 {
v.later(row.after)
v.settleAll()
}
if row.then != "" {
checkerSays(v, "g", row.then, row.failed, head)
put()
v.settleAll()
}
open := v.op.open()
wantOpen := min(row.asks, 1)
if row.open < 0 {
wantOpen = 0
}
if v.op.count() != row.asks || len(open) != wantOpen {
t.Fatalf("open asks %v, asked %d times; wanted asked %d times, %d open", open, v.op.count(), row.asks, wantOpen)
}
if wantOpen == 0 {
d := v.delivery(IDOf("novox/app", readyHead))
for _, w := range row.want {
if d.Ready == nil || !strings.Contains(d.Ready.Waits, w) {
t.Fatalf("the delivery's wait does not say %q: %+v", w, d.Ready)
}
}
return
if len(open) != 1 || v.op.count() != row.asks {
t.Fatalf("open asks %v, asked %d times; wanted one open, asked %d times", open, v.op.count(), row.asks)
}
e := v.op.ask(open[0]).Explanation
for _, w := range row.want {
@@ -180,8 +146,8 @@ func TestAnApprovedPullRequestIsMergedThroughTheMergeTool(t *testing.T) {
u.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
u.h.PullUpdated(pr("novox/app", 8, other, "feat/y", "src/b.go"))
u.settleAll()
if u.op.count() != 0 || u.state(IDOf("novox/app", readyHead)) != Ready {
t.Fatalf("ungated, two reviewed pull requests with no verdict: %d asks, %s; wanted ready and not asked", u.op.count(), u.state(IDOf("novox/app", readyHead)))
if u.op.count() != 2 || u.state(IDOf("novox/app", readyHead)) != Ready {
t.Fatalf("ungated, two reviewed pull requests with no verdict: %d asks, %s", u.op.count(), u.state(IDOf("novox/app", readyHead)))
}
if gates, _ := u.h.Status("listening")["check-gates-merge"].(bool); gates {
t.Fatalf("delivery_status does not say the check gates no merge: %v", u.h.Status("listening"))
@@ -191,12 +157,8 @@ func TestAnApprovedPullRequestIsMergedThroughTheMergeTool(t *testing.T) {
t.Fatalf("show does not say the check gates no merge: %v", shown)
}
u.h.Checked(judgedAt("novox/app", 8, other, "fail", "t1t1t1t1t1t1"))
checkerSays(u, "feat/y", "fail", "TestB", headOf("novox/app", 8, other))
u.h.PullMerged(merged("novox/app", 7, readyHead, "m7m7m7m7m7m7"))
u.settleAll()
if u.op.count() != 1 {
t.Fatalf("ungated, a failed verdict is asked once (the check gates no merge): %d asks", u.op.count())
}
d = u.delivery(IDOf("novox/app", other))
if d.State != Ready || d.Check == nil || d.Check.Passes() {
t.Fatalf("ungated, after a failed verdict and a trunk's move: %s, verdict %+v", d.State, d.Check)
@@ -361,44 +323,14 @@ func TestAGroupMergesEveryMemberInOnePassOnlyOnceComposedAndApproved(t *testing.
u.h.PullUpdated(pr("novox/mesh-controller", 1, ctlHead, "feat/x", "internal/a.go"))
u.h.PullUpdated(pr("novox/mesh-catalog", 2, catHead, "feat/x", "modules/app/module.json"))
u.settleAll()
group := []sdk.Head{headOf("novox/mesh-controller", 1, ctlHead), headOf("novox/mesh-catalog", 2, catHead)}
checkerSays(u, "feat/x", "running", "", group...)
u.settleAll()
// The group's check is the one of its heads together: while it runs, nothing is asked and each member says it waits.
if d := u.delivery(IDOf("novox/mesh-catalog", catHead)); u.op.count() != 0 || d.Ready == nil ||
!strings.Contains(d.Ready.Waits, waitsCheckBeforeAsking+"its check has no verdict yet: it is running") {
t.Fatalf("ungated, the group is asked %d times while its check runs; wanted none, and the wait said: %+v", u.op.count(), d.Ready)
}
checkerSays(u, "feat/x", "pass", "", group...)
u.settleAll()
if u.op.count() != 1 {
t.Fatalf("ungated, the group is asked %d times once its check passed; wanted once", u.op.count())
t.Fatalf("ungated, the group is asked %d times; wanted once", u.op.count())
}
if e := u.op.ask(u.op.open()[0]).Explanation; !strings.Contains(e, "2 pull requests, passed its check. Approve merges all of them into main in one pass, at the heads named;") {
t.Fatalf("ungated, the group's ask does not say its check passed:\n%s", e)
// 1733: the group's ask claims no pass it has not had.
if e := u.op.ask(u.op.open()[0]).Explanation; strings.Contains(e, "passed") ||
!strings.Contains(e, "2 pull requests: its check has no verdict yet. Approve merges all of them into main in one pass, at the heads named, now, before its check ends;") {
t.Fatalf("ungated, the group's ask does not say its check has no verdict yet:\n%s", e)
}
// A member re-pushed past the bound after its sibling became ready: the bound counts from the new head, so nothing is
// asked as unanswered at once (review round 1).
r := newWorld(t)
ungated(r)
r.op.auto = false
const ctlHead2 = "c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3"
r.h.PullUpdated(pr("novox/mesh-controller", 1, ctlHead, "feat/x", "internal/a.go"))
r.h.PullUpdated(pr("novox/mesh-catalog", 2, catHead, "feat/x", "modules/app/module.json"))
r.settleAll()
r.later(askCheckBound + time.Minute)
r.h.PullUpdated(pr("novox/mesh-controller", 1, ctlHead2, "feat/x", "internal/a.go"))
// Made ready by a handler, before the look gives it a run: no verdict and no status at the new heads, so only the rule
// that a member with no run counts as ready now keeps the older sibling's time from asking it as unanswered.
r.h.mu.Lock()
r.h.ungate(r.h.deliveries[IDOf("novox/mesh-controller", ctlHead2)], r.h.Now())
r.h.mu.Unlock()
r.settleAll()
if d := r.delivery(IDOf("novox/mesh-catalog", catHead)); r.op.count() != 0 || d.Ready == nil ||
!strings.Contains(d.Ready.Waits, waitsCheckBeforeAsking) {
t.Fatalf("a member re-pushed past the bound: asked %d times, wait %+v; wanted none asked and the wait said", r.op.count(), d.Ready)
}
u.op.answer(u.op.open()[0], OptionApprove)
u.settleAll()
if len(u.forge.merges) != 2 {
+1 -1
View File
@@ -99,7 +99,7 @@
},
"check-gates-merge": {
"type": "boolean",
"description": "Whether mesh/check gates the merge. True (the default): the operator's Approve is asked, and a merge handed, only on a passing verdict judged against the trunk's head, and a trunk's move puts a verdict out of date (ADR 0447, ADR 0505 §4). False (the operator, 2026-10-25 22:56: \"run the check locally only, but not as a gate, it loses us too much time\"; developers run the unit and integration levels locally before a pull request): a pull request reviewed at its head is ready, and its Approve is asked once the check at its heads (a group: of all its heads together) has a verdict, a pass or a failure said in the ask, or after 60 minutes with none, said so (the operator, 2026-10-27 23:54: \"if you don't want me to approve it, don't send the approval request\"); an approved merge waits for no verdict; no merge is refused for a check judged on an older trunk; a later verdict is shown on the pull request and the delivery, and asks a pending Approve again in its words; a group still merges all its members in one pass. Set it false together with the gitea module's check-gates-merge, which lets its merge tool merge an approved head without a passing mesh/check.",
"description": "Whether mesh/check gates the merge. True (the default): the operator's Approve is asked, and a merge handed, only on a passing verdict judged against the trunk's head, and a trunk's move puts a verdict out of date (ADR 0447, ADR 0505 §4). False (the operator, 2026-10-25 22:56: \"run the check locally only, but not as a gate, it loses us too much time\"; developers run the unit and integration levels locally before a pull request): a pull request reviewed at its head is ready and its Approve asked at once, with no verdict waited on; no merge is refused for a check judged on an older trunk; a verdict that comes is shown on the pull request and the delivery, never waited on; a group still merges all its members in one pass. Set it false together with the gitea module's check-gates-merge, which lets its merge tool merge an approved head without a passing mesh/check.",
"trusted": false,
"default": true
}
@@ -559,7 +559,7 @@ func cycleRules(is *Issue, from, to string) error {
}
if IsCore(is.LocatedIn) && is.Replay == "" && is.ReplayNone == "" {
return fmt.Errorf("issue %d is a core issue (it is located in the controller, the node-engine, the tool "+
"runner, the SDK, the delivery parts, or the catalog's bus, forge or build modules): it resolves with replay, the replay's id "+
"runner, the SDK, the delivery parts, or the catalogue's bus, forge or build modules): it resolves with replay, the replay's id "+
"in mesh-lab's replays register, or replay-none, why no replay is possible (ADR 0237)", is.Number)
}
case StatusWontfix:
-19
View File
@@ -206,29 +206,10 @@ account (and, until R1, the controller) and no other caller, and only sealed to
answers the controller alone today; it must also answer `<node>.mesh-vault` when it moves with the media catalogue,
after release 57.
## Taking what runs: `move-in` with `replace_running` (issue 1126, cause C4)
`move-in` never replaces a value the vault holds, so where the controller made an own secret anew after the move (a
rotation at start, a re-issue), the vault kept the first value while the new one runs. The node-engine of the machine
the secret is for hands the vault what runs, through `move-in` with `replace_running: true`, in an intake's two steps
(`owntake.go`): module, name and why, then the value sealed to the call's key. It is `move-in`'s and no verb of its
own, so the node-engine asks it on the subject it may publish already and the seat promises nothing new. Its own machine's secrets alone (the machine is the caller's, as the bus proved it); a
value the vault holds, never a person's (`accept`) or a provider's software's (`issued`, but for a covered bus
account); never over a value the vault changed in the last 15 minutes. The same value changes nothing and says so.
The replaced value is kept sealed as the record's `previous` (dropped by any later change), the generation is raised,
`secret-changed` and `own-replaced` are said, and the act is in `secret_handed` (`own-replaced`, `own-same`,
`own-take-refused`). A covered bus account so replaced has its hash written again. `own_drift` lists, from every
node's latest shadow answer (`<node>.node` in `node-engine.have`), each own secret whose node says another value,
with what the vault holds and whether the node's ask would be taken now. **The switch** is the vault's: a person
switches every machine's asks off or on with `own_take_switch` (`on`, `why`), kept in the vault's store over a
restart; it is on until switched off, and `own_drift` shows it.
## Events
- `secret-changed` — `name`, `by`, `at`, `generation`: which secret, who changed it, when. Never a value
or a sealed copy.
- `own-replaced` — `secret`, `node`, `module`, `name`, `from_generation`, `to_generation`, `by`, `why`, `at`:
an own secret replaced by what runs on its machine. Never a value or a fingerprint.
- `provisioned`, `rotated` — the custody ledger's, by fingerprint, as before.
- `provisioner.retirement` (ADR 0230 §35) — `waiting`, `settled`, `approved`, `rejected`, `retired`,
`reenabled`, `deleted`, naming holders, never a value.
+11 -1
View File
@@ -53,6 +53,8 @@ type AccountHash struct {
Adopted bool `json:"adopted,omitempty"`
From string `json:"from,omitempty"`
Node string `json:"node,omitempty"`
// Rotating is a rotation under way over a second login (rotation.go, ADR 0561 §4): absent when none is.
Rotating *Rotating `json:"rotating,omitempty"`
}
// AccountStore is the vault's state of bus-account hashes: read and written by the vault's instances alone.
@@ -61,6 +63,8 @@ type AccountStore interface {
Put(a AccountHash) error
// Users is every user with a key.
Users() ([]string, error)
// Delete takes a user's key out: an account retired (retire.go).
Delete(user string) error
}
// busAccounts is AccountStore over the vault's own state through its runtime.
@@ -80,6 +84,8 @@ func (busAccounts) Get(user string) (*AccountHash, error) {
func (busAccounts) Users() ([]string, error) { return stdio.State(BusAccountsState).Keys() }
func (busAccounts) Delete(user string) error { return stdio.State(BusAccountsState).Delete(user) }
func (busAccounts) Put(a AccountHash) error {
_, err := stdio.State(BusAccountsState).Put(a.User, a)
return err
@@ -181,6 +187,10 @@ func (v *Vault) HashAccount(secret string, force bool) (Hashed, error) {
if err != nil {
return Hashed{}, err
}
if rec.Retired != nil {
v.hashes.paid(secret)
return Hashed{}, fmt.Errorf("%s is retired (%s): its hash is written again only when it is wanted again", secret, rec.Retired.Why)
}
user, password, err := accountOf(secret, value)
if err != nil {
return Hashed{}, err
@@ -259,7 +269,7 @@ func (v *Vault) HashHeld() (written []Hashed, failed map[string]string) {
return nil, failed
}
for _, r := range records {
if !Covered(r.Name) {
if !Covered(r.Name) || r.Retired != nil {
continue
}
h, err := v.HashAccount(r.Name, false)
+3 -26
View File
@@ -58,32 +58,6 @@ type adoptionKept struct {
failed string // why the last look found nothing to adopt, or ""
}
// busNode is the node the assignments name as holding the bus module: exactly one.
func (v *Vault) busNode() (string, error) {
if v.Assignments.Keys == nil {
return "", errors.New("the vault cannot read the assignments, so it cannot tell which node holds the bus")
}
keys, err := v.Assignments.Keys()
if err != nil {
return "", fmt.Errorf("the assignments' keys could not be read: %w", err)
}
var nodes []string
for _, k := range keys {
if node, module, ok := strings.Cut(k, "."); ok && module == BusModule {
nodes = append(nodes, node)
}
}
sort.Strings(nodes)
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return "", fmt.Errorf("no node is assigned the bus module %s", BusModule)
}
return "", fmt.Errorf("%d nodes are assigned the bus module %s (%s): the vault adopts from one alone", len(nodes),
BusModule, strings.Join(nodes, ", "))
}
// AdoptNow is the tool account_adopt: the bus node's have read now and adopted, though it says the same as before.
func (v *Vault) AdoptNow(caller string) (Adoption, error) {
if v.Haves == nil {
@@ -143,6 +117,9 @@ func (v *Vault) adopt(node string, raw []byte, by string, force bool) (Adoption,
if err != nil {
return Adoption{}, fmt.Errorf("the have of %s on %s is not a have: %w", BusModule, node, err)
}
if have.UserList != nil {
v.LoadedListHeard(have.UserList.Revision)
}
if have.UserList == nil || have.UserList.Handed == nil {
return Adoption{}, fmt.Errorf("the have of %s on %s hands no hashes yet (its node-engine hands them once it "+
"heard the vault's key in its answer to node-key, and writes the list)", BusModule, node)
+1 -13
View File
@@ -91,9 +91,7 @@ type callKey struct {
// ask is the ask's record for `secret-ask`, which the call's id is.
ask *AskRecord
// move is what `move-in` takes: the row of the controller's store (move.go).
move *MoveOf
// why is what `move-in` with replace_running was asked for, in the caller's words (owntake.go).
why string
move *MoveOf
public [32]byte
private [32]byte
until time.Time
@@ -151,16 +149,6 @@ func (v *Vault) openCall(verb, secret, by string, ask *AskRecord) (string, strin
return id, base64.StdEncoding.EncodeToString(pub[:]), nil
}
// callKind is the kind of the open call id, or "" when none is open: what its second step is for.
func (v *Vault) callKind(id string) string {
v.callsMu.Lock()
defer v.callsMu.Unlock()
if c, ok := v.pending[id]; ok {
return c.verb
}
return ""
}
// takeCall ends a call: its key is forgotten whatever follows.
func (v *Vault) takeCall(verb, id string) (*callKey, error) {
v.callsMu.Lock()
@@ -48,6 +48,13 @@ func (f *fakeAccounts) Put(a AccountHash) error {
return nil
}
func (f *fakeAccounts) Delete(user string) error {
f.mu.Lock()
defer f.mu.Unlock()
delete(f.keys, user)
return nil
}
func (f *fakeAccounts) Users() ([]string, error) {
f.mu.Lock()
defer f.mu.Unlock()
@@ -0,0 +1,49 @@
package main
// The switch on the controller's lease (novox/hq ADR 0561 §3): minting is on only while the lease is handed to a holder
// that is no controller, and off for a controller's value, a key deleted or expired, or one that cannot be read. The
// write that hands it away turns it on and mints every wanted account the vault holds no value for; a lease handed back
// turns it off. No clock and no setting turns it. A key's age passing is heard by no watch, so the lease is read afresh
// before every mint (LeaseRead): a lease that expired since mints nothing.
import "git.novox.be/novox/mesh-sdk/go/buscompose"
// LeaseHeard is the watch of the controller's lease. When minting turns on or off, every wanted account is judged again:
// minted when on, held back with the new why when off.
func (v *Vault) LeaseHeard(raw []byte, found bool, readErr error) {
if !v.setLease(raw, found, readErr) {
return
}
on, why := v.mintingOn()
v.log("minting is %s: %s", map[bool]string{true: "ON", false: "off"}[on], why)
for _, user := range v.wantedUsers() {
if w, ok := v.wanted(user); ok {
if _, err := v.mintWanted(w, "the lease write"); err != nil {
v.log("%s is not minted: %v", user, err)
}
}
}
}
// setLease records what the lease says, and answers whether minting turned on or off by it.
func (v *Vault) setLease(raw []byte, found bool, readErr error) bool {
on, why := buscompose.LeaseHandedAway(raw, found, readErr)
m := &v.minting
m.mu.Lock()
defer m.mu.Unlock()
flipped := on != m.on || m.why == ""
if flipped {
m.since = v.Now().UTC()
}
m.on, m.why = on, why
return flipped
}
// leaseAfresh reads the lease again before a mint, where the vault can: a key that expired since is heard by no watch.
func (v *Vault) leaseAfresh() {
if v.LeaseRead == nil {
return
}
raw, found, err := v.LeaseRead()
v.setLease(raw, found, err)
}
+82 -2
View File
@@ -51,8 +51,8 @@ func build() *Env {
// Where it sees a consumer bind a provider (pair.go): the same mirror, every key.
env.Vault = &Vault{Store: store, Own: own, Askers: Declared{Read: readAssignment, Store: store},
Assignments: Mirror{Keys: assignmentKeys, Read: readAssignment}, Emit: emit, Ask: stdio.Ask,
Now: time.Now, Log: say, Accounts: busAccounts{}, Haves: readHave,
HaveKeys: func() ([]string, error) { return stdio.State(HaveRead).Keys() }}
Now: time.Now, Log: say, Accounts: busAccounts{}, Haves: readHave, LeaseRead: readLease, WantRead: readWant,
Placement: placement}
return env
}
@@ -96,6 +96,74 @@ func watchHandings(env *Env) bool {
return true
}
// watchWants mints from the grants part's wanted accounts as they change (mint.go, ADR 0561 §2): a watch, never a poll.
// It answers whether the watch began; one that did not is begun again at the next minute pass.
func watchWants(env *Env) bool {
if env.Vault == nil {
return true
}
err := stdio.State(WantedRead).Watch("", func(c stdio.StateChange) error {
env.Vault.WantHeard(c.Key, c.Value, c.Op == "delete" || c.Op == "purge" || len(c.Value) == 0)
return nil
})
if err != nil {
say("the grants part's wanted accounts are not watched, so nothing is minted; begun again at the next pass: %v", err)
return false
}
// The watch returns once every current key was handed: what has no key now is no longer wanted.
env.Vault.WantsRead()
return true
}
// placement reads the indexer's placement through the runtime under the vault's own account (its manifest reads it).
var placement = PlacementReader{
Keys: func() ([]string, error) { return stdio.State(PlacementRead).Keys() },
Read: func(key string) ([]byte, error) {
e, err := stdio.State(PlacementRead).Get(key)
if err != nil || e == nil {
return nil, err
}
return e.Value, nil
},
}
// readWant is one wanted account of the grants part, read afresh (issue-account).
func readWant(user string) ([]byte, bool, error) {
e, err := stdio.State(WantedRead).Get(user)
if err != nil || e == nil {
return nil, false, err
}
return e.Value, true, nil
}
// readLease is the controller's lease key, read through the runtime under the vault's own account (its manifest reads it).
func readLease() ([]byte, bool, error) {
e, err := stdio.State(LeaseRead).Get(LeaseKey)
if err != nil || e == nil {
return nil, false, err
}
return e.Value, true, nil
}
// watchLease turns minting on and off as the controller's lease is written (lease.go, ADR 0561 §3): a watch, never a
// poll; and the lease is read afresh before every mint. It answers whether the watch began.
func watchLease(env *Env) bool {
if env.Vault == nil {
return true
}
env.Vault.LeaseHeard(readLease())
err := stdio.State(LeaseRead).Watch(LeaseKey, func(c stdio.StateChange) error {
deleted := c.Op == "delete" || c.Op == "purge" || len(c.Value) == 0
env.Vault.LeaseHeard(c.Value, !deleted, nil)
return nil
})
if err != nil {
say("the controller's lease is not watched, so minting stays as last read; begun again at the next pass: %v", err)
return false
}
return true
}
// adoptOperatorKey takes the operator key from the export the mesh writes to the vault's root (what
// `operator key set` recorded; the controller keeps only a public half there), and seals again any
// operator copy not yet sealed to the current key. Run every minute, so a failure partway is finished. It
@@ -149,14 +217,26 @@ func main() {
written, failed := env.Vault.HashHeld()
say("hashed %d bus accounts at start; %d could not be, tried again every minute: %v", len(written), len(failed), failed)
}
// The operator key first: nothing is kept without it, so a want heard before it would not be minted.
env.pass()
watched := watchHandings(env)
lease := watchLease(env)
wants := watchWants(env)
for {
if !watched {
watched = watchHandings(env)
}
if !lease {
lease = watchLease(env)
}
if !wants {
wants = watchWants(env)
}
env.pass()
if env.Vault != nil {
env.Vault.HashOwed()
env.Vault.MintOwed()
env.Vault.RetirePass()
}
env.pairPass()
if env.Custody != nil {
+376
View File
@@ -0,0 +1,376 @@
package main
// The vault mints every new bus account (novox/hq ADR 0561 §1 to §4, issue 774).
//
// The grants part says which accounts the mesh wants, in its state `accounts` that the vault alone reads (§2): one key
// per bus user, holding what the controller's credential carries beside the password. The vault watches it, and for a
// user it holds no value for and whose hash it did not adopt it makes a password, keeps the account whole (built by
// mesh-sdk's HeldCredential, byte for byte the controller's shape) as the module's own secret on that node
// (`own/<node>/<module>/<broker|broker-<process>|provisioner-broker>`), sealed, with the operator's copy; writes the
// bcrypt hash into `bus-accounts`; and says `account-issued`, then `secret-changed`. The node's engine asks `own` again
// on `secret-changed` and composes.
//
// **One issuer at every moment** (§3): minting is on only while the controller's lease is handed to a holder that is no
// controller (mesh-sdk LeaseHandedAway). Until then the controller mints, the vault keeps hashing what it is handed, and
// vault_status names every wanted account it holds back and why. **Nothing is minted anew** (§4): an account whose value
// the vault holds, or whose hash it adopted, is never minted; the node accounts and the controller's own are never wanted.
// **Never two values for one user** (§7): a user whose hash the vault already wrote from another of its secrets is held
// back, said, and never replaced but by a rotation.
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"sync"
"time"
"git.novox.be/novox/mesh-sdk/go/buscompose"
)
// WantedRead is the grants part's state of wanted accounts, as the vault's manifest reads it.
const WantedRead = buscompose.GrantsAccounts
// LeaseRead is the controller's lease, as the vault's manifest reads it, and LeaseKey its one key.
const (
LeaseRead = buscompose.ControllerLease
LeaseKey = buscompose.ControllerLeaseKey
)
// AccountIssuedEvent is what the vault says when it minted an account (mesh-sdk buscompose.AccountIssued).
const AccountIssuedEvent = buscompose.AccountIssuedEvent
// minting is the switch and what the vault knows of the wanted accounts, kept in memory and read again from the bus at
// every start: the grants part's state and the lease are the record, never this.
type minting struct {
mu sync.Mutex
on bool
why string
since time.Time
// wants are the wanted accounts, by user, as last heard.
wants map[string]buscompose.WantedAccount
// heldBack are the wanted users the vault did not mint, with why (vault_status).
heldBack map[string]string
// owed are the wanted users whose mint failed, tried again at the pass (MintOwed).
owed map[string]bool
// minted are the accounts this vault minted since it started, by user (vault_status).
minted map[string]Minted
// loadedRevision is the highest revision of the user list the bus node said it loaded (rotation.go).
loadedRevision uint64
// retiring is what the passes keep of the accounts no longer wanted (retire.go).
retiring retiring
// mintMu keeps one mint at a time: a want heard, the switch turning on, and issue-account.
mintMu sync.Mutex
}
// Minted is what one mint did: the account and its secret, never its value or its hash.
type Minted struct {
User string `json:"user"`
Secret string `json:"secret"`
Generation int `json:"generation"`
At time.Time `json:"at"`
// Hashed says its hash is written; false leaves it owed, written at the next pass.
Hashed bool `json:"hashed"`
}
// MintState is what vault_status says of minting.
type MintState struct {
On bool `json:"on"`
Why string `json:"why"`
Since time.Time `json:"since,omitzero"`
Wanted int `json:"wanted"`
HeldBack map[string]string `json:"held_back"`
Minted []Minted `json:"minted"`
}
// MintState answers how minting stands.
func (v *Vault) MintState() MintState {
m := &v.minting
m.mu.Lock()
defer m.mu.Unlock()
out := MintState{On: m.on, Why: m.why, Since: m.since, Wanted: len(m.wants), HeldBack: map[string]string{}, Minted: []Minted{}}
if out.Why == "" {
out.Why = "the controller's lease has not been read yet, so nothing is minted"
}
for u, why := range m.heldBack {
out.HeldBack[u] = why
}
for _, x := range m.minted {
out.Minted = append(out.Minted, x)
}
sort.Slice(out.Minted, func(i, j int) bool { return out.Minted[i].User < out.Minted[j].User })
return out
}
// mintingOn says whether the vault mints now, and why.
func (v *Vault) mintingOn() (bool, string) {
v.minting.mu.Lock()
defer v.minting.mu.Unlock()
if v.minting.why == "" {
return false, "the controller's lease has not been read yet, so nothing is minted"
}
return v.minting.on, v.minting.why
}
func (v *Vault) holdBack(user, why string) {
m := &v.minting
m.mu.Lock()
defer m.mu.Unlock()
if m.heldBack == nil {
m.heldBack = map[string]string{}
}
m.heldBack[user] = why
}
func (v *Vault) noLongerHeld(user string) {
m := &v.minting
m.mu.Lock()
defer m.mu.Unlock()
delete(m.heldBack, user)
}
// AccountSecret is the vault's name of the own secret a wanted account is held in.
func AccountSecret(w buscompose.WantedAccount) (string, error) {
return OwnSecret(w.Node, w.Module, w.OwnSecret())
}
// WantHeard is the watch of the grants part's wanted accounts: a key put is a want, minted when minting is on; a key
// deleted is a want gone (retire.go).
func (v *Vault) WantHeard(user string, raw []byte, deleted bool) {
if deleted {
v.wantGone(user)
return
}
w, err := buscompose.ReadWantedAccount(user, raw)
if err != nil {
v.log("the wanted account %s is not read, so nothing is minted for it: %v", user, err)
v.holdBack(user, "its wanted key is not readable: "+err.Error())
return
}
v.minting.mu.Lock()
if v.minting.wants == nil {
v.minting.wants = map[string]buscompose.WantedAccount{}
}
v.minting.wants[user] = w
v.minting.mu.Unlock()
v.wantBack(user)
if _, err := v.mintWanted(w, "the grants part's want of "+user); err != nil {
v.log("%s is not minted: %v", user, err)
}
}
// errHeldBack is a want the vault does not mint now, with why: not an error of the vault.
type errHeldBack struct{ why string }
func (e errHeldBack) Error() string { return e.why }
// mintWanted mints w when minting is on, the vault holds no value for it and adopted no hash of it; otherwise it says
// why not and, where that is a hold, keeps it for vault_status.
func (v *Vault) mintWanted(w buscompose.WantedAccount, by string) (Minted, error) {
m, err := v.mintOnce(w, by)
var held errHeldBack
v.owe(w.User, err != nil && !errors.As(err, &held) && w.Valid() == nil)
return m, err
}
// mintOnce is one try of mintWanted.
func (v *Vault) mintOnce(w buscompose.WantedAccount, by string) (Minted, error) {
v.minting.mintMu.Lock()
defer v.minting.mintMu.Unlock()
if err := w.Valid(); err != nil {
v.holdBack(w.User, err.Error())
return Minted{}, err
}
secret, err := AccountSecret(w)
if err != nil {
v.holdBack(w.User, err.Error())
return Minted{}, err
}
if _, held, err := v.Store.Read(secret); err != nil {
return Minted{}, err
} else if held {
// Its value is held (the controller's, handed in, or one the vault minted): never minted anew (§4).
v.noLongerHeld(w.User)
return Minted{}, errHeldBack{secret + " is held already: an account the vault holds a value for is never minted anew (ADR 0561 §4)"}
}
if v.Accounts == nil {
v.holdBack(w.User, "the vault has no state of bus accounts to write the hash to")
return Minted{}, errors.New("the vault has no state of bus accounts to write the hash to")
}
was, err := v.Accounts.Get(w.User)
if err != nil {
v.holdBack(w.User, "its key in "+BusAccountsState+" cannot be read: "+err.Error())
return Minted{}, err
}
if was != nil && was.Adopted {
// The hash the bus loaded is kept (§4): not minted, and not held back either.
v.noLongerHeld(w.User)
return Minted{}, errHeldBack{w.User + "'s hash was adopted from the list the bus loaded: it keeps it, and is never minted (ADR 0561 §4)"}
}
if was != nil && was.Of != "" && was.Of != secret {
why := fmt.Sprintf("%s holds the hash of %s for %s, not of %s: a user has one value, so nothing is minted until "+
"a person sees why (ADR 0561 §7)", BusAccountsState, was.Of, w.User, secret)
v.holdBack(w.User, why)
return Minted{}, errHeldBack{why}
}
v.leaseAfresh()
if on, why := v.mintingOn(); !on {
v.holdBack(w.User, "held back: "+why)
return Minted{}, errHeldBack{why}
}
raw := make([]byte, 30)
if _, err := rand.Read(raw); err != nil {
return Minted{}, err
}
value, err := buscompose.HeldCredential(w, base64.RawURLEncoding.EncodeToString(raw))
if err != nil {
v.holdBack(w.User, err.Error())
return Minted{}, err
}
c, err := v.keepLocked(secret, string(value), "the vault", "", OriginMade, keepOptions{neverReplace: true, quiet: true})
if err != nil {
v.holdBack(w.User, "its value could not be kept: "+err.Error())
return Minted{}, err
}
out := Minted{User: w.User, Secret: secret, Generation: c.Generation, At: c.At}
// The hash first, then account-issued, then secret-changed: the grants part composes the user before the node asks.
if _, err := v.HashAccount(secret, false); err != nil {
v.hashes.owe(secret, err.Error())
v.log("%s is minted and kept, and ITS HASH IS NOT WRITTEN, written at the next pass: %v", w.User, err)
} else {
out.Hashed = true
if v.Emit != nil {
e := buscompose.AccountIssued{User: w.User, Kind: w.Kind, Node: w.Node, Module: w.Module, Process: w.Process,
Generation: c.Generation, At: c.At}
body := map[string]any{}
b, _ := json.Marshal(e)
_ = json.Unmarshal(b, &body)
if err := v.Emit(AccountIssuedEvent, body); err != nil {
v.log("%s is minted and hashed, but %s could not be said: %v", w.User, AccountIssuedEvent, err)
}
}
}
v.announce(c)
v.minting.mu.Lock()
if v.minting.minted == nil {
v.minting.minted = map[string]Minted{}
}
v.minting.minted[w.User] = out
v.minting.mu.Unlock()
v.noLongerHeld(w.User)
v.log("minted the bus account %s as %s (generation %d), for %s", w.User, secret, c.Generation, by)
return out, nil
}
// MintOwed tries again, at the vault's minute pass, every wanted account whose mint failed (its value could not be kept,
// its key read, its password made): a want heard is never lost to one refusal. A want held back is not owed: the switch
// or the want changing judges it again.
func (v *Vault) MintOwed() {
v.minting.mu.Lock()
var owed []string
for u := range v.minting.owed {
owed = append(owed, u)
}
v.minting.mu.Unlock()
sort.Strings(owed)
for _, u := range owed {
if w, ok := v.wanted(u); ok {
if _, err := v.mintWanted(w, "the pass, after a mint that failed"); err != nil {
v.log("%s is still not minted: %v", u, err)
}
} else {
v.owe(u, false)
}
}
}
// owe marks user's mint as failed (tried again at the pass) or not.
func (v *Vault) owe(user string, owed bool) {
v.minting.mu.Lock()
defer v.minting.mu.Unlock()
if !owed {
delete(v.minting.owed, user)
return
}
if v.minting.owed == nil {
v.minting.owed = map[string]bool{}
}
v.minting.owed[user] = true
}
// heldBackOrMinted is a mint's answer as a tool gives it.
func heldBackOrMinted(m Minted, err error) (any, error) {
var held errHeldBack
if errors.As(err, &held) {
return map[string]any{"minted": false, "why": held.why}, nil
}
if err != nil {
return nil, err
}
return map[string]any{"minted": true, "account": m}, nil
}
// IssueAccount is the seat's verb issue-account (ADR 0561 §9): one wanted user minted now, its key read afresh from the
// grants part's state. The recovery when a want was not heard: it mints nothing a want would not, and is refused while
// minting is off, for a node's account and the controller's (never minted here, §4), and for a user nobody wants.
func (v *Vault) IssueAccount(caller, user string) (any, error) {
user = strings.TrimSpace(user)
if user == "" {
return nil, errors.New("issue-account names a bus user (`user`), e.g. ace.mesh-build-go")
}
if nodeOrController(user) {
return nil, fmt.Errorf("%s is never minted by the vault: a node's account and the controller's keep the hash they "+
"have (ADR 0561 §4)", user)
}
v.leaseAfresh()
if on, why := v.mintingOn(); !on {
return nil, fmt.Errorf("not minted: %s", why)
}
raw, found, err := []byte(nil), false, error(nil)
if v.WantRead != nil {
raw, found, err = v.WantRead(user)
} else if w, ok := v.wanted(user); ok {
raw, err = json.Marshal(w)
found = err == nil
}
if err != nil {
return nil, fmt.Errorf("the wanted account %s could not be read: %w", user, err)
}
if !found {
return nil, fmt.Errorf("the grants part holds no wanted account %s: the vault mints only what placement composes "+
"(grants_accounts lists them)", user)
}
w, err := buscompose.ReadWantedAccount(user, raw)
if err != nil {
return nil, err
}
v.log("issue-account %s, asked by %s", user, someoneOr("", caller))
return heldBackOrMinted(v.mintWanted(w, "issue-account by "+someoneOr("", caller)))
}
// wantedUsers is every wanted user heard, sorted.
func (v *Vault) wantedUsers() []string {
v.minting.mu.Lock()
defer v.minting.mu.Unlock()
out := make([]string, 0, len(v.minting.wants))
for u := range v.minting.wants {
out = append(out, u)
}
sort.Strings(out)
return out
}
func (v *Vault) wanted(user string) (buscompose.WantedAccount, bool) {
v.minting.mu.Lock()
defer v.minting.mu.Unlock()
w, ok := v.minting.wants[user]
return w, ok
}
// nodeOrController says user is a node's account or the controller's: never minted here (ADR 0561 §4, §9).
func nodeOrController(user string) bool {
return user == ControllerCaller || strings.HasPrefix(user, "node.")
}
@@ -0,0 +1,422 @@
//go:build integration
package main
// The vault whole against a real bus (novox/hq ADR 0561 §1 to §4, issue 774's acceptance 12): the built binary, played
// over its real stdin and stdout as the node's tool runtime plays it (tools/call with the caller in _meta; mesh/state.*
// and mesh/publish answered from a real nats-server's key-value buckets and subjects), its store in a directory of its
// own. A want written to the grants part's state is minted only once the controller's lease is handed away: the hash is
// in bus-accounts, own answers the value sealed to the node, the value is the controller's shape and its hash's
// password, account-issued is said; an adopted user is never minted, and a lease handed back mints nothing.
import (
"bufio"
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/nacl/box"
"git.novox.be/novox/mesh-sdk/go/buscompose"
"git.novox.be/novox/mesh-sdk/go/seal"
"git.novox.be/novox/mesh-sdk/go/testbus"
)
// wire is one line between the runtime and the bundle (the SDK's stdio message).
type wire struct {
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
}
// player is the node's tool runtime as far as the vault needs it, over a real bus.
type player struct {
t *testing.T
ctx context.Context
nc *nats.Conn
js jetstream.JetStream
mu sync.Mutex
in io.Writer
next int
pending map[string]chan wire
said []string
}
// bucketOf is the bucket a state names: the vault's own by its local name, another's as `<owner>.<name>`.
func bucketOf(state string) string {
if owner, name, ok := strings.Cut(state, "."); ok {
return owner + "_" + name
}
return "mesh-vault_" + state
}
func (p *player) send(m map[string]any) {
raw, _ := json.Marshal(m)
p.mu.Lock()
defer p.mu.Unlock()
_, _ = p.in.Write(append(raw, '\n'))
}
func (p *player) answer(id json.RawMessage, result any, err error) {
if err != nil {
p.send(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": err.Error()}})
return
}
p.send(map[string]any{"id": id, "result": result})
}
func (p *player) kv(state string) (jetstream.KeyValue, error) {
return p.js.KeyValue(p.ctx, bucketOf(state))
}
// serve answers what the bundle asks, and hands the answers to what the test asked it.
func (p *player) serve(out io.Reader) {
scanner := bufio.NewScanner(out)
scanner.Buffer(make([]byte, 1<<20), 1<<24)
for scanner.Scan() {
var m wire
if json.Unmarshal(scanner.Bytes(), &m) != nil {
continue
}
if m.Method == "" {
var key string
_ = json.Unmarshal(m.ID, &key)
p.mu.Lock()
ch := p.pending[key]
delete(p.pending, key)
p.mu.Unlock()
if ch != nil {
ch <- m
}
continue
}
go p.handle(m)
}
}
func (p *player) handle(m wire) {
var a struct {
State string `json:"state"`
Key string `json:"key"`
Value json.RawMessage `json:"value"`
Body json.RawMessage `json:"body"`
}
_ = json.Unmarshal(m.Params, &a)
switch m.Method {
case "mesh/state.get":
kv, err := p.kv(a.State)
if err != nil {
p.answer(m.ID, nil, err)
return
}
e, err := kv.Get(p.ctx, a.Key)
if errors.Is(err, jetstream.ErrKeyNotFound) {
p.answer(m.ID, nil, nil)
return
}
if err != nil {
p.answer(m.ID, nil, err)
return
}
p.answer(m.ID, map[string]any{"key": e.Key(), "value": json.RawMessage(e.Value()), "revision": e.Revision()}, nil)
case "mesh/state.put":
kv, err := p.kv(a.State)
if err == nil {
var rev uint64
rev, err = kv.Put(p.ctx, a.Key, a.Value)
if err == nil {
p.answer(m.ID, map[string]any{"revision": rev}, nil)
return
}
}
p.answer(m.ID, nil, err)
case "mesh/state.keys":
kv, err := p.kv(a.State)
if err != nil {
p.answer(m.ID, nil, err)
return
}
keys, err := kv.Keys(p.ctx)
if errors.Is(err, jetstream.ErrNoKeysFound) {
keys, err = []string{}, nil
}
p.answer(m.ID, keys, err)
case "mesh/state.delete":
kv, err := p.kv(a.State)
if err == nil {
err = kv.Delete(p.ctx, a.Key)
}
p.answer(m.ID, map[string]any{}, err)
case "mesh/state.watch":
kv, err := p.kv(a.State)
if err != nil {
p.answer(m.ID, nil, err)
return
}
key := strings.ReplaceAll(a.Key, "**", ">")
if key == "" {
key = ">"
}
w, err := kv.Watch(p.ctx, key)
if err != nil {
p.answer(m.ID, nil, err)
return
}
var watch string
_ = json.Unmarshal(m.ID, &watch)
current := true
for e := range w.Updates() {
if e == nil {
current = false
p.answer(m.ID, map[string]any{}, nil)
continue
}
op := "put"
if e.Operation() != jetstream.KeyValuePut {
op = "delete"
}
change := map[string]any{"state": a.State, "key": e.Key(), "op": op, "revision": e.Revision(), "current": current}
if op == "put" {
change["value"] = json.RawMessage(e.Value())
}
p.mu.Lock()
p.next++
id := fmt.Sprintf("w-%d", p.next)
p.mu.Unlock()
p.send(map[string]any{"id": id, "method": "mesh/state", "params": map[string]any{"watch": watch, "change": change}})
}
case "mesh/publish":
var e struct {
Key string `json:"key"`
Body json.RawMessage `json:"body"`
}
_ = json.Unmarshal(m.Params, &e)
p.mu.Lock()
p.said = append(p.said, e.Key+" "+string(e.Body))
p.mu.Unlock()
p.answer(m.ID, map[string]any{}, p.nc.Publish("mesh.mod.mesh-vault.event."+e.Key, e.Body))
default:
// mesh/ask and the rest: nothing answers on this bus, as a call with no responder.
p.answer(m.ID, nil, errors.New("nats: no responders available for request"))
}
}
// call is a tools/call of the vault as caller, answered as the tool's JSON.
func (p *player) call(name, caller string, args map[string]any) (json.RawMessage, error) {
p.mu.Lock()
p.next++
id := fmt.Sprintf("c-%d", p.next)
ch := make(chan wire, 1)
p.pending[id] = ch
p.mu.Unlock()
p.send(map[string]any{"id": id, "method": "tools/call", "params": map[string]any{"name": name, "arguments": args,
"_meta": map[string]any{"mesh/caller": caller}}})
select {
case m := <-ch:
var r struct {
Content []struct {
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
}
if m.Error != nil {
return nil, errors.New(m.Error.Message)
}
if err := json.Unmarshal(m.Result, &r); err != nil || len(r.Content) != 1 {
return nil, fmt.Errorf("%s answered %s", name, m.Result)
}
if r.IsError {
return nil, errors.New(r.Content[0].Text)
}
return json.RawMessage(r.Content[0].Text), nil
case <-time.After(30 * time.Second):
return nil, fmt.Errorf("%s did not answer in 30s", name)
}
}
func (p *player) put(t *testing.T, state, key string, v any) {
t.Helper()
kv, err := p.kv(state)
if err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(v)
if _, err := kv.Put(p.ctx, key, raw); err != nil {
t.Fatal(err)
}
}
func (p *player) hashOf(t *testing.T, user string) *AccountHash {
t.Helper()
kv, err := p.kv(BusAccountsState)
if err != nil {
t.Fatal(err)
}
e, err := kv.Get(p.ctx, user)
if errors.Is(err, jetstream.ErrKeyNotFound) {
return nil
}
if err != nil {
t.Fatal(err)
}
var a AccountHash
if err := json.Unmarshal(e.Value(), &a); err != nil {
t.Fatal(err)
}
return &a
}
func eventually(t *testing.T, what string, ok func() bool) {
t.Helper()
for end := time.Now().Add(30 * time.Second); time.Now().Before(end); time.Sleep(50 * time.Millisecond) {
if ok() {
return
}
}
t.Fatalf("never: %s", what)
}
// 774/AC12.
func TestTheVaultWholeMintsOnTheBusOnlyFromTheLeaseWrite(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
dir := t.TempDir()
bin := filepath.Join(dir, "mesh-vault")
build := exec.Command("go", "build", "-o", bin, ".")
build.Stderr = os.Stderr
if err := build.Run(); err != nil {
t.Fatalf("the vault does not build: %v", err)
}
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
t.Fatal(err)
}
t.Cleanup(nc.Close)
js, err := jetstream.New(nc)
if err != nil {
t.Fatal(err)
}
for _, b := range []string{"mesh-vault_bus-accounts", "mesh-grants_accounts", "mesh-controller_lease",
"mesh-controller_assignments", "node-engine_have", "mesh-delivery-indexer_placement"} {
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: b, History: 2}); err != nil {
t.Fatal(err)
}
}
// The operator key, as the mesh exports it to the vault's root.
opPub, _, err := box.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
root := filepath.Join(dir, "root")
_ = os.MkdirAll(root, 0o700)
export, _ := json.Marshal(map[string]string{"operator-key": base64.StdEncoding.EncodeToString(opPub[:])})
if err := os.WriteFile(filepath.Join(root, "export.json"), export, 0o600); err != nil {
t.Fatal(err)
}
cmd := exec.CommandContext(ctx, bin)
cmd.Env = append(os.Environ(), "MESH_VAULT_STORE="+filepath.Join(dir, "store"), "MESH_VAULT_STATE="+filepath.Join(dir, "state"),
"MESH_VAULT_ROOT="+root, "MESH_VAULT_LEDGER="+filepath.Join(dir, "ledger"), "MESH_RECEIVES="+filepath.Join(dir, "mesh.json"),
"MESH_NODE=novox", "MESH_MODULE=mesh-vault")
stdin, _ := cmd.StdinPipe()
stdout, _ := cmd.StdoutPipe()
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = stdin.Close(); cancel(); _ = cmd.Wait() })
p := &player{t: t, ctx: ctx, nc: nc, js: js, in: stdin, pending: map[string]chan wire{}}
go p.serve(stdout)
status := func() MintState {
raw, err := p.call("vault_status", "person.jochen", nil)
if err != nil {
return MintState{}
}
var s struct {
Minting MintState `json:"minting"`
}
_ = json.Unmarshal(raw, &s)
return s.Minting
}
// The controller holds the lease: a want is held back, nothing is minted.
p.put(t, "mesh-controller.lease", LeaseKey, map[string]any{"instance": "novox/1/2026-10-27", "epoch": 57})
x, y, z := aWant("mod-x"), aWant("mod-y"), aWant("mod-z")
p.put(t, "mesh-vault.bus-accounts", y.User, AccountHash{User: y.User, Hash: "$2a$04$adoptedadoptedadoptedadoptedadoptedadoptedadopte", Adopted: true})
p.put(t, "mesh-grants.accounts", x.User, x)
p.put(t, "mesh-grants.accounts", y.User, y)
eventually(t, "the want held back under the controller's lease", func() bool {
return strings.Contains(status().HeldBack[x.User], "controller holds the lease")
})
if p.hashOf(t, x.User) != nil {
t.Fatal("minted under the controller's lease")
}
// The write that hands the lease away mints it.
p.put(t, "mesh-controller.lease", LeaseKey, map[string]any{"handed-to": "the operator's hand-over"})
eventually(t, "the account minted at the lease write", func() bool { return p.hashOf(t, x.User) != nil })
nodePub, nodePriv := aSealingKey(t)
if _, err := p.call(Seat+".node-key", "node.ace", map[string]any{"key": nodePub}); err != nil {
t.Fatal(err)
}
raw, err := p.call(Seat+".own", "node.ace", map[string]any{})
if err != nil {
t.Fatal(err)
}
var own OwnAnswer
if err := json.Unmarshal(raw, &own); err != nil {
t.Fatal(err)
}
if len(own.Own) != 1 || own.Own[0].Module != "mod-x" || own.Own[0].Name != "broker" || own.Own[0].Origin != OriginMade {
t.Fatalf("own answers %+v", own.Own)
}
value, err := seal.Open(own.Own[0].Sealed, nodePriv)
if err != nil {
t.Fatal(err)
}
var held struct{ Password string }
_ = json.Unmarshal([]byte(value), &held)
shape, _ := buscompose.HeldCredential(x, held.Password)
if value != string(shape) {
t.Errorf("the minted value %q is not the controller's shape %q", value, shape)
}
if h := p.hashOf(t, x.User); bcrypt.CompareHashAndPassword([]byte(h.Hash), []byte(held.Password)) != nil || h.Adopted || h.Generation != 1 {
t.Errorf("bus-accounts %s holds %+v, not the minted password's hash", x.User, h)
}
if h := p.hashOf(t, y.User); h == nil || !h.Adopted {
t.Errorf("the adopted %s was replaced: %+v", y.User, h)
}
p.mu.Lock()
said := strings.Join(p.said, "\n")
p.mu.Unlock()
if !strings.Contains(said, AccountIssuedEvent+` {"`) || !strings.Contains(said, `"user":"ace.mod-x"`) || strings.Contains(said, held.Password) {
t.Errorf("the vault said: %s", said)
}
// Handed back to a controller: a new want mints nothing.
p.put(t, "mesh-controller.lease", LeaseKey, map[string]any{"instance": "novox/2/2026-10-28", "epoch": 58})
p.put(t, "mesh-grants.accounts", z.User, z)
eventually(t, "the new want held back once the lease is the controller's again", func() bool {
return strings.Contains(status().HeldBack[z.User], "controller holds the lease")
})
if p.hashOf(t, z.User) != nil {
t.Error("minted after the lease was handed back")
}
}
@@ -0,0 +1,244 @@
package main
import (
"encoding/json"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/buscompose"
"git.novox.be/novox/mesh-sdk/go/seal"
)
// aWant is a wanted account of a module on ace, as the grants part writes it.
func aWant(module string) buscompose.WantedAccount {
return buscompose.WantedAccount{User: "ace." + module, Kind: buscompose.KindModule, Node: "ace", Module: module,
URL: "nats://novox.mesh:4222", Fingerprint: "ab:cd", Claims: []buscompose.ClaimedSeat{{Seat: "s", Scope: "node"}}}
}
func wantRaw(t *testing.T, w buscompose.WantedAccount) []byte {
t.Helper()
raw, err := json.Marshal(w)
if err != nil {
t.Fatal(err)
}
return raw
}
// mintingVault is a vault with a state of bus accounts, ace's sealing key stated, ace's modules assigned, and minting
// turned on or off as on says.
func mintingVault(t *testing.T, on bool) (testVault, *fakeAccounts, string) {
t.Helper()
plans := assignments{"ace.mod-x": `{"node":"ace","module":"mod-x"}`, "ace.mod-y": `{"node":"ace","module":"mod-y"}`}
v := newVault(t, nil)
v.Askers = Declared{Read: plans.read, Store: v.Store}
accounts := &fakeAccounts{}
v.Accounts = accounts
pub, priv := aSealingKey(t)
if err := v.recordNodeKey("ace", pub, "node.ace"); err != nil {
t.Fatal(err)
}
if on {
v.LeaseHeard([]byte(`{"handed-to":"the operator's hand-over"}`), true, nil)
} else {
v.LeaseHeard([]byte(`{"instance":"novox/1/2026-10-27","epoch":57}`), true, nil)
}
return v, accounts, priv
}
// 774/AC7 (novox/hq ADR 0561 §1, §2, §4): a want with no value, minting on, is minted once: kept whole in the controller's
// shape as the module's broker, its hash in bus-accounts, said account-issued before secret-changed, and answered by own
// sealed to the node; a value held or a hash adopted is never minted.
func TestTheVaultMintsAWantedAccountOnceAndNothingItHolds(t *testing.T) {
v, accounts, nodePriv := mintingVault(t, true)
w := aWant("mod-x")
before := len(v.bus.events)
v.WantHeard(w.User, wantRaw(t, w), false)
rec, held, err := v.Store.Read("own/ace/mod-x/broker")
if err != nil || !held || rec.Generation != 1 || rec.Origin != OriginMade {
t.Fatalf("the minted account is kept as %+v (held %v, %v)", rec, held, err)
}
value, err := seal.Open(rec.AtRest, v.Own.PrivateKey)
if err != nil {
t.Fatal(err)
}
var got struct{ Password string }
_ = json.Unmarshal([]byte(value), &got)
shape, _ := buscompose.HeldCredential(w, got.Password)
if len(got.Password) != 40 || value != string(shape) {
t.Errorf("the minted value is %q, not the controller's shape %q", value, shape)
}
if !accounts.hashOf(w.User, got.Password, 1) {
t.Errorf("%s's hash is not the minted password's: %+v", w.User, accounts.keys[w.User])
}
var order []string
for _, e := range v.bus.events[before:] {
order = append(order, e["event"].(string))
}
if strings.Join(order, ",") != AccountHashedEvent+","+AccountIssuedEvent+","+ChangedEvent {
t.Errorf("said %v, want the hash, account-issued, then secret-changed", order)
}
for _, raw := range v.bus.raw[before:] {
if strings.Contains(raw, got.Password) || strings.Contains(raw, "$2a$") {
t.Errorf("a value or a hash was said: %s", raw)
}
}
own, err := v.OwnOfNode("node.ace")
if err != nil || len(own.Own) != 1 {
t.Fatalf("own answered %+v, %v", own, err)
}
if opened, err := seal.Open(own.Own[0].Sealed, nodePriv); err != nil || opened != value {
t.Errorf("own's sealed value opens to %q, %v", opened, err)
}
// Heard again, or for a value held, or for a hash adopted: nothing is minted, nothing is held back.
v.WantHeard(w.User, wantRaw(t, w), false)
if rec, _, _ := v.Store.Read("own/ace/mod-x/broker"); rec.Generation != 1 {
t.Errorf("a want heard again minted generation %d", rec.Generation)
}
accounts.keys["ace.mod-y"] = AccountHash{User: "ace.mod-y", Hash: "$2a$04$adopted", Adopted: true}
y := aWant("mod-y")
v.WantHeard(y.User, wantRaw(t, y), false)
if _, held, _ := v.Store.Read("own/ace/mod-y/broker"); held || accounts.keys["ace.mod-y"].Hash != "$2a$04$adopted" {
t.Errorf("an adopted user was minted")
}
if st := v.MintState(); len(st.HeldBack) != 0 || len(st.Minted) != 1 {
t.Errorf("vault_status says %+v: an adopted user is not held back, one account minted", st)
}
}
// 774/AC8 (novox/hq ADR 0561 §3): while the controller holds the lease nothing is minted and vault_status says why and
// names each wanted account held back (never an adopted one); the write that hands the lease away mints them; a lease
// handed back, expired or unreadable turns minting off again, read afresh before every mint.
func TestNothingIsMintedUntilTheLeaseIsHandedAway(t *testing.T) {
v, accounts, _ := mintingVault(t, false)
accounts.keys = map[string]AccountHash{"ace.mod-y": {User: "ace.mod-y", Hash: "$2a$04$adopted", Adopted: true}}
for _, m := range []string{"mod-x", "mod-y"} {
w := aWant(m)
v.WantHeard(w.User, wantRaw(t, w), false)
}
st := v.MintState()
if st.On || !strings.Contains(st.Why, "controller holds the lease") || len(st.HeldBack) != 1 ||
!strings.Contains(st.HeldBack["ace.mod-x"], "controller holds the lease") {
t.Fatalf("under the controller's lease vault_status says %+v", st)
}
if _, held, _ := v.Store.Read("own/ace/mod-x/broker"); held {
t.Fatal("minted while the controller holds the lease")
}
// Handed away: the wanted account is minted at that write, the adopted one is not.
lease := []byte(`{"handed-to":"the operator's hand-over"}`)
v.LeaseRead = func() ([]byte, bool, error) { return lease, true, nil }
v.LeaseHeard(lease, true, nil)
if _, held, _ := v.Store.Read("own/ace/mod-x/broker"); !held {
t.Fatalf("not minted at the lease write: %+v", v.MintState())
}
if _, held, _ := v.Store.Read("own/ace/mod-y/broker"); held {
t.Error("an adopted account was minted at the lease write")
}
if st := v.MintState(); !st.On || len(st.HeldBack) != 0 {
t.Errorf("after the lease write vault_status says %+v", st)
}
// The key expired (no watch hears a key's age pass): read afresh before the next mint, nothing is minted.
v.LeaseRead = func() ([]byte, bool, error) { return nil, false, nil }
z := aWant("mod-z")
v.WantHeard(z.User, wantRaw(t, z), false)
if _, held, _ := v.Store.Read("own/ace/mod-z/broker"); held {
t.Error("minted after the lease's key expired")
}
if st := v.MintState(); st.On || !strings.Contains(st.HeldBack["ace.mod-z"], "no lease is written") {
t.Errorf("after the key expired vault_status says %+v", st)
}
}
// 774/AC10 issue-account (novox/hq ADR 0561 §9): the verb mints one wanted user now, read afresh; it is refused while
// minting is off, for a node's account and the controller's, and for a user nobody wants; a user held already is said so.
func TestIssueAccountMintsOneWantedUserNowAndRefusesTheRest(t *testing.T) {
v, _, _ := mintingVault(t, false)
w := aWant("mod-x")
raw := wantRaw(t, w)
v.WantRead = func(user string) ([]byte, bool, error) {
if user == w.User {
return raw, true, nil
}
return nil, false, nil
}
for user, says := range map[string]string{
"ace.mod-x": "controller holds the lease",
"node.ace": "never minted",
"controller": "never minted",
} {
if _, err := v.IssueAccount("person.jochen", user); err == nil || !strings.Contains(err.Error(), says) {
t.Errorf("%s: %v, want a refusal saying %q", user, err, says)
}
}
v.LeaseHeard([]byte(`{"handed-to":"the operator's hand-over"}`), true, nil)
if _, err := v.IssueAccount("person.jochen", "ace.nobody"); err == nil || !strings.Contains(err.Error(), "no wanted account") {
t.Errorf("a user nobody wants: %v", err)
}
got, err := v.IssueAccount("person.jochen", w.User)
if err != nil || got.(map[string]any)["minted"] != true {
t.Fatalf("issue-account: %v, %v", got, err)
}
if again, err := v.IssueAccount("person.jochen", w.User); err != nil || again.(map[string]any)["minted"] != false ||
!strings.Contains(again.(map[string]any)["why"].(string), "held already") {
t.Errorf("issue-account again: %v, %v", again, err)
}
}
// 774/AC10 the rotation's rule (novox/hq ADR 0561 §4): at most one rotation begins per revision of the loaded user list,
// over the second login `<user>--b`, never of a node's account, the controller's or an adopted hash, and `rotate` of a
// covered account stays refused, so nothing rotates in place.
func TestOneRotationBeginsPerRevisionOfTheLoadedList(t *testing.T) {
v, accounts, _ := mintingVault(t, true)
for _, m := range []string{"mod-x", "mod-y"} {
w := aWant(m)
v.WantHeard(w.User, wantRaw(t, w), false)
}
if _, err := v.BeginRotation("ace.mod-x"); err == nil || !strings.Contains(err.Error(), "not known yet") {
t.Errorf("began with no loaded revision known: %v", err)
}
v.LoadedListHeard(570)
r, err := v.BeginRotation("ace.mod-x")
if err != nil || r.Login != "ace.mod-x--b" || r.Revision != 570 || r.Generation != 2 || accounts.keys["ace.mod-x"].Rotating == nil {
t.Fatalf("the first rotation: %+v, %v", r, err)
}
if _, err := v.BeginRotation("ace.mod-y"); err == nil || !strings.Contains(err.Error(), "one rotation begins per revision") {
t.Errorf("a second rotation in one revision: %v", err)
}
v.LoadedListHeard(571)
if _, err := v.BeginRotation("ace.mod-y"); err != nil {
t.Errorf("the next revision's rotation: %v", err)
}
if _, err := v.BeginRotation("ace.mod-x"); err == nil || !strings.Contains(err.Error(), "rotating already") {
t.Errorf("an account rotating began again: %v", err)
}
accounts.keys["node.ace"] = AccountHash{User: "node.ace", Hash: "$2a$04$n", Adopted: true}
for _, u := range []string{"node.ace", "controller"} {
if _, err := v.BeginRotation(u); err == nil {
t.Errorf("%s began a rotation", u)
}
}
if _, err := v.RotateFor(ControllerCaller, "own/ace/mod-x/broker", Narrow{}, "the test", "a rotation in place"); err == nil {
t.Error("a covered account rotated in place")
}
}
// A mint that failed (here: no operator key yet, so nothing can be kept) is tried again at the pass, never lost.
func TestAFailedMintIsTriedAgainAtThePass(t *testing.T) {
v, accounts, _ := mintingVault(t, true)
key, _ := v.Store.OperatorKey()
if err := v.Store.setOperatorKey("", "the test", v.Now()); err != nil {
t.Fatal(err)
}
w := aWant("mod-x")
v.WantHeard(w.User, wantRaw(t, w), false)
if _, ok := accounts.keys[w.User]; ok {
t.Fatal("minted with no operator key")
}
if err := v.Store.setOperatorKey(key, "the test", v.Now()); err != nil {
t.Fatal(err)
}
v.MintOwed()
if _, ok := accounts.keys[w.User]; !ok {
t.Errorf("not minted at the pass after the failure: %+v", v.MintState())
}
}
@@ -14,8 +14,6 @@ import (
"testing"
"time"
"git.novox.be/novox/mesh-sdk/go/delivery"
"git.novox.be/novox/mesh-sdk/go/seal"
"golang.org/x/crypto/nacl/box"
)
@@ -321,139 +319,3 @@ func TestMoveInThroughTheTool(t *testing.T) {
t.Fatalf("asks through the tool: %+v, %v", moved, err)
}
}
// Issue 1126, cause C4: a machine's node-engine hands the vault what runs of its own machine's own secret, where the
// vault holds another. Refused for another machine's secret, one that is not an own secret or not held, a person's or a
// provider's software's value, an empty value, and one the vault changed in the last 15 minutes; the same value changes
// nothing. A replacement keeps the old value as the previous generation, raises the generation, and says own-replaced
// with both generations and never a value; own_drift lists it from the node's shadow answer.
func TestANodeEngineHandsTheVaultWhatRunsOnItsOwnMachine(t *testing.T) {
v := newVault(t, nil)
tick, later := v.Now, time.Duration(0)
v.Now = func() time.Time { return tick().Add(later) }
old, running := "the-value-moved-in-first", "the-value-the-controller-made-at-start"
if _, err := moveIn(t, v, "node.anchor", superuser(), old); err != nil {
t.Fatal(err)
}
for _, origin := range []string{"accepted", "issued"} {
m := superuser()
m.Name, m.Origin = "from-"+origin, origin
if _, err := moveIn(t, v, "node.anchor", m, "value-"+origin); err != nil {
t.Fatal(err)
}
}
later = time.Hour
// Through move-in's tool as the node-engine asks it: replace_running in the first step, the second known by its call.
moveInTool := toolNamed(t, definitions(&Env{Vault: v.Vault}), Seat+".move-in")
take := func(caller string, of OwnTakeOf, value string) (OwnReplaced, error) {
got, err := moveInTool.runAs(caller, map[string]any{ReplaceRunningArg: true, "node": of.Node, "module": of.Module,
"name": of.Name, "secret": of.Secret, "why": of.Why})
if err != nil {
return OwnReplaced{}, err
}
opened := got.(Opened)
got, err = moveInTool.runAs(caller, map[string]any{"call": opened.Call, "sealed": sealToCall(t, opened.SealTo, value)})
if err != nil {
return OwnReplaced{}, err
}
return got.(OwnReplaced), nil
}
pg := OwnTakeOf{Module: "postgres", Name: "superuser-password", Why: "the shadow answer says another value"}
for name, row := range map[string]struct {
caller string
of OwnTakeOf
value string
says string
}{
"another machine's, named": {"node.shanks", OwnTakeOf{Node: "anchor", Module: "postgres", Name: "superuser-password"}, running, "anchor's"},
"another machine's, whole name": {"node.shanks", OwnTakeOf{Secret: "own/anchor/postgres/superuser-password"}, running, "anchor's"},
"not a node-engine": {ControllerCaller, pg, running, "not a node-engine"},
"a module's tools": {"anchor.node-tools", pg, running, "not a node-engine"},
"not an own secret": {"node.anchor", OwnTakeOf{Secret: "pair/anchor/database/shanks/gitea"}, running, "not a module's own secret"},
"not held": {"node.anchor", OwnTakeOf{Module: "postgres", Name: "never-made"}, running, "nothing to replace"},
"a person's value": {"node.anchor", OwnTakeOf{Module: "postgres", Name: "from-accepted"}, running, "by a person"},
"a provider's software's value": {"node.anchor", OwnTakeOf{Module: "postgres", Name: "from-issued"}, running, "issued by its provider"},
"an empty value": {"node.anchor", pg, " ", "empty"},
} {
if _, err := take(row.caller, row.of, row.value); err == nil || !strings.Contains(err.Error(), row.says) {
t.Errorf("%s: %v, want refused saying %q", name, err, row.says)
}
}
if rec, _, _ := v.Store.Read("own/anchor/postgres/superuser-password"); rec.Generation != 1 || rec.Previous != nil {
t.Fatalf("a refusal changed the secret: generation %d, previous %+v", rec.Generation, rec.Previous)
}
// The value the vault holds already changes nothing, and says so.
if same, err := take("node.anchor", pg, old); err != nil || !same.Unchanged || same.To != 1 {
t.Errorf("the same value: %+v %v", same, err)
}
// What runs replaces it: one generation more, the old kept as the previous, origin kept, its fingerprint answered.
got, err := take("node.anchor", pg, running)
if err != nil {
t.Fatal(err)
}
rec, _, _ := v.Store.Read("own/anchor/postgres/superuser-password")
if got.From != 1 || got.To != 2 || got.Unchanged || got.Fingerprint != Fingerprint(running) || rec.Generation != 2 ||
rec.Origin != OriginMade || rec.ChangedBy != "node.anchor" || rec.Previous == nil || rec.Previous.Generation != 1 {
t.Fatalf("replaced %+v, the record at generation %d origin %q by %s, previous %+v", got, rec.Generation, rec.Origin,
rec.ChangedBy, rec.Previous)
}
if now, _ := seal.Open(rec.AtRest, v.Own.PrivateKey); now != running {
t.Error("the vault does not hold what runs")
}
if was, _ := seal.Open(rec.Previous.AtRest, v.Own.PrivateKey); was != old ||
openOperator(t, v.operatorPublic, v.operatorPrivate, rec.Previous.Operator.Sealed) != old {
t.Error("the previous value is not kept, for the vault and the operator")
}
// Said once, with both generations and why, never a value.
var replaced []map[string]any
for _, e := range v.bus.events {
if e["event"] == OwnReplacedEvent {
replaced = append(replaced, e["body"].(map[string]any))
}
}
if len(replaced) != 1 || replaced[0]["secret"] != "own/anchor/postgres/superuser-password" ||
replaced[0]["from_generation"] != 1 || replaced[0]["to_generation"] != 2 || replaced[0]["node"] != "anchor" ||
replaced[0]["why"] != pg.Why {
t.Errorf("own-replaced said %v", replaced)
}
if all := everything(t, v, got); strings.Contains(all, running) || strings.Contains(all, old) {
t.Fatal("a value is in something the vault said, answered or wrote in the clear")
}
// Taken again at once, over the value the vault just took: refused.
if _, err := take("node.anchor", pg, "a-value-older-than-the-vaults"); err == nil || !strings.Contains(err.Error(), "less than") {
t.Errorf("a running value over one the vault just took: %v", err)
}
// Switched off by a person, every ask is refused, saying who and why; on again, taken again.
later += time.Hour
if _, err := v.SwitchOwnTake("jochen", false, "the test"); err != nil {
t.Fatal(err)
}
if _, err := take("node.anchor", pg, "after-the-switch"); err == nil || !strings.Contains(err.Error(), "switched off (by jochen") {
t.Errorf("an ask while switched off: %v", err)
}
if _, err := v.SwitchOwnTake("jochen", true, "the test"); err != nil {
t.Fatal(err)
}
later -= time.Hour
// own_drift reads it from the node's latest shadow answer, mesh-wide; the id as a node runs it, its module's name
// first (captured from novox's shadow answer, 2026-10-28: only-office.needs-jwt).
answer := delivery.CandidateAnswer{Head: "h", Verdict: delivery.CandidateDiffers, Differs: []delivery.ModuleDiffers{{
Module: "postgres", Why: "the resource differs", Bodies: []delivery.ResourceBodies{{ID: "postgres.needs-superuser-password",
Composed: `{"sealed":"` + delivery.MaskedAnotherValue + `"}`, Running: `{"sealed":"` + delivery.MaskedAnotherValue + `"}`}}}}}
have, err := delivery.EncodeHaveNode(delivery.HaveNode{Candidates: map[string]delivery.CandidateAnswer{"g": answer},
Composes: delivery.ComposesController})
if err != nil {
t.Fatal(err)
}
v.HaveKeys = func() ([]string, error) { return []string{"anchor.node", "anchor.postgres"}, nil }
v.Haves = func(key string) ([]byte, error) { return have, nil }
drift, err := v.OwnDrift()
if err != nil {
t.Fatal(err)
}
if len(drift.Secrets) != 1 || drift.Secrets[0].Secret != "own/anchor/postgres/superuser-password" ||
drift.Secrets[0].Generation != 2 || drift.Secrets[0].Previous != 1 || drift.Secrets[0].Takeable ||
len(drift.Nodes) != 1 || drift.Nodes[0].ValuesDiffer["g"] != 1 || drift.Nodes[0].Composes != delivery.ComposesController {
t.Errorf("own_drift: %+v", drift)
}
}
+6 -9
View File
@@ -84,17 +84,14 @@ func (v *Vault) credentialRefusal(node string, c CredentialAsked) string {
if c.Consumer != node {
return fmt.Sprintf("%s asks as a consumer on %s, and is not that machine", node, c.Consumer)
}
// The consuming module stands on the machine: read, never assumed (an assignment that cannot be read refuses).
read, why := v.assignmentReader(node)
if why != "" {
return why
}
raw, err := read(node + "." + c.ConsumerModule)
// The consuming module stands on the machine: read from the placement and the assignments, never assumed (one
// that cannot be read refuses).
stands, err := v.standsOn(node, c.ConsumerModule)
if err != nil {
return fmt.Sprintf(notYetPrefix+"the assignment %s.%s could not be read: %v", node, c.ConsumerModule, err)
return fmt.Sprintf(notYetPrefix+"where %s stands could not be read: %v", c.ConsumerModule, err)
}
if raw == nil {
return fmt.Sprintf("%s is not on %s: neither assigned there nor required by a module there", c.ConsumerModule, node)
if !stands {
return fmt.Sprintf("%s is not on %s: neither placed nor assigned there, nor required by a module there", c.ConsumerModule, node)
}
return ""
case "provider":
@@ -1,401 +0,0 @@
package main
// The vault takes what runs (novox/hq issue 1126, cause C4; ADR 0550 §5: a module's own secrets are the vault's).
//
// `move-in` never replaces a value the vault holds (move.go), so its first import of a machine's own secret is fixed.
// Where the controller later made that secret anew (a rotation at start, a re-issue) without handing it here, the new
// value is what runs and what its consumers hold, and the vault keeps the old one. Only the machine the value is sealed
// to can open what runs, so its node-engine hands it in through `move-in` with replace_running: true, in the two steps
// of every intake (intake.go): name the module and the secret and why, and get a call and a key made for it; then send
// the value sealed to that key. It is move-in's, not a verb of its own, so a node-engine asks it on the subject it may
// already publish and no seat promises anything new (the lead, 2026-10-28).
//
// **From the node-engine of the machine the secret is for, about its own machine alone**: the machine is the caller's,
// as the bus proved it (`node.<machine>`), never an argument; a machine named that is not the caller's is refused, and so
// is a name that is not an own secret. **Only a value the vault holds is replaced**, and never a person's (accept) or a
// provider's software's (issued) but for a covered bus account, nor one the vault changed less than RecentlyChanged ago:
// a running value is older than a value the vault just took (a re-issue the machine has not applied yet), and is never
// put back over it. The same value again changes nothing and says so; an empty one is refused.
//
// The value replaced is kept as the record's previous generation (Record.Previous), the generation is raised,
// `secret-changed` and `own-replaced` are said (the secret, the machine, both generations and why; never a value), and the
// act is written in the record of hand-outs (secret_handed). A covered bus account so replaced has its hash written again
// (accounts.go), so the bus-accounts key is of the value the bus runs.
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/delivery"
)
// ReplaceRunningArg is the argument of `move-in` that makes it take a running own secret over the one the vault holds.
const ReplaceRunningArg = "replace_running"
// ReplaceRunning names the act in what the vault says, and is the kind of its open calls.
const ReplaceRunning = "move-in with " + ReplaceRunningArg
// OwnReplacedEvent is what the vault says when it replaced an own secret with what runs: never a value.
const OwnReplacedEvent = "own-replaced"
// RecentlyChanged is how long after the vault changed a secret a running value is not taken over it.
var RecentlyChanged = 15 * time.Minute
// OwnTakeOf names the secret of one `move-in` with replace_running: Module and Name (or Secret whole), Node only to be checked
// against the caller's machine, and Why in the caller's words.
type OwnTakeOf struct {
Node, Module, Name, Secret, Why string
}
// OwnReplaced is what one `move-in` with replace_running did: the secret, the generation it replaced and the one it holds now, the
// fingerprint of the value held now (what the node-engine checks against the value it handed), whether the value was
// held already. Never a value.
type OwnReplaced struct {
Secret string `json:"secret"`
Node string `json:"node"`
Module string `json:"module"`
Name string `json:"name"`
From int `json:"from_generation"`
To int `json:"to_generation"`
Unchanged bool `json:"unchanged,omitempty"`
Fingerprint string `json:"fingerprint"`
Said string `json:"said"`
}
// ownTakeSecret is the secret a node-engine names, and its machine: refused for a caller that is no node-engine, for
// another machine, and for a name that is not an own secret.
func ownTakeSecret(caller string, of OwnTakeOf) (secret, node string, err error) {
node, ok := nodeEngineOf(caller)
if !ok {
if caller == "" || caller == stdio.Unproven {
caller = "an unproven caller"
}
return "", "", fmt.Errorf("%s takes a value from a machine's node-engine alone, about its own machine; %s is "+
"not a node-engine; nothing is taken", ReplaceRunning, caller)
}
if of.Secret != "" {
parts := strings.Split(of.Secret, "/")
if len(parts) != 4 || parts[0] != "own" {
return "", "", fmt.Errorf("%s is not a module's own secret (own/<machine>/<module>/<name>): %s replaces "+
"those alone; nothing is taken", of.Secret, ReplaceRunning)
}
if of.Node != "" && of.Node != parts[1] {
return "", "", fmt.Errorf("%s is not on %s; nothing is taken", of.Secret, of.Node)
}
of.Node, of.Module, of.Name = parts[1], parts[2], parts[3]
}
if of.Node != "" && of.Node != node {
return "", "", fmt.Errorf("%s may hand the vault its own machine's secrets alone, and %s/%s is %s's: nothing "+
"is taken", caller, of.Module, of.Name, of.Node)
}
secret, err = OwnSecret(node, of.Module, of.Name)
if err != nil {
return "", "", fmt.Errorf("%w; nothing is taken", err)
}
return secret, node, nil
}
// ownTakeRefusal says why the held record rec is not replaced by a running value, or "".
func ownTakeRefusal(rec Record, now time.Time) string {
switch {
case rec.Origin == OriginAccepted:
return fmt.Sprintf("%s was given by a person, and a person alone gives it anew (accept); nothing is taken", rec.Name)
case rec.Origin == OriginIssued && !Covered(rec.Name):
return fmt.Sprintf("%s is issued by its provider's software, and `issued` is the only way it enters the vault "+
"(ADR 0305 §10); nothing is taken", rec.Name)
case now.Sub(rec.ChangedAt) < RecentlyChanged:
return fmt.Sprintf("the vault changed %s at %s (generation %d, by %s), less than %s ago: a running value is "+
"taken only over an older one, so a value the vault just took is never put back; nothing is taken",
rec.Name, rec.ChangedAt.Format(time.RFC3339), rec.Generation, rec.ChangedBy, RecentlyChanged)
}
return ""
}
// OwnTakeOpen opens a call to take the running value of one of the caller's machine's own secrets.
func (v *Vault) OwnTakeOpen(caller string, of OwnTakeOf) (Opened, error) {
secret, _, err := ownTakeSecret(caller, of)
if err != nil {
return Opened{}, err
}
why := strings.TrimSpace(of.Why)
if len(why) > 300 || strings.ContainsAny(why, "\r\n\x00") {
return Opened{}, errors.New("why is not one short line; nothing is taken")
}
rec, held, err := v.Store.Read(secret)
if err != nil {
return Opened{}, err
}
refused := v.ownTakeOff()
switch {
case refused != "":
case !held:
refused = fmt.Sprintf("the vault holds no secret named %s, so there is nothing to replace; nothing is taken", secret)
default:
refused = ownTakeRefusal(rec, v.Now())
}
if refused != "" {
_ = v.recordHanding(Handing{To: caller, Name: secret, Generation: rec.Generation, Outcome: "own-take-refused", Why: refused})
return Opened{}, errors.New(refused)
}
id, key, err := v.openCall(ReplaceRunning, secret, caller, nil)
if err != nil {
return Opened{}, err
}
v.callsMu.Lock()
if c := v.pending[id]; c != nil {
c.why = why
}
v.callsMu.Unlock()
return Opened{Call: id, SealTo: key, Secret: secret}, nil
}
// OwnTakeTake opens the value sealed to the call's key and replaces the secret with it, keeping the value it replaces.
func (v *Vault) OwnTakeTake(caller, call, sealed string) (OwnReplaced, error) {
if _, ok := nodeEngineOf(caller); !ok {
return OwnReplaced{}, fmt.Errorf("%s takes a value from a machine's node-engine alone; %q is not one",
ReplaceRunning, caller)
}
c, err := v.takeCall(ReplaceRunning, call)
if err != nil {
return OwnReplaced{}, err
}
if c.by != caller {
return OwnReplaced{}, fmt.Errorf("the %s call %q was opened by another caller; nothing was taken", ReplaceRunning, call)
}
value, err := c.open(sealed)
if err != nil {
return OwnReplaced{}, err
}
defer zero(value)
parts := strings.Split(c.secret, "/")
out := OwnReplaced{Secret: c.secret, Node: parts[1], Module: parts[2], Name: parts[3]}
if strings.TrimSpace(string(value)) == "" {
why := "the value handed is empty; nothing was taken"
_ = v.recordHanding(Handing{To: caller, Name: c.secret, Outcome: "own-take-refused", Why: why})
return OwnReplaced{}, errors.New(why)
}
now := v.Now()
changed, err := v.keepWith(c.secret, string(value), caller, "", "", keepOptions{replaceOnly: true, keepPrevious: true,
refuse: func(before Record) string { return ownTakeRefusal(before, now) }})
if err != nil {
_ = v.recordHanding(Handing{To: caller, Name: c.secret, Outcome: "own-take-refused", Why: err.Error()})
return OwnReplaced{}, err
}
out.Fingerprint = Fingerprint(string(value))
if changed.Unchanged {
out.From, out.To, out.Unchanged = changed.Generation, changed.Generation, true
out.Said = fmt.Sprintf("the vault holds this value of %s already (generation %d): nothing changed", c.secret, changed.Generation)
_ = v.recordHanding(Handing{To: caller, Name: c.secret, Generation: changed.Generation, Outcome: "own-same", Why: c.why})
v.log("%s handed %s's running value, the one the vault holds (generation %d): nothing changed", caller, c.secret,
changed.Generation)
return out, nil
}
out.From, out.To = changed.Generation-1, changed.Generation
out.Said = fmt.Sprintf("%s is now the value that runs on %s, generation %d; generation %d is kept as the previous",
c.secret, out.Node, out.To, out.From)
if err := v.recordHanding(Handing{To: caller, Name: c.secret, Generation: out.To, Outcome: "own-replaced", Why: c.why}); err != nil {
out.Said += "; the record of hand-outs could not be written: " + err.Error()
}
v.log("replaced %s (generation %d → %d) with the value that runs, handed by %s: %s", c.secret, out.From, out.To,
caller, someoneOr(c.why, "no reason given"))
if v.Emit != nil {
body := map[string]any{"secret": c.secret, "node": out.Node, "module": out.Module, "name": out.Name,
"from_generation": out.From, "to_generation": out.To, "by": caller, "why": c.why,
"at": changed.At.Format(time.RFC3339Nano)}
if err := v.Emit(OwnReplacedEvent, body); err != nil {
v.log("%s is replaced at generation %d, but %s could not be said: %v", c.secret, out.To, OwnReplacedEvent, err)
}
}
return out, nil
}
// ---- own_drift ----------------------------------------------------------------------------------------------
// DriftRow is one own secret a node's latest shadow answer says the vault holds another value of than runs there.
type DriftRow struct {
Secret string `json:"secret"`
Node string `json:"node"`
Module string `json:"module"`
Name string `json:"name"`
Groups []string `json:"groups"`
Held bool `json:"held"`
Generation int `json:"generation,omitempty"`
Changed time.Time `json:"changed,omitzero"`
ChangedBy string `json:"changed_by,omitempty"`
Origin string `json:"origin,omitempty"`
Previous int `json:"previous_generation,omitempty"`
// Takeable says move-in with replace_running would take the running value now; Refused why not.
Takeable bool `json:"takeable"`
Refused string `json:"refused,omitempty"`
}
// DriftNode is one node's answers as read: whose compositions it applies, and per group how many values differ.
type DriftNode struct {
Node string `json:"node"`
Composes string `json:"composes,omitempty"`
ValuesDiffer map[string]int `json:"values_differ,omitempty"`
Unread string `json:"unread,omitempty"`
}
// Drift is own_drift's answer.
type Drift struct {
Switch OwnTakeSwitch `json:"switch"`
Secrets []DriftRow `json:"secrets"`
Nodes []DriftNode `json:"nodes"`
Note string `json:"note"`
}
// OwnDrift reads every node's own have key (`<node>.node`) and lists, from its latest answers to the placement
// candidates, every own secret whose shown bodies say another value (delivery.OwnValuesDiffer), with what the vault holds
// of it and whether move-in with replace_running would take the running value now.
func (v *Vault) OwnDrift() (Drift, error) {
if v.Haves == nil || v.HaveKeys == nil {
return Drift{}, errors.New("the vault reads no node's have, so it cannot say what drifted")
}
keys, err := v.HaveKeys()
if err != nil {
return Drift{}, fmt.Errorf("the keys of %s could not be listed: %w", HaveRead, err)
}
sort.Strings(keys)
rows := map[string]*DriftRow{}
out := Drift{Secrets: []DriftRow{}, Nodes: []DriftNode{},
Note: "from each node's latest shadow answers; a value is never shown: move-in with replace_running from that node replaces it"}
for _, key := range keys {
node, isNode := strings.CutSuffix(key, "."+delivery.HaveNodeWord)
if !isNode || !namePart.MatchString(node) {
continue
}
dn := DriftNode{Node: node}
raw, err := v.Haves(key)
if err != nil || raw == nil {
dn.Unread = fmt.Sprintf("its have could not be read: %v", err)
out.Nodes = append(out.Nodes, dn)
continue
}
have, err := delivery.DecodeHaveNode(raw)
if err != nil {
dn.Unread = err.Error()
out.Nodes = append(out.Nodes, dn)
continue
}
dn.Composes = have.Composes
for group, a := range have.Candidates {
if n := delivery.ValuesDiffer(a); n > 0 {
if dn.ValuesDiffer == nil {
dn.ValuesDiffer = map[string]int{}
}
dn.ValuesDiffer[group] = n
}
for _, o := range delivery.OwnValuesDiffer(a) {
secret, err := OwnSecret(node, o.Module, o.Name)
if err != nil {
continue
}
r := rows[secret]
if r == nil {
r = &DriftRow{Secret: secret, Node: node, Module: o.Module, Name: o.Name}
rows[secret] = r
}
r.Groups = append(r.Groups, group)
}
}
out.Nodes = append(out.Nodes, dn)
}
names := make([]string, 0, len(rows))
for n := range rows {
names = append(names, n)
}
sort.Strings(names)
if out.Switch, err = v.Store.OwnTakeSwitch(); err != nil {
return Drift{}, err
}
off := v.ownTakeOff()
for _, n := range names {
r := rows[n]
sort.Strings(r.Groups)
rec, held, err := v.Store.Read(n)
switch {
case err != nil:
r.Refused = err.Error()
case !held:
r.Refused = "the vault holds no secret named " + n
default:
r.Held, r.Generation, r.Changed, r.ChangedBy, r.Origin = true, rec.Generation, rec.ChangedAt, rec.ChangedBy, rec.Origin
if rec.Previous != nil {
r.Previous = rec.Previous.Generation
}
r.Refused = ownTakeRefusal(rec, v.Now())
if off != "" {
r.Refused = off
}
r.Takeable = r.Refused == ""
}
out.Secrets = append(out.Secrets, *r)
}
return out, nil
}
// ---- own_take_switch ----------------------------------------------------------------------------------------
// OwnTakeSwitch is whether move-in with replace_running takes values, who switched it last, when and why. On until a person
// switches it off; kept in the vault's own store, so it holds over a restart.
type OwnTakeSwitch struct {
On bool `json:"on"`
By string `json:"by,omitempty"`
At time.Time `json:"at,omitzero"`
Why string `json:"why,omitempty"`
}
func (s *Store) ownTakeSwitchPath() string { return filepath.Join(s.dir, "replace-running.json") }
// OwnTakeSwitch is the switch as kept: on when nothing was ever switched.
func (s *Store) OwnTakeSwitch() (OwnTakeSwitch, error) {
raw, err := os.ReadFile(s.ownTakeSwitchPath())
if errors.Is(err, os.ErrNotExist) {
return OwnTakeSwitch{On: true}, nil
}
if err != nil {
return OwnTakeSwitch{}, err
}
var sw OwnTakeSwitch
if err := json.Unmarshal(raw, &sw); err != nil {
return OwnTakeSwitch{}, fmt.Errorf("the switch of %s is not readable: %w", ReplaceRunning, err)
}
return sw, nil
}
// SwitchOwnTake switches move-in with replace_running on or off, a person's act with why; the caller is recorded as the bus
// proved it.
func (v *Vault) SwitchOwnTake(caller string, on bool, why string) (OwnTakeSwitch, error) {
why = strings.TrimSpace(why)
if why == "" || len(why) > 300 || strings.ContainsAny(why, "\r\n\x00") {
return OwnTakeSwitch{}, errors.New("say why in one short line; nothing was switched")
}
sw := OwnTakeSwitch{On: on, By: someoneOr(caller, stdio.Unproven), At: v.Now().UTC(), Why: why}
raw, _ := json.MarshalIndent(sw, "", " ")
if err := writeWhole(v.Store.ownTakeSwitchPath(), append(raw, '\n')); err != nil {
return OwnTakeSwitch{}, err
}
v.log("%s is switched %s by %s: %s", ReplaceRunning, map[bool]string{true: "on", false: "off"}[on], sw.By, why)
return sw, nil
}
// ownTakeOff says why move-in with replace_running takes nothing now, or "".
func (v *Vault) ownTakeOff() string {
sw, err := v.Store.OwnTakeSwitch()
if err != nil {
return err.Error() + "; nothing is taken"
}
if !sw.On {
return fmt.Sprintf("%s is switched off (by %s at %s: %s); nothing is taken", ReplaceRunning, sw.By,
sw.At.Format(time.RFC3339), sw.Why)
}
return ""
}
+134
View File
@@ -0,0 +1,134 @@
package main
// Where modules stand, from the catalogue's placement (novox/hq ADR 0549 §3, §5; ADR 0561; issue 774). The controller's
// assignments mirror goes with its lease, so the vault reads which module stands on which node from the indexer's
// placement first, and the assignments beside it while both stand: a module either names stands. The provisioner's plan,
// which only an assignment's value carries, is read from the assignments still: its home after the lease is a subtask of
// its own (issue 774).
import (
"errors"
"fmt"
"slices"
"sort"
"strings"
"git.novox.be/novox/mesh-sdk/go/delivery"
)
// PlacementRead is the indexer's placement, as the vault's manifest reads it.
const PlacementRead = delivery.IndexerModule + "." + delivery.PlacementState
// PlacementReader reads the indexer's placement: every key, and one key's value (nil when there is none).
type PlacementReader struct {
Keys func() ([]string, error)
Read func(key string) ([]byte, error)
}
// placements is every node's placement, by node; none when the vault reads no placement.
func (v *Vault) placements() (map[string]delivery.Placement, error) {
out := map[string]delivery.Placement{}
if v.Placement.Keys == nil || v.Placement.Read == nil {
return out, nil
}
keys, err := v.Placement.Keys()
if err != nil {
return nil, fmt.Errorf("the placement's keys could not be read: %w", err)
}
for _, k := range keys {
node, err := delivery.ParsePlacementKey(k)
if err != nil {
continue
}
raw, err := v.Placement.Read(k)
if err != nil {
return nil, fmt.Errorf("the placement of %s could not be read: %w", node, err)
}
if raw == nil {
continue
}
p, err := delivery.DecodePlacement(raw)
if err != nil || p.Node != node {
continue
}
out[node] = p
}
return out, nil
}
// placedOn says module is placed on node by the catalogue.
func (v *Vault) placedOn(node, module string) (bool, error) {
if v.Placement.Read == nil {
return false, nil
}
key, err := delivery.PlacementKey(node)
if err != nil {
return false, err
}
raw, err := v.Placement.Read(key)
if err != nil || raw == nil {
return false, err
}
p, err := delivery.DecodePlacement(raw)
if err != nil {
return false, fmt.Errorf("the placement of %s is not readable: %w", node, err)
}
return slices.Contains(p.Assigned(), module), nil
}
// standsOn says module stands on node: placed there, or assigned there while the assignments stand. A read that fails is
// an error, never "not there".
func (v *Vault) standsOn(node, module string) (bool, error) {
placed, err := v.placedOn(node, module)
if err != nil || placed {
return placed, err
}
d, ok := v.Askers.(Declared)
if !ok || d.Read == nil {
if v.Placement.Read == nil {
return false, errors.New("the vault reads neither the placement nor the assignments")
}
return false, nil
}
raw, err := standing(d.Read)(node + "." + module)
return raw != nil, err
}
// busNode is the node running the bus's module: from the placement, and from the assignments while no placement names
// one. The vault adopts from one node alone.
func (v *Vault) busNode() (string, error) {
placed, err := v.placements()
if err != nil {
return "", err
}
var nodes []string
for node, p := range placed {
if slices.Contains(p.Assigned(), BusModule) {
nodes = append(nodes, node)
}
}
from := "placed"
if len(nodes) == 0 && v.Assignments.Keys != nil {
from = "assigned"
keys, err := v.Assignments.Keys()
if err != nil {
return "", fmt.Errorf("the assignments' keys could not be read: %w", err)
}
for _, k := range keys {
if node, module, ok := strings.Cut(k, "."); ok && module == BusModule {
nodes = append(nodes, node)
}
}
} else if len(nodes) == 0 && len(placed) == 0 {
return "", errors.New("the vault reads neither the placement nor the assignments, so it cannot tell which node holds the bus")
}
sort.Strings(nodes)
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return "", fmt.Errorf("no node is %s the bus module %s", from, BusModule)
}
return "", fmt.Errorf("%d nodes are %s the bus module %s (%s): the vault adopts from one alone", len(nodes), from,
BusModule, strings.Join(nodes, ", "))
}
@@ -0,0 +1,66 @@
package main
import (
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/delivery"
)
// placementsOf is the indexer's placement of each node, as the vault reads it.
func placementsOf(t *testing.T, nodes map[string][]string) PlacementReader {
t.Helper()
values := map[string][]byte{}
for node, modules := range nodes {
p := delivery.Placement{V: delivery.Version, Node: node}
for _, m := range modules {
p.Modules = append(p.Modules, delivery.PlacedModule{Module: m})
}
raw, err := delivery.EncodePlacement(p)
if err != nil {
t.Fatal(err)
}
key, _ := delivery.PlacementKey(node)
values[key] = raw
}
return PlacementReader{
Keys: func() ([]string, error) {
var out []string
for k := range values {
out = append(out, k)
}
return out, nil
},
Read: func(key string) ([]byte, error) { return values[key], nil },
}
}
// 774/AC11 (novox/hq ADR 0561, ADR 0549 §3, §5): with no assignments to read, the vault tells from the catalogue's
// placement which node holds the bus and whether a consumer's module stands on its node; while both stand, a module
// either names stands.
func TestTheVaultReadsWhereModulesStandFromPlacement(t *testing.T) {
v := newVault(t, nil)
v.Placement = placementsOf(t, map[string][]string{"novox": {"nats", "web"}, "ace": {"shop"}})
if node, err := v.busNode(); err != nil || node != "novox" {
t.Errorf("the bus node from placement: %q, %v", node, err)
}
asked := func(node, module string) CredentialAsked {
return CredentialAsked{Role: "consumer", Provision: "postgres", Consumer: node, ConsumerModule: module, Provider: "novox"}
}
if why := v.credentialRefusal("ace", asked("ace", "shop")); why != "" {
t.Errorf("shop stands on ace by placement, refused: %s", why)
}
if why := v.credentialRefusal("ace", asked("ace", "web")); !strings.Contains(why, "is not on ace") {
t.Errorf("web is not placed on ace, and is answered %q", why)
}
// While both stand, an assignment still names a module placement does not yet.
v.Askers = Declared{Read: assignments{"ace.web": `{"node":"ace","module":"web"}`}.read, Store: v.Store}
if why := v.credentialRefusal("ace", asked("ace", "web")); why != "" {
t.Errorf("web assigned on ace, refused: %s", why)
}
// Two nodes placed with the bus: the vault adopts from neither.
v.Placement = placementsOf(t, map[string][]string{"novox": {"nats"}, "ace": {"nats"}})
if _, err := v.busNode(); err == nil || !strings.Contains(err.Error(), "2 nodes") {
t.Errorf("two bus nodes: %v", err)
}
}
+264
View File
@@ -0,0 +1,264 @@
package main
// A wanted account no longer wanted is retired within ADR 0230's bounds (novox/hq ADR 0561 §2, issue 774).
//
// The grants part deletes a wanted account's key when no input names its user any more. The vault then retires the
// account: it takes its hash out of `bus-accounts`, so the grants part's next list drops the user, and marks the value
// retired in its store, keeping it (a value is deleted only by a person, ADR 0230). As ADR 0230 §15 and §18 have it, the
// same set of accounts gone must stand for five passes and ten minutes first, and a set of more than three, or more than
// half of the accounts held, waits for a person, who retires them with `account_retire`. Wanted again, an account is
// re-enabled at once: the mark taken off and its hash written again. Nothing is retired while the controller holds the
// lease (it forgets the accounts it mints), or before the wanted accounts are read whole.
import (
"errors"
"fmt"
"sort"
"strings"
"time"
)
// retiring is what the passes keep of the accounts no longer wanted, under minting.mu.
type retiring struct {
wantsRead bool
key string
passes int
first time.Time
waiting []string
why string
retired []string
}
// RetireState is what vault_status says of retirement.
type RetireState struct {
Gone []string `json:"gone"`
Passes int `json:"passes"`
Since time.Time `json:"since,omitzero"`
Waiting []string `json:"waiting_for_a_person"`
Why string `json:"why"`
Retired []string `json:"retired"`
}
// RetireState answers how retirement stands.
func (v *Vault) RetireState() RetireState {
m := &v.minting
m.mu.Lock()
defer m.mu.Unlock()
r := m.retiring
out := RetireState{Passes: r.passes, Since: r.first, Why: r.why, Waiting: append([]string{}, r.waiting...),
Retired: append([]string{}, r.retired...), Gone: []string{}}
if r.key != "" {
out.Gone = strings.Split(r.key, " ")
}
return out
}
// WantsRead says the wanted accounts were read whole once (the watch handed every current key): only then is an account
// with no key known to be no longer wanted.
func (v *Vault) WantsRead() {
v.minting.mu.Lock()
defer v.minting.mu.Unlock()
v.minting.retiring.wantsRead = true
}
// wantGone is a wanted account's key deleted: forgotten as wanted, its retirement left to the passes.
func (v *Vault) wantGone(user string) {
v.minting.mu.Lock()
defer v.minting.mu.Unlock()
delete(v.minting.wants, user)
delete(v.minting.heldBack, user)
}
// wantBack is a wanted account's key written: a retired account of it is re-enabled at once.
func (v *Vault) wantBack(user string) {
w, ok := v.wanted(user)
if !ok {
return
}
secret, err := AccountSecret(w)
if err != nil {
return
}
rec, held, err := v.Store.Read(secret)
if err != nil || !held || rec.Retired == nil {
return
}
rec.Retired = nil
if err := v.Store.Write(rec); err != nil {
v.log("%s is wanted again and NOT RE-ENABLED: its mark could not be taken off: %v", user, err)
return
}
if _, err := v.HashAccount(secret, true); err != nil {
v.hashes.owe(secret, err.Error())
v.log("%s is wanted again and its hash is not written yet, written at the next pass: %v", user, err)
}
v.minting.mu.Lock()
r := &v.minting.retiring
for i, u := range r.retired {
if u == user {
r.retired = append(r.retired[:i], r.retired[i+1:]...)
break
}
}
v.minting.mu.Unlock()
v.log("%s is wanted again: re-enabled, its hash written again", user)
}
// goneAccounts are the users whose hash the vault wrote from a value it holds and that no wanted key names, sorted, and
// how many such hashes it holds in all.
func (v *Vault) goneAccounts() ([]string, int, error) {
users, err := v.Accounts.Users()
if err != nil {
return nil, 0, err
}
var gone []string
held := 0
for _, u := range users {
a, err := v.Accounts.Get(u)
if err != nil {
return nil, 0, err
}
if a == nil || a.Adopted || a.Of == "" {
continue
}
held++
if _, wanted := v.wanted(u); !wanted {
gone = append(gone, u)
}
}
sort.Strings(gone)
return gone, held, nil
}
// RetirePass is one pass of retirement, at the vault's minute pass.
func (v *Vault) RetirePass() {
if v.Accounts == nil {
return
}
v.leaseAfresh()
on, leaseWhy := v.mintingOn()
m := &v.minting
m.mu.Lock()
read := m.retiring.wantsRead
m.mu.Unlock()
reset := func(why string) {
m.mu.Lock()
defer m.mu.Unlock()
m.retiring.key, m.retiring.passes, m.retiring.first, m.retiring.waiting, m.retiring.why = "", 0, time.Time{}, nil, why
}
switch {
case !read:
reset("the wanted accounts are not read whole yet, so none is known to be gone")
return
case !on:
reset("nothing is retired: " + leaseWhy)
return
}
gone, held, err := v.goneAccounts()
if err != nil {
reset("the accounts held could not be read: " + err.Error())
return
}
if len(gone) == 0 {
reset("")
return
}
now := v.Now().UTC()
key := strings.Join(gone, " ")
m.mu.Lock()
r := &m.retiring
if r.key != key {
r.key, r.passes, r.first, r.waiting = key, 0, now, nil
}
r.passes++
passes, since := r.passes, r.first
m.mu.Unlock()
setWhy := func(why string, waiting []string) {
m.mu.Lock()
defer m.mu.Unlock()
m.retiring.why, m.retiring.waiting = why, waiting
}
if passes < StablePasses || now.Sub(since) < StableFor {
setWhy(fmt.Sprintf("%d no longer wanted (%s): retired once the same set stands for %d passes and %s (ADR 0230)",
len(gone), key, StablePasses, StableFor), nil)
return
}
if len(gone) > RetireAtOnce || float64(len(gone)) > RetireFraction*float64(held) {
why := fmt.Sprintf("%d accounts are no longer wanted, more than %d or more than half of the %d held at once: they "+
"wait for a person (account_retire), ADR 0230 §18", len(gone), RetireAtOnce, held)
setWhy(why, gone)
v.log("%s: %s", why, key)
return
}
for _, u := range gone {
if err := v.retireOne(u, "no longer wanted by the grants part", "the vault's pass"); err != nil {
v.log("%s is not retired: %v", u, err)
}
}
reset("")
}
// retireOne marks the value of user's account retired and takes its hash out of bus-accounts.
func (v *Vault) retireOne(user, why, by string) error {
a, err := v.Accounts.Get(user)
if err != nil {
return err
}
if a == nil || a.Adopted || a.Of == "" {
return fmt.Errorf("the vault holds no account of %s it made or was handed: an adopted hash is never retired here", user)
}
rec, held, err := v.Store.Read(a.Of)
if err != nil {
return err
}
if held {
rec.Retired = &RetiredMark{At: v.Now().UTC().Format(time.RFC3339), Why: why + ", by " + by}
if err := v.Store.Write(rec); err != nil {
return fmt.Errorf("its value could not be marked retired: %w", err)
}
}
if err := v.Accounts.Delete(user); err != nil {
return fmt.Errorf("its hash could not be taken out of %s: %w", BusAccountsState, err)
}
v.minting.mu.Lock()
v.minting.retiring.retired = append(v.minting.retiring.retired, user)
v.minting.mu.Unlock()
v.log("retired the bus account %s (%s): its hash is out of %s and its value kept, marked; %s", user, a.Of,
BusAccountsState, why)
return nil
}
// RetireAccounts is the tool account_retire: a person retires accounts no longer wanted, past ADR 0230's bound, with why.
func (v *Vault) RetireAccounts(caller string, users []string, why string) (any, error) {
if strings.TrimSpace(why) == "" {
return nil, errors.New("account_retire says why (`why`)")
}
if len(users) == 0 {
return nil, errors.New("account_retire names the accounts (`users`), as vault_status lists them waiting")
}
// As the passes: never while the controller holds the lease (it forgets the accounts it mints), nor before the wanted
// accounts are read whole (an account not read yet is not known to be gone).
v.leaseAfresh()
if on, why := v.mintingOn(); !on {
return nil, fmt.Errorf("nothing was retired: %s", why)
}
v.minting.mu.Lock()
read := v.minting.retiring.wantsRead
v.minting.mu.Unlock()
if !read {
return nil, errors.New("nothing was retired: the wanted accounts are not read whole yet, so none is known to be gone")
}
for _, u := range users {
if _, wanted := v.wanted(u); wanted {
return nil, fmt.Errorf("%s is still wanted by the grants part: only an account no longer wanted is retired; nothing was retired", u)
}
}
var done []string
for _, u := range users {
if err := v.retireOne(u, strings.TrimSpace(why), someoneOr("", caller)); err != nil {
return map[string]any{"retired": done}, fmt.Errorf("%s: %w", u, err)
}
done = append(done, u)
}
return map[string]any{"retired": done}, nil
}
@@ -0,0 +1,89 @@
package main
import (
"strings"
"testing"
"time"
)
// 774/AC9 (novox/hq ADR 0561 §2, ADR 0230 §15, §18): a wanted account whose key is deleted is retired (its hash taken
// out of bus-accounts, its value kept, marked) only once the same set has stood for five passes and ten minutes, and never
// more than three, or more than half of those held, at once: past that it waits for a person (account_retire). Wanted
// again, it is re-enabled at once; and a retired account is not hashed again at a start.
func TestAWantGoneRetiresItsAccountOnlyWithinTheBounds(t *testing.T) {
v, accounts, _ := mintingVault(t, true)
clock := time.Date(2026, 10, 28, 9, 0, 0, 0, time.UTC)
v.Now = func() time.Time { return clock }
modules := []string{"m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8"}
for _, m := range modules {
w := aWant(m)
v.WantHeard(w.User, wantRaw(t, w), false)
}
v.WantsRead()
if len(accounts.keys) != 8 {
t.Fatalf("minted %d", len(accounts.keys))
}
pass := func(n int, every time.Duration) {
for i := 0; i < n; i++ {
clock = clock.Add(every)
v.RetirePass()
}
}
v.WantHeard("ace.m1", nil, true)
pass(5, time.Second)
if _, ok := accounts.keys["ace.m1"]; !ok {
t.Fatal("retired after five passes in five seconds: ADR 0230 waits ten minutes too")
}
pass(1, 10*time.Minute)
if _, ok := accounts.keys["ace.m1"]; ok {
t.Fatalf("not retired after five passes and ten minutes: %+v", v.RetireState())
}
if rec, held, _ := v.Store.Read("own/ace/m1/broker"); !held || rec.Retired == nil {
t.Fatalf("the retired account's value is %+v (held %v): kept, and marked", rec, held)
}
if written, _ := v.HashHeld(); len(written) != 0 {
t.Errorf("a start hashed a retired account again: %+v", written)
}
// Wanted again: re-enabled at once.
w := aWant("m1")
v.WantHeard(w.User, wantRaw(t, w), false)
if rec, _, _ := v.Store.Read("own/ace/m1/broker"); rec.Retired != nil || accounts.keys["ace.m1"].Hash == "" {
t.Fatalf("wanted again, ace.m1 is %+v with hash %v", rec.Retired, accounts.keys["ace.m1"])
}
// Four gone at once is over the bound: it waits for a person, who retires them by hand.
for _, m := range modules[4:] {
v.WantHeard("ace."+m, nil, true)
}
pass(6, 3*time.Minute)
st := v.RetireState()
if len(accounts.keys) != 8 || len(st.Waiting) != 4 || !strings.Contains(st.Why, "more than 3") {
t.Fatalf("over the bound: %d keys, %+v", len(accounts.keys), st)
}
if _, err := v.RetireAccounts("person.jochen", []string{"ace.m5"}, ""); err == nil {
t.Error("retired by hand with no why")
}
if _, err := v.RetireAccounts("person.jochen", []string{"ace.m2"}, "test"); err == nil {
t.Error("retired by hand an account still wanted")
}
// Never while the controller holds the lease, nor before the wants are read whole.
held := v.LeaseRead
v.LeaseRead = func() ([]byte, bool, error) { return []byte(`{"instance":"novox/1","epoch":57}`), true, nil }
if _, err := v.RetireAccounts("person.jochen", []string{"ace.m5"}, "the modules left"); err == nil || !strings.Contains(err.Error(), "controller holds the lease") {
t.Errorf("retired by hand under the controller's lease: %v", err)
}
v.LeaseRead = held
v.LeaseHeard([]byte(`{"handed-to":"the operator's hand-over"}`), true, nil)
v.minting.mu.Lock()
v.minting.retiring.wantsRead = false
v.minting.mu.Unlock()
if _, err := v.RetireAccounts("person.jochen", []string{"ace.m5"}, "the modules left"); err == nil || !strings.Contains(err.Error(), "not read whole") {
t.Errorf("retired by hand before the wants were read: %v", err)
}
v.WantsRead()
if _, err := v.RetireAccounts("person.jochen", []string{"ace.m5", "ace.m6"}, "the modules left"); err != nil {
t.Fatal(err)
}
if _, ok := accounts.keys["ace.m5"]; ok || len(accounts.keys) != 6 {
t.Errorf("after a person's retirement %d keys remain", len(accounts.keys))
}
}
@@ -0,0 +1,94 @@
package main
// The record of a bus account's rotation, and its one rule (novox/hq ADR 0561 §4; issue 774, the lead's decision of
// 2026-10-27). A module's, a process's or a provisioner client's account rotates over two credentials (ADR 0114 §10):
// a second login, `<user>--b`, carrying the first login's permissions verbatim, which the bus composer composes only while
// the account's key in `bus-accounts` names it in `rotating`. The vault starts at most one rotation per revision of the
// user list the bus loaded. What composes and delivers the second login is a subtask of its own, before the lease write;
// until it is built nothing begins a rotation, and `rotate` of a covered account stays refused, so nothing rotates in
// place.
import (
"fmt"
"strings"
"time"
)
// SecondLoginSuffix makes an account's second login: reserved, so no module or process may be named to end in it.
const SecondLoginSuffix = "--b"
// Rotating is a rotation under way, as the account's key in bus-accounts says it: the second login, the generation of
// the value it carries, since when, and the revision of the loaded user list it began at.
type Rotating struct {
Login string `json:"login"`
Generation int `json:"generation"`
Since time.Time `json:"since"`
Revision uint64 `json:"revision"`
}
// LoadedListHeard keeps the revision of the user list the bus node says it loaded (its have of the bus module).
func (v *Vault) LoadedListHeard(revision uint64) {
v.minting.mu.Lock()
defer v.minting.mu.Unlock()
if revision > v.minting.loadedRevision {
v.minting.loadedRevision = revision
}
}
// BeginRotation records a rotation of user's account at the loaded list's revision, under the one rule: none for a
// node's account or the controller's, none while minting is off, none of an account the vault did not make or was not
// handed, none twice for one account, and none when another began at this revision.
func (v *Vault) BeginRotation(user string) (Rotating, error) {
if nodeOrController(user) {
return Rotating{}, fmt.Errorf("%s does not rotate here: a node's account and the controller's keep the hash they have (ADR 0561 §4)", user)
}
if on, why := v.mintingOn(); !on {
return Rotating{}, fmt.Errorf("no rotation begins: %s", why)
}
v.minting.mu.Lock()
revision := v.minting.loadedRevision
v.minting.mu.Unlock()
if revision == 0 {
return Rotating{}, fmt.Errorf("no rotation begins: the revision of the user list the bus loaded is not known yet")
}
users, err := v.Accounts.Users()
if err != nil {
return Rotating{}, err
}
var mine *AccountHash
began := ""
for _, u := range users {
a, err := v.Accounts.Get(u)
if err != nil {
return Rotating{}, err
}
if a == nil {
continue
}
if a.Rotating != nil && a.Rotating.Revision == revision {
began = u
}
if u == user {
mine = a
}
}
switch {
case mine == nil || mine.Adopted || mine.Of == "":
return Rotating{}, fmt.Errorf("the vault holds no account of %s it made or was handed, so it rotates none", user)
case mine.Rotating != nil:
return Rotating{}, fmt.Errorf("%s is rotating already, since %s (second login %s)", user, mine.Rotating.Since.Format(time.RFC3339), mine.Rotating.Login)
case strings.HasSuffix(user, SecondLoginSuffix):
return Rotating{}, fmt.Errorf("%s is a second login, which never rotates of its own", user)
case began != "":
return Rotating{}, fmt.Errorf("no rotation of %s begins: %s's began at the loaded list's revision %d, and one "+
"rotation begins per revision (ADR 0561 §4)", user, began, revision)
}
r := Rotating{Login: user + SecondLoginSuffix, Generation: mine.Generation + 1, Since: v.Now().UTC(), Revision: revision}
next := *mine
next.Rotating = &r
if err := v.Accounts.Put(next); err != nil {
return Rotating{}, err
}
v.log("a rotation of %s begins at the loaded list's revision %d: second login %s", user, revision, r.Login)
return r, nil
}
+2 -14
View File
@@ -48,20 +48,8 @@ type Record struct {
// MovedFrom is, for a value the move took from the controller's store (design 57's V3), the node-engine that
// handed it in and the controller's generation for it, kept as it was.
MovedFrom *MovedFrom `json:"moved-from,omitempty"`
// Previous is the value this one replaced when a machine's node-engine handed the vault what runs there
// (move-in with replace_running, owntake.go): kept sealed as it was, so the replacement can be read and undone. Any later
// change of the secret drops it.
Previous *PreviousValue `json:"previous,omitempty"`
}
// PreviousValue is a replaced value as the store kept it: its generation, both its seals, and who changed it when.
type PreviousValue struct {
Generation int `json:"generation"`
AtRest seal.Box `json:"at-rest"`
Operator OperatorCopy `json:"operator"`
ChangedAt time.Time `json:"changed-at"`
ChangedBy string `json:"changed-by"`
Origin string `json:"origin,omitempty"`
// Retired marks a bus account no longer wanted (retire.go, ADR 0561 §2): its value kept, its hash taken out.
Retired *RetiredMark `json:"retired,omitempty"`
}
// OperatorCopy is a value sealed to the operator key named in Key.
+41 -69
View File
@@ -195,53 +195,13 @@ func definitions(env *Env) []toolDef {
}
return v.RotateFor(caller, secret, one, arg(a, "by"), arg(a, "why"))
}},
{Name: "own_take_switch",
Description: "Switch move-in's replace_running on or off for every machine, a person's act with why (on until " +
"switched off; kept over a restart). While off, every machine's ask is refused, saying who switched it " +
"off and why. own_drift shows the switch.",
Input: map[string]any{"type": "object", "required": []string{"on", "why"}, "properties": map[string]any{
"on": map[string]any{"type": "boolean", "description": "true takes running values, false takes none"},
"why": str("why, in one line")}},
run: func(caller string, a map[string]any) (any, error) {
v, err := env.ready()
if err != nil {
return nil, err
}
on, ok := a["on"].(bool)
if !ok {
return nil, errors.New("say on: true or false; nothing was switched")
}
return v.SwitchOwnTake(caller, on, arg(a, "why"))
}},
{Name: "own_drift",
Description: "Every own secret whose node's latest shadow answer says the vault holds another value than runs " +
"there (the masked word \"another value\", issue 1126), for all nodes in one call: the secret, the " +
"groups that show it, the vault's generation, origin and previous generation, and whether the node's " +
"move-in with replace_running would take the running value now (or why not); and per node whose compositions it " +
"applies and how many values differ per group. Never a value.",
Input: map[string]any{"type": "object", "properties": map[string]any{}},
run: func(_ string, _ map[string]any) (any, error) {
v, err := env.ready()
if err != nil {
return nil, err
}
return v.OwnDrift()
}},
{Name: Seat + ".move-in",
Description: "Take one value of the controller's store into the vault, as it is (design 57's V3): from the " +
"node-engine of a machine it was sealed to, and no other caller, in two steps — name the row (node, " +
"module and name for a module's own; provider, provision, consumer, consumer_module and local for a " +
"pair credential), its origin and the controller's generation, and get a call and a key made for it; " +
"then send the call, the value sealed to that key and read_back_to, a key of your own. Never replaces " +
"a value the vault holds; answers what it kept, read back from its store sealed to read_back_to. " +
"With replace_running: true it does the one thing it otherwise never does (issue 1126, cause C4): it " +
"replaces one own secret of the asking machine (the machine as the bus proved the caller) with the " +
"value that runs there; first step module, name and why, second step call and sealed. It keeps the " +
"old value as the previous generation, raises the generation and says own-replaced, never the value; " +
"answers both generations and the fingerprint of what it holds. Refused: another machine's secret, " +
"one that is not an own secret or not held, an empty value, a person's value, a provider's but a " +
"covered bus account, a value the vault changed in the last 15 minutes, and everything while " +
"own_take_switch is off. The same value is a no-op.",
"a value the vault holds; answers what it kept, read back from its store sealed to read_back_to.",
Input: intakeInput(map[string]string{"node": "a module's own secret: its machine", "module": "its module",
"name": "its name in the module", "provider": "a pair credential: the provider's machine",
"provision": "the provision", "consumer": "the consumer's machine",
@@ -250,10 +210,6 @@ func definitions(env *Env) []toolDef {
"generation": "the controller's generation for the value, kept as it is",
"made_at": "when the controller made or took it (RFC 3339)",
"read_back_to": "the second step: a raw X25519 public key in base64 the read-back is sealed to",
ReplaceRunningArg: "true to replace an own secret of this machine with the value that runs here " +
"(the second step is known by its call)",
"secret": "with replace_running, or the secret's whole name, own/<machine>/<module>/<name>",
"why": "with replace_running: why the value is handed, in words",
"sealing_key": "the first step, optional: this machine's sealing key, a raw X25519 public key in " +
"base64, which the core's credentials are sealed to from then on (ADR 0349 §16)"}),
run: func(caller string, a map[string]any) (any, error) {
@@ -261,17 +217,9 @@ func definitions(env *Env) []toolDef {
if err != nil {
return nil, err
}
replace := isTrue(a[ReplaceRunningArg])
if call := arg(a, "call"); call != "" {
if replace || v.callKind(call) == ReplaceRunning {
return v.OwnTakeTake(caller, call, arg(a, "sealed"))
}
return v.MoveTake(caller, call, arg(a, "sealed"), arg(a, "read_back_to"))
}
if replace {
return v.OwnTakeOpen(caller, OwnTakeOf{Node: arg(a, "node"), Module: arg(a, "module"),
Name: arg(a, "name"), Secret: arg(a, "secret"), Why: arg(a, "why")})
}
m := MoveOf{Node: arg(a, "node"), Module: arg(a, "module"), Name: arg(a, "name"),
Provider: arg(a, "provider"), Provision: arg(a, "provision"), Consumer: arg(a, "consumer"),
ConsumerModule: arg(a, "consumer_module"), Local: arg(a, "local"), Origin: arg(a, "origin"),
@@ -303,6 +251,20 @@ func definitions(env *Env) []toolDef {
// clause 9, adopt.go): a public half, never the private one.
return map[string]any{"recorded": true, "vault_key": v.Own.PublicKey}, nil
}},
{Name: Seat + ".issue-account",
Description: "Mint one bus account the grants part wants, now (novox/hq ADR 0561 §9): the recovery when the vault did not " +
"hear a want. Reads the wanted key afresh from mesh-grants.accounts and mints it as a want would: only while " +
"the controller's lease is handed away, never for a node's account or the controller's, never a user nobody " +
"wants, and never anew for one whose value the vault holds or whose hash it adopted (it says so). Answers " +
"whether it minted, the secret and generation, never the value or the hash.",
Input: map[string]any{"user": str("the bus user, e.g. ace.mesh-build-go")},
run: func(caller string, a map[string]any) (any, error) {
v, err := env.ready()
if err != nil {
return nil, err
}
return v.IssueAccount(caller, arg(a, "user"))
}},
{Name: Seat + ".own",
Description: "The own secrets of this machine's modules, each sealed to the machine's sealing key (novox/hq ADR 0547 §2, " +
"ADR 0550 §5, issue 1126): from the node-engine of the machine alone, about its own machine (the bus proves which), " +
@@ -476,6 +438,28 @@ func definitions(env *Env) []toolDef {
}
return env.Vault.HashUser(arg(a, "user"), caller)
}},
{Name: "account_retire",
Description: "Retire bus accounts the grants part no longer wants, by a person's act with why (novox/hq ADR 0561 §2, " +
"ADR 0230 §18): the vault takes each one's hash out of its state `bus-accounts`, so the grants part's next user " +
"list drops the user, and keeps its value marked retired. For the set vault_status lists as waiting for a " +
"person (more than three, or more than half, gone at once); refused for an account still wanted, an adopted " +
"hash, and with no why. Wanted again, an account is re-enabled at once.",
Input: map[string]any{"users": map[string]any{"type": "array", "items": str("a bus user")},
"why": str("why they are retired")},
run: func(caller string, a map[string]any) (any, error) {
if env.Vault == nil {
return nil, errors.New("the vault is not ready")
}
var users []string
if list, ok := a["users"].([]any); ok {
for _, u := range list {
if s, ok := u.(string); ok {
users = append(users, strings.TrimSpace(s))
}
}
}
return env.Vault.RetireAccounts(caller, users, arg(a, "why"))
}},
{Name: "secret_vault_export",
Description: "Every secret the vault itself holds, as its copy sealed to the operator key, in the shape of " +
"`secret export`: saved to a file, `nox secret recover vault mesh-vault <name> --key <operator key file> " +
@@ -544,7 +528,9 @@ func definitions(env *Env) []toolDef {
run: func(string, map[string]any) (any, error) { return env.health(), nil }},
{Name: "vault_status",
Description: "What needs a person's eye in the vault: operator copies still sealed to an earlier key, the operator " +
"key the mesh's export holds if the vault refused it, and how often the record of hand-outs was rolled.",
"key the mesh's export holds if the vault refused it, how often the record of hand-outs was rolled, and " +
"minting (novox/hq ADR 0561 §3, §9): whether the vault mints bus accounts now and why (only while the " +
"controller's lease is handed away), every wanted account it holds back with why, and those it minted.",
run: func(string, map[string]any) (any, error) {
if env.Vault == nil {
return map[string]any{"ready": false, "error": fmt.Sprint(env.Broken)}, nil
@@ -556,7 +542,7 @@ func definitions(env *Env) []toolDef {
key, _ := env.Vault.Store.OperatorKey()
return map[string]any{"ready": true, "operator_key": key, "copies_on_an_earlier_key": left,
"operator_key_refused": env.keyRefused(), "handed_rolled": env.Vault.Store.Rolled(),
"ok": left == 0 && env.keyRefused() == "" && key != ""}, nil
"minting": env.Vault.MintState(), "retiring": env.Vault.RetireState(), "ok": left == 0 && env.keyRefused() == "" && key != ""}, nil
}},
}
}
@@ -607,17 +593,6 @@ func (e *Env) ready() (*Vault, error) {
return nil, errors.New("the vault is not ready")
}
// isTrue is a switch argument said true, as a boolean or as the word.
func isTrue(v any) bool {
switch t := v.(type) {
case bool:
return t
case string:
return strings.EqualFold(strings.TrimSpace(t), "true")
}
return false
}
func arg(a map[string]any, key string) string {
s, _ := a[key].(string)
return strings.TrimSpace(s)
@@ -845,9 +820,6 @@ func ownAnswer(v *Vault, node, module, prefix string) (map[string]any, error) {
if r.ChangedVia != "" {
row["changedVia"] = r.ChangedVia
}
if r.Previous != nil {
row["previousGeneration"] = r.Previous.Generation
}
if note != nil {
row["error"] = note
}
+16 -37
View File
@@ -49,8 +49,6 @@ type Vault struct {
// Haves reads the node-engines' have bucket, where the bus node hands the loaded list's hashes (adopt.go): nil
// adopts nothing.
Haves HaveReader
// HaveKeys lists the keys of the node-engines' have bucket, for own_drift (owntake.go): nil lists none.
HaveKeys func() ([]string, error)
mu sync.Mutex
// hashMu keeps one hashing at a time, and hashes what is owed (accounts.go).
@@ -58,6 +56,14 @@ type Vault struct {
hashes hashing
// adoption is the last adoption (adopt.go), under mu.
adoption adoptionKept
// WantRead reads one wanted account afresh (issue-account): nil reads the wants as the watch handed them.
WantRead func(user string) ([]byte, bool, error)
// Placement reads the catalogue's placement (placed.go): where modules stand once the assignments are gone.
Placement PlacementReader
// LeaseRead reads the controller's lease afresh before a mint (lease.go): nil reads it only as the watch hands it.
LeaseRead func() ([]byte, bool, error)
// minting is the switch on the lease and what the vault knows of the wanted bus accounts (mint.go).
minting minting
// callsMu guards pending: the keys of the calls open now (intake.go), never written anywhere.
callsMu sync.Mutex
pending map[string]*callKey
@@ -106,13 +112,10 @@ func (v *Vault) keep(name, value, by, via, origin string) (Changed, error) {
// was first made, and where it was moved from.
type keepOptions struct {
neverReplace bool
madeAt time.Time
movedFrom *MovedFrom
// replaceOnly, keepPrevious and refuse are what move-in with replace_running keeps (owntake.go): only a value held is replaced,
// keeping its origin and the value it replaces, and refuse, under the store's lock, says why a held value is not.
replaceOnly bool
keepPrevious bool
refuse func(before Record) string
// quiet keeps secret-changed for the caller to say once the rest is done (a minted account: mint.go).
quiet bool
madeAt time.Time
movedFrom *MovedFrom
}
// keepWith is keep with the move's options. A covered bus account kept anew has its hash written once it is kept
@@ -154,18 +157,10 @@ func (v *Vault) keepLocked(name, value, by, via, origin string, opt keepOptions)
if err != nil {
return Changed{}, err
}
if !held && opt.replaceOnly {
return Changed{}, fmt.Errorf("the vault holds no secret named %s, so there is nothing to replace; nothing was taken", name)
}
if held {
if old, err := seal.Open(before.AtRest, v.Own.PrivateKey); err == nil && old == value {
return Changed{Name: name, Generation: before.Generation, At: before.ChangedAt, By: before.ChangedBy, Unchanged: true}, nil
}
if opt.refuse != nil {
if why := opt.refuse(before); why != "" {
return Changed{}, errors.New(why)
}
}
if opt.neverReplace {
return Changed{}, fmt.Errorf("the vault already holds another value for %s (generation %d, changed by %s "+
"at %s), and the move never replaces a value the vault holds: nothing was taken", name,
@@ -189,13 +184,6 @@ func (v *Vault) keepLocked(name, value, by, via, origin string, opt keepOptions)
MadeAt: now, ChangedAt: now, ChangedBy: by, ChangedVia: via, Origin: origin}
if held {
rec.Generation, rec.MadeAt = before.Generation+1, before.MadeAt
if opt.replaceOnly {
rec.Origin, rec.MovedFrom = before.Origin, before.MovedFrom
}
if opt.keepPrevious {
rec.Previous = &PreviousValue{Generation: before.Generation, AtRest: before.AtRest, Operator: before.Operator,
ChangedAt: before.ChangedAt, ChangedBy: before.ChangedBy, Origin: before.Origin}
}
} else if !opt.madeAt.IsZero() {
rec.MadeAt = opt.madeAt.UTC()
}
@@ -208,7 +196,9 @@ func (v *Vault) keepLocked(name, value, by, via, origin string, opt keepOptions)
return Changed{}, err
}
c := Changed{Name: name, Generation: rec.Generation, At: now, By: by}
v.announce(c)
if !opt.quiet {
v.announce(c)
}
return c, nil
}
@@ -365,8 +355,7 @@ func (v *Vault) reseal(key string) (int, error) {
n := 0
var failed []error
for _, rec := range all {
if rec.Operator.Key == key && rec.Operator.Box == OperatorBox &&
(rec.Previous == nil || rec.Previous.Operator.Key == key && rec.Previous.Operator.Box == OperatorBox) {
if rec.Operator.Key == key && rec.Operator.Box == OperatorBox {
continue
}
value, err := seal.Open(rec.AtRest, v.Own.PrivateKey)
@@ -375,16 +364,6 @@ func (v *Vault) reseal(key string) (int, error) {
continue
}
sealed, err := operatorSeal(key, []byte(value))
if err == nil && rec.Previous != nil {
// And the value it replaced (owntake.go): a copy of every value the vault keeps is the operator's.
var old string
if old, err = seal.Open(rec.Previous.AtRest, v.Own.PrivateKey); err == nil {
var prev string
if prev, err = operatorSeal(key, []byte(old)); err == nil {
rec.Previous.Operator = OperatorCopy{Box: OperatorBox, Key: key, Sealed: prev}
}
}
}
if err == nil {
rec.Operator = OperatorCopy{Box: OperatorBox, Key: key, Sealed: sealed}
err = v.Store.Write(rec)
@@ -131,9 +131,11 @@ func filesUnder(t *testing.T, dir string) map[string]string {
// The manifest declares one bucket, and no secret is in it: the vault's only place for a secret is its own store on its
// own disk (ADR 0349 §7, ADR 0201 §13). The one bucket is bus-accounts, the bcrypt hashes of the bus accounts it holds
// (ADR 0547 clause 9), opened in accounts.go alone. It reads two buckets of others', and only reads them: the
// controller's assignments, for what each node's plan names (askers.go, design 57 V4), and the node-engines' haves, where
// the bus node hands the loaded list's hashes sealed to the vault (adopt.go, ADR 0547 clause 9), in main.go alone.
// (ADR 0547 clause 9), opened in accounts.go alone. It reads five buckets of others', and only reads them: the
// controller's assignments, for what each node's plan names (askers.go, design 57 V4), the node-engines' haves, where
// the bus node hands the loaded list's hashes sealed to the vault (adopt.go, ADR 0547 clause 9), the grants part's wanted
// accounts and the controller's lease (mint.go, lease.go, ADR 0561 §2, §3), and the catalogue's placement (placed.go), in
// main.go alone.
func TestNoBucketHoldsASecret(t *testing.T) {
raw, err := os.ReadFile("../../module.json")
if err != nil {
@@ -147,8 +149,9 @@ func TestNoBucketHoldsASecret(t *testing.T) {
t.Errorf("the manifest declares buckets %s: a secret is in no bucket, sealed or not (ADR 0201 §13), and the one "+
"bucket is the accounts' hashes (ADR 0547 clause 9)", s)
}
if r, _ := json.Marshal(manifest["reads"]); string(r) != `["mesh-controller.assignments","node-engine.have"]` {
t.Errorf("the manifest reads %s: the vault reads the controller's assignments and the haves alone", r)
if r, _ := json.Marshal(manifest["reads"]); string(r) != `["mesh-controller.assignments","node-engine.have","mesh-grants.accounts","mesh-controller.lease","mesh-delivery-indexer.placement"]` {
t.Errorf("the manifest reads %s: the vault reads the controller's assignments, the haves and the grants part's "+
"wanted accounts alone", r)
}
sources, _ := filepath.Glob("*.go")
bucket := regexp.MustCompile(`stdio\.State\(|nats-io|jetstream|KeyValue`)
@@ -166,12 +169,21 @@ func TestNoBucketHoldsASecret(t *testing.T) {
code = []byte(strings.Replace(string(code), "stdio.State(BusAccountsState).Get(", "", 1))
code = []byte(strings.Replace(string(code), "stdio.State(BusAccountsState).Put(", "", 1))
code = []byte(strings.Replace(string(code), "stdio.State(BusAccountsState).Keys(", "", 1))
code = []byte(strings.Replace(string(code), "stdio.State(BusAccountsState).Delete(", "", 1))
}
// The haves, in main.go alone: one read, one watch and their keys (own_drift), never a write.
// The haves, in main.go alone: one read and one watch, never a write; and one watch of the wanted accounts, the
// grants part's, which hold no secret (ADR 0561 §2).
if f == "main.go" {
code = []byte(strings.Replace(string(code), "stdio.State(HaveRead).Get(", "", 1))
code = []byte(strings.Replace(string(code), "stdio.State(HaveRead).Watch(", "", 1))
code = []byte(strings.Replace(string(code), "stdio.State(HaveRead).Keys(", "", 1))
code = []byte(strings.Replace(string(code), "stdio.State(WantedRead).Watch(", "", 1))
code = []byte(strings.Replace(string(code), "stdio.State(WantedRead).Get(", "", 1))
// And the controller's lease, one read and one watch (ADR 0561 §3).
code = []byte(strings.Replace(string(code), "stdio.State(LeaseRead).Get(", "", 1))
code = []byte(strings.Replace(string(code), "stdio.State(LeaseRead).Watch(", "", 1))
// And the catalogue's placement, where modules stand (placed.go): its keys and one key, read.
code = []byte(strings.Replace(string(code), "stdio.State(PlacementRead).Keys(", "", 1))
code = []byte(strings.Replace(string(code), "stdio.State(PlacementRead).Get(", "", 1))
}
if m := bucket.Find(code); m != nil {
t.Errorf("%s opens a bucket (%s): the vault keeps every secret in its own store only", f, m)
+1 -1
View File
@@ -3,7 +3,7 @@ module mesh-vault
go 1.26.0
require (
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261028090029-3028c7ec4ed2
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261027220144-3f7957e16972
github.com/nats-io/nats-server/v2 v2.11.17
github.com/nats-io/nats.go v1.54.0
golang.org/x/crypto v0.57.0
+2 -2
View File
@@ -1,5 +1,5 @@
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261028090029-3028c7ec4ed2 h1:eSwObLdxs3jxPrlcwdaMo9hzIDTUz2ogWw8cjX8To7I=
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261028090029-3028c7ec4ed2/go.mod h1:ouERNpZizzwZ0HLEtAypsY9FR20FyUgUYRni6J7kVCY=
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261027220144-3f7957e16972 h1:iYDYv4HpV1ic20Ban0MaOErryQfNT8ngjlh0bKW6sCU=
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261027220144-3f7957e16972/go.mod h1:ouERNpZizzwZ0HLEtAypsY9FR20FyUgUYRni6J7kVCY=
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op h1:Z/MZK75wC/NSrkgqeNIa7jexam9uWzhLmFTSCPI/kn0=
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
+9 -6
View File
@@ -16,11 +16,14 @@
"rotated",
"secret-changed",
"account-hashed",
"own-replaced"
"account-issued"
],
"reads": [
"mesh-controller.assignments",
"node-engine.have"
"node-engine.have",
"mesh-grants.accounts",
"mesh-controller.lease",
"mesh-delivery-indexer.placement"
],
"state": [
{
@@ -157,6 +160,7 @@
"secret_own",
"account_hash",
"account_adopt",
"account_retire",
"secret_asks",
"secret_vault_export",
"provisioner_retirement",
@@ -164,9 +168,7 @@
"provisioner_retire_reject",
"provisioner_delete",
"vault_status",
"vault_health",
"own_drift",
"own_take_switch"
"vault_health"
],
"claims": [
{
@@ -181,7 +183,8 @@
"move-in",
"node-key",
"move-asks",
"own"
"own",
"issue-account"
]
}
]
-16
View File
@@ -1130,8 +1130,6 @@ func (h *Holder) record(s Sent) {
if h.Store != nil {
if err := h.Store.PutRecent(recent); err != nil {
h.noteStore(err)
} else {
h.storeWritten()
}
}
}
@@ -1145,20 +1143,6 @@ func (h *Holder) persist(r *Record) {
h.mu.Unlock()
if err := h.Store.Put(c); err != nil {
h.noteStore(err)
} else {
h.storeWritten()
}
}
// storeWritten clears a state problem once a write succeeds again: the status says what holds now, never a
// failure that passed (issue 1507's reading of 2026-10-28: a verdict kept a single failure of the day before).
func (h *Holder) storeWritten() {
h.mu.Lock()
was := h.storeErr
h.storeErr = ""
h.mu.Unlock()
if was != "" {
h.Logf("[messenger] writes its state again (it could not: %s)", was)
}
}
+3 -23
View File
@@ -71,14 +71,9 @@ type memStore struct {
passes map[string]Pass
// puts counts the writes, so a write of bytes identical to what is stored is still seen (issue 422's review).
puts int
// fail, when set, refuses every write of a record or of the sends, as the bus does with no responders.
fail error
}
func (m *memStore) Put(r Record) error {
if m.fail != nil {
return m.fail
}
if m.recs == nil {
m.recs = map[string]Record{}
}
@@ -94,13 +89,7 @@ func (m *memStore) All() ([]Record, error) {
}
return out, nil
}
func (m *memStore) PutRecent(s []Sent) error {
if m.fail != nil {
return m.fail
}
m.recent = s
return nil
}
func (m *memStore) PutRecent(s []Sent) error { m.recent = s; return nil }
func (m *memStore) PutWalk(w Walk) error {
if m.walks == nil {
m.walks = map[string]Walk{}
@@ -442,21 +431,15 @@ func TestEscalationIsSaidOnce(t *testing.T) {
}
func TestAChannelThatCannotSendSaysSoAndIsTriedAgain(t *testing.T) {
h, tg, _, c, store := newHolder(t)
h, tg, _, c, _ := newHolder(t)
h.Desk = nil
tg.fail = errors.New("telegram sendMessage: cannot connect (dial)")
// The state could not be written either, once: said while it lasts, and no longer once a write succeeds
// (issue 1507's reading of 2026-10-28: a verdict kept a day-old "no responders").
store.fail = errors.New("nats: no responders available for request")
h.Condition(EventRaised, cond("machine.ace.silent", Urgent, "silent"))
st := h.Status("listening")
if !strings.HasPrefix(st.Verdict, "CANNOT SEND") || len(st.Unsent) != 1 || st.Channels[0].LastError == "" {
t.Fatalf("status: %+v", st)
}
if st.StateProblem == "" {
t.Fatalf("a failed state write is not said: %+v", st)
}
tg.fail, store.fail = nil, nil
tg.fail = nil
h.Flush()
if len(tg.sends) != 0 {
t.Fatalf("tried again before a minute")
@@ -466,9 +449,6 @@ func TestAChannelThatCannotSendSaysSoAndIsTriedAgain(t *testing.T) {
if len(tg.sends) != 1 || h.Status("listening").Verdict != "ok" {
t.Fatalf("not retried: %d, %s", len(tg.sends), h.Status("listening").Verdict)
}
if p := h.Status("listening").StateProblem; p != "" {
t.Fatalf("a state write that succeeded again still says the old failure: %s", p)
}
}
func TestNothingConfiguredIsSaidInTheStatus(t *testing.T) {
+4 -6
View File
@@ -677,8 +677,7 @@ func tools(h *Holder, l *listening) []stdio.Tool {
Run: func(map[string]any) (any, error) { return h.Open(), nil }},
{Name: "operator-channel.history",
Description: "What was said to the operator lately, newest first — each send, digest, edit and failure with its " +
"channel, key and outcome — every message refused for carrying an address, a path or a secret, and what " +
"waits to be sent on each channel, since when and when its burst window ends.",
"channel, key and outcome — and every message refused for carrying an address, a path or a secret.",
Input: map[string]any{"limit": map[string]any{"type": "integer", "description": "at most this many of each (default 50)"}},
Run: func(a map[string]any) (any, error) { return h.History(limitArg(a, 50)), nil }},
{Name: "operator-channel.notify",
@@ -751,10 +750,9 @@ func tools(h *Holder, l *listening) []stdio.Tool {
return h.Unlink(kind)
}},
{Name: "messenger_recent",
Description: "The recent sends — each message, digest, edit and failure on each channel, newest first — the refusals, " +
"and what waits to be sent: each message held on a channel (its burst window is 30 s), since when and when its window ends.",
Input: map[string]any{"limit": map[string]any{"type": "integer", "description": "at most this many (default 20)"}},
Run: func(a map[string]any) (any, error) { return h.History(limitArg(a, 20)), nil }},
Description: "The recent sends — each message, digest, edit and failure on each channel, newest first — and the refusals.",
Input: map[string]any{"limit": map[string]any{"type": "integer", "description": "at most this many (default 20)"}},
Run: func(a map[string]any) (any, error) { return h.History(limitArg(a, 20)), nil }},
{Name: "messenger_test",
Description: "Send a test message now, to one channel kind or every one (default), through the content rule " +
"and the cap: proves a channel reaches the operator. Answers per channel: put on its queue, or why not.",
@@ -66,40 +66,3 @@ func TestAnAskAlreadySentIsNotSentAgainAfterARestart(t *testing.T) {
t.Fatalf("sent again after a restart: %d", len(tg.sends))
}
}
// Issue 1507, read again 2026-10-28: three asks taken at 08:50:03-08:50:14 went out together at 08:50:33, at the
// end of the first one's burst window; a reading of the history in between showed no send and no refusal, and the
// asks read as lost. What waits in an outbox is in the history, with when its window ends, until it is sent.
func TestTheHistorySaysAnAskWaitingForItsBurstWindow(t *testing.T) {
h, tg, _, c, store, _ := newRouter(t)
link(h, store, c, "42", c.now().Add(-2*time.Hour))
submit(t, h, "mesh-config", heldAsk(c, "cfg-1"))
waiting := func() []Waiting { return h.History(20)["waiting"].([]Waiting) }
for _, step := range []struct {
name string
pass time.Duration
want int
}{
{"taken, inside its window", 0, 1},
{"its window passed and it was sent", BurstWindow + time.Second, 0},
} {
c.pass(step.pass)
stand(h, c)
h.Flush()
w := waiting()
if len(w) != step.want {
t.Fatalf("%s: %d waiting, want %d: %+v", step.name, len(w), step.want, w)
}
if step.want == 1 {
if w[0].Key != "ask.mesh-config.cfg-1" || w[0].Channel != tg.Name() || w[0].Due == "" {
t.Fatalf("%s: waiting %+v, want the ask on %s with when its window ends", step.name, w[0], tg.Name())
}
if len(tg.sends) != 0 {
t.Fatalf("%s: sent before its window ended", step.name)
}
}
}
if len(tg.sends) != 1 {
t.Fatalf("sent %d times, want once", len(tg.sends))
}
}
+1 -30
View File
@@ -214,36 +214,7 @@ func (h *Holder) History(limit int) map[string]any {
for i := len(h.refusals) - 1; i >= 0 && len(refusals) < limit; i-- {
refusals = append(refusals, h.refusals[i])
}
return map[string]any{"sends": sends, "refusals": refusals, "waiting": h.waitingNow()}
}
// Waiting is one message held in a channel's outbox, not sent yet: history says it, so a message held for its
// burst window reads as waiting and not as never sent (issue 1507, its reading of 2026-10-28).
type Waiting struct {
Channel string `json:"channel"`
Key string `json:"key"`
What string `json:"what"`
Since string `json:"since"`
// Due is when its burst window ends: it goes out at the first flush from then, unless a rule holds it longer.
Due string `json:"window_ends"`
}
// waitingNow is every message held in an outbox, oldest first. Called with mu held.
func (h *Holder) waitingNow() []Waiting {
out := []Waiting{}
for ch, list := range h.outbox {
for _, it := range list {
out = append(out, Waiting{Channel: ch, Key: it.Key, What: it.What,
Since: it.At.Format(time.RFC3339Nano), Due: it.At.Add(BurstWindow).Format(time.RFC3339Nano)})
}
}
sort.SliceStable(out, func(i, j int) bool {
if out[i].Since != out[j].Since {
return out[i].Since < out[j].Since
}
return out[i].Channel < out[j].Channel
})
return out
return map[string]any{"sends": sends, "refusals": refusals}
}
// Test sends a test message on one channel or both, through the content rule and the cap.
-1125
View File
File diff suppressed because it is too large Load Diff
-276
View File
@@ -1,276 +0,0 @@
{
"v": 1,
"node": "g14",
"decided": {
"address": "10.10.0.4",
"account": "jochen",
"tunnel": {
"interface": "wg0",
"unit": "wg-quick@wg0",
"config": "/etc/wireguard/wg0.conf",
"port": 51820,
"mtu": 1380,
"address": "10.10.0.4/24",
"range": "10.10.0.0/24",
"public-key": "mq76YPW0FrExhAvt/ZG1SB2BK6/cPISKgXO53SEMazU="
}
},
"modules": [
{
"module": "adwaita"
},
{
"module": "asus-zephyrus-g14"
},
{
"module": "avahi"
},
{
"module": "blueman"
},
{
"module": "bluetooth"
},
{
"module": "ca-trust"
},
{
"module": "claude-code",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "clipmenu"
},
{
"module": "cups"
},
{
"module": "dbus"
},
{
"module": "dev-tools"
},
{
"module": "disk-load"
},
{
"module": "dmenu"
},
{
"module": "docker"
},
{
"module": "docker-compose"
},
{
"module": "dunst",
"has-layer": true
},
{
"module": "fail2ban"
},
{
"module": "feh"
},
{
"module": "flatpak"
},
{
"module": "fonts"
},
{
"module": "forticlient"
},
{
"module": "gnome-keyring"
},
{
"module": "go"
},
{
"module": "hostname",
"has-layer": true
},
{
"module": "i3"
},
{
"module": "i3status-rust"
},
{
"module": "kernel"
},
{
"module": "lemurs"
},
{
"module": "localization"
},
{
"module": "logrotate"
},
{
"module": "memory-pressure"
},
{
"module": "mesh-build-go",
"has-layer": true
},
{
"module": "mesh-build-node",
"bindings": {
"npm-package-registry": {
"node": "novox",
"module": "gitea"
}
}
},
{
"module": "mesh-cli"
},
{
"module": "mesh-files"
},
{
"module": "mesh-host",
"has-layer": true
},
{
"module": "mesh-mail-notifier"
},
{
"module": "mesh-provisioner-client"
},
{
"module": "mesh-reads"
},
{
"module": "mesh-wireguard"
},
{
"module": "netcheck"
},
{
"module": "networkmanager"
},
{
"module": "nextcloud-client"
},
{
"module": "nftables"
},
{
"module": "nm-applet"
},
{
"module": "node-env"
},
{
"module": "node-tools"
},
{
"module": "nodejs"
},
{
"module": "okioki",
"has-layer": true
},
{
"module": "openrazer"
},
{
"module": "pacman",
"has-layer": true
},
{
"module": "picom"
},
{
"module": "polychromatic"
},
{
"module": "power",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "powerlevel10k"
},
{
"module": "restic"
},
{
"module": "rofi"
},
{
"module": "screen-lock"
},
{
"module": "sensors"
},
{
"module": "slack"
},
{
"module": "snapd"
},
{
"module": "ssh-client"
},
{
"module": "sshd"
},
{
"module": "sudo"
},
{
"module": "systemd"
},
{
"module": "systemd-resolved"
},
{
"module": "time-sync"
},
{
"module": "triggerhappy"
},
{
"module": "xclip"
},
{
"module": "xdg",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "xorg"
},
{
"module": "xterm"
},
{
"module": "zsh"
},
{
"module": "zsh-autosuggestions"
},
{
"module": "zsh-syntax-highlighting"
}
],
"pins": {
"wildcard-resolution": {
"node": "novox",
"module": "dnsmasq"
}
},
"holds": [
{
"claim": "bookkeeping",
"scope": "mesh",
"module": "okioki"
}
]
}
-666
View File
@@ -1,666 +0,0 @@
{
"v": 1,
"node": "novox",
"decided": {
"endpoint": "142.132.152.141:51820",
"site": "hosting",
"hub": true,
"address": "10.10.0.1",
"public-domain": "novox.be",
"account": "jochens",
"agent-account": "nox",
"tunnel": {
"interface": "wg0",
"unit": "wg-quick@wg0",
"config": "/etc/wireguard/wg0.conf",
"port": 51820,
"address": "10.10.0.1/24",
"range": "10.10.0.0/24",
"public-key": "xW0ETQwyR9rHi2XSfOJrKkairE+Fp70FPNNcirqMixY="
},
"peer-names": {
"XT1l25Z0/YhRNQ8FQM+9XsAp7chx5MI0eLOOg1SUEXA=": "shanks",
"mq76YPW0FrExhAvt/ZG1SB2BK6/cPISKgXO53SEMazU=": "g14",
"zTKYP6Sz1hDwnwxIHgiGXYAeGcWbqti3tcSvKEA0Ew4=": "ace"
}
},
"modules": [
{
"module": "artifact-store-tools",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "avahi"
},
{
"module": "ca-trust"
},
{
"module": "claude-code",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "claude-licence-manager",
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
},
"secret": {
"node": "novox",
"module": "mesh-vault"
}
}
},
{
"module": "dbus"
},
{
"module": "de-spiegel",
"ports": {
"35621": 20005
},
"bindings": {
"smtp": {
"node": "novox",
"module": "mailu"
}
}
},
{
"module": "desk-channel",
"has-layer": true
},
{
"module": "dev-tools"
},
{
"module": "disk-load"
},
{
"module": "distribution",
"layer": {
"ports": {
"5000": 5100
}
},
"has-layer": true
},
{
"module": "dnsmasq"
},
{
"module": "docker"
},
{
"module": "fail2ban"
},
{
"module": "gitea",
"ports": {
"3000": 20000
},
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
},
"secret": {
"node": "novox",
"module": "mesh-vault"
}
},
"layer": {
"expose": {
"22": "anywhere"
},
"ports": {
"22": 222
}
},
"has-layer": true
},
{
"module": "go"
},
{
"module": "hostname",
"has-layer": true
},
{
"module": "invoicing",
"ports": {
"80": 20007,
"9000": 20008
},
"bindings": {
"mongodb-database": {
"node": "novox",
"module": "mongodb"
},
"s3-bucket": {
"node": "novox",
"module": "minio"
}
}
},
{
"module": "kernel",
"has-layer": true
},
{
"module": "keycloak",
"ports": {
"8080": 20009
},
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
}
},
"has-layer": true
},
{
"module": "link2pay"
},
{
"module": "localization"
},
{
"module": "logrotate"
},
{
"module": "mailu",
"ports": {
"110": 110,
"143": 143,
"25": 25,
"4243": 20004,
"465": 465,
"587": 587,
"8080": 20010,
"993": 993,
"995": 995
},
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
},
"secret": {
"node": "novox",
"module": "mesh-vault"
}
},
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "mesh-build-go",
"has-layer": true
},
{
"module": "mesh-build-node",
"bindings": {
"npm-package-registry": {
"node": "novox",
"module": "gitea"
}
}
},
{
"module": "mesh-catalog",
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
}
}
},
{
"module": "mesh-cli"
},
{
"module": "mesh-config"
},
{
"module": "mesh-controller"
},
{
"module": "mesh-delivery-checker"
},
{
"module": "mesh-delivery-forge-bridge"
},
{
"module": "mesh-delivery-gate",
"has-layer": true
},
{
"module": "mesh-delivery-indexer"
},
{
"module": "mesh-delivery-teller"
},
{
"module": "mesh-delivery-watchman"
},
{
"module": "mesh-files"
},
{
"module": "mesh-grants"
},
{
"module": "mesh-host",
"has-layer": true
},
{
"module": "mesh-issues"
},
{
"module": "mesh-knowledge",
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
}
}
},
{
"module": "mesh-mail",
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
},
"s3-bucket": {
"node": "novox",
"module": "minio"
}
},
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "mesh-mail-reader",
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
}
}
},
{
"module": "mesh-mail-web",
"bindings": {
"oidc-client": {
"node": "novox",
"module": "keycloak"
}
},
"layer": {
"endpoints": {
"web": {
"reach": "internal"
}
}
},
"has-layer": true
},
{
"module": "mesh-provisioner"
},
{
"module": "mesh-provisioner-client"
},
{
"module": "mesh-reads"
},
{
"module": "mesh-vault"
},
{
"module": "mesh-wireguard"
},
{
"module": "messenger",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "minio",
"ports": {
"9000": 20001,
"9001": 20002
}
},
{
"module": "mongodb",
"ports": {
"27017": 20006
}
},
{
"module": "mssql",
"layer": {
"ports": {
"1433": 4848
}
},
"has-layer": true
},
{
"module": "nats"
},
{
"module": "netcheck"
},
{
"module": "nextcloud",
"ports": {
"80": 20003
},
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
},
"s3-bucket": {
"node": "novox",
"module": "minio"
}
}
},
{
"module": "nftables"
},
{
"module": "node-env"
},
{
"module": "node-tools"
},
{
"module": "nodejs"
},
{
"module": "only-office"
},
{
"module": "pacman",
"has-layer": true
},
{
"module": "photos",
"ports": {
"9000": 20011
},
"bindings": {
"mongodb-database": {
"node": "novox",
"module": "mongodb"
},
"s3-bucket": {
"node": "novox",
"module": "minio"
}
}
},
{
"module": "postgres",
"layer": {
"ports": {
"5432": 6852
}
},
"has-layer": true
},
{
"module": "power",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "powerlevel10k"
},
{
"module": "records",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "restic",
"layer": {
"places": {
"repository": "/home/restic"
}
},
"has-layer": true
},
{
"module": "route-proxy"
},
{
"module": "ssh-client"
},
{
"module": "sshd"
},
{
"module": "step-ca"
},
{
"module": "sudo"
},
{
"module": "systemd"
},
{
"module": "systemd-networkd"
},
{
"module": "telegram"
},
{
"module": "time-sync"
},
{
"module": "umami",
"bindings": {
"postgres-database": {
"node": "novox",
"module": "postgres"
},
"secret": {
"node": "novox",
"module": "mesh-vault"
}
},
"layer": {
"expose": {
"3000": "mesh"
},
"ports": {
"3000": 1212
}
},
"has-layer": true
},
{
"module": "website",
"ports": {
"8080": 20012
}
},
{
"module": "zsh",
"has-layer": true
},
{
"module": "zsh-autosuggestions"
},
{
"module": "zsh-syntax-highlighting"
}
],
"holds": [
{
"claim": "anthropic-licence-manager",
"scope": "mesh",
"module": "claude-licence-manager",
"site": "hosting"
},
{
"claim": "channel",
"scope": "mesh",
"module": "desk-channel",
"site": "hosting",
"kind": "desktop"
},
{
"claim": "channel",
"scope": "mesh",
"module": "telegram",
"site": "hosting",
"kind": "telegram"
},
{
"claim": "document-converter",
"scope": "mesh",
"module": "only-office",
"site": "hosting"
},
{
"claim": "git",
"scope": "mesh",
"module": "gitea",
"site": "hosting"
},
{
"claim": "intake",
"scope": "mesh",
"module": "desk-channel",
"site": "hosting",
"kind": "desktop"
},
{
"claim": "intake",
"scope": "mesh",
"module": "telegram",
"site": "hosting",
"kind": "telegram"
},
{
"claim": "issue-tracker",
"scope": "mesh",
"module": "mesh-issues",
"site": "hosting"
},
{
"claim": "knowledge-base",
"scope": "mesh",
"module": "mesh-knowledge",
"site": "hosting"
},
{
"claim": "mail-reading",
"scope": "mesh",
"module": "mesh-mail-reader",
"site": "hosting"
},
{
"claim": "mail-store",
"scope": "mesh",
"module": "mesh-mail",
"site": "hosting"
},
{
"claim": "mail-webclient",
"scope": "mesh",
"module": "mesh-mail-web",
"site": "hosting"
},
{
"claim": "mesh-artifact-store",
"scope": "mesh",
"module": "distribution",
"site": "hosting"
},
{
"claim": "mesh-broker",
"scope": "mesh",
"module": "nats",
"site": "hosting"
},
{
"claim": "mesh-catalog",
"scope": "mesh",
"module": "mesh-catalog",
"site": "hosting"
},
{
"claim": "mesh-config",
"scope": "mesh",
"module": "mesh-config",
"site": "hosting"
},
{
"claim": "mesh-controller",
"scope": "mesh",
"module": "mesh-controller",
"site": "hosting"
},
{
"claim": "mesh-delivery",
"scope": "mesh",
"module": "mesh-delivery-gate",
"site": "hosting"
},
{
"claim": "mesh-dns-resolver",
"scope": "mesh",
"module": "dnsmasq",
"site": "hosting"
},
{
"claim": "mesh-provisioner",
"scope": "mesh",
"module": "mesh-provisioner",
"site": "hosting"
},
{
"claim": "mesh-store",
"scope": "mesh",
"module": "postgres",
"site": "hosting"
},
{
"claim": "mesh-vault",
"scope": "mesh",
"module": "mesh-vault",
"site": "hosting"
},
{
"claim": "npm-package-registry",
"scope": "mesh",
"module": "gitea",
"site": "hosting"
},
{
"claim": "object-store",
"scope": "mesh",
"module": "minio",
"site": "hosting"
},
{
"claim": "operator-channel",
"scope": "mesh",
"module": "messenger",
"site": "hosting"
}
]
}
-304
View File
@@ -1,304 +0,0 @@
{
"v": 1,
"node": "shanks",
"decided": {
"site": "home",
"address": "10.10.0.3",
"account": "jochen",
"tunnel": {
"interface": "wg0",
"unit": "wg-quick@wg0",
"config": "/etc/wireguard/wg0.conf",
"port": 51820,
"address": "10.10.0.3/24",
"range": "10.10.0.0/24",
"public-key": "XT1l25Z0/YhRNQ8FQM+9XsAp7chx5MI0eLOOg1SUEXA="
}
},
"modules": [
{
"module": "adwaita"
},
{
"module": "avahi"
},
{
"module": "blueman"
},
{
"module": "bluetooth"
},
{
"module": "brother",
"bindings": {
"s3-bucket": {
"node": "novox",
"module": "minio"
}
},
"has-layer": true
},
{
"module": "buildah"
},
{
"module": "ca-trust"
},
{
"module": "claude-code",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "clipmenu"
},
{
"module": "cups"
},
{
"module": "dbus"
},
{
"module": "dev-tools"
},
{
"module": "disk-load"
},
{
"module": "dmenu"
},
{
"module": "docker"
},
{
"module": "docker-compose"
},
{
"module": "dunst"
},
{
"module": "fail2ban"
},
{
"module": "feh"
},
{
"module": "flatpak"
},
{
"module": "fonts"
},
{
"module": "forticlient"
},
{
"module": "gnome-keyring"
},
{
"module": "go"
},
{
"module": "hostname",
"has-layer": true
},
{
"module": "i3"
},
{
"module": "i3status-rust"
},
{
"module": "kernel",
"has-layer": true
},
{
"module": "lab",
"bindings": {
"npm-package-registry": {
"node": "novox",
"module": "gitea"
}
},
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "lemurs"
},
{
"module": "localization"
},
{
"module": "logrotate"
},
{
"module": "mesh-build-go",
"has-layer": true
},
{
"module": "mesh-build-image"
},
{
"module": "mesh-build-node",
"bindings": {
"npm-package-registry": {
"node": "novox",
"module": "gitea"
}
}
},
{
"module": "mesh-cli"
},
{
"module": "mesh-delivery-builder"
},
{
"module": "mesh-delivery-view"
},
{
"module": "mesh-files"
},
{
"module": "mesh-host",
"has-layer": true
},
{
"module": "mesh-mail-notifier"
},
{
"module": "mesh-provisioner-client"
},
{
"module": "mesh-reads"
},
{
"module": "mesh-wireguard"
},
{
"module": "mounts",
"has-layer": true
},
{
"module": "netcheck"
},
{
"module": "networkmanager"
},
{
"module": "nextcloud-client"
},
{
"module": "nftables"
},
{
"module": "nm-applet"
},
{
"module": "node-env"
},
{
"module": "node-tools"
},
{
"module": "nodejs"
},
{
"module": "openrazer"
},
{
"module": "pacman",
"has-layer": true
},
{
"module": "picom"
},
{
"module": "polychromatic"
},
{
"module": "power",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "powerlevel10k"
},
{
"module": "restic"
},
{
"module": "rofi"
},
{
"module": "screen-lock"
},
{
"module": "slack"
},
{
"module": "snapd"
},
{
"module": "ssh-client"
},
{
"module": "sshd"
},
{
"module": "sudo"
},
{
"module": "systemd"
},
{
"module": "systemd-resolved"
},
{
"module": "time-sync"
},
{
"module": "xclip"
},
{
"module": "xdg",
"has-mesh-wide": true,
"has-layer": true
},
{
"module": "xorg"
},
{
"module": "xterm"
},
{
"module": "zsh"
},
{
"module": "zsh-autosuggestions"
},
{
"module": "zsh-syntax-highlighting"
}
],
"pins": {
"wildcard-resolution": {
"node": "novox",
"module": "dnsmasq"
}
},
"holds": [
{
"claim": "printer",
"scope": "mesh",
"module": "brother",
"site": "home"
},
{
"claim": "scanner",
"scope": "mesh",
"module": "brother",
"site": "home"
}
]
}
-1
View File
@@ -2,7 +2,6 @@
# *Not:* words with no scope or with (tools). A copy, so a catalogue merge needs nothing else; novox/hq's
# words.py compares it with the glossary. Regenerate with: python3 00-META/checks/words.py --list tools
build machine
catalogue
change plan
control plane
flavor