Compare commits
68
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee2160d00c | ||
|
|
0e7d9e74d2 | ||
|
|
1d8a244ba4 | ||
|
|
2edef5a00a | ||
|
|
fadf5025cc | ||
|
|
baa5ef802e | ||
|
|
5b20e419ec | ||
|
|
7e3e62062b | ||
|
|
7e0001e304 | ||
|
|
d94764f001 | ||
|
|
482232e8c5 | ||
|
|
e223262408 | ||
|
|
dbe2949f84 | ||
|
|
b7d9590fdc | ||
|
|
7ee2869d60 | ||
|
|
0b74c04aa8 | ||
|
|
e1c8965ddb | ||
|
|
47ef2644ac | ||
|
|
cb7bf94a77 | ||
|
|
8e821ef449 | ||
|
|
07b9bd0ed4 | ||
|
|
02427a60ef | ||
|
|
8661bcfa22 | ||
|
|
6049537655 | ||
|
|
bf3e801f67 | ||
|
|
50861c74f8 | ||
|
|
b15846dd6e | ||
|
|
a44d490d97 | ||
|
|
af5cf53a34 | ||
|
|
2bb5d344f6 | ||
|
|
e846c289c8 | ||
|
|
0fcc560fec | ||
|
|
acf8a76646 | ||
|
|
b62bb15839 | ||
|
|
ff9d3ee6a0 | ||
|
|
c8255eb15d | ||
|
|
4ded07bc63 | ||
|
|
054dc9618c | ||
|
|
ebf7f3773d | ||
|
|
c876ad4a83 | ||
|
|
12a5e7be73 | ||
|
|
23a2e1e204 | ||
|
|
66d22dd53e | ||
|
|
7ed119995f | ||
|
|
faebc3569a | ||
|
|
1faee6e279 | ||
|
|
6f7d06726c | ||
|
|
f09daabec3 | ||
|
|
bb5a342863 | ||
|
|
eadf301f9f | ||
|
|
9c166398f2 | ||
|
|
e209d46faf | ||
|
|
f1f866050e | ||
|
|
4d15a155e6 | ||
|
|
e46eeb8298 | ||
|
|
5f491e0c09 | ||
|
|
73404a3c3f | ||
|
|
305c2ba247 | ||
|
|
8ad121d5c3 | ||
|
|
305601d25e | ||
|
|
910bc58fe0 | ||
|
|
0096beeff9 | ||
|
|
6aa30eae66 | ||
|
|
bb60de6d61 | ||
|
|
a84d0094a0 | ||
|
|
dd39d4ace7 | ||
|
|
5bd40fa406 | ||
|
|
1906081937 |
+1
-1
@@ -1,4 +1,4 @@
|
||||
66
|
||||
62
|
||||
The long-running resources of this catalogue that do not say how they are ready (`health`, novox/hq ADR 0240
|
||||
rule 8), as `module check` counts them. It may only go down: merge-check.sh fails a change that raises it, and
|
||||
one that lowers it writes the new number on the first line. From 2026-11-18, or once it is 0, a long-running
|
||||
|
||||
@@ -14,7 +14,7 @@ WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -o /mesh-builder ./cmd/mesh-builder
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -buildvcs=false -ldflags=-buildid= -o /mesh-builder ./cmd/mesh-builder
|
||||
|
||||
# Unlike mesh-controller's own FROM scratch (ADR 0006: nothing to audit but one binary), the build
|
||||
# machine's whole job is shelling out to git and docker — it needs a real userland to do that in,
|
||||
|
||||
@@ -13,6 +13,11 @@ that repository's main (`build.artifacts[].context`); this module ships the pack
|
||||
Assign it to every machine with a container runtime. It replaces `builder`, the one-holder form of the
|
||||
same thing; retire that once this is assigned where it was.
|
||||
|
||||
A send that replaces the agent's container does not throw away the build it runs: the container declares
|
||||
`busy` as `/usr/local/bin/mesh-builder busy` (novox/hq ADR 0335). The node-engine asks it before replacing it; from that
|
||||
ask the agent takes no new build, the node-engine leaves it running while it says a build is in hand, and
|
||||
replaces it once it says idle, or after 15 minutes at the latest.
|
||||
|
||||
## The package registry (novox/hq ADR 0336)
|
||||
|
||||
The package registry (`npm-package-registry`, provided by the gitea module) is an optional requirement.
|
||||
|
||||
@@ -115,3 +115,57 @@ func TestTheGenesisDocumentIsDeclaredAndIssuedOutside(t *testing.T) {
|
||||
}
|
||||
t.Fatal("the build agent has no environment file")
|
||||
}
|
||||
|
||||
// **The judge cache is the agent's own, beside its workspace and never in it** (novox/hq ADR 0358 §6, issue 704): a
|
||||
// directory resource of its own, kept as the agent's data, mounted into the agent at the same path as on the host —
|
||||
// the container runtime resolves a judge build's mounts on the host — and handed to the agent as MESH_JUDGE_CACHE.
|
||||
func TestTheJudgeCacheIsADirectoryOfItsOwnMountedAtTheSamePath(t *testing.T) {
|
||||
raw, err := os.ReadFile("module.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m struct {
|
||||
Data struct {
|
||||
Own []struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
Class string `json:"class"`
|
||||
} `json:"own"`
|
||||
} `json:"data"`
|
||||
Resources []struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Content string `json:"content"`
|
||||
Volumes []string `json:"volumes"`
|
||||
} `json:"resources"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir, data, env, mounted := false, false, false, false
|
||||
for _, d := range m.Data.Own {
|
||||
if d.ID == "judge-cache" && d.Path == "${dir:judge-cache}" && d.Class == "cache" {
|
||||
data = true
|
||||
}
|
||||
}
|
||||
for _, r := range m.Resources {
|
||||
switch {
|
||||
case r.ID == "judge-cache" && r.Type == "directory":
|
||||
dir = true
|
||||
case r.ID == "agent-env":
|
||||
env = strings.Contains(r.Content, "MESH_JUDGE_CACHE=${dir:judge-cache}\n")
|
||||
case r.ID == "server":
|
||||
for _, v := range r.Volumes {
|
||||
if v == "${dir:judge-cache}:${dir:judge-cache}" {
|
||||
mounted = true
|
||||
}
|
||||
if strings.HasPrefix(v, "${dir:workspace}") && strings.Contains(v, "judge-cache") {
|
||||
t.Errorf("the judge cache is mounted inside the workspace: %s", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !dir || !data || !env || !mounted {
|
||||
t.Fatalf("the judge cache: directory %v, data %v, env %v, mounted at the same path %v", dir, data, env, mounted)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,12 @@
|
||||
"path": "${dir:workspace}",
|
||||
"class": "cache",
|
||||
"why": "a build's working copy, cloned again for every build"
|
||||
},
|
||||
{
|
||||
"id": "judge-cache",
|
||||
"path": "${dir:judge-cache}",
|
||||
"class": "cache",
|
||||
"why": "the Go cache every merge check's judge is built with and the release-branch judges kept per head; mounted into judge builds only, never into a check's containers (novox/hq ADR 0358 §6)"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -54,12 +60,17 @@
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "judge-cache",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "agent-env",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/build-agent.env",
|
||||
"mode": "0600",
|
||||
"content": "MESH_BROKER_FILE=/run/mesh/broker\nMESH_NODE=${machine:name}\nMESH_REGISTRY=${bound:artifact-store:at}:${bound:artifact-store:port}\nMESH_PACKAGE_BINDING=/run/mesh/package-registry.json\nMESH_NPM_TOKEN_FILE=/run/mesh/package-registry.secret\nMESH_GENESIS_PACKAGE_REGISTRY=/run/mesh/genesis-package-registry.json\nMESH_WORKSPACE=${dir:workspace}\n"
|
||||
"content": "MESH_BROKER_FILE=/run/mesh/broker\nMESH_NODE=${machine:name}\nMESH_REGISTRY=${bound:artifact-store:at}:${bound:artifact-store:port}\nMESH_PACKAGE_BINDING=/run/mesh/package-registry.json\nMESH_NPM_TOKEN_FILE=/run/mesh/package-registry.secret\nMESH_GENESIS_PACKAGE_REGISTRY=/run/mesh/genesis-package-registry.json\nMESH_WORKSPACE=${dir:workspace}\nMESH_JUDGE_CACHE=${dir:judge-cache}\n"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
@@ -72,6 +83,7 @@
|
||||
"volumes": [
|
||||
"${dir:mesh-state}:/run/mesh:ro",
|
||||
"${dir:workspace}:${dir:workspace}",
|
||||
"${dir:judge-cache}:${dir:judge-cache}",
|
||||
"/var/run/docker.sock:/var/run/docker.sock"
|
||||
],
|
||||
"restart-on": [
|
||||
@@ -85,6 +97,9 @@
|
||||
"timeout": "5s",
|
||||
"looks": 3,
|
||||
"grace": "60s"
|
||||
},
|
||||
"busy": {
|
||||
"command": "/usr/local/bin/mesh-builder busy"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
@@ -11,8 +11,9 @@ Two directories, declared, so the mesh refuses a second module owning either:
|
||||
- `~/.claude` under the home of the account agents run as (the operator's, unless the machine names an agent
|
||||
account of its own), that account's, `0700`. The module owns the directory —
|
||||
that it exists, who owns it, its mode — and of what is inside only what it writes. Everything else
|
||||
in it (memory, history, projects, local settings, a person's own rules and skills) is the person's
|
||||
and is never read or written (hq ADR 0182). Unassigned, the module leaves the directory: the host
|
||||
in it (history, projects, local settings, a person's own rules and skills) is the person's
|
||||
and is never read or written (hq ADR 0182) — but for each project's memory folder, which the module
|
||||
carries between nodes (hq ADR 0343, below). Unassigned, the module leaves the directory: the host
|
||||
removes a directory only when it is empty.
|
||||
|
||||
And, for where the agent runs as an account of its own (hq ADR 0266):
|
||||
@@ -69,8 +70,37 @@ must see, a node that joins later included — kept, so it carries no secret eit
|
||||
| an MCP server registered through this module before registering was refused (hq issue 340) | a key in the module's `servers` state — `all.<server>` for every node, `<node>.<server>` for one; every node watches it and renders what applies to it, a node's own entry over the one for every node. A node that joins later, or was off, reads the whole current set at start; unregistering is a delete. Nothing adds a key any more: a new tool server is the operator's, in the `mcp_servers` setting at the controller's terminal |
|
||||
| a proposed instruction section (hq ADR 0274) | a key in the module's `proposals` state per proposal, the ask published on `operator-channel` under this module's name, and the router's record of it read under that name alone; what a node approved is its own file, never the bus |
|
||||
| a session's question to the operator (hq ADR 0332) | a key `q-…` in the module's `questions` state per question, the ask published on `operator-channel` under this module's name, and the router's record of it read under that name alone; the router's word that it ended without a choice is kept on the question; two slot keys `slot-1`, `slot-2` name the questions open |
|
||||
| a project's memory (hq ADR 0343) | a key in the module's `memory` state per file — `<kind>.<project and path, base64url>`, `operator` for the operator's own homes and `agent` for an agent account's — holding the text, its digest, the digest of the version it replaced, the node and when it changed; a removal is a value marked removed, never a deleted key. Written at the revision read, so of two nodes writing one file only one wins. Every node of the same kind watches it. No event and no tool answer carries memory text |
|
||||
| the agent's configuration (hq ADR 0216) | a key in the module's `config` state per registration — `mesh.<kind>.<name>` for every node, `node.<node>.<kind>.<name>` for one, `home.<node>.<kind>.<name>` for one account's own directory — the item and its files in one value, at most 256 KiB. Every node watches it and renders what applies to it, a node item over a mesh item of the same kind and name. A hook, settings, or an item that would run something by itself is never taken, whenever it was put there (hq issue 340) |
|
||||
|
||||
## A session's memory follows the operator (hq ADR 0343)
|
||||
|
||||
A session started on another node starts with what the sessions on every other node learned (hq issue 367). The
|
||||
module's long-running process carries each project's memory folder, `~/.claude/projects/<project>/memory/`, and
|
||||
nothing else of the home. A project is one entry of the projects directory and a path is relative, no part empty,
|
||||
`.` or `..`: a value in the state naming anything else is never taken, and nothing is touched for it.
|
||||
|
||||
- **Picked up** every ten seconds: a file whose text differs from the version last carried goes into the `memory`
|
||||
state. Not carried, and listed with why: a symbolic link, a file over 128 KiB or too large for one value once
|
||||
encoded, and a file holding a key block, a
|
||||
signed token, a known token prefix or a password in an address.
|
||||
- **Written** on every other node of the same home kind, only where its file is still the version the change
|
||||
replaced, or the version it last carried (a node that was away), or there is none; staged in the folder and renamed in, never through a symbolic link. The version
|
||||
replaced is kept first in `memory-copies/` in the module's state directory, 30 days.
|
||||
- **A file changed on two nodes** becomes one file holding both, the newer first, then a line naming each version's
|
||||
node and time, then the older (two versions too large for one file: the newer in it, the older beside it as
|
||||
`<name>.older-from-<node>`); what was written is carried, so every node ends on it, and the operator is warned through
|
||||
the operator channel's `notify` (a warning, cleared when the file next changes without a conflict).
|
||||
- **A removal** of a carried file, from a folder that still exists, is a marker in the state for 30 days: a node still
|
||||
holding the removed version moves it into the copies; a node that changed it keeps it and carries it again. A
|
||||
missing folder, a key the state lost and a deleted key remove nothing, and neither does a file or folder that
|
||||
cannot be read on a look: it is kept everywhere and listed as not carried.
|
||||
- **The two home kinds never mix**: the operator's own homes carry among themselves, an agent account's among
|
||||
themselves (hq ADR 0266), so a confined agent's notes never reach a session run as the operator.
|
||||
- **No tool writes memory** (hq issue 340): `claude_code_memory` only lists what is carried — fingerprints, never the
|
||||
text — the files not carried, the open conflicts and the copies kept. A value put straight into the state by a
|
||||
holder of a tool runner's credential is not yet told apart (hq issue 638).
|
||||
|
||||
## The mesh's tools first (hq ADR 0245)
|
||||
|
||||
The agent kept reaching for `ssh <machine> journalctl` while the service manager's `journal` verb existed. So:
|
||||
@@ -149,9 +179,12 @@ said in the render's answer. What was registered before is still rendered and ma
|
||||
hand-over, the context a later session needs — or with `remove` for a section approved before. Nothing becomes
|
||||
active: the proposal is kept in the module's `proposals` state and the operator is asked through the operator
|
||||
channel (`operator-channel`, hq ADR 0259) with Approve and Decline, both at the level approve, so only a channel that
|
||||
proves who answered (Telegram) carries either. The phone shows the whole text when it is short and every line may
|
||||
leave the mesh, else its first lines and a fingerprint; the whole text is read at the controller's terminal with
|
||||
`mesh-cli ask claude-code claude_code_proposals '{"id": "<id>"}'`. Decline, or no answer within a day, discards it.
|
||||
proves who answered (Telegram) carries either. The ask reads at a glance (hq issue 639): its explanation is one
|
||||
line saying what the proposal does — the proposer's `summary`, at most 300 characters, or the module's own words —
|
||||
and its Details, which the phone shows collapsed after the answers, carry the text (whole when it is short and every
|
||||
line may leave the mesh, else its first lines), where it came from and its fingerprint; the whole text is read at the
|
||||
controller's terminal with `mesh-cli ask claude-code claude_code_proposals '{"id": "<id>"}'`. A proposal made before
|
||||
that change is asked, and its warrant held, in the form it was made in (`form`). Decline, or no answer within a day, discards it.
|
||||
**Every node proves the approval itself**: it reads the router's own record of the ask under this module's name,
|
||||
judges the record as this module would have made it, composes the ask again from the proposal and holds the warrant to it (the same ask digest, the option's bound act,
|
||||
the text's digest, in time), and only then writes the section into its own `approved.json`, which the managed
|
||||
|
||||
@@ -495,22 +495,3 @@ func TestALowerGenerationAfterTheManagerWasRebuiltIsStillApplied(t *testing.T) {
|
||||
t.Fatalf("asked %v, credentials %v: a lower generation was ignored", asked, creds(t, p))
|
||||
}
|
||||
}
|
||||
|
||||
// The tips preference reaches the managed settings as spinnerTipsEnabled, either way, and is left out when the
|
||||
// mesh filled none: set in one call through the controller, never at the terminal.
|
||||
func TestTheTipsPreferenceIsRenderedAsSpinnerTipsEnabled(t *testing.T) {
|
||||
off, on := false, true
|
||||
for _, c := range []struct {
|
||||
tips *bool
|
||||
want any
|
||||
}{{&off, false}, {&on, true}, {nil, nil}} {
|
||||
out := Render(Facts{Console: "x"}, Settings{Preferences: Preferences{Tips: c.tips}}, nil, "/h", nil, Config{})
|
||||
var managed map[string]any
|
||||
if err := json.Unmarshal([]byte(out["managed-settings.json"]), &managed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, has := managed["spinnerTipsEnabled"]; got != c.want || has != (c.want != nil) {
|
||||
t.Errorf("tips %v rendered spinnerTipsEnabled %v (present %v)", c.tips, got, has)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +152,36 @@ func (s stateOf) Create(key string, value any) error {
|
||||
return err
|
||||
}
|
||||
func (s stateOf) Keys() ([]string, error) { return s.s.Keys() }
|
||||
|
||||
// memoryStateOf adapts the SDK's state to the memory carrier: every write at the revision read (ADR 0343).
|
||||
type memoryStateOf struct{ s stdio.KeptState }
|
||||
|
||||
func (s memoryStateOf) Get(key string) (json.RawMessage, uint64, bool, error) {
|
||||
e, err := s.s.Get(key)
|
||||
if err != nil || e == nil {
|
||||
return nil, 0, false, err
|
||||
}
|
||||
return e.Value, e.Revision, true, nil
|
||||
}
|
||||
func (s memoryStateOf) Create(key string, value any) error {
|
||||
_, err := s.s.Create(key, value)
|
||||
return err
|
||||
}
|
||||
func (s memoryStateOf) Update(key string, value any, revision uint64) error {
|
||||
_, err := s.s.Update(key, value, revision)
|
||||
return err
|
||||
}
|
||||
func (s memoryStateOf) Keys() ([]string, error) { return s.s.Keys() }
|
||||
func (s memoryStateOf) Delete(key string) error { return s.s.Delete(key) }
|
||||
|
||||
// memoryCarrier carries this node's memory folders (ADR 0343); nil until the long-running half starts it.
|
||||
var memoryCarrier *MemoryCarrier
|
||||
|
||||
// notifyOperator tells the operator through the operator channel's notify verb (ADR 0253).
|
||||
func notifyOperator(args map[string]any) error {
|
||||
_, err := ask("seat:operator-channel.notify", args)
|
||||
return err
|
||||
}
|
||||
func (s stateOf) Get(key string) (json.RawMessage, bool, error) {
|
||||
e, err := s.s.Get(key)
|
||||
if err != nil || e == nil {
|
||||
@@ -354,6 +384,9 @@ func tools(p Paths, servers ServerState, view *ServerView, config ConfigState, c
|
||||
out = append(out, stdio.Tool{Name: "claude_code_registrations",
|
||||
Description: "Read-only: everything registered through this module that a Claude Code session runs or obeys — the tool servers, the hooks, the settings and the skills, subagents, commands, output styles and instructions — by key, with who registered it, when, and whether it is still rendered (novox/hq issue 340), beside what the operator set for this node at the controller's terminal (managed_settings, mcp_servers). `by` is the node whose tool runner served the call, never the caller.",
|
||||
Run: func(map[string]any) (any, error) { return Registrations(p, servers, config) }})
|
||||
out = append(out, stdio.Tool{Name: "claude_code_memory",
|
||||
Description: "Read-only: what this node carries of the agent's memory between nodes (novox/hq ADR 0343) — the home kind it carries for (the operator's own homes, or an agent account's), each project's memory files with their fingerprint and the node and time of their last version, the files not carried and why, the conflicts still open (a file changed on two nodes, kept twice in one file, the newer first), and how many replaced or removed versions are kept. Fingerprints only, never the text; it changes nothing.",
|
||||
Run: func(map[string]any) (any, error) { return memoryCarrier.Status(), nil }})
|
||||
out = append(out, proposalTools(p)...)
|
||||
judge := NewJudge(p)
|
||||
out = append(out, judgeTool(judge), judgedTool(judge))
|
||||
@@ -430,6 +463,12 @@ func main() {
|
||||
proposing = &Proposing{Store: stateOf{stdio.State(ProposalsState)}, Bus: sdkAskBus{}, Record: recordWarrant,
|
||||
Now: time.Now, Write: writeManaged}
|
||||
go proposing.watch(p)
|
||||
memoryCarrier = NewMemoryCarrier(p, memoryStateOf{stdio.State(MemoryState)}, notifyOperator)
|
||||
go memoryCarrier.Run(func(handle func(key, op string, value json.RawMessage, revision uint64) error) error {
|
||||
return stdio.State(MemoryState).Watch("", func(c stdio.StateChange) error {
|
||||
return handle(c.Key, c.Op, c.Value, c.Revision)
|
||||
})
|
||||
})
|
||||
go run(p, view, configView)
|
||||
if err := stdio.Serve("", tools(p, servers, view, config, configView)); err != nil {
|
||||
say("%v", err)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,968 @@
|
||||
package main
|
||||
|
||||
// A session's memory follows the operator (novox/hq ADR 0343, issue 367). Every test runs against temporary homes
|
||||
// and a state in memory with the bus's watch semantics: never the live memory folders.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// memState is the `memory` state in memory: revisions, create and compare-and-set, and every change handed to every
|
||||
// watcher, the writer included, as the bus does.
|
||||
type memState struct {
|
||||
mu sync.Mutex
|
||||
values map[string]json.RawMessage
|
||||
revs map[string]uint64
|
||||
rev uint64
|
||||
pending []change
|
||||
watchers []*MemoryCarrier
|
||||
}
|
||||
|
||||
type change struct {
|
||||
key, op string
|
||||
value json.RawMessage
|
||||
rev uint64
|
||||
}
|
||||
|
||||
func newMemState() *memState {
|
||||
return &memState{values: map[string]json.RawMessage{}, revs: map[string]uint64{}}
|
||||
}
|
||||
|
||||
var errChanged = errors.New("wrong last revision")
|
||||
|
||||
func (s *memState) Get(key string) (json.RawMessage, uint64, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
v, ok := s.values[key]
|
||||
return v, s.revs[key], ok, nil
|
||||
}
|
||||
|
||||
func (s *memState) write(key string, value any) {
|
||||
raw, _ := json.Marshal(value)
|
||||
s.rev++
|
||||
s.values[key], s.revs[key] = raw, s.rev
|
||||
s.pending = append(s.pending, change{key, "put", raw, s.rev})
|
||||
}
|
||||
|
||||
func (s *memState) Create(key string, value any) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.values[key]; ok {
|
||||
return errChanged
|
||||
}
|
||||
s.write(key, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memState) Update(key string, value any, revision uint64) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.revs[key] != revision {
|
||||
return errChanged
|
||||
}
|
||||
s.write(key, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memState) Keys() ([]string, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
var keys []string
|
||||
for k := range s.values {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (s *memState) Delete(key string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.values, key)
|
||||
delete(s.revs, key)
|
||||
s.rev++
|
||||
s.pending = append(s.pending, change{key, "delete", nil, s.rev})
|
||||
return nil
|
||||
}
|
||||
|
||||
// pump hands every change so far to every watcher, until none is left.
|
||||
func (s *memState) pump(t *testing.T) {
|
||||
t.Helper()
|
||||
for i := 0; i < 50; i++ {
|
||||
s.mu.Lock()
|
||||
todo := s.pending
|
||||
s.pending = nil
|
||||
s.mu.Unlock()
|
||||
if len(todo) == 0 {
|
||||
return
|
||||
}
|
||||
for _, c := range todo {
|
||||
for _, w := range s.watchers {
|
||||
if err := w.Take(c.key, c.op, c.value, c.rev); err != nil {
|
||||
t.Logf("%s taking %s: %v", w.Node, c.key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, w := range s.watchers {
|
||||
if err := w.Drain(); err != nil && !errors.Is(err, errChanged) {
|
||||
t.Logf("%s applying: %v", w.Node, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Fatal("the state never settled")
|
||||
}
|
||||
|
||||
// clock is a clock a test moves.
|
||||
type clock struct{ now time.Time }
|
||||
|
||||
func (c *clock) Now() time.Time { return c.now }
|
||||
|
||||
// memNode is one node's carrier over its own temporary home and state directory.
|
||||
type memNode struct {
|
||||
*MemoryCarrier
|
||||
notices []map[string]any
|
||||
}
|
||||
|
||||
func newMemNode(t *testing.T, root, name, kind string, state *memState, c *clock) *memNode {
|
||||
t.Helper()
|
||||
n := &memNode{}
|
||||
home := filepath.Join(root, name, "home")
|
||||
stateDir := filepath.Join(root, name, "state")
|
||||
for _, d := range []string{filepath.Join(home, ".claude", "projects"), stateDir} {
|
||||
if err := os.MkdirAll(d, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
n.MemoryCarrier = &MemoryCarrier{Home: home, Node: name, State: stateDir, Kind: kind, Store: state, Now: c.Now,
|
||||
wake: make(chan struct{}, 1),
|
||||
Notify: func(a map[string]any) error { n.notices = append(n.notices, a); return nil }}
|
||||
state.watchers = append(state.watchers, n.MemoryCarrier)
|
||||
return n
|
||||
}
|
||||
|
||||
func (n *memNode) path(project, file string) string {
|
||||
return filepath.Join(n.Home, ".claude", "projects", project, "memory", filepath.FromSlash(file))
|
||||
}
|
||||
|
||||
func (n *memNode) write(t *testing.T, project, file, text string, at time.Time) {
|
||||
t.Helper()
|
||||
p := n.path(project, file)
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(text), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = os.Chtimes(p, at, at)
|
||||
}
|
||||
|
||||
func (n *memNode) read(t *testing.T, project, file string) (string, bool) {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(n.path(project, file))
|
||||
if os.IsNotExist(err) {
|
||||
return "", false
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(raw), true
|
||||
}
|
||||
|
||||
func (n *memNode) look(t *testing.T) {
|
||||
t.Helper()
|
||||
if err := n.Look(); err != nil && !errors.Is(err, errChanged) {
|
||||
t.Fatalf("%s's look: %v", n.Node, err)
|
||||
}
|
||||
}
|
||||
|
||||
// copies is every text kept in the node's copies.
|
||||
func (n *memNode) copies(t *testing.T) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
_ = filepath.WalkDir(n.MemoryCarrier.copies(), func(p string, d os.DirEntry, err error) error {
|
||||
if err == nil && !d.IsDir() {
|
||||
raw, _ := os.ReadFile(p)
|
||||
out = append(out, string(raw))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func holdsText(list []string, s string) bool {
|
||||
for _, x := range list {
|
||||
if x == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const project = "-home-op-projects-novox-hq"
|
||||
|
||||
func twoNodes(t *testing.T) (*memState, *clock, *memNode, *memNode) {
|
||||
state, c := newMemState(), &clock{now: time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)}
|
||||
root := t.TempDir()
|
||||
return state, c, newMemNode(t, root, "g14", HomeOperator, state, c), newMemNode(t, root, "shanks", HomeOperator, state, c)
|
||||
}
|
||||
|
||||
// carried writes a file on g14 and carries it to shanks.
|
||||
func carriedOnBoth(t *testing.T, state *memState, c *clock, a, b *memNode, file, text string) {
|
||||
t.Helper()
|
||||
a.write(t, project, file, text, c.now)
|
||||
a.look(t)
|
||||
state.pump(t)
|
||||
b.look(t)
|
||||
state.pump(t)
|
||||
if got, _ := b.read(t, project, file); got != text {
|
||||
t.Fatalf("not carried to %s: %q", b.Node, got)
|
||||
}
|
||||
}
|
||||
|
||||
// §5, §6: a memory file written on one node appears unchanged on another, at any depth, and is carried once.
|
||||
func TestAMemoryFileWrittenOnOneNodeAppearsUnchangedOnAnother(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
g14.write(t, project, "MEMORY.md", "- [state](state.md) — where things stand\n", c.now)
|
||||
g14.write(t, project, "notes/state.md", "ADR 0343 proposed.\n", c.now)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
for file, want := range map[string]string{"MEMORY.md": "- [state](state.md) — where things stand\n", "notes/state.md": "ADR 0343 proposed.\n"} {
|
||||
if got, ok := shanks.read(t, project, file); !ok || got != want {
|
||||
t.Fatalf("%s on shanks: %q, %v", file, got, ok)
|
||||
}
|
||||
}
|
||||
before := state.rev
|
||||
shanks.look(t)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
if state.rev != before {
|
||||
t.Fatalf("a carried file was carried again: %d changes", state.rev-before)
|
||||
}
|
||||
// A change on shanks comes back to g14, over the version it replaced, which g14 keeps.
|
||||
c.now = c.now.Add(time.Minute)
|
||||
shanks.write(t, project, "notes/state.md", "ADR 0343 accepted.\n", c.now)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
if got, _ := g14.read(t, project, "notes/state.md"); got != "ADR 0343 accepted.\n" {
|
||||
t.Fatalf("the change did not reach g14: %q", got)
|
||||
}
|
||||
if !holdsText(g14.copies(t), "ADR 0343 proposed.\n") {
|
||||
t.Fatal("the version replaced on g14 was not kept")
|
||||
}
|
||||
if len(g14.notices)+len(shanks.notices) != 0 {
|
||||
t.Fatalf("a plain change warned: %v %v", g14.notices, shanks.notices)
|
||||
}
|
||||
// No value in the state is anything but a version of a memory file, and no tool answer carries the text.
|
||||
raw, _ := json.Marshal(g14.Status())
|
||||
if strings.Contains(string(raw), "accepted") {
|
||||
t.Fatalf("the memory tool answered the text: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// §1, §2: only the memory folders are carried; a symbolic link, an oversized file and a secret's shape are not, and are
|
||||
// listed with why.
|
||||
func TestOnlyTheMemoryFoldersAreCarried(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
projectDir := filepath.Join(g14.Home, ".claude", "projects", project)
|
||||
g14.write(t, project, "MEMORY.md", "index\n", c.now)
|
||||
for path, text := range map[string]string{
|
||||
filepath.Join(projectDir, "session.jsonl"): "{}\n",
|
||||
filepath.Join(g14.Home, ".claude", "settings.json"): "{}\n",
|
||||
filepath.Join(g14.Home, ".claude", "history.jsonl"): "{}\n",
|
||||
} {
|
||||
if err := os.WriteFile(path, []byte(text), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
g14.write(t, project, "key.md", "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n", c.now)
|
||||
g14.write(t, project, "url.md", "https://op:hunter2@git.example.org/x\n", c.now)
|
||||
g14.write(t, project, "big.md", strings.Repeat("x", MemoryMostBytes+1), c.now)
|
||||
g14.write(t, project, "hash.md", "head 1fe6ea4ee47379007598e163784dbd7ac50b7f79\n", c.now)
|
||||
outside := filepath.Join(t.TempDir(), "elsewhere.md")
|
||||
_ = os.WriteFile(outside, []byte("not memory\n"), 0o600)
|
||||
if err := os.Symlink(outside, g14.path(project, "link.md")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
for _, file := range []string{"key.md", "url.md", "big.md", "link.md"} {
|
||||
if _, ok := shanks.read(t, project, file); ok {
|
||||
t.Errorf("%s was carried", file)
|
||||
}
|
||||
}
|
||||
for _, file := range []string{"MEMORY.md", "hash.md"} {
|
||||
if _, ok := shanks.read(t, project, file); !ok {
|
||||
t.Errorf("%s was not carried", file)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(shanks.Home, ".claude", "projects", project, "session.jsonl")); err == nil {
|
||||
t.Error("a session was carried")
|
||||
}
|
||||
for _, f := range []string{"settings.json", "history.jsonl"} {
|
||||
if _, err := os.Stat(filepath.Join(shanks.Home, ".claude", f)); err == nil {
|
||||
t.Errorf("%s was carried", f)
|
||||
}
|
||||
}
|
||||
keys, _ := state.Keys()
|
||||
if len(keys) != 2 {
|
||||
t.Fatalf("the state holds %d keys, not the two memory files: %v", len(keys), keys)
|
||||
}
|
||||
not, _ := g14.Status()["not carried"].(map[string]string)
|
||||
for _, file := range []string{"key.md", "url.md", "big.md", "link.md"} {
|
||||
if not[project+"/"+file] == "" {
|
||||
t.Errorf("%s is not listed as not carried: %v", file, not)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// §4: the operator's homes and an agent account's homes never take each other's memory.
|
||||
func TestHomesOfTheTwoKindsNeverTakeEachOthersMemory(t *testing.T) {
|
||||
state, c := newMemState(), &clock{now: time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)}
|
||||
root := t.TempDir()
|
||||
laptop := newMemNode(t, root, "g14", HomeOperator, state, c)
|
||||
control := newMemNode(t, root, "novox", HomeAgent, state, c)
|
||||
control.write(t, project, "MEMORY.md", "from a confined agent\n", c.now)
|
||||
control.look(t)
|
||||
state.pump(t)
|
||||
if _, ok := laptop.read(t, project, "MEMORY.md"); ok {
|
||||
t.Fatal("a confined agent's memory reached the operator's home")
|
||||
}
|
||||
laptop.write(t, project, "MEMORY.md", "the operator's\n", c.now)
|
||||
laptop.look(t)
|
||||
state.pump(t)
|
||||
if got, _ := control.read(t, project, "MEMORY.md"); got != "from a confined agent\n" {
|
||||
t.Fatalf("the operator's memory reached the agent account's home: %q", got)
|
||||
}
|
||||
// A value of the other kind put under this kind's key is refused too.
|
||||
key := MemoryKey(HomeOperator, project, "x.md")
|
||||
raw, _ := json.Marshal(MemoryVersion{Kind: HomeAgent, Project: project, Path: "x.md", Text: "x", Digest: digestOf([]byte("x")), Node: "novox"})
|
||||
if err := laptop.Take(key, "put", raw, 99); err == nil {
|
||||
t.Fatal("a value of another kind was taken")
|
||||
}
|
||||
// Which kind a node carries for.
|
||||
if k, _ := HomeKind(Paths{Agent: "jochen", Operator: "jochen", Home: "/home/jochen"}); k != HomeOperator {
|
||||
t.Fatalf("the operator's own home is %q", k)
|
||||
}
|
||||
if k, _ := HomeKind(Paths{Agent: "agent", Operator: "jochen", Home: "/home/agent", AgentHome: "/home/agent", OperatorHome: "/home/jochen"}); k != HomeAgent {
|
||||
t.Fatalf("an agent account's home is %q", k)
|
||||
}
|
||||
if k, why := HomeKind(Paths{Agent: "agent", Operator: "jochen", Home: "/home/jochen", AgentHome: "/home/agent", OperatorHome: "/home/jochen"}); k != "" || why == "" {
|
||||
t.Fatalf("a confined agent in the operator's home carries %q", k)
|
||||
}
|
||||
}
|
||||
|
||||
// §7, §8: a file changed on two nodes since it was carried is kept twice in one file on both, the newer first, with
|
||||
// one warning; it clears once the file is tidied.
|
||||
func TestAFileChangedOnTwoNodesIsKeptTwiceTheNewerFirstWithAWarning(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "MEMORY.md", "- base\n")
|
||||
g14.write(t, project, "MEMORY.md", "- base\n- learned on g14\n", c.now.Add(time.Minute))
|
||||
shanks.write(t, project, "MEMORY.md", "- base\n- learned on shanks\n", c.now.Add(2*time.Minute))
|
||||
c.now = c.now.Add(3 * time.Minute)
|
||||
g14.look(t)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
g14.look(t)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
a, _ := g14.read(t, project, "MEMORY.md")
|
||||
b, _ := shanks.read(t, project, "MEMORY.md")
|
||||
if a != b {
|
||||
t.Fatalf("the nodes did not end on one text:\n%s\n----\n%s", a, b)
|
||||
}
|
||||
newer, older := strings.Index(a, "learned on shanks"), strings.Index(a, "learned on g14")
|
||||
marker := strings.Index(a, "<!-- novox mesh: this file was changed on two nodes")
|
||||
if newer < 0 || older < 0 || marker < 0 || !(newer < marker && marker < older) {
|
||||
t.Fatalf("not both versions, the newer first, with the line between:\n%s", a)
|
||||
}
|
||||
if !strings.Contains(a[marker:], "changed on shanks") || !strings.Contains(a[marker:], "changed on g14") {
|
||||
t.Fatalf("the line does not name both nodes:\n%s", a)
|
||||
}
|
||||
notices := append(append([]map[string]any{}, g14.notices...), shanks.notices...)
|
||||
if len(notices) != 1 || notices[0]["severity"] != "warning" || notices[0]["clear"] != nil {
|
||||
t.Fatalf("not one warning: %v", notices)
|
||||
}
|
||||
for _, field := range []string{"headline", "explanation", "summary", "resolved"} {
|
||||
s, _ := notices[0][field].(string)
|
||||
if s == "" || strings.ContainsAny(s, "/~:") && field != "explanation" || strings.Contains(s, ".md") {
|
||||
t.Errorf("the warning's %s is empty or names a path: %q", field, s)
|
||||
}
|
||||
// The plain rule (ADR 0253 §3): it never sends the operator elsewhere.
|
||||
if field != "summary" && (strings.Contains(strings.ToLower(s), "agent") || strings.Contains(strings.ToLower(s), "session")) {
|
||||
t.Errorf("the warning's %s sends the operator elsewhere: %q", field, s)
|
||||
}
|
||||
}
|
||||
if e, _ := notices[0]["explanation"].(string); !strings.HasPrefix(e, "Needs you: ") {
|
||||
t.Errorf("the explanation does not open with its verdict: %q", e)
|
||||
}
|
||||
if h, _ := notices[0]["headline"].(string); len([]rune(h)) > 60 {
|
||||
t.Errorf("the headline is longer than sixty characters: %q", h)
|
||||
}
|
||||
all := append(g14.copies(t), shanks.copies(t)...)
|
||||
for _, v := range []string{"- base\n- learned on g14\n", "- base\n- learned on shanks\n"} {
|
||||
if !holdsText(all, v) {
|
||||
t.Errorf("the version %q was not kept", v)
|
||||
}
|
||||
}
|
||||
if st := g14.Status(); len(st["conflicts"].([]conflict))+len(shanks.Status()["conflicts"].([]conflict)) != 1 {
|
||||
t.Fatalf("the conflict is not listed: %v", st)
|
||||
}
|
||||
// Tidied on either node, the warning clears.
|
||||
c.now = c.now.Add(time.Minute)
|
||||
g14.write(t, project, "MEMORY.md", "- base\n- learned on g14\n- learned on shanks\n", c.now)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
cleared := false
|
||||
for _, n := range append(g14.notices, shanks.notices...) {
|
||||
if n["clear"] == true {
|
||||
cleared = true
|
||||
}
|
||||
}
|
||||
if !cleared {
|
||||
t.Fatal("the warning did not clear once the file was tidied")
|
||||
}
|
||||
if got, _ := shanks.read(t, project, "MEMORY.md"); got != "- base\n- learned on g14\n- learned on shanks\n" {
|
||||
t.Fatalf("the tidied file did not reach shanks: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The order of the two versions: the later change first, equal times by node name.
|
||||
func TestMergeVersionsPutsTheNewerFirst(t *testing.T) {
|
||||
at := time.Date(2026, 10, 13, 12, 0, 0, 0, time.UTC)
|
||||
m := string(MergeVersions([]byte("old\n"), "g14", at, []byte("new\n"), "shanks", at.Add(time.Second)))
|
||||
if strings.Index(m, "new") > strings.Index(m, "old") {
|
||||
t.Fatalf("the newer is not first: %s", m)
|
||||
}
|
||||
m = string(MergeVersions([]byte("from shanks\n"), "shanks", at, []byte("from ace\n"), "ace", at))
|
||||
if strings.Index(m, "from ace") > strings.Index(m, "from shanks") {
|
||||
t.Fatalf("equal times are not ordered by node name: %s", m)
|
||||
}
|
||||
}
|
||||
|
||||
// §9: a removal moves the other node's unchanged file into the copies.
|
||||
func TestARemovalMovesTheUnchangedFileIntoTheCopies(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "old.md", "an old note\n")
|
||||
carriedOnBoth(t, state, c, g14, shanks, "MEMORY.md", "index\n")
|
||||
if err := os.Remove(g14.path(project, "old.md")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
if _, ok := shanks.read(t, project, "old.md"); ok {
|
||||
t.Fatal("the removal did not reach shanks")
|
||||
}
|
||||
if !holdsText(shanks.copies(t), "an old note\n") {
|
||||
t.Fatal("the removed version was not kept on shanks")
|
||||
}
|
||||
raw, _, ok, _ := state.Get(MemoryKey(HomeOperator, project, "old.md"))
|
||||
var v MemoryVersion
|
||||
_ = json.Unmarshal(raw, &v)
|
||||
if !ok || !v.Removed || v.Text != "" {
|
||||
t.Fatalf("the removal is not a marker in the state: %s", raw)
|
||||
}
|
||||
if got, _ := shanks.read(t, project, "MEMORY.md"); got != "index\n" {
|
||||
t.Fatal("another file was touched")
|
||||
}
|
||||
}
|
||||
|
||||
// §9: a change outlives a removal, whichever reaches the state first.
|
||||
func TestAChangeOutlivesARemoval(t *testing.T) {
|
||||
for _, removalFirst := range []bool{true, false} {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "note.md", "v1\n")
|
||||
_ = os.Remove(g14.path(project, "note.md"))
|
||||
shanks.write(t, project, "note.md", "v2\n", c.now.Add(time.Minute))
|
||||
if removalFirst {
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
shanks.look(t)
|
||||
} else {
|
||||
shanks.look(t)
|
||||
g14.look(t)
|
||||
}
|
||||
state.pump(t)
|
||||
g14.look(t)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
for _, n := range []*memNode{g14, shanks} {
|
||||
if got, _ := n.read(t, project, "note.md"); got != "v2\n" {
|
||||
t.Fatalf("removal first %v: the change did not outlive the removal on %s: %q", removalFirst, n.Node, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// §9: a missing folder, a state that lost its keys and a deleted key remove nothing.
|
||||
func TestAMissingFolderOrAnAbsentKeyRemovesNothing(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "MEMORY.md", "index\n")
|
||||
key := MemoryKey(HomeOperator, project, "MEMORY.md")
|
||||
// The folder gone on g14.
|
||||
if err := os.RemoveAll(filepath.Join(g14.Home, ".claude", "projects", project, "memory")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
if got, _ := shanks.read(t, project, "MEMORY.md"); got != "index\n" {
|
||||
t.Fatal("a missing folder removed the file elsewhere")
|
||||
}
|
||||
// A deleted key.
|
||||
_ = state.Delete(key)
|
||||
state.pump(t)
|
||||
if got, _ := shanks.read(t, project, "MEMORY.md"); got != "index\n" {
|
||||
t.Fatal("a deleted key removed the file")
|
||||
}
|
||||
// The state lost: the file is carried again, not removed.
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
if _, _, ok, _ := state.Get(key); !ok {
|
||||
t.Fatal("a file whose key the state lost was not carried again")
|
||||
}
|
||||
if got, _ := shanks.read(t, project, "MEMORY.md"); got != "index\n" {
|
||||
t.Fatalf("the file was touched on shanks: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// §10: on a first carrying, two nodes' different versions are both kept, and each node's own files reach the other.
|
||||
func TestTheFirstCarryingKeepsEveryVersion(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
g14.write(t, project, "MEMORY.md", "- laptop's index\n", c.now)
|
||||
g14.write(t, project, "laptop.md", "only on the laptop\n", c.now)
|
||||
shanks.write(t, project, "MEMORY.md", "- workstation's index\n", c.now.Add(time.Hour))
|
||||
shanks.write(t, project, "workstation.md", "only on the workstation\n", c.now)
|
||||
shanks.write(t, project, "same.md", "same\n", c.now)
|
||||
g14.write(t, project, "same.md", "same\n", c.now)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
for _, n := range []*memNode{g14, shanks} {
|
||||
index, _ := n.read(t, project, "MEMORY.md")
|
||||
if !strings.Contains(index, "laptop's index") || !strings.Contains(index, "workstation's index") ||
|
||||
strings.Index(index, "workstation's index") > strings.Index(index, "laptop's index") {
|
||||
t.Fatalf("%s's index does not hold both, the newer first:\n%s", n.Node, index)
|
||||
}
|
||||
for file, want := range map[string]string{"laptop.md": "only on the laptop\n", "workstation.md": "only on the workstation\n", "same.md": "same\n"} {
|
||||
if got, _ := n.read(t, project, file); got != want {
|
||||
t.Fatalf("%s's %s: %q", n.Node, file, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
if n := len(g14.notices) + len(shanks.notices); n != 1 {
|
||||
t.Fatalf("%d warnings for one conflict", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing is written through a symbolic link: a memory folder that is one is neither read nor written.
|
||||
func TestNothingIsWrittenThroughASymbolicLink(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
elsewhere := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(shanks.Home, ".claude", "projects", project), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(elsewhere, filepath.Join(shanks.Home, ".claude", "projects", project, "memory")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g14.write(t, project, "MEMORY.md", "index\n", c.now)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
if entries, _ := os.ReadDir(elsewhere); len(entries) != 0 {
|
||||
t.Fatalf("written through a symbolic link: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
// The manifest declares the state and the tool; the tool reads and never writes.
|
||||
func TestTheManifestDeclaresTheMemoryState(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../module.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m struct {
|
||||
State []string `json:"state"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &m)
|
||||
if !holdsText(m.State, MemoryState) {
|
||||
t.Fatalf("the manifest does not declare the %q state: %v", MemoryState, m.State)
|
||||
}
|
||||
var carrier *MemoryCarrier
|
||||
if st := carrier.Status(); st["carrying"] != false {
|
||||
t.Fatalf("a carrier not started says it carries: %v", st)
|
||||
}
|
||||
}
|
||||
|
||||
// replay hands one node the whole current set, as a watch begins when the node comes back.
|
||||
func (s *memState) replay(t *testing.T, n *memNode) {
|
||||
t.Helper()
|
||||
keys, _ := s.Keys()
|
||||
for _, k := range keys {
|
||||
raw, rev, _, _ := s.Get(k)
|
||||
if err := n.Take(k, "put", raw, rev); err != nil {
|
||||
t.Logf("%s taking %s: %v", n.Node, k, err)
|
||||
}
|
||||
}
|
||||
if err := n.Drain(); err != nil && !errors.Is(err, errChanged) {
|
||||
t.Logf("%s applying: %v", n.Node, err)
|
||||
}
|
||||
}
|
||||
|
||||
// §6: a node that was away while a file changed twice takes the newest version, whose base it never saw, because
|
||||
// its own file holds no change it did not carry; the version replaced is kept.
|
||||
func TestANodeThatWasAwayTakesTheNewestVersion(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "MEMORY.md", "v1\n")
|
||||
state.watchers = []*MemoryCarrier{g14.MemoryCarrier}
|
||||
for _, v := range []string{"v2\n", "v3\n"} {
|
||||
c.now = c.now.Add(time.Minute)
|
||||
g14.write(t, project, "MEMORY.md", v, c.now)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
}
|
||||
state.watchers = append(state.watchers, shanks.MemoryCarrier)
|
||||
state.replay(t, shanks)
|
||||
if got, _ := shanks.read(t, project, "MEMORY.md"); got != "v3\n" {
|
||||
t.Fatalf("the node that was away holds %q", got)
|
||||
}
|
||||
if !holdsText(shanks.copies(t), "v1\n") {
|
||||
t.Fatal("the version replaced was not kept")
|
||||
}
|
||||
if len(g14.notices)+len(shanks.notices) != 0 {
|
||||
t.Fatal("taking a newer version warned")
|
||||
}
|
||||
}
|
||||
|
||||
// §2, §7: two versions too large to share one file are kept in two: the newer in the file, the older beside it,
|
||||
// both carried; and a text that would not fit in one value of the state is not carried.
|
||||
func TestTwoVersionsTooLargeForOneFileAreKeptInTwo(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "big.md", "base\n")
|
||||
older := strings.Repeat("from g14 ", MemoryMostBytes/9-100) + "\n"
|
||||
newer := strings.Repeat("from shanks ", MemoryMostBytes/12-100) + "\n"
|
||||
g14.write(t, project, "big.md", older, c.now.Add(time.Minute))
|
||||
shanks.write(t, project, "big.md", newer, c.now.Add(2*time.Minute))
|
||||
c.now = c.now.Add(3 * time.Minute)
|
||||
g14.look(t)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
g14.look(t)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
beside := OlderBeside("big.md", "g14")
|
||||
if beside != "big.older-from-g14.md" {
|
||||
t.Fatalf("the older is named %q", beside)
|
||||
}
|
||||
for _, n := range []*memNode{g14, shanks} {
|
||||
if got, _ := n.read(t, project, "big.md"); got != newer {
|
||||
t.Fatalf("%s's file does not hold the newer version", n.Node)
|
||||
}
|
||||
if got, _ := n.read(t, project, beside); got != older {
|
||||
t.Fatalf("%s does not hold the older version beside it", n.Node)
|
||||
}
|
||||
}
|
||||
notices := append(append([]map[string]any{}, g14.notices...), shanks.notices...)
|
||||
if len(notices) != 1 || !strings.Contains(notices[0]["explanation"].(string), "second file beside it") {
|
||||
t.Fatalf("not one warning saying the older is beside it: %v", notices)
|
||||
}
|
||||
// Under the size limit, but too large once encoded: not carried, and said.
|
||||
g14.write(t, project, "angles.md", strings.Repeat("<", MemoryMostBytes-10), c.now)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
if _, ok := shanks.read(t, project, "angles.md"); ok {
|
||||
t.Fatal("a text too large for one value was carried")
|
||||
}
|
||||
not, _ := g14.Status()["not carried"].(map[string]string)
|
||||
if not[project+"/angles.md"] == "" {
|
||||
t.Fatalf("it is not listed as not carried: %v", not)
|
||||
}
|
||||
}
|
||||
|
||||
// stateHolds says whether any value of the state holds s.
|
||||
func (s *memState) holds(sub string) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, v := range s.values {
|
||||
var mv MemoryVersion
|
||||
_ = json.Unmarshal(v, &mv)
|
||||
if strings.Contains(mv.Text, sub) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// putRaw puts a value straight into the state, as a holder of a tool runner's credential could.
|
||||
func (s *memState) putRaw(t *testing.T, v MemoryVersion) string {
|
||||
t.Helper()
|
||||
key := MemoryKey(v.Kind, v.Project, v.Path)
|
||||
s.mu.Lock()
|
||||
s.write(key, v)
|
||||
s.mu.Unlock()
|
||||
return key
|
||||
}
|
||||
|
||||
// Review of #276, 1: a value whose project or path leads out of a memory folder is never taken, and nothing is
|
||||
// written for it.
|
||||
func TestAValueLeadingOutOfAMemoryFolderIsNeverTaken(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
root := filepath.Dir(filepath.Dir(shanks.Home))
|
||||
for _, bad := range []struct{ project, path string }{
|
||||
{"../../../escaped", "x.md"}, {"..", "x.md"}, {"a/b", "x.md"}, {"", "x.md"},
|
||||
{project, "../x.md"}, {project, "/abs.md"}, {project, "a//x.md"}, {project, "./x.md"}, {project, "a/../../x.md"},
|
||||
} {
|
||||
text := "planted\n"
|
||||
state.putRaw(t, MemoryVersion{Kind: HomeOperator, Project: bad.project, Path: bad.path, Text: text,
|
||||
Digest: digestOf([]byte(text)), Node: "elsewhere", Changed: c.now})
|
||||
if NameProblem(bad.project, bad.path) == "" {
|
||||
t.Errorf("%q %q is taken as a name", bad.project, bad.path)
|
||||
}
|
||||
}
|
||||
state.pump(t)
|
||||
g14.look(t)
|
||||
shanks.look(t)
|
||||
_ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
|
||||
if err == nil && !d.IsDir() {
|
||||
if raw, _ := os.ReadFile(p); string(raw) == "planted\n" {
|
||||
t.Errorf("a planted value was written at %s", p)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if NameProblem(project, "notes/a.md") != "" || NameProblem(project, "MEMORY.md") != "" {
|
||||
t.Fatal("a memory file's own name is refused")
|
||||
}
|
||||
}
|
||||
|
||||
// Review of #276, 2: a file or a folder that cannot be read is kept everywhere, never carried as a removal, and is
|
||||
// said as not carried.
|
||||
func TestWhatCannotBeReadIsNeverTakenForGone(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("root reads a file whatever its mode")
|
||||
}
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "MEMORY.md", "index\n")
|
||||
carriedOnBoth(t, state, c, g14, shanks, "notes/deep.md", "deep\n")
|
||||
file, folder := g14.path(project, "MEMORY.md"), filepath.Dir(g14.path(project, "notes/deep.md"))
|
||||
_ = os.Chmod(file, 0)
|
||||
_ = os.Chmod(folder, 0)
|
||||
t.Cleanup(func() { _ = os.Chmod(file, 0o644); _ = os.Chmod(folder, 0o755) })
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
for _, f := range []string{"MEMORY.md", "notes/deep.md"} {
|
||||
if _, ok := shanks.read(t, project, f); !ok {
|
||||
t.Errorf("%s, unreadable on g14, was removed on shanks", f)
|
||||
}
|
||||
}
|
||||
not, _ := g14.Status()["not carried"].(map[string]string)
|
||||
if len(not) == 0 {
|
||||
t.Fatalf("nothing is said as not carried: %v", not)
|
||||
}
|
||||
keys, _ := state.Keys()
|
||||
for _, k := range keys {
|
||||
raw, _, _, _ := state.Get(k)
|
||||
var v MemoryVersion
|
||||
_ = json.Unmarshal(raw, &v)
|
||||
if v.Removed {
|
||||
t.Errorf("%s/%s was carried as a removal", v.Project, v.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Review of #276, 3: no text reaches the state without being screened, on the removal and the conflict paths too.
|
||||
func TestNoUnscreenedTextReachesTheState(t *testing.T) {
|
||||
token := "ghp_" + strings.Repeat("A1b2C3d4", 5) + "\n"
|
||||
big := strings.Repeat("x", MemoryMostBytes+10) + "\n"
|
||||
for _, text := range []string{token, big} {
|
||||
// The removal path: removed on g14, changed on shanks to what is never carried.
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "note.md", "v1\n")
|
||||
_ = os.Remove(g14.path(project, "note.md"))
|
||||
shanks.write(t, project, "note.md", text, c.now.Add(time.Minute))
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
if state.holds(text[:20]) {
|
||||
t.Errorf("the removal path put text that is never carried into the state")
|
||||
}
|
||||
if got, _ := shanks.read(t, project, "note.md"); got != text {
|
||||
t.Errorf("the change on shanks was not kept")
|
||||
}
|
||||
// The conflict path: changed on g14, and on shanks to what is never carried.
|
||||
state, c, g14, shanks = twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "note.md", "v1\n")
|
||||
g14.write(t, project, "note.md", "v2\n", c.now.Add(time.Minute))
|
||||
shanks.write(t, project, "note.md", text, c.now.Add(2*time.Minute))
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
if state.holds(text[:20]) {
|
||||
t.Errorf("the conflict path put text that is never carried into the state")
|
||||
}
|
||||
if got, _ := shanks.read(t, project, "note.md"); got != text {
|
||||
t.Errorf("shanks's own version was not kept as it was")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Review of #276, 4: a conflict whose file cannot be written leaves the state as it was, says so once, and merges
|
||||
// once when the folder is writable again.
|
||||
func TestAConflictThatCannotBeWrittenIsNotMergedAgainAndAgain(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("root writes a folder whatever its mode")
|
||||
}
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "MEMORY.md", "base\n")
|
||||
g14.write(t, project, "MEMORY.md", "base\nfrom g14\n", c.now.Add(time.Minute))
|
||||
shanks.write(t, project, "MEMORY.md", "base\nfrom shanks\n", c.now.Add(2*time.Minute))
|
||||
folder := filepath.Dir(shanks.path(project, "MEMORY.md"))
|
||||
_ = os.Chmod(folder, 0o500)
|
||||
t.Cleanup(func() { _ = os.Chmod(folder, 0o700) })
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
for i := 0; i < 5; i++ {
|
||||
_ = shanks.Look()
|
||||
state.pump(t)
|
||||
}
|
||||
if state.holds("<!-- novox mesh") {
|
||||
t.Fatal("a merge that could not be written here reached the state")
|
||||
}
|
||||
unwritten := 0
|
||||
for _, n := range shanks.notices {
|
||||
if strings.HasSuffix(n["key"].(string), ".unwritten") {
|
||||
unwritten++
|
||||
}
|
||||
}
|
||||
if unwritten != 1 {
|
||||
t.Fatalf("%d warnings that the file could not be written", unwritten)
|
||||
}
|
||||
_ = os.Chmod(folder, 0o700)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
for _, n := range []*memNode{g14, shanks} {
|
||||
got, _ := n.read(t, project, "MEMORY.md")
|
||||
if strings.Count(got, "<!-- novox mesh") != 1 || !strings.Contains(got, "from g14") || !strings.Contains(got, "from shanks") {
|
||||
t.Fatalf("%s does not hold both versions once:\n%s", n.Node, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Review of #276, minor: a file that changed between its reading and its writing is not written over; text that is
|
||||
// not UTF-8 is not carried.
|
||||
func TestAFileChangedBeforeItsWritingIsNotWrittenOver(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
_ = state
|
||||
g14.write(t, project, "a.md", "read\n", c.now)
|
||||
g14.write(t, project, "a.md", "changed meanwhile\n", c.now)
|
||||
err := g14.writeLocal(project, "a.md", []byte("incoming\n"), "replaced", digestOf([]byte("read\n")))
|
||||
if !errors.Is(err, errChangedHere) {
|
||||
t.Fatalf("written over a change: %v", err)
|
||||
}
|
||||
if got, _ := g14.read(t, project, "a.md"); got != "changed meanwhile\n" {
|
||||
t.Fatalf("the change was replaced: %q", got)
|
||||
}
|
||||
g14.write(t, project, "latin1.md", "caf\xe9\n", c.now)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
if _, ok := shanks.read(t, project, "latin1.md"); ok {
|
||||
t.Fatal("text that is not UTF-8 was carried")
|
||||
}
|
||||
not, _ := g14.Status()["not carried"].(map[string]string)
|
||||
if !strings.Contains(not[project+"/latin1.md"], "UTF-8") {
|
||||
t.Fatalf("it is not said why: %v", not)
|
||||
}
|
||||
}
|
||||
|
||||
// §9: a node that was away takes a removal of a version newer than the one it holds, when it holds no change of
|
||||
// its own: the removed file does not come back.
|
||||
func TestARemovalReachesANodeThatWasAway(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
carriedOnBoth(t, state, c, g14, shanks, "old.md", "v1\n")
|
||||
state.watchers = []*MemoryCarrier{g14.MemoryCarrier}
|
||||
c.now = c.now.Add(time.Minute)
|
||||
g14.write(t, project, "old.md", "v2\n", c.now)
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
_ = os.Remove(g14.path(project, "old.md"))
|
||||
g14.look(t)
|
||||
state.pump(t)
|
||||
state.watchers = append(state.watchers, shanks.MemoryCarrier)
|
||||
state.replay(t, shanks)
|
||||
shanks.look(t)
|
||||
state.pump(t)
|
||||
g14.look(t)
|
||||
if _, ok := shanks.read(t, project, "old.md"); ok {
|
||||
t.Fatal("the removal did not reach the node that was away")
|
||||
}
|
||||
if _, ok := g14.read(t, project, "old.md"); ok {
|
||||
t.Fatal("the removed file came back")
|
||||
}
|
||||
if !holdsText(shanks.copies(t), "v1\n") {
|
||||
t.Fatal("the version removed on the node that was away was not kept")
|
||||
}
|
||||
}
|
||||
|
||||
// slowState answers every read only once it is let go, as a state a whole bus away does under load.
|
||||
type slowState struct {
|
||||
*memState
|
||||
gate chan struct{}
|
||||
}
|
||||
|
||||
func (s slowState) Get(key string) (json.RawMessage, uint64, bool, error) {
|
||||
<-s.gate
|
||||
return s.memState.Get(key)
|
||||
}
|
||||
|
||||
// Issue 367, seen live: the runtime hands a watch its current values one at a time and gives them all ten seconds;
|
||||
// shanks's handler read the state and waited for its look for each of a few hundred values, so the watch never
|
||||
// started and nothing written on g14 reached it. The handler now only notes a change: it returns at once while a
|
||||
// look holds the carrier and while the state is slow to answer, and Drain applies what it noted.
|
||||
func TestTheWatchHandlerReturnsAtOnceAndDrainAppliesWhatItNoted(t *testing.T) {
|
||||
state, c, g14, shanks := twoNodes(t)
|
||||
g14.write(t, project, "MEMORY.md", "index\n", c.now)
|
||||
g14.look(t)
|
||||
state.mu.Lock()
|
||||
state.pending = nil
|
||||
state.mu.Unlock()
|
||||
slow := slowState{memState: state, gate: make(chan struct{})}
|
||||
shanks.Store = slow
|
||||
key := MemoryKey(HomeOperator, project, "MEMORY.md")
|
||||
raw, rev, _, _ := state.Get(key)
|
||||
shanks.mu.Lock() // a look running
|
||||
done := make(chan error, 1)
|
||||
start := time.Now()
|
||||
for i := 0; i < 400; i++ {
|
||||
go func() { done <- shanks.Take(key, "put", raw, rev) }()
|
||||
}
|
||||
for i := 0; i < 400; i++ {
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("the watch handler waited for the look or the state (%d of 400 returned)", i)
|
||||
}
|
||||
}
|
||||
if took := time.Since(start); took > time.Second {
|
||||
t.Fatalf("400 values took %s to hand over", took)
|
||||
}
|
||||
shanks.mu.Unlock()
|
||||
close(slow.gate)
|
||||
if err := shanks.Drain(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := shanks.read(t, project, "MEMORY.md"); got != "index\n" {
|
||||
t.Fatalf("what the watch noted was not applied: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -124,7 +124,6 @@ func HomeScopeRefused(p Paths, target string) string {
|
||||
func (p Paths) credentials() string { return filepath.Join(p.Home, ".claude", ".credentials.json") }
|
||||
func (p Paths) account() string { return filepath.Join(p.Home, ".claude.json") }
|
||||
func (p Paths) binding() string { return filepath.Join(p.State, "licence.json") }
|
||||
func (p Paths) preferences() string { return filepath.Join(p.State, "preferences.json") }
|
||||
func (p Paths) apiKey() string { return filepath.Join(p.keyDir(), "api-key") }
|
||||
func (p Paths) helper() string { return filepath.Join(p.keyDir(), "api-key-helper") }
|
||||
|
||||
@@ -219,7 +218,6 @@ func RenderNow(p Paths, write WriteManaged) ([]string, error) {
|
||||
}
|
||||
var settings Settings
|
||||
readJSON(p.Settings, &settings)
|
||||
readJSON(p.preferences(), &settings.Preferences)
|
||||
var binding *Binding
|
||||
var b Binding
|
||||
if readJSON(p.binding(), &b) {
|
||||
|
||||
@@ -130,7 +130,7 @@ func proposalTools(p Paths) []stdio.Tool {
|
||||
text, _ = a["content"].(string)
|
||||
}
|
||||
return Propose(p, ProposeInput{Scope: scopeOf(a), Nodes: nodesOf(a["nodes"]), Name: strArg(a, "name"),
|
||||
Text: text, Remove: boolArg(a, "remove")}, proposing.Store, proposing.Bus, proposing.Now())
|
||||
Text: text, Remove: boolArg(a, "remove"), Summary: strArg(a, "summary")}, proposing.Store, proposing.Bus, proposing.Now())
|
||||
}},
|
||||
{Name: "claude_code_proposals",
|
||||
Description: "The instruction sections proposed for the operator's approval (novox/hq ADR 0274), newest first: what " +
|
||||
@@ -164,14 +164,14 @@ func questionTools(p Paths, notLaunched error) []stdio.Tool {
|
||||
"operator's word to you; it authorises no call that needs the operator's approval.",
|
||||
Input: map[string]any{
|
||||
"headline": str("what is decided, in a few plain words, at most 60 characters, e.g. 'Merge the resolver fix tonight?'"),
|
||||
"context": str("what the operator decides and why it matters, in plain words, at most 1500 bytes"),
|
||||
"context": str("what the operator decides and why it matters, in plain words: two or three short sentences, one line, at most 300 characters"),
|
||||
"options": map[string]any{"type": "array", "description": "two to four answers; exactly one recommended",
|
||||
"items": map[string]any{"type": "object", "properties": map[string]any{
|
||||
"label": str("the button's words, at most 24 characters"),
|
||||
"means": str("what you do when it is chosen, in plain words"),
|
||||
"recommended": map[string]any{"type": "boolean", "description": "true on the one you recommend"},
|
||||
}, "required": []string{"label", "means"}}},
|
||||
"why": str("why the recommended option is the one you recommend"),
|
||||
"why": str("why the recommended option is the one you recommend, at most 120 bytes"),
|
||||
"on_expiry": str("what you do if nobody answers before it expires, e.g. 'I leave the pull request open'"),
|
||||
"by": str("required: your session's name, as who@node or who, e.g. fix-589@g14"),
|
||||
"expires_minutes": map[string]any{"type": "integer",
|
||||
|
||||
@@ -104,6 +104,12 @@ type Proposal struct {
|
||||
Digest string `json:"digest"`
|
||||
From string `json:"from"`
|
||||
At time.Time `json:"at"`
|
||||
// Summary is what the operator's phone shows of it, at a glance, in its proposer's words; empty, the module
|
||||
// says what it does (novox/hq issue 639).
|
||||
Summary string `json:"summary,omitempty"`
|
||||
// Form is how its ask is composed, so every node composes the same one again to hold the warrant to it: 0 for
|
||||
// a proposal made before issue 639 (its text in the explanation), AskGlance for one read at a glance.
|
||||
Form int `json:"form,omitempty"`
|
||||
// Asked is empty once the ask was published, or says why it was not; nothing composes from it.
|
||||
Asked string `json:"asked,omitempty"`
|
||||
}
|
||||
@@ -164,9 +170,109 @@ func (p Proposal) Act(option string) asks.Act {
|
||||
"at": p.At.UTC().Format(time.RFC3339Nano)}
|
||||
}
|
||||
|
||||
// AskGlance is the form of an ask read at a glance (Proposal.Form, Question.Form; novox/hq issue 639).
|
||||
const AskGlance = 1
|
||||
|
||||
// Ask is the ask for a proposal, composed from it alone: every node composes the same one, and holds the
|
||||
// router's warrant to it.
|
||||
// router's warrant to it — in the form it was asked in.
|
||||
func (p Proposal) Ask() asks.Ask {
|
||||
if p.Form == AskGlance {
|
||||
return p.glanceAsk()
|
||||
}
|
||||
return p.listedAsk()
|
||||
}
|
||||
|
||||
// glanceAsk is the ask read at a glance on the phone (novox/hq issue 639): its headline, and as its explanation
|
||||
// the summary of what it does; the text, where it came from, its fingerprint and where to read all of it are its
|
||||
// Details, which the router notes after the answers, collapsed where the channel can.
|
||||
func (p Proposal) glanceAsk() asks.Ask {
|
||||
verb := map[string]string{ActionAdd: "Add", ActionReplace: "Replace", ActionRemove: "Remove"}[p.Action]
|
||||
shown, whole := excerpt(p.Text)
|
||||
part := ""
|
||||
if p.Action != ActionRemove && !whole {
|
||||
part = " Part shown"
|
||||
}
|
||||
headline := fmt.Sprintf("%s Claude instructions '%s'?%s", verb, p.Name, part)
|
||||
if len([]rune(headline)) > asks.HeadlineLength {
|
||||
headline = verb + " Claude instructions?" + part
|
||||
}
|
||||
var d strings.Builder
|
||||
if p.Action == ActionRemove {
|
||||
fmt.Fprintf(&d, "Proposed through the claude-code module on %s at %s UTC. The approved text it removes has the fingerprint %s.",
|
||||
p.From, p.At.UTC().Format("15:04 on 2 Jan"), p.Fingerprint())
|
||||
} else {
|
||||
if whole {
|
||||
d.WriteString("The text:\n" + shown + "\n")
|
||||
} else {
|
||||
d.WriteString("NOT SHOWN IN FULL here. Its first lines:\n" + shown + "\n")
|
||||
}
|
||||
fmt.Fprintf(&d, "Proposed through the claude-code module on %s at %s UTC: %d lines, %d bytes, fingerprint %s.",
|
||||
p.From, p.At.UTC().Format("15:04 on 2 Jan"), p.Lines(), len(p.Text), p.Fingerprint())
|
||||
}
|
||||
fmt.Fprintf(&d, "\nRead all of it at the controller's terminal: mesh-cli ask claude-code claude_code_proposals '{\"id\": \"%s\"}'.", p.ID)
|
||||
does := "the text becomes part of those sessions' instructions"
|
||||
if p.Action == ActionRemove {
|
||||
does = "the instructions are removed from those sessions"
|
||||
}
|
||||
return p.withOptions(asks.Ask{ID: p.ID, Headline: headline, Explanation: p.summary(), Details: d.String()}, does)
|
||||
}
|
||||
|
||||
// summary is what the proposal does, at a glance: its proposer's words, or the module's.
|
||||
func (p Proposal) summary() string {
|
||||
if s := strings.TrimSpace(p.Summary); s != "" {
|
||||
return s
|
||||
}
|
||||
lines := fmt.Sprintf("these %d lines", p.Lines())
|
||||
if p.Lines() == 1 {
|
||||
lines = "this line"
|
||||
}
|
||||
where := strings.ToUpper(p.where()[:1]) + p.where()[1:]
|
||||
switch p.Action {
|
||||
case ActionRemove:
|
||||
return fmt.Sprintf("%s stops reading the instructions '%s' from its next start.", where, p.Name)
|
||||
case ActionReplace:
|
||||
return fmt.Sprintf("%s reads %s in place of the instructions '%s', as the mesh's own word, from its next start until "+
|
||||
"they are removed the same way.", where, lines, p.Name)
|
||||
}
|
||||
return fmt.Sprintf("%s reads %s as the mesh's own word, from its next start until they are removed the same way.", where, lines)
|
||||
}
|
||||
|
||||
// SummaryProblem says why a proposer's summary cannot be shown at a glance, or "".
|
||||
func SummaryProblem(summary string) string {
|
||||
switch s := strings.TrimSpace(summary); {
|
||||
case s == "":
|
||||
return ""
|
||||
case strings.Contains(s, "\n"):
|
||||
return "the summary is more than one line"
|
||||
case len([]rune(s)) > asks.SummaryLength:
|
||||
return fmt.Sprintf("the summary is %d characters, more than the %d a phone shows at a glance", len([]rune(s)), asks.SummaryLength)
|
||||
case !shownLine(s):
|
||||
return "the summary names a path, an address, a host name or a long word, which a phone is not shown"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// withOptions is an ask with what every form of it carries: who answers, its expiry, what it is about, and its two
|
||||
// options, each binding its act.
|
||||
func (p Proposal) withOptions(a asks.Ask, does string) asks.Ask {
|
||||
a.Who, a.Expires, a.OnExpiry = asks.Operator, p.At.Add(ProposalLasts), "the proposal is discarded; nothing changes"
|
||||
a.About = "instructions." + p.Scope + "." + strings.Join(p.Nodes, "+") + "." + p.Name
|
||||
if len(p.Nodes) == 0 {
|
||||
a.About = "instructions." + p.Scope + "." + p.Name
|
||||
}
|
||||
for _, o := range []struct{ id, label, does string }{
|
||||
{OptionApprove, "Approve", does},
|
||||
{OptionDecline, "Decline", "nothing changes; the proposal is discarded"},
|
||||
} {
|
||||
binds, _ := asks.ActDigest(p.Act(o.id))
|
||||
a.Options = append(a.Options, asks.Option{ID: o.id, Label: o.label, Does: o.does, Level: asks.Approve, Binds: binds})
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// listedAsk is the ask as it was composed before issue 639, the text in its explanation: composed only to hold the
|
||||
// warrant of a proposal made then.
|
||||
func (p Proposal) listedAsk() asks.Ask {
|
||||
verb := map[string]string{ActionAdd: "Add", ActionReplace: "Replace", ActionRemove: "Remove"}[p.Action]
|
||||
shown, whole := excerpt(p.Text)
|
||||
part := ""
|
||||
@@ -617,6 +723,8 @@ type ProposeInput struct {
|
||||
Name string
|
||||
Text string
|
||||
Remove bool
|
||||
// Summary is what the operator's phone shows of it, in one line (novox/hq issue 639); empty, the module says it.
|
||||
Summary string
|
||||
}
|
||||
|
||||
// AtTheTerminalInstead is the other way, said whenever a proposal is refused for want of a channel.
|
||||
@@ -696,7 +804,11 @@ func Propose(p Paths, in ProposeInput, store ProposalStore, bus AskBus, now time
|
||||
return nil, err
|
||||
}
|
||||
active, isActive := approved.Sections[sectionKey(in.Scope, nodes, in.Name)]
|
||||
prop := Proposal{ID: newProposalID(), Scope: in.Scope, Nodes: nodes, Name: in.Name, From: p.Node, At: now.UTC()}
|
||||
if problem := SummaryProblem(in.Summary); problem != "" {
|
||||
return refuse(problem)
|
||||
}
|
||||
prop := Proposal{ID: newProposalID(), Scope: in.Scope, Nodes: nodes, Name: in.Name, From: p.Node, At: now.UTC(),
|
||||
Summary: strings.TrimSpace(in.Summary), Form: AskGlance}
|
||||
switch {
|
||||
case in.Remove:
|
||||
if !isActive {
|
||||
|
||||
@@ -147,14 +147,17 @@ func TestAProposalAsksTheOperatorAtTheLevelApproveAndChangesNothing(t *testing.T
|
||||
if err := a.Check(t0); err != nil {
|
||||
t.Fatalf("the router would refuse the ask: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(a.Explanation, "Add instructions 'handoff-from-g14' to every Claude session on the mesh?") {
|
||||
t.Errorf("the phone does not say what is asked first: %q", a.Explanation)
|
||||
// At a glance (issue 639): what it does is the explanation, one line; the text is the Details, which the
|
||||
// router notes collapsed after the answers.
|
||||
if a.Explanation != "Every Claude session on the mesh reads these 4 lines as the mesh's own word, from its next start until they are removed the same way." ||
|
||||
asks.Glance(a.Explanation) != nil {
|
||||
t.Errorf("the phone does not say what is asked at a glance: %q", a.Explanation)
|
||||
}
|
||||
if a.Headline != "Add Claude instructions 'handoff-from-g14'?" {
|
||||
t.Errorf("headline: %q", a.Headline)
|
||||
}
|
||||
if !strings.Contains(a.Explanation, "The whole text:\n\n"+strings.TrimRight(handover, "\n")) {
|
||||
t.Errorf("a short text is shown whole: %q", a.Explanation)
|
||||
if !strings.HasPrefix(a.Details, "The text:\n"+strings.TrimRight(handover, "\n")+"\nProposed through the claude-code module on g14 at ") {
|
||||
t.Errorf("a short text is not shown whole: %q", a.Details)
|
||||
}
|
||||
if len(a.Options) != 2 {
|
||||
t.Fatalf("options: %+v", a.Options)
|
||||
@@ -294,7 +297,7 @@ func TestARemovalNeedsTheSameApprovalAndARecordDeletedRemovesNothing(t *testing.
|
||||
t.Fatal(err)
|
||||
}
|
||||
rid := out["proposed"].(string)
|
||||
if !strings.HasPrefix(r.published[rid].Explanation, "Remove the instructions 'handoff-from-g14' from every Claude session on the mesh?") {
|
||||
if r.published[rid].Explanation != "Every Claude session on the mesh stops reading the instructions 'handoff-from-g14' from its next start." {
|
||||
t.Errorf("removal ask: %q", r.published[rid].Explanation)
|
||||
}
|
||||
if !strings.Contains(renderedInstructions(t, p), "### handoff-from-g14") {
|
||||
@@ -326,7 +329,7 @@ func TestANodeScopedSectionReachesOnlyItsNodes(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := out["proposed"].(string)
|
||||
if !strings.HasPrefix(r.published[id].Explanation, "Add instructions 'builds' to every Claude session on shanks?") {
|
||||
if !strings.HasPrefix(r.published[id].Explanation, "Every Claude session on shanks reads this line as the mesh's own word") {
|
||||
t.Errorf("%q", r.published[id].Explanation)
|
||||
}
|
||||
r.close(r.chose(id, OptionApprove, t0.Add(time.Hour)))
|
||||
@@ -417,15 +420,16 @@ func TestALongTextIsShownInPartAndReadWholeAtTheTerminal(t *testing.T) {
|
||||
}
|
||||
id := out["proposed"].(string)
|
||||
a := r.published[id]
|
||||
if strings.Contains(a.Explanation, "/etc/claude-code") || !strings.Contains(a.Explanation, "[1 line(s) not shown here") {
|
||||
t.Errorf("a line with a path was shown: %q", a.Explanation)
|
||||
if strings.Contains(a.Details, "/etc/claude-code") || !strings.Contains(a.Details, "[1 line(s) not shown here") ||
|
||||
!strings.HasPrefix(a.Details, "NOT SHOWN IN FULL here.") || !strings.HasSuffix(a.Headline, "Part shown") {
|
||||
t.Errorf("a line with a path was shown, or the cut not said: %q", a.Details)
|
||||
}
|
||||
if !strings.Contains(a.Explanation, "mesh-cli ask claude-code claude_code_proposals") ||
|
||||
!strings.Contains(a.Explanation, "fingerprint there must be "+out["fingerprint"].(string)) {
|
||||
t.Errorf("the phone does not say where to read all of it: %q", a.Explanation)
|
||||
if !strings.Contains(a.Details, "mesh-cli ask claude-code claude_code_proposals") ||
|
||||
!strings.Contains(a.Details, "fingerprint "+out["fingerprint"].(string)) {
|
||||
t.Errorf("the phone does not say where to read all of it: %q", a.Details)
|
||||
}
|
||||
if len(a.Explanation) > 3000 {
|
||||
t.Errorf("the explanation is %d bytes", len(a.Explanation))
|
||||
if len(a.Details) > 3000 || asks.Glance(a.Explanation) != nil {
|
||||
t.Errorf("the details are %d bytes; the explanation %q", len(a.Details), a.Explanation)
|
||||
}
|
||||
list, err := ListProposals(p, store, r, id, t0)
|
||||
if err != nil {
|
||||
@@ -739,3 +743,33 @@ func TestAnAskTakenAfterItsRefusalIsStillAnswered(t *testing.T) {
|
||||
t.Errorf("decided %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A proposer's summary is the explanation, held to a glance; a proposal made before issue 639 is composed as it was
|
||||
// asked, so the warrant for it still holds after the change.
|
||||
func TestAProposalIsAskedAtAGlanceAndAnOlderOneAsItWasAsked(t *testing.T) {
|
||||
p, _ := node(t, "g14")
|
||||
store, r := &memProposals{m: map[string]json.RawMessage{}}, newRouter()
|
||||
out, err := Propose(p, ProposeInput{Scope: ScopeMesh, Name: "handoff-from-g14", Text: handover,
|
||||
Summary: "Every session learns how hand-overs are written, so the next one reads them the same way."}, store, r, t0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := out["proposed"].(string)
|
||||
a := r.published[id]
|
||||
if a.Explanation != "Every session learns how hand-overs are written, so the next one reads them the same way." {
|
||||
t.Errorf("the proposer's summary is not the explanation: %q", a.Explanation)
|
||||
}
|
||||
for _, bad := range []string{strings.Repeat("word ", 70), "one\ntwo", "Read it in /etc/claude-code first."} {
|
||||
if _, err := Propose(p, ProposeInput{Scope: ScopeMesh, Name: "other", Text: handover, Summary: bad}, store, r, t0); err == nil ||
|
||||
!strings.Contains(err.Error(), "the summary") {
|
||||
t.Errorf("the summary %q was taken: %v", bad, err)
|
||||
}
|
||||
}
|
||||
prop, _ := readProposal(store, id)
|
||||
older := prop
|
||||
older.Form = 0
|
||||
listed := older.Ask()
|
||||
if !strings.Contains(listed.Explanation, "The whole text:") || listed.Details != "" || listed.Digest() == prop.Ask().Digest() {
|
||||
t.Errorf("a proposal made before is not composed as it was asked: %q", listed.Explanation)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,9 +69,9 @@ const (
|
||||
// The bounds of what a question says.
|
||||
const (
|
||||
FewestQuestionOptions = 2
|
||||
MostContextBytes = 1500
|
||||
MostContextBytes = asks.SummaryLength
|
||||
MostMeansBytes = 200
|
||||
MostWhyBytes = 300
|
||||
MostWhyBytes = 120
|
||||
MostOnExpiryBytes = 200
|
||||
)
|
||||
|
||||
@@ -131,6 +131,8 @@ type Question struct {
|
||||
From string `json:"from"`
|
||||
At time.Time `json:"at"`
|
||||
Expires time.Time `json:"expires"`
|
||||
// Form is how its ask is composed (AskGlance since novox/hq issue 639), so the answer is held to the ask asked.
|
||||
Form int `json:"form,omitempty"`
|
||||
// Asked is empty once the ask was published, or says why it was not; nothing composes from it.
|
||||
Asked string `json:"asked,omitempty"`
|
||||
// Ended is the router's word that the ask ended without a choice, as heard on the decided subject: a refused ask
|
||||
@@ -160,8 +162,41 @@ func (q Question) Act(option string) asks.Act {
|
||||
return act
|
||||
}
|
||||
|
||||
// Ask is the ask for a question, composed from it alone.
|
||||
// Ask is the ask for a question, composed from it alone, in the form it was asked in.
|
||||
func (q Question) Ask() asks.Ask {
|
||||
if q.Form == AskGlance {
|
||||
return q.glanceAsk()
|
||||
}
|
||||
return q.listedAsk()
|
||||
}
|
||||
|
||||
// glanceAsk is the question read at a glance on the phone (novox/hq issue 639): its context, then the recommended
|
||||
// answer and why as its one point; who asked and what the answer does are its Details.
|
||||
func (q Question) glanceAsk() asks.Ask {
|
||||
explanation := strings.TrimSpace(q.Context)
|
||||
if rec, ok := q.recommended(); ok {
|
||||
explanation += fmt.Sprintf("\n• Recommended: %s, because %s.", rec.Label, strings.TrimRight(strings.TrimSpace(q.Why), "."))
|
||||
}
|
||||
details := fmt.Sprintf("Asked by the agent session %s on %s through the claude-code module, at %s UTC. Your answer is told "+
|
||||
"to that session; it performs nothing by itself.", q.By, q.From, q.At.UTC().Format("15:04 on 2 Jan"))
|
||||
return q.withOptions(asks.Ask{ID: q.ID, Headline: q.Headline, Explanation: explanation, Details: details})
|
||||
}
|
||||
|
||||
func (q Question) withOptions(a asks.Ask) asks.Ask {
|
||||
a.Who, a.Expires, a.OnExpiry = asks.Operator, q.Expires, q.OnExpiry
|
||||
for _, o := range q.Options {
|
||||
does := o.Means
|
||||
if o.Recommended {
|
||||
does = "Recommended. " + does
|
||||
}
|
||||
binds, _ := asks.ActDigest(q.Act(o.ID))
|
||||
a.Options = append(a.Options, asks.Option{ID: o.ID, Label: o.Label, Does: does, Level: asks.Approve, Binds: binds})
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// listedAsk is the ask as it was composed before issue 639: composed only to hold the answer to a question asked then.
|
||||
func (q Question) listedAsk() asks.Ask {
|
||||
var b strings.Builder
|
||||
b.WriteString(strings.TrimSpace(q.Context))
|
||||
if rec, ok := q.recommended(); ok {
|
||||
@@ -199,8 +234,10 @@ func QuestionProblem(q Question) string {
|
||||
switch {
|
||||
case strings.TrimSpace(q.Context) == "":
|
||||
add("it gives no context: say in plain words what the operator decides and why it matters")
|
||||
case len(q.Context) > MostContextBytes:
|
||||
add("its context is %d bytes, more than the %d a phone shows in one glance", len(q.Context), MostContextBytes)
|
||||
case len([]rune(q.Context)) > MostContextBytes:
|
||||
add("its context is %d characters, more than the %d a phone shows in one glance", len([]rune(q.Context)), MostContextBytes)
|
||||
case strings.Contains(strings.TrimSpace(q.Context), "\n"):
|
||||
add("its context is more than one line: a phone shows it at a glance as one short paragraph")
|
||||
}
|
||||
if n := len(q.Options); n < FewestQuestionOptions || n > asks.MostOptions {
|
||||
add("it offers %d options; a question offers %d to %d", n, FewestQuestionOptions, asks.MostOptions)
|
||||
@@ -322,7 +359,7 @@ func AskQuestion(p Paths, in QuestionInput, store QuestionStore, bus AskBus, now
|
||||
}
|
||||
q := Question{ID: newQuestionID(), Headline: strings.TrimSpace(in.Headline), Context: strings.TrimSpace(in.Context),
|
||||
Why: strings.TrimSpace(in.Why), OnExpiry: strings.TrimSpace(in.OnExpiry), By: by, From: p.Node, At: now.UTC(),
|
||||
Expires: now.UTC().Add(life)}
|
||||
Expires: now.UTC().Add(life), Form: AskGlance}
|
||||
for i, o := range in.Options {
|
||||
q.Options = append(q.Options, QuestionOption{ID: fmt.Sprintf("o%d", i+1), Label: strings.TrimSpace(o.Label),
|
||||
Means: strings.TrimSpace(o.Means), Recommended: o.Recommended})
|
||||
|
||||
@@ -68,10 +68,13 @@ func TestAQuestionIsAskedUnderTheModulesNameAtTheLevelApprove(t *testing.T) {
|
||||
if !strings.HasPrefix(a.Options[0].Does, "Recommended. ") || strings.HasPrefix(a.Options[1].Does, "Recommended") {
|
||||
t.Errorf("the recommendation is not on the recommended option alone: %+v", a.Options)
|
||||
}
|
||||
for _, want := range []string{"Recommended: Merge now, because it is reviewed and the checks are green.",
|
||||
"the agent session fix-589 on g14", "performs nothing by itself"} {
|
||||
if !strings.Contains(a.Explanation, want) {
|
||||
t.Errorf("the explanation does not say %q:\n%s", want, a.Explanation)
|
||||
// At a glance (issue 639): the context and the recommendation are the explanation; who asks is the Details.
|
||||
if !strings.HasSuffix(a.Explanation, "\n• Recommended: Merge now, because it is reviewed and the checks are green.") || asks.Glance(a.Explanation) != nil {
|
||||
t.Errorf("the explanation does not read at a glance:\n%s", a.Explanation)
|
||||
}
|
||||
for _, want := range []string{"the agent session fix-589 on g14", "performs nothing by itself"} {
|
||||
if !strings.Contains(a.Details, want) || strings.Contains(a.Explanation, want) {
|
||||
t.Errorf("the details do not say %q:\n%s", want, a.Details)
|
||||
}
|
||||
}
|
||||
if err := a.Check(t0); err != nil {
|
||||
|
||||
@@ -42,15 +42,6 @@ type Settings struct {
|
||||
MCPServers map[string]map[string]any `json:"mcp_servers"`
|
||||
// ManagedSettings are keys of the agent's managed settings the operator sets, for the mesh or a node.
|
||||
ManagedSettings map[string]any `json:"managed_settings"`
|
||||
// Preferences are this module's own preferences, from its untrusted preferences file: set in one call
|
||||
// with the controller's `settings` verb, for the mesh or a node, like any module's preference (ADR 0262).
|
||||
Preferences Preferences `json:"-"`
|
||||
}
|
||||
|
||||
// Preferences are the module's preferences as the mesh filled them; nil is a value the file did not carry.
|
||||
type Preferences struct {
|
||||
// Tips is whether Claude Code shows a tip while it works (`spinnerTipsEnabled`).
|
||||
Tips *bool `json:"tips"`
|
||||
}
|
||||
|
||||
// Binding is the licence this node holds, as it was last applied.
|
||||
@@ -130,11 +121,6 @@ func RenderWithMesh(facts Facts, settings Settings, binding *Binding, helperPath
|
||||
// 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).
|
||||
managed := mergeSettings(map[string]any{}, settings.ManagedSettings)
|
||||
// The module's preferences: keys of how a session looks, never of what it may do, so they are set in one
|
||||
// call through the controller rather than at the terminal, and laid over the operator's keys of the same name.
|
||||
if settings.Preferences.Tips != nil {
|
||||
managed["spinnerTipsEnabled"] = *settings.Preferences.Tips
|
||||
}
|
||||
// The mesh's own keys are laid last: a setting never replaces them.
|
||||
managed["attribution"] = map[string]any{"commit": "", "pr": ""}
|
||||
managed["allowAllClaudeAiMcps"] = true
|
||||
|
||||
@@ -2,6 +2,6 @@ module claude-code
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.11-0.20261009143344-f047d0a4a970
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.7 h1:C0sTQmtTiyYH7bnqZb7PusXnqA37gKuT7Nqjn9gG47w=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.7/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.11-0.20261009143344-f047d0a4a970 h1:9tFDQsgmI+4X7/BpZGXIr+HemPKE7YddYGqWV0lINAI=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.11-0.20261009143344-f047d0a4a970/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.13 h1:Su4JYpZ+zhNovkGA2DgxiZdcuHpjw2tPJzc/7PljhXg=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.13/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013141520-9588871d6629 h1:7TYFV1Q6Mcz+lsLP/sds87tysET4rKCn3rRIQV8gNmA=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013141520-9588871d6629/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013145622-f4745447ba6d h1:HEJyqorKktrkJPeeJdwEo0kdrJjH3fm/YVS9MGftCqY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013145622-f4745447ba6d/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44 h1:r5xIo5qWOXQdCSMxvqJy8kV4U+P/QWXFK6971Ha6wU8=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
{
|
||||
"module": "claude-code",
|
||||
"version": "1",
|
||||
"settings": {
|
||||
"tips": {
|
||||
"kind": "preference",
|
||||
"default": true,
|
||||
"why": "Claude Code shows a tip while it works; false turns tips off in every session on the machine, written as spinnerTipsEnabled in its managed settings"
|
||||
}
|
||||
},
|
||||
"slug": "agent",
|
||||
"capabilities": [
|
||||
"package-manager"
|
||||
@@ -26,7 +19,8 @@
|
||||
"holdings",
|
||||
"config",
|
||||
"proposals",
|
||||
"questions"
|
||||
"questions",
|
||||
"memory"
|
||||
],
|
||||
"reads": [
|
||||
"claude-licence-manager.bindings"
|
||||
@@ -39,6 +33,7 @@
|
||||
"claude_code_grant",
|
||||
"claude_code_add_api_key",
|
||||
"claude_code_registrations",
|
||||
"claude_code_memory",
|
||||
"claude_code_mcp_list",
|
||||
"claude_code_mcp_register",
|
||||
"claude_code_mcp_unregister",
|
||||
@@ -153,15 +148,6 @@
|
||||
"owner": "${machine:account}",
|
||||
"merge": "json",
|
||||
"content": "{\n \"role\": \"\",\n \"mcp_servers\": {},\n \"managed_settings\": {},\n \"instructions\": {},\n \"output_styles\": {},\n \"skills\": {},\n \"commands\": {},\n \"agents\": {}\n}\n"
|
||||
},
|
||||
{
|
||||
"id": "preferences",
|
||||
"trusted": false,
|
||||
"type": "file",
|
||||
"path": "${dir:state}/preferences.json",
|
||||
"mode": "0600",
|
||||
"owner": "${machine:account}",
|
||||
"content": "{\n \"tips\": ${setting:tips}\n}\n"
|
||||
}
|
||||
],
|
||||
"shell": [
|
||||
|
||||
@@ -233,7 +233,13 @@ func (d *Desk) show(machine string, m asks.Message, replace int) (int, error) {
|
||||
case m.Silent:
|
||||
urgency = "low"
|
||||
}
|
||||
args := map[string]any{"summary": m.Title, "body": html.EscapeString(m.Body), "urgency": urgency, "app_name": "mesh"}
|
||||
// The note — who asked, what each answer does, the expiry — follows the body after a blank line: a
|
||||
// notification has no smaller text, and the note is never left out (novox/hq issue 639).
|
||||
text := strings.TrimSpace(m.Body)
|
||||
if note := strings.TrimSpace(m.Note); note != "" {
|
||||
text = strings.TrimSpace(text + "\n\n" + note)
|
||||
}
|
||||
args := map[string]any{"summary": m.Title, "body": html.EscapeString(text), "urgency": urgency, "app_name": "mesh"}
|
||||
if replace != 0 {
|
||||
args["replace_id"] = replace
|
||||
}
|
||||
|
||||
@@ -103,6 +103,16 @@ func TestAClickOnAMachineTheMessageWasShownOnIsSaidToTheRouter(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The note follows the body after a blank line: the desk has no smaller text, and leaves nothing out (issue 639).
|
||||
func TestTheNoteFollowsTheBody(t *testing.T) {
|
||||
d, shown, _, _ := newDesk(t, "laptop")
|
||||
take(t, d, asks.Show, asks.Message{Handle: "m1", Title: "q", Body: "The summary.", Note: "Asked by mesh-knowledge at 16:05.",
|
||||
Buttons: []asks.Button{{Label: "Silence for a week", Ticket: "t1"}}})
|
||||
if last := (*shown)[len(*shown)-1]; last.args["body"] != "The summary.\n\nAsked by mesh-knowledge at 16:05." {
|
||||
t.Errorf("the body: %q", last.args["body"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnEditReplacesTheNotification(t *testing.T) {
|
||||
d, shown, _, _ := newDesk(t, "laptop")
|
||||
take(t, d, asks.Show, asks.Message{Handle: "m1", Title: "q", Buttons: []asks.Button{{Label: "Silence for a week", Ticket: "t1"}}})
|
||||
|
||||
@@ -2,4 +2,4 @@ module deskchannel
|
||||
|
||||
go 1.22
|
||||
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.10
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44
|
||||
|
||||
@@ -1,2 +1,8 @@
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.10 h1:EHhnPRrkw7/CSQAqRsxYnTvlTZ3dI02IPO6WSmVX80o=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.10/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013141520-9588871d6629 h1:7TYFV1Q6Mcz+lsLP/sds87tysET4rKCn3rRIQV8gNmA=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013141520-9588871d6629/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013145622-f4745447ba6d h1:HEJyqorKktrkJPeeJdwEo0kdrJjH3fm/YVS9MGftCqY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013145622-f4745447ba6d/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44 h1:r5xIo5qWOXQdCSMxvqJy8kV4U+P/QWXFK6971Ha6wU8=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
|
||||
@@ -4,6 +4,13 @@ The forge, and the mesh's npm package registry: it claims the `git` and `npm-pac
|
||||
Its tools, its events and the provisioner of registry accounts are the TypeScript bundle (`index.ts`,
|
||||
`tools/`, `provisioner/`). This README covers the two Go bundles beside it.
|
||||
|
||||
**What a registry consumer is told** (`serves.npm-package-registry`): where the registry answers on the
|
||||
private network (`scheme`, `port`, `npm-path`), and its `public-root`, the address the forge writes every
|
||||
tarball at: `https://` and the forge's route's composed public name, under the npm path
|
||||
(`${bound:route:name-web}`, novox/hq ADR 0346). A lock file holds that address, and npm 12 installs a
|
||||
locked tarball only from the registry it is configured with, so a consumer that installs from lock files
|
||||
trusts that root. On a machine with no public domain the key is left out, and the plan says so.
|
||||
|
||||
## Announcing pull requests to the merge check (novox/hq to-be 45 §9, issue 347)
|
||||
|
||||
Every new head of an open pull request is announced as `pull.updated`, once, and the controller has it checked.
|
||||
|
||||
+121
-5
@@ -101,6 +101,92 @@ export interface OpenPull {
|
||||
/** The head's statuses by context, the newest of each, with its state (novox/hq issue 438): what tells a check
|
||||
* that started and never answered — pending — from one that answered. */
|
||||
checks: Record<string, HeadCheck>;
|
||||
/** The pull request's labels, by name. */
|
||||
labels?: string[];
|
||||
/** Its ready mark (novox/hq issue 722): the label `mesh/ready` and the newest comment "ready at <full head sha>", the
|
||||
* head a reviewer approved. Absent without the label; `head` empty when the label names no head in a comment. */
|
||||
ready?: ReadyMark;
|
||||
}
|
||||
|
||||
/** The label that marks a pull request ready to merge at the head a comment names (novox/hq issue 722). */
|
||||
export const READY_LABEL = "mesh/ready";
|
||||
|
||||
/** A comment that names the head a pull request is marked ready at: "ready at <full sha>", on a line of its own. */
|
||||
const READY_AT = /^\s*ready at ([0-9a-f]{40}|[0-9a-f]{64})\b/im;
|
||||
|
||||
/** A pull request's ready mark: the head it names, who said it and when, and the label's id, to take it off. */
|
||||
export interface ReadyMark {
|
||||
head: string;
|
||||
by?: string;
|
||||
at?: string;
|
||||
label_id: number;
|
||||
}
|
||||
|
||||
/** **The accounts whose "ready at" comment counts** (novox/hq issue 722): the trusted setting ready-authors, which
|
||||
* the mesh writes to the file MESH_GITEA_READY_AUTHORS_FILE names as a line `authors=<account> <account> …`. A file
|
||||
* that cannot be read leaves the mesh's own forge account alone, said; never an empty list read as everyone. */
|
||||
export function readyAuthors(file = process.env.MESH_GITEA_READY_AUTHORS_FILE, own = process.env.MESH_GITEA_ADMIN_USER,
|
||||
read: (f: string) => string = (f) => readFileSync(f, "utf8")): string[] {
|
||||
const fallback = own ? [own] : [];
|
||||
if (!file) return fallback;
|
||||
try {
|
||||
const line = read(file).split("\n").find((l) => l.startsWith("authors="));
|
||||
const authors = (line ?? "").slice("authors=".length).split(/[\s,]+/).filter(Boolean);
|
||||
if (authors.length) return authors;
|
||||
console.error(`[gitea] ${file} names no account that may mark a pull request ready; only ${fallback.join(", ") || "none"} may`);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${file} cannot be read (${err instanceof Error ? err.message : err}); only ` +
|
||||
`${fallback.join(", ") || "none"} may mark a pull request ready`);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** One event of an issue's or pull request's timeline, as the forge keeps it, oldest first: a comment, a push to a
|
||||
* pull request's branch (`pull_push`), a label added (body "1") or taken off (body ""), and the rest. */
|
||||
export interface TimelineEvent {
|
||||
id: number;
|
||||
type: string;
|
||||
body: string;
|
||||
created_at?: string;
|
||||
user?: string;
|
||||
label?: { id: number; name: string };
|
||||
}
|
||||
|
||||
/** The comments that wrote "ready at" without counting, by id: each said once in the log (novox/hq issue 722). */
|
||||
const ignoredSaid = new Set<number>();
|
||||
|
||||
/** **The ready mark a pull request's timeline makes** (novox/hq issue 722), read in the forge's order — every event is
|
||||
* one row of one table, numbered as it happened, so the order is exact where times share a second. A "ready at"
|
||||
* comment counts only when its author is one of the accounts given, and only when it was written after the label
|
||||
* mesh/ready was last added and after the last push to the pull request's branch: a push or the label taken off
|
||||
* undoes every mark before it, so a mark older than the latest push never counts, even with the label still on. A
|
||||
* comment by any other account is ignored, and said once. */
|
||||
export function readyMarkOf(labelID: number, events: TimelineEvent[], authors: string[],
|
||||
say: (line: string) => void = (l) => console.error(l)): ReadyMark {
|
||||
const listed = new Set(authors.map((a) => a.toLowerCase()));
|
||||
let labelled = false;
|
||||
let mark: ReadyMark | undefined;
|
||||
for (const e of [...events].sort((x, y) => x.id - y.id)) {
|
||||
if (e.type === "pull_push") {
|
||||
mark = undefined;
|
||||
} else if (e.type === "label" && e.label?.name === READY_LABEL) {
|
||||
labelled = e.body === "1";
|
||||
mark = undefined;
|
||||
} else if (e.type === "comment") {
|
||||
const m = READY_AT.exec(e.body);
|
||||
if (!m) continue;
|
||||
if (!listed.has(String(e.user ?? "").toLowerCase())) {
|
||||
if (!ignoredSaid.has(e.id)) {
|
||||
ignoredSaid.add(e.id);
|
||||
say(`[gitea] a "ready at ${m[1].slice(0, 12)}" comment (${e.id}) by ${e.user ?? "an unknown account"} is ignored: ` +
|
||||
`only ${authors.join(", ") || "no account"} may mark a pull request ready (novox/hq issue 722)`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (labelled) mark = { head: m[1].toLowerCase(), by: e.user, at: e.created_at, label_id: labelID };
|
||||
}
|
||||
}
|
||||
return mark ?? { head: "", label_id: labelID };
|
||||
}
|
||||
|
||||
/** One status on a head, the newest of its context: its state, what it said, and when it was set. */
|
||||
@@ -332,8 +418,9 @@ export class GiteaClient {
|
||||
|
||||
/** The open pull requests of every repository the mesh's account sees, updated since a moment when one is given,
|
||||
* page by page (novox/hq issue 347): each with its repository and its own update time. */
|
||||
async searchOpenPulls(since?: string): Promise<{ owner: string; name: string; number: number; updated_at?: string }[]> {
|
||||
const out: { owner: string; name: string; number: number; updated_at?: string }[] = [];
|
||||
async searchOpenPulls(since?: string): Promise<{ owner: string; name: string; number: number; updated_at?: string;
|
||||
labels?: { id: number; name: string }[] }[]> {
|
||||
const out: { owner: string; name: string; number: number; updated_at?: string; labels?: { id: number; name: string }[] }[] = [];
|
||||
for (let page = 1; page <= 20; page++) {
|
||||
const qs = new URLSearchParams({ type: "pulls", state: "open", limit: "50", page: String(page) });
|
||||
if (since) qs.set("since", since);
|
||||
@@ -343,7 +430,8 @@ export class GiteaClient {
|
||||
const [fo, fn] = String(r.full_name ?? "").split("/");
|
||||
const owner = String(r.owner ?? fo ?? "");
|
||||
const name = String(r.name ?? fn ?? "");
|
||||
if (owner && name && i?.number) out.push({ owner, name, number: Number(i.number), updated_at: i.updated_at });
|
||||
const labels = (Array.isArray(i?.labels) ? i.labels : []).map((l: any) => ({ id: Number(l?.id ?? 0), name: String(l?.name ?? "") }));
|
||||
if (owner && name && i?.number) out.push({ owner, name, number: Number(i.number), updated_at: i.updated_at, labels });
|
||||
}
|
||||
if (!found || found.length < 50) break;
|
||||
}
|
||||
@@ -354,7 +442,7 @@ export class GiteaClient {
|
||||
* requires and the contexts its head has a status of, in any state. What mesh-delivery reads to say a pull
|
||||
* request the mesh was never asked to check; asked of the forge, never of what the announcer remembers, so a
|
||||
* fault in the announcer cannot hide itself. Reads only. */
|
||||
async openPulls(): Promise<OpenPull[]> {
|
||||
async openPulls(readyAuthors: string[] = []): Promise<OpenPull[]> {
|
||||
const out: OpenPull[] = [];
|
||||
const rules = new Map<string, BranchProtection[] | undefined>();
|
||||
for (const found of await this.searchOpenPulls()) {
|
||||
@@ -364,9 +452,14 @@ export class GiteaClient {
|
||||
if (!rules.has(full)) rules.set(full, await this.branchProtections(found.owner, found.name).catch(() => undefined));
|
||||
const rule = rules.get(full)?.find((p) => (p.rule_name ?? p.branch_name) === (pull.base || "main"));
|
||||
const checks = await this.headChecks(found.owner, found.name, pull.head_sha);
|
||||
const labels = found.labels ?? [];
|
||||
// The ready mark (novox/hq issue 722): its timeline is read, whole, only for a pull request that carries the label.
|
||||
const label = labels.find((l) => l.name === READY_LABEL);
|
||||
const ready = label ? readyMarkOf(label.id, await this.timeline(found.owner, found.name, pull.number), readyAuthors)
|
||||
: undefined;
|
||||
out.push({ owner: found.owner, repo: found.name, number: pull.number, base: pull.base ?? "", head_sha: pull.head_sha,
|
||||
html_url: pull.html_url, required: rule?.enable_status_check ? (rule.status_check_contexts ?? []) : [],
|
||||
statuses: Object.keys(checks), checks });
|
||||
statuses: Object.keys(checks), checks, labels: labels.map((l) => l.name), ...(ready ? { ready } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -639,6 +732,24 @@ export class GiteaClient {
|
||||
return this.requestText(`${repoPath(owner, repo)}/pulls/${index}.diff`);
|
||||
}
|
||||
|
||||
/** **Every event of an issue's or pull request's timeline**, oldest first, page by page (novox/hq issue 722): a long
|
||||
* thread hides nothing. Bounded at 100 pages of 50; a longer one is said, and its first 5000 events read. */
|
||||
async timeline(owner: string, repo: string, index: number): Promise<TimelineEvent[]> {
|
||||
indexOf(index);
|
||||
const out: TimelineEvent[] = [];
|
||||
for (let page = 1; page <= 100; page++) {
|
||||
const raw = await this.request<any[]>(`${repoPath(owner, repo)}/issues/${index}/timeline?page=${page}&limit=50`);
|
||||
for (const e of raw ?? []) {
|
||||
out.push({ id: Number(e?.id ?? 0), type: String(e?.type ?? ""), body: String(e?.body ?? ""),
|
||||
created_at: e?.created_at, user: e?.user?.login,
|
||||
...(e?.label ? { label: { id: Number(e.label.id ?? 0), name: String(e.label.name ?? "") } } : {}) });
|
||||
}
|
||||
if (!raw || raw.length < 50) return out;
|
||||
}
|
||||
console.error(`[gitea] ${owner}/${repo}#${index} has more than 5000 timeline events; only the first 5000 are read`);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Every comment on an issue or pull request, oldest first. */
|
||||
async listComments(owner: string, repo: string, index: number): Promise<GiteaComment[]> {
|
||||
indexOf(index);
|
||||
@@ -803,6 +914,11 @@ export class GiteaAdmin {
|
||||
return { status: res.status, body };
|
||||
}
|
||||
|
||||
/** One admin-API call with a JSON body, answering the status and body (the system webhook, novox/hq issue 729). */
|
||||
call(method: string, path: string, body?: unknown): Promise<AdminResponse> {
|
||||
return this.request(path, { method, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
||||
}
|
||||
|
||||
/** Fail with the forge's own message when a status the caller did not expect comes back. */
|
||||
private static fail(path: string, res: AdminResponse): never {
|
||||
const detail = typeof res.body === "string" ? res.body : JSON.stringify(res.body);
|
||||
|
||||
+152
-64
@@ -40,10 +40,11 @@ import { emit, on } from "@novox/mesh-sdk/events";
|
||||
import { registerModuleTools } from "@novox/mesh-sdk/tools";
|
||||
import { commitStatusTool } from "./delivery.js";
|
||||
import { mergeTool } from "./merge.js";
|
||||
import { GiteaClient, movedSince } from "./client.js";
|
||||
import { GiteaAdmin, GiteaClient, movedSince } from "./client.js";
|
||||
import { CHECK_CONTEXT, REPO_CHECK_CONTEXT, commentFor, headsToAnnounce, statusesFor, type Announced, type Checked,
|
||||
type RepoCheckFacts, reposToLook } from "./pulls.js";
|
||||
import { GateWriter, clonedAs, type BuildStarted } from "./gate.js";
|
||||
import { HOOK_PATH, HOOK_PORT, Pace, claimHead, ensureSystemHook, keptSecret, receiver, type ForgeEvent } from "./webhook.js";
|
||||
import { announcementOf, keepTook, lateVerdictComment, outOfDateWords, sameCommit, tookFile, weighTrunks } from "./trunk.js";
|
||||
|
||||
// Without a way to a token — configured, or mintable with the admin account (token.ts) — there is
|
||||
@@ -145,57 +146,9 @@ async function pollMerged(client: GiteaClient): Promise<void> {
|
||||
// at once.
|
||||
const fresh = !!pull.merged_at && !!since && pull.merged_at > since;
|
||||
if (primedMerges && fresh) {
|
||||
// What it changed, asked for only now: a module is rebuilt because a file inside its own
|
||||
// directory moved, and without this every module built from a repository is rebuilt for a
|
||||
// change to any of them (novox/hq 04-ISSUES/131).
|
||||
const changed = await client.listPullFiles(repo.owner, repo.name, pull.number);
|
||||
// Which of the directories they are in hold a module at the merge commit (novox/hq issue 278): a
|
||||
// change inside one is that module's, held or not, and only a file in none is shared code. Not
|
||||
// said when the list is cut or the forge could not be asked; the mesh then keeps its old rule.
|
||||
let moduleDirs: string[] | null = null;
|
||||
if (!changed.truncated) {
|
||||
try {
|
||||
moduleDirs = await client.moduleDirsAt(repo.owner, repo.name, pull.merge_commit_sha, changed.paths);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${repo.full_name}#${pull.number}: which directories hold a module could not be read, ` +
|
||||
`so the mesh reads its files by the old rule — ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
// The head it merged, and what its head was checked as (novox/hq ADR 0239): the delivery it was, made
|
||||
// from the forge's word when its owner never heard the head.
|
||||
let headChecks: Record<string, string> | null = null;
|
||||
if (pull.head_sha) {
|
||||
try {
|
||||
headChecks = await client.commitStatuses(repo.owner, repo.name, pull.head_sha);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${repo.full_name}#${pull.number}: its head's statuses could not be read — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
await emit("pull.merged", {
|
||||
owner: repo.owner,
|
||||
repo: repo.name,
|
||||
number: pull.number,
|
||||
title: pull.title,
|
||||
body: pull.body,
|
||||
head_sha: pull.head_sha,
|
||||
...(headChecks ? { head_checks: headChecks } : {}),
|
||||
head: pull.head,
|
||||
base: pull.base,
|
||||
merge_commit_sha: pull.merge_commit_sha,
|
||||
merged_at: pull.merged_at,
|
||||
clone_url: repo.clone_url,
|
||||
html_url: pull.html_url,
|
||||
paths: changed.paths,
|
||||
paths_truncated: changed.truncated,
|
||||
// Which of them the merge deleted (novox/hq ADR 0236): a module whose manifest went is forgotten,
|
||||
// not built.
|
||||
removed: changed.removed,
|
||||
...(moduleDirs ? { module_dirs: moduleDirs, module_dirs_said: true } : {}),
|
||||
});
|
||||
// Said, because a trigger that fires silently is indistinguishable from one that did not
|
||||
// fire (novox/hq 04-ISSUES/131) — this line is how an operator knows the mesh was told.
|
||||
console.log(`[gitea] announced merge ${repo.full_name}#${pull.number} (${pull.merge_commit_sha.slice(0, 8)}) into ${pull.base}`);
|
||||
if (await announceMerge(client, repo, pull)) pace.miss(`the merge of ${repo.full_name}#${pull.number}`);
|
||||
}
|
||||
else announced.add(pull.merge_commit_sha);
|
||||
announced.add(pull.merge_commit_sha);
|
||||
changed = true;
|
||||
}
|
||||
@@ -206,6 +159,73 @@ async function pollMerged(client: GiteaClient): Promise<void> {
|
||||
lastLook = began;
|
||||
}
|
||||
|
||||
type RepoOf = { owner: string; name: string; full_name: string; clone_url?: string };
|
||||
type PullOf = Awaited<ReturnType<GiteaClient["listPullRequests"]>>[number];
|
||||
|
||||
/** **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;
|
||||
// Recorded before the first wait, so the other path finds it taken while this one is still asking the forge.
|
||||
announced.add(pull.merge_commit_sha);
|
||||
try {
|
||||
// What it changed, asked for only now: a module is rebuilt because a file inside its own
|
||||
// directory moved, and without this every module built from a repository is rebuilt for a
|
||||
// change to any of them (novox/hq 04-ISSUES/131).
|
||||
const changed = await client.listPullFiles(repo.owner, repo.name, pull.number);
|
||||
// Which of the directories they are in hold a module at the merge commit (novox/hq issue 278): a
|
||||
// change inside one is that module's, held or not, and only a file in none is shared code. Not
|
||||
// said when the list is cut or the forge could not be asked; the mesh then keeps its old rule.
|
||||
let moduleDirs: string[] | null = null;
|
||||
if (!changed.truncated) {
|
||||
try {
|
||||
moduleDirs = await client.moduleDirsAt(repo.owner, repo.name, pull.merge_commit_sha, changed.paths);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${repo.full_name}#${pull.number}: which directories hold a module could not be read, ` +
|
||||
`so the mesh reads its files by the old rule — ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
// The head it merged, and what its head was checked as (novox/hq ADR 0239): the delivery it was, made
|
||||
// from the forge's word when its owner never heard the head.
|
||||
let headChecks: Record<string, string> | null = null;
|
||||
if (pull.head_sha) {
|
||||
try {
|
||||
headChecks = await client.commitStatuses(repo.owner, repo.name, pull.head_sha);
|
||||
} catch (err) {
|
||||
console.error(`[gitea] ${repo.full_name}#${pull.number}: its head's statuses could not be read — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
await emit("pull.merged", {
|
||||
owner: repo.owner,
|
||||
repo: repo.name,
|
||||
number: pull.number,
|
||||
title: pull.title,
|
||||
body: pull.body,
|
||||
head_sha: pull.head_sha,
|
||||
...(headChecks ? { head_checks: headChecks } : {}),
|
||||
head: pull.head,
|
||||
base: pull.base,
|
||||
merge_commit_sha: pull.merge_commit_sha,
|
||||
merged_at: pull.merged_at,
|
||||
clone_url: repo.clone_url,
|
||||
html_url: pull.html_url,
|
||||
paths: changed.paths,
|
||||
paths_truncated: changed.truncated,
|
||||
// Which of them the merge deleted (novox/hq ADR 0236): a module whose manifest went is forgotten,
|
||||
// not built.
|
||||
removed: changed.removed,
|
||||
...(moduleDirs ? { module_dirs: moduleDirs, module_dirs_said: true } : {}),
|
||||
});
|
||||
// Said, because a trigger that fires silently is indistinguishable from one that did not
|
||||
// fire (novox/hq 04-ISSUES/131) — this line is how an operator knows the mesh was told.
|
||||
console.log(`[gitea] announced merge ${repo.full_name}#${pull.number} (${pull.merge_commit_sha.slice(0, 8)}) into ${pull.base}`);
|
||||
} catch (err) {
|
||||
announced.delete(pull.merge_commit_sha);
|
||||
throw err;
|
||||
}
|
||||
keepAnnounced();
|
||||
return true;
|
||||
}
|
||||
|
||||
// **Every new head of an open pull request is announced, once** (novox/hq to-be 45 §9): the mesh checks it
|
||||
// against every machine of its facts before it merges. Kept beside the merges' record, so a restart
|
||||
// announces nothing twice; the first look on a machine with no record announces only what moved in the
|
||||
@@ -228,6 +248,31 @@ function keepHeads(): void {
|
||||
writeFileSync(tmp, JSON.stringify({ heads }));
|
||||
renameSync(tmp, pullsRecord);
|
||||
}
|
||||
/** **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 = `${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.
|
||||
if (!claimHead(heads, key, sha)) return false;
|
||||
try {
|
||||
// The announcement the merge tool makes too when it asks a check (trunk.ts, novox/hq ADR 0323 §5).
|
||||
await emit("pull.updated", await announcementOf(client, repo.owner, repo.name, repo.clone_url ?? "", pull));
|
||||
} catch (err) {
|
||||
if (before === undefined) delete heads[key];
|
||||
else heads[key] = before;
|
||||
throw err;
|
||||
}
|
||||
keepHeads();
|
||||
// Said, so an operator knows the mesh was asked to check it.
|
||||
console.log(`[gitea] announced ${key} at ${sha.slice(0, 8)} to be checked before it merges`);
|
||||
// Pending until the verdict comes, so the pull request says a check is running rather than nothing — and
|
||||
// where it is: in the build queue from now, until a build machine takes it (novox/hq issue 446).
|
||||
await gates.pending(repo.owner, repo.name, sha);
|
||||
return true;
|
||||
}
|
||||
type OpenOf = Awaited<ReturnType<GiteaClient["listOpenPullsSince"]>>[number];
|
||||
|
||||
let lastPullLook = "";
|
||||
// **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.
|
||||
@@ -259,15 +304,8 @@ async function pollPulls(client: GiteaClient): Promise<void> {
|
||||
const key = `${repo.full_name}#${pull.number}`;
|
||||
const fresh = primedPulls || (!!pull.updated_at && pull.updated_at > dayAgo);
|
||||
if (fresh) {
|
||||
// The announcement the merge tool makes too when it asks a check (trunk.ts, novox/hq ADR 0323 §5).
|
||||
await emit("pull.updated", await announcementOf(client, repo.owner, repo.name, repo.clone_url, pull));
|
||||
// Said, so an operator knows the mesh was asked to check it.
|
||||
console.log(`[gitea] announced ${key} at ${String(pull.head_sha).slice(0, 8)} to be checked before it merges`);
|
||||
// Pending until the verdict comes, so the pull request says a check is running rather than nothing — and
|
||||
// where it is: in the build queue from now, until a build machine takes it (novox/hq issue 446).
|
||||
await gates.pending(repo.owner, repo.name, String(pull.head_sha));
|
||||
}
|
||||
heads[key] = String(pull.head_sha);
|
||||
if (await announceHead(client, repo, pull)) pace.miss(`${key} at ${String(pull.head_sha).slice(0, 8)}`);
|
||||
} else heads[key] = String(pull.head_sha);
|
||||
changed = true;
|
||||
}
|
||||
if (await trunksMoved(client, repo.owner, repo.name)) changedTrunks = true;
|
||||
@@ -413,12 +451,59 @@ async function buildStarted(event: { body: unknown }): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** How fast the polls look: 30 s until the forge's events are heard, five minutes while they are (webhook.ts). */
|
||||
const pace = new Pace();
|
||||
|
||||
/** 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;
|
||||
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
|
||||
* the token; the webhook is made or corrected with the admin account (ADR 0266: the tools' token holds no admin scope).
|
||||
* Answers whether events are heard; a forge that refuses is said, and the polls keep their pace.
|
||||
*/
|
||||
async function listenForForge(client: GiteaClient): Promise<boolean> {
|
||||
const stateDir = process.env.MESH_GITEA_STATE_DIR;
|
||||
const url = process.env.MESH_GITEA_HOOK_URL;
|
||||
if (!stateDir || !url) {
|
||||
console.log("[gitea] no webhook receiver: MESH_GITEA_STATE_DIR or MESH_GITEA_HOOK_URL unset, so the polls alone watch the forge");
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const secret = keptSecret(join(stateDir, "webhook.secret"));
|
||||
const port = Number(process.env.MESH_GITEA_HOOK_PORT ?? HOOK_PORT);
|
||||
const server = receiver({ secret, port, heard: () => pace.heard(),
|
||||
publish: (event) => emit(event.name, event.body),
|
||||
act: (event) => actOn(client, event) });
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, process.env.MESH_GITEA_HOOK_HOST ?? "0.0.0.0", () => resolve());
|
||||
});
|
||||
const did = await ensureSystemHook(GiteaAdmin.fromEnv(), url.replace(/\/+$/, "") + HOOK_PATH, secret);
|
||||
console.log(`[gitea] listening for the forge's events on port ${port}; its system webhook ${did}, every event, signed`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`[gitea] the forge's events are not heard, so the polls keep their pace — ${err instanceof Error ? err.message : err}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (gitea) {
|
||||
const client = gitea;
|
||||
// A poll that fails says so once, not once a minute: the same reason repeating (the forge not up
|
||||
// yet, the admin account refused on a restored forge) is one fact, and a recovery is worth a line.
|
||||
let failing: string | null = null;
|
||||
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||
const tick = (fn: () => Promise<void>, every: number | (() => number)): void => {
|
||||
const everyMs = (): number => (typeof every === "number" ? every : every());
|
||||
// **One pass at a time** (novox/hq issue 250): the next pass is scheduled when this one has ended, so a
|
||||
// pass that outlasts its interval delays the next instead of running beside it — two passes at once
|
||||
// could each announce the same merge before either recorded it.
|
||||
@@ -433,12 +518,15 @@ if (gitea) {
|
||||
if (why !== failing) console.error(`[gitea] not watching until this clears — ${why}`);
|
||||
failing = why;
|
||||
})
|
||||
.finally(() => setTimeout(run, everyMs));
|
||||
.finally(() => setTimeout(run, everyMs()));
|
||||
run();
|
||||
};
|
||||
// **The forge's events first, the polls as the safety net** (novox/hq issue 729): while verified deliveries arrive the
|
||||
// polls slow to every five minutes and announce only what no event said (Pace); otherwise they keep 30 s.
|
||||
await listenForForge(client);
|
||||
tick(() => pollRepos(client), 60_000);
|
||||
tick(() => pollMerged(client), 30_000);
|
||||
tick(() => pollPulls(client), 30_000);
|
||||
tick(() => pollMerged(client), () => pace.every());
|
||||
tick(() => pollPulls(client), () => pace.every());
|
||||
await on("mesh-controller.checked", (event) => {
|
||||
const c = (event.body ?? {}) as Checked;
|
||||
// A head's own verdict takes its turn after every write of that head's gate already asked for (gate.ts).
|
||||
|
||||
@@ -42,7 +42,47 @@
|
||||
"issue.opened",
|
||||
"pull.merged",
|
||||
"pull.updated",
|
||||
"pull.closed"
|
||||
"pull.closed",
|
||||
"forge.push",
|
||||
"forge.create",
|
||||
"forge.delete",
|
||||
"forge.fork",
|
||||
"forge.status",
|
||||
"forge.pull-request.opened",
|
||||
"forge.pull-request.reopened",
|
||||
"forge.pull-request.synchronized",
|
||||
"forge.pull-request.edited",
|
||||
"forge.pull-request.closed",
|
||||
"forge.pull-request.merged",
|
||||
"forge.pull-request.labeled",
|
||||
"forge.pull-request.unlabeled",
|
||||
"forge.pull-request.assigned",
|
||||
"forge.pull-request.unassigned",
|
||||
"forge.pull-request.reviewed",
|
||||
"forge.pull-request.review-requested",
|
||||
"forge.pull-request.commented",
|
||||
"forge.pull-request.changed",
|
||||
"forge.issue-comment.created",
|
||||
"forge.issue-comment.edited",
|
||||
"forge.issue-comment.deleted",
|
||||
"forge.issues.opened",
|
||||
"forge.issues.reopened",
|
||||
"forge.issues.closed",
|
||||
"forge.issues.edited",
|
||||
"forge.issues.labeled",
|
||||
"forge.issues.unlabeled",
|
||||
"forge.issues.assigned",
|
||||
"forge.issues.unassigned",
|
||||
"forge.issues.changed",
|
||||
"forge.release.published",
|
||||
"forge.release.updated",
|
||||
"forge.release.deleted",
|
||||
"forge.release.changed",
|
||||
"forge.repository.created",
|
||||
"forge.repository.deleted",
|
||||
"forge.repository.changed",
|
||||
"forge.wiki.changed",
|
||||
"forge.other"
|
||||
],
|
||||
"consumes": [
|
||||
"mesh-controller.checked",
|
||||
@@ -61,14 +101,22 @@
|
||||
"port": 22,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "git over ssh, gitea's own unmodified sshd. Published on the machine's own side at 222, the mesh's fixed public convention \u2014 not 22, which the machine's own daemon holds and a module does not take"
|
||||
"why": "git over ssh, gitea's own unmodified sshd. Published on the machine's own side at 222, the mesh's fixed public convention — not 22, which the machine's own daemon holds and a module does not take"
|
||||
},
|
||||
{
|
||||
"name": "forge-events",
|
||||
"port": 3047,
|
||||
"protocol": "tcp",
|
||||
"from": "machine",
|
||||
"why": "the forge's system webhook, every event signed with a secret the module keeps, from the forge's container on the docker bridge to the module's receiver at the bridge's gateway 172.17.0.1 (novox/hq issue 729)"
|
||||
}
|
||||
],
|
||||
"serves": {
|
||||
"npm-package-registry": {
|
||||
"scheme": "http",
|
||||
"port": 3000,
|
||||
"npm-path": "/api/packages/novox/npm/"
|
||||
"npm-path": "/api/packages/novox/npm/",
|
||||
"public-root": "https://${bound:route:name-web}/api/packages/novox/npm/"
|
||||
},
|
||||
"git": {
|
||||
"scheme": "http",
|
||||
@@ -108,6 +156,13 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"ready-authors": {
|
||||
"kind": "preference",
|
||||
"default": "mesh-admin jschoubben",
|
||||
"why": "the forge accounts whose comment \"ready at <full head sha>\" marks a pull request ready for mesh-delivery to merge, separated by spaces: the mesh's own forge account and the operator's (novox/hq issue 722). A comment by any other account is ignored and said in the forge's log. Trusted: who may have a change merged is the operator's word"
|
||||
}
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
@@ -121,6 +176,14 @@
|
||||
"path": "${dir:mesh-state}/state",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "ready-authors",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/ready-authors",
|
||||
"mode": "0600",
|
||||
"trusted": true,
|
||||
"content": "# The accounts whose \"ready at <sha>\" comment marks a pull request ready (novox/hq issue 722), from the setting\n# ready-authors, written by the mesh. Replaced on every push; change the setting, never this file.\nauthors=${setting:ready-authors}\n"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
@@ -137,7 +200,7 @@
|
||||
"type": "file",
|
||||
"path": "${dir:state}/server.env",
|
||||
"mode": "0600",
|
||||
"content": "GITEA__security__INTERNAL_TOKEN=${secret:internal-token}\nGITEA__database__DB_TYPE=postgres\nGITEA__database__HOST=${bound:postgres-database:at}:${bound:postgres-database:port}\nGITEA__database__NAME=${bound:postgres-database:as}\nGITEA__database__USER=${bound:postgres-database:as}\nGITEA__database__PASSWD=${secret:postgres-database}\n"
|
||||
"content": "GITEA__security__INTERNAL_TOKEN=${secret:internal-token}\nGITEA__database__DB_TYPE=postgres\nGITEA__database__HOST=${bound:postgres-database:at}:${bound:postgres-database:port}\nGITEA__database__NAME=${bound:postgres-database:as}\nGITEA__database__USER=${bound:postgres-database:as}\nGITEA__database__PASSWD=${secret:postgres-database}\nGITEA__webhook__ALLOWED_HOST_LIST=172.17.0.1\n"
|
||||
},
|
||||
{
|
||||
"id": "data",
|
||||
@@ -148,6 +211,13 @@
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"health": {
|
||||
"kind": "http",
|
||||
"endpoint": "web",
|
||||
"path": "/api/healthz",
|
||||
"status": 200,
|
||||
"needs": "postgres-database"
|
||||
},
|
||||
"name": "gitea",
|
||||
"image": "gitea/gitea@sha256:87a67ee09d3ae0d1df5fda5dcda3e2a1f9236a45b0a59025d6e00e46adc43bef",
|
||||
"env": {
|
||||
@@ -199,7 +269,8 @@
|
||||
"path": "${dir:mesh-state}/config.json",
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
"merge": "json",
|
||||
"takes-settings": []
|
||||
}
|
||||
],
|
||||
"provides": [
|
||||
@@ -238,7 +309,11 @@
|
||||
"MESH_GITEA_ADMIN_USER": "mesh-admin",
|
||||
"MESH_GITEA_ADMIN_PASSWORD_FILE": "${dir:state}/admin.secret",
|
||||
"MESH_GITEA_STATE_DIR": "${dir:runtime-state}",
|
||||
"MESH_RECEIVES": "${dir:grants}/npm.json"
|
||||
"MESH_RECEIVES": "${dir:grants}/npm.json",
|
||||
"MESH_GITEA_READY_AUTHORS_FILE": "${dir:mesh-state}/ready-authors",
|
||||
"MESH_GITEA_HOOK_URL": "http://172.17.0.1:3047",
|
||||
"MESH_GITEA_HOOK_PORT": "3047",
|
||||
"MESH_GITEA_HOOK_HOST": "172.17.0.1"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -137,3 +137,120 @@ test("a merged pull request whose branch was deleted is announced with its branc
|
||||
assert.equal(headBranchOf({ ref: "refs/pull/7/head" }), "refs/pull/7/head");
|
||||
assert.equal(headBranchOf(undefined), undefined);
|
||||
});
|
||||
|
||||
// **A pull request marked ready says the head it is marked at** (novox/hq issue 722): the label mesh/ready and the
|
||||
// newest comment "ready at <full head sha>" by a listed account, written after the label was added and after the last
|
||||
// push. Read from the pull request's whole timeline, page by page; without the label nothing is read.
|
||||
const head = "c".repeat(40), older = "d".repeat(40);
|
||||
const ev = (id: number, type: string, body: string, user = "mesh-admin", label?: { id: number; name: string }) =>
|
||||
({ id, type, body, user: { login: user }, created_at: `2026-10-14T10:${String(id % 60).padStart(2, "0")}:00Z`,
|
||||
...(label ? { label } : {}) });
|
||||
const readyLabel = { id: 31, name: "mesh/ready" };
|
||||
|
||||
function forgeWith(timeline: unknown[]) {
|
||||
const asked: string[] = [];
|
||||
const server = createServer((req, res) => {
|
||||
const url = req.url ?? "";
|
||||
asked.push(url);
|
||||
const send = (v: unknown) => res.end(JSON.stringify(v));
|
||||
if (url.startsWith("/api/v1/repos/issues/search")) {
|
||||
return send(url.includes("page=1") ? [
|
||||
{ number: 7, repository: { owner: "novox", name: "hq", full_name: "novox/hq" },
|
||||
labels: [{ id: 31, name: "mesh/ready" }, { id: 2, name: "bug" }] },
|
||||
{ number: 8, repository: { owner: "novox", name: "hq", full_name: "novox/hq" }, labels: [] },
|
||||
] : []);
|
||||
}
|
||||
if (url.startsWith("/api/v1/repos/novox/hq/pulls/7")) {
|
||||
return send({ number: 7, state: "open", base: { ref: "main" }, head: { ref: "x", sha: head }, html_url: "h" });
|
||||
}
|
||||
if (url.startsWith("/api/v1/repos/novox/hq/pulls/8")) {
|
||||
return send({ number: 8, state: "open", base: { ref: "main" }, head: { ref: "y", sha: older }, html_url: "h" });
|
||||
}
|
||||
const t = /\/issues\/7\/timeline\?page=(\d+)&limit=50/.exec(url);
|
||||
if (t) {
|
||||
const page = Number(t[1]);
|
||||
return send(timeline.slice((page - 1) * 50, page * 50));
|
||||
}
|
||||
if (url.includes("/branch_protections")) return send([]);
|
||||
if (url.includes("/status")) return send({ statuses: [] });
|
||||
res.statusCode = 404;
|
||||
res.end("{}");
|
||||
});
|
||||
return { server, asked };
|
||||
}
|
||||
|
||||
async function readOpen(timeline: unknown[], authors = ["mesh-admin", "jschoubben"]) {
|
||||
const { GiteaClient } = await import("../client.ts");
|
||||
const { server, asked } = forgeWith(timeline);
|
||||
await new Promise<void>((r) => server.listen(0, r));
|
||||
try {
|
||||
const client = new GiteaClient(`http://127.0.0.1:${(server.address() as any).port}`, "t");
|
||||
return { open: await client.openPulls(authors), asked };
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
|
||||
test("a pull request's ready mark is read: the label and the head the newest listed ready comment names", async () => {
|
||||
const { open, asked } = await readOpen([
|
||||
ev(1, "pull_push", JSON.stringify({ commit_ids: [head] })),
|
||||
ev(2, "label", "1", "mesh-admin", readyLabel),
|
||||
ev(3, "comment", `ready at ${older}`),
|
||||
ev(4, "comment", `Reviewed: approve.\nready at ${head}\n`),
|
||||
ev(5, "comment", "thanks", "jschoubben"),
|
||||
]);
|
||||
assert.deepEqual(open[0].labels, ["mesh/ready", "bug"]);
|
||||
assert.deepEqual(open[0].ready, { head, by: "mesh-admin", at: "2026-10-14T10:04:00Z", label_id: 31 });
|
||||
assert.equal(open[1].ready, undefined, "no label, no mark");
|
||||
assert.ok(!asked.some((u) => u.includes("/issues/8/")), "no timeline read without the label");
|
||||
});
|
||||
|
||||
test("a ready comment by an account not listed is ignored, and said", async () => {
|
||||
const { readyMarkOf } = await import("../client.ts");
|
||||
const said: string[] = [];
|
||||
const mark = readyMarkOf(31, [
|
||||
ev(1, "pull_push", "{}") as any, ev(2, "label", "1", "mesh-admin", readyLabel) as any,
|
||||
{ ...ev(3, "comment", `ready at ${head}`, "outsider"), user: "outsider" },
|
||||
].map((e: any) => ({ ...e, user: typeof e.user === "string" ? e.user : e.user.login })), ["mesh-admin"], (l) => said.push(l));
|
||||
assert.equal(mark.head, "", "an outsider's mark counts");
|
||||
assert.equal(said.length, 1);
|
||||
assert.match(said[0], /by outsider is ignored/);
|
||||
});
|
||||
|
||||
test("a ready comment older than the latest push, or than the label, never counts", async () => {
|
||||
const pushedAfter = await readOpen([
|
||||
ev(1, "label", "1", "mesh-admin", readyLabel),
|
||||
ev(2, "comment", `ready at ${head}`),
|
||||
ev(3, "pull_push", JSON.stringify({ commit_ids: [head] })),
|
||||
]);
|
||||
assert.equal(pushedAfter.open[0].ready?.head, "", "a mark written before the latest push counts, the label still on");
|
||||
const beforeLabel = await readOpen([
|
||||
ev(1, "pull_push", "{}"),
|
||||
ev(2, "comment", `ready at ${head}`),
|
||||
ev(3, "label", "1", "mesh-admin", readyLabel),
|
||||
]);
|
||||
assert.equal(beforeLabel.open[0].ready?.head, "", "a mark written before the label was added counts");
|
||||
const takenOff = await readOpen([
|
||||
ev(1, "label", "1", "mesh-admin", readyLabel),
|
||||
ev(2, "comment", `ready at ${head}`),
|
||||
ev(3, "label", "", "mesh-admin", readyLabel),
|
||||
]);
|
||||
assert.equal(takenOff.open[0].ready?.head, "", "a mark whose label was taken off since counts");
|
||||
});
|
||||
|
||||
test("a long thread hides nothing: every page of the timeline is read", async () => {
|
||||
const events: unknown[] = [ev(1, "pull_push", "{}"), ev(2, "label", "1", "mesh-admin", readyLabel),
|
||||
ev(3, "comment", `ready at ${older}`)];
|
||||
for (let id = 4; id < 130; id++) events.push(ev(id, "comment", "a long discussion", "jschoubben"));
|
||||
events.push(ev(130, "comment", `ready at ${head}`, "jschoubben"));
|
||||
const { open, asked } = await readOpen(events);
|
||||
assert.equal(open[0].ready?.head, head, "the newest mark, on the third page, is not read");
|
||||
assert.equal(asked.filter((u) => u.includes("/issues/7/timeline")).length, 3);
|
||||
});
|
||||
|
||||
test("the accounts that may mark are the setting's, and only the mesh's own when it cannot be read", async () => {
|
||||
const { readyAuthors } = await import("../client.ts");
|
||||
assert.deepEqual(readyAuthors("f", "mesh-admin", () => "# x\nauthors=mesh-admin jschoubben\n"), ["mesh-admin", "jschoubben"]);
|
||||
assert.deepEqual(readyAuthors("f", "mesh-admin", () => { throw new Error("gone"); }), ["mesh-admin"]);
|
||||
assert.deepEqual(readyAuthors("f", "mesh-admin", () => "authors=\n"), ["mesh-admin"]);
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { collectTools } from "@novox/mesh-sdk/tools";
|
||||
import { AdminRefused, MintedToken, TOKEN_SCOPES } from "../dist/token.js";
|
||||
import { AdminRefused, MINT_RETRY_AFTER_MS, MintedToken, TOKEN_SCOPES } from "../dist/token.js";
|
||||
import { GiteaClient } from "../dist/client.js";
|
||||
import { getGiteaTools } from "../dist/tools/index.js";
|
||||
|
||||
@@ -29,6 +29,9 @@ interface Forge {
|
||||
mints: number;
|
||||
lastScopes: string[] | null;
|
||||
tokens: Map<string, string>;
|
||||
/** Tokens beyond the one per name `tokens` holds, by id: what two mints racing leave (novox/hq issue 739). */
|
||||
twins: Map<number, { name: string; sha1: string }>;
|
||||
tokenCalls: number;
|
||||
scopesOf: Map<string, string[]>;
|
||||
admins: Map<string, string>;
|
||||
pullState: string;
|
||||
@@ -42,6 +45,9 @@ function fakeForge(): Promise<Forge> {
|
||||
mints: 0,
|
||||
lastScopes: null as string[] | null,
|
||||
tokens: new Map<string, string>(), // name -> value
|
||||
twins: new Map<number, { name: string; sha1: string }>(),
|
||||
idOf: new Map<string, number>(), // value -> id
|
||||
tokenCalls: 0,
|
||||
scopesOf: new Map<string, string[]>(), // value -> scopes, so a route can enforce them like gitea does
|
||||
admins: new Map([[ADMIN, PASSWORD]]),
|
||||
pullState: "open",
|
||||
@@ -73,21 +79,41 @@ function fakeForge(): Promise<Forge> {
|
||||
const tokens = url.pathname.match(/^\/api\/v1\/users\/([^/]+)\/tokens(?:\/([^/]+))?$/);
|
||||
if (tokens) {
|
||||
const user = basic(req);
|
||||
forge.tokenCalls++;
|
||||
if (user === null || user !== decodeURIComponent(tokens[1])) return json(res, 401, { message: "auth required" });
|
||||
const named = (name: string): number =>
|
||||
(forge.tokens.has(name) ? 1 : 0) + [...forge.twins.values()].filter((t) => t.name === name).length;
|
||||
if (req.method === "POST") {
|
||||
const { name, scopes } = await body(req);
|
||||
if (forge.tokens.has(name)) return json(res, 400, { message: "token name has already been used" });
|
||||
if (named(name) > 0) return json(res, 400, { message: "token name has already been used" });
|
||||
forge.mints++;
|
||||
forge.lastScopes = scopes;
|
||||
const sha1 = `minted-${forge.mints}-${Math.random().toString(36).slice(2)}`;
|
||||
forge.tokens.set(name, sha1);
|
||||
forge.idOf.set(sha1, forge.mints);
|
||||
forge.scopesOf.set(sha1, scopes);
|
||||
return json(res, 201, { id: forge.mints, name, sha1, scopes, token_last_eight: sha1.slice(-8) });
|
||||
}
|
||||
if (req.method === "GET" && !tokens[2]) {
|
||||
const page = Number(url.searchParams.get("page") ?? "1");
|
||||
const all = [...[...forge.tokens].map(([name, v]) => ({ id: forge.idOf.get(v) ?? 0, name })),
|
||||
...[...forge.twins].map(([id, t]) => ({ id, name: t.name }))];
|
||||
return json(res, 200, page === 1 ? all : []);
|
||||
}
|
||||
if (req.method === "DELETE" && tokens[2]) {
|
||||
const name = decodeURIComponent(tokens[2]);
|
||||
if (!forge.tokens.has(name)) return json(res, 404, { message: "token not found" });
|
||||
forge.tokens.delete(name);
|
||||
const key = decodeURIComponent(tokens[2]);
|
||||
// gitea: "identified by ID and if not available by name"
|
||||
if (/^\d+$/.test(key)) {
|
||||
const id = Number(key);
|
||||
if (forge.twins.delete(id)) return json(res, 204, null);
|
||||
const hit = [...forge.tokens].find(([, v]) => forge.idOf.get(v) === id);
|
||||
if (!hit) return json(res, 404, { message: "token not found" });
|
||||
forge.tokens.delete(hit[0]);
|
||||
return json(res, 204, null);
|
||||
}
|
||||
if (named(key) > 1) return json(res, 422, { message: `multiple matches for token name '${key}'` });
|
||||
if (!forge.tokens.has(key)) return json(res, 404, { message: "token not found" });
|
||||
forge.tokens.delete(key);
|
||||
return json(res, 204, null);
|
||||
}
|
||||
return json(res, 405, { message: "method not allowed" });
|
||||
@@ -180,7 +206,9 @@ function fakeForge(): Promise<Forge> {
|
||||
get pullState() { return forge.pullState; },
|
||||
get pullTitle() { return forge.pullTitle; },
|
||||
get branchDeleted() { return forge.branchDeleted; },
|
||||
get tokenCalls() { return forge.tokenCalls; },
|
||||
tokens: forge.tokens,
|
||||
twins: forge.twins,
|
||||
scopesOf: forge.scopesOf,
|
||||
admins: forge.admins,
|
||||
close: () => new Promise((r) => server.close(() => r())),
|
||||
@@ -209,8 +237,9 @@ async function delivered(forge: Forge): Promise<{ env: NodeJS.ProcessEnv; file:
|
||||
}
|
||||
|
||||
/** A client as a fresh process would build it: a new source over the kept file, its log captured. */
|
||||
function minted(env: NodeJS.ProcessEnv, logs: string[]): GiteaClient {
|
||||
function minted(env: NodeJS.ProcessEnv, logs: string[], now?: () => number): GiteaClient {
|
||||
const source = new MintedToken({
|
||||
now,
|
||||
url: env.MESH_GITEA_URL!,
|
||||
admin: env.MESH_GITEA_ADMIN_USER!,
|
||||
passwordFile: env.MESH_GITEA_ADMIN_PASSWORD_FILE!,
|
||||
@@ -325,6 +354,44 @@ test("the kept file is gone but the forge still holds a token by that name: repl
|
||||
assert.ok(logs.some((l) => l.includes('already holds a token named "mesh-tools"')), logs.join("\n"));
|
||||
});
|
||||
|
||||
test("two tokens carry the name (two mints raced): each is dropped by its id and one is minted, not a 422 for good (issue 739)", async () => {
|
||||
const { env, logs } = await delivered(forge);
|
||||
await minted(env, logs).listRepos();
|
||||
// What two processes minting at once leave: a second token by the same name, whose value nobody kept.
|
||||
// Two tokens by the name, neither of them the one kept.
|
||||
forge.tokens.clear();
|
||||
forge.twins.set(9001, { name: "mesh-tools", sha1: "raced-first" });
|
||||
forge.twins.set(9002, { name: "mesh-tools", sha1: "raced-second" });
|
||||
|
||||
const repos = await minted(env, logs).listRepos();
|
||||
|
||||
assert.equal(repos.length, 1);
|
||||
assert.equal(forge.twins.size, 0);
|
||||
assert.equal([...forge.tokens.keys()].filter((n) => n === "mesh-tools").length, 1);
|
||||
assert.ok(logs.some((l) => l.includes('holds 2 tokens named "mesh-tools"')), logs.join("\n"));
|
||||
});
|
||||
|
||||
test("a mint that failed is not asked of the forge again within the retry window: the same error, no basic-auth call (issue 739)", async () => {
|
||||
const { env, logs } = await delivered(forge);
|
||||
forge.admins.delete(ADMIN);
|
||||
try {
|
||||
let clock = 5_000_000;
|
||||
const client = minted(env, logs, () => clock);
|
||||
await assert.rejects(client.listRepos(), AdminRefused);
|
||||
const calls = forge.tokenCalls;
|
||||
|
||||
await assert.rejects(client.listRepos(), AdminRefused);
|
||||
await assert.rejects(client.listRepos(), AdminRefused);
|
||||
assert.equal(forge.tokenCalls, calls);
|
||||
|
||||
clock += MINT_RETRY_AFTER_MS;
|
||||
await assert.rejects(client.listRepos(), AdminRefused);
|
||||
assert.equal(forge.tokenCalls, calls + 1);
|
||||
} finally {
|
||||
forge.admins.set(ADMIN, PASSWORD);
|
||||
}
|
||||
});
|
||||
|
||||
test("concurrent first calls share one mint", async () => {
|
||||
const { env, logs } = await delivered(forge);
|
||||
const client = minted(env, logs);
|
||||
@@ -339,7 +406,8 @@ test("the admin account is refused: said plainly, nothing kept, and the next cal
|
||||
const { env, file, logs } = await delivered(forge);
|
||||
forge.admins.delete(ADMIN); // the forge's data came from a predecessor; mesh-admin was never created there
|
||||
try {
|
||||
const client = minted(env, logs);
|
||||
let clock = 1_000_000;
|
||||
const client = minted(env, logs, () => clock);
|
||||
const before = forge.mints;
|
||||
|
||||
await assert.rejects(client.listRepos(), (err: unknown) => {
|
||||
@@ -354,8 +422,9 @@ test("the admin account is refused: said plainly, nothing kept, and the next cal
|
||||
assert.equal(forge.mints, before);
|
||||
await assert.rejects(stat(file), /ENOENT/);
|
||||
|
||||
// The account appears (the operator created it): the very next call mints and works.
|
||||
// The account appears (the operator created it): the next call after the retry window mints and works.
|
||||
forge.admins.set(ADMIN, PASSWORD);
|
||||
clock += MINT_RETRY_AFTER_MS;
|
||||
assert.equal((await client.listRepos()).length, 1);
|
||||
assert.equal(forge.mints, before + 1);
|
||||
} finally {
|
||||
|
||||
@@ -173,3 +173,29 @@ test("a verdict that landed out of date keeps its account on the pull request",
|
||||
const bare = lateVerdictComment({ commit: HEAD, trunk: TRUNK.slice(0, 12), verdict: "pass" }, null, words);
|
||||
assert.match(bare, /head dfb1415aaaaa merged into trunk a2c2c35bbbbb, pass/);
|
||||
});
|
||||
|
||||
test("a release branch's move puts every open pull request into it out of date, as a trunk's does (ADR 0358 §5)", async () => {
|
||||
// novox/hq ADR 0358 §5: for a pull request into a release branch, the release branch takes the trunk's place in ADR
|
||||
// 0323 — the check merges the head onto the release branch's head and names it as the trunk commit, so the release
|
||||
// branch's move puts its open verdicts out of date, and leaves those into main alone.
|
||||
const release = "feat/57-config-and-provisioning";
|
||||
const heads: Record<string, string> = { main: TRUNK, [release]: "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" };
|
||||
const pulls = [{ number: 315, base: release, head: "3".repeat(40) }, { number: 1, base: "main", head: "1".repeat(40) }];
|
||||
const { forge, statuses } = aForge(pulls, heads);
|
||||
const gates = new GateWriter(forge);
|
||||
const trunks: Record<string, string> = {};
|
||||
await weighTrunks(forge, gates, trunks, "novox", "mesh-controller");
|
||||
|
||||
heads[release] = MOVED;
|
||||
assert.equal(await weighTrunks(forge, gates, trunks, "novox", "mesh-controller"), true);
|
||||
const s = statuses.get("3".repeat(40))!;
|
||||
assert.equal(s["mesh/merge-gate"].state, "pending");
|
||||
assert.match(s["mesh/merge-gate"].description!, /judged against trunk eeeeeeeeeeee, the trunk is now d28ca95ccccc/);
|
||||
assert.equal(s["mesh/repo-check"].state, "pending");
|
||||
assert.equal(statuses.get("1".repeat(40))!["mesh/merge-gate"].state, "success", "a pull request into main is left");
|
||||
assert.equal(trunks[`novox/mesh-controller:${release}`], MOVED);
|
||||
|
||||
// The merge tool's rule reads the same: a verdict judged against the release branch's old head is not current.
|
||||
assert.equal(verdictAtTrunk({ "mesh/merge-gate": { state: "success",
|
||||
description: "head x merged into trunk eeeeeeeeeeee — pass" } }, MOVED).current, false);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createHmac } from "node:crypto";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
// **The forge says every event on the bus** (novox/hq issue 729): a signed delivery is published once and acted on,
|
||||
// an unsigned or unverified one is refused, and an event and the poll seeing the same head announce it once.
|
||||
|
||||
const secret = "s".repeat(64);
|
||||
const sign = (body: string, key = secret) => createHmac("sha256", key).update(body).digest("hex");
|
||||
const opened = JSON.stringify({ action: "opened", number: 7, pull_request: { number: 7, title: "t", user: { login: "jo" },
|
||||
head: { ref: "feat/x", sha: "a".repeat(40) }, base: { ref: "main" }, merged: false },
|
||||
repository: { name: "hq", full_name: "novox/hq", owner: { login: "novox" } }, sender: { login: "jo" } });
|
||||
|
||||
async function serve(published: { name: string }[], acted: { name: string }[]) {
|
||||
const { receiver, HOOK_PATH } = await import("../webhook.ts");
|
||||
const server = receiver({ secret, port: 0, log: () => {},
|
||||
publish: async (e) => { published.push(e); }, act: async (e) => { acted.push(e); } });
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
|
||||
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}${HOOK_PATH}`;
|
||||
return { server, url };
|
||||
}
|
||||
|
||||
test("a signed event is published on the bus and acted on once", async () => {
|
||||
const published: { name: string }[] = [], acted: { name: string }[] = [];
|
||||
const { server, url } = await serve(published, acted);
|
||||
try {
|
||||
const headers = { "X-Gitea-Event": "pull_request", "X-Gitea-Signature": sign(opened), "X-Gitea-Delivery": "d-1" };
|
||||
const res = await fetch(url, { method: "POST", body: opened, headers });
|
||||
assert.equal(res.status, 200);
|
||||
// The same delivery sent again is answered and published nowhere.
|
||||
const again = await fetch(url, { method: "POST", body: opened, headers });
|
||||
assert.equal(again.status, 200);
|
||||
await server.idle();
|
||||
assert.deepEqual(published.map((e) => e.name), ["forge.pull-request.opened"]);
|
||||
assert.deepEqual(acted.map((e) => e.name), ["forge.pull-request.opened"]);
|
||||
} finally { server.close(); }
|
||||
});
|
||||
|
||||
test("an unsigned event, or one whose signature does not verify, is refused and published nowhere", async () => {
|
||||
const published: { name: string }[] = [], acted: { name: string }[] = [];
|
||||
const { server, url } = await serve(published, acted);
|
||||
try {
|
||||
const unsigned = await fetch(url, { method: "POST", body: opened, headers: { "X-Gitea-Event": "pull_request" } });
|
||||
assert.equal(unsigned.status, 401);
|
||||
assert.match(await unsigned.text(), /unsigned/);
|
||||
const forged = await fetch(url, { method: "POST", body: opened,
|
||||
headers: { "X-Gitea-Event": "pull_request", "X-Gitea-Signature": sign(opened, "another secret") } });
|
||||
assert.equal(forged.status, 401);
|
||||
assert.match(await forged.text(), /does not verify/);
|
||||
const big = "x".repeat(5 * 1024 * 1024 + 1);
|
||||
const large = await fetch(url, { method: "POST", body: big,
|
||||
headers: { "X-Gitea-Event": "push", "X-Gitea-Signature": sign(big) } });
|
||||
assert.equal(large.status, 413);
|
||||
await server.idle();
|
||||
assert.deepEqual(published, []);
|
||||
assert.deepEqual(acted, []);
|
||||
} finally { server.close(); }
|
||||
});
|
||||
|
||||
test("an event and the poll seeing the same head announce it once", async () => {
|
||||
const { claimHead } = await import("../webhook.ts");
|
||||
const heads: Record<string, string> = {};
|
||||
const sha = "a".repeat(40);
|
||||
assert.equal(claimHead(heads, "novox/hq#7", sha), true, "the event claims the head and announces it");
|
||||
assert.equal(claimHead(heads, "novox/hq#7", sha), false, "the poll finds it taken");
|
||||
assert.equal(claimHead(heads, "novox/hq#7", "b".repeat(40)), true, "a new head is announced again");
|
||||
});
|
||||
|
||||
test("each forge event is named in the module's stream and trimmed", async () => {
|
||||
const { eventOf } = await import("../webhook.ts");
|
||||
const merged = eventOf("pull_request", { action: "closed", pull_request: { number: 3, merged: true, merge_commit_sha: "c".repeat(40),
|
||||
head: { sha: "a".repeat(40) }, base: { ref: "main" } }, repository: { name: "hq", owner: { login: "novox" } } });
|
||||
assert.equal(merged.name, "forge.pull-request.merged");
|
||||
assert.equal(merged.body.merge_commit_sha, "c".repeat(40));
|
||||
assert.equal(eventOf("pull_request", { action: "label_updated", pull_request: { number: 3 }, label: { name: "mesh/ready" } }).name,
|
||||
"forge.pull-request.labeled");
|
||||
const comment = eventOf("issue_comment", { action: "created", is_pull: true, issue: { number: 3 },
|
||||
comment: { id: 9, body: "ready at abc", user: { login: "jo" } } });
|
||||
assert.equal(comment.name, "forge.pull-request.commented");
|
||||
assert.equal(comment.body.comment, "ready at abc");
|
||||
assert.equal(eventOf("push", { ref: "refs/heads/main", after: "d".repeat(40) }).name, "forge.push");
|
||||
assert.equal(eventOf("pull_request_review_approved", {}).name, "forge.other");
|
||||
});
|
||||
|
||||
test("the system webhook is made when none points at the receiver, and corrected when one does", async () => {
|
||||
const { ensureSystemHook } = await import("../webhook.ts");
|
||||
const calls: string[] = [];
|
||||
let hooks: unknown[] = [];
|
||||
const admin = { call: async (method: string, path: string, body?: any) => {
|
||||
calls.push(`${method} ${path}`);
|
||||
if (method === "GET") return { status: 200, body: hooks };
|
||||
if (method === "POST") { assert.ok(body.events.includes("pull_request") && body.events.includes("push")); assert.equal(body.config.secret, secret); return { status: 201, body: {} }; }
|
||||
return { status: 200, body: {} };
|
||||
} };
|
||||
assert.equal(await ensureSystemHook(admin, "http://h:3047/forge-event", secret), "created");
|
||||
hooks = [{ id: 4, config: { url: "http://h:3047/forge-event" } }];
|
||||
assert.equal(await ensureSystemHook(admin, "http://h:3047/forge-event", secret), "corrected");
|
||||
assert.ok(calls.includes("PATCH /admin/hooks/4"));
|
||||
});
|
||||
|
||||
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.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();
|
||||
now += 1000;
|
||||
pace.miss("novox/hq#7 at aaaaaaaa");
|
||||
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");
|
||||
});
|
||||
+60
-4
@@ -97,13 +97,25 @@ export interface MintedTokenOptions {
|
||||
readonly scopes?: readonly string[];
|
||||
readonly log?: (line: string) => void;
|
||||
readonly fetch?: typeof fetch;
|
||||
/** The clock, in milliseconds; a test sets it. */
|
||||
readonly now?: () => number;
|
||||
}
|
||||
|
||||
/**
|
||||
* **How long a failed mint is not tried again** (novox/hq issue 739). Every call that finds no token mints, and a
|
||||
* mint is two or three calls over basic auth, each one hashing the admin password on the forge. A mint that keeps
|
||||
* failing, once per tool call, is a loop the forge pays for in CPU: on 2026-10-14 it ran several times a minute
|
||||
* on the control-node while it was already overloaded. Within this window the last failure is answered again,
|
||||
* without asking the forge.
|
||||
*/
|
||||
export const MINT_RETRY_AFTER_MS = 30_000;
|
||||
|
||||
/** The token the module mints for itself, kept in its state and renewed when the forge rejects it. */
|
||||
export class MintedToken implements TokenSource {
|
||||
private held: string | null = null;
|
||||
private readFile = false;
|
||||
private inflight: Promise<string> | null = null;
|
||||
private failed: { at: number; error: unknown } | null = null;
|
||||
private readonly name: string;
|
||||
private readonly scopes: readonly string[];
|
||||
private readonly log: (line: string) => void;
|
||||
@@ -114,8 +126,11 @@ export class MintedToken implements TokenSource {
|
||||
this.scopes = opts.scopes ?? TOKEN_SCOPES;
|
||||
this.log = opts.log ?? ((line) => console.log(`[gitea] ${line}`));
|
||||
this.fetchImpl = opts.fetch ?? fetch;
|
||||
this.now = opts.now ?? Date.now;
|
||||
}
|
||||
|
||||
private readonly now: () => number;
|
||||
|
||||
/**
|
||||
* Build from the runtime's environment: the forge's URL, the admin login and password file the
|
||||
* manifest hands the runtime, and the module's state directory (MESH_GITEA_STATE_DIR, a directory
|
||||
@@ -126,7 +141,10 @@ export class MintedToken implements TokenSource {
|
||||
const opts = MintedToken.optionsFromEnv(url, env);
|
||||
// One source per kept file in a process. The watcher and the tools entrypoint both build a
|
||||
// client in the same runtime; two sources over one file would each renew on a 401 and drop the
|
||||
// other's token by name, forever. Shared, a renewal is one renewal.
|
||||
// other's token by name, forever. Shared, a renewal is one renewal. Across processes it is not shared: the
|
||||
// runtime serves the watcher (index.js) and the tools (tools/index.js) as separate bundles, so two sources over
|
||||
// one file do exist. renew() reads the kept file before it mints, and a race that still leaves two tokens by
|
||||
// the name is undone by dropping each by its id (doMint; novox/hq issue 739).
|
||||
const shared = MintedToken.shared.get(opts.file);
|
||||
if (shared) return shared;
|
||||
const source = new MintedToken(opts);
|
||||
@@ -163,7 +181,7 @@ export class MintedToken implements TokenSource {
|
||||
}
|
||||
if (kept !== null) return this.mint("the kept token was minted with other scopes than the tools take now — minting one with them");
|
||||
}
|
||||
return this.mint("no token kept — minting one");
|
||||
return this.mint(this.failed ? "no token held since the last mint failed — minting one" : "no token kept — minting one");
|
||||
}
|
||||
|
||||
async renew(rejected: string): Promise<string> {
|
||||
@@ -188,8 +206,19 @@ export class MintedToken implements TokenSource {
|
||||
/** One mint at a time: concurrent first calls share it, rather than each minting its own. */
|
||||
private mint(why: string): Promise<string> {
|
||||
if (this.inflight === null) {
|
||||
// A mint that failed a moment ago is not asked of the forge again yet (novox/hq issue 739): its error stands.
|
||||
if (this.failed !== null && this.now() - this.failed.at < MINT_RETRY_AFTER_MS) return Promise.reject(this.failed.error);
|
||||
this.log(why);
|
||||
this.inflight = this.doMint().finally(() => {
|
||||
this.inflight = this.doMint().then(
|
||||
(token) => {
|
||||
this.failed = null;
|
||||
return token;
|
||||
},
|
||||
(err) => {
|
||||
this.failed = { at: this.now(), error: err };
|
||||
throw err;
|
||||
},
|
||||
).finally(() => {
|
||||
this.inflight = null;
|
||||
});
|
||||
}
|
||||
@@ -261,7 +290,12 @@ export class MintedToken implements TokenSource {
|
||||
// went while the forge's data stayed. It is ours to replace: drop it by name and mint again.
|
||||
this.log(`the forge already holds a token named "${this.name}" — replacing it`);
|
||||
const dropped = await call("DELETE", `/${encodeURIComponent(this.name)}`);
|
||||
if (dropped.status !== 204 && dropped.status !== 404) {
|
||||
if (dropped.status === 422) {
|
||||
// More than one token carries the name (novox/hq issue 739): two processes minted at once, and the forge's
|
||||
// check that a name is unused is not atomic. The forge refuses a delete by such a name for good, so every
|
||||
// one of them is dropped by its id — all are ours, and none of their values is kept.
|
||||
await this.dropEveryNamed(call, dropped);
|
||||
} else if (dropped.status !== 204 && dropped.status !== 404) {
|
||||
throw new Error(`Gitea DELETE /users/${this.opts.admin}/tokens/${this.name}: ${dropped.status} ${detail(dropped.body)}`);
|
||||
}
|
||||
res = await call("POST", "", { name: this.name, scopes: this.scopes });
|
||||
@@ -277,6 +311,28 @@ export class MintedToken implements TokenSource {
|
||||
this.log(`minted a token for "${this.opts.admin}" (${this.scopes.join(", ")}), kept at ${this.opts.file}`);
|
||||
return token;
|
||||
}
|
||||
|
||||
/** Drop, by id, every token of the admin account that carries this name; the forge listed them, page by page. */
|
||||
private async dropEveryNamed(call: (method: string, path?: string) => Promise<{ status: number; body: any }>,
|
||||
refused: { status: number; body: any }): Promise<void> {
|
||||
const ids: number[] = [];
|
||||
for (let page = 1; page <= 20; page++) {
|
||||
const listed = await call("GET", `?page=${page}&limit=50`);
|
||||
if (listed.status !== 200 || !Array.isArray(listed.body)) {
|
||||
throw new Error(`Gitea DELETE /users/${this.opts.admin}/tokens/${this.name}: ${refused.status} ${detail(refused.body)}; ` +
|
||||
`and its tokens could not be listed to drop them one by one: ${listed.status} ${detail(listed.body)}`);
|
||||
}
|
||||
for (const t of listed.body) if (t?.name === this.name && Number.isInteger(t?.id)) ids.push(t.id);
|
||||
if (listed.body.length < 50) break;
|
||||
}
|
||||
this.log(`the forge holds ${ids.length} tokens named "${this.name}" — dropping each by its id`);
|
||||
for (const id of ids) {
|
||||
const dropped = await call("DELETE", `/${id}`);
|
||||
if (dropped.status !== 204 && dropped.status !== 404) {
|
||||
throw new Error(`Gitea DELETE /users/${this.opts.admin}/tokens/${id}: ${dropped.status} ${detail(dropped.body)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function detail(body: unknown): string {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
import { GiteaClient, type BranchProtection } from "../client.js";
|
||||
import { GiteaClient, readyAuthors, type BranchProtection } from "../client.js";
|
||||
import { appendNote, run, viewBody, viewComment } from "../delivery.js";
|
||||
import { containedFrom, isCommit, mergeableUnder, newestByContext } from "../checks.js";
|
||||
import {
|
||||
@@ -514,9 +514,9 @@ function allGiteaTools(gitea: GiteaClient): ToolDefinition[] {
|
||||
},
|
||||
{
|
||||
name: "gitea_open_pulls",
|
||||
description: "Every open pull request of every repository, from the forge itself: its head, its base, the statuses the base's protection requires and the ones its head has, each with its state, description and when it was set. What mesh-delivery reads to say a pull request the mesh was never asked to check (novox/hq issue 347), or whose check started and never answered (issue 438). Reads only.",
|
||||
description: "Every open pull request of every repository, from the forge itself: its head, its base, the statuses the base's protection requires and the ones its head has, each with its state, description and when it was set. What mesh-delivery reads to say a pull request the mesh was never asked to check (novox/hq issue 347), or whose check started and never answered (issue 438), and each pull request's labels and ready mark — the label mesh/ready and the head named by the newest comment \"ready at <full head sha>\" that a listed account (the setting ready-authors) wrote after the label was added and after the last push — which mesh-delivery merges on (issue 722). Reads only.",
|
||||
input: {},
|
||||
run: async () => ({ pulls: await gitea.openPulls() }),
|
||||
run: async () => ({ pulls: await gitea.openPulls(readyAuthors()) }),
|
||||
},
|
||||
{
|
||||
name: "gitea_contains",
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
// **The forge says every event on the bus** (novox/hq issue 729; to-be 10: an event makes it fast, nothing makes it
|
||||
// necessary). The module keeps one system webhook on its forge for every event, pointing at its own receiver, signed
|
||||
// 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.
|
||||
// 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.
|
||||
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
/** The name the receiver answers on, and the port it listens on unless the manifest says otherwise. */
|
||||
export const HOOK_PATH = "/forge-event";
|
||||
export const HOOK_PORT = 3047;
|
||||
|
||||
/** The secret the forge signs with: read from its 0600 file, or minted and kept there. */
|
||||
export function keptSecret(file: string, log: (line: string) => void = (l) => console.log(`[gitea] ${l}`)): string {
|
||||
try {
|
||||
const kept = readFileSync(file, "utf8").trim();
|
||||
if (kept.length >= 32) {
|
||||
log(`reusing the webhook secret kept at ${file}`);
|
||||
return kept;
|
||||
}
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
||||
}
|
||||
const secret = randomBytes(32).toString("hex");
|
||||
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
||||
const tmp = `${file}.tmp`;
|
||||
writeFileSync(tmp, secret + "\n", { mode: 0o600 });
|
||||
chmodSync(tmp, 0o600);
|
||||
renameSync(tmp, file);
|
||||
log(`minted a webhook secret, kept at ${file}`);
|
||||
return secret;
|
||||
}
|
||||
|
||||
/** Whether a body carries the forge's HMAC-SHA256 signature (X-Gitea-Signature, hex) under the secret. */
|
||||
export function verified(secret: string, body: Buffer | string, signature: string | undefined): boolean {
|
||||
if (!secret || !signature || !/^[0-9a-f]{64}$/i.test(signature.trim())) return false;
|
||||
const want = createHmac("sha256", secret).update(body).digest();
|
||||
const got = Buffer.from(signature.trim(), "hex");
|
||||
return got.length === want.length && timingSafeEqual(got, want);
|
||||
}
|
||||
|
||||
/** One forge event as the bus carries it: its name inside the stream, and what is needed of it — no secrets. */
|
||||
export interface ForgeEvent {
|
||||
name: string;
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Every event name the module emits for the forge, without its forge. prefix (module.json `emits`). */
|
||||
export const EVENTS: readonly string[] = ["push", "create", "delete", "fork", "status", "pull-request.opened", "pull-request.reopened", "pull-request.synchronized", "pull-request.edited", "pull-request.closed", "pull-request.merged", "pull-request.labeled", "pull-request.unlabeled", "pull-request.assigned", "pull-request.unassigned", "pull-request.reviewed", "pull-request.review-requested", "pull-request.commented", "pull-request.changed", "issue-comment.created", "issue-comment.edited", "issue-comment.deleted", "issues.opened", "issues.reopened", "issues.closed", "issues.edited", "issues.labeled", "issues.unlabeled", "issues.assigned", "issues.unassigned", "issues.changed", "release.published", "release.updated", "release.deleted", "release.changed", "repository.created", "repository.deleted", "repository.changed", "wiki.changed", "other"];
|
||||
|
||||
/** The families the module's stream carries (module.json `streams`); any other kind is said as other.<kind>; underscores become hyphens. */
|
||||
export const FAMILIES = ["push", "create", "delete", "fork", "status", "pull_request", "issue_comment", "issues",
|
||||
"release", "repository", "wiki"] as const;
|
||||
|
||||
const ACTIONS: Record<string, string> = { label_updated: "labeled", label_cleared: "unlabeled", synchronized: "synchronized" };
|
||||
|
||||
function str(v: unknown): string | undefined {
|
||||
return typeof v === "string" && v ? v : undefined;
|
||||
}
|
||||
function num(v: unknown): number | undefined {
|
||||
return typeof v === "number" ? v : undefined;
|
||||
}
|
||||
function login(u: any): string | undefined {
|
||||
return str(u?.login) ?? str(u?.username);
|
||||
}
|
||||
|
||||
/**
|
||||
* The event a forge delivery is: its kind (X-Gitea-Event) and the payload's action, trimmed to ids, repository, refs,
|
||||
* shas, author, labels and a comment's body (a ready mark is one, ADR 0364). A merge is pull-request.merged, a comment on
|
||||
* a pull request pull-request.commented.
|
||||
*/
|
||||
export function eventOf(kind: string, payload: any): ForgeEvent {
|
||||
// The bus's event names take lower-case letters, digits and hyphens: the forge's underscores become hyphens.
|
||||
const event = forgeEventOf(kind, payload);
|
||||
const name = event.name.toLowerCase().replace(/_/g, "-").replace(/[^a-z0-9.-]/g, "-");
|
||||
// Published on the module's events as it publishes its others, each name declared in its `emits`: one the manifest
|
||||
// does not name is forge.other, saying what the forge called it. Its own stream (ADR 0363) follows issue 725.
|
||||
if (EVENTS.includes(name)) return { name: `forge.${name}`, body: event.body };
|
||||
return { name: "forge.other", body: { ...event.body, kind, said: name } };
|
||||
}
|
||||
|
||||
function forgeEventOf(said: string, payload: any): ForgeEvent {
|
||||
// The forge names some kinds finer than their family (pull_request_label, pull_request_sync): read by the payload.
|
||||
let kind = said;
|
||||
if (said.startsWith("pull_request") && payload?.pull_request) kind = "pull_request";
|
||||
if ((said.startsWith("issue") || said === "pull_request_comment") && payload?.comment) kind = "issue_comment";
|
||||
if (said.startsWith("issue") && !payload?.comment && payload?.issue) kind = "issues";
|
||||
const repo = payload?.repository ?? {};
|
||||
const base: Record<string, unknown> = {
|
||||
owner: login(repo.owner), repo: str(repo.name), full_name: str(repo.full_name), clone_url: str(repo.clone_url),
|
||||
sender: login(payload?.sender),
|
||||
};
|
||||
const family = (FAMILIES as readonly string[]).includes(kind) ? kind : `other`;
|
||||
let action = str(payload?.action);
|
||||
const pull = payload?.pull_request;
|
||||
if (kind === "push") {
|
||||
return { name: "push", body: { ...base, ref: str(payload.ref), before: str(payload.before), after: str(payload.after),
|
||||
commits: Array.isArray(payload.commits) ? payload.commits.length : undefined, pusher: login(payload.pusher) } };
|
||||
}
|
||||
if (kind === "pull_request" && pull) {
|
||||
if (action === "closed" && pull.merged) action = "merged";
|
||||
action = ACTIONS[action ?? ""] ?? action ?? "changed";
|
||||
return { name: `pull_request.${action}`, body: { ...base, number: num(pull.number ?? payload.number),
|
||||
title: str(pull.title), author: login(pull.user), head: str(pull.head?.ref), head_sha: str(pull.head?.sha),
|
||||
base: str(pull.base?.ref), merged: !!pull.merged, merge_commit_sha: str(pull.merge_commit_sha),
|
||||
merged_at: str(pull.merged_at), html_url: str(pull.html_url),
|
||||
labels: Array.isArray(pull.labels) ? pull.labels.map((l: any) => str(l?.name)).filter(Boolean) : undefined,
|
||||
label: str(payload.label?.name) } };
|
||||
}
|
||||
if (kind === "issue_comment") {
|
||||
const issue = payload.issue ?? {};
|
||||
const onPull = !!payload.is_pull || !!issue.pull_request;
|
||||
return { name: onPull ? "pull_request.commented" : `issue_comment.${action ?? "created"}`, body: { ...base,
|
||||
number: num(issue.number), comment_id: num(payload.comment?.id), author: login(payload.comment?.user),
|
||||
comment: str(payload.comment?.body), action } };
|
||||
}
|
||||
if (kind === "create" || kind === "delete") {
|
||||
return { name: kind, body: { ...base, ref: str(payload.ref), ref_type: str(payload.ref_type), sha: str(payload.sha) } };
|
||||
}
|
||||
if (kind === "status") {
|
||||
return { name: "status", body: { ...base, sha: str(payload.sha), context: str(payload.context), state: str(payload.state) } };
|
||||
}
|
||||
const name = family === "other" ? `other.${kind.replace(/[^a-z0-9_-]/gi, "_") || "unknown"}` :
|
||||
["fork"].includes(family) ? family : `${family}.${action ?? "changed"}`;
|
||||
return { name, body: { ...base, number: num(payload?.number ?? payload?.issue?.number), action } };
|
||||
}
|
||||
|
||||
export interface ReceiverOptions {
|
||||
secret: string;
|
||||
port: number;
|
||||
host?: string;
|
||||
/** Publishes one event on the bus. */
|
||||
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, so the polls know events are heard. */
|
||||
heard?: () => void;
|
||||
log?: (line: string) => void;
|
||||
}
|
||||
|
||||
/** The most a delivery may carry: the forge's push of many commits stays well under it. */
|
||||
export const MAX_BODY = 5 * 1024 * 1024;
|
||||
/** How many deliveries' ids are remembered, so a delivery sent again is published once. */
|
||||
export const REMEMBERED = 2000;
|
||||
|
||||
/**
|
||||
* The receiver. A request without a signature is refused before its body is read, a body over MAX_BODY is refused, and
|
||||
* one whose signature does not verify is refused, each with 401 or 413 and a line saying so. A verified delivery is
|
||||
* answered 200 at once and queued: it is published and acted on after the reply, one at a time, so the forge's
|
||||
* delivery timeout is never reached. A delivery whose X-Gitea-Delivery id was already heard is answered and dropped.
|
||||
*/
|
||||
export function receiver(opts: ReceiverOptions): Server & { idle(): Promise<void> } {
|
||||
const log = opts.log ?? ((l) => console.log(`[gitea] ${l}`));
|
||||
const seen = new Set<string>();
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
const server = createServer((req, res) => {
|
||||
if (req.method !== "POST" || (req.url ?? "").split("?")[0] !== HOOK_PATH) {
|
||||
res.statusCode = 404;
|
||||
return res.end();
|
||||
}
|
||||
const from = req.socket.remoteAddress ?? "?";
|
||||
const signature = String(req.headers["x-gitea-signature"] ?? "").trim();
|
||||
if (!signature) {
|
||||
log(`refused a forge event from ${from}: it is unsigned`);
|
||||
res.writeHead(401, { Connection: "close" });
|
||||
res.end("unsigned\n");
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
if (Number(req.headers["content-length"] ?? 0) > MAX_BODY) {
|
||||
log(`refused a forge event from ${from}: its body is over ${MAX_BODY} bytes`);
|
||||
res.writeHead(413, { Connection: "close" });
|
||||
res.end("too large\n");
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
let over = false;
|
||||
req.on("data", (c: Buffer) => {
|
||||
size += c.length;
|
||||
if (size > MAX_BODY) {
|
||||
if (!over) {
|
||||
over = true;
|
||||
log(`refused a forge event from ${from}: its body is over ${MAX_BODY} bytes`);
|
||||
res.writeHead(413, { Connection: "close" });
|
||||
res.end("too large\n");
|
||||
req.destroy();
|
||||
}
|
||||
} else chunks.push(c);
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (over) return;
|
||||
const body = Buffer.concat(chunks);
|
||||
if (!verified(opts.secret, body, signature)) {
|
||||
log(`refused a forge event from ${from}: its signature does not verify`);
|
||||
res.statusCode = 401;
|
||||
return res.end("signature does not verify\n");
|
||||
}
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = JSON.parse(body.toString("utf8"));
|
||||
} catch {
|
||||
res.statusCode = 400;
|
||||
return res.end("not JSON\n");
|
||||
}
|
||||
opts.heard?.();
|
||||
const delivery = String(req.headers["x-gitea-delivery"] ?? "");
|
||||
if (delivery && seen.has(delivery)) {
|
||||
res.statusCode = 200;
|
||||
return res.end("already heard\n");
|
||||
}
|
||||
if (delivery) {
|
||||
seen.add(delivery);
|
||||
if (seen.size > REMEMBERED) seen.delete(seen.values().next().value as string);
|
||||
}
|
||||
const event = eventOf(String(req.headers["x-gitea-event"] ?? "other"), payload);
|
||||
res.statusCode = 200;
|
||||
res.end("queued\n");
|
||||
queue = queue.then(async () => {
|
||||
try {
|
||||
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 polls catch it — ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
return Object.assign(server, { idle: () => queue });
|
||||
}
|
||||
|
||||
/** What ensuring the system webhook needs of the forge's administration (GiteaAdmin's login). */
|
||||
export interface HookAdmin {
|
||||
call(method: string, path: string, body?: unknown): Promise<{ status: number; body: any }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* **How fast the polls look** (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.
|
||||
*/
|
||||
export class Pace {
|
||||
private last = 0;
|
||||
private missed = 0;
|
||||
private readonly now: () => number;
|
||||
private readonly log: (l: string) => void;
|
||||
constructor(now: () => number = Date.now, log: (l: string) => void = (l) => console.error(`[gitea] ${l}`)) {
|
||||
this.now = now;
|
||||
this.log = log;
|
||||
}
|
||||
heard(): void {
|
||||
this.last = this.now();
|
||||
}
|
||||
/** The poll found a head or merge no forge event announced. */
|
||||
miss(what: string): void {
|
||||
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 = this.now();
|
||||
}
|
||||
hearing(): boolean {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/** Every event family the forge (1.27) can send a webhook. */
|
||||
export const HOOK_EVENTS = ["create", "delete", "fork", "push", "issues", "issue_comment", "pull_request",
|
||||
"pull_request_review_request", "wiki", "repository", "release", "package", "status", "workflow_run", "workflow_job"];
|
||||
|
||||
/**
|
||||
* **One system webhook, for every event, at the receiver** (issue 729): created when none points there, corrected
|
||||
* when one does but differs (events, active, content type), and its secret set again each start — the forge never
|
||||
* hands a secret back, so a corrected secret cannot be told from a kept one. Answers what it did.
|
||||
*/
|
||||
export async function ensureSystemHook(admin: HookAdmin, url: string, secret: string): Promise<"created" | "corrected"> {
|
||||
// POST /admin/hooks makes a system webhook, and its options take no flag for it (the forge's 1.27.3 API schema). The
|
||||
// forge has no "every event" word: each family is named, and a family name (issues, pull_request) takes all of it.
|
||||
const want = { type: "gitea", active: true, events: HOOK_EVENTS, branch_filter: "*",
|
||||
config: { url, content_type: "json", secret } };
|
||||
const listed = await admin.call("GET", "/admin/hooks?type=system&limit=50");
|
||||
if (listed.status !== 200) throw new Error(`the forge's system webhooks could not be listed: ${listed.status}`);
|
||||
const hooks: any[] = Array.isArray(listed.body) ? listed.body : [];
|
||||
const ours = hooks.filter((h) => h?.config?.url === url);
|
||||
if (ours.length === 0) {
|
||||
const made = await admin.call("POST", "/admin/hooks", want);
|
||||
if (made.status !== 201 && made.status !== 200) throw new Error(`the forge's system webhook could not be made: ${made.status}`);
|
||||
return "created";
|
||||
}
|
||||
for (const extra of ours.slice(1)) await admin.call("DELETE", `/admin/hooks/${extra.id}`);
|
||||
const fixed = await admin.call("PATCH", `/admin/hooks/${ours[0].id}`, { active: true, events: HOOK_EVENTS, branch_filter: "*",
|
||||
config: { url, content_type: "json", secret } });
|
||||
if (fixed.status !== 200) throw new Error(`the forge's system webhook could not be corrected: ${fixed.status}`);
|
||||
return "corrected";
|
||||
}
|
||||
|
||||
/**
|
||||
* **Claim a head for announcing, once** (issue 729): true when `sha` is not already the head recorded for `key`, which
|
||||
* it then is. The poll and the forge's event both claim before they announce, so whichever comes second finds it taken.
|
||||
*/
|
||||
export function claimHead(heads: Record<string, string>, key: string, sha: string): boolean {
|
||||
if (!sha || heads[key] === sha) return false;
|
||||
heads[key] = sha;
|
||||
return true;
|
||||
}
|
||||
@@ -104,7 +104,9 @@
|
||||
],
|
||||
"env": {
|
||||
"MESH_LAB_WORK": "${dir:work}",
|
||||
"MESH_LAB_ENV_FILE": "${dir:state}/lab.env"
|
||||
"MESH_LAB_ENV_FILE": "${dir:state}/lab.env",
|
||||
"MESH_LAB_FORGE_BINDING": "${dir:state}/package-registry.json",
|
||||
"MESH_LAB_FORGE_SECRET": "${dir:state}/package-registry.secret"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
BASE_IMAGE_ALIAS, BASE_MAX_AGE_DAYS, baseImageFrom, baseProblem, baseScript, buildingBase, cleanCredentials, credentialPath,
|
||||
describeBase, launchRebuild, launchRun, listBaseBuilds, listRuns, readStatus, runRefusal, running, staleBase,
|
||||
type BaseImage,
|
||||
} from "../tools/runs.ts";
|
||||
|
||||
// Defends novox/hq issue 698: the lab's base image was 44 days old, a bed machine raised from it carried a
|
||||
// package database the mirrors no longer served, and genesis-keeps-its-bus stopped on a 404 for
|
||||
// postgresql-libs. Nothing said how old the image was, nothing refused it, and no mesh tool rebuilt it.
|
||||
|
||||
const now = new Date("2026-10-14T01:00:00Z");
|
||||
const listed = (uploaded: string, alias = BASE_IMAGE_ALIAS) => JSON.stringify([
|
||||
{ aliases: [{ name: "images:other" }], uploaded_at: "2026-10-13T00:00:00Z" },
|
||||
{ aliases: [{ name: alias }], uploaded_at: uploaded, created_at: "2026-08-01T00:00:00Z" },
|
||||
]);
|
||||
|
||||
test("the base image's age is read from when this machine made it", () => {
|
||||
const b = baseImageFrom(listed("2026-08-31T09:00:00Z"), now);
|
||||
assert.equal(b.exists, true);
|
||||
assert.equal(b.built, "2026-08-31T09:00:00.000Z");
|
||||
assert.equal(b.ageDays, 43);
|
||||
assert.match(describeBase(b), /built 2026-08-31T09:00:00.000Z \(43 day\(s\) ago; the bound is 14\)/);
|
||||
});
|
||||
|
||||
test("an image older than the bound refuses a run, naming the tool that rebuilds it", () => {
|
||||
const stale = baseImageFrom(listed("2026-08-31T09:00:00Z"), now);
|
||||
const reason = runRefusal(stale);
|
||||
assert.ok(reason, "a 43-day-old base image was not refused");
|
||||
assert.match(reason, /older than the lab's bound of 14 days/);
|
||||
assert.match(reason, /lab_base \{"rebuild": true\}/);
|
||||
assert.equal(staleBase(stale), reason);
|
||||
});
|
||||
|
||||
test("an image within the bound runs", () => {
|
||||
const fresh = baseImageFrom(listed(new Date(now.getTime() - BASE_MAX_AGE_DAYS * 86_400_000).toISOString()), now);
|
||||
assert.equal(fresh.ageDays, BASE_MAX_AGE_DAYS);
|
||||
assert.equal(runRefusal(fresh), undefined);
|
||||
});
|
||||
|
||||
test("a missing image, or one whose age cannot be read, is said and not refused", () => {
|
||||
const none = baseImageFrom(listed("2026-10-01T00:00:00Z", "something-else"), now);
|
||||
assert.equal(none.exists, false);
|
||||
assert.equal(runRefusal(none), undefined);
|
||||
assert.match(describeBase(none), /is not on this machine; rebuild it with lab_base/);
|
||||
const unread = baseImageFrom(undefined, now);
|
||||
assert.equal(runRefusal(unread), undefined);
|
||||
assert.match(describeBase(unread), /its age is not known/);
|
||||
});
|
||||
|
||||
test("no run starts while the base image is rebuilt", () => {
|
||||
const fresh = baseImageFrom(listed("2026-10-13T00:00:00Z"), now);
|
||||
const reason = runRefusal(fresh, { id: "base-x", started: "2026-10-14T00:59:00Z" });
|
||||
assert.match(reason ?? "", /is being rebuilt \(base-x/);
|
||||
});
|
||||
|
||||
test("a rebuild is mesh-lab's base build from the forge's main, with no secret in its script", () => {
|
||||
const s = baseScript("/work/base-x", "https://forge.invalid", "/work/.base-x.git-credentials");
|
||||
assert.match(s, /clone --quiet --depth 1 'https:\/\/forge.invalid\/novox\/mesh-lab.git'/);
|
||||
assert.match(s, /src\/cli.ts base build/);
|
||||
assert.ok(s.indexOf("rm -f '/work/.base-x.git-credentials'") < s.indexOf("npm ci"), "the credential outlives the clone");
|
||||
});
|
||||
|
||||
test("a rebuild is known by its status, and is not a run", () => {
|
||||
const work = mkdtempSync(join(tmpdir(), "lab-base-"));
|
||||
try {
|
||||
mkdirSync(join(work, "base-1"));
|
||||
writeFileSync(join(work, "base-1", "status.json"), JSON.stringify({ id: "base-1", state: "built", started: "2026-10-13T00:00:00Z" }));
|
||||
mkdirSync(join(work, "base-2"));
|
||||
// A build whose process is gone while it says building was lost, and holds nothing up.
|
||||
writeFileSync(join(work, "base-2", "status.json"), JSON.stringify({ id: "base-2", state: "building", started: "2026-10-14T00:00:00Z", pid: 2 ** 22 + 7 }));
|
||||
assert.deepEqual(listBaseBuilds(work).map((b) => `${b.id} ${b.state}`), ["base-2 lost", "base-1 built"]);
|
||||
assert.equal(buildingBase(work), undefined);
|
||||
writeFileSync(join(work, "base-2", "status.json"), JSON.stringify({ id: "base-2", state: "building", started: "2026-10-14T00:00:00Z", pid: process.pid }));
|
||||
assert.equal(buildingBase(work)?.id, "base-2");
|
||||
assert.deepEqual(listRuns(work), []);
|
||||
assert.ok(readFileSync(join(work, "base-1", "status.json"), "utf8"));
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// **A run and a rebuild asked together: one starts** (review 256). Each asks the package registry, which
|
||||
// waits, and each refused while the other was going; asked at once, both passed their checks before either
|
||||
// wrote its status. The registry is asked first now, and the check and the start are one step.
|
||||
function aLab(): string {
|
||||
return mkdtempSync(join(tmpdir(), "lab-launch-"));
|
||||
}
|
||||
const fresh: BaseImage = { alias: BASE_IMAGE_ALIAS, exists: true, built: "2026-10-13T00:00:00.000Z", ageDays: 1 };
|
||||
const slowRegistry = () => new Promise<{ registry: string }>((ok) => setTimeout(() => ok({ registry: "https://forge.invalid/r/" }), 20));
|
||||
const launch = { registry: slowRegistry, base: () => fresh };
|
||||
function beginRun(work: string, id: string) {
|
||||
return () => {
|
||||
mkdirSync(join(work, id));
|
||||
const s = { id, state: "running" as const, started: new Date().toISOString(), tests: [], refs: {}, pid: process.pid };
|
||||
writeFileSync(join(work, id, "status.json"), JSON.stringify(s));
|
||||
return s;
|
||||
};
|
||||
}
|
||||
function beginBuild(work: string, id: string) {
|
||||
return () => {
|
||||
mkdirSync(join(work, id));
|
||||
const b = { id, state: "building" as const, started: new Date().toISOString(), pid: process.pid };
|
||||
writeFileSync(join(work, id, "status.json"), JSON.stringify(b));
|
||||
return b;
|
||||
};
|
||||
}
|
||||
|
||||
test("a run and a rebuild asked at once: exactly one starts", async () => {
|
||||
for (const runFirst of [true, false]) {
|
||||
const work = aLab();
|
||||
try {
|
||||
// Both asked before either answers, in one order and then the other.
|
||||
const ask = { run: () => launchRun(work, launch, beginRun(work, "run-a")), build: () => launchRebuild(work, launch, beginBuild(work, "base-a")) };
|
||||
const [r, b] = runFirst ? await Promise.all([ask.run(), ask.build()])
|
||||
: (await Promise.all([ask.build(), ask.run()])).reverse() as [Awaited<ReturnType<typeof ask.run>>, Awaited<ReturnType<typeof ask.build>>];
|
||||
assert.equal([r.started, b.started].filter(Boolean).length, 1, `both or neither started: run ${r.started}, rebuild ${b.started}`);
|
||||
assert.equal(listRuns(work).length + listBaseBuilds(work).length, 1);
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("two runs, or two rebuilds, asked at once: one of each starts", async () => {
|
||||
const work = aLab();
|
||||
try {
|
||||
const runs = await Promise.all([launchRun(work, launch, beginRun(work, "run-a")), launchRun(work, launch, beginRun(work, "run-b"))]);
|
||||
assert.deepEqual(runs.map((r) => r.started).sort(), [false, true]);
|
||||
const other = aLab();
|
||||
const builds = await Promise.all([launchRebuild(other, launch, beginBuild(other, "base-a")), launchRebuild(other, launch, beginBuild(other, "base-b"))]);
|
||||
assert.deepEqual(builds.map((b) => b.started).sort(), [false, true]);
|
||||
rmSync(other, { recursive: true, force: true });
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a run is refused on a stale base, and starts nothing", async () => {
|
||||
const work = aLab();
|
||||
try {
|
||||
const stale: BaseImage = { alias: BASE_IMAGE_ALIAS, exists: true, built: "2026-08-31T09:00:00.000Z", ageDays: 43 };
|
||||
const r = await launchRun(work, { registry: slowRegistry, base: () => stale }, beginRun(work, "run-a"));
|
||||
assert.equal(r.started, false);
|
||||
assert.match(r.started ? "" : r.reason, /lab_base \{"rebuild": true\}/);
|
||||
assert.deepEqual(listRuns(work), []);
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a rebuild or a run that never recorded its process is lost, and holds nothing up", () => {
|
||||
const work = aLab();
|
||||
try {
|
||||
mkdirSync(join(work, "base-x"));
|
||||
writeFileSync(join(work, "base-x", "status.json"), JSON.stringify({ id: "base-x", state: "building", started: "2026-10-14T00:00:00Z" }));
|
||||
mkdirSync(join(work, "run-x"));
|
||||
writeFileSync(join(work, "run-x", "status.json"), JSON.stringify({ id: "run-x", state: "running", started: "2026-10-14T00:00:00Z", tests: [], refs: {} }));
|
||||
assert.equal(listBaseBuilds(work)[0]?.state, "lost");
|
||||
assert.equal(buildingBase(work), undefined);
|
||||
assert.equal(readStatus(work, "run-x")?.state, "lost");
|
||||
assert.equal(running(work), undefined);
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a rebuild's credential left behind is cleaned, and a running one's is kept", () => {
|
||||
const work = aLab();
|
||||
try {
|
||||
for (const id of ["base-old", "base-now", "run-old", "run-now"]) writeFileSync(credentialPath(work, id), "x");
|
||||
const removed = cleanCredentials(work, [credentialPath(work, "base-now"), credentialPath(work, "run-now")]).sort();
|
||||
assert.deepEqual(removed, [credentialPath(work, "base-old"), credentialPath(work, "run-old")].sort());
|
||||
} finally {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("lab_check's problem: a stale, missing or unread base image; a fresh one is none", () => {
|
||||
assert.match(baseProblem({ alias: BASE_IMAGE_ALIAS, exists: false }) ?? "", /is not on this machine/);
|
||||
assert.match(baseProblem({ alias: BASE_IMAGE_ALIAS, exists: false, problem: "incus could not list the lab's images" }) ?? "", /age is not known/);
|
||||
assert.match(baseProblem({ alias: BASE_IMAGE_ALIAS, exists: true, built: "x", ageDays: 30 }) ?? "", /older than the lab's bound/);
|
||||
assert.equal(baseProblem(fresh), undefined);
|
||||
});
|
||||
|
||||
// The tools use the gate and the check above (index.ts registers with the SDK when imported, so it is read).
|
||||
test("lab_run and lab_base start through the gate, and lab_check names what is wrong with the base", () => {
|
||||
const index = readFileSync(new URL("../tools/index.ts", import.meta.url), "utf8");
|
||||
assert.match(index, /await launchRun\(work,/);
|
||||
assert.match(index, /await launchRebuild\(work,/);
|
||||
assert.match(index, /const unfit = baseProblem\(base\);\s*if \(unfit\) problems\.push\(unfit\)/);
|
||||
assert.match(index, /if \(args\.rebuild !== true\) return reading;/);
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { spawnSync } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { installPlan, installStep, NPM_REPOSITORIES, REPOSITORIES, script } from "../tools/runs.ts";
|
||||
import { installPlan, installStep, NPM_REPOSITORIES, outcomeOf, readStatus, REPOSITORIES, script } from "../tools/runs.ts";
|
||||
|
||||
// Defends novox/hq issue 624: lab_run ran `npm ci` at the root of every checkout it installs, and
|
||||
// mesh-tools keeps its package in node-tools/ with no lock file at its root, so every run failed at its
|
||||
@@ -194,3 +194,295 @@ test("the lab asks the package registry for read only", () => {
|
||||
assert.ok(m.requires.includes("npm-package-registry"));
|
||||
assert.equal(m.contributes?.["npm-package-registry"]?.access, "read");
|
||||
});
|
||||
|
||||
// lab_check failed for ever on "destination path '<work>/check' already exists": it cloned into one fixed
|
||||
// path and ignored whether removing the last one worked (novox/hq issue 624). Each check now works in a
|
||||
// fresh directory, and what earlier checks left is cleared or named.
|
||||
import { checkDir, clearChecks } from "../tools/runs.ts";
|
||||
|
||||
test("each check gets a fresh directory of its own", () => {
|
||||
const work = mkdtempSync(join(tmpdir(), "lab-work-"));
|
||||
const a = checkDir(work);
|
||||
const b = checkDir(work);
|
||||
assert.notEqual(a, b);
|
||||
assert.ok(a.startsWith(join(work, "check-")) && existsSync(a) && existsSync(b));
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// As root nothing is locked against removal, so the unremovable tree cannot be made: skipped there, before
|
||||
// it makes anything (the merge check runs as root).
|
||||
test("what earlier checks left is cleared, and what cannot be is named rather than tripped over", {
|
||||
skip: process.getuid?.() === 0 ? "running as root, which no directory mode stops from removing anything" : false,
|
||||
}, () => {
|
||||
const work = mkdtempSync(join(tmpdir(), "lab-work-"));
|
||||
for (const d of ["check/src", "check-setup/mesh-lab", "check-abc", "run-x", "keep"]) mkdirSync(join(work, d), { recursive: true });
|
||||
// A tree this account cannot empty: a directory it may not write, with something in it.
|
||||
mkdirSync(join(work, "check-stuck", "locked"), { recursive: true });
|
||||
writeFileSync(join(work, "check-stuck", "locked", "file"), "x");
|
||||
chmodSync(join(work, "check-stuck", "locked"), 0o555);
|
||||
const said = clearChecks(work);
|
||||
chmodSync(join(work, "check-stuck", "locked"), 0o755);
|
||||
for (const gone of ["check", "check-setup", "check-abc"]) assert.equal(existsSync(join(work, gone)), false, gone);
|
||||
assert.ok(existsSync(join(work, "run-x")) && existsSync(join(work, "keep")));
|
||||
assert.equal(said.length, 1);
|
||||
assert.match(said[0] as string, /check-stuck, left by an earlier check, could not be removed/);
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// And as root too: what earlier checks left is cleared.
|
||||
test("leftover checks are cleared, whoever runs the check", () => {
|
||||
const work = mkdtempSync(join(tmpdir(), "lab-work-"));
|
||||
for (const d of ["check/src", "check-setup/mesh-lab", "check-abc", "run-x"]) mkdirSync(join(work, d), { recursive: true });
|
||||
assert.deepEqual(clearChecks(work), []);
|
||||
for (const gone of ["check", "check-setup", "check-abc"]) assert.equal(existsSync(join(work, gone)), false, gone);
|
||||
assert.ok(existsSync(join(work, "run-x")));
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// The lab's tools read the bound credential, so the runtime is given that file by the tools bundle's env
|
||||
// (ADR 0192), as gitea and umami are given theirs: the runtime's account may then read exactly it, and no
|
||||
// other credential changes hands (issue 624).
|
||||
test("the lab's tools bundle names its bound credential and binding in its env", () => {
|
||||
const m = JSON.parse(readFileSync(join(import.meta.dirname, "..", "module.json"), "utf8")) as {
|
||||
secrets: Record<string, string>; binds: Record<string, string>;
|
||||
build: { artifacts: { name: string; env?: Record<string, string> }[] };
|
||||
};
|
||||
const env = m.build.artifacts.find((a) => a.name === "code")?.env ?? {};
|
||||
assert.equal(env.MESH_LAB_FORGE_SECRET, m.secrets["npm-package-registry"]);
|
||||
assert.equal(env.MESH_LAB_FORGE_BINDING, m.binds["npm-package-registry"]);
|
||||
});
|
||||
|
||||
// The next setup failure of novox/hq issue 624 (run-2026-10-13T13-15-26-634Z on shanks): npm 12 refused
|
||||
// mesh-tools' locked @novox/mesh-sdk with EALLOWREMOTE. The lab named the registry by its forge setting's
|
||||
// address (http://novox.internal:20000/…), the lock file holds the address the forge writes every tarball
|
||||
// URL at (https://git.novox.be/…), and npm 12 installs a locked tarball only from its configured registry.
|
||||
// A run names the registry by the address the registry names itself by.
|
||||
import { npmRegistry } from "../tools/runs.ts";
|
||||
|
||||
function aRegistry(answer: () => Response | Promise<Response>): { get: typeof fetch; asked: string[] } {
|
||||
const asked: string[] = [];
|
||||
const get = (async (url: string | URL | Request) => {
|
||||
asked.push(String(url));
|
||||
return answer();
|
||||
}) as typeof fetch;
|
||||
return { get, asked };
|
||||
}
|
||||
|
||||
const packument = (tarball: string) => new Response(JSON.stringify({
|
||||
name: "@novox/mesh-sdk", "dist-tags": { latest: "0.1.14" },
|
||||
versions: { "0.1.1": { dist: { tarball: "http://old.example/api/packages/novox/npm/x.tgz" } }, "0.1.14": { dist: { tarball } } },
|
||||
}), { status: 200, headers: { "content-type": "application/json" } });
|
||||
|
||||
test("a run names the package registry by the address the registry gives its tarballs", async () => {
|
||||
const r = aRegistry(() => packument("https://forge.example.org/api/packages/novox/npm/%40novox%2Fmesh-sdk/-/0.1.14/mesh-sdk-0.1.14.tgz"));
|
||||
const got = await npmRegistry("http://forge.example.org:3000/", r.get, "https://forge.example.org/api/packages/novox/npm/");
|
||||
assert.deepEqual(got, { registry: "https://forge.example.org/api/packages/novox/npm/" });
|
||||
assert.deepEqual(r.asked, ["http://forge.example.org:3000/api/packages/novox/npm/@novox%2fmesh-sdk"]);
|
||||
// The forge's own scheme is taken too, with its port.
|
||||
const plain = await npmRegistry("http://forge.example.org:3000",
|
||||
aRegistry(() => packument("http://forge.example.org:3000/api/packages/novox/npm/%40novox%2Fmesh-sdk/-/0.1.14/mesh-sdk-0.1.14.tgz")).get);
|
||||
assert.deepEqual(plain, { registry: "http://forge.example.org:3000/api/packages/novox/npm/" });
|
||||
});
|
||||
|
||||
// What the registry answers may come over plain HTTP, so it never decides where packages come from: only
|
||||
// the forge's public root or its own address, scheme, host and port, under the npm path, with nothing after
|
||||
// it (review of mesh-catalog #275, ADR 0346).
|
||||
test("a registry that does not give an address the lab takes leaves the forge's, and the reason is said", async () => {
|
||||
const sdk = "/api/packages/novox/npm/%40novox%2Fmesh-sdk/-/0.1.14/mesh-sdk-0.1.14.tgz";
|
||||
for (const [answer, why] of [
|
||||
[() => new Response("not found", { status: 404 }), /it answered 404/],
|
||||
[() => new Response("{}", { status: 200 }), /no tarball/],
|
||||
[() => { throw new Error("connect ECONNREFUSED"); }, /ECONNREFUSED/],
|
||||
[() => packument(`https://forge.example.org/elsewhere/mesh-sdk-0.1.14.tgz`), /not under \/api\/packages\/novox\/npm\//],
|
||||
[() => packument(`https://attacker.example.net${sdk}`), /at https:\/\/attacker\.example\.net, which is neither the forge's public root nor its own address/],
|
||||
[() => packument(`https://attacker.example.net/x?u=https://novox.internal${sdk}`), /query or a fragment/],
|
||||
[() => packument(`https://novox.internal${sdk}?x=1`), /query or a fragment/],
|
||||
[() => packument(`https://novox.internal${sdk}#frag`), /query or a fragment/],
|
||||
[() => packument(`https://attacker.example.net/#https://novox.internal${sdk}`), /query or a fragment/],
|
||||
[() => packument(`ftp://novox.internal${sdk}`), /at ftp:\/\/novox\.internal, which is neither/],
|
||||
[() => packument(`file:///api/packages/novox/npm/x.tgz`), /which is neither/],
|
||||
[() => packument(`https://novox.internal/api/packages/novox/npm/\nregistry=https://attacker.example.net/\nallow-remote=all`), /whitespace or a control character/],
|
||||
[() => packument(`https://user:pw@novox.internal${sdk}`), /user or password/],
|
||||
] as [() => Response, RegExp][]) {
|
||||
const got = await npmRegistry("http://novox.internal:20000", aRegistry(answer).get);
|
||||
assert.equal(got.registry, "http://novox.internal:20000/api/packages/novox/npm/", String(why));
|
||||
assert.match(got.problem ?? "", /did not give an address the lab takes/);
|
||||
assert.match(got.problem ?? "", why);
|
||||
}
|
||||
});
|
||||
|
||||
test("a run's npm configuration names the registry it was given, and the forge's own address only without one", () => {
|
||||
const given = script("/work", "run-x", "http://novox.internal:20000", ["t.test.ts"], {}, undefined,
|
||||
"https://forge.example.org/api/packages/novox/npm/");
|
||||
assert.match(given, / '@novox:registry=https:\/\/forge\.example\.org\/api\/packages\/novox\/npm\/' > '\/work\/run-x\/\.npmrc'\n/);
|
||||
assert.doesNotMatch(given, /@novox:registry=http:\/\/novox\.internal/);
|
||||
const none = script("/work", "run-x", "http://novox.internal:20000", ["t.test.ts"], {});
|
||||
assert.match(none, /'@novox:registry=http:\/\/novox\.internal:20000\/api\/packages\/novox\/npm\/'/);
|
||||
});
|
||||
|
||||
// The public root the forge serves in the lab's binding (novox/hq ADR 0346) is the one other origin a
|
||||
// tarball may come from, by scheme, host and port: the review of #275 found the port ignored.
|
||||
import { publicRootOf } from "../tools/runs.ts";
|
||||
|
||||
test("a tarball is taken at the forge's public root, and at no other port or scheme of its host", async () => {
|
||||
const sdk = "/api/packages/novox/npm/%40novox%2Fmesh-sdk/-/0.1.14/mesh-sdk-0.1.14.tgz";
|
||||
const root = "https://git.example.org/api/packages/novox/npm/";
|
||||
const at = (tarball: string, publicRoot?: string) =>
|
||||
npmRegistry("http://novox.internal:20000", aRegistry(() => packument(tarball)).get, publicRoot);
|
||||
assert.deepEqual(await at(`https://git.example.org${sdk}`, root), { registry: root });
|
||||
for (const tarball of [`https://git.example.org:8443${sdk}`, `http://git.example.org${sdk}`, `https://example.org${sdk}`]) {
|
||||
const got = await at(tarball, root);
|
||||
assert.equal(got.registry, "http://novox.internal:20000/api/packages/novox/npm/", tarball);
|
||||
assert.match(got.problem ?? "", /neither the forge's public root nor its own address/, tarball);
|
||||
}
|
||||
// Without a public root, the forge's public name is not trusted on its own word.
|
||||
assert.match((await at(`https://git.example.org${sdk}`)).problem ?? "", /neither/);
|
||||
// And the forge's own address only at its own port.
|
||||
assert.match((await at(`http://novox.internal${sdk}`, root)).problem ?? "", /neither/);
|
||||
});
|
||||
|
||||
test("the public root is read from the binding, and only an https root at the npm path is taken", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "lab-root-"));
|
||||
const binding = (root: unknown) => {
|
||||
const f = join(dir, `b-${Math.random()}.json`);
|
||||
writeFileSync(f, JSON.stringify({ provision: "npm-package-registry", at: "home", serves: { scheme: "http", port: 3000,
|
||||
"npm-path": "/api/packages/novox/npm/", ...(root === undefined ? {} : { "public-root": root }) } }));
|
||||
return f;
|
||||
};
|
||||
assert.deepEqual(publicRootOf(binding("https://git.example.org/api/packages/novox/npm/")),
|
||||
{ root: "https://git.example.org/api/packages/novox/npm/" });
|
||||
assert.deepEqual(publicRootOf(binding("https://git.example.org:8443/api/packages/novox/npm/")),
|
||||
{ root: "https://git.example.org:8443/api/packages/novox/npm/" });
|
||||
for (const [root, why] of [
|
||||
[undefined, /serves no public-root/],
|
||||
["http://git.example.org/api/packages/novox/npm/", /is not https:\/\/<host>/],
|
||||
["https://git.example.org/elsewhere/", /is not https:\/\/<host>/],
|
||||
["https://git.example.org/api/packages/novox/npm/?x=1", /is not https:\/\/<host>/],
|
||||
["https://u:p@git.example.org/api/packages/novox/npm/", /is not https:\/\/<host>/],
|
||||
["https://git.example.org/api/packages/novox/npm/\nallow-remote=all", /whitespace or a control character/],
|
||||
["https://${bound:route:name-web}/api/packages/novox/npm/", /not a URL|is not https/],
|
||||
] as [unknown, RegExp][]) {
|
||||
const got = publicRootOf(binding(root));
|
||||
assert.equal(got.root, undefined, String(root));
|
||||
assert.match(got.problem ?? "", why, String(root));
|
||||
}
|
||||
assert.match(publicRootOf(join(dir, "none.json")).problem ?? "", /could not be read/);
|
||||
assert.match(publicRootOf(undefined).problem ?? "", /no npm-package-registry binding/);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// A forge setting that is not http(s) is never a trusted origin (review of #280): a `file:` tarball's origin
|
||||
// is "null", as is a `file:` forge's, and the two must not match.
|
||||
test("a forge setting that is not http(s) trusts no origin of its own", async () => {
|
||||
const got = await npmRegistry("file:///srv/forge", aRegistry(() => packument("file:///api/packages/novox/npm/x.tgz")).get);
|
||||
assert.match(got.problem ?? "", /neither the forge's public root nor its own address/);
|
||||
const root = "https://git.example.org/api/packages/novox/npm/";
|
||||
const viaRoot = await npmRegistry("ftp://novox.internal", aRegistry(() =>
|
||||
packument("ftp://novox.internal/api/packages/novox/npm/x.tgz")).get, root);
|
||||
assert.match(viaRoot.problem ?? "", /neither/);
|
||||
});
|
||||
|
||||
// Defends novox/hq issue 693: a run whose only test skipped as NOT REACHED read "0 passed, 0 failed", exit 0,
|
||||
// and lab_status said passed. The log's tail, as run-2026-10-14T00-21-44-014Z on shanks wrote it.
|
||||
const oldLog = [
|
||||
"STOPPED at step 16 of 24, base: \t\t\t\tMake sure you have all the referenced content and try again.",
|
||||
"\ufe63 genesis adopts its bus as the nats module in place: one bus, its streams kept, the node connected (588152.016874ms) # ADR 0333 §5 NOT REACHED: the first run stopped at step 16 of 24, base, before the broker step:",
|
||||
" \t\t\t\tMake sure you have all the referenced content and try again.",
|
||||
"NotFound: content digest sha256:e2de96513ba9: not found",
|
||||
"ℹ tests 1", "ℹ suites 0", "ℹ pass 0", "ℹ fail 0", "ℹ cancelled 0", "ℹ skipped 1", "ℹ todo 0",
|
||||
"ℹ duration_ms 590254.163993",
|
||||
"",
|
||||
"recorded: test/integration/genesis-keeps-its-bus.test.ts — 0 passed, 0 failed, against mesh-lab 7ed7da1",
|
||||
].join("\n");
|
||||
|
||||
// The same run, as the lab's suite says it once it names its skips (mesh-lab, issue 693).
|
||||
const newLog = [
|
||||
"ℹ tests 1", "ℹ pass 0", "ℹ fail 0", "ℹ skipped 1",
|
||||
"",
|
||||
"recorded: test/integration/genesis-keeps-its-bus.test.ts — 0 passed, 0 failed, 1 skipped, against mesh-lab 7ed7da1",
|
||||
"NOT PASSED: no test passed: 1 skipped, 1 of them as NOT REACHED",
|
||||
"skipped: genesis adopts its bus — one bus (test/integration/genesis-keeps-its-bus.test.ts) # ADR 0333 §5 NOT REACHED: the first run stopped at step 16 of 24, base: NotFound: content digest",
|
||||
].join("\n");
|
||||
|
||||
function anEndedRun(log: string, state: "passed" | "failed", exit: number): { work: string; id: string } {
|
||||
const work = mkdtempSync(join(tmpdir(), "lab-runs-"));
|
||||
const id = "run-2026-10-14T00-21-44-014Z";
|
||||
mkdirSync(join(work, id));
|
||||
writeFileSync(join(work, id, "run.log"), log);
|
||||
writeFileSync(join(work, id, "status.json"), JSON.stringify({
|
||||
id, state, exit, started: "2026-10-14T00:21:44.014Z", ended: "2026-10-14T00:33:11.179Z",
|
||||
tests: ["test/integration/genesis-keeps-its-bus.test.ts"], refs: {},
|
||||
}));
|
||||
return { work, id };
|
||||
}
|
||||
|
||||
test("a run whose only test skipped as NOT REACHED, from a lab of before, reads as failed with the reason", () => {
|
||||
const { work, id } = anEndedRun(oldLog, "passed", 0);
|
||||
const s = readStatus(work, id);
|
||||
assert.equal(s?.state, "failed", JSON.stringify(s));
|
||||
assert.equal(s?.exit, 0);
|
||||
assert.equal(s?.outcome?.passed, 0);
|
||||
assert.equal(s?.outcome?.skipped, 1);
|
||||
assert.equal(s?.outcome?.notPassed, "no test passed: 1 skipped, 1 of them as NOT REACHED");
|
||||
assert.match(s?.outcome?.skips[0]?.reason ?? "", /^ADR 0333 §5 NOT REACHED: the first run stopped at step 16 of 24, base, before the broker step:$/);
|
||||
// Kept in the run's record, not only answered.
|
||||
const kept = JSON.parse(readFileSync(join(work, id, "status.json"), "utf8"));
|
||||
assert.equal(kept.state, "failed");
|
||||
assert.equal(kept.outcome.notPassed, "no test passed: 1 skipped, 1 of them as NOT REACHED");
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("the lab's own NOT PASSED and skipped lines are read, a test name's punctuation and all", () => {
|
||||
const { work, id } = anEndedRun(newLog, "failed", 1);
|
||||
const s = readStatus(work, id);
|
||||
assert.equal(s?.state, "failed");
|
||||
assert.equal(s?.outcome?.notPassed, "no test passed: 1 skipped, 1 of them as NOT REACHED");
|
||||
assert.deepEqual(s?.outcome?.skips, [{
|
||||
file: "test/integration/genesis-keeps-its-bus.test.ts",
|
||||
test: "genesis adopts its bus — one bus",
|
||||
reason: "ADR 0333 §5 NOT REACHED: the first run stopped at step 16 of 24, base: NotFound: content digest",
|
||||
}]);
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("a run that passed tests and skipped one for a declared reason stays passed, its skip listed", () => {
|
||||
const log = [
|
||||
"✔ a module lands (12ms)",
|
||||
"﹣ a builder builds (0.1ms) # set MESH_LAB_BUILDER to a built mesh-builder",
|
||||
"ℹ tests 2", "ℹ pass 1", "ℹ fail 0", "ℹ skipped 1",
|
||||
].join("\n");
|
||||
const { work, id } = anEndedRun(log, "passed", 0);
|
||||
const s = readStatus(work, id);
|
||||
assert.equal(s?.state, "passed");
|
||||
assert.equal(s?.outcome?.notPassed, undefined);
|
||||
assert.equal(s?.outcome?.skips[0]?.reason, "set MESH_LAB_BUILDER to a built mesh-builder");
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("a run that ran no test at all is not passed", () => {
|
||||
assert.equal(outcomeOf("ℹ tests 0\nℹ pass 0\nℹ fail 0\nℹ skipped 0\n").notPassed, "no test passed: none ran");
|
||||
});
|
||||
|
||||
// Review 254 on issue 693: a test's own output, printed before the suite reports, is not the suite's verdict.
|
||||
test("a line a test printed that looks like the suite's is not read as the suite's", () => {
|
||||
const log = [
|
||||
"NOT PASSED: a test printed this",
|
||||
"skipped: a forged skip (test/integration/x.test.ts) # FORGED NOT REACHED",
|
||||
"✔ a module lands (12ms)",
|
||||
"ℹ tests 1", "ℹ pass 1", "ℹ fail 0", "ℹ skipped 0",
|
||||
"",
|
||||
"recorded: test/integration/x.test.ts — 1 passed, 0 failed, 0 skipped, against mesh-lab 7ed7da1",
|
||||
].join("\n");
|
||||
const o = outcomeOf(log);
|
||||
assert.equal(o.notPassed, undefined, JSON.stringify(o));
|
||||
assert.deepEqual(o.skips, []);
|
||||
});
|
||||
|
||||
test("not reached is matched in any case", () => {
|
||||
const log = [
|
||||
"✔ a module lands (12ms)",
|
||||
"﹣ the broker step (0.1ms) # the broker step was not reached",
|
||||
"ℹ tests 2", "ℹ pass 1", "ℹ fail 0", "ℹ skipped 1",
|
||||
].join("\n");
|
||||
assert.equal(outcomeOf(log).notPassed, "1 test(s) skipped as NOT REACHED: their subject was not reached");
|
||||
});
|
||||
|
||||
+78
-18
@@ -8,8 +8,9 @@ import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
cleanCredentials, credentialArgs, forgeCredential, installPlan, listRuns, NPM_REPOSITORIES, readStatus, REPOSITORIES, running, start,
|
||||
stop, tail, writeCredential,
|
||||
checkDir, cleanCredentials, clearChecks, credentialArgs, forgeCredential, installPlan, listRuns, npmRegistry, NPM_REPOSITORIES, publicRootOf, readStatus, REPOSITORIES, running, start,
|
||||
stop, tail, writeCredential, baseBuildLog, buildingBase, listBaseBuilds, startBaseBuild, credentialPath, launchRun,
|
||||
launchRebuild, BASE_MAX_AGE_DAYS, describeBase, readBaseImage, baseProblem,
|
||||
} from "./runs.js";
|
||||
|
||||
export function getLabTools(env: NodeJS.ProcessEnv): ToolDefinition[] {
|
||||
@@ -19,6 +20,14 @@ export function getLabTools(env: NodeJS.ProcessEnv): ToolDefinition[] {
|
||||
// without restarting the runtime. MESH_LAB_FORGE itself still wins, for a hand-run instance.
|
||||
const forgeOf = (): string => (env.MESH_LAB_FORGE ?? wordIn(env.MESH_LAB_ENV_FILE, "MESH_LAB_FORGE")).replace(/\/+$/, "");
|
||||
// The forge credential the mesh binds and seals to the lab (novox/hq issue 624), read at each call.
|
||||
// The registry's public root the forge serves in the lab's binding (novox/hq ADR 0346), read at each call.
|
||||
const bindingOf = (): string | undefined =>
|
||||
env.MESH_LAB_FORGE_BINDING ?? (wordIn(env.MESH_LAB_ENV_FILE, "MESH_LAB_FORGE_BINDING") || undefined);
|
||||
const registryOf = async (forge: string) => {
|
||||
const root = publicRootOf(bindingOf());
|
||||
const registry = await npmRegistry(forge, fetch, root.root);
|
||||
return registry.problem && root.problem ? { ...registry, problem: `${registry.problem}; ${root.problem}` } : registry;
|
||||
};
|
||||
const credentialOf = (forge: string): string | undefined => forgeCredential(forge,
|
||||
env.MESH_LAB_FORGE_BINDING ?? wordIn(env.MESH_LAB_ENV_FILE, "MESH_LAB_FORGE_BINDING"),
|
||||
env.MESH_LAB_FORGE_SECRET ?? wordIn(env.MESH_LAB_ENV_FILE, "MESH_LAB_FORGE_SECRET"));
|
||||
@@ -30,22 +39,39 @@ export function getLabTools(env: NodeJS.ProcessEnv): ToolDefinition[] {
|
||||
run: async () => {
|
||||
const forge = forgeOf();
|
||||
if (!forge) return { ok: false, output: "the lab's forge is not set: settings for lab, {\"forge\": \"<url>\"}" };
|
||||
const dir = `${work}/check`;
|
||||
spawnSync("rm", ["-rf", dir]);
|
||||
const clone = spawnSync("git", ["clone", "--quiet", "--depth", "1", `${forge}/novox/mesh-lab.git`, dir], { encoding: "utf8" });
|
||||
if (clone.status !== 0) return { ok: false, output: clone.stderr };
|
||||
spawnSync("npm", ["ci", "--no-audit", "--no-fund", "--loglevel=error"], { cwd: dir, encoding: "utf8" });
|
||||
const check = spawnSync("node", ["--experimental-strip-types", "src/cli.ts", "check"], { cwd: dir, encoding: "utf8" });
|
||||
// What earlier checks left is cleared, and what could not be is said; this check works in a fresh
|
||||
// directory of its own either way, and removes it when it is done.
|
||||
const leftovers = clearChecks(work);
|
||||
const dir = checkDir(work);
|
||||
let check: ReturnType<typeof spawnSync>;
|
||||
let problems: string[];
|
||||
try {
|
||||
const clone = spawnSync("git", ["clone", "--quiet", "--depth", "1", `${forge}/novox/mesh-lab.git`, dir], { encoding: "utf8" });
|
||||
if (clone.status !== 0) return { ok: false, output: [String(clone.stderr).trim(), ...leftovers].join("\n") };
|
||||
spawnSync("npm", ["ci", "--no-audit", "--no-fund", "--loglevel=error"], { cwd: dir, encoding: "utf8" });
|
||||
check = spawnSync("node", ["--experimental-strip-types", "src/cli.ts", "check"], { cwd: dir, encoding: "utf8" });
|
||||
problems = setupProblems(forge, `${dir}/setup`, credentialOf(forge));
|
||||
// And the address a run names the package registry by (npmRegistry): said when the registry does not say it.
|
||||
const registry = await registryOf(forge);
|
||||
if (registry.problem) problems.push(registry.problem);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
// **And what a run would check out and install, before a run finds out** (novox/hq issue 624): every
|
||||
// repository it clones answers on the forge, and every one it installs has a lock file where the run
|
||||
// installs from.
|
||||
// A credential a stopped, crashed or rebooted run left behind is removed, and said; one still in use
|
||||
// by a running run is not.
|
||||
const busy = running(work);
|
||||
const left = cleanCredentials(work, busy ? `${work}/.${busy.id}.git-credentials` : undefined);
|
||||
const problems = setupProblems(forge, `${work}/check-setup`, credentialOf(forge));
|
||||
const removed = left.length > 0 ? `removed ${left.length} forge credential(s) a run left behind: ${left.join(", ")}` : "";
|
||||
const output = [`${check.stdout}${check.stderr}`.trim(), removed, ...problems].filter(Boolean).join("\n");
|
||||
// A credential a stopped, crashed or rebooted run or rebuild left behind is removed, and said; one still in
|
||||
// use by a running run or rebuild is not.
|
||||
const busy = [running(work)?.id, buildingBase(work)?.id].filter((id): id is string => !!id);
|
||||
const left = cleanCredentials(work, busy.map((id) => credentialPath(work, id)));
|
||||
const removed = left.length > 0 ? `removed ${left.length} forge credential(s) a run or rebuild left behind: ${left.join(", ")}` : "";
|
||||
// **And how old the base image is** (novox/hq issue 698): past the bound, missing, or of an age that cannot
|
||||
// be read is a problem here, though lab_run refuses only the first.
|
||||
const base = readBaseImage();
|
||||
const unfit = baseProblem(base);
|
||||
if (unfit) problems.push(unfit);
|
||||
const output = [`${check.stdout}${check.stderr}`.trim(), describeBase(base), removed, ...leftovers, ...problems]
|
||||
.filter(Boolean).join("\n");
|
||||
return { ok: check.status === 0 && problems.length === 0, output };
|
||||
},
|
||||
},
|
||||
@@ -77,9 +103,43 @@ export function getLabTools(env: NodeJS.ProcessEnv): ToolDefinition[] {
|
||||
}
|
||||
const stranger = Object.keys(refs).filter((r) => !REPOSITORIES.includes(r));
|
||||
if (stranger.length > 0) return { started: false, reason: `the lab does not build ${stranger.join(", ")}` };
|
||||
const busy = running(work);
|
||||
if (busy) return { started: false, reason: `${busy.id} is still ${busy.state}; one run at a time`, running: busy };
|
||||
return { started: true, run: start(work, forge, tests, refs, credentialOf(forge)) };
|
||||
// **One job at a time, not on a base image past its bound, nor while it is rebuilt** (novox/hq issue 698,
|
||||
// review 256): the registry asked first, then the check and the start with nothing awaited between.
|
||||
const launched = await launchRun(work, { registry: () => registryOf(forge), base: () => readBaseImage() },
|
||||
(registry) => start(work, forge, tests, refs, credentialOf(forge), registry));
|
||||
if (!launched.started) return launched;
|
||||
return { started: true, run: launched.job, base: describeBase(launched.base), registry: launched.registry,
|
||||
...(launched.problem ? { problem: launched.problem } : {}) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lab_base",
|
||||
description:
|
||||
"The lab's base image, which every bed machine with a container runtime is raised from: when it was built, its " +
|
||||
`age, the bound lab_run refuses past (${BASE_MAX_AGE_DAYS} days), and the last rebuilds with the newest one's log. ` +
|
||||
"Reads only, unless rebuild is true: then it rebuilds the image with mesh-lab's `base build` from the forge's " +
|
||||
"main, in the background, and answers at once; ask again for the build's state and the image's new age.",
|
||||
input: {
|
||||
rebuild: { type: "boolean", description: "rebuild the image (default false: only read)" },
|
||||
},
|
||||
run: async (args) => {
|
||||
const before = readBaseImage();
|
||||
const builds = listBaseBuilds(work).slice(0, 3);
|
||||
const newest = builds[0];
|
||||
const reading = {
|
||||
base: before, said: describeBase(before), bound: BASE_MAX_AGE_DAYS,
|
||||
...(baseProblem(before) ? { problem: baseProblem(before) } : {}),
|
||||
builds, ...(newest ? { log: baseBuildLog(work, newest.id) } : {}),
|
||||
};
|
||||
if (args.rebuild !== true) return reading;
|
||||
const forge = forgeOf();
|
||||
if (!forge) return { ...reading, started: false, reason: "the lab's forge is not set: settings for lab, {\"forge\": \"<url>\"}" };
|
||||
// Not under a run, nor beside another rebuild: the registry asked first, then the check and the start with
|
||||
// nothing awaited between (review 256).
|
||||
const launched = await launchRebuild(work, { registry: () => registryOf(forge), base: () => before },
|
||||
(registry) => startBaseBuild(work, forge, credentialOf(forge), registry));
|
||||
if (launched.started === false) return { ...reading, started: false, reason: launched.reason };
|
||||
return { ...reading, started: true, build: launched.job };
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
+504
-16
@@ -6,8 +6,8 @@
|
||||
// and that file is the whole of what the tools read back: a runtime that restarts mid-run still answers
|
||||
// for it, and says it was lost rather than pretending it is still going.
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
/**
|
||||
@@ -60,6 +60,108 @@ export function installStep(root: string, build: boolean): string {
|
||||
fi`;
|
||||
}
|
||||
|
||||
/** Where the forge serves the mesh's npm packages, under its own address (gitea's npm registry for the novox org). */
|
||||
export const NPM_PATH = "/api/packages/novox/npm/";
|
||||
|
||||
/**
|
||||
* The registry's public root, as the forge serves it in the lab's npm-package-registry binding
|
||||
* (`serves.public-root`, novox/hq ADR 0346): the forge's route's composed public name under the npm path.
|
||||
* The mesh writes the binding, and it is checked all the same: an https URL whose path is the npm path and
|
||||
* nothing else. Undefined, with why, when the binding has none or it is not that shape — a forge on a
|
||||
* machine with no public domain serves none (ADR 0346 §3).
|
||||
*/
|
||||
export function publicRootOf(bindingFile: string | undefined): { root?: string; problem?: string } {
|
||||
if (!bindingFile) return { problem: "the lab has no npm-package-registry binding" };
|
||||
let said: unknown;
|
||||
try {
|
||||
said = (JSON.parse(readFileSync(bindingFile, "utf8")) as { serves?: Record<string, unknown> }).serves?.["public-root"];
|
||||
} catch (e) {
|
||||
return { problem: `its npm-package-registry binding could not be read: ${e instanceof Error ? e.message : String(e)}` };
|
||||
}
|
||||
if (typeof said !== "string" || !said) return { problem: "its npm-package-registry binding serves no public-root" };
|
||||
if (/[\s\u0000-\u001f\u007f]/.test(said)) return { problem: "the binding's public-root holds whitespace or a control character" };
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(said);
|
||||
} catch {
|
||||
return { problem: `the binding's public-root ${JSON.stringify(said)} is not a URL` };
|
||||
}
|
||||
if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || u.pathname !== NPM_PATH) {
|
||||
return { problem: `the binding's public-root ${JSON.stringify(said)} is not https://<host>${NPM_PATH}` };
|
||||
}
|
||||
return { root: `${u.origin}${NPM_PATH}` };
|
||||
}
|
||||
|
||||
/**
|
||||
* The address a run names the @novox registry by: the one the registry names itself by, when that is the
|
||||
* forge's public root or the forge's own address (novox/hq issue 624, ADR 0346).
|
||||
*
|
||||
* **npm 12 installs a locked tarball only from the registry it is configured with.** Its `allow-remote`
|
||||
* defaults to `none`, and a lock file's `resolved` URL counts as the registry's only when its origin and
|
||||
* path are the configured scope registry's; any other is a "remote" tarball and refused (EALLOWREMOTE).
|
||||
* The forge writes every tarball URL — in what it answers, and so in every lock file made against it — at
|
||||
* its own public address, whichever address it was asked at. So the lab asks the registry, at the forge,
|
||||
* for the SDK's newest tarball and names the registry by the origin of that URL.
|
||||
*
|
||||
* **What the registry answers is not trusted for where packages come from** (review of mesh-catalog #275):
|
||||
* it may be fetched over plain HTTP. The tarball URL is parsed, and taken only when it carries no
|
||||
* whitespace, control character, user, password, query or fragment, its path is under the npm path, and
|
||||
* its origin — scheme, host and port — is one the lab already trusts: the public root the forge serves in
|
||||
* the lab's binding (`publicRoot`, ADR 0346), or the forge setting's own. The registry is then built from
|
||||
* the parsed origin and the npm path alone, never from the string answered, so nothing the registry says
|
||||
* reaches the run's npm configuration but a scheme, a host and a port. Anything else falls back to the
|
||||
* forge's own address and says why, so a run still starts and lab_check names it.
|
||||
*/
|
||||
export async function npmRegistry(forge: string, get: typeof fetch = fetch, publicRoot?: string):
|
||||
Promise<{ registry: string; problem?: string }> {
|
||||
const asked = `${forge.replace(/\/+$/, "")}${NPM_PATH}`;
|
||||
const url = `${asked}@novox%2fmesh-sdk`;
|
||||
const fallback = (why: string) => ({
|
||||
registry: asked,
|
||||
problem: `the package registry at ${url} did not give an address the lab takes (${why}), so a run names it ${asked}, and npm 12 refuses a locked @novox tarball at any other`,
|
||||
});
|
||||
let own: URL;
|
||||
try {
|
||||
own = new URL(forge);
|
||||
} catch {
|
||||
return fallback(`the forge ${JSON.stringify(forge)} is not a URL`);
|
||||
}
|
||||
// The forge setting's own origin is trusted only as an http(s) one: any other scheme's origin is
|
||||
// "null", or names no registry npm would fetch from.
|
||||
const trusted = own.protocol === "https:" || own.protocol === "http:" ? [own.origin] : [];
|
||||
if (publicRoot) {
|
||||
try {
|
||||
trusted.unshift(new URL(publicRoot).origin);
|
||||
} catch {
|
||||
// publicRootOf hands only a parsed root; a caller's other string is not trusted.
|
||||
}
|
||||
}
|
||||
try {
|
||||
const res = await get(url, { signal: AbortSignal.timeout(15_000) });
|
||||
if (!res.ok) return fallback(`it answered ${res.status}`);
|
||||
const doc = await res.json() as { "dist-tags"?: { latest?: string }; versions?: Record<string, { dist?: { tarball?: unknown } }> };
|
||||
const latest = doc["dist-tags"]?.latest ?? "";
|
||||
const tarball = doc.versions?.[latest]?.dist?.tarball;
|
||||
if (typeof tarball !== "string" || !tarball) return fallback("no tarball for its latest version");
|
||||
if (/[\s\u0000-\u001f\u007f]/.test(tarball)) return fallback("its tarball URL holds whitespace or a control character");
|
||||
let t: URL;
|
||||
try {
|
||||
t = new URL(tarball);
|
||||
} catch {
|
||||
return fallback("its tarball is not a URL");
|
||||
}
|
||||
if (t.username || t.password) return fallback("its tarball URL carries a user or password");
|
||||
if (t.search || t.hash) return fallback("its tarball URL carries a query or a fragment");
|
||||
if (!t.pathname.startsWith(NPM_PATH)) return fallback(`its tarball is not under ${NPM_PATH}`);
|
||||
if (!trusted.includes(t.origin)) {
|
||||
return fallback(`its tarball is at ${t.origin}, which is neither the forge's public root nor its own address (${trusted.join(", ")})`);
|
||||
}
|
||||
return { registry: `${t.origin}${NPM_PATH}` };
|
||||
} catch (e) {
|
||||
return fallback(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The forge credential a run's clones may present, as a git credential-store line —
|
||||
* scheme://user:password@host[:port] — for the forge's own origin, or undefined when the lab holds none.
|
||||
@@ -121,22 +223,55 @@ trap ${shellQuote(`${rm}; exit 129`)} HUP`;
|
||||
}
|
||||
|
||||
/**
|
||||
* cleanCredentials removes every run's credential file left in the work directory but the one named — what
|
||||
* a crash or a reboot left behind, which no trap could remove. Answers what it removed.
|
||||
* cleanCredentials removes every run's and every base rebuild's credential file left in the work directory
|
||||
* but the ones named — what a crash or a reboot left behind, which no trap could remove. Answers what it
|
||||
* removed.
|
||||
*/
|
||||
export function cleanCredentials(work: string, keep?: string): string[] {
|
||||
export function cleanCredentials(work: string, keep?: string | string[]): string[] {
|
||||
if (!existsSync(work)) return [];
|
||||
const kept = new Set([keep ?? []].flat());
|
||||
const removed: string[] = [];
|
||||
for (const name of readdirSync(work)) {
|
||||
if (!/^\.run-.*\.git-credentials$/.test(name)) continue;
|
||||
if (!/^\.(run|base)-.*\.git-credentials$/.test(name)) continue;
|
||||
const path = join(work, name);
|
||||
if (path === keep) continue;
|
||||
if (kept.has(path)) continue;
|
||||
rmSync(path, { force: true });
|
||||
removed.push(path);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* checkDir is a directory of lab_check's own for one check, fresh each time (novox/hq issue 624). The check
|
||||
* cloned into the one fixed path `<work>/check`, removing it first and ignoring whether that worked; a tree
|
||||
* an earlier check left that this account could not remove — one cloned as another account before the
|
||||
* work directory was the operator's — made every check fail on "destination path already exists".
|
||||
*/
|
||||
export function checkDir(work: string): string {
|
||||
mkdirSync(work, { recursive: true });
|
||||
return mkdtempSync(join(work, "check-"));
|
||||
}
|
||||
|
||||
/**
|
||||
* clearChecks removes what earlier checks left in the work directory — the fixed `check` and `check-setup`
|
||||
* of before, and any `check-*` — and says, for each it could not remove, which and why, so a check reports
|
||||
* it rather than tripping over it.
|
||||
*/
|
||||
export function clearChecks(work: string): string[] {
|
||||
if (!existsSync(work)) return [];
|
||||
const said: string[] = [];
|
||||
for (const name of readdirSync(work)) {
|
||||
if (name !== "check" && name !== "check-setup" && !name.startsWith("check-")) continue;
|
||||
const path = join(work, name);
|
||||
try {
|
||||
rmSync(path, { recursive: true, force: true });
|
||||
} catch (err) {
|
||||
said.push(`${path}, left by an earlier check, could not be removed: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
return said;
|
||||
}
|
||||
|
||||
/** The arguments that have git offer the credential in that file, and only that one. */
|
||||
export function credentialArgs(path: string | undefined): string {
|
||||
if (!path) return "";
|
||||
@@ -153,6 +288,117 @@ export interface RunStatus {
|
||||
commits?: Record<string, string>;
|
||||
exit?: number;
|
||||
pid?: number;
|
||||
/** What the suite said of its tests, read from the run's log once it ended (novox/hq issue 693). */
|
||||
outcome?: Outcome;
|
||||
}
|
||||
|
||||
/** One skipped test, its file and the reason it gave. */
|
||||
export interface Skip {
|
||||
file: string;
|
||||
test: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a run's suite said of its tests: its totals, each skip with its reason, and — when the run did not
|
||||
* pass although its exit said 0 — why (`notPassed`). Totals the runner did not print are absent.
|
||||
*/
|
||||
export interface Outcome {
|
||||
passed?: number;
|
||||
failed?: number;
|
||||
skipped?: number;
|
||||
skips: Skip[];
|
||||
notPassed?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* outcomeOf reads what a run's log says of its tests (novox/hq issue 693).
|
||||
*
|
||||
* **A run in which no test passed has proven nothing**, and the runner exits 0 when every test skipped:
|
||||
* the genesis bed skipped its only test as "NOT REACHED", the suite printed "0 passed, 0 failed", and the
|
||||
* lab recorded the run as passed. The lab's suite now says it itself — a "NOT PASSED: <why>" line and a
|
||||
* "skipped: <test> (<file>) # <reason>" line per skip after its "recorded:" line, and an exit that is not
|
||||
* 0 — and this reads those lines. For a run of a lab from before (a branch, or an old log), the same rule is
|
||||
* read from the runner's own output: its summary totals, and its skip lines' first line of reason.
|
||||
*
|
||||
* The rule, the lab suite's (mesh-lab src/outcomes.ts): **not passed when no test passed**, or when a test
|
||||
* skipped as NOT REACHED (its subject was not reached); a skip for another reason beside tests that passed
|
||||
* leaves the run passed, its reason listed.
|
||||
*/
|
||||
export function outcomeOf(log: string): Outcome {
|
||||
const plain = log.replace(/\u001b\[[0-9;]*m/g, "");
|
||||
const total = (word: string) => {
|
||||
// The last summary in the log: the runner's own, once per run.
|
||||
const all = [...plain.matchAll(new RegExp(`^\\s*(?:\u2139|#)\\s*${word}\\s+(\\d+)\\s*$`, "gm"))];
|
||||
const last = all[all.length - 1];
|
||||
return last ? Number(last[1]) : undefined;
|
||||
};
|
||||
const outcome: Outcome = { skips: [] };
|
||||
const passed = total("pass");
|
||||
const failed = total("fail");
|
||||
const skipped = total("skipped");
|
||||
if (passed !== undefined) outcome.passed = passed;
|
||||
if (failed !== undefined) outcome.failed = failed;
|
||||
if (skipped !== undefined) outcome.skipped = skipped;
|
||||
|
||||
// **The suite's own lines are read only after its last "recorded:" line** (novox/hq issue 693, review
|
||||
// 254): a test prints what it likes before the suite reports, and a line of its that looked like the
|
||||
// suite's — "NOT PASSED: …", "skipped: … # NOT REACHED" — would otherwise stand for the suite's verdict.
|
||||
const recorded = [...plain.matchAll(/^recorded: .*$/gm)];
|
||||
const lastRecorded = recorded[recorded.length - 1];
|
||||
const suiteSaid = lastRecorded ? plain.slice((lastRecorded.index ?? 0) + lastRecorded[0].length) : "";
|
||||
|
||||
// The suite's own line, "skipped: <test> (<file>) # <reason>": the file in brackets, a .ts, parts it.
|
||||
for (const m of suiteSaid.matchAll(/^skipped: (.*?) \(([^()]+\.ts)\) # (.*)$/gm)) {
|
||||
outcome.skips.push({ file: m[2] ?? "", test: m[1] ?? "", reason: m[3] === "no reason given" ? "" : m[3] ?? "" });
|
||||
}
|
||||
if (outcome.skips.length === 0) {
|
||||
// A lab from before names no skip itself; its runner's spec line does: "﹣ <test> (<ms>ms) # <reason>".
|
||||
for (const m of plain.matchAll(/^\s*\ufe63 (.*?) \([\d.]+m?s\) # (.*)$/gm)) {
|
||||
const reason = (m[2] ?? "").trim();
|
||||
outcome.skips.push({ file: "", test: m[1] ?? "", reason: reason === "SKIP" ? "" : reason });
|
||||
}
|
||||
}
|
||||
|
||||
const said = suiteSaid.match(/^NOT PASSED: (.*)$/m);
|
||||
if (said) {
|
||||
outcome.notPassed = (said[1] ?? "").trim();
|
||||
} else if ((failed ?? 0) === 0) {
|
||||
// In any case: "not reached" says the same as "NOT REACHED".
|
||||
const unreached = outcome.skips.filter((s) => s.reason.toUpperCase().includes("NOT REACHED")).length;
|
||||
if (passed === 0) {
|
||||
outcome.notPassed = outcome.skips.length > 0 || (skipped ?? 0) > 0
|
||||
? `no test passed: ${skipped ?? outcome.skips.length} skipped${unreached > 0 ? `, ${unreached} of them as NOT REACHED` : ""}`
|
||||
: "no test passed: none ran";
|
||||
} else if (unreached > 0) {
|
||||
outcome.notPassed = `${unreached} test(s) skipped as NOT REACHED: their subject was not reached`;
|
||||
}
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/**
|
||||
* settled is a run that ended, with its outcome read from its log: a run whose exit said 0 and whose suite
|
||||
* proved nothing reads as failed, with why (novox/hq issue 693). Read once and kept in its status, so the
|
||||
* record says it too; a run still going, stopped or lost is left as it is.
|
||||
*/
|
||||
export function settled(work: string, s: RunStatus): RunStatus {
|
||||
if (s.outcome || !s.ended || (s.state !== "passed" && s.state !== "failed")) return s;
|
||||
let log: string;
|
||||
try {
|
||||
log = readFileSync(join(runDir(work, s.id), "run.log"), "utf8");
|
||||
} catch {
|
||||
return s;
|
||||
}
|
||||
const outcome = outcomeOf(log);
|
||||
const next: RunStatus = { ...s, outcome };
|
||||
if (next.state === "passed" && outcome.notPassed) next.state = "failed";
|
||||
try {
|
||||
writeFileSync(statusPath(work, s.id), JSON.stringify(next, null, 2));
|
||||
} catch {
|
||||
// Read again next time: what lab_status answers is the same either way.
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function runDir(work: string, id: string): string {
|
||||
@@ -167,16 +413,23 @@ export function readStatus(work: string, id: string): RunStatus | undefined {
|
||||
try {
|
||||
const s = JSON.parse(readFileSync(statusPath(work, id), "utf8")) as RunStatus;
|
||||
// A run whose process is gone while its status still says it is going was lost — the runtime or
|
||||
// the machine restarted under it. Said, rather than left reading as running for ever.
|
||||
if (!["passed", "failed", "stopped", "lost"].includes(s.state) && s.pid && !alive(s.pid)) {
|
||||
// the machine restarted under it. Said, rather than left reading as running for ever. One that never
|
||||
// recorded a process (the runtime died between writing its status and starting it) is lost too: it
|
||||
// would otherwise hold up every run after it (review 256).
|
||||
if (!["passed", "failed", "stopped", "lost"].includes(s.state) && gone(s.pid)) {
|
||||
s.state = "lost";
|
||||
}
|
||||
return s;
|
||||
return settled(work, s);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** gone is whether a job's process is not running: none recorded, or none by that id. */
|
||||
function gone(pid: number | undefined): boolean {
|
||||
return !pid || !alive(pid);
|
||||
}
|
||||
|
||||
function alive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
@@ -209,7 +462,7 @@ const shellQuote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
|
||||
* at this run's own tree, so what is built and claimed is exactly what was checked out.
|
||||
*/
|
||||
export function script(work: string, id: string, forge: string, tests: string[], refs: Record<string, string>,
|
||||
credential?: string): string {
|
||||
credential?: string, registry = `${forge}${NPM_PATH}`): string {
|
||||
const dir = runDir(work, id);
|
||||
const setState = (state: string) =>
|
||||
`node -e ${shellQuote(
|
||||
@@ -235,9 +488,9 @@ node -e ${shellQuote(
|
||||
`const fs=require("fs");const f=${JSON.stringify(join(dir, "status.json"))};const s=JSON.parse(fs.readFileSync(f,"utf8"));s.commits=Object.fromEntries(fs.readFileSync(${JSON.stringify(join(dir, "commits.txt"))},"utf8").trim().split("\\n").map(l=>l.split(" ")));fs.writeFileSync(f,JSON.stringify(s,null,2))`,
|
||||
)}
|
||||
${setState("building")}
|
||||
# The @novox scope resolves from the mesh's own package registry on the forge, as the builder
|
||||
# resolves it; nothing else is asked of it.
|
||||
printf '%s\n' ${shellQuote(`@novox:registry=${forge}/api/packages/novox/npm/`)} > ${shellQuote(join(dir, ".npmrc"))}
|
||||
# The @novox scope resolves from the mesh's own package registry on the forge, named by the address it
|
||||
# names itself by (npmRegistry), which is the address its lock files hold; nothing else is asked of it.
|
||||
printf '%s\n' ${shellQuote(`@novox:registry=${registry}`)} > ${shellQuote(join(dir, ".npmrc"))}
|
||||
export NPM_CONFIG_USERCONFIG=${shellQuote(join(dir, ".npmrc"))}
|
||||
${NPM_REPOSITORIES.map((repo) => installStep(join(dir, repo), repo !== "mesh-lab")).join("\n")}
|
||||
mkdir -p ${shellQuote(bin)}
|
||||
@@ -263,7 +516,7 @@ node --experimental-strip-types src/cli.ts suite ${tests.map(shellQuote).join("
|
||||
|
||||
/** start begins a run and returns at once with its status. */
|
||||
export function start(work: string, forge: string, tests: string[], refs: Record<string, string>,
|
||||
credential?: string): RunStatus {
|
||||
credential?: string, registry?: string): RunStatus {
|
||||
const id = `run-${new Date().toISOString().replace(/[:.]/g, "-")}`;
|
||||
const dir = runDir(work, id);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
@@ -272,7 +525,7 @@ export function start(work: string, forge: string, tests: string[], refs: Record
|
||||
// What a crashed or rebooted run left behind goes before this run writes its own.
|
||||
cleanCredentials(work);
|
||||
const credentials = writeCredential(credentialPath(work, id), credential);
|
||||
writeFileSync(join(dir, "run.sh"), script(work, id, forge, tests, refs, credentials), { mode: 0o700 });
|
||||
writeFileSync(join(dir, "run.sh"), script(work, id, forge, tests, refs, credentials, registry), { mode: 0o700 });
|
||||
|
||||
// The wrapper records how the run ended, then removes the checkouts and keeps the log and status: a
|
||||
// run's tree is its own, and the next run starts from fresh ones (novox/hq ADR 0172).
|
||||
@@ -313,3 +566,238 @@ export function tail(work: string, id: string, lines: number): string {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the base image (novox/hq issue 698)
|
||||
//
|
||||
// Every bed machine that needs a container runtime is a clone of one base image, `mesh-lab/base`, which
|
||||
// mesh-lab's `base build` makes from the distribution's current image. A machine raised from it carries the
|
||||
// package database the image was built with. On a rolling distribution the mirrors stop serving what an old
|
||||
// database names within weeks, and a bed that installs a package then fails on a 404 that reads as a mirror
|
||||
// outage (novox/hq issue 205; seen 2026-10-14 when genesis-keeps-its-bus installed postgresql-libs from a
|
||||
// database six weeks old). So the lab names the image's age wherever it is asked, refuses a run on an image
|
||||
// older than the bound, and rebuilds the image when asked to.
|
||||
//
|
||||
// **The bound is 14 days** (BASE_MAX_AGE_DAYS). Arch's mirrors keep a package version for as long as it is
|
||||
// current and drop it soon after it is replaced; an image a fortnight old has reliably installed what beds
|
||||
// install, and the one that failed was 44 days old. A rebuild takes minutes, so a short bound costs little;
|
||||
// a run refused is cheaper than a bed that fails an hour in for a reason that is not the change under test.
|
||||
|
||||
/** The image every bed machine with a runtime is raised from, as mesh-lab names it (src/lifecycle/place.ts). */
|
||||
export const BASE_IMAGE_ALIAS = "mesh-lab/base";
|
||||
|
||||
/** How old the base image may be, in days, before a run is refused (see the head of this file). */
|
||||
export const BASE_MAX_AGE_DAYS = 14;
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
export interface BaseImage {
|
||||
alias: string;
|
||||
/** Whether the image is there at all. */
|
||||
exists: boolean;
|
||||
/** When this machine made it, ISO. */
|
||||
built?: string;
|
||||
/** Its age in whole days. */
|
||||
ageDays?: number;
|
||||
/** Why its age could not be read, when it could not. */
|
||||
problem?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* baseImageFrom reads `incus image list <alias> --format json`: the image whose aliases hold the base's
|
||||
* name, and when it was made here (its upload, which a publish sets).
|
||||
*/
|
||||
export function baseImageFrom(listed: string | undefined, now: Date): BaseImage {
|
||||
const alias = BASE_IMAGE_ALIAS;
|
||||
if (listed === undefined) return { alias, exists: false, problem: "incus could not list the lab's images" };
|
||||
let images: Array<{ aliases?: Array<{ name?: string }>; uploaded_at?: string; created_at?: string }>;
|
||||
try {
|
||||
images = JSON.parse(listed);
|
||||
} catch {
|
||||
return { alias, exists: false, problem: "incus listed the lab's images as something that is not JSON" };
|
||||
}
|
||||
const image = (Array.isArray(images) ? images : []).find((i) => (i.aliases ?? []).some((a) => a.name === alias));
|
||||
if (!image) return { alias, exists: false };
|
||||
const made = [image.uploaded_at, image.created_at].map((t) => (t ? Date.parse(t) : NaN))
|
||||
.find((t) => Number.isFinite(t) && t > 0);
|
||||
if (made === undefined) return { alias, exists: true, problem: "incus gives no time the image was made" };
|
||||
return { alias, exists: true, built: new Date(made).toISOString(), ageDays: Math.floor((now.getTime() - made) / DAY) };
|
||||
}
|
||||
|
||||
/** readBaseImage asks incus, on this machine, for the base image. */
|
||||
export function readBaseImage(now = new Date()): BaseImage {
|
||||
const listed = spawnSync("incus", ["image", "list", BASE_IMAGE_ALIAS, "--format", "json"], { encoding: "utf8" });
|
||||
return baseImageFrom(listed.status === 0 ? listed.stdout : undefined, now);
|
||||
}
|
||||
|
||||
/** The base image's age in one sentence, as lab_check and lab_run say it. */
|
||||
export function describeBase(b: BaseImage): string {
|
||||
if (b.problem) return `the base image ${b.alias}: its age is not known: ${b.problem}`;
|
||||
if (!b.exists) return `the base image ${b.alias} is not on this machine; rebuild it with lab_base {"rebuild": true}`;
|
||||
return `the base image ${b.alias} was built ${b.built} (${b.ageDays} day(s) ago; the bound is ${BASE_MAX_AGE_DAYS})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* staleBase is why a run is refused for its base image, or undefined when it is not: an image older than the
|
||||
* bound. An image that is missing or whose age cannot be read is not refused here — a bed that needs it says
|
||||
* so itself, and a bed that does not need it runs.
|
||||
*/
|
||||
export function staleBase(b: BaseImage): string | undefined {
|
||||
if (!b.exists || b.ageDays === undefined || b.ageDays <= BASE_MAX_AGE_DAYS) return undefined;
|
||||
return `the base image ${b.alias} was built ${b.built}, ${b.ageDays} days ago, older than the lab's bound of ` +
|
||||
`${BASE_MAX_AGE_DAYS} days: a bed machine raised from it carries a package database the mirrors no longer serve ` +
|
||||
`(novox/hq issues 205, 698). Rebuild it with lab_base {"rebuild": true}, then run again`;
|
||||
}
|
||||
|
||||
/**
|
||||
* baseProblem is what lab_check and lab_base say is wrong with the base image, or undefined: past the bound, not
|
||||
* on this machine, or of an age that cannot be read (review 256). Only the first refuses a run.
|
||||
*/
|
||||
export function baseProblem(b: BaseImage): string | undefined {
|
||||
if (b.problem || !b.exists) return describeBase(b);
|
||||
return staleBase(b);
|
||||
}
|
||||
|
||||
/**
|
||||
* runRefusal is why lab_run starts no run for the base image, or undefined: a rebuild still going, which
|
||||
* replaces the image a bed raises its machines from, or an image older than the bound.
|
||||
*/
|
||||
export function runRefusal(base: BaseImage, rebuilding?: { id: string; started: string }): string | undefined {
|
||||
if (rebuilding) return `the base image is being rebuilt (${rebuilding.id}, since ${rebuilding.started}); run once lab_base says it is built`;
|
||||
return staleBase(base);
|
||||
}
|
||||
|
||||
// ---- its rebuild: mesh-lab's `base build`, in the background, as a run is.
|
||||
|
||||
export interface BaseBuild {
|
||||
id: string;
|
||||
state: "building" | "built" | "failed" | "lost";
|
||||
started: string;
|
||||
ended?: string;
|
||||
exit?: number;
|
||||
pid?: number;
|
||||
}
|
||||
|
||||
function buildStatusPath(work: string, id: string): string {
|
||||
return join(work, id, "status.json");
|
||||
}
|
||||
|
||||
/** The base builds, newest first. A build whose process is gone while it says building was lost. */
|
||||
export function listBaseBuilds(work: string): BaseBuild[] {
|
||||
if (!existsSync(work)) return [];
|
||||
const builds: BaseBuild[] = [];
|
||||
for (const id of readdirSync(work).filter((d) => d.startsWith("base-"))) {
|
||||
try {
|
||||
const b = JSON.parse(readFileSync(buildStatusPath(work, id), "utf8")) as BaseBuild;
|
||||
if (b.state === "building" && gone(b.pid)) b.state = "lost";
|
||||
builds.push(b);
|
||||
} catch {
|
||||
// A directory without a status is not a build.
|
||||
}
|
||||
}
|
||||
return builds.sort((a, b) => b.started.localeCompare(a.started));
|
||||
}
|
||||
|
||||
/** The base build still going, if any. */
|
||||
export function buildingBase(work: string): BaseBuild | undefined {
|
||||
return listBaseBuilds(work).find((b) => b.state === "building");
|
||||
}
|
||||
|
||||
/** The last lines of a base build's log. */
|
||||
export function baseBuildLog(work: string, id: string, lines = 40): string {
|
||||
try {
|
||||
return readFileSync(join(work, id, "build.log"), "utf8").split("\n").slice(-Math.max(1, lines)).join("\n");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* baseScript is what one rebuild runs: mesh-lab's main from the forge, installed the way a run installs it,
|
||||
* then its `base build`, which replaces the image and reads back that it works before publishing it.
|
||||
*/
|
||||
export function baseScript(dir: string, forge: string, credential?: string, registry = `${forge}${NPM_PATH}`): string {
|
||||
const lab = join(dir, "mesh-lab");
|
||||
return `set -euo pipefail
|
||||
export GIT_TERMINAL_PROMPT=0
|
||||
${credentialGuard(credential)}
|
||||
cd ${shellQuote(dir)}
|
||||
git ${credentialArgs(credential)}clone --quiet --depth 1 ${shellQuote(`${forge}/novox/mesh-lab.git`)} ${shellQuote(lab)}
|
||||
${credential ? `rm -f ${shellQuote(credential)}` : ""}
|
||||
echo "mesh-lab $(git -C ${shellQuote(lab)} rev-parse HEAD)"
|
||||
printf '%s\\n' ${shellQuote(`@novox:registry=${registry}`)} > ${shellQuote(join(dir, ".npmrc"))}
|
||||
export NPM_CONFIG_USERCONFIG=${shellQuote(join(dir, ".npmrc"))}
|
||||
${installStep(lab, false)}
|
||||
cd ${shellQuote(lab)}
|
||||
node --experimental-strip-types src/cli.ts base build
|
||||
`;
|
||||
}
|
||||
|
||||
/** startBaseBuild rebuilds the base image in the background and answers at once with the build. */
|
||||
export function startBaseBuild(work: string, forge: string, credential?: string, registry?: string): BaseBuild {
|
||||
const id = `base-${new Date().toISOString().replace(/[:.]/g, "-")}`;
|
||||
const dir = join(work, id);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const build: BaseBuild = { id, state: "building", started: new Date().toISOString() };
|
||||
writeFileSync(buildStatusPath(work, id), JSON.stringify(build, null, 2));
|
||||
// What a crashed or rebooted run or rebuild left behind goes before this one writes its own.
|
||||
cleanCredentials(work);
|
||||
const credentials = writeCredential(credentialPath(work, id), credential);
|
||||
writeFileSync(join(dir, "build.sh"), baseScript(dir, forge, credentials, registry), { mode: 0o700 });
|
||||
const wrapper = `bash ${shellQuote(join(dir, "build.sh"))} > ${shellQuote(join(dir, "build.log"))} 2>&1; code=$?
|
||||
node -e ${shellQuote(
|
||||
`const f=${JSON.stringify(buildStatusPath(work, id))};const s=JSON.parse(require("fs").readFileSync(f,"utf8"));s.state=process.argv[1]==="0"?"built":"failed";s.exit=Number(process.argv[1]);s.ended=new Date().toISOString();require("fs").writeFileSync(f,JSON.stringify(s,null,2))`,
|
||||
)} "$code"
|
||||
rm -f ${shellQuote(credentialPath(work, id))}
|
||||
rm -rf ${shellQuote(join(dir, "mesh-lab"))}`;
|
||||
const child = spawn("bash", ["-c", wrapper], { detached: true, stdio: "ignore" });
|
||||
child.unref();
|
||||
build.pid = child.pid;
|
||||
writeFileSync(buildStatusPath(work, id), JSON.stringify(build, null, 2));
|
||||
return build;
|
||||
}
|
||||
|
||||
// ---- starting a run or a rebuild: one job on the lab's machine at a time (review 256).
|
||||
//
|
||||
// **Everything that waits is done first; the check and the start are one step.** A run and a rebuild each
|
||||
// refused while the other was going, but each asked the package registry — an await — between its check and
|
||||
// writing its status, so a run and a rebuild asked together could both pass their checks and both start: a
|
||||
// bed raising machines from an image being replaced under it. Here the registry is asked first, and nothing
|
||||
// is awaited between reading what is going and writing the new job's status, so in the one runtime that
|
||||
// serves the lab's tools no other call runs in between.
|
||||
|
||||
export interface Launch {
|
||||
/** The address a run or a rebuild names the package registry by, asked of the forge (npmRegistry). */
|
||||
registry: () => Promise<{ registry: string; problem?: string }>;
|
||||
/** The base image as it is now. */
|
||||
base: () => BaseImage;
|
||||
}
|
||||
|
||||
export type Launched<T> = { started: true; registry: string; problem?: string; base: BaseImage; job: T }
|
||||
| { started: false; reason: string; base: BaseImage };
|
||||
|
||||
/** launchRun starts a run unless a run or a rebuild is going, or the base image is past its bound. */
|
||||
export async function launchRun(work: string, launch: Launch, begin: (registry: string) => RunStatus):
|
||||
Promise<Launched<RunStatus>> {
|
||||
const registry = await launch.registry();
|
||||
// From here to begin(): nothing awaited.
|
||||
const base = launch.base();
|
||||
const busy = running(work);
|
||||
if (busy) return { started: false, reason: `${busy.id} is still ${busy.state}; one run at a time`, base };
|
||||
const refused = runRefusal(base, buildingBase(work));
|
||||
if (refused) return { started: false, reason: refused, base };
|
||||
return { started: true, ...registry, base, job: begin(registry.registry) };
|
||||
}
|
||||
|
||||
/** launchRebuild starts a rebuild of the base image unless a run or another rebuild is going. */
|
||||
export async function launchRebuild(work: string, launch: Launch, begin: (registry: string) => BaseBuild):
|
||||
Promise<Launched<BaseBuild>> {
|
||||
const registry = await launch.registry();
|
||||
// From here to begin(): nothing awaited.
|
||||
const base = launch.base();
|
||||
const rebuilding = buildingBase(work);
|
||||
if (rebuilding) return { started: false, reason: `${rebuilding.id} is still rebuilding it`, base };
|
||||
// A run raises its machines from the image; replacing it under one would change what the run tests.
|
||||
const busy = running(work);
|
||||
if (busy) return { started: false, reason: `${busy.id} is still ${busy.state}, and raises its machines from this image`, base };
|
||||
return { started: true, ...registry, base, job: begin(registry.registry) };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
// Whether mail flows through mailu, as the node-engine asks it every interval (novox/hq ADR 0240, kind
|
||||
// `tool`; issue 690). Every container read healthy on 2026-10-14 while postfix could not resolve a name:
|
||||
// inbound mail was refused with 450 and outbound mail sat in the deferred queue for days. The parts'
|
||||
// checks judge parts; this judges the flow, from inside the postfix container, the way postfix sees it:
|
||||
//
|
||||
// 1. postfix runs (`postfix status`, standing in for the image's own check, `! /usr/libexec/postfix/master
|
||||
// -t`, which this one replaces);
|
||||
// 2. the deferred queue (`postqueue -j`) shows no fault of this side: a recipient deferred longer than the
|
||||
// bound because a lookup failed here, or overdue mail to three or more domains. One or two far domains
|
||||
// that do not answer are theirs, and can stay deferred for days: said, never unhealthy, so one dead
|
||||
// recipient does not page the operator for days;
|
||||
// 3. a public mail host's name resolves through the resolver postfix is given: a resolver that
|
||||
// SERVFAILs refuses inbound mail before anything reaches the queue.
|
||||
//
|
||||
// The answer is the health answer every health tool gives (mesh-sdk go/health): `state`, `healthy` beside
|
||||
// it for an older reader, and `why` in words — counts, the oldest message's age and its first reason —
|
||||
// never a bare false.
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const run = promisify(execFile);
|
||||
|
||||
/** How long a message may wait in the deferred queue before mail is said not to flow. */
|
||||
export const DEFERRED_BOUND_SECONDS = 30 * 60;
|
||||
|
||||
/** The public name resolved through postfix's resolver: gmail's mail exchanger, which mail needs. */
|
||||
export const PUBLIC_NAME = "gmail-smtp-in.l.google.com";
|
||||
|
||||
// The lookup postfix's own would make, through the resolver the container is given; a failure is said on one
|
||||
// line ("gaierror: [Errno -3] Try again" is what a SERVFAIL reads as), never as a traceback.
|
||||
const RESOLVE = [
|
||||
"import socket, sys",
|
||||
"try:",
|
||||
` socket.getaddrinfo(${JSON.stringify(PUBLIC_NAME)}, 25)`,
|
||||
"except Exception as e:",
|
||||
" sys.exit(type(e).__name__ + ': ' + str(e))",
|
||||
].join("\n");
|
||||
|
||||
/** Overdue mail to this many recipient domains or more is our side's fault, not one far server's. */
|
||||
export const SPREAD_DOMAINS = 3;
|
||||
|
||||
/**
|
||||
* What postfix writes when its own lookups fail, as on 2026-10-14 (issue 687): "Host or domain name not
|
||||
* found. Name service error for name=gmail.com type=MX: Host not found, try again", or "Temporary lookup
|
||||
* failure". A far server that is down reads otherwise ("Connection timed out", "Connection refused").
|
||||
*/
|
||||
export const LOCAL_LOOKUP_FAILURE =
|
||||
/Name service error|Temporary lookup failure|Host or domain name not found.*try again/is;
|
||||
|
||||
/** The domain of an address, lower-cased; "(no recipient)" when there is none. */
|
||||
function domainOf(address?: string): string {
|
||||
const at = address?.lastIndexOf("@") ?? -1;
|
||||
return address && at >= 0 ? address.slice(at + 1).toLowerCase() : "(no recipient)";
|
||||
}
|
||||
|
||||
/** Runs a command in a container: its stdout, or a rejection carrying stderr. */
|
||||
export type Exec = (container: string, command: string[]) => Promise<string>;
|
||||
|
||||
/** The health answer (mesh-sdk go/health): healthy, or unhealthy with why. */
|
||||
export interface HealthAnswer {
|
||||
state: "healthy" | "unhealthy";
|
||||
healthy: boolean;
|
||||
why: string;
|
||||
queue?: {
|
||||
messages: number;
|
||||
deferred: number;
|
||||
overdue: number;
|
||||
oldestDeferredSeconds?: number;
|
||||
overdueDomains?: string[];
|
||||
nameServiceFailures?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** One message as `postqueue -j` prints it, one JSON object a line (postfix 3.1 and later). */
|
||||
interface Queued {
|
||||
queue_name?: string;
|
||||
queue_id?: string;
|
||||
arrival_time?: number;
|
||||
recipients?: Array<{ address?: string; delay_reason?: string }>;
|
||||
}
|
||||
|
||||
/** docker exec, bounded: a hung container is an answer too. */
|
||||
export function dockerExec(timeoutMs = 10_000): Exec {
|
||||
return async (container, command) =>
|
||||
(await run("docker", ["exec", container, ...command], { timeout: timeoutMs })).stdout;
|
||||
}
|
||||
|
||||
/** What a failed exec said, on one line: its stderr when it has one, else its message. */
|
||||
function said(e: unknown): string {
|
||||
const err = e as { stderr?: string; message?: string; killed?: boolean; signal?: string };
|
||||
if (err?.killed || err?.signal === "SIGTERM") return "it did not answer in time";
|
||||
const text = (err?.stderr ?? "").trim() || (err?.message ?? String(e)).trim();
|
||||
return text.split("\n").map((l) => l.trim()).filter(Boolean)[0] ?? "it failed and said nothing";
|
||||
}
|
||||
|
||||
/** An age in words: "2 days 3 hours", "45 minutes". */
|
||||
export function age(seconds: number): string {
|
||||
const s = Math.max(0, Math.floor(seconds));
|
||||
const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
|
||||
const unit = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`;
|
||||
if (d > 0) return h > 0 ? `${unit(d, "day")} ${unit(h, "hour")}` : unit(d, "day");
|
||||
if (h > 0) return m > 0 ? `${unit(h, "hour")} ${unit(m, "minute")}` : unit(h, "hour");
|
||||
return unit(m, "minute");
|
||||
}
|
||||
|
||||
function parseQueue(output: string): Queued[] {
|
||||
const queued: Queued[] = [];
|
||||
for (const line of output.split("\n")) {
|
||||
const text = line.trim();
|
||||
if (!text.startsWith("{")) continue; // "Mail queue is empty" and the like
|
||||
queued.push(JSON.parse(text) as Queued);
|
||||
}
|
||||
return queued;
|
||||
}
|
||||
|
||||
/**
|
||||
* Judge whether mail flows. `now` is in seconds since the epoch. Every part is asked even when one
|
||||
* fails, so the answer says everything that is wrong at once.
|
||||
*/
|
||||
export async function mailFlows(
|
||||
exec: Exec,
|
||||
container: string,
|
||||
now: number = Date.now() / 1000,
|
||||
boundSeconds: number = DEFERRED_BOUND_SECONDS,
|
||||
): Promise<HealthAnswer> {
|
||||
const faults: string[] = [];
|
||||
const [status, queue, resolve] = await Promise.allSettled([
|
||||
exec(container, ["postfix", "status"]),
|
||||
exec(container, ["postqueue", "-j"]),
|
||||
exec(container, ["python3", "-c", RESOLVE]),
|
||||
]);
|
||||
|
||||
if (status.status === "rejected") {
|
||||
faults.push(`postfix in ${container} does not run: ${said(status.reason)}.`);
|
||||
}
|
||||
|
||||
let summary: HealthAnswer["queue"];
|
||||
const notes: string[] = [];
|
||||
if (queue.status === "rejected") {
|
||||
faults.push(`postfix's queue in ${container} could not be read: ${said(queue.reason)}.`);
|
||||
} else {
|
||||
let queued: Queued[] = [];
|
||||
try {
|
||||
queued = parseQueue(queue.value);
|
||||
} catch (e) {
|
||||
faults.push(`postfix's queue in ${container} printed a line that is not JSON: ${said(e)}.`);
|
||||
}
|
||||
const deferred = queued.filter((q) => q.queue_name === "deferred");
|
||||
const overdue = deferred
|
||||
.filter((q) => typeof q.arrival_time === "number" && now - q.arrival_time > boundSeconds)
|
||||
.sort((a, b) => (a.arrival_time ?? 0) - (b.arrival_time ?? 0));
|
||||
const oldest = deferred.reduce<number | undefined>(
|
||||
(o, q) => (typeof q.arrival_time === "number" && (o === undefined || q.arrival_time < o) ? q.arrival_time : o),
|
||||
undefined,
|
||||
);
|
||||
// Each overdue recipient, oldest message first: what our side is judged by, not one far host.
|
||||
const late = overdue.flatMap((q) =>
|
||||
(q.recipients?.length ? q.recipients : [{}]).map((r) => ({
|
||||
to: r.address,
|
||||
domain: domainOf(r.address),
|
||||
reason: r.delay_reason?.trim() || "postfix gave no reason",
|
||||
waited: now - (q.arrival_time ?? now),
|
||||
})),
|
||||
);
|
||||
const lookups = late.filter((r) => LOCAL_LOOKUP_FAILURE.test(r.reason));
|
||||
const domains = [...new Set(late.map((r) => r.domain))];
|
||||
summary = {
|
||||
messages: queued.length,
|
||||
deferred: deferred.length,
|
||||
overdue: overdue.length,
|
||||
...(oldest !== undefined ? { oldestDeferredSeconds: Math.max(0, Math.floor(now - oldest)) } : {}),
|
||||
...(domains.length > 0 ? { overdueDomains: domains } : {}),
|
||||
...(lookups.length > 0 ? { nameServiceFailures: lookups.length } : {}),
|
||||
};
|
||||
const one = (r: (typeof late)[number]) =>
|
||||
`the oldest, ${age(r.waited)} old${r.to ? ` to ${r.to}` : ""}, waits because: ${r.reason}`;
|
||||
const bound = age(boundSeconds);
|
||||
if (lookups.length > 0) {
|
||||
faults.push(
|
||||
`${lookups.length} deferred ${lookups.length === 1 ? "recipient has" : "recipients have"} waited longer ` +
|
||||
`than ${bound} on a name-service failure, which is this server's resolver; ${one(lookups[0])}.`,
|
||||
);
|
||||
} else if (domains.length >= SPREAD_DOMAINS) {
|
||||
faults.push(
|
||||
`${overdue.length} of ${deferred.length} deferred messages have waited longer than ${bound}, to ` +
|
||||
`${domains.length} domains (${domains.join(", ")}): more than one far server's fault; ${one(late[0])}.`,
|
||||
);
|
||||
} else if (late.length > 0) {
|
||||
notes.push(
|
||||
`${overdue.length} deferred ${overdue.length === 1 ? "message has" : "messages have"} waited longer than ` +
|
||||
`${bound}, only to ${domains.join(" and ")}, which reads as the far side's: ${one(late[0])}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (resolve.status === "rejected") {
|
||||
faults.push(`${container} cannot resolve ${PUBLIC_NAME} through its resolver: ${said(resolve.reason)}.`);
|
||||
}
|
||||
|
||||
if (faults.length > 0) {
|
||||
const why = [`Mail does not flow.`, ...faults, ...notes].join(" ");
|
||||
return { state: "unhealthy", healthy: false, why, queue: summary };
|
||||
}
|
||||
const waiting = !summary || summary.deferred === 0
|
||||
? " The deferred queue is empty."
|
||||
: notes.length > 0
|
||||
? ` ${notes.join(" ")}`
|
||||
: ` ${summary.deferred} deferred, the oldest ${age(summary.oldestDeferredSeconds ?? 0)} old, within ${age(boundSeconds)}.`;
|
||||
return {
|
||||
state: "healthy",
|
||||
healthy: true,
|
||||
why: `Mail flows: postfix runs, ${PUBLIC_NAME} resolves.${waiting}`,
|
||||
queue: summary,
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,10 @@
|
||||
"policy": "record",
|
||||
"why": "people's mail: any change to how its containers are declared recreates them together in one send, and the mail is down for everyone until they are up again — a person chooses the moment (hq ADR 0242, issue 295)"
|
||||
},
|
||||
"unhealthy": {
|
||||
"severity": "urgent",
|
||||
"why": "while mailu is broken, mail is refused or stuck for everyone with a mailbox here (hq ADR 0355, issue 687)"
|
||||
},
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
@@ -56,6 +60,19 @@
|
||||
"api-token": "${dir:state}/api-token.secret"
|
||||
}
|
||||
},
|
||||
"tools": [
|
||||
"mailu_list_users",
|
||||
"mailu_create_user",
|
||||
"mailu_change_password",
|
||||
"mailu_delete_user",
|
||||
"mailu_list_aliases",
|
||||
"mailu_create_alias",
|
||||
"mailu_delete_alias",
|
||||
"mailu_list_domains",
|
||||
"mailu_read_mail",
|
||||
"mailu_search_mail",
|
||||
"mailu_health"
|
||||
],
|
||||
"emits": [
|
||||
"user.created",
|
||||
"user.deleted",
|
||||
@@ -371,7 +388,7 @@
|
||||
"id": "resolver",
|
||||
"type": "container",
|
||||
"name": "mailu-resolver",
|
||||
"image": "ghcr.io/mailu/unbound@sha256:3a0fdfb364a63f4f9259526e013c1ef40f5f14de3621ce1560804b3a5909584a",
|
||||
"image": "ghcr.io/mailu/unbound@sha256:2c037bc5c988b5c0ab7e1b6e6ffa762e14ba1e45c96281ac87f8b9be8eee8b6e",
|
||||
"health": {
|
||||
"kind": "runtime"
|
||||
},
|
||||
@@ -443,7 +460,12 @@
|
||||
"name": "mailu-smtp",
|
||||
"image": "ghcr.io/mailu/postfix@sha256:e2e49f39e53b80eac9e7a2f18d9df11edeb4914fd62dbba89b3155e8e034f62e",
|
||||
"health": {
|
||||
"kind": "runtime"
|
||||
"kind": "tool",
|
||||
"tool": "mailu_health",
|
||||
"interval": "60s",
|
||||
"timeout": "30s",
|
||||
"looks": 3,
|
||||
"grace": "120s"
|
||||
},
|
||||
"network": "mailu",
|
||||
"env-file": [
|
||||
@@ -560,7 +582,12 @@
|
||||
"name": "mailu-front",
|
||||
"image": "ghcr.io/mailu/nginx@sha256:36f98897cd1bc9d27628bbb4e04bdf60147af2ec7507d6da77f002c4f256896d",
|
||||
"health": {
|
||||
"kind": "runtime"
|
||||
"kind": "exec",
|
||||
"command": "curl -m3 -skfLo /dev/null http://127.0.0.1:10204/health && kill -0 $(cat /run/dovecot/master.pid) && python3 -c \"import smtplib; s = smtplib.SMTP('127.0.0.1', 25, timeout=5); s.ehlo('health'); s.quit()\" && openssl x509 -checkend 1209600 -noout -in /certs/letsencrypt/live/mailu/nginx-chain.pem",
|
||||
"interval": "60s",
|
||||
"timeout": "15s",
|
||||
"looks": 3,
|
||||
"grace": "120s"
|
||||
},
|
||||
"network": "mailu",
|
||||
"env-file": [
|
||||
@@ -637,6 +664,7 @@
|
||||
"MESH_MAILU_URL": "http://127.0.0.1:${port:8080}/api/v1",
|
||||
"MESH_MAILU_API_KEY_FILE": "${dir:state}/api-token.secret",
|
||||
"MESH_MAILU_IMAP_CONTAINER": "mailu-imap",
|
||||
"MESH_MAILU_SMTP_CONTAINER": "mailu-smtp",
|
||||
"MESH_MAILU_CONFIG_FILE": "${dir:mesh-state}/config.json",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
}
|
||||
@@ -673,7 +701,7 @@
|
||||
"jails": [
|
||||
{
|
||||
"name": "mailu-front",
|
||||
"failregex": "^.*(?:imap|pop3|submission|managesieve)-login: .*\\(auth failed, \\d+ attempts(?: in \\d+ secs)?\\):.*rip=<HOST>(?:,|$)",
|
||||
"failregex": "^.*(?:imap|pop3|submission|managesieve)-login: .*\\(auth failed, \\d+ attempts(?: in \\d+ secs)?\\):.*rip=<HOST>(?:,|$)\n ^.*client login failed: \"AUTH not supported\" while in http auth state, client: <HOST>, server: \\S+:25,",
|
||||
"jail": "backend = systemd\njournalmatch = CONTAINER_NAME=mailu-front\nport = smtp,submission,submissions,imap,imaps,pop3,pop3s\nmaxretry = 3\nfindtime = 1d\nbantime = 1d"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// Whether mail flows (novox/hq issue 690): the health tool is unhealthy, in words, when a message waits in
|
||||
// postfix's deferred queue longer than the bound, when postfix does not run, when a public name does not
|
||||
// resolve, and when the container cannot be reached — and healthy otherwise. Run against the compiled
|
||||
// module, the way the runtime loads it.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { mailFlows, DEFERRED_BOUND_SECONDS } from "../dist/health.js";
|
||||
|
||||
const NOW = 1_800_000_000;
|
||||
|
||||
type Answers = { status?: string | Error; queue?: string | Error; resolve?: string | Error };
|
||||
|
||||
/** A container that answers each command as told; an Error is a failed exec, with its stderr. */
|
||||
function container(a: Answers) {
|
||||
const asked: string[][] = [];
|
||||
const exec = async (_name: string, command: string[]) => {
|
||||
asked.push(command);
|
||||
const answer = command[0] === "postfix" ? a.status ?? "" : command[0] === "postqueue" ? a.queue ?? "" : a.resolve ?? "";
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer;
|
||||
};
|
||||
return { exec, asked };
|
||||
}
|
||||
|
||||
function failed(stderr: string): Error {
|
||||
return Object.assign(new Error("Command failed: docker exec"), { stderr });
|
||||
}
|
||||
|
||||
function deferred(id: string, ageSeconds: number, reason: string, to = "friend@example.com"): string {
|
||||
return JSON.stringify({
|
||||
queue_name: "deferred",
|
||||
queue_id: id,
|
||||
arrival_time: NOW - ageSeconds,
|
||||
message_size: 1234,
|
||||
sender: "someone@example.org",
|
||||
recipients: [{ address: to, delay_reason: reason }],
|
||||
});
|
||||
}
|
||||
|
||||
test("an empty queue is healthy, and says so", async () => {
|
||||
const c = container({ queue: "" });
|
||||
const a = await mailFlows(c.exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "healthy");
|
||||
assert.equal(a.healthy, true);
|
||||
assert.match(a.why, /deferred queue is empty/);
|
||||
assert.deepEqual(a.queue, { messages: 0, deferred: 0, overdue: 0 });
|
||||
assert.equal(c.asked.length, 3, "postfix, its queue and a lookup were each asked");
|
||||
});
|
||||
|
||||
test("a recipient overdue on a name-service failure is unhealthy, with counts, its age and its reason", async () => {
|
||||
const reason = "Host or domain name not found. Name service error for name=gmail.com type=MX: Host not found, try again";
|
||||
const queue = [
|
||||
deferred("AAA111", 3 * 86400 + 2 * 3600, reason),
|
||||
deferred("BBB222", 5 * 60, "connect to mx.example.net[192.0.2.1]:25: Connection timed out"),
|
||||
JSON.stringify({ queue_name: "active", queue_id: "CCC333", arrival_time: NOW - 10, recipients: [] }),
|
||||
].join("\n");
|
||||
const a = await mailFlows(container({ queue }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.equal(a.healthy, false);
|
||||
assert.match(a.why, /^Mail does not flow\./);
|
||||
assert.match(a.why, /1 deferred recipient has waited longer than 30 minutes on a name-service failure/);
|
||||
assert.match(a.why, /3 days 2 hours old to friend@example\.com/);
|
||||
assert.ok(a.why.includes(reason), "the reason is said");
|
||||
assert.deepEqual(a.queue, {
|
||||
messages: 3, deferred: 2, overdue: 1, oldestDeferredSeconds: 3 * 86400 + 2 * 3600,
|
||||
overdueDomains: ["example.com"], nameServiceFailures: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test("one dead far domain overdue is healthy, and said", async () => {
|
||||
const queue = [
|
||||
deferred("AAA111", 2 * 86400, "connect to mx.dead.example[192.0.2.9]:25: Connection timed out", "a@dead.example"),
|
||||
deferred("BBB222", 3600, "connect to mx.dead.example[192.0.2.9]:25: Connection timed out", "b@dead.example"),
|
||||
].join("\n");
|
||||
const a = await mailFlows(container({ queue }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "healthy");
|
||||
assert.equal(a.healthy, true);
|
||||
assert.match(a.why, /2 deferred messages have waited longer than 30 minutes, only to dead\.example, which reads as the far side's/);
|
||||
assert.match(a.why, /2 days old to a@dead\.example, waits because: connect to mx\.dead\.example/);
|
||||
assert.deepEqual(a.queue?.overdueDomains, ["dead.example"]);
|
||||
});
|
||||
|
||||
test("overdue mail to three domains is unhealthy, whatever the reason", async () => {
|
||||
const timedOut = "connect to mx[192.0.2.1]:25: Connection timed out";
|
||||
const queue = [
|
||||
deferred("AAA111", 7200, timedOut, "a@one.example"),
|
||||
deferred("BBB222", 3600, timedOut, "b@two.example"),
|
||||
deferred("CCC333", 3600, timedOut, "c@three.example"),
|
||||
].join("\n");
|
||||
const a = await mailFlows(container({ queue }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.match(a.why, /3 of 3 deferred messages have waited longer than 30 minutes, to 3 domains \(one\.example, two\.example, three\.example\)/);
|
||||
assert.match(a.why, /the oldest, 2 hours old to a@one\.example/);
|
||||
});
|
||||
|
||||
test("a deferred message younger than the bound is healthy, and is said", async () => {
|
||||
const queue = deferred("BBB222", DEFERRED_BOUND_SECONDS - 60, "connect to mx.example.net: Connection timed out");
|
||||
const a = await mailFlows(container({ queue }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "healthy");
|
||||
assert.equal(a.healthy, true);
|
||||
assert.match(a.why, /1 deferred, the oldest 29 minutes old, within 30 minutes/);
|
||||
});
|
||||
|
||||
test("a container that cannot be reached is unhealthy, and says what docker said", async () => {
|
||||
const gone = failed("Error response from daemon: No such container: mailu-smtp\n");
|
||||
const a = await mailFlows(container({ status: gone, queue: gone, resolve: gone }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.equal(a.healthy, false);
|
||||
assert.match(a.why, /postfix in mailu-smtp does not run: Error response from daemon: No such container: mailu-smtp\./);
|
||||
assert.match(a.why, /postfix's queue in mailu-smtp could not be read: Error response from daemon: No such container/);
|
||||
assert.equal(a.queue, undefined);
|
||||
});
|
||||
|
||||
test("a name that does not resolve is unhealthy, though the queue is empty", async () => {
|
||||
const a = await mailFlows(
|
||||
container({ queue: "", resolve: failed("gaierror: [Errno -3] Try again\n") }).exec,
|
||||
"mailu-smtp",
|
||||
NOW,
|
||||
);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.match(a.why, /mailu-smtp cannot resolve gmail-smtp-in\.l\.google\.com through its resolver: gaierror: \[Errno -3\] Try again\./);
|
||||
});
|
||||
|
||||
test("a container that does not answer in time is said so", async () => {
|
||||
const hung = Object.assign(new Error("Command failed"), { killed: true, signal: "SIGTERM" });
|
||||
const a = await mailFlows(container({ queue: hung }).exec, "mailu-smtp", NOW);
|
||||
assert.equal(a.state, "unhealthy");
|
||||
assert.match(a.why, /postfix's queue in mailu-smtp could not be read: it did not answer in time\./);
|
||||
});
|
||||
|
||||
test("the health tool is served without the admin API, on the smtp container it is told", async () => {
|
||||
const { collectTools } = await import("@novox/mesh-sdk/tools");
|
||||
await import("../dist/tools/index.js");
|
||||
const mailu = collectTools({ MESH_MAILU_SMTP_CONTAINER: "mailu-smtp" }).find((m) => m.module === "mailu");
|
||||
const names = (mailu?.tools ?? []).map((t) => t.name);
|
||||
assert.deepEqual(names, ["mailu_health"]);
|
||||
assert.match(mailu!.tools[0].description, /inside mailu-smtp/);
|
||||
});
|
||||
@@ -4,6 +4,27 @@
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { MailuClient } from "../client.js";
|
||||
import { dockerExec, mailFlows, DEFERRED_BOUND_SECONDS, PUBLIC_NAME, SPREAD_DOMAINS } from "../health.js";
|
||||
|
||||
/**
|
||||
* Whether mail flows (novox/hq ADR 0240, issue 690): the tool the node-engine asks as the smtp container's
|
||||
* check. It needs no admin API, only the postfix container, so it is served even when the API is not
|
||||
* configured — a check that vanished with the API would say unhealthy for the wrong reason.
|
||||
*/
|
||||
export function getHealthTool(env: NodeJS.ProcessEnv): ToolDefinition {
|
||||
const container = env.MESH_MAILU_SMTP_CONTAINER || "mailu-smtp";
|
||||
return {
|
||||
name: "mailu_health",
|
||||
description:
|
||||
`Whether mail flows through mailu, asked inside ${container}: postfix runs; no recipient has waited ` +
|
||||
`deferred longer than ${DEFERRED_BOUND_SECONDS / 60} minutes on a name-service failure here, and overdue ` +
|
||||
`deferred mail does not reach ${SPREAD_DOMAINS} or more domains (one or two far domains are said, not ` +
|
||||
`unhealthy); and ${PUBLIC_NAME} resolves through the resolver postfix uses. Says counts, domains, the ` +
|
||||
"oldest message's age and its reason (novox/hq ADR 0240, issue 690).",
|
||||
input: {},
|
||||
run: async () => mailFlows(dockerExec(), container),
|
||||
};
|
||||
}
|
||||
|
||||
export function getMailuTools(mailu: MailuClient): ToolDefinition[] {
|
||||
return [
|
||||
@@ -143,12 +164,14 @@ export function getMailuTools(mailu: MailuClient): ToolDefinition[] {
|
||||
];
|
||||
}
|
||||
|
||||
// The tools exist only when the admin API is configured; without it, mailu contributes none rather
|
||||
// than failing the whole runtime.
|
||||
// The admin tools exist only when the admin API is configured; without it, mailu contributes only its
|
||||
// health tool rather than failing the whole runtime.
|
||||
registerModuleTools("mailu", (env) => {
|
||||
let tools: ToolDefinition[] = [];
|
||||
try {
|
||||
return getMailuTools(MailuClient.fromEnv(env));
|
||||
tools = getMailuTools(MailuClient.fromEnv(env));
|
||||
} catch {
|
||||
return [];
|
||||
tools = [];
|
||||
}
|
||||
return [...tools, getHealthTool(env)];
|
||||
});
|
||||
|
||||
@@ -8,5 +8,5 @@
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["client.ts", "index.ts", "tools/index.ts"]
|
||||
"include": ["client.ts", "health.ts", "index.ts", "tools/index.ts"]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
// What the catalogue makes of a build outcome it hears (novox/hq issue 712).
|
||||
//
|
||||
// Kept apart from index.ts, which subscribes at its top level, so the decision can be tested without a bus.
|
||||
|
||||
import type { Made } from "./store.js";
|
||||
|
||||
/** What the build seat says when it has built something, and what the control plane replays. */
|
||||
export interface Built {
|
||||
module?: string;
|
||||
commit?: string;
|
||||
repository?: string;
|
||||
path?: string;
|
||||
ref?: string;
|
||||
manifest?: unknown;
|
||||
/** What this build published, each pinned as anything else would name it. */
|
||||
made?: Made[];
|
||||
/**
|
||||
* Every artifact this was built on top of, so the edge is derived rather than declared.
|
||||
*
|
||||
* References, not module names: the builder sees a pinned image and cannot see which module
|
||||
* produced it. Turning that into an edge between module-versions is this module's job.
|
||||
*/
|
||||
against?: string[];
|
||||
/**
|
||||
* This is history, not news — the mesh re-announcing a build this catalogue was not there for.
|
||||
*
|
||||
* Registered exactly as any other, and announced as nothing. A module that moved months ago is
|
||||
* not something anything should act on now: emitting `upgraded` would have the control plane
|
||||
* decide about a rollout, and `rebuild-needed` would ask for builds of things that are already
|
||||
* current.
|
||||
*/
|
||||
replay?: boolean;
|
||||
/** Why the build failed; a failed build made no module-version. */
|
||||
failed?: string;
|
||||
/** A dry run is looked at, never taken in (novox/hq issue 240). */
|
||||
"dry-run"?: boolean;
|
||||
/** A pull request's merge check or a branch tried before one (to-be 45 §9, issue 686): nothing merged. */
|
||||
"check-outcome"?: unknown;
|
||||
check?: unknown;
|
||||
/** The repository's default branch as the build seat read the forge at the build (ADR 0238); empty from a seat older than the rule. */
|
||||
trunk?: string;
|
||||
/** Whether the commit is on `trunk`. */
|
||||
"on-trunk"?: boolean;
|
||||
/** The branches the commit is on. */
|
||||
branches?: string[];
|
||||
}
|
||||
|
||||
/** The events a build outcome reaches this module on: the build seat's, as it happens, and the control plane's replay. */
|
||||
export const BUILD_EVENTS = [
|
||||
// **The build seat that builds now** (novox/hq ADR 0190). Until issue 712 the catalogue heard only the
|
||||
// retired seat below, so every build after the handover reached the graph only through the replay this
|
||||
// module asks for when it starts: a merge built and pushed stayed out of the catalogue until its next start.
|
||||
"node-build-agent.built",
|
||||
// The retired build role, while a machine still serves it (ADR 0190's handover). Goes with the seat row.
|
||||
"mesh-build-machine.built",
|
||||
// What the mesh already held, when this module asks what it missed (novox/hq ADR 0134).
|
||||
"mesh-controller.built-before",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Whether a build outcome is a module-version to place in the graph, and why not when it is not.
|
||||
*
|
||||
* It mirrors two of the rules the controller keeps before it registers a build (mesh-controller
|
||||
* cmd/mesh-controller/main.go `builds.Built`, build.go `publishable`): a merge check, a try and a dry run are
|
||||
* never published, and **only a commit on its repository's trunk is** (ADR 0238) — a branch built through
|
||||
* the `build` verb is checked, never a module's version. Where the seat names no trunk (one older than the
|
||||
* rule) it is placed, as the controller lets it through. A failure made nothing and is passed over too.
|
||||
*
|
||||
* Not mirrored, because the catalogue cannot see what they read: the branch a module follows when it is not
|
||||
* the default one (the controller's `follows`; such a module's builds off the default branch are passed over
|
||||
* here and reach the graph by the replay), ADR 0266's rule that a module registers only from the repository
|
||||
* it is built from, a superseded request, a build in the scratch namespace, one that failed its gate, and a
|
||||
* build whose source is unchanged. Each needs the controller's records. This is safe for what the mesh
|
||||
* sends, which is chosen from the controller's own module table and never from this graph; that the graph
|
||||
* can still hold a build the controller refused under those rules is a follow-up (hq issue 712).
|
||||
*/
|
||||
export function placeable(body: Built):
|
||||
| { placed: "yes"; module: string; commit: string }
|
||||
| { placed: "no"; why: string; fault: boolean } {
|
||||
if (body["check-outcome"] != null || body.check != null) {
|
||||
return { placed: "no", why: "a merge check or a try: nothing of it merged", fault: false };
|
||||
}
|
||||
if (body["dry-run"]) {
|
||||
return { placed: "no", why: "a dry run is looked at, never taken in", fault: false };
|
||||
}
|
||||
if (body.failed) {
|
||||
return { placed: "no", why: "a failed build made no module-version", fault: false };
|
||||
}
|
||||
if (body.trunk && !body["on-trunk"] && !(body.branches ?? []).includes(body.trunk)) {
|
||||
return { placed: "no", why: `the commit is not on its repository's trunk ${body.trunk}: checked, never published (ADR 0238)`, fault: false };
|
||||
}
|
||||
if (!body.module || !body.commit) {
|
||||
return { placed: "no", why: "it named no module or no commit", fault: true };
|
||||
}
|
||||
return { placed: "yes", module: body.module, commit: body.commit };
|
||||
}
|
||||
@@ -10,7 +10,8 @@
|
||||
// diamond need no special handling, and nothing holds a plan.
|
||||
|
||||
import { on, emit } from "@novox/mesh-sdk/events";
|
||||
import { Graph, type Made } from "./store.js";
|
||||
import { Graph } from "./store.js";
|
||||
import { BUILD_EVENTS, placeable, type Built } from "./heard.js";
|
||||
|
||||
const graph = Graph.fromEnv();
|
||||
|
||||
@@ -21,54 +22,29 @@ const graph = Graph.fromEnv();
|
||||
// would block the very apply that brings the overlay up — stopped being true when a step's failure
|
||||
// became this module's business and not the machine's (ADR 0136).
|
||||
|
||||
/** What the builder says when it has built something. */
|
||||
interface Built {
|
||||
module?: string;
|
||||
commit?: string;
|
||||
repository?: string;
|
||||
path?: string;
|
||||
ref?: string;
|
||||
manifest?: unknown;
|
||||
/** What this build published, each pinned as anything else would name it. */
|
||||
made?: Made[];
|
||||
/**
|
||||
* Every artifact this was built on top of, so the edge is derived rather than declared.
|
||||
*
|
||||
* References, not module names: the builder sees a pinned image and cannot see which module
|
||||
* produced it. Turning that into an edge between module-versions is this module's job.
|
||||
*/
|
||||
against?: string[];
|
||||
/**
|
||||
* This is history, not news — the mesh re-announcing a build this catalogue was not there for.
|
||||
*
|
||||
* Registered exactly as any other, and announced as nothing. A module that moved months ago is
|
||||
* not something anything should act on now: emitting `upgraded` would have the control plane
|
||||
* decide about a rollout, and `rebuild-needed` would ask for builds of things that are already
|
||||
* current.
|
||||
*/
|
||||
replay?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a build means for the graph, wherever it came from.
|
||||
*
|
||||
* Two emitters say the same thing and neither is a mistake: the build machine says it as it happens,
|
||||
* and the control plane says what it already held when this module asks what it missed
|
||||
* (novox/hq ADR 0134). A replay is marked as one in its body, so nothing acts on a module that moved
|
||||
* months ago — see `replay` above.
|
||||
* months ago — see `replay` in heard.ts.
|
||||
*/
|
||||
const placeTheBuild = async (event: { body: unknown }): Promise<void> => {
|
||||
const body = (event.body ?? {}) as Built;
|
||||
if (!body.module || !body.commit) {
|
||||
// Said rather than dropped: a build that announced itself without saying what it built is a
|
||||
// fault in the builder, and a silent discard here would make it look like a missing event.
|
||||
console.error("mesh-catalog: a build event named no module or no commit; ignored", body);
|
||||
const placing = placeable(body);
|
||||
if (placing.placed === "no") {
|
||||
// A check, a try, a dry run and a failure are the build seat's ordinary outcomes: passed over. One
|
||||
// that names no module or commit is a fault in the builder, said rather than dropped, so it does
|
||||
// not look like a missing event.
|
||||
if (placing.fault) console.error(`mesh-catalog: a build event was not placed: ${placing.why}`, body);
|
||||
return;
|
||||
}
|
||||
const { module, commit } = placing;
|
||||
|
||||
const { upgraded, previous } = await graph.register({
|
||||
module: body.module,
|
||||
commit: body.commit,
|
||||
module,
|
||||
commit,
|
||||
repository: body.repository ?? "",
|
||||
path: body.path ?? "",
|
||||
ref: body.ref ?? "",
|
||||
@@ -80,7 +56,7 @@ const placeTheBuild = async (event: { body: unknown }): Promise<void> => {
|
||||
if (body.replay) return;
|
||||
|
||||
await emit("registered", {
|
||||
module: body.module, commit: body.commit, upgraded,
|
||||
module, commit, upgraded,
|
||||
});
|
||||
|
||||
// **A rebuild that changed nothing is not an upgrade.** Announcing it would ripple outward
|
||||
@@ -88,7 +64,7 @@ const placeTheBuild = async (event: { body: unknown }): Promise<void> => {
|
||||
if (!upgraded) return;
|
||||
|
||||
await emit("upgraded", {
|
||||
module: body.module, commit: body.commit, previous,
|
||||
module, commit, previous,
|
||||
});
|
||||
|
||||
// What can be built now — stale, and waiting on nothing that is itself stale.
|
||||
@@ -101,9 +77,9 @@ const placeTheBuild = async (event: { body: unknown }): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
// As it happens, and what the mesh already held when this module asked what it missed.
|
||||
await on("mesh-build-machine.built", placeTheBuild);
|
||||
await on("mesh-controller.built-before", placeTheBuild);
|
||||
// As it happens — from the build seat that builds now, and the retired one while it still answers — and
|
||||
// what the mesh already held when this module asked what it missed (novox/hq issue 712).
|
||||
for (const heard of BUILD_EVENTS) await on(heard, placeTheBuild);
|
||||
|
||||
// **And ask for what was built before this catalogue existed** (novox/hq 04-ISSUES/050).
|
||||
//
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
"postgres-database": "${dir:state}/database.secret"
|
||||
},
|
||||
"consumes": [
|
||||
"node-build-agent.built",
|
||||
"mesh-build-machine.built",
|
||||
"mesh-controller.built-before"
|
||||
],
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { BUILD_EVENTS, placeable } from "../heard.js";
|
||||
|
||||
// A walk's build as the build seat says it (mesh-controller's link.BuildResult), here mailu's of novox/hq issue 712.
|
||||
const walkBuild = {
|
||||
id: "build-1791997333800041716",
|
||||
repository: "http://novox.internal:20000/novox/mesh-catalog.git",
|
||||
path: "modules/mailu",
|
||||
ref: "main",
|
||||
on: "shanks",
|
||||
trunk: "main",
|
||||
"on-trunk": true,
|
||||
branches: ["main"],
|
||||
module: "mailu",
|
||||
commit: "e1c8965ddbf1cf9af9cf1eed7a72ae9ffa6d5a87",
|
||||
manifest: { module: "mailu", unhealthy: { severity: "urgent", why: "mail stops" } },
|
||||
made: [{ name: "code", kind: "bundle", reference: "artifact-store://mailu/code/blobs/sha256:d041" }],
|
||||
};
|
||||
|
||||
test("the catalogue hears the build seat that builds now, not only the retired one (issue 712)", async () => {
|
||||
assert.ok(BUILD_EVENTS.includes("node-build-agent.built"));
|
||||
assert.ok(BUILD_EVENTS.includes("mesh-controller.built-before"));
|
||||
// Subscribing is not enough: the mesh grants and routes only what the manifest consumes.
|
||||
const manifest = JSON.parse(await readFile(new URL("../module.json", import.meta.url), "utf8"));
|
||||
for (const heard of BUILD_EVENTS) assert.ok(manifest.consumes.includes(heard), `${heard} is not consumed`);
|
||||
});
|
||||
|
||||
test("a walk's build is placed, under its module and commit", () => {
|
||||
assert.deepEqual(placeable(walkBuild), { placed: "yes", module: "mailu", commit: walkBuild.commit });
|
||||
// A walk that took the check's build of the same key says so, and is placed all the same (ADR 0350 §2).
|
||||
assert.equal(placeable({ ...walkBuild, reused: "the check's build" } as never).placed, "yes");
|
||||
});
|
||||
|
||||
test("a merge check, a try, a dry run and a failure are passed over without a fault", () => {
|
||||
for (const [body, why] of [
|
||||
[{ ...walkBuild, "check-outcome": { verdict: "passed" } }, "merge check"],
|
||||
[{ ...walkBuild, check: { try: true } }, "merge check or a try"],
|
||||
[{ ...walkBuild, "dry-run": true }, "dry run"],
|
||||
[{ ...walkBuild, failed: "exit status 1" }, "failed"],
|
||||
] as const) {
|
||||
const placing = placeable(body);
|
||||
assert.equal(placing.placed, "no");
|
||||
if (placing.placed === "no") {
|
||||
assert.match(placing.why, new RegExp(why));
|
||||
assert.equal(placing.fault, false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("an outcome that names no module or commit is said as the builder's fault", () => {
|
||||
const placing = placeable({ repository: walkBuild.repository, commit: walkBuild.commit });
|
||||
assert.equal(placing.placed, "no");
|
||||
if (placing.placed === "no") assert.equal(placing.fault, true);
|
||||
});
|
||||
|
||||
test("a branch built through the build verb is passed over; a commit on the trunk, or from a seat that names none, is placed (ADR 0238)", () => {
|
||||
const branch = { ...walkBuild, ref: "feature", "on-trunk": false, branches: ["feature"] };
|
||||
const placing = placeable(branch);
|
||||
assert.equal(placing.placed, "no");
|
||||
if (placing.placed === "no") {
|
||||
assert.match(placing.why, /not on its repository's trunk main/);
|
||||
assert.equal(placing.fault, false);
|
||||
}
|
||||
// On the trunk by its branches although the seat did not set on-trunk.
|
||||
assert.equal(placeable({ ...branch, branches: ["feature", "main"] }).placed, "yes");
|
||||
// A seat older than the rule says no trunk: placed, as the controller lets it through.
|
||||
const { trunk, "on-trunk": _on, branches, ...older } = walkBuild;
|
||||
assert.equal(placeable(older).placed, "yes");
|
||||
});
|
||||
@@ -11,6 +11,7 @@
|
||||
"include": [
|
||||
"pg.d.ts",
|
||||
"store.ts",
|
||||
"heard.ts",
|
||||
"index.ts",
|
||||
"tools/index.ts",
|
||||
"prepare/index.ts"
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// One build per change (novox/hq ADR 0350): a pull request closed unmerged has its check builds let go of, and a
|
||||
// walk's record says per module whether its build reused a check's build or built, and why.
|
||||
|
||||
// A pull request closed unmerged asks the controller to let go of what its checks built for its merge (§5); one
|
||||
// the controller cannot answer is said, never fatal.
|
||||
func TestAPullRequestClosedUnmergedLetsGoOfItsCheckBuilds(t *testing.T) {
|
||||
w := newWorldOver(t, newMemStore(), newFakeController(), newFakeForge(), atCC)
|
||||
cc := pr(cat, 101, headCC, "feat/claude-code", "modules/claude-code/module.json")
|
||||
w.h.PullUpdated(cc)
|
||||
w.h.PullClosed(cc)
|
||||
if want := []string{"novox/mesh-catalog#101"}; !reflect.DeepEqual(w.ctl.forgot, want) {
|
||||
t.Fatalf("closed unmerged, the controller was asked to let go of %v", w.ctl.forgot)
|
||||
}
|
||||
if s := w.state(IDOf(cat, headCC)); s != Stopped {
|
||||
t.Fatalf("closed unmerged it is %s", s)
|
||||
}
|
||||
|
||||
w.ctl.down = true
|
||||
du := pr(cat, 102, headDu, "feat/dunst", "modules/dunst/module.json")
|
||||
w.h.PullUpdated(du)
|
||||
w.h.PullClosed(du)
|
||||
if s := w.state(IDOf(cat, headDu)); s != Stopped {
|
||||
t.Fatalf("with the controller down, a closed delivery is %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
// The walk's record says per module what its build did, and the delivery keeps it beside its walk (§4).
|
||||
func TestAWalksRecordSaysWhetherEachModuleWasReusedOrBuilt(t *testing.T) {
|
||||
walk := catWalk("plan-1", mergeCC, atCC.Add(time.Minute), "claude-code", "dunst")
|
||||
walk.Modules["claude-code"].Made = "reused from the check of novox/mesh-catalog#101 at head cccccccccccc " +
|
||||
"(merged into trunk 553b71910000): tools sha256:aa"
|
||||
walk.Modules["dunst"].Made = "built: no check of novox/mesh-catalog#101 built it"
|
||||
seen := walk.Seen()
|
||||
if !strings.HasPrefix(seen.Built["claude-code"], "reused from the check of novox/mesh-catalog#101") ||
|
||||
seen.Built["dunst"] != "built: no check of novox/mesh-catalog#101 built it" {
|
||||
t.Fatalf("the delivery keeps %v", seen.Built)
|
||||
}
|
||||
if catWalk("plan-2", mergeCC, atCC, "dunst").Seen().Built != nil {
|
||||
t.Fatal("a walk from a controller that says nothing of its builds reads as if it said something")
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,18 @@ type fakeController struct {
|
||||
onCheck func()
|
||||
// planned is what Plan answers instead of "builds app", when set.
|
||||
planned *DeliveryPlan
|
||||
// forgot are the pull requests whose check builds were let go of (novox/hq ADR 0350 §5), "owner/repo#n".
|
||||
forgot []string
|
||||
}
|
||||
|
||||
func (c *fakeController) ForgetChecks(owner, repo string, number int) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.down {
|
||||
return errors.New("down")
|
||||
}
|
||||
c.forgot = append(c.forgot, fmt.Sprintf("%s/%s#%d", owner, repo, number))
|
||||
return nil
|
||||
}
|
||||
|
||||
func newFakeController() *fakeController {
|
||||
@@ -384,6 +396,9 @@ type fakeForge struct {
|
||||
// open is what OpenPulls answers; openDown a forge that cannot say.
|
||||
open []OpenPull
|
||||
openDown bool
|
||||
// merges, comments and unlabels are what was asked of the forge for ready marks (novox/hq issue 722).
|
||||
merges, comments, unlabels []string
|
||||
refuse error
|
||||
}
|
||||
|
||||
func (f *fakeForge) OpenPulls() ([]OpenPull, error) {
|
||||
@@ -637,3 +652,25 @@ func aWalk(id, repo, commit string, waits bool) Walk {
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// Merge, Comment and Unlabel record what was asked (novox/hq issue 722); Merge answers refuse when set.
|
||||
func (f *fakeForge) Merge(owner, repo string, number int, head string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.merges = append(f.merges, fmt.Sprintf("%s/%s#%d@%s", owner, repo, number, head))
|
||||
return f.refuse
|
||||
}
|
||||
|
||||
func (f *fakeForge) Comment(owner, repo string, number int, body string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.comments = append(f.comments, fmt.Sprintf("%s/%s#%d: %s", owner, repo, number, body))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeForge) Unlabel(owner, repo string, number, label int) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.unlabels = append(f.unlabels, fmt.Sprintf("%s/%s#%d-%d", owner, repo, number, label))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -69,6 +69,8 @@ type Holder struct {
|
||||
leaveRefused map[string]string
|
||||
// tried counts the owed effects Flush tried since this owner started, by how each ended (novox/hq issue 407).
|
||||
tried owedTries
|
||||
// marks are the open pull requests read with a ready mark, by owner/repo#number (novox/hq issue 722, ready.go).
|
||||
marks map[string]*marked
|
||||
}
|
||||
|
||||
// owedTries is how many owed effects were tried since this owner started, and when the last was: three numbers
|
||||
@@ -120,6 +122,7 @@ func (h *Holder) init() {
|
||||
h.askTried = map[string]time.Time{}
|
||||
h.walkAsked = map[string]time.Time{}
|
||||
h.unchecked = map[string]unchecked{}
|
||||
h.marks = map[string]*marked{}
|
||||
h.walks = map[string]seenWalk{}
|
||||
h.orphans = map[string]time.Time{}
|
||||
h.asking = map[string]bool{}
|
||||
@@ -593,9 +596,12 @@ func verdictOfState(s string) string {
|
||||
}
|
||||
|
||||
// PullClosed takes a pull request closed unmerged: its open deliveries are stopped.
|
||||
//
|
||||
// **And what its checks built for its merge goes** (novox/hq ADR 0350 §5): nothing will take it now. Asked of the
|
||||
// controller once the deliveries are settled, outside the lock; a refusal is said, and the build seat's holders let
|
||||
// go of it within the week anyway.
|
||||
func (h *Holder) PullClosed(p PullEvent) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
for _, d := range h.deliveries {
|
||||
if d.Repository == p.repository() && d.Number == p.Number && !d.State.Final() && d.MergedAs == "" {
|
||||
d.ClosedUnmerged = true
|
||||
@@ -605,6 +611,16 @@ func (h *Holder) PullClosed(p PullEvent) {
|
||||
}
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
if h.Controller == nil || p.Owner == "" || p.Repo == "" || p.Number <= 0 {
|
||||
return
|
||||
}
|
||||
if err := h.Controller.ForgetChecks(p.Owner, p.Repo, p.Number); err != nil {
|
||||
h.mu.Lock()
|
||||
h.refuse(fmt.Errorf("%s#%d closed, and its check builds stay until the week's sweep: %w", p.repository(),
|
||||
p.Number, err))
|
||||
h.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// CheckedEvent is the controller's `checked`.
|
||||
@@ -983,6 +999,12 @@ func (h *Holder) Tick() {
|
||||
for _, ask := range h.leaveStopped() {
|
||||
ask()
|
||||
}
|
||||
h.mu.Lock()
|
||||
asks := h.readyAsks(h.Now())
|
||||
h.mu.Unlock()
|
||||
for _, ask := range asks {
|
||||
ask()
|
||||
}
|
||||
}
|
||||
|
||||
// plan works out, under the lock, what to ask; each ask applies its own answer.
|
||||
|
||||
@@ -76,8 +76,9 @@ func run(h *Holder, l *listening) {
|
||||
logf("[mesh-delivery] the controller's walks cannot be read: %v", err)
|
||||
}
|
||||
}
|
||||
// Every open pull request, from the forge itself, every five minutes (novox/hq issue 347).
|
||||
if now.Sub(looked) >= 5*time.Minute {
|
||||
// Every open pull request, from the forge itself, every minute (novox/hq issues 347, 722): what says a
|
||||
// head nobody checks, and the ready marks a merge is asked on.
|
||||
if now.Sub(looked) >= time.Minute {
|
||||
looked = now
|
||||
h.SeeOpenPulls()
|
||||
}
|
||||
|
||||
@@ -61,11 +61,13 @@ func TestItClaimsTheDeliverySeatAndFollowsWhatItHandles(t *testing.T) {
|
||||
}
|
||||
// It calls exactly what its ports ask: the controller's six verbs and the forge's four tools.
|
||||
want := []string{}
|
||||
for _, v := range []string{"delivery-plan", "delivery-order", "delivery-check", "deliver", "delivery-stop", "delivery-walks"} {
|
||||
for _, v := range []string{"delivery-plan", "delivery-order", "delivery-check", "deliver", "delivery-stop", "delivery-walks", "forget-checks"} {
|
||||
want = append(want, "seat:"+ControllerSeat+"."+v)
|
||||
}
|
||||
want = append(want, "gitea.gitea_note_append", "gitea.gitea_delivery_view", "gitea.gitea_commit_status",
|
||||
"gitea.gitea_commit_statuses", "gitea.gitea_contains", "gitea.gitea_open_pulls")
|
||||
"gitea.gitea_commit_statuses", "gitea.gitea_contains", "gitea.gitea_open_pulls",
|
||||
// The merge on a ready mark (novox/hq issue 722): the merge tool, a comment, a label taken off.
|
||||
"gitea.gitea_merge_pull_request", "gitea.gitea_add_comment", "gitea.gitea_api")
|
||||
if !reflect.DeepEqual(m.Invokes, want) {
|
||||
t.Fatalf("invokes %v, wanted %v", m.Invokes, want)
|
||||
}
|
||||
|
||||
@@ -110,6 +110,9 @@ type Delivery struct {
|
||||
LetGo time.Time `json:"let_go"`
|
||||
LetGoWhy string `json:"let_go_why,omitempty"`
|
||||
|
||||
// Ready is what this owner did with its pull request's ready mark (novox/hq issue 722, ready.go).
|
||||
Ready *ReadyRun `json:"ready,omitempty"`
|
||||
|
||||
Transitions []Transition `json:"transitions,omitempty"`
|
||||
// Owed are the forge's and the bus's effects of its transitions not yet done: said only after the
|
||||
// delivery is kept, retried until done.
|
||||
@@ -402,6 +405,9 @@ type WalkModule struct {
|
||||
Build string `json:"build,omitempty"`
|
||||
Gate *WalkGate `json:"gate,omitempty"`
|
||||
GatedBy string `json:"gated_by,omitempty"`
|
||||
// Made is what the walk's build of it did (novox/hq ADR 0350 §4): "reused from <check build>", naming the pull
|
||||
// request's head, the trunk commit and the digests, or "built: <why>". Empty from a controller before it.
|
||||
Made string `json:"made,omitempty"`
|
||||
}
|
||||
|
||||
// WalkGate is a module's judging on its first machine.
|
||||
@@ -592,6 +598,9 @@ type WalkSeen struct {
|
||||
// Unchanged are the modules the walk said matched what runs, with why (novox/hq issue 611): not built, and
|
||||
// nothing for it to deliver.
|
||||
Unchanged map[string]string `json:"unchanged,omitempty"`
|
||||
// Built is, per module, what the walk's build of it did (novox/hq ADR 0350 §4): "reused from <check build>" or
|
||||
// "built: <why>" — what `show` says beside the build phase.
|
||||
Built map[string]string `json:"built,omitempty"`
|
||||
}
|
||||
|
||||
// Seen is a walk as a delivery keeps it.
|
||||
@@ -616,6 +625,12 @@ func (w Walk) Seen() *WalkSeen {
|
||||
if m != nil && (m.SentAt != nil || m.Gate != nil && m.Gate.Verdict == "passed") {
|
||||
s.Moved = append(s.Moved, name)
|
||||
}
|
||||
if m != nil && m.Made != "" {
|
||||
if s.Built == nil {
|
||||
s.Built = map[string]string{}
|
||||
}
|
||||
s.Built[name] = m.Made
|
||||
}
|
||||
}
|
||||
sort.Strings(s.Moved)
|
||||
s.MovedSaid = true
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
@@ -70,6 +71,8 @@ type Controller interface {
|
||||
StopWithout(walk, why, by string, without []string) (StopAnswer, error)
|
||||
// Walks are the walks the controller keeps — one, given its id — and whether this seat has a holder on record.
|
||||
Walks(walk string) (bool, []Walk, error)
|
||||
// ForgetChecks lets go of the builds a pull request's merge checks made for its merge (novox/hq ADR 0350 §5).
|
||||
ForgetChecks(owner, repo string, number int) error
|
||||
}
|
||||
|
||||
// Forge is what the forge's holder does for a delivery.
|
||||
@@ -88,6 +91,13 @@ type Forge interface {
|
||||
// OpenPulls is every open pull request, with what its base requires and what its head has (novox/hq issue
|
||||
// 347). Reads only.
|
||||
OpenPulls() ([]OpenPull, error)
|
||||
// Merge asks the forge's merge tool to merge a pull request at the head named (gitea_merge_pull_request, novox/hq
|
||||
// issue 722): the one path every merge takes. Its refusal is the error, in its words.
|
||||
Merge(owner, repo string, number int, head string) error
|
||||
// Comment adds a comment to a pull request.
|
||||
Comment(owner, repo string, number int, body string) error
|
||||
// Unlabel takes a label off a pull request, by the label's id.
|
||||
Unlabel(owner, repo string, number, label int) error
|
||||
}
|
||||
|
||||
// ForgeChecks is what the forge says of a commit's checks (the gitea module's gitea_commit_statuses).
|
||||
@@ -271,6 +281,11 @@ func (c seatController) Deliver(walk, why string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (c seatController) ForgetChecks(owner, repo string, number int) error {
|
||||
_, err := c.verb("forget-checks", map[string]any{"owner": owner, "repo": repo, "number": strconv.Itoa(number)})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c seatController) Stop(walk, why, by string) error {
|
||||
_, err := c.verb("delivery-stop", map[string]any{"plan": walk, "why": why, "by": by})
|
||||
return err
|
||||
@@ -384,6 +399,19 @@ func (f toolForge) Statuses(owner, repo string, number int, commit, base string)
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (f toolForge) Merge(owner, repo string, number int, head string) error {
|
||||
return f.tool("gitea_merge_pull_request", map[string]any{"owner": owner, "repo": repo, "number": number, "head": head})
|
||||
}
|
||||
|
||||
func (f toolForge) Comment(owner, repo string, number int, body string) error {
|
||||
return f.tool("gitea_add_comment", map[string]any{"owner": owner, "repo": repo, "number": number, "body": body})
|
||||
}
|
||||
|
||||
func (f toolForge) Unlabel(owner, repo string, number, label int) error {
|
||||
return f.tool("gitea_api", map[string]any{"method": "DELETE",
|
||||
"path": fmt.Sprintf("/repos/%s/%s/issues/%d/labels/%d", owner, repo, number, label)})
|
||||
}
|
||||
|
||||
func (f toolForge) OpenPulls() ([]OpenPull, error) {
|
||||
raw, err := f.ask("gitea.gitea_open_pulls", map[string]any{})
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Merge on ready (novox/hq issue 722).
|
||||
//
|
||||
// The operator, 2026-10-14: "the reviewer task should merge the request or mark the MR as ready to merge in any case".
|
||||
// Before, a reviewed pull request with green checks waited until a session called the forge's merge tool, and again
|
||||
// after every check the tool asked because the trunk had moved. Now the independent reviewer marks the pull request
|
||||
// ready at the head it approved — the forge label `mesh/ready` and a comment "ready at <full head sha>" (approving
|
||||
// through the forge is the operator's) — and this owner merges it, through the forge's own merge tool
|
||||
// (gitea_merge_pull_request), the one path every merge takes:
|
||||
//
|
||||
// - only at the head the mark names, and only while that is the pull request's head: a push after the mark clears
|
||||
// it — the label taken off, and said on the pull request — and the new head needs a mark of its own;
|
||||
// - only when its delivery is ready here: its check passed against its trunk's head. A verdict out of date is judged
|
||||
// again by the merge tool, which asks the check against the trunk's head itself (novox/hq ADR 0323 §5); the merge
|
||||
// is asked again once a minute, and lands on the passing verdict;
|
||||
// - a group member only at its turn in the group's order, and only once the group's composed check passed for its
|
||||
// members' heads as they are;
|
||||
// - a check that failed merges nothing: it is said once on the pull request, and as a stalled line, which the
|
||||
// controller raises as the condition `delivery.<id>.stalled`. So is a mark the merge tool refused for an hour.
|
||||
//
|
||||
// What this owner does with a mark is kept on the delivery (Ready), said in its log, and the merge's transitions name
|
||||
// it as their author.
|
||||
|
||||
// ReadyMark is a pull request's ready mark as the forge reads it (the gitea module's gitea_open_pulls): the head the
|
||||
// newest "ready at" comment names, who wrote it and when, and the label's id. Head is empty when the label is on and
|
||||
// no comment names a head.
|
||||
type ReadyMark struct {
|
||||
Head string `json:"head"`
|
||||
By string `json:"by,omitempty"`
|
||||
At string `json:"at,omitempty"`
|
||||
LabelID int `json:"label_id"`
|
||||
}
|
||||
|
||||
// ReadyLabel is the label that marks a pull request ready.
|
||||
const ReadyLabel = "mesh/ready"
|
||||
|
||||
// readyTryEvery is how often a marked head's merge is asked while the merge tool refuses it: a check it asked takes
|
||||
// minutes, and a refusal costs the forge a few reads.
|
||||
const readyTryEvery = time.Minute
|
||||
|
||||
// readyRefusedFor is how long the merge tool may refuse a marked head before it is said as stalled: longer than a
|
||||
// check takes (the controller's checkTimeout is 45 minutes), so a check on its way is never said.
|
||||
const readyRefusedFor = time.Hour
|
||||
|
||||
// ReadyRun is what this owner did with a delivery's ready mark: kept on the delivery and shown whole by `show`.
|
||||
type ReadyRun struct {
|
||||
// Head, By and MarkedAt are the mark: the head it names, who marked it, when.
|
||||
Head string `json:"head"`
|
||||
By string `json:"by,omitempty"`
|
||||
MarkedAt string `json:"marked_at,omitempty"`
|
||||
// Seen is when this owner first read the mark.
|
||||
Seen time.Time `json:"seen"`
|
||||
// Waits is what the merge waits on, when it waits: a verdict, the group's turn or its composed check.
|
||||
Waits string `json:"waits,omitempty"`
|
||||
// Tries is how many times the merge was asked; LastTry when, and Answer what the merge tool last answered.
|
||||
Tries int `json:"tries,omitempty"`
|
||||
LastTry time.Time `json:"last_try"`
|
||||
Answer string `json:"answer,omitempty"`
|
||||
// RefusedSince is when the merge tool began refusing it without a break.
|
||||
RefusedSince *time.Time `json:"refused_since,omitempty"`
|
||||
// Merged is when the merge tool merged it.
|
||||
Merged *time.Time `json:"merged,omitempty"`
|
||||
// Failed is why it is not merged and will not be on this head: its check failed. Said once on the pull request.
|
||||
Failed string `json:"failed,omitempty"`
|
||||
}
|
||||
|
||||
// mergedBy is who a merge this owner made on a ready mark is said to be by, in its transitions.
|
||||
func (r *ReadyRun) mergedBy() string {
|
||||
if r == nil || r.Merged == nil {
|
||||
return ""
|
||||
}
|
||||
by := byOwner + ", on the ready mark at " + shortOf(r.Head, 12)
|
||||
if r.By != "" {
|
||||
by += " by " + r.By
|
||||
}
|
||||
return by
|
||||
}
|
||||
|
||||
// marked is a pull request read with a ready mark.
|
||||
type marked struct {
|
||||
pull OpenPull
|
||||
// cleared is when the mark was cleared, the label taken off: not cleared again within readyTryEvery.
|
||||
cleared time.Time
|
||||
}
|
||||
|
||||
// pullKey is a pull request as a key: owner/repo#number.
|
||||
func pullKey(p OpenPull) string {
|
||||
return strings.ToLower(p.Owner+"/"+p.Repo) + fmt.Sprintf("#%d", p.Number)
|
||||
}
|
||||
|
||||
// seeMarks keeps the open pull requests that carry a ready mark; under the lock. A pull request no longer open or
|
||||
// no longer marked drops out.
|
||||
func (h *Holder) seeMarks(open []OpenPull) {
|
||||
seen := map[string]*marked{}
|
||||
for _, p := range open {
|
||||
if p.Ready == nil || p.HeadSHA == "" {
|
||||
continue
|
||||
}
|
||||
k := pullKey(p)
|
||||
m := &marked{pull: p}
|
||||
if was := h.marks[k]; was != nil && was.pull.Ready != nil && was.pull.Ready.Head == p.Ready.Head &&
|
||||
was.pull.HeadSHA == p.HeadSHA {
|
||||
m.cleared = was.cleared
|
||||
}
|
||||
seen[k] = m
|
||||
}
|
||||
h.marks = seen
|
||||
}
|
||||
|
||||
// sameFull is whether a mark names a head: the whole sha, or — read from an older forge module — at least twelve
|
||||
// characters of it.
|
||||
func sameFull(mark, head string) bool {
|
||||
mark, head = strings.ToLower(mark), strings.ToLower(head)
|
||||
return len(mark) >= 12 && strings.HasPrefix(head, mark)
|
||||
}
|
||||
|
||||
// readyAsks works out, under the lock, what each ready mark needs: a mark cleared, a merge asked, a failure said.
|
||||
// The asking happens outside the lock.
|
||||
func (h *Holder) readyAsks(now time.Time) []func() {
|
||||
var asks []func()
|
||||
for k, m := range h.marks {
|
||||
p, mark := m.pull, *m.pull.Ready
|
||||
repository := strings.ToLower(p.Owner + "/" + p.Repo)
|
||||
if !sameFull(mark.Head, p.HeadSHA) {
|
||||
if !m.cleared.IsZero() && now.Sub(m.cleared) < readyTryEvery {
|
||||
continue
|
||||
}
|
||||
m.cleared = now
|
||||
asks = append(asks, h.clearMark(k, p, mark))
|
||||
continue
|
||||
}
|
||||
d := h.deliveries[IDOf(repository, p.HeadSHA)]
|
||||
if d == nil || d.State.Final() || d.MergedAs != "" {
|
||||
continue // not announced yet, or past its merge
|
||||
}
|
||||
if d.Ready == nil || d.Ready.Head != mark.Head {
|
||||
d.Ready = &ReadyRun{Head: mark.Head, By: mark.By, MarkedAt: mark.At, Seen: now}
|
||||
h.Logf("[mesh-delivery] %s is marked ready at %s by %s: merged once its check passes against its trunk's head",
|
||||
d.ID, shortOf(mark.Head, 12), orNone(mark.By))
|
||||
h.keep(d)
|
||||
}
|
||||
r := d.Ready
|
||||
if r.Merged != nil {
|
||||
continue
|
||||
}
|
||||
if d.State == Rejected {
|
||||
if r.Failed == "" {
|
||||
r.Failed = "its check failed"
|
||||
if d.Check != nil {
|
||||
r.Failed += ": " + oneLine(d.Check.Summary)
|
||||
if j := d.Check.Judged(); j != "" {
|
||||
r.Failed += " (" + j + ")"
|
||||
}
|
||||
}
|
||||
r.Waits = ""
|
||||
h.Logf("[mesh-delivery] %s is marked ready and not merged: %s", d.ID, r.Failed)
|
||||
h.keep(d)
|
||||
asks = append(asks, h.sayOn(d, fmt.Sprintf("mesh-delivery: **not merged.** This pull request is marked "+
|
||||
"ready at %s, and %s. A new head, marked ready once reviewed, or a recheck that passes, merges it.",
|
||||
mark.Head, r.Failed)))
|
||||
}
|
||||
continue
|
||||
}
|
||||
r.Failed = ""
|
||||
waits := h.readyWaits(d)
|
||||
if waits != r.Waits {
|
||||
r.Waits = waits
|
||||
if waits != "" {
|
||||
h.Logf("[mesh-delivery] %s is marked ready and waits: %s", d.ID, waits)
|
||||
}
|
||||
h.keep(d)
|
||||
}
|
||||
if waits != "" || (!r.LastTry.IsZero() && now.Sub(r.LastTry) < readyTryEvery) {
|
||||
continue
|
||||
}
|
||||
r.Tries++
|
||||
r.LastTry = now
|
||||
h.keep(d)
|
||||
asks = append(asks, h.askMerge(d.ID, p, mark.Head))
|
||||
}
|
||||
return asks
|
||||
}
|
||||
|
||||
// readyWaits is what a marked delivery's merge waits on; empty when it is asked now. A ready delivery is asked; so is
|
||||
// a proposed one whose verdict went out of date and whose check nobody asked again — the merge tool asks it.
|
||||
func (h *Holder) readyWaits(d *Delivery) string {
|
||||
switch {
|
||||
case d.State == Ready:
|
||||
case d.State == Proposed && d.outOfDate() != "" && d.AskedAgain == nil:
|
||||
case d.State == Proposed && d.AskedAgain != nil:
|
||||
return "its check against the trunk's head is asked and has not answered"
|
||||
default:
|
||||
return "its check has not passed yet (" + string(d.State) + ")"
|
||||
}
|
||||
if d.Group == "" {
|
||||
return ""
|
||||
}
|
||||
return h.groupTurnToMerge(d)
|
||||
}
|
||||
|
||||
// groupTurnToMerge is why a group member may not merge yet; empty at its turn: the group's composed check passed for
|
||||
// its members' heads as they are and is not out of date, and every member before it in the group's order merged.
|
||||
func (h *Holder) groupTurnToMerge(d *Delivery) string {
|
||||
g := h.groups[d.Group]
|
||||
if g == nil {
|
||||
return ""
|
||||
}
|
||||
members := h.membersOf(g)
|
||||
if state, why := GroupState(g, members); state != "ready" && state != "delivering" {
|
||||
return fmt.Sprintf("its group %s is %s: %s", g.ID, state, why)
|
||||
}
|
||||
if c := g.Check; c == nil || (c.Verdict != "pass" && c.Verdict != "warning") || c.OutOfDate != "" ||
|
||||
!sameMembers(c.Commits, commitsOf(members)) {
|
||||
return "its group " + g.ID + "'s composed check has not passed for its members' heads"
|
||||
}
|
||||
if !containsString(g.Order, d.ID) {
|
||||
return "its group " + g.ID + "'s order is not worked out for it yet"
|
||||
}
|
||||
for _, id := range g.Order {
|
||||
if id == d.ID {
|
||||
return ""
|
||||
}
|
||||
if o := h.deliveries[id]; o != nil && o.MergedAs == "" && !o.State.Final() {
|
||||
return "its group " + g.ID + "'s order merges " + id + " first"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// askMerge asks the forge's merge tool to merge a marked head, and keeps its answer.
|
||||
func (h *Holder) askMerge(id string, p OpenPull, head string) func() {
|
||||
return func() {
|
||||
err := h.Forge.Merge(p.Owner, p.Repo, p.Number, head)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
d := h.deliveries[id]
|
||||
if d == nil || d.Ready == nil {
|
||||
return
|
||||
}
|
||||
r, now := d.Ready, h.Now()
|
||||
if err == nil {
|
||||
r.Merged, r.Answer, r.RefusedSince = &now, "merged", nil
|
||||
h.Logf("[mesh-delivery] %s merged on its ready mark at %s, its check passed against its trunk's head", id,
|
||||
shortOf(head, 12))
|
||||
h.keep(d)
|
||||
return
|
||||
}
|
||||
answer := oneLine(err.Error())
|
||||
if r.RefusedSince == nil {
|
||||
r.RefusedSince = &now
|
||||
}
|
||||
if answer != r.Answer {
|
||||
h.Logf("[mesh-delivery] %s is marked ready, and the merge tool did not merge it (asked again in %s): %s", id,
|
||||
readyTryEvery, answer)
|
||||
}
|
||||
r.Answer = answer
|
||||
h.keep(d)
|
||||
}
|
||||
}
|
||||
|
||||
// clearMark takes a mark off a pull request whose head moved after it, and says so on it.
|
||||
func (h *Holder) clearMark(k string, p OpenPull, mark ReadyMark) func() {
|
||||
return func() {
|
||||
err := h.Forge.Unlabel(p.Owner, p.Repo, p.Number, mark.LabelID)
|
||||
if err == nil {
|
||||
err = h.Forge.Comment(p.Owner, p.Repo, p.Number, fmt.Sprintf("mesh-delivery: the ready mark at %s is cleared: "+
|
||||
"the head is now %s, pushed after it. Mark the new head ready once it is reviewed.", mark.Head, p.HeadSHA))
|
||||
}
|
||||
if err != nil {
|
||||
h.Logf("[mesh-delivery] %s's ready mark at %s names an older head than %s, and could not be cleared yet: %v",
|
||||
k, shortOf(mark.Head, 12), shortOf(p.HeadSHA, 12), err)
|
||||
return
|
||||
}
|
||||
h.Logf("[mesh-delivery] %s's ready mark at %s cleared: its head is now %s", k, shortOf(mark.Head, 12),
|
||||
shortOf(p.HeadSHA, 12))
|
||||
h.mu.Lock()
|
||||
delete(h.marks, k)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// sayOn comments on a delivery's pull request.
|
||||
func (h *Holder) sayOn(d *Delivery, body string) func() {
|
||||
owner, repo, number, id := d.Owner(), d.Repo(), d.Number, d.ID
|
||||
return func() {
|
||||
if err := h.Forge.Comment(owner, repo, number, body); err != nil {
|
||||
h.Logf("[mesh-delivery] %s: could not say on its pull request: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readyLines are the marked heads that will not merge: a check that failed at once, a merge refused past its bound;
|
||||
// as stalled lines, which the controller raises as conditions. Under the lock.
|
||||
func (h *Holder) readyLines(now time.Time) []StalledLine {
|
||||
var out []StalledLine
|
||||
for _, d := range h.deliveries {
|
||||
r := d.Ready
|
||||
if r == nil || r.Merged != nil || d.MergedAs != "" || d.State.Final() {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case r.Failed != "" && d.State == Rejected:
|
||||
out = append(out, StalledLine{ID: d.ID, Number: d.Number, State: d.State, For: now.Sub(r.Seen).Round(time.Second).String(),
|
||||
Bound: "0s", H2: "none: a new head marked ready, or a recheck that passes — the operator's",
|
||||
Says: fmt.Sprintf("%s#%d is marked ready at %s and not merged: %s", d.Repository, d.Number,
|
||||
shortOf(r.Head, 12), r.Failed)})
|
||||
case r.RefusedSince != nil && now.Sub(*r.RefusedSince) >= readyRefusedFor:
|
||||
out = append(out, StalledLine{ID: d.ID, Number: d.Number, State: d.State,
|
||||
For: now.Sub(*r.RefusedSince).Round(time.Second).String(), Bound: readyRefusedFor.String(),
|
||||
H2: "none: the merge is asked again each minute — the operator's",
|
||||
Says: fmt.Sprintf("%s#%d is marked ready at %s, and the merge tool has refused it since %s: %s", d.Repository,
|
||||
d.Number, shortOf(r.Head, 12), r.RefusedSince.UTC().Format(time.RFC3339), r.Answer)})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// **A pull request marked ready is merged by this owner** (novox/hq issue 722): before, a reviewed pull request with
|
||||
// green checks waited until a session called the merge tool, and again after every check the tool asked because the
|
||||
// trunk had moved. Each test below fails on a holder without the ready mark: nothing merged it.
|
||||
|
||||
const (
|
||||
readyHead = "1111111111111111111111111111111111111111"
|
||||
pushed = "2222222222222222222222222222222222222222"
|
||||
)
|
||||
|
||||
// markedPull is an open pull request as gitea_open_pulls reads it, labelled mesh/ready at the head named.
|
||||
func markedPull(repo string, number int, head, markedAt string) OpenPull {
|
||||
owner, name, _ := strings.Cut(repo, "/")
|
||||
return OpenPull{Owner: owner, Repo: name, Number: number, Base: "main", HeadSHA: head, Labels: []string{ReadyLabel},
|
||||
Ready: &ReadyMark{Head: markedAt, By: "reviewer", At: "2026-10-14T19:00:00Z", LabelID: 31}}
|
||||
}
|
||||
|
||||
func judgedAt(repo string, number int, sha, gate, trunk string) CheckedEvent {
|
||||
c := verdict(repo, number, sha, gate)
|
||||
c.Trunk = trunk
|
||||
return c
|
||||
}
|
||||
|
||||
func TestAReadyPullRequestMarkedAtItsHeadIsMergedThroughTheMergeTool(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
id := IDOf("novox/app", readyHead)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "pass", "t1t1t1t1t1t1"))
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 0 {
|
||||
t.Fatalf("an unmarked pull request was merged: %v", w.forge.merges)
|
||||
}
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, readyHead, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 || w.forge.merges[0] != "novox/app#7@"+readyHead {
|
||||
t.Fatalf("a ready, marked pull request was merged %v; wanted once, at the marked head", w.forge.merges)
|
||||
}
|
||||
d := w.delivery(id)
|
||||
if d.Ready == nil || d.Ready.Merged == nil || d.Ready.By != "reviewer" || d.Ready.Tries != 1 {
|
||||
t.Fatalf("what was done with the mark is not kept: %+v", d.Ready)
|
||||
}
|
||||
// Its merge's transition names who merged it.
|
||||
w.h.PullMerged(merged("novox/app", 7, readyHead, "m7m7m7m7m7m7"))
|
||||
w.h.WalkMoved(w.ctl.put(aWalk("plan-7", "novox/app", "m7m7m7m7m7m7", true)))
|
||||
w.settleAll()
|
||||
d = w.delivery(id)
|
||||
var last Transition
|
||||
for _, tr := range d.Transitions {
|
||||
if tr.Event == EvMerged {
|
||||
last = tr
|
||||
}
|
||||
}
|
||||
if !strings.Contains(last.By, "ready mark at "+readyHead[:12]+" by reviewer") {
|
||||
t.Fatalf("the merge's transition does not name the mark: %+v", last)
|
||||
}
|
||||
if len(w.forge.merges) != 1 {
|
||||
t.Fatalf("merged again: %v", w.forge.merges)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPushAfterTheMarkClearsItAndNothingIsMerged(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.PullUpdated(pr("novox/app", 7, pushed, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, pushed, "pass", "t1t1t1t1t1t1"))
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, pushed, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 0 {
|
||||
t.Fatalf("a head pushed after the mark was merged: %v", w.forge.merges)
|
||||
}
|
||||
if len(w.forge.unlabels) != 1 || w.forge.unlabels[0] != "novox/app#7-31" {
|
||||
t.Fatalf("the stale mark's label was not taken off: %v", w.forge.unlabels)
|
||||
}
|
||||
if len(w.forge.comments) != 1 || !strings.Contains(w.forge.comments[0], "cleared") ||
|
||||
!strings.Contains(w.forge.comments[0], pushed) {
|
||||
t.Fatalf("the cleared mark is not said on the pull request: %v", w.forge.comments)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMovedTrunkIsJudgedAgainByTheMergeToolAndMergedOnItsVerdict(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
id := IDOf("novox/app", readyHead)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "pass", "t1t1t1t1t1t1"))
|
||||
// Another merge moves the trunk: its verdict is out of date, and it goes back to proposed.
|
||||
w.h.PullMerged(merged("novox/app", 9, "9999999999999999", "t2t2t2t2t2t2"))
|
||||
if w.state(id) != Proposed {
|
||||
t.Fatalf("out of date, it is %s", w.state(id))
|
||||
}
|
||||
// The merge tool asks the check against the trunk's head and refuses: nothing merged.
|
||||
w.forge.refuse = errors.New("the forge refused gitea_merge_pull_request: The check of head merged into trunk was asked")
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, readyHead, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 {
|
||||
t.Fatalf("the merge tool was not asked once to judge it again: %v", w.forge.merges)
|
||||
}
|
||||
// The tool's ask is the head announced again; it waits for that verdict, asking nothing.
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.later(5 * time.Minute)
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 || !strings.Contains(w.delivery(id).Ready.Waits, "asked") {
|
||||
t.Fatalf("asked again while its check was on its way: %v (%+v)", w.forge.merges, w.delivery(id).Ready)
|
||||
}
|
||||
// It passes against the trunk's head: merged, without anyone asking.
|
||||
w.forge.refuse = nil
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "pass", "t2t2t2t2t2t2"))
|
||||
w.settleAll()
|
||||
if w.state(id) != Ready || len(w.forge.merges) != 2 || w.delivery(id).Ready.Merged == nil {
|
||||
t.Fatalf("on its passing verdict it was not merged: %s %v %+v", w.state(id), w.forge.merges, w.delivery(id).Ready)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMarkedHeadWhoseCheckFailedIsNotMergedAndIsSaid(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
id := IDOf("novox/app", readyHead)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "fail", "t1t1t1t1t1t1"))
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, readyHead, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
w.later(10 * time.Minute)
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 0 {
|
||||
t.Fatalf("a head whose check failed was merged: %v", w.forge.merges)
|
||||
}
|
||||
if len(w.forge.comments) != 1 || !strings.Contains(w.forge.comments[0], "not merged") {
|
||||
t.Fatalf("the failure is not said once on the pull request: %v", w.forge.comments)
|
||||
}
|
||||
lines := w.h.Stalled()
|
||||
if len(lines) != 1 || lines[0].ID != id || lines[0].State != Rejected || !strings.Contains(lines[0].Says, "marked ready") {
|
||||
t.Fatalf("the failure is not a stalled line, which the controller raises as a condition: %+v", lines)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMarkRefusedForAnHourIsSaid(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
w.h.PullUpdated(pr("novox/app", 7, readyHead, "feat/x", "src/a.go"))
|
||||
w.h.Checked(judgedAt("novox/app", 7, readyHead, "pass", "t1t1t1t1t1t1"))
|
||||
w.forge.refuse = errors.New("the forge refused gitea_merge_pull_request: mesh/repo-check is pending")
|
||||
w.forge.open = []OpenPull{markedPull("novox/app", 7, readyHead, readyHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
w.later(30 * time.Second)
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 {
|
||||
t.Fatalf("asked again within the minute: %v", w.forge.merges)
|
||||
}
|
||||
w.later(readyRefusedFor)
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 2 {
|
||||
t.Fatalf("not asked again after a minute: %v", w.forge.merges)
|
||||
}
|
||||
if lines := w.h.Stalled(); len(lines) != 1 || !strings.Contains(lines[0].Says, "refused it since") {
|
||||
t.Fatalf("a mark refused for an hour is not said: %+v", lines)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGroupMergesItsMarkedMembersInOrderOnlyOnceComposed(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
const ctlHead, catHead = "c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1", "d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2"
|
||||
ctl, cat := IDOf("novox/mesh-controller", ctlHead), IDOf("novox/mesh-catalog", catHead)
|
||||
w.ctl.order = func(ms []Member) Order { return Order{Order: []string{ctl, cat}} }
|
||||
w.h.PullUpdated(pr("novox/mesh-controller", 1, ctlHead, "feat/x", "internal/a.go"))
|
||||
w.h.PullUpdated(pr("novox/mesh-catalog", 2, catHead, "feat/x", "modules/app/module.json"))
|
||||
w.h.Checked(judgedAt("novox/mesh-controller", 1, ctlHead, "pass", "t1t1t1t1t1t1"))
|
||||
w.h.Checked(judgedAt("novox/mesh-catalog", 2, catHead, "pass", "t3t3t3t3t3t3"))
|
||||
w.forge.open = []OpenPull{markedPull("novox/mesh-controller", 1, ctlHead, ctlHead),
|
||||
markedPull("novox/mesh-catalog", 2, catHead, catHead)}
|
||||
w.h.SeeOpenPulls()
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 0 {
|
||||
t.Fatalf("a member merged before its group's composed check passed: %v", w.forge.merges)
|
||||
}
|
||||
w.h.Checked(CheckedEvent{Group: "feat/x", ID: "check-1", Verdict: "pass", Summary: "both compose"})
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 1 || w.forge.merges[0] != "novox/mesh-controller#1@"+ctlHead {
|
||||
t.Fatalf("composed, the first member in the group's order was not merged alone: %v", w.forge.merges)
|
||||
}
|
||||
if waits := w.delivery(cat).Ready.Waits; !strings.Contains(waits, "merges "+ctl+" first") {
|
||||
t.Fatalf("the second member does not say it waits its turn: %q", waits)
|
||||
}
|
||||
w.h.PullMerged(merged("novox/mesh-controller", 1, ctlHead, "m1m1m1m1m1m1"))
|
||||
w.settleAll()
|
||||
if len(w.forge.merges) != 2 || w.forge.merges[1] != "novox/mesh-catalog#2@"+catHead {
|
||||
t.Fatalf("after the first member merged, the next was not: %v", w.forge.merges)
|
||||
}
|
||||
}
|
||||
@@ -498,7 +498,12 @@ func Apply(d *Delivery, ev Event, act bool, f Facts) (Transition, error) {
|
||||
if why == "" {
|
||||
why = r.Guard
|
||||
}
|
||||
t := Transition{At: f.Now, From: d.State, To: r.To, Event: ev, Why: why, By: f.By}
|
||||
by := f.By
|
||||
if by == "" && (ev == EvMerged || ev == EvDone) && d.MergedAs != "" {
|
||||
// A merge this owner made on a ready mark names it as its author (novox/hq issue 722).
|
||||
by = d.Ready.mergedBy()
|
||||
}
|
||||
t := Transition{At: f.Now, From: d.State, To: r.To, Event: ev, Why: why, By: by}
|
||||
d.State, d.Since = r.To, f.Now
|
||||
d.Transitions = append(d.Transitions, t)
|
||||
if len(d.Transitions) > keptTransitions {
|
||||
|
||||
@@ -72,6 +72,9 @@ type OpenPull struct {
|
||||
// than that says none: the head is then read by Statuses alone, as before, and a pending check is not told
|
||||
// from an answered one.
|
||||
Checks map[string]HeadCheck `json:"checks,omitempty"`
|
||||
// Labels are its labels by name, and Ready its ready mark, when it carries one (novox/hq issue 722).
|
||||
Labels []string `json:"labels,omitempty"`
|
||||
Ready *ReadyMark `json:"ready,omitempty"`
|
||||
}
|
||||
|
||||
// HeadCheck is one status on a head as the forge keeps it: pending, success, failure, error or warning.
|
||||
@@ -201,6 +204,7 @@ func (h *Holder) SeeOpenPulls() {
|
||||
seen[id] = u
|
||||
}
|
||||
h.unchecked = seen
|
||||
h.seeMarks(open)
|
||||
}
|
||||
|
||||
// started is whether the head's check started, rather than was never asked: it has any merge check, or a delivery
|
||||
|
||||
@@ -249,6 +249,7 @@ func (h *Holder) Stalled() []StalledLine {
|
||||
}
|
||||
out = append(out, h.withChecks(h.uncheckedLines(now))...)
|
||||
out = append(out, h.orphanLines(now)...)
|
||||
out = append(out, h.readyLines(now)...)
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -41,12 +41,16 @@
|
||||
"seat:mesh-controller.deliver",
|
||||
"seat:mesh-controller.delivery-stop",
|
||||
"seat:mesh-controller.delivery-walks",
|
||||
"seat:mesh-controller.forget-checks",
|
||||
"gitea.gitea_note_append",
|
||||
"gitea.gitea_delivery_view",
|
||||
"gitea.gitea_commit_status",
|
||||
"gitea.gitea_commit_statuses",
|
||||
"gitea.gitea_contains",
|
||||
"gitea.gitea_open_pulls"
|
||||
"gitea.gitea_open_pulls",
|
||||
"gitea.gitea_merge_pull_request",
|
||||
"gitea.gitea_add_comment",
|
||||
"gitea.gitea_api"
|
||||
],
|
||||
"state": [
|
||||
"deliveries",
|
||||
|
||||
@@ -72,7 +72,7 @@ as text. `get` serves each, and any other field a record of hq wrote under `fiel
|
||||
## Writing a record
|
||||
|
||||
1. `reserve` a number for its kind.
|
||||
2. `propose` the record whole. It is refused, naming every reason at once, when it breaks one of the **29 rules
|
||||
2. `propose` the record whole. It is refused, naming every reason at once, when it breaks one of the **30 rules
|
||||
that judge one record or its prose**. They are hq's checks moved to the write; `PerRecordRules` in `rules.go`
|
||||
lists each one with the check it comes from:
|
||||
- 25 on the structure: kind, reserved number, title, topic, date, deciders, research status, at least one
|
||||
@@ -81,7 +81,10 @@ as text. `get` serves each, and any other field a record of hq wrote under `fiel
|
||||
supersedes or changes is accepted, a changed clause is in force or changed (a drafted one too), a superseded record cited beside its
|
||||
superseder, a graduated effort says what it became, and the links in its text resolve;
|
||||
- 4 on the prose: no word the glossary retired, no daemon's line, a deferral names its tracking issue, and a
|
||||
progressive insight in the dated, marked form.
|
||||
progressive insight in the dated, marked form;
|
||||
- 1 on the operator's ask (hq issue 639): `brief`, a record that needs the operator carries a brief its ask reads
|
||||
at a glance — a headline of at most 60 characters, a one-line summary of at most 300, at most three points of
|
||||
at most 160, and no path, address, dotted name or long word. It holds records dated from 2026-10-13.
|
||||
|
||||
A rule holds a record from the day hq's checks began to hold it (`RuleFrom` in `rules.go`):
|
||||
- retired words from 2026-10-07 and daemons' lines from 2026-10-09 for a research effort; for a decision record
|
||||
@@ -122,7 +125,10 @@ as text. `get` serves each, and any other field a record of hq wrote under `fiel
|
||||
- On approve the record and its clauses are accepted and in force. Every clause it changes moves to
|
||||
`changed`, and every record it supersedes moves to `superseded`, each as a new version of that record. A record marked `needs-operator` is first asked of the
|
||||
operator (an ask that cannot be published is taken back, and the record is reviewed again later): an ask with
|
||||
Approve and Decline, both at the level approve, each bound to this version's digest. It is
|
||||
Approve and Decline, both at the level approve, each bound to this version's digest. The ask reads at a glance
|
||||
(hq issue 639): the record's `brief` — a headline saying what it changes for the operator, a summary, at most three
|
||||
points — and as its Details who proposed it, the review, the fingerprint and how to read its clauses; the clauses
|
||||
are never listed. An ask made before that change is composed again as it was asked (`form`). It is
|
||||
accepted only on the router's warrant for Approve, read back from the router's own record and held to the ask
|
||||
composed again. A record changed after it was asked finds the digests differ, and nothing is accepted. The
|
||||
warrant is kept with the record.
|
||||
|
||||
@@ -309,9 +309,11 @@ type Got struct {
|
||||
Source string `json:"source,omitempty"`
|
||||
Reserved string `json:"reserved,omitempty"`
|
||||
NeedsOperat bool `json:"needs-operator,omitempty"`
|
||||
Cut string `json:"cut,omitempty"`
|
||||
Bound int `json:"bound"`
|
||||
Read string `json:"read,omitempty"`
|
||||
// Brief is what the operator's ask shows of it (issue 639).
|
||||
Brief *Brief `json:"brief,omitempty"`
|
||||
Cut string `json:"cut,omitempty"`
|
||||
Bound int `json:"bound"`
|
||||
Read string `json:"read,omitempty"`
|
||||
|
||||
// Reconstructed, Amended and Touches are the record's fields of those names; Fields, any other it holds as
|
||||
// written (hq issue 487).
|
||||
@@ -349,7 +351,7 @@ func (k *KB) Get(a GetAsk) (*Got, error) {
|
||||
bound := boundOf(a.Bound)
|
||||
g := &Got{Record: key.String(), Title: r.Title, Status: r.Status, Topic: r.Topic, Date: r.Date, Deciders: r.Deciders,
|
||||
Version: version, Versions: e.Versions, Insights: r.Insights, Reviews: r.Reviews, Drafting: r.Drafting, Source: r.Source,
|
||||
NeedsOperat: r.NeedsOperator, Bound: bound, Since: k.since(ctx, key),
|
||||
NeedsOperat: r.NeedsOperator, Brief: r.Brief, Bound: bound, Since: k.since(ctx, key),
|
||||
Reconstructed: r.Reconstructed, Amended: r.Amended, Touches: r.Touches, Fields: r.Extra}
|
||||
if r.Status == StatusReserved || r.Status == StatusWithdrawn {
|
||||
g.Reserved = fmt.Sprintf("reserved by %s at %s for %q", r.ReservedBy, r.ReservedAt.Format("2006-01-02 15:04 UTC"), r.ReservedFor)
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/asks"
|
||||
)
|
||||
|
||||
// novox/hq issue 639: the operator would not read the ask for ADR 0343 — thirty plain lines, every clause one per
|
||||
// line. A record that needs the operator is asked with its brief: a headline that says what it changes for them, a
|
||||
// summary, at most three points; who proposed it, the fingerprint and how to read the clauses are the Details.
|
||||
|
||||
// adr0343 is ADR 0343 as it was asked on 2026-10-13: thirteen clauses, and the brief its author would now give.
|
||||
func adr0343() *Record {
|
||||
r := &Record{Kind: KindDecision, Number: 343, Status: StatusProposed, Date: "2026-10-13", NeedsOperator: true,
|
||||
Title: "A session's memory follows the operator: the agent module carries each project's memory folder to every node, and a file changed on two keeps both",
|
||||
Author: "fix-367@g14",
|
||||
Brief: &Brief{Headline: "Your agents' memory follows you to every machine",
|
||||
Summary: "What an agent learns in a project's memory is copied to every machine that runs the agent, so a session " +
|
||||
"anywhere starts with it. A file changed on two machines keeps both versions and warns you; secrets in memory " +
|
||||
"files are screened, though not perfectly.",
|
||||
Points: []string{"Only memory folders travel: links and files over 128 KiB stay where they are",
|
||||
"A conflict reaches you as a warning that needs you",
|
||||
"A deleted file is marked, and a newer change elsewhere outlives the deletion"}}}
|
||||
leads := []string{"Only the memory folders are carried", "Some memory files are not carried, and each is listed with why",
|
||||
"The memory folders become paths the module's own process writes", "Memory moves only between homes of the same kind",
|
||||
"The module's process on each node notices a change and puts it in the module's state",
|
||||
"Every other node writes the new version where its own file holds no change it did not carry, and keeps the version replaced",
|
||||
"When a file changed on two nodes, both versions are kept, the newer first",
|
||||
"A conflict is sent to the operator as a warning that needs them",
|
||||
"A deletion is carried as a removal marker, and a change outlives it",
|
||||
"On a node's first carrying, every version learned before is kept", "One read-only tool shows what is carried",
|
||||
"A value put straight into the state is not yet told apart from one the module put there", "How it is checked"}
|
||||
for i, l := range leads {
|
||||
r.Clauses = append(r.Clauses, Clause{N: i + 1, Text: "**" + l + ".** The statement.", Status: ClauseProposed, Source: SourceWritten})
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func TestADecisionAskReadsAtAGlance(t *testing.T) {
|
||||
r := adr0343()
|
||||
at := time.Date(2026, 10, 13, 14, 5, 0, 0, time.UTC)
|
||||
a := composeAsk(r, &OperatorAsk{ID: "kb-decision-343-0d1e2f3a", At: at, Version: 12, Form: AskGlance})
|
||||
if err := a.Check(at); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.Headline != "Your agents' memory follows you to every machine" {
|
||||
t.Errorf("the headline is not what it changes for the operator: %q", a.Headline)
|
||||
}
|
||||
if err := asks.Glance(a.Explanation); err != nil {
|
||||
t.Errorf("%v:\n%s", err, a.Explanation)
|
||||
}
|
||||
if n := strings.Count(a.Explanation, "\n• "); n != 3 || !strings.HasPrefix(a.Explanation, "What an agent learns") {
|
||||
t.Errorf("the summary and its %d points:\n%s", n, a.Explanation)
|
||||
}
|
||||
for _, c := range r.Clauses {
|
||||
if strings.Contains(a.Explanation+a.Details, c.Lead()) {
|
||||
t.Errorf("the ask lists the clause %d: %q", c.N, c.Lead())
|
||||
}
|
||||
}
|
||||
details := strings.Split(a.Details, "\n")
|
||||
if len(details) != 2 || !strings.Contains(details[0], "ADR 0343, proposed by fix-367@g14; the knowledge base's own review approved it.") ||
|
||||
!strings.Contains(details[0], "Fingerprint "+fingerprint(r.Digest())+".") ||
|
||||
details[1] != "Read its 13 clauses with the knowledge base's get, number 343." {
|
||||
t.Errorf("the details:\n%s", a.Details)
|
||||
}
|
||||
// The ask made before the brief is composed again as it was, so its warrant still holds after the change.
|
||||
old := composeAsk(r, &OperatorAsk{ID: "kb-decision-343-0d1e2f3a", At: at, Version: 12})
|
||||
if !strings.Contains(old.Explanation, "Its 13 clause(s):") || old.Headline != "Accept ADR 0343?" || old.Details != "" || old.Digest() == a.Digest() {
|
||||
t.Errorf("an ask made before the brief is not composed as it was asked:\n%s", old.Explanation)
|
||||
}
|
||||
// Without a brief (a record proposed before the rule), the glance is the title, and no clause.
|
||||
r.Brief = nil
|
||||
a = composeAsk(r, &OperatorAsk{ID: "kb-decision-343-0d1e2f3a", At: at, Version: 12, Form: AskGlance})
|
||||
if a.Headline != "Approve ADR 0343?" || asks.Glance(a.Explanation) != nil || strings.Contains(a.Explanation, "Only the memory folders") {
|
||||
t.Errorf("without a brief: %q\n%s", a.Headline, a.Explanation)
|
||||
}
|
||||
}
|
||||
|
||||
// A brief is held to what the phone reads at a glance, each way it fails named.
|
||||
func TestABriefIsHeldToAGlance(t *testing.T) {
|
||||
good := adr0343().Brief
|
||||
if got := briefProblems(good); len(got) != 0 {
|
||||
t.Fatalf("the brief of ADR 0343 is refused: %v", got)
|
||||
}
|
||||
for name, c := range map[string]struct {
|
||||
change func(b *Brief)
|
||||
says string
|
||||
}{
|
||||
"no headline": {func(b *Brief) { b.Headline = "" }, "headline is empty"},
|
||||
"long headline": {func(b *Brief) { b.Headline = strings.Repeat("memory ", 10) }, "longer than 60"},
|
||||
"no summary": {func(b *Brief) { b.Summary = " " }, "summary is empty"},
|
||||
"long summary": {func(b *Brief) { b.Summary = strings.Repeat("A short sentence. ", 20) }, "summary is"},
|
||||
"four points": {func(b *Brief) { b.Points = append(b.Points, "one more") }, "4 points"},
|
||||
"a path": {func(b *Brief) { b.Points[0] = "Carried from the agent's home under .claude/projects" }, "names a path"},
|
||||
"two lines": {func(b *Brief) { b.Summary = "One.\nTwo." }, "more than one line"},
|
||||
} {
|
||||
b := *good
|
||||
b.Points = append([]string{}, good.Points...)
|
||||
c.change(&b)
|
||||
if got := fmt.Sprint(briefProblems(&b)); !strings.Contains(got, c.says) {
|
||||
t.Errorf("%s: %s", name, got)
|
||||
}
|
||||
}
|
||||
if got := briefProblems(nil); len(got) != 1 || !strings.Contains(got[0], "carries a brief") {
|
||||
t.Errorf("no brief: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -238,6 +238,8 @@ type ProposeAsk struct {
|
||||
Links []LinkAsk
|
||||
Homes []string
|
||||
NeedsOperator bool
|
||||
// Brief is what the operator's ask shows (novox/hq issue 639).
|
||||
Brief *Brief
|
||||
// Status is a research effort's: active, graduated or abandoned.
|
||||
Status string
|
||||
// Insight, for an accepted record, is what stood before: the proposal is a progressive insight.
|
||||
@@ -280,7 +282,7 @@ func (k *KB) Propose(caller string, a ProposeAsk) (*Proposed, error) {
|
||||
}
|
||||
r := &Record{Kind: a.Kind, Number: a.Number, Title: strings.TrimSpace(a.Title), Topic: strings.TrimSpace(a.Topic),
|
||||
Status: StatusProposed, Date: strings.TrimSpace(a.Date), Deciders: a.Deciders, Effort: a.Status,
|
||||
NeedsOperator: a.NeedsOperator, Sections: a.Sections, Homes: a.Homes, Author: caller}
|
||||
NeedsOperator: a.NeedsOperator, Brief: a.Brief, Sections: a.Sections, Homes: a.Homes, Author: caller}
|
||||
if r.Date == "" {
|
||||
r.Date = k.now().Format("2006-01-02")
|
||||
}
|
||||
|
||||
@@ -914,8 +914,8 @@ func Tools(k *KB, caller func(map[string]any) string) []stdio.Tool {
|
||||
Description: "Propose a record whole under a reserved number: its title, topic, date and deciders; for a decision its " +
|
||||
"clauses, each opening with a bold lead (\"**What is decided.** …\"), and its reasoning in sections (Context, " +
|
||||
"Considered Options, Consequences, How it is checked, References); for a research effort its status and documents; its " +
|
||||
"links (supersedes, changes \"0276 §4\", extends, became, cites), and whether it needs the operator. Refused, naming " +
|
||||
"every reason at once and writing nothing, when it breaks one of the 29 rules that judge one record or its prose — a " +
|
||||
"links (supersedes, changes \"0276 §4\", extends, became, cites), and whether it needs the operator, with the brief its ask shows. Refused, naming " +
|
||||
"every reason at once and writing nothing, when it breaks one of the 30 rules that judge one record or its prose — a " +
|
||||
"link to nothing, a clause without a bold lead, a superseded record cited alone, an unknown topic, a retired word. A " +
|
||||
"proposal is revised by proposing it again; an accepted record changes only by a progressive insight (insight: what " +
|
||||
"stood before). The knowledge base then reviews each version itself, in a judgement that sees only the record, the " +
|
||||
@@ -937,13 +937,19 @@ func Tools(k *KB, caller func(map[string]any) string) []stdio.Tool {
|
||||
"to": text("the target"), "from": integer("the clause of this record it goes out from")}, "required": []string{"kind", "to"}}},
|
||||
"homes": texts("hq documents that cite it, such as a design's path; a decision needs one unless an accepted record links it"),
|
||||
"needs-operator": flag("it holds only once the operator approves it"),
|
||||
"status": map[string]any{"type": "string", "enum": ResearchStatuses, "description": "a research effort's status"},
|
||||
"insight": text("for an accepted record: a progressive insight, saying what stood before"),
|
||||
"why": text("one line: why this version"),
|
||||
"brief": map[string]any{"type": "object", "description": "required with needs-operator: what the operator's phone shows " +
|
||||
"in place of the clauses (issue 639) — a headline of at most 60 characters saying what it changes for the operator, " +
|
||||
"not the title; a summary of two or three short sentences, at most 300 characters, on what changes, why and what it " +
|
||||
"costs or risks; at most three points of at most 160 characters. No path, address, dotted name or long word",
|
||||
"properties": map[string]any{"headline": text("what it changes for the operator"), "summary": text("two or three short sentences"),
|
||||
"points": texts("at most three, only where they add something")}, "required": []string{"headline", "summary"}},
|
||||
"status": map[string]any{"type": "string", "enum": ResearchStatuses, "description": "a research effort's status"},
|
||||
"insight": text("for an accepted record: a progressive insight, saying what stood before"),
|
||||
"why": text("one line: why this version"),
|
||||
}),
|
||||
Run: func(m map[string]any) (any, error) {
|
||||
a, err := readArgs("propose", m, "kind", "number", "title", "topic", "date", "deciders", "clauses", "sections",
|
||||
"links", "homes", "needs-operator", "status", "insight", "why")
|
||||
"links", "homes", "needs-operator", "brief", "status", "insight", "why")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -977,6 +983,12 @@ func Tools(k *KB, caller func(map[string]any) string) []stdio.Tool {
|
||||
if err := decode(m["links"], &p.Links, "links is a list of {kind, to, from}"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if m["brief"] != nil {
|
||||
p.Brief = &Brief{}
|
||||
if err := decode(m["brief"], p.Brief, "brief is {headline, summary, points}"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return k.Propose(caller(m), p)
|
||||
}},
|
||||
{Name: Seat + ".import",
|
||||
|
||||
@@ -121,6 +121,12 @@ func TestItsProcessesAreThePreparationTheActAndTheJudge(t *testing.T) {
|
||||
!reflect.DeepEqual(m.Tools, []string{HealthTool, HighestTool}) {
|
||||
t.Fatalf("watch %v, tools %v", watch, m.Tools)
|
||||
}
|
||||
// The watch's verdict is whether the database serves, so its check names the provision it exercises: while the
|
||||
// database's provider is unhealthy, this finding is held under the provider's condition (hq ADR 0240 rule 5,
|
||||
// issue 145).
|
||||
if h["needs"] != "postgres-database" {
|
||||
t.Fatalf("watch's check needs %v; it exercises postgres-database", h["needs"])
|
||||
}
|
||||
if watch["env"].(map[string]any)["MESH_KNOWLEDGE_STATUS"] != m.Build.Artifacts[0].Env["MESH_KNOWLEDGE_STATUS"] {
|
||||
t.Fatal("watch writes another status file than the health tool reads")
|
||||
}
|
||||
|
||||
@@ -84,9 +84,48 @@ func fingerprint(digest string) string {
|
||||
return strings.Join(g, " ")
|
||||
}
|
||||
|
||||
// AskGlance is the form of an ask read at a glance (OperatorAsk.Form, novox/hq issue 639).
|
||||
const AskGlance = 1
|
||||
|
||||
// composeAsk is the ask for a record, composed from the record and its ask alone: asked once, and composed
|
||||
// again to hold the warrant to it.
|
||||
// again to hold the warrant to it — in the form it was asked in, so an ask made before a form changed is still
|
||||
// held to the words the operator was shown.
|
||||
func composeAsk(r *Record, a *OperatorAsk) asks.Ask {
|
||||
if a.Form == AskGlance {
|
||||
return glanceAsk(r, a)
|
||||
}
|
||||
return listedAsk(r, a)
|
||||
}
|
||||
|
||||
// glanceAsk is the ask read at a glance on the phone (novox/hq issue 639): the brief's headline, its summary and
|
||||
// points; who proposed it, its review, its fingerprint and how to read every clause are its Details, which the
|
||||
// router notes after the answers. A record without a brief (one proposed before the rule) is asked with its
|
||||
// title as its summary. The clauses are never listed.
|
||||
func glanceAsk(r *Record, a *OperatorAsk) asks.Ask {
|
||||
name := r.Key().String()
|
||||
headline, explanation := "Approve "+name+"?", name+" needs your approval before it holds."
|
||||
if t := strings.TrimSuffix(strings.TrimSpace(r.Title), "."); shown(t) && len([]rune(t)) < asks.SummaryLength {
|
||||
explanation = t + "."
|
||||
}
|
||||
if r.Brief != nil && len(briefProblems(r.Brief)) == 0 {
|
||||
headline, explanation = strings.TrimSpace(r.Brief.Headline), r.Brief.Explanation()
|
||||
}
|
||||
author := r.Author
|
||||
if author == "" {
|
||||
author = "an agent session"
|
||||
}
|
||||
clauses := fmt.Sprintf("Read its %d clauses with the knowledge base's get, number %d.", len(r.Clauses), r.Number)
|
||||
if len(r.Clauses) == 0 {
|
||||
clauses = fmt.Sprintf("Read it whole with the knowledge base's get, number %d.", r.Number)
|
||||
}
|
||||
details := fmt.Sprintf("%s, proposed by %s; the knowledge base's own review approved it. Fingerprint %s.\n%s",
|
||||
name, author, fingerprint(r.Digest()), clauses)
|
||||
return withOptions(r, a, asks.Ask{ID: a.ID, Headline: headline, Explanation: explanation, Details: details})
|
||||
}
|
||||
|
||||
// listedAsk is the ask as it was composed before the brief: every clause's lead listed. Composed only to hold
|
||||
// the warrant of an ask made then.
|
||||
func listedAsk(r *Record, a *OperatorAsk) asks.Ask {
|
||||
name := r.Key().String()
|
||||
headline := "Accept " + name + "?"
|
||||
var b strings.Builder
|
||||
@@ -111,9 +150,15 @@ func composeAsk(r *Record, a *OperatorAsk) asks.Ask {
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&b, "\n\nRead it whole with the knowledge base's get, number %d; its fingerprint is %s.", r.Number, fingerprint(r.Digest()))
|
||||
out := asks.Ask{ID: a.ID, Headline: headline, Explanation: b.String(), Who: asks.Operator,
|
||||
Expires: a.At.Add(AskLasts), OnExpiry: "the record stays proposed; nothing of it is in force",
|
||||
About: "knowledge." + r.Kind + "." + strconv.Itoa(r.Number)}
|
||||
return withOptions(r, a, asks.Ask{ID: a.ID, Headline: headline, Explanation: b.String()})
|
||||
}
|
||||
|
||||
// withOptions is an ask with what every form of it carries: who answers, its expiry, what it is about, and its
|
||||
// two options, each binding its act.
|
||||
func withOptions(r *Record, a *OperatorAsk, out asks.Ask) asks.Ask {
|
||||
out.Who, out.Expires = asks.Operator, a.At.Add(AskLasts)
|
||||
out.OnExpiry = "the record stays proposed; nothing of it is in force"
|
||||
out.About = "knowledge." + r.Kind + "." + strconv.Itoa(r.Number)
|
||||
for _, o := range []struct{ id, label, does string }{
|
||||
{OptionApprove, "Approve", "the record is accepted and its clauses are in force"},
|
||||
{OptionDecline, "Decline", "the record stays proposed; nothing of it is in force"},
|
||||
@@ -157,7 +202,7 @@ func (k *KB) askOperator(ctx context.Context, held *Entry, w *Record, by string,
|
||||
if k.Asks == nil {
|
||||
return unasked("the operator cannot be asked from here")
|
||||
}
|
||||
oa := &OperatorAsk{ID: newAskID(w), At: k.now(), Version: version, Said: AskWaiting}
|
||||
oa := &OperatorAsk{ID: newAskID(w), At: k.now(), Version: version, Said: AskWaiting, Form: AskGlance}
|
||||
ask := composeAsk(w, oa)
|
||||
if err := ask.Check(k.now()); err != nil {
|
||||
return unasked(fmt.Sprintf("the ask could not be made (%v)", err))
|
||||
|
||||
@@ -248,6 +248,9 @@ type OperatorAsk struct {
|
||||
ID string `json:"id"`
|
||||
At time.Time `json:"at"`
|
||||
Version int `json:"version"`
|
||||
// Form is how the ask was composed, so it is composed again the same way to hold the warrant to it: 0 for
|
||||
// an ask made before the brief (the clause leads listed), AskGlance for one read at a glance (issue 639).
|
||||
Form int `json:"form,omitempty"`
|
||||
// Said is what came of it: waiting, approved, declined, expired, refused (and why).
|
||||
Said string `json:"said"`
|
||||
Warrant string `json:"warrant,omitempty"`
|
||||
@@ -291,11 +294,14 @@ type Record struct {
|
||||
// written; what is one is a touches link.
|
||||
Touches []string `json:"touches,omitempty"`
|
||||
// Effort is the status a proposed research effort takes when it is accepted.
|
||||
Effort string `json:"effort,omitempty"`
|
||||
NeedsOperator bool `json:"needs-operator,omitempty"`
|
||||
Clauses []Clause `json:"clauses,omitempty"`
|
||||
Links []Link `json:"links,omitempty"`
|
||||
Sections []Section `json:"sections,omitempty"`
|
||||
Effort string `json:"effort,omitempty"`
|
||||
NeedsOperator bool `json:"needs-operator,omitempty"`
|
||||
// Brief is what the operator's phone shows when the record asks for their Approve: written by its author,
|
||||
// in the operator's words (novox/hq issue 639). Required of a record that needs the operator (the rule brief).
|
||||
Brief *Brief `json:"brief,omitempty"`
|
||||
Clauses []Clause `json:"clauses,omitempty"`
|
||||
Links []Link `json:"links,omitempty"`
|
||||
Sections []Section `json:"sections,omitempty"`
|
||||
// Homes are the documents of hq that cite the record (a design, a playbook), while those live in hq.
|
||||
Homes []string `json:"homes,omitempty"`
|
||||
// Extra holds the fields of an imported record this slice has no field of its own for, as written.
|
||||
@@ -329,6 +335,25 @@ type Insight struct {
|
||||
By string `json:"by,omitempty"`
|
||||
}
|
||||
|
||||
// Brief is a record as the operator is asked about it, on a phone, at a glance (novox/hq issue 639): a headline
|
||||
// that says what the record changes for the operator — not its title — a summary of two or three short
|
||||
// sentences on what changes, why, and what it costs or risks, and at most three points, only where they add
|
||||
// something. The clauses are never listed in the ask; it says how to read them.
|
||||
type Brief struct {
|
||||
Headline string `json:"headline"`
|
||||
Summary string `json:"summary"`
|
||||
Points []string `json:"points,omitempty"`
|
||||
}
|
||||
|
||||
// Explanation is the brief as the ask explains it: the summary, then a line for each point.
|
||||
func (b Brief) Explanation() string {
|
||||
out := strings.TrimSpace(b.Summary)
|
||||
for _, p := range b.Points {
|
||||
out += "\n• " + strings.TrimSpace(p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// PendingState marks a version that is a proposal over an accepted record: a progressive insight waiting for
|
||||
// its review. The accepted version stays the one served until it is accepted.
|
||||
type PendingState struct {
|
||||
@@ -442,6 +467,12 @@ func Render(r *Record) string {
|
||||
if r.NeedsOperator {
|
||||
field("needs operator", "yes")
|
||||
}
|
||||
if r.Brief != nil {
|
||||
field("brief", r.Brief.Headline)
|
||||
for _, l := range strings.Split(r.Brief.Explanation(), "\n") {
|
||||
field("brief", l)
|
||||
}
|
||||
}
|
||||
field("homes", strings.Join(r.Homes, ", "))
|
||||
keys := make([]string, 0, len(r.Extra))
|
||||
for k := range r.Extra {
|
||||
|
||||
@@ -18,6 +18,10 @@ func proposed(t *testing.T, w *world, author string, needsOperator bool) int {
|
||||
n := w.reserved(t, author)
|
||||
p := valid(n)
|
||||
p.NeedsOperator = needsOperator
|
||||
if needsOperator {
|
||||
p.Brief = &Brief{Headline: "Merges land after ninety seconds of quiet",
|
||||
Summary: "A merge window closes after ninety seconds without a merge, so merges land sooner."}
|
||||
}
|
||||
if _, err := w.k.Propose(author, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -245,7 +249,8 @@ func TestARecordThatNeedsTheOperatorIsAcceptedOnlyOnTheWarrant(t *testing.T) {
|
||||
}
|
||||
ask := w.router.asked[0]
|
||||
if err := ask.Check(w.clock); err != nil || ask.Options[0].Level != asks.Approve || ask.Options[1].Level != asks.Approve ||
|
||||
!strings.Contains(ask.Explanation, "the knowledge base's own review") {
|
||||
!strings.Contains(ask.Details, "the knowledge base's own review") || ask.Headline != "Merges land after ninety seconds of quiet" ||
|
||||
asks.Glance(ask.Explanation) != nil || strings.Contains(ask.Explanation, "The window closes") {
|
||||
t.Fatalf("the ask: %v %+v", err, ask)
|
||||
}
|
||||
// Without the warrant: nothing is accepted, however often the router's record is read or the reviews run.
|
||||
|
||||
@@ -2,9 +2,10 @@ package main
|
||||
|
||||
// The rules a record is held to (novox/hq ADR 0290 rule 4, to-be 55 §4 and §5).
|
||||
//
|
||||
// **29 rules judge one record or its prose**, and `propose` refuses a record that breaks any of them, naming every
|
||||
// **30 rules judge one record or its prose**, and `propose` refuses a record that breaks any of them, naming every
|
||||
// one it breaks at once. They are hq's checks (00-META/checks/records.py, cycle.py, index.py, words.py) as they
|
||||
// judge one record, moved to the write: 25 on its structure, 4 on its prose. Each has an id, said in the refusal,
|
||||
// judge one record, moved to the write: 25 on its structure, 4 on its prose; and the brief a record that needs
|
||||
// the operator is asked with (novox/hq issue 639). Each has an id, said in the refusal,
|
||||
// and one case in the table test (TestEveryPerRecordRuleRefusesAProposal).
|
||||
//
|
||||
// **4 rules judge the whole record set** (wholeSetRules) and run after every acceptance, and in the check
|
||||
@@ -15,6 +16,8 @@ import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/asks"
|
||||
)
|
||||
|
||||
// Rule is one rule that judges one record: its id and what it holds.
|
||||
@@ -25,7 +28,7 @@ type Rule struct {
|
||||
From string
|
||||
}
|
||||
|
||||
// PerRecordRules are the 29, in the order they are judged.
|
||||
// PerRecordRules are the 30, in the order they are judged.
|
||||
var PerRecordRules = []Rule{
|
||||
{"kind", "a record is a decision or a research effort", "cycle.py"},
|
||||
{"reserved", "its number was reserved for its kind and holds no other record", "cycle.py (duplicate numbers)"},
|
||||
@@ -56,6 +59,7 @@ var PerRecordRules = []Rule{
|
||||
{"daemon-line", "it writes no daemon's line", "words.py lines"},
|
||||
{"deferral", "a paragraph that puts work off names the issue that tracks it", "cycle.py deferrals"},
|
||||
{"insight-form", "a progressive insight its text mentions is in the dated, marked form", "records.py insights"},
|
||||
{"brief", "a record that needs the operator carries a brief its ask reads at a glance: a headline, a summary, at most three points, each fit for the phone", "novox/hq issue 639"},
|
||||
}
|
||||
|
||||
// Refusal is one rule a record breaks, and how.
|
||||
@@ -116,7 +120,7 @@ func allText(r *Record) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// JudgeRecord holds a proposed record to the 29 rules. held is the entry its number holds (a reservation, the
|
||||
// JudgeRecord holds a proposed record to the 30 rules. held is the entry its number holds (a reservation, the
|
||||
// proposal being revised, or the accepted record an insight corrects); lookup reads every other record.
|
||||
func JudgeRecord(r *Record, held *Entry, lookup Lookup, ref *Reference) []Refusal {
|
||||
var out []Refusal
|
||||
@@ -349,6 +353,11 @@ func JudgeRecord(r *Record, held *Entry, lookup Lookup, ref *Reference) []Refusa
|
||||
refuse("insight-form", "a progressive insight dated %s predates the record (%s)", mk[1], r.Date)
|
||||
}
|
||||
}
|
||||
if r.NeedsOperator || r.Brief != nil {
|
||||
for _, why := range briefProblems(r.Brief) {
|
||||
refuse("brief", "%s", why)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -597,6 +606,7 @@ var RuleFrom = map[string]string{
|
||||
"consequences": "2026-10-11",
|
||||
"checked": "2026-10-11",
|
||||
"live-citation": "2026-10-11",
|
||||
"brief": "2026-10-13",
|
||||
}
|
||||
|
||||
// DecisionFrom overrides RuleFrom for a decision record: hq's words check never read 02-DECISIONS ("a decision
|
||||
@@ -615,3 +625,35 @@ func Holds(rule, kind, date string) bool {
|
||||
}
|
||||
return !dated || !isDay.MatchString(date) || date >= from
|
||||
}
|
||||
|
||||
// briefProblems are the ways a brief would not read at a glance on the operator's phone (novox/hq issue 639):
|
||||
// missing; a headline empty or longer than an ask's; a summary or a point the router could refuse, or that
|
||||
// names a path, an address or a long word (shown); more than three points, or one too long (asks.Glance).
|
||||
func briefProblems(b *Brief) []string {
|
||||
if b == nil {
|
||||
return []string{"a record that needs the operator carries a brief (headline, summary, points): what it changes for the operator, " +
|
||||
"in their words, which its ask shows in place of its clauses"}
|
||||
}
|
||||
var out []string
|
||||
h := strings.TrimSpace(b.Headline)
|
||||
if h == "" || strings.Contains(h, "\n") || len([]rune(h)) > asks.HeadlineLength {
|
||||
out = append(out, fmt.Sprintf("the brief's headline is empty, more than one line, or longer than %d characters", asks.HeadlineLength))
|
||||
}
|
||||
if s := strings.TrimSpace(b.Summary); s == "" || strings.Contains(s, "\n") {
|
||||
out = append(out, "the brief's summary is empty or more than one line")
|
||||
}
|
||||
for i, p := range b.Points {
|
||||
if p = strings.TrimSpace(p); p == "" || strings.Contains(p, "\n") {
|
||||
out = append(out, fmt.Sprintf("the brief's point %d is empty or more than one line", i+1))
|
||||
}
|
||||
}
|
||||
if err := asks.Glance(b.Explanation()); err != nil {
|
||||
out = append(out, "the brief "+strings.TrimPrefix(err.Error(), "the explanation "))
|
||||
}
|
||||
for _, line := range append([]string{h}, strings.Split(b.Explanation(), "\n")...) {
|
||||
if !shown(line) {
|
||||
out = append(out, fmt.Sprintf("the brief's line %q names a path, an address, a dotted name or a long word, which the operator's phone is not shown", line))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -90,6 +90,9 @@ func TestEveryPerRecordRuleRefusesAProposal(t *testing.T) {
|
||||
{"insight-form", func(p *ProposeAsk, w *world, t *testing.T) {
|
||||
p.Sections[2].Text = "A progressive insight corrected the count."
|
||||
}},
|
||||
{"brief", func(p *ProposeAsk, w *world, t *testing.T) {
|
||||
p.Date, p.NeedsOperator = "2026-10-13", true
|
||||
}},
|
||||
}
|
||||
covered := map[string]bool{}
|
||||
for _, c := range cases {
|
||||
@@ -100,8 +103,8 @@ func TestEveryPerRecordRuleRefusesAProposal(t *testing.T) {
|
||||
t.Errorf("the rule %s has no case", r.ID)
|
||||
}
|
||||
}
|
||||
if len(PerRecordRules) != 29 {
|
||||
t.Errorf("%d per-record rules; ADR 0290 counts 29", len(PerRecordRules))
|
||||
if len(PerRecordRules) != 30 {
|
||||
t.Errorf("%d per-record rules; ADR 0290 counts 29, and issue 639 adds the brief", len(PerRecordRules))
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.rule, func(t *testing.T) {
|
||||
|
||||
@@ -3,7 +3,7 @@ module mesh-knowledge
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261011091942-4cf45b5ca0cf
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/nats-io/nats-server/v2 v2.11.17
|
||||
github.com/nats-io/nats.go v1.51.0
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261011091942-4cf45b5ca0cf h1:ED/+RszKwm86U7H/NZRbS4b5LzQ8n7rubqKmeFqFtvM=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261011091942-4cf45b5ca0cf/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013141520-9588871d6629 h1:7TYFV1Q6Mcz+lsLP/sds87tysET4rKCn3rRIQV8gNmA=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013141520-9588871d6629/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013145622-f4745447ba6d h1:HEJyqorKktrkJPeeJdwEo0kdrJjH3fm/YVS9MGftCqY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013145622-f4745447ba6d/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44 h1:r5xIo5qWOXQdCSMxvqJy8kV4U+P/QWXFK6971Ha6wU8=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
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/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
|
||||
@@ -156,6 +156,7 @@
|
||||
"health": {
|
||||
"kind": "tool",
|
||||
"tool": "knowledge_health",
|
||||
"needs": "postgres-database",
|
||||
"interval": "60s",
|
||||
"timeout": "10s",
|
||||
"looks": 2,
|
||||
|
||||
@@ -49,8 +49,9 @@ channel's client and no channel's secret.
|
||||
warrant published to the asker alone. A warrant the bus did not take is published again every minute.
|
||||
- **What the operator sees when they answer** (issue 372): first, in reply to the answer where it was given,
|
||||
that it was recorded and whether its asker was told ("You chose Approve: recorded, and claude-code was
|
||||
told.") — said only once the ask's end is recorded — or, refused, why; then the ask's message edited to how
|
||||
it ended, as its title ("You chose Approve at 13:30 on Telegram · <headline>"), with no answers left on it.
|
||||
told.") — said only once the ask's end is recorded — or, refused, why; then the ask's message edited with no
|
||||
answers left on it: its question whole (headline, summary, points, link, Details), and below it how it ended
|
||||
("You chose Approve at 13:30 on Telegram.") and who acts on it (issue 714).
|
||||
What the asker then did is not said: the asks protocol carries no result back to the router, so the
|
||||
message says only that the asker was told and acts on it itself.
|
||||
- **An ask never defaults**: at its expiry it ends `expired` and its asker does what it said it would.
|
||||
@@ -129,8 +130,24 @@ operator (urgent at its bound, or its words now say "Needs you:"). An urgent con
|
||||
|
||||
**A message offers the answers of the ask about it, and Details** (`cmd/messenger/answers.go`). The router
|
||||
calls no verb of a condition's: the controller asks for the answers a condition names, and performs the one
|
||||
chosen on its warrant. Details is a ticket per kind, good for a day, used once, shown where it was chosen. A
|
||||
warning kept quiet is also said once after a day.
|
||||
chosen on its warrant. Details is a ticket per kind, good for a day, used once, shown where it was chosen, on a
|
||||
condition's message. A warning kept quiet is also said once after a day.
|
||||
|
||||
**An ask's message reads at a glance** (hq issue 639). Its title is the asker's headline and its body the asker's
|
||||
explanation alone — a summary, then at most three points (`asks.Glance`; an ask that does not hold to it is shown
|
||||
and said in the log). Everything else is the message's note (`asks.Message.Note`), which a channel shows apart and
|
||||
smaller: who asked and when, with what happens if nobody answers; what each answer does; where else it is answered;
|
||||
and the asker's Details (who proposed it, a fingerprint, how to read it whole) — on a kind that proves who answers
|
||||
and was given the ask's answers, its Details whole (`asks.Ask.WholeDetails`): every value an approval sets, held to
|
||||
the secret rule alone, as the whole words are. Answered, the message keeps its headline, body and Details, so the
|
||||
operator can read back what they answered (issue 714); its note becomes "You chose Approve at 16:06 on Telegram."
|
||||
with the router's word on the asker.
|
||||
|
||||
**An ask's values are shown whole where the sender is proven** (hq issue 383). An ask may carry its explanation
|
||||
twice: as it is held to the whole content rule, and whole (`asks.Ask.Whole`), its paths and addresses as they
|
||||
are. The whole is shown only on a kind the controller issued as `verified-sender` and that was given the ask's
|
||||
answers; everywhere else, and for every condition, the explanation under the content rule stands. A secret's
|
||||
shape leaves the mesh nowhere: an ask whose whole words carry one is refused as a whole (`CheckSecret`).
|
||||
|
||||
| When | What |
|
||||
|---|---|
|
||||
|
||||
@@ -365,10 +365,12 @@ func TestAnApproveFromTheLinkedAccountIsAWarrantForTheAskerAlone(t *testing.T) {
|
||||
for _, m := range ch.edits {
|
||||
edited = m
|
||||
}
|
||||
// The question's title is how it ended, read at a glance; then what the router knows of the asker (issue 372).
|
||||
if len(edited.Actions) != 0 || edited.Title != "You chose Release at 12:00 on Telegram · Delivery of hq held for 36 hours" ||
|
||||
!strings.HasPrefix(edited.Body, "Told to mesh-delivery, which acts on it itself.\n") {
|
||||
t.Errorf("%s still offers %q, or does not say how it ended: %q / %q", ch.name, labelsOf(edited), edited.Title, edited.Body)
|
||||
// The question stays whole (issue 714); below it, how it ended and what the router knows of the asker
|
||||
// (issue 372).
|
||||
if len(edited.Actions) != 0 || edited.Title != "Delivery of hq held for 36 hours" ||
|
||||
edited.Body != heldAsk(c, "d-1").Explanation ||
|
||||
edited.Note != "You chose Release at 12:00 on Telegram.\nTold to mesh-delivery, which acts on it itself." {
|
||||
t.Errorf("%s still offers %q, or does not keep the question and say how it ended (issue 714): %q / %q / %q", ch.name, labelsOf(edited), edited.Title, edited.Body, edited.Note)
|
||||
}
|
||||
}
|
||||
// The tap is confirmed where it was made, in reply to it, once the warrant stood — and before the question
|
||||
@@ -624,8 +626,8 @@ func TestAnAskExpiresAndNeverDefaults(t *testing.T) {
|
||||
for _, m := range tg.edits {
|
||||
edited = m
|
||||
}
|
||||
if len(edited.Actions) != 0 || !strings.HasPrefix(edited.Title, "No longer answerable: nobody answered in time · Delivery of hq") ||
|
||||
!strings.HasPrefix(edited.Body, "The delivery stays held.") {
|
||||
if len(edited.Actions) != 0 || !strings.HasPrefix(edited.Title, "Delivery of hq") ||
|
||||
edited.Body == "" || edited.Note != "No longer answerable: nobody answered in time.\nThe delivery stays held." {
|
||||
t.Errorf("the copy still offers answers, or does not say how it ended: %+v", edited)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,6 +163,50 @@ func (h *Holder) openAsk(r *Record) *AskRecord {
|
||||
return &rec
|
||||
}
|
||||
|
||||
// wholeOf is an ask's explanation with its values whole (asks.Ask.Whole), where an ask's own message on one
|
||||
// kind shows it in place of the explanation (novox/hq issue 383): on a kind that proves who answers by the
|
||||
// controller's fresh word (Promises, as every other verified-sender judgement here), and that the router gave
|
||||
// the ask's answers (a ticket there, so the kind was linked and root-free when the ask was taken). Empty where
|
||||
// the kind proves nothing, the ask has no whole words, or the record is a condition's — a condition's words
|
||||
// stay under the whole content rule, whatever an ask about it carries — then the explanation, held to that
|
||||
// rule, is shown. The ask's state does not matter: a message edited to say how the ask ended still shows what
|
||||
// was approved.
|
||||
func (h *Holder) wholeOf(r *Record, kind string) string {
|
||||
if a := h.provenAsk(r, kind); a != nil {
|
||||
return a.Whole
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// wholeDetailsOf is an ask's Details with their values whole (asks.Ask.WholeDetails), shown in the note in place of
|
||||
// its Details where wholeOf would show its whole words: every value an approval sets, so the operator reads exactly
|
||||
// what they approve (the review of mesh-controller #304). Empty elsewhere.
|
||||
func (h *Holder) wholeDetailsOf(r *Record, kind string) string {
|
||||
if a := h.provenAsk(r, kind); a != nil {
|
||||
return a.WholeDetails
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// provenAsk is the ask of an ask's own record when the kind proves who answers and was given the ask's answers;
|
||||
// nil otherwise.
|
||||
func (h *Holder) provenAsk(r *Record, kind string) *asks.Ask {
|
||||
if r == nil || r.Origin != "ask" || r.Ask == "" || kind == "" || h.Bench == nil {
|
||||
return nil
|
||||
}
|
||||
e := h.askOf(r.Ask)
|
||||
if e == nil || !h.Bench.Promises(kind, "verified-sender") {
|
||||
return nil
|
||||
}
|
||||
for _, tk := range e.rec.Tickets {
|
||||
if tk.Kind == kind {
|
||||
a := e.rec.Ask
|
||||
return &a
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// carriers are the kinds that can carry an answer of a level now: ready, offering a choice, and for
|
||||
// approve verifying their sender with an account of the operator's linked, where the controller says now
|
||||
// that no agent can become root (rootFree, asked live).
|
||||
@@ -439,6 +483,18 @@ func (h *Holder) TakeAsk(verb, asker string, body json.RawMessage) error {
|
||||
h.refuseAsk(asker, a, "its words carry "+refusal.String()+", which may not leave the mesh: move it into a reference or say it in words")
|
||||
return nil
|
||||
}
|
||||
// An ask that does not read at a glance is said, and shown all the same: the bound is its asker's to keep
|
||||
// (asks.Glance, issue 639), and refusing it would leave the operator unasked.
|
||||
if err := asks.Glance(a.Explanation); err != nil {
|
||||
h.Logf("[messenger] %s's ask %q is a wall of text on the phone: %v", asker, a.Headline, err)
|
||||
}
|
||||
// The whole words are shown only where the sender is proven (wholeOf), so a path or an address may stand
|
||||
// in them; a secret's shape leaves the mesh nowhere, and an ask carrying one is refused as a whole, never
|
||||
// shown with its explanation alone (novox/hq issue 383).
|
||||
if refusal, ok := CheckSecret(a.Whole + "\n" + a.WholeDetails); !ok {
|
||||
h.refuseAsk(asker, a, "its whole words carry "+refusal.String()+", which may not leave the mesh on any channel: withhold it")
|
||||
return nil
|
||||
}
|
||||
open, replaced := 0, ""
|
||||
h.mu.Lock()
|
||||
for k, e := range h.asks {
|
||||
@@ -1040,7 +1096,7 @@ func (h *Holder) showOnHandle(kind string, m Message) (string, error) {
|
||||
if h.Publish == nil {
|
||||
return "", errors.New("this router cannot reach the bus")
|
||||
}
|
||||
out := asks.Message{Handle: newHandle(), Title: m.Title, Body: m.Body, Urgent: m.Urgent, Silent: m.Quiet, Reply: m.Reply, To: m.To,
|
||||
out := asks.Message{Handle: newHandle(), Title: m.Title, Body: m.Body, Note: m.Note, Urgent: m.Urgent, Silent: m.Quiet, Reply: m.Reply, To: m.To,
|
||||
Secret: m.Secret}
|
||||
if out.To == "" && h.Bench != nil && h.Bench.To != nil {
|
||||
out.To = h.Bench.To(kind)
|
||||
@@ -1065,7 +1121,7 @@ func (h *Holder) showOn(kind string, m Message) error {
|
||||
if h.Publish == nil {
|
||||
return errors.New("this router cannot reach the bus")
|
||||
}
|
||||
out := asks.Message{Handle: newHandle(), Title: m.Title, Body: m.Body, Urgent: m.Urgent, Silent: m.Quiet, Reply: m.Reply}
|
||||
out := asks.Message{Handle: newHandle(), Title: m.Title, Body: m.Body, Note: m.Note, Urgent: m.Urgent, Silent: m.Quiet, Reply: m.Reply}
|
||||
if h.Bench != nil && h.Bench.To != nil {
|
||||
out.To = h.Bench.To(kind)
|
||||
}
|
||||
|
||||
@@ -65,6 +65,59 @@ func Check(text string) (Refusal, bool) {
|
||||
return Refusal{"address", "a hardware address"}, false
|
||||
case reIPv6.MatchString(text):
|
||||
return Refusal{"address", "an IPv6 address"}, false
|
||||
}
|
||||
if refusal, ok := secretShape(text); !ok {
|
||||
return refusal, false
|
||||
}
|
||||
if reWinPath.MatchString(text) {
|
||||
return Refusal{"path", "a drive path"}, false
|
||||
}
|
||||
if refusal, ok := randomRun(text); !ok {
|
||||
return refusal, false
|
||||
}
|
||||
for _, word := range strings.FieldsFunc(text, func(r rune) bool {
|
||||
return unicode.IsSpace(r) || strings.ContainsRune("\"'`()[]{}<>,;|", r)
|
||||
}) {
|
||||
w := strings.TrimRight(word, ".:!?")
|
||||
if isPath(w) {
|
||||
return Refusal{"path", "a file path"}, false
|
||||
}
|
||||
if isHostName(w) {
|
||||
return Refusal{"address", "a host name"}, false
|
||||
}
|
||||
}
|
||||
return Refusal{}, true
|
||||
}
|
||||
|
||||
// CheckSecret says whether a text carries a secret's shape — the one class that leaves the mesh nowhere. It is
|
||||
// what an ask's whole words (asks.Ask.Whole, novox/hq issue 383) are held to: on a kind that proves who answers,
|
||||
// a path or an address is what the operator approves and may be shown, a secret never. A path is read as one:
|
||||
// a run with a slash in it is judged piece by piece between the slashes, so "/mnt/Photos_2024/Jochen" is a
|
||||
// path and not a random string (the review of 2026-10-10); the named shapes — a key block, a signed token, a
|
||||
// bot token, a known token shape, a value given to a secret's name, a long hexadecimal string — hold whatever
|
||||
// the run holds.
|
||||
func CheckSecret(text string) (Refusal, bool) {
|
||||
if refusal, ok := secretShape(text); !ok {
|
||||
return refusal, false
|
||||
}
|
||||
return randomRunOutsidePaths(text)
|
||||
}
|
||||
|
||||
// randomRunOutsidePaths is randomRun with each run that holds a slash judged by its pieces between the slashes.
|
||||
func randomRunOutsidePaths(text string) (Refusal, bool) {
|
||||
for _, run := range reRun.FindAllString(text, -1) {
|
||||
for _, piece := range strings.Split(run, "/") {
|
||||
if len(piece) >= 20 && looksRandom(piece) {
|
||||
return Refusal{"secret", "a long random-looking string"}, false
|
||||
}
|
||||
}
|
||||
}
|
||||
return Refusal{}, true
|
||||
}
|
||||
|
||||
// secretShape is the secret shapes a pattern names.
|
||||
func secretShape(text string) (Refusal, bool) {
|
||||
switch {
|
||||
case rePEM.MatchString(text):
|
||||
return Refusal{"secret", "a key block"}, false
|
||||
case reJWT.MatchString(text):
|
||||
@@ -77,25 +130,17 @@ func Check(text string) (Refusal, bool) {
|
||||
return Refusal{"secret", "a value given to a secret's name"}, false
|
||||
case reHex.MatchString(text):
|
||||
return Refusal{"secret", "a long hexadecimal string"}, false
|
||||
case reWinPath.MatchString(text):
|
||||
return Refusal{"path", "a drive path"}, false
|
||||
}
|
||||
return Refusal{}, true
|
||||
}
|
||||
|
||||
// randomRun is a long unbroken run of characters spread as a random string's are.
|
||||
func randomRun(text string) (Refusal, bool) {
|
||||
for _, run := range reRun.FindAllString(text, -1) {
|
||||
if looksRandom(run) {
|
||||
return Refusal{"secret", "a long random-looking string"}, false
|
||||
}
|
||||
}
|
||||
for _, word := range strings.FieldsFunc(text, func(r rune) bool {
|
||||
return unicode.IsSpace(r) || strings.ContainsRune("\"'`()[]{}<>,;|", r)
|
||||
}) {
|
||||
w := strings.TrimRight(word, ".:!?")
|
||||
if isPath(w) {
|
||||
return Refusal{"path", "a file path"}, false
|
||||
}
|
||||
if isHostName(w) {
|
||||
return Refusal{"address", "a host name"}, false
|
||||
}
|
||||
}
|
||||
return Refusal{}, true
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ func TestAnApprovalIsConfirmedWhereItWasGivenAndThenTheQuestionSaysHowItEnded(t
|
||||
}
|
||||
want := []string{
|
||||
"send You chose Release: recorded, and mesh-delivery was told.",
|
||||
"edit You chose Release at 12:00 on Telegram · Delivery of hq held for 36 hours",
|
||||
"edit Delivery of hq held for 36 hours",
|
||||
}
|
||||
if strings.Join(log, "\n") != strings.Join(want, "\n") {
|
||||
t.Fatalf("the operator saw, in order:\n%s\nwant:\n%s", strings.Join(log, "\n"), strings.Join(want, "\n"))
|
||||
@@ -122,8 +122,8 @@ func TestTheConfirmationNeverClaimsWhatDidNotHappen(t *testing.T) {
|
||||
for _, m := range tg.edits {
|
||||
edited = m
|
||||
}
|
||||
if !strings.HasPrefix(edited.Body, "Told to mesh-delivery as soon as the bus takes it") {
|
||||
t.Errorf("the question claims its asker was told: %q", edited.Body)
|
||||
if !strings.Contains(edited.Note, "\nTold to mesh-delivery as soon as the bus takes it") {
|
||||
t.Errorf("the question claims its asker was told: %q", edited.Note)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/asks"
|
||||
)
|
||||
|
||||
// novox/hq issue 639: an ask's message reads at a glance on the phone. Its body is the asker's summary and points
|
||||
// alone; who asked and when, what each answer does, the expiry and the asker's Details are its note. Once answered
|
||||
// it keeps the question whole, so the operator can read back what they answered (issue 714).
|
||||
|
||||
// decisionAsk is the ask for ADR 0343 as the knowledge base composes it now (its glance form).
|
||||
func decisionAsk(c *clock) asks.Ask {
|
||||
return asks.Ask{ID: "kb-decision-343-0d1e2f3a", Headline: "Your agents' memory follows you to every machine",
|
||||
Explanation: "What an agent learns in a project's memory is copied to every machine that runs the agent, so a session " +
|
||||
"anywhere starts with it. A file changed on two machines keeps both versions and warns you; secrets in memory files " +
|
||||
"are screened, though not perfectly.\n" +
|
||||
"• Only memory folders travel: links and files over 128 KiB stay where they are\n" +
|
||||
"• A conflict reaches you as a warning that needs you\n" +
|
||||
"• A deleted file is marked, and a newer change elsewhere outlives the deletion",
|
||||
Who: asks.Operator, Expires: c.now().Add(23*time.Hour + 50*time.Minute), OnExpiry: "the record stays proposed; nothing of it is in force",
|
||||
About: "knowledge.decision.343",
|
||||
Details: "ADR 0343, proposed by fix-367@g14; the knowledge base's own review approved it. Fingerprint a59f 361b f60e cb5e d237 a837.\n" +
|
||||
"Read its 13 clauses with the knowledge base's get, number 343.",
|
||||
Options: []asks.Option{
|
||||
{ID: "approve", Label: "Approve", Does: "the record is accepted and its clauses are in force", Level: asks.Approve, Binds: bound("approve")},
|
||||
{ID: "decline", Label: "Decline", Does: "the record stays proposed; nothing of it is in force", Level: asks.Approve, Binds: bound("decline")},
|
||||
}}
|
||||
}
|
||||
|
||||
func TestAnAsksMessageIsItsSummaryWithTheRestInItsNote(t *testing.T) {
|
||||
h, tg, _, c, store, _ := newRouter(t)
|
||||
link(h, store, c, "42", c.now().Add(-2*time.Hour))
|
||||
a := decisionAsk(c)
|
||||
submit(t, h, "mesh-knowledge", a)
|
||||
settle(h, c)
|
||||
if len(tg.sends) != 1 {
|
||||
t.Fatalf("telegram got %d messages", len(tg.sends))
|
||||
}
|
||||
m := tg.sends[0]
|
||||
if m.Title != a.Headline || m.Body != a.Explanation {
|
||||
t.Errorf("the body is not the asker's summary and points alone:\n%s\n%s", m.Title, m.Body)
|
||||
}
|
||||
note := strings.Split(m.Note, "\n")
|
||||
asked := c.now().In(time.UTC).Format("15:04")
|
||||
want := []string{
|
||||
"Asked by mesh-knowledge at " + asked + ". Unanswered by tomorrow " + a.Expires.In(time.UTC).Format("15:04") +
|
||||
": the record stays proposed; nothing of it is in force.",
|
||||
"Approve: the record is accepted and its clauses are in force. Decline: the record stays proposed; nothing of it is in force.",
|
||||
"ADR 0343, proposed by fix-367@g14; the knowledge base's own review approved it. Fingerprint a59f 361b f60e cb5e d237 a837.",
|
||||
"Read its 13 clauses with the knowledge base's get, number 343.",
|
||||
}
|
||||
if strings.Join(note, "\n") != strings.Join(want, "\n") {
|
||||
t.Errorf("the note:\n%s\nwant:\n%s", m.Note, strings.Join(want, "\n"))
|
||||
}
|
||||
if n := len(strings.Split(m.Text(), "\n")); n > 9 || len(m.Actions) != 2 {
|
||||
t.Errorf("the message is %d lines offering %s:\n%s", n, labelsOf(m), m.Text())
|
||||
}
|
||||
// Answered, it keeps its headline, summary, points and Details; below them, how it ended and who acts on it;
|
||||
// its buttons are gone (issue 714: the one line issue 639 made left nothing to read back).
|
||||
if out, err := h.Chosen("telegram", choiceOf(ticketFor(m, "Approve"), "42", c.now())); err != nil || out != "chosen" {
|
||||
t.Fatalf("Approve: %q %v", out, err)
|
||||
}
|
||||
var edited Message
|
||||
for _, e := range tg.edits {
|
||||
edited = e
|
||||
}
|
||||
if edited.Title != a.Headline || edited.Body != a.Explanation+"\n"+want[2]+"\n"+want[3] ||
|
||||
edited.Note != "You chose Approve at "+asked+" on Telegram.\nTold to mesh-knowledge, which acts on it itself." ||
|
||||
len(edited.Actions) != 0 {
|
||||
t.Errorf("the answered copy: %q\n%q\n%q", edited.Title, edited.Body, edited.Note)
|
||||
}
|
||||
}
|
||||
|
||||
// An ask that does not read at a glance is shown all the same, and said: refusing it would leave the operator
|
||||
// unasked, and the bound is its asker's to keep.
|
||||
func TestAnAskThatIsAWallOfTextIsShownAndSaid(t *testing.T) {
|
||||
h, tg, _, c, store, _ := newRouter(t)
|
||||
link(h, store, c, "42", c.now().Add(-2*time.Hour))
|
||||
var said []string
|
||||
h.Logf = func(f string, a ...any) { said = append(said, f) }
|
||||
a := decisionAsk(c)
|
||||
a.Explanation += "\nA fourth point\nA fifth point"
|
||||
submit(t, h, "mesh-knowledge", a)
|
||||
settle(h, c)
|
||||
if len(tg.sends) != 1 || !strings.Contains(strings.Join(said, "\n"), "is a wall of text on the phone") {
|
||||
t.Errorf("sent %d, said %v", len(tg.sends), said)
|
||||
}
|
||||
}
|
||||
@@ -90,8 +90,11 @@ const (
|
||||
|
||||
// Message is what a channel shows: a title line and a body, and the answers it offers.
|
||||
type Message struct {
|
||||
Title string
|
||||
Body string
|
||||
Title string
|
||||
Body string
|
||||
// Note is the secondary words, after the body and the answers: who asked, what each answer does, the
|
||||
// expiry, the asker's Details (asks.Message.Note, issue 639).
|
||||
Note string
|
||||
Urgent bool
|
||||
Quiet bool // a clearing: shown without urgency
|
||||
Actions []Choice
|
||||
@@ -111,10 +114,13 @@ type Choice struct {
|
||||
}
|
||||
|
||||
func (m Message) Text() string {
|
||||
if m.Body == "" {
|
||||
return m.Title
|
||||
t := m.Title
|
||||
for _, more := range []string{m.Body, m.Note} {
|
||||
if more != "" {
|
||||
t += "\n" + more
|
||||
}
|
||||
}
|
||||
return m.Title + "\n" + m.Body
|
||||
return t
|
||||
}
|
||||
|
||||
// Channel is one way to the operator.
|
||||
@@ -839,19 +845,31 @@ func (h *Holder) sayOn(r *Record, what, kind string) Message {
|
||||
if what == "cleared" || what == "silenced" || m.Title == "A mesh message was withheld" {
|
||||
return m
|
||||
}
|
||||
// On a kind that proves who answers, an ask's explanation is shown with its values whole (issue 383): the
|
||||
// path or the address the operator approves is readable there; a secret's shape still is not.
|
||||
whole := h.wholeOf(r, kind)
|
||||
if whole != "" {
|
||||
if wm, ok := h.wholeWords(r, what, whole); ok {
|
||||
m = wm
|
||||
} else {
|
||||
whole = ""
|
||||
}
|
||||
}
|
||||
if r.Answered != "" {
|
||||
m = h.answeredWords(r, m)
|
||||
m = h.answeredWords(r, m, kind)
|
||||
}
|
||||
if kind == "" {
|
||||
return m
|
||||
}
|
||||
withheld := map[string]bool{} // the labels of answers whose effect could not be said
|
||||
if rec := h.openAsk(r); rec != nil {
|
||||
// Who asks, as the bus proves it (the asker is the subject's, never the body's), what each answer does,
|
||||
// and what happens if nobody answers (the review of 2026-10-09).
|
||||
for _, line := range h.askLines(rec) {
|
||||
// The note (issue 639): who asks, as the bus proves it (the asker is the subject's, never the body's), what
|
||||
// each answer does, what happens if nobody answers (the review of 2026-10-09), where else it is answered,
|
||||
// and the asker's Details. The body stays the asker's summary and points, read at a glance.
|
||||
var note []string
|
||||
for _, line := range h.askLines(rec, r) {
|
||||
if _, ok := Check(line); ok {
|
||||
m.Body = strings.TrimSpace(m.Body + "\n" + line)
|
||||
note = append(note, line)
|
||||
}
|
||||
}
|
||||
// **An answer whose effect is not said is not offered** (the confirmation review of 2026-10-09): its line
|
||||
@@ -864,9 +882,25 @@ func (h *Holder) sayOn(r *Record, what, kind string) Message {
|
||||
}
|
||||
if line := h.elsewhere(rec, kind); line != "" {
|
||||
if _, ok := Check(line); ok {
|
||||
m.Body = strings.TrimSpace(m.Body + "\n" + line)
|
||||
note = append(note, line)
|
||||
}
|
||||
}
|
||||
// On a kind that proves who answers, the Details whole (issue 383): every value an approval sets, held to
|
||||
// the secret rule alone, as the whole words are.
|
||||
details, passes := rec.Ask.Details, Check
|
||||
if wd := h.wholeDetailsOf(r, kind); wd != "" {
|
||||
details, passes = wd, CheckSecret
|
||||
}
|
||||
for _, line := range strings.Split(strings.TrimSpace(details), "\n") {
|
||||
if line = strings.TrimSpace(line); line == "" {
|
||||
continue
|
||||
}
|
||||
if refusal, ok := passes(line); !ok {
|
||||
line = withheldLine(line, refusal, passes)
|
||||
}
|
||||
note = append(note, line)
|
||||
}
|
||||
m.Note = strings.Join(note, "\n")
|
||||
}
|
||||
for _, c := range h.choices(r, kind) {
|
||||
if !withheld[c.Label] {
|
||||
@@ -876,39 +910,92 @@ func (h *Holder) sayOn(r *Record, what, kind string) Message {
|
||||
return m
|
||||
}
|
||||
|
||||
// answeredWords is a message that says what came of its question. An ask's own message is the question
|
||||
// itself, so its title becomes how it ended — "You chose Approve at 13:30 on Telegram · <headline>" — read at
|
||||
// a glance on the phone, where the edit rings nothing (issue 372); the rest of what came of it, the
|
||||
// explanation and when it was asked follow. A condition's message keeps its own title, and says it first.
|
||||
func (h *Holder) answeredWords(r *Record, m Message) Message {
|
||||
// answeredWords is a message that says what came of its question. An ask's own message keeps the question
|
||||
// whole — its headline as the title, the asker's summary, points and link as the body, its Details after them —
|
||||
// so the operator can read back what they answered (issue 714, which undid issue 639's one line). How it ended
|
||||
// ("You chose Approve at 13:30 on Telegram.") and what the router knows of the asker after it are the note,
|
||||
// below the question, and its answers are gone (issue 372). A channel that must shorten it cuts the body from
|
||||
// its end, the Details first; never the headline or the note. A condition's message keeps its own title, and
|
||||
// says how it ended first.
|
||||
func (h *Holder) answeredWords(r *Record, m Message, kind string) Message {
|
||||
if r.Origin == "ask" {
|
||||
first, rest, _ := strings.Cut(r.Answered, "\n")
|
||||
headline, explanation := wordsOf(r)
|
||||
out := Message{Title: strings.TrimSuffix(first, ".") + " · " + headline, Urgent: m.Urgent, Quiet: m.Quiet,
|
||||
Body: strings.TrimSpace(rest + "\n" + explanation + "\nAsked " + when(r.Raised, h.Now(), h.zone()) + ".")}
|
||||
if _, ok := Check(out.Text()); ok {
|
||||
headline, _ := wordsOf(r)
|
||||
body := []string{}
|
||||
if b := strings.TrimSpace(m.Body); b != "" {
|
||||
body = append(body, b)
|
||||
}
|
||||
body = append(body, h.answeredDetails(r, kind)...)
|
||||
out := Message{Title: headline, Body: strings.Join(body, "\n"), Note: strings.TrimSpace(r.Answered),
|
||||
Urgent: m.Urgent, Quiet: m.Quiet}
|
||||
if _, ok := Check(out.Title + "\n" + out.Note); ok {
|
||||
return out
|
||||
}
|
||||
// Its words refused (they are the asker's): the outcome is still said, before what may leave.
|
||||
// Its headline refused (it is the asker's): the outcome is still said, before what may leave.
|
||||
}
|
||||
m.Body = strings.TrimSpace(r.Answered + "\n" + m.Body)
|
||||
return m
|
||||
}
|
||||
|
||||
// askLines are what an ask's message says of the ask itself: who asks, each option's effect, and its expiry.
|
||||
func (h *Holder) askLines(rec *AskRecord) []string {
|
||||
// answeredDetails are an answered ask's Details, line by line, as its open message noted them (issue 714): whole
|
||||
// on a kind that proves who answers, a line that may not leave withheld and said so.
|
||||
func (h *Holder) answeredDetails(r *Record, kind string) []string {
|
||||
if r.Ask == "" {
|
||||
return nil
|
||||
}
|
||||
e := h.askOf(r.Ask)
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
details, passes := e.rec.Ask.Details, Check
|
||||
if wd := h.wholeDetailsOf(r, kind); wd != "" {
|
||||
details, passes = wd, CheckSecret
|
||||
}
|
||||
var lines []string
|
||||
for _, line := range strings.Split(strings.TrimSpace(details), "\n") {
|
||||
if line = strings.TrimSpace(line); line == "" {
|
||||
continue
|
||||
}
|
||||
if refusal, ok := passes(line); !ok {
|
||||
line = withheldLine(line, refusal, passes)
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// wholeWords is a record's message with the ask's whole words in place of its explanation, when they carry no
|
||||
// secret's shape once composed; else false, and the message under the whole content rule stands.
|
||||
func (h *Holder) wholeWords(r *Record, what, whole string) (Message, bool) {
|
||||
c := *r
|
||||
c.Explanation = whole
|
||||
m := compose(&c, what, h.Now(), h.zone(), 0)
|
||||
if refusal, ok := CheckSecret(m.Text()); !ok {
|
||||
h.Logf("[messenger] the whole words of %s carry %s; shown as on a channel that proves nothing", r.Key, refusal)
|
||||
return Message{}, false
|
||||
}
|
||||
return m, true
|
||||
}
|
||||
|
||||
// askLines are what an ask's message notes of the ask itself, in two lines: who asks and when, with what happens
|
||||
// if nobody answers; then each option's effect.
|
||||
func (h *Holder) askLines(rec *AskRecord, r *Record) []string {
|
||||
asker := rec.Asker
|
||||
if asker == SelfAsker {
|
||||
asker = "the router itself"
|
||||
}
|
||||
lines := []string{"Asked by " + asker + "."}
|
||||
first := "Asked by " + asker + " at " + when(r.Raised, h.Now(), h.zone()) + "."
|
||||
if !rec.Ask.Expires.IsZero() && rec.Ask.OnExpiry != "" {
|
||||
first += " Unanswered by " + by(rec.Ask.Expires, h.Now(), h.zone()) + ": " + strings.TrimSuffix(rec.Ask.OnExpiry, ".") + "."
|
||||
}
|
||||
lines := []string{first}
|
||||
var does []string
|
||||
for _, o := range rec.Ask.Options {
|
||||
if o.Does != "" {
|
||||
lines = append(lines, o.Label+": "+o.Does+".")
|
||||
does = append(does, o.Label+": "+strings.TrimSuffix(o.Does, ".")+".")
|
||||
}
|
||||
}
|
||||
if !rec.Ask.Expires.IsZero() && rec.Ask.OnExpiry != "" {
|
||||
lines = append(lines, "If nobody answers by "+by(rec.Ask.Expires, h.Now(), h.zone())+": "+rec.Ask.OnExpiry+".")
|
||||
if len(does) > 0 {
|
||||
lines = append(lines, strings.Join(does, " "))
|
||||
}
|
||||
return lines
|
||||
}
|
||||
@@ -1092,3 +1179,20 @@ func roughly(d time.Duration) string {
|
||||
}
|
||||
return fmt.Sprintf("%d days", int(d.Hours()/24))
|
||||
}
|
||||
|
||||
// withheldLine is a note line the rule refused, said withheld: a change's line ("+ key: value") keeps its key's name,
|
||||
// so the operator knows which setting holds a value they are not shown (the review of mesh-controller #304); any
|
||||
// other line, or one whose key the rule refuses too, is said withheld whole.
|
||||
func withheldLine(line string, refusal Refusal, passes func(string) (Refusal, bool)) string {
|
||||
if len(line) > 2 && strings.ContainsRune("+~-=", rune(line[0])) && line[1] == ' ' {
|
||||
key := line[2:]
|
||||
if i := strings.IndexAny(key, ": "); i > 0 {
|
||||
key = key[:i]
|
||||
}
|
||||
named := line[:2] + key + " (a value carrying " + refusal.What + " is withheld here)"
|
||||
if _, ok := passes(named); ok {
|
||||
return named
|
||||
}
|
||||
}
|
||||
return "(a line carrying " + refusal.What + " is withheld here)"
|
||||
}
|
||||
|
||||
@@ -158,8 +158,8 @@ func TestAnAsksExpiryIsSaidWithItsDay(t *testing.T) {
|
||||
rec := &AskRecord{Asker: ConditionOwner}
|
||||
rec.Ask.Expires = now.Add(7 * 24 * time.Hour)
|
||||
rec.Ask.OnExpiry = "nothing is done"
|
||||
lines := strings.Join(h.askLines(rec), "\n")
|
||||
if !strings.Contains(lines, "If nobody answers by Fri 16 Oct 21:33: nothing is done.") {
|
||||
lines := strings.Join(h.askLines(rec, &Record{Raised: now}), "\n")
|
||||
if !strings.Contains(lines, "Unanswered by Fri 16 Oct 21:33: nothing is done.") {
|
||||
t.Fatalf("%s", lines)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ func (h *Holder) Preview(key, what string) (map[string]any, error) {
|
||||
asking := h.openAsk(&r) != nil // askOf takes the same lock, so this is asked outside it
|
||||
m, line, refusal, ownWords := h.allowedWords(&r, what, now)
|
||||
if r.Answered != "" {
|
||||
m = h.answeredWords(&r, m)
|
||||
m = h.answeredWords(&r, m, "")
|
||||
}
|
||||
out := map[string]any{
|
||||
"key": key,
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestAReplacedAsksMessageEndsWithIt(t *testing.T) {
|
||||
m, edited = r.m, true
|
||||
}
|
||||
}
|
||||
if !edited || len(m.Actions) != 0 || !strings.Contains(m.Title, "Replaced by a newer question") {
|
||||
if !edited || len(m.Actions) != 0 || !strings.HasPrefix(m.Note, "Replaced by a newer question") {
|
||||
t.Errorf("%s: the replaced ask's message still stands: edited %v, %q %v", ch.name, edited, m.Text(), labelsOf(m))
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,7 @@ func TestAnAsksMessageLeftOpenAfterItsAskEndedIsEndedOnTheNextTick(t *testing.T)
|
||||
if got := openAskRecords(h); len(got) != 0 {
|
||||
t.Fatalf("the message of an ended ask is still open: %v", got)
|
||||
}
|
||||
if m, ok := tg.edits["1"]; !ok || len(m.Actions) != 0 || !strings.Contains(m.Title, "Replaced by a newer question") {
|
||||
if m, ok := tg.edits["1"]; !ok || len(m.Actions) != 0 || !strings.HasPrefix(m.Note, "Replaced by a newer question") {
|
||||
t.Errorf("the leftover's copy was not ended: %v %q %v", ok, m.Text(), labelsOf(m))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,11 +208,12 @@ func TestAnAsksMessageSaysWhoAsksWhatEachAnswerDoesAndWhatExpiryDoes(t *testing.
|
||||
link(h, store, c, "42", c.now().Add(-2*time.Hour))
|
||||
submit(t, h, "mesh-delivery", heldAsk(c, "d-1"))
|
||||
settle(h, c)
|
||||
body := tg.sends[0].Body
|
||||
for _, want := range []string{"Asked by mesh-delivery.", "Release: the delivery goes on.", "Stop: the delivery ends.",
|
||||
// In the note, after the body and the buttons (issue 639): the body is the asker's own words alone.
|
||||
body := tg.sends[0].Note
|
||||
for _, want := range []string{"Asked by mesh-delivery at ", "Release: the delivery goes on. Stop: the delivery ends.",
|
||||
"Silence for a week: nothing more is said of it for a week.",
|
||||
"If nobody answers by " + c.now().Add(2*time.Hour-BurstWindow).In(time.UTC).Format("15:04") + ": the delivery stays held."} {
|
||||
if !strings.Contains(body, want) {
|
||||
"Unanswered by " + c.now().Add(2*time.Hour-BurstWindow).In(time.UTC).Format("15:04") + ": the delivery stays held."} {
|
||||
if !strings.Contains(body, want) || strings.Contains(tg.sends[0].Body, want) {
|
||||
t.Errorf("the message does not say %q:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,7 +286,7 @@ func (c *SeatChannel) putOn(kind, handle string, m Message, edit bool) error {
|
||||
}
|
||||
// Secret travels whatever the path: a link's code is kept by no channel (the review of 2026-10-09 found it
|
||||
// dropped here, where the desk's own role sends).
|
||||
out := asks.Message{Handle: handle, Title: m.Title, Body: m.Body, Urgent: m.Urgent, Silent: m.Quiet, Reply: m.Reply,
|
||||
out := asks.Message{Handle: handle, Title: m.Title, Body: m.Body, Note: m.Note, Urgent: m.Urgent, Silent: m.Quiet, Reply: m.Reply,
|
||||
Secret: m.Secret}
|
||||
if c.Bench.To != nil {
|
||||
out.To = c.Bench.To(kind)
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/asks"
|
||||
)
|
||||
|
||||
// novox/hq issue 383: a settings proposal's values are what the operator approves, so where the sender is proven
|
||||
// they are shown whole; where nothing is proven, the explanation under the whole content rule stands.
|
||||
|
||||
// proposalAsk is a proposal as the controller composes it: the explanation with its values masked, the whole
|
||||
// with them whole, and Details with the fingerprint and where to read it, which the note shows.
|
||||
func proposalAsk(c *clock, id string) asks.Ask {
|
||||
a := heldAsk(c, id)
|
||||
a.Headline = "Set mounts on shanks?"
|
||||
a.Options = a.Options[:2]
|
||||
a.Explanation = "+ shares: media=‹path›\n+ sources: recalbox=‹address›@‹path›\nProposed by an agent at 15:11."
|
||||
a.Whole = "+ shares: media=/storage/media\n+ sources: recalbox=smb://nas.lan/recalbox@/mnt/recalbox\nProposed by an agent at 15:11."
|
||||
a.Details = "Fingerprint 1234 5678 9abc def0 1234 5678.\nRead it whole: settings proposals " + id + " at the controller's terminal."
|
||||
return a
|
||||
}
|
||||
|
||||
func TestAnAsksWholeWordsAreShownWhereTheSenderIsProvenAndMaskedElsewhere(t *testing.T) {
|
||||
h, tg, _, c, store, w := newRouter(t)
|
||||
link(h, store, c, "42", c.now().Add(-2*time.Hour))
|
||||
submit(t, h, "mesh-controller", proposalAsk(c, "s-1"))
|
||||
settle(h, c)
|
||||
if len(tg.sends) != 1 {
|
||||
t.Fatalf("telegram got %d messages", len(tg.sends))
|
||||
}
|
||||
phone := tg.sends[0]
|
||||
for _, want := range []string{"+ shares: media=/storage/media", "recalbox=smb://nas.lan/recalbox@/mnt/recalbox", "Proposed by an agent at 15:11."} {
|
||||
if !strings.Contains(phone.Body, want) {
|
||||
t.Errorf("the phone, which proves who answers, lacks %q:\n%s", want, phone.Body)
|
||||
}
|
||||
}
|
||||
if strings.Contains(phone.Body, "‹") || strings.Contains(phone.Body, "Fingerprint") || strings.Contains(phone.Body, "settings proposals") {
|
||||
t.Errorf("the phone shows a masked value, or the Details' words, in the body:\n%s", phone.Body)
|
||||
}
|
||||
// The Details are the note's, after what the answers do (issue 639): no answer of their own.
|
||||
if !strings.Contains(phone.Note, "Fingerprint 1234 5678 9abc def0 1234 5678.") ||
|
||||
!strings.Contains(phone.Note, "Read it whole: settings proposals s-1 at the controller's terminal.") {
|
||||
t.Errorf("the phone's note lacks the Details:\n%s", phone.Note)
|
||||
}
|
||||
if phone.Title != "Set mounts on shanks?" || ticketFor(phone, "Release") == "" || ticketFor(phone, DetailsLabel) != "" {
|
||||
t.Errorf("the phone's message: %q offering %s", phone.Title, labelsOf(phone))
|
||||
}
|
||||
// The desk proves nothing: the same record composed for it shows the explanation, its values masked.
|
||||
r := h.open["ask.mesh-controller.s-1"]
|
||||
if r == nil {
|
||||
t.Fatal("no record of the ask")
|
||||
}
|
||||
desk := h.sayOn(r, "raised", "desktop")
|
||||
if !strings.Contains(desk.Body, "+ shares: media=‹path›") || strings.Contains(desk.Text(), "/storage/media") || strings.Contains(desk.Text(), "nas.lan") {
|
||||
t.Errorf("the desk shows a value whole:\n%s", desk.Text())
|
||||
}
|
||||
if got := w.of("mesh-controller"); len(got) != 0 || store.asks["mesh-controller.s-1"].State != StateOpen {
|
||||
t.Errorf("the ask was answered: %+v / %s", got, store.asks["mesh-controller.s-1"].State)
|
||||
}
|
||||
// Approved, the message keeps its headline and words, and says below them how it ended (issue 714).
|
||||
if out, err := h.Chosen("telegram", choiceOf(ticketFor(phone, "Release"), "42", c.now())); err != nil || out != "chosen" {
|
||||
t.Fatalf("Release: %q %v", out, err)
|
||||
}
|
||||
edited, ok := tg.edits["1"]
|
||||
if !ok {
|
||||
t.Fatalf("the phone's message was not edited: %+v", tg.edits)
|
||||
}
|
||||
if edited.Title != "Set mounts on shanks?" || edited.Body == "" ||
|
||||
!strings.HasPrefix(edited.Note, "You chose Release at ") || len(edited.Actions) != 0 {
|
||||
t.Errorf("the edited message: %q\n%s\nactions %+v", edited.Title, edited.Body, edited.Actions)
|
||||
}
|
||||
}
|
||||
|
||||
// The mutation on the switch: the same ask without whole words is shown on the phone as on the desk, from its
|
||||
// explanation; the whole words alone make the difference, and only where the sender is proven.
|
||||
func TestAnAskWithoutWholeWordsIsShownFromItsExplanationEverywhere(t *testing.T) {
|
||||
h, tg, _, c, store, _ := newRouter(t)
|
||||
link(h, store, c, "42", c.now().Add(-2*time.Hour))
|
||||
a := proposalAsk(c, "s-2")
|
||||
a.Whole, a.Details = "", ""
|
||||
submit(t, h, "mesh-controller", a)
|
||||
settle(h, c)
|
||||
if len(tg.sends) != 1 || !strings.Contains(tg.sends[0].Body, "+ shares: media=‹path›") || strings.Contains(tg.sends[0].Body, "/storage/media") {
|
||||
t.Fatalf("telegram: %+v", tg.sends)
|
||||
}
|
||||
if ticketFor(tg.sends[0], DetailsLabel) != "" || strings.Contains(tg.sends[0].Note, "Fingerprint") {
|
||||
t.Errorf("an ask that says nothing for Details offers or notes it: %s\n%s", labelsOf(tg.sends[0]), tg.sends[0].Note)
|
||||
}
|
||||
// A kind that proves nothing never shows the whole words, whatever the ask says.
|
||||
a = proposalAsk(c, "s-3")
|
||||
submit(t, h, "mesh-controller", a)
|
||||
settle(h, c)
|
||||
if whole := h.wholeOf(h.open["ask.mesh-controller.s-3"], "desktop"); whole != "" {
|
||||
t.Errorf("the desk is given the whole words: %q", whole)
|
||||
}
|
||||
if whole := h.wholeOf(h.open["ask.mesh-controller.s-3"], "telegram"); whole != a.Whole {
|
||||
t.Errorf("the phone is not given the whole words: %q", whole)
|
||||
}
|
||||
}
|
||||
|
||||
// A secret's shape leaves the mesh nowhere: an ask whose whole words carry one is refused as a whole, so the
|
||||
// phone never sees it, with or without the proven sender.
|
||||
func TestAnAskWhoseWholeWordsCarryASecretIsRefused(t *testing.T) {
|
||||
// A path is read as a path, whatever its case and digits; a random run outside one is still a secret.
|
||||
for text, may := range map[string]bool{
|
||||
"+ shares: photos=/mnt/Photos_2024/Jochen": true,
|
||||
"+ sources: games=smb://nas.lan/Recalbox_Games2024": true,
|
||||
"+ library: /srv/media/Series_Archive/Season01": true,
|
||||
"+ key: xK9mQ2vL8pR4tW7yB3nF6hJ1dG5sA0zC": false,
|
||||
} {
|
||||
if _, ok := CheckSecret(text); ok != may {
|
||||
t.Errorf("CheckSecret(%q) lets it leave: %v", text, ok)
|
||||
}
|
||||
}
|
||||
// A condition's record never shows an ask's whole words, whichever kind: its words are its own.
|
||||
{
|
||||
h, _, _, c, store, _ := newRouter(t)
|
||||
link(h, store, c, "42", c.now().Add(-2*time.Hour))
|
||||
k := cond("delivery.hq.held", Warning, "the delivery of hq is held")
|
||||
k.Raised = c.now()
|
||||
h.Condition(EventRaised, k)
|
||||
settle(h, c)
|
||||
a := proposalAsk(c, "s-5")
|
||||
a.About = "delivery.hq.held"
|
||||
submit(t, h, "mesh-controller", a)
|
||||
settle(h, c)
|
||||
if r := h.open["delivery.hq.held"]; r == nil || r.Ask != "mesh-controller.s-5" || h.wholeOf(r, "telegram") != "" {
|
||||
t.Errorf("a condition's record is given an ask's whole words")
|
||||
}
|
||||
}
|
||||
for _, secret := range []string{
|
||||
"+ token: ghp_abcdefghijklmnopqrstuvwxyz0123456789",
|
||||
"+ password=hunter2",
|
||||
"+ key: 0123456789abcdef0123456789abcdef",
|
||||
"-----BEGIN PRIVATE KEY-----",
|
||||
} {
|
||||
h, tg, _, c, store, w := newRouter(t)
|
||||
link(h, store, c, "42", c.now().Add(-2*time.Hour))
|
||||
a := proposalAsk(c, "s-4")
|
||||
a.Whole = "+ shares: media=/storage/media\n" + secret
|
||||
submit(t, h, "mesh-controller", a)
|
||||
settle(h, c)
|
||||
got := w.of("mesh-controller")
|
||||
if len(tg.sends) != 0 || len(got) != 1 || got[0].Outcome != asks.OutcomeRefused || !strings.Contains(got[0].Words, "whole words carry secret") {
|
||||
t.Errorf("%q: sent %d, told %+v", secret, len(tg.sends), got)
|
||||
}
|
||||
if _, kept := store.asks["mesh-controller.s-4"]; kept {
|
||||
t.Errorf("%q: the refused ask was recorded", secret)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The review of mesh-controller #304: a proposal of five keys, one of them 300 characters long, shows two keys at
|
||||
// a glance; every key and every value, whole, is in the note on a kind that proves who answers, so the operator can
|
||||
// read exactly what Approve sets. The desk, which proves nothing, shows them masked.
|
||||
func TestEveryKeyAndItsWholeValueIsInTheNoteWhereTheSenderIsProven(t *testing.T) {
|
||||
h, tg, _, c, store, _ := newRouter(t)
|
||||
link(h, store, c, "42", c.now().Add(-2*time.Hour))
|
||||
var long strings.Builder
|
||||
long.WriteString("library=/storage")
|
||||
for i := 0; long.Len() < 300; i++ {
|
||||
long.WriteString(fmt.Sprintf("/album-%02d", i))
|
||||
}
|
||||
value := long.String()[:300]
|
||||
keys := map[string]string{"a": "1", "b": "2", "c": "3", "d": "4", "shares": value}
|
||||
masked := map[string]string{"a": "1", "b": "2", "c": "3", "d": "4", "shares": "library=‹path›"}
|
||||
lines := func(values map[string]string) string {
|
||||
var out []string
|
||||
for _, k := range []string{"a", "b", "c", "d", "shares"} {
|
||||
out = append(out, "+ "+k+": "+values[k])
|
||||
}
|
||||
return strings.Join(out, "\n")
|
||||
}
|
||||
a := proposalAsk(c, "s-9")
|
||||
a.Explanation = "Changes 5 setting(s) of mounts on shanks.\n+ a: 1\n+ b: 2\nand 3 more, each whole below: c, d, shares"
|
||||
a.Whole = ""
|
||||
a.Details = "Fingerprint 1234 5678 9abc def0 1234 5678.\n" + lines(masked)
|
||||
a.WholeDetails = "Fingerprint 1234 5678 9abc def0 1234 5678.\n" + lines(keys)
|
||||
submit(t, h, "mesh-controller", a)
|
||||
settle(h, c)
|
||||
if len(tg.sends) != 1 {
|
||||
t.Fatalf("telegram got %d messages", len(tg.sends))
|
||||
}
|
||||
phone := tg.sends[0]
|
||||
for k, v := range keys {
|
||||
if !strings.Contains(phone.Note, "+ "+k+": "+v) {
|
||||
t.Errorf("the phone's note lacks %s whole:\n%s", k, phone.Note)
|
||||
}
|
||||
}
|
||||
if strings.Contains(phone.Body, "/storage") || strings.Count(phone.Body, "\n") > 3 {
|
||||
t.Errorf("the body is not the glance:\n%s", phone.Body)
|
||||
}
|
||||
desk := h.sayOn(h.open["ask.mesh-controller.s-9"], "raised", "desktop")
|
||||
if strings.Contains(desk.Text(), "/storage") || !strings.Contains(desk.Note, "+ shares: library=‹path›") {
|
||||
t.Errorf("the desk shows a value whole, or not every key:\n%s", desk.Note)
|
||||
}
|
||||
// A secret's shape in the whole details refuses the ask as a whole.
|
||||
b := proposalAsk(c, "s-10")
|
||||
b.WholeDetails = "+ token: ghp_abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
submit(t, h, "mesh-controller", b)
|
||||
settle(h, c)
|
||||
if _, kept := store.asks["mesh-controller.s-10"]; kept || len(tg.sends) != 1 {
|
||||
t.Errorf("an ask whose whole details carry a secret was taken")
|
||||
}
|
||||
}
|
||||
|
||||
// A change's line the rule refuses keeps its key's name in the note (the review of mesh-controller #304): the
|
||||
// operator knows which setting holds a value they are not shown. A line whose key the rule refuses too is said
|
||||
// withheld whole.
|
||||
func TestAWithheldChangeLineKeepsItsKey(t *testing.T) {
|
||||
for line, want := range map[string]string{
|
||||
"+ password: hunter2": "+ password (a value carrying a value given to a secret's name is withheld here)",
|
||||
"~ shares: /mnt/media (was: x)": "~ shares (a value carrying a file path is withheld here)",
|
||||
"Read it at /etc/x": "(a line carrying a file path is withheld here)",
|
||||
"+ ghp_abcdefghijklmnopqrstuvwxyz0123456789: 1": "(a line carrying ",
|
||||
} {
|
||||
refusal, ok := Check(line)
|
||||
if ok {
|
||||
t.Fatalf("%q passes the content rule", line)
|
||||
}
|
||||
if got := withheldLine(line, refusal, Check); !strings.HasPrefix(got, want) {
|
||||
t.Errorf("%q: %q, want %q", line, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,14 @@ func compose(r *Record, what string, now time.Time, loc *time.Location, withhold
|
||||
since += "."
|
||||
}
|
||||
body := since
|
||||
if explanation != "" {
|
||||
if r.Origin == "ask" && what != "reminder" && what != "quiet-reminder" {
|
||||
// An ask's own message (issue 639): its body is the asker's summary and points; when it was asked is in
|
||||
// its note, with who asked.
|
||||
body = ""
|
||||
}
|
||||
if explanation != "" && body == "" {
|
||||
body = explanation
|
||||
} else if explanation != "" {
|
||||
body = explanation + "\n" + since
|
||||
}
|
||||
return Message{Title: title, Body: body, Urgent: urgent}
|
||||
|
||||
@@ -2,4 +2,4 @@ module messenger
|
||||
|
||||
go 1.22
|
||||
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.10
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44
|
||||
|
||||
@@ -1,2 +1,8 @@
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.10 h1:EHhnPRrkw7/CSQAqRsxYnTvlTZ3dI02IPO6WSmVX80o=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.10/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.13 h1:Su4JYpZ+zhNovkGA2DgxiZdcuHpjw2tPJzc/7PljhXg=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.13/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013141520-9588871d6629 h1:7TYFV1Q6Mcz+lsLP/sds87tysET4rKCn3rRIQV8gNmA=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013141520-9588871d6629/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013145622-f4745447ba6d h1:HEJyqorKktrkJPeeJdwEo0kdrJjH3fm/YVS9MGftCqY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013145622-f4745447ba6d/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44 h1:r5xIo5qWOXQdCSMxvqJy8kV4U+P/QWXFK6971Ha6wU8=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.14-0.20261013182924-5933eb757d44/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
|
||||
@@ -97,6 +97,13 @@
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"health": {
|
||||
"kind": "http",
|
||||
"endpoint": "web",
|
||||
"path": "/healthz/readiness",
|
||||
"status": 200,
|
||||
"needs": "postgres-database"
|
||||
},
|
||||
"name": "n8n",
|
||||
"artifact": "server",
|
||||
"network": "n8n",
|
||||
|
||||
@@ -83,6 +83,14 @@
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"health": {
|
||||
"kind": "http",
|
||||
"endpoint": "web",
|
||||
"path": "/status.php",
|
||||
"status": 200,
|
||||
"body": "\"installed\":true",
|
||||
"needs": "postgres-database"
|
||||
},
|
||||
"name": "nextcloud",
|
||||
"image": "nextcloud@sha256:fb966733647ea03f0446b0c22eac9733c8eb616d37b960caca9d4c3010e14a08",
|
||||
"env-file": [
|
||||
|
||||
@@ -20,7 +20,7 @@ WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -o /mesh-route-proxy ./examples/route-proxy
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -buildvcs=false -ldflags=-buildid= -o /mesh-route-proxy ./examples/route-proxy
|
||||
|
||||
# A small runtime with the public CA roots the ACME client needs to reach a real authority, and run
|
||||
# as root so it can bind :80 and :443 — the two privileged ports a public front door listens on.
|
||||
|
||||
@@ -31,6 +31,7 @@ as the operator.
|
||||
| | fixed here |
|
||||
|---|---|
|
||||
| D1 | up to 4096 characters arrive whole; longer is cut and the cut said |
|
||||
| issues 383, 639 | shown formatted (HTML), never reworded: the title bold, the body as it is with a key line in monospace, the note apart in a blockquote collapsed to its first lines, kept whole when a message is too long (the body is cut first, and the cut said); `<`, `>` and `&` escaped first, so nothing in the words is read as markup. A tap is compared by the plain words, whitespace aside |
|
||||
| D4 | a warning or a clearing arrives without sound; an urgent message or a question rings |
|
||||
| D5 | a rate limit is waited out as told |
|
||||
| D6 | a refusal is a permanent failure, said to the router and not retried; an edit to the same text is a success |
|
||||
|
||||
@@ -249,9 +249,10 @@ func keyboard(buttons [][2]string) map[string]any {
|
||||
return map[string]any{"inline_keyboard": rows}
|
||||
}
|
||||
|
||||
// Send posts a message and answers its id. silent: it arrives without sound (D4).
|
||||
// Send posts a message, its text in ParseMode (rendered or escaped by the caller), and answers its id. silent:
|
||||
// it arrives without sound (D4).
|
||||
func (b *Bot) Send(chat int64, text string, buttons [][2]string, silent bool) (int64, error) {
|
||||
body := map[string]any{"chat_id": chat, "text": text, "disable_notification": silent,
|
||||
body := map[string]any{"chat_id": chat, "text": text, "parse_mode": ParseMode, "disable_notification": silent,
|
||||
"link_preview_options": map[string]any{"is_disabled": true}}
|
||||
if len(buttons) > 0 {
|
||||
body["reply_markup"] = keyboard(buttons)
|
||||
@@ -261,9 +262,10 @@ func (b *Bot) Send(chat int64, text string, buttons [][2]string, silent bool) (i
|
||||
return out.MessageID, err
|
||||
}
|
||||
|
||||
// Edit replaces a message's text and buttons; none given, the buttons go.
|
||||
// Edit replaces a message's text (in ParseMode, rendered or escaped by the caller) and buttons; none given, the
|
||||
// buttons go.
|
||||
func (b *Bot) Edit(chat, id int64, text string, buttons [][2]string) error {
|
||||
err := b.call("editMessageText", map[string]any{"chat_id": chat, "message_id": id, "text": text,
|
||||
err := b.call("editMessageText", map[string]any{"chat_id": chat, "message_id": id, "text": text, "parse_mode": ParseMode,
|
||||
"reply_markup": keyboard(buttons), "link_preview_options": map[string]any{"is_disabled": true}}, nil)
|
||||
if notModified(err) {
|
||||
return nil
|
||||
|
||||
@@ -7,7 +7,9 @@ package main
|
||||
//
|
||||
// - **Work** comes from its kind's worker on the `channel` queue: `show` (a message with buttons, each
|
||||
// carrying only the router's ticket), `send` (words), `edit` (a message shown before, by the router's
|
||||
// handle). Up to 4096 characters arrive whole; longer is cut and the cut said (D1). A warning or a
|
||||
// handle). Up to 4096 characters arrive whole; longer is cut and the cut said (D1). The words are shown
|
||||
// as the router gave them, formatted (render.go): the title bold, a key line in monospace, the note in a
|
||||
// collapsed blockquote after the body, escaped so that none of them is read as markup (issues 383, 639). A warning or a
|
||||
// clearing arrives without sound, an urgent message or a question rings (D4). A rate limit is waited out
|
||||
// as told (D5); a refusal is a permanent failure, said to the router, never retried; an edit to the same
|
||||
// text is a success (D6). A message that cannot be delivered after three tries is said as failed. A
|
||||
@@ -88,10 +90,18 @@ type Store interface {
|
||||
Show(chat, id int64, digest string) error
|
||||
}
|
||||
|
||||
// wordsDigest is what a tap's message is compared by: the words as Telegram gives them back — its line
|
||||
// endings and outer spaces aside — so a message whose words another holder of the token changed is told
|
||||
// from the one this channel showed (the review of 2026-10-09).
|
||||
// wordsDigest is what a tap's message is compared by: the words as Telegram gives them back — how the
|
||||
// whitespace between them runs aside, which Telegram may change around a blockquote (issue 639) — so a message
|
||||
// whose words another holder of the token changed is told from the one this channel showed (the review of
|
||||
// 2026-10-09).
|
||||
func wordsDigest(words string) string {
|
||||
sum := sha256.Sum256([]byte(strings.Join(strings.Fields(words), " ")))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// linesDigest is the digest a message shown before issue 639 was kept under: its line endings and outer spaces
|
||||
// aside. A tap on such a message is still compared by it.
|
||||
func linesDigest(words string) string {
|
||||
w := strings.TrimSpace(strings.ReplaceAll(words, "\r\n", "\n"))
|
||||
sum := sha256.Sum256([]byte(w))
|
||||
return hex.EncodeToString(sum[:])
|
||||
@@ -155,20 +165,6 @@ func (c *Channel) init() {
|
||||
}
|
||||
}
|
||||
|
||||
// text is a message as the chat shows it, cut at MaxLength and the cut said (D1).
|
||||
func text(m asks.Message) string {
|
||||
t := m.Title
|
||||
if m.Body != "" {
|
||||
t += "\n" + m.Body
|
||||
}
|
||||
if utf8.RuneCountInString(t) <= MaxLength {
|
||||
return t
|
||||
}
|
||||
runes := []rune(t)
|
||||
keep := MaxLength - utf8.RuneCountInString(cutNote)
|
||||
return string(runes[:keep]) + cutNote
|
||||
}
|
||||
|
||||
// buttons are a message's buttons as the API takes them: a label and the ticket, which must fit the 64
|
||||
// bytes Telegram allows; one that does not is left out and said.
|
||||
func (c *Channel) buttons(m asks.Message) [][2]string {
|
||||
@@ -231,7 +227,7 @@ func (c *Channel) Take(subject string, body json.RawMessage) error {
|
||||
c.fail(m.Handle, err, true)
|
||||
return nil
|
||||
}
|
||||
words, buttons := text(m), c.buttons(m)
|
||||
said, buttons := partsOf(m), c.buttons(m)
|
||||
silent := m.Silent || (!m.Urgent && len(buttons) == 0)
|
||||
// **A message said again under a handle already shown replaces it** (issue 373): a reminder or an
|
||||
// escalation is one message per problem, not one more beside it. An edit here notifies nobody, so this one
|
||||
@@ -253,15 +249,15 @@ func (c *Channel) Take(subject string, body json.RawMessage) error {
|
||||
var id int64
|
||||
switch {
|
||||
case place != nil:
|
||||
err = c.Bot.Edit(place.Chat, place.ID, words, buttons)
|
||||
err = c.Bot.Edit(place.Chat, place.ID, said.html(), buttons)
|
||||
if err == nil || notModified(err) {
|
||||
c.keepShown(place.Chat, place.ID, words)
|
||||
c.keepShown(place.Chat, place.ID, said.plain())
|
||||
}
|
||||
if gone(err) {
|
||||
place, err = nil, c.newMessage(m.Handle, chat, words, buttons, silent, &id)
|
||||
place, err = nil, c.newMessage(m.Handle, chat, said, buttons, silent, &id)
|
||||
}
|
||||
default:
|
||||
err = c.newMessage(m.Handle, chat, words, buttons, silent, &id)
|
||||
err = c.newMessage(m.Handle, chat, said, buttons, silent, &id)
|
||||
}
|
||||
if err == nil {
|
||||
if earlier != nil {
|
||||
@@ -297,13 +293,15 @@ func (c *Channel) replaced(p Placed) {
|
||||
return
|
||||
}
|
||||
c.Logf("[telegram] an earlier message could not be deleted (%v); its buttons are taken away instead", err)
|
||||
if err := c.Bot.Edit(p.Chat, p.ID, "Replaced by a newer message below.", nil); err != nil && !gone(err) {
|
||||
if err := c.Bot.Edit(p.Chat, p.ID, escape("Replaced by a newer message below."), nil); err != nil && !gone(err) {
|
||||
c.Logf("[telegram] an earlier message could not be marked replaced either: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Channel) newMessage(handle string, chat int64, words string, buttons [][2]string, silent bool, id *int64) error {
|
||||
got, err := c.Bot.Send(chat, words, buttons, silent)
|
||||
// newMessage sends words, rendered (render.go), and keeps where they are and what they say, plain.
|
||||
func (c *Channel) newMessage(handle string, chat int64, parts shown, buttons [][2]string, silent bool, id *int64) error {
|
||||
words := parts.plain()
|
||||
got, err := c.Bot.Send(chat, parts.html(), buttons, silent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -353,7 +351,7 @@ func (c *Channel) Handle(u Update) {
|
||||
// Only on a message showing exactly what this channel put there: one whose words another holder of
|
||||
// the token changed, or one it never showed, answers nothing (the review of 2026-10-09).
|
||||
if want, err := c.Store.Shown(cb.Message.Chat.ID, cb.Message.MessageID); err != nil || want == "" ||
|
||||
want != wordsDigest(cb.Message.Text) {
|
||||
(want != wordsDigest(cb.Message.Text) && want != linesDigest(cb.Message.Text)) {
|
||||
words := "That answer was not taken: this message does not show what the mesh put there. Nothing was done."
|
||||
c.answerTap(cb.ID, words)
|
||||
// Said on the phone alone, never in the chat: the tapper may be somebody the buttons reached, who is told
|
||||
@@ -461,7 +459,7 @@ func (c *Channel) remember(id string, chat int64) {
|
||||
}
|
||||
|
||||
func (c *Channel) reply(chat int64, words string) {
|
||||
if _, err := c.Bot.Send(chat, words, nil, true); err != nil {
|
||||
if _, err := c.Bot.Send(chat, escape(words), nil, true); err != nil {
|
||||
c.Logf("[telegram] could not answer in the chat: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,7 +202,7 @@ func TestAQuestionIsShownWithItsTicketsAndRingsAndAWarningIsSilent(t *testing.T)
|
||||
}
|
||||
b := sent[0].Body
|
||||
kb, _ := json.Marshal(b["reply_markup"])
|
||||
if b["chat_id"] != float64(42) || b["text"] != "Delivery of hq held\nNeeds you: release it." || b["disable_notification"] != false ||
|
||||
if b["chat_id"] != float64(42) || b["text"] != "<b>Delivery of hq held</b>\nNeeds you: release it." || b["disable_notification"] != false ||
|
||||
string(kb) != `{"inline_keyboard":[[{"callback_data":"0123456789abcdef0123456789abcdef","text":"Release"}]]}` {
|
||||
t.Errorf("sent %v %s", b, kb)
|
||||
}
|
||||
@@ -230,12 +230,83 @@ func TestALongMessageIsCutAndTheCutSaid(t *testing.T) {
|
||||
if err := c.Take(subject, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := f.of("sendMessage")[0].Body["text"].(string)
|
||||
// The bound is on the words, as Telegram's is on the text once its markup is read: the tags do not count.
|
||||
got := strings.NewReplacer("<b>", "", "</b>", "").Replace(f.of("sendMessage")[0].Body["text"].(string))
|
||||
got = strings.ReplaceAll(got, ">", ">")
|
||||
if n := len([]rune(got)); n != MaxLength || !strings.HasSuffix(got, cutNote) {
|
||||
t.Errorf("%d characters, ends %q (D1)", n, got[len(got)-40:])
|
||||
}
|
||||
}
|
||||
|
||||
// A message is shown formatted, never reworded (issues 383 and 639): the title bold, a key line in monospace, the
|
||||
// note apart in a collapsed blockquote, and every '<', '>' and '&' escaped, so a message carrying one neither breaks
|
||||
// nor injects. The tap on it is still compared by the plain words, which is what Telegram gives back.
|
||||
func TestAMessageIsRenderedInHTMLWithItsMarkupEscaped(t *testing.T) {
|
||||
c, f, s, _ := newChannel(t, goodToken)
|
||||
subject, body := work(asks.Show, asks.Message{Handle: "q1", Title: "Set mounts on <shanks> & co?",
|
||||
Body: "Changes two settings.\n+ shares: media=/storage/media\n~ sources: a=b (was: c)",
|
||||
Note: "Asked by mesh-controller at 15:11.\nFingerprint 1234 5678 9abc.",
|
||||
To: "42", Buttons: []asks.Button{{Label: "Approve", Ticket: "tkt"}}})
|
||||
if err := c.Take(subject, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sent := f.of("sendMessage")
|
||||
want := "<b>Set mounts on <shanks> & co?</b>\nChanges two settings.\n<code>+ shares: media=/storage/media</code>\n" +
|
||||
"<code>~ sources: a=b (was: c)</code>\n\n<blockquote expandable>Asked by mesh-controller at 15:11.\nFingerprint 1234 5678 9abc.</blockquote>"
|
||||
if len(sent) != 1 || sent[0].Body["text"] != want || sent[0].Body["parse_mode"] != "HTML" {
|
||||
t.Fatalf("sent %v", sent)
|
||||
}
|
||||
f.mu.Lock()
|
||||
shown := f.next
|
||||
f.mu.Unlock()
|
||||
// Telegram gives the words back plain, the space around the blockquote as it pleases: the tap on them is taken.
|
||||
c.Handle(Update{UpdateID: 1, Callback: &Callback{ID: "cb1", Data: "tkt", From: User{ID: 42, FirstName: "Jo"},
|
||||
Message: &Msg{MessageID: shown, Chat: Chat{ID: 42, Type: "private"},
|
||||
Text: "Set mounts on <shanks> & co?\nChanges two settings.\n+ shares: media=/storage/media\n~ sources: a=b (was: c)\n" +
|
||||
"Asked by mesh-controller at 15:11.\nFingerprint 1234 5678 9abc."}}})
|
||||
if got := s.of(asks.IntakeSubject(asks.Chosen, Kind)); len(got) != 1 {
|
||||
t.Fatalf("the tap on the rendered message was not taken: %s", got)
|
||||
}
|
||||
// Words changed by another holder of the token are still told apart.
|
||||
c.Handle(Update{UpdateID: 2, Callback: &Callback{ID: "cb2", Data: "tkt", From: User{ID: 42, FirstName: "Jo"},
|
||||
Message: &Msg{MessageID: shown, Chat: Chat{ID: 42, Type: "private"},
|
||||
Text: "Set mounts on <shanks> & co?\nChanges three settings.\n+ shares: media=/storage/media\n~ sources: a=b (was: c)\n" +
|
||||
"Asked by mesh-controller at 15:11.\nFingerprint 1234 5678 9abc."}}})
|
||||
if got := s.of(asks.IntakeSubject(asks.Chosen, Kind)); len(got) != 1 {
|
||||
t.Fatalf("a tap on changed words was taken: %s", got)
|
||||
}
|
||||
// The edit says what was chosen, one line with the headline, and is in the same mode.
|
||||
subject, body = work(asks.Edit, asks.Message{Handle: "q1", Title: "You chose Approve at 15:06 on Telegram · Set mounts on <shanks> & co?",
|
||||
Note: "Told to mesh-controller, which acts on it itself.", To: "42"})
|
||||
if err := c.Take(subject, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ed := f.of("editMessageText")
|
||||
if len(ed) != 1 || ed[0].Body["parse_mode"] != "HTML" ||
|
||||
ed[0].Body["text"] != "<b>You chose Approve at 15:06 on Telegram · Set mounts on <shanks> & co?</b>\n\n<blockquote expandable>Told to mesh-controller, which acts on it itself.</blockquote>" {
|
||||
t.Errorf("edited %v", ed)
|
||||
}
|
||||
// A plain answer in the chat is escaped too.
|
||||
c.reply(42, "a <b>tag</b> & more")
|
||||
if last := f.of("sendMessage"); last[len(last)-1].Body["text"] != "a <b>tag</b> & more" {
|
||||
t.Errorf("a reply was not escaped: %v", last[len(last)-1].Body["text"])
|
||||
}
|
||||
}
|
||||
|
||||
// A message shown before issue 639 was kept under the digest of its lines: a tap on it is still taken.
|
||||
func TestATapOnAMessageShownBeforeIsStillTaken(t *testing.T) {
|
||||
c, _, s, st := newChannel(t, goodToken)
|
||||
words := "Delivery held\nRelease or Stop."
|
||||
if err := st.Show(42, 9, linesDigest(words)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Handle(Update{UpdateID: 1, Callback: &Callback{ID: "cb1", Data: "tkt", From: User{ID: 42, FirstName: "Jo"},
|
||||
Message: &Msg{MessageID: 9, Chat: Chat{ID: 42, Type: "private"}, Text: words}}})
|
||||
if got := s.of(asks.IntakeSubject(asks.Chosen, Kind)); len(got) != 1 {
|
||||
t.Fatalf("the tap on a message shown before was not taken: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnEditToTheSameTextIsASuccessAndAGoneMessageIsSentAgain(t *testing.T) {
|
||||
c, f, s, st := newChannel(t, goodToken)
|
||||
st.Place("m1", Placed{Chat: 42, ID: 7})
|
||||
@@ -528,7 +599,7 @@ func TestATapTheRouterIsSlowOnClaimsNothingAndItsWordComesInTheChat(t *testing.T
|
||||
if err := c.Take(subject, body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sent := f.of("sendMessage"); len(sent) != sentBefore+1 || sent[len(sent)-1].Body["text"] != "You chose Release: recorded." {
|
||||
if sent := f.of("sendMessage"); len(sent) != sentBefore+1 || sent[len(sent)-1].Body["text"] != "<b>You chose Release: recorded.</b>" {
|
||||
t.Errorf("the late word was not said in the chat: %v", sent)
|
||||
}
|
||||
// Telegram refuses an acknowledgement that came too late: the word goes to the chat instead.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user