Compare commits

..
29 Commits
Author SHA1 Message Date
mesh-admin 9747f3e1b1 Merge pull request 'go: a module reads the values its bucket still keeps for a key (ADR 0307, issue 502)' (#22) from adr-0307-state-history into main 2026-10-12 08:21:13 +00:00
jochen d41d255f28 go: a module reads the values its bucket still keeps for a key, so the tracker can carry them into its log (hq ADR 0307)
mesh/delivery delivered
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery-group group adr-0307-state-history merged: every member is merged
2026-10-12 10:17:56 +02:00
mesh-admin 5794ccd569 Merge pull request 'go: a module appends to and reads its log through the runtime (ADR 0297, issues 501, 502)' (#21) from adr-0297-log into main 2026-10-11 18:08:52 +00:00
jochen eaed934629 go: a module appends to and reads its log through the runtime, so its record outlives a bucket's history (hq ADR 0297)
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery delivered
2026-10-11 19:16:09 +02:00
mesh-admin 4cf45b5ca0 Merge pull request 'go: a tool reads its caller from the runtime (hq issue 365)' (#20) from fix/365-a-tool-call-names-its-caller into main 2026-10-11 09:19:42 +00:00
jschoubben d9e24e95a2 go: a tool reads its caller from the runtime, so a record can say who acted (hq issue 365)
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery delivered
mesh/delivery-group group fix/365-a-tool-call-names-its-caller merged: every member is merged
The runtime names the caller it took from the subject a call arrived on in the
call's _meta; stdio.CallerOf(args) hands it to the tool. Never read from the
arguments, and Unproven when the runtime named none, so a bundle on an older
runtime still says, explicitly, that its caller was not proven.
2026-10-11 05:11:08 +02:00
mesh-admin ee1e1a8303 Merge pull request 'cli: a client reads the answer its failed write left waiting, so a refusal is heard (issue 444)' (#19) from fix/444-a-client-reads-the-answer-its-write-could-not-finish into main 2026-10-11 00:56:01 +00:00
jschoubben 24f5ee81bd cli: after a failed write take only a refusal, since nothing can have run, and pin that the read keeps the ask's deadline (hq issue 444)
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery delivered
2026-10-11 02:49:17 +02:00
jschoubben b4900f52b8 cli: read the engine's answer after a failed request write, so a refusal is not lost as a broken pipe (hq issue 444)
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery superseded: a newer head of the same pull request
2026-10-11 02:43:54 +02:00
mesh-admin 19cfe0ef03 Merge pull request 'go/health: a health tool answers healthy, unhealthy or waits (issue 386, ADR 0283)' (#18) from feat/386-a-wait-for-the-operator into main 2026-10-10 19:13:46 +00:00
jochen 33917f91ac Refuse every form of path or address in a wait's words, a contradicting healthy answer, and a malformed wait at Waiting
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery delivered
mesh/delivery-group group feat/386-a-wait-for-the-operator merged: every member is merged
From the review of mesh-sdk#18: quoted and bracketed paths, home and relative
paths, IPv6, host and port, UNC and drive paths passed the check.
2026-10-10 21:10:01 +02:00
jochen 622b6b4f55 Add go/health: a health tool answers healthy, unhealthy or waits (hq ADR 0283, issue 386)
mesh/delivery-group group feat/386-a-wait-for-the-operator checking: 1 of 2 member(s) ready
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery superseded: a newer head of the same pull request
A module waiting for the operator's secret had only 'not healthy' to say,
so its first-node gate failed and the operator was told nothing to do.
The answer gains a state and named waits, and Read refuses any wait it
cannot check, so a malformed wait never excuses a fault.
2026-10-10 21:06:44 +02:00
mesh-admin 67dfeafd51 Merge pull request 'go/asks: an ask says what a channel that proves who answers shows whole, and what Details shows (issue 383)' (#17) from fix/383-an-ask-says-what-a-proving-channel-shows-whole into main 2026-10-10 13:50:56 +00:00
jochen 4f3efc98e0 go/asks: an ask says what a channel that proves who answers shows whole, and what Details shows (hq issue 383)
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery delivered
A settings proposal reached the phone with its values masked, so the operator could not
tell what they were approving. An ask now carries Whole, shown in place of Explanation on
a kind that proves its sender and carries the ask's answers, and Details, what the
Details answer shows. Both enter the digest only when given, so an ask without them
digests as before and a router and an asker of different builds still agree on it.
2026-10-10 15:23:41 +02:00
mesh-admin 7605a3fa56 Merge pull request 'go: a counter by compare-and-set, so a number is handed out once (hq research 042)' (#16) from feat/a-counter-by-compare-and-set into main 2026-10-10 10:37:11 +00:00
jochen 9c548753b8 go: say an Increment error other than a lost write may have spent its number, refuse null, and prove the writers collided
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery delivered
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/delivery-group group feat/a-counter-by-compare-and-set merged: every member is merged
The review of 2026-10-10: a timeout can come after the write landed, so a caller tolerates gaps; a null value
is no counter; and a contention test where no write was lost would prove nothing.
2026-10-10 12:33:41 +02:00
jochen c58ce2c7fe go: a counter by compare-and-set, so a number is handed out once (hq research 042)
mesh/delivery-group group feat/a-counter-by-compare-and-set checking: 0 of 2 member(s) ready
mesh/delivery superseded: a newer head of the same pull request
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
The coming issues module hands out issue numbers from its own state; two instances must never hand out one
number twice. Create and Update already write by compare-and-set (ADR 0259), so State(...).Increment reads,
writes one more at the revision read, and on a lost write reads and tries again, bounded by the caller's
attempts. A lost write past the bound is ErrChanged, any other refusal and a value that is no counter are
returned at once: nothing is reported counted that was not written.

Part of the issue tracker decision, hq research 042.
2026-10-10 12:31:05 +02:00
mesh-admin ff1fcd4441 Merge pull request 'go/cli: carry mesh-cli's standard input with its line, for the controller's terminal alone (hq ADR 0259 §10, ADR 0272)' (#15) from feat/a-terminal-line-takes-standard-input into main 2026-10-09 15:31:47 +00:00
jschoubben f047d0a4a9 go/cli: carry mesh-cli's standard input with its line, bounded at 64 KiB, for the controller's terminal alone
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery covered after its stop: a later walk that contains it was delivered: plan-1791659640519725407 (novox/mesh-sdk at 19cfe0ef into main, done, …
mesh/delivery-group group feat/a-terminal-line-takes-standard-input closed: a member was closed before the group merged
A secret given at the terminal (secret accept … --from -) has no way through mesh-cli today: the controller
runs every line with no standard input. The request now carries it, refused over 64 KiB by mesh-cli and by
the reader alike, and MaxRequest grows by what base64 makes of that bound.
2026-10-09 16:33:44 +02:00
mesh-admin 97f9acfb51 Merge pull request 'Go: seat traffic, compare-and-set state, and the asks contract (hq ADR 0259)' (#12) from feat/asks-answered-on-any-channel into main 2026-10-09 14:17:37 +00:00
jschoubben 16984aafc6 Refuse a warrant for an ask with no expiry, and one that says no time (the confirmation review of 2026-10-09)
mesh/merge-gate pass: builds mesh-sdk, sent nowhere; no bus step; every machine composes with the change as it did without (4 of 4 compose)
mesh/repo-check pass: its merge-check.sh passed, each part in its toolchain: merge-check.sh (typescript), go/merge-check.sh (go)
mesh/delivery covered after its stop: a later walk that contains it was delivered: plan-1791659640519725407 (novox/mesh-sdk at 19cfe0ef into main, done, …
mesh/delivery-group group feat/asks-answered-on-any-channel closed: a member was closed before the group merged
For skipped the expiry check when the warrant carried no time, and an ask with a zero expiry was
answered at any time. Neither can be shown to be in time, so neither is acted on.
2026-10-09 13:58:50 +02:00
jschoubben 81a8e8a537 Digest an ask and an act over named fields in a canonical encoding, not a language's encoding of a struct
The review of 2026-10-09: a digest over Go's JSON of a struct changes when a tag is renamed or a field
added, and another language cannot reproduce it. An act is now a flat map of named strings, and both
digests are over length-prefixed values in a fixed order, versioned; a test fails when a field is added
to Ask or Option without being added to the digest.
2026-10-09 13:58:27 +02:00
jschoubben f7b57fb1ad Bind a warrant to the exact ask and each option to the act it performs (hq ADR 0259 §6)
A warrant named the ask by id and the option by id, and the asker acted on whatever its record held
for them. Now the ask carries, for every option above acknowledge, the digest of exactly what it
performs (Option.Binds, ActDigest), the router puts the digest of the ask it took in the warrant
(Warrant.AskDigest), For refuses a warrant whose digest is not that of the ask the asker keeps, and
Option.Performs refuses an act the option did not bind. A warrant then authorises one act, as the
person was shown it, once.
2026-10-09 13:58:27 +02:00
jochen e53ceadcf4 Mark a message a channel shows once and keeps no copy of 2026-10-09 13:58:27 +02:00
jochen c65a9bd324 Give an asking module a client that acts on each warrant once, and tell a lost compare-and-set by its code 2026-10-09 13:58:27 +02:00
jochen a2b619b638 Say which linked account a message is for 2026-10-09 13:58:27 +02:00
jochen 8c3480c845 Say a channel's failure, its standing, and what a message replies to 2026-10-09 13:58:27 +02:00
jochen d7be28a1a9 Read the kinds a module's membership names 2026-10-09 13:58:27 +02:00
jochen 3d0c8b02b2 Give modules the seat traffic and the contract to ask a person and answer on a channel (hq ADR 0259) 2026-10-09 13:58:27 +02:00
21 changed files with 3161 additions and 16 deletions
+19
View File
@@ -90,6 +90,25 @@ runtime's (`node-tools/internal/launch`, mesh-tools).
values and then every change. Through the runtime that launched the bundle, which refuses what the
module did not declare. Current values, never history and never a secret (novox/hq ADR 0201).
### `seats` and `asks` — asking a person, answering on a channel (Go)
A seat may name its caller or its kind (novox/hq ADR 0259): `stdio.SeatPublish` submits an accept or says
an event under the module's own name or kind, `stdio.SeatTake` takes a held seat's work, `stdio.SeatProve`
and `stdio.SeatAnswer` carry a proof (a code typed by a person, by request and reply, never kept),
`stdio.SeatRecord` reads a record kept for the module, and `State(...).Create` and `.Update` write by
compare-and-set. The runtime does each only as far as the module's membership lists. `go/asks` is the
contract on top: the `Ask` an asker publishes and the checks it is held to (its `Whole` is what a channel that proves
who answers shows in place of its `Explanation`, and its `Details` what the Details answer shows, hq issue 383), the `Warrant` it acts on
(`For`, `Says`), and the `Message`, `Choice`, `LinkAsked` and `Code` a channel takes and says, with the
subjects each travels on.
`go/asker` is an asking module's client (ADR 0259 §10): `Ask` keeps an ask in the module's own state and then
publishes it under the module's name; `Cancel`; `Where` reads its state from the router's record; `Listen` and
`Take` hand the module each warrant once — marked acted on by compare-and-set before the module acts, and only
for an ask it made, an option it offered, at that option's level, before it expired. A lost compare-and-set is
`stdio.ErrChanged`, told by the runtime's error code.
`State(...).Increment(key, attempts)` is a counter on top of the two (for numbers handed out once, such as an
issue's): it reads the key, writes one more at the revision read, and on a lost write reads and tries again, at
most `attempts` times; past that it is `stdio.ErrChanged` and nothing was counted.
### `primitives` — sealing, semver, resolved-env
Seal/unseal for secrets, semantic version comparison, and the accessor a module uses to read its
own resolved environment.
+2 -2
View File
@@ -2,8 +2,8 @@
`stdio.Serve("", tools)` speaks MCP over stdio to the node's tool runtime, as the module the runtime
names (novox/hq ADR 0188, ADR 0193). A `Tool` is a name, a description, an argument schema and a
function; calls run concurrently. A tool named `<seat>.<verb>` is the seat's implementation.
`stdio.Emit(type, body)` publishes an event as the module, `stdio.Subscribe(pattern, handler)` receives the module's events (taken when the handler returns nil, offered again when it returns an error — the one rule is in the repository README, "Taking an event") and `stdio.Ask(key, body)` calls a tool, and `stdio.State(name)` gets, puts, deletes, lists and watches the module's declared state — all through the runtime (novox/hq ADR 0193, 0198, 0201). Standard library only.
function; calls run concurrently. `stdio.CallerOf(args)` inside a tool is who called it: the bus user the runtime took from the subject the call arrived on, named in the call's `_meta`, never read from the arguments — or `stdio.Unproven` when the runtime named none (novox/hq issue 365). A tool named `<seat>.<verb>` is the seat's implementation.
`stdio.Emit(type, body)` publishes an event as the module, `stdio.Subscribe(pattern, handler)` receives the module's events (taken when the handler returns nil, offered again when it returns an error — the one rule is in the repository README, "Taking an event") and `stdio.Ask(key, body)` calls a tool, and `stdio.State(name)` gets, puts, deletes, lists, watches and reads the kept history of the module's declared state, and `stdio.Log(name)` appends to, reads, and measures a log of operations the module declared — all through the runtime (novox/hq ADR 0193, 0198, 0201, 0297, 0307). Standard library only.
## Installing
+196
View File
@@ -0,0 +1,196 @@
// Package asker is a module's client for asking a person (novox/hq ADR 0259 §10): it publishes an ask under
// the module's own name, cancels it, reads its state from the router's record, and hands the module each
// warrant once — only one for an ask it made, for an option it offered, at that option's level, before it
// expired. The module then acts with its own grants.
//
// It keeps what it asked, and which warrants it acted on, in a state of the module's own (declared in its
// manifest, by default `asked`): the ask is written before it is published, and a warrant is marked acted on
// by compare-and-set before the module's handler runs, so a redelivery, or a second instance, acts once.
package asker
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/asks"
)
// Client asks as one module.
type Client struct {
// Module is the asking module's name: the one the bus grants its asks under.
Module string
// State is the module's own state the asks are kept in.
State Store
// Now is the clock; nil is time.Now.
Now func() time.Time
// Publish, Record and Subscribe reach the bus; nil is the stdio SDK's, through the module's runtime.
Publish func(subject string, body any, id string) error
Record func(key string) (*stdio.StateEntry, error)
Subscribe func(pattern string, handle func(stdio.Envelope) error) error
}
// Store is where the asks are kept: stdio.State(name) is one.
type Store interface {
Get(key string) (*stdio.StateEntry, error)
Create(key string, value any) (uint64, error)
Update(key string, value any, revision uint64) (uint64, error)
}
// New is a client for the module the runtime serves, keeping its asks in the state named.
func New(state string) *Client {
return &Client{Module: os.Getenv("MESH_MODULE"), State: stdio.State(state)}
}
func (c *Client) now() time.Time {
if c.Now != nil {
return c.Now()
}
return time.Now()
}
// Kept is one ask as the module keeps it.
type Kept struct {
Ask asks.Ask `json:"ask"`
Asked time.Time `json:"asked"`
Acted bool `json:"acted,omitempty"`
Ended asks.Outcome `json:"ended,omitempty"`
Answer *asks.Warrant `json:"answer,omitempty"`
}
func key(id string) string { return "ask." + id }
// Ask checks an ask, keeps it, and publishes it under the module's own name. An ask with an id already kept
// is refused: a new question is a new id.
func (c *Client) Ask(a asks.Ask) error {
if err := a.Check(c.now()); err != nil {
return err
}
if _, err := c.State.Create(key(a.ID), Kept{Ask: a, Asked: c.now()}); err != nil {
if errors.Is(err, stdio.ErrChanged) {
return fmt.Errorf("an ask %s was already made: a new question is a new id", a.ID)
}
return err
}
return c.publish(asks.AskSubject(c.Module), a, a.ID)
}
// Cancel takes an ask back: the router ends it and edits every copy.
func (c *Client) Cancel(id string) error {
return c.publish(asks.CancelSubject(c.Module), map[string]string{"id": id}, "cancel."+id)
}
func (c *Client) publish(subject string, body any, id string) error {
if c.Publish != nil {
return c.Publish(subject, body, id)
}
return stdio.SeatPublish(subject, body, id)
}
// Where is an ask's state as the router keeps it: its state and its warrant, if any — read under the
// module's own name and no other's.
func (c *Client) Where(id string) (state string, w *asks.Warrant, err error) {
read := c.Record
if read == nil {
read = func(k string) (*stdio.StateEntry, error) { return stdio.SeatRecord("", k) }
}
e, err := read(id)
if err != nil || e == nil {
return "", nil, err
}
var rec struct {
State string `json:"state"`
Warrant *asks.Warrant `json:"warrant"`
}
if err := json.Unmarshal(e.Value, &rec); err != nil {
return "", nil, fmt.Errorf("the router's record of %s cannot be read: %w", id, err)
}
return rec.State, rec.Warrant, nil
}
// Handled is what came of a warrant: acted on, refused (and why), or already done.
type Handled string
const (
Acted Handled = "acted"
Refused Handled = "refused"
Done Handled = "already acted on"
Recorded Handled = "ended without a choice"
)
// Take hands act a warrant once, after holding it to the ask it answers. act performs the option with the
// module's own grants; its error is said and the warrant stays acted on (a person's decision is not
// performed twice; the module says the failure in its own record).
func (c *Client) Take(w asks.Warrant, act func(asks.Option, asks.Warrant) error) (Handled, error) {
if w.Asker != c.Module {
return Refused, fmt.Errorf("a warrant for %s reached %s", w.Asker, c.Module)
}
e, err := c.State.Get(key(w.Ask))
if err != nil {
return "", err
}
if e == nil {
return Refused, fmt.Errorf("%s holds no ask %s", c.Module, w.Ask)
}
var k Kept
if err := json.Unmarshal(e.Value, &k); err != nil {
return "", err
}
if k.Acted || k.Ended != "" {
return Done, nil
}
if w.Outcome != asks.OutcomeChosen {
k.Ended = w.Outcome
k.Answer = &w
if _, err := c.State.Update(key(w.Ask), k, e.Revision); err != nil && !errors.Is(err, stdio.ErrChanged) {
return "", err
}
return Recorded, nil
}
o, err := w.For(c.Module, k.Ask)
if err != nil {
return Refused, err
}
// Marked before acting: of two deliveries, or two instances, only the one whose write stands acts.
k.Acted, k.Ended, k.Answer = true, asks.OutcomeChosen, &w
if _, err := c.State.Update(key(w.Ask), k, e.Revision); err != nil {
if errors.Is(err, stdio.ErrChanged) {
return Done, nil
}
return "", err
}
return Acted, act(o, w)
}
// Listen hands every warrant for this module to Take, with act. It asks the runtime for the module's
// events matching the router's `decided` subject for this module.
func (c *Client) Listen(act func(asks.Option, asks.Warrant) error, said func(Handled, asks.Warrant, error)) error {
subscribe := c.Subscribe
if subscribe == nil {
subscribe = stdio.Subscribe
}
return subscribe(asks.Seat+".decided."+c.Module, func(e stdio.Envelope) error {
if !strings.HasPrefix(e.Key, asks.Seat+".decided.") {
return nil
}
var w asks.Warrant
if err := json.Unmarshal(e.Body, &w); err != nil {
if said != nil {
said(Refused, w, fmt.Errorf("a warrant could not be read: %w", err))
}
return nil
}
h, err := c.Take(w, act)
if h == "" && err != nil {
return err // the state could not be reached: offered again
}
if said != nil {
said(h, w, err)
}
return nil
})
}
+141
View File
@@ -0,0 +1,141 @@
package asker
import (
"encoding/json"
"strings"
"testing"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/asks"
)
type mem struct {
vals map[string]json.RawMessage
revs map[string]uint64
n uint64
}
func (m *mem) Get(k string) (*stdio.StateEntry, error) {
v, ok := m.vals[k]
if !ok {
return nil, nil
}
return &stdio.StateEntry{Key: k, Value: v, Revision: m.revs[k]}, nil
}
func (m *mem) Create(k string, v any) (uint64, error) {
if _, ok := m.vals[k]; ok {
return 0, stdio.ErrChanged
}
return m.put(k, v)
}
func (m *mem) Update(k string, v any, rev uint64) (uint64, error) {
if rev == 0 || m.revs[k] != rev {
return 0, stdio.ErrChanged
}
return m.put(k, v)
}
func (m *mem) put(k string, v any) (uint64, error) {
raw, _ := json.Marshal(v)
m.n++
m.vals[k], m.revs[k] = raw, m.n
return m.n, nil
}
var now = time.Date(2026, 10, 8, 14, 0, 0, 0, time.UTC)
func client() (*Client, map[string][]string) {
sent := map[string][]string{}
c := &Client{Module: "mesh-delivery", State: &mem{vals: map[string]json.RawMessage{}, revs: map[string]uint64{}},
Now: func() time.Time { return now },
Publish: func(subject string, body any, id string) error {
sent[subject] = append(sent[subject], id)
return nil
}}
return c, sent
}
// releaseHQ is the act the ask's one option binds.
var releaseHQ = map[string]string{"verb": "release", "delivery": "hq"}
func held() asks.Ask {
binds, _ := asks.ActDigest(releaseHQ)
return asks.Ask{ID: "d-1", Headline: "Delivery of hq held", Explanation: "Needs you: release it, or stop it.",
Who: asks.Operator, Expires: now.Add(time.Hour), OnExpiry: "the delivery stays held",
Options: []asks.Option{{ID: "release", Label: "Release", Does: "it goes on", Level: asks.Approve, Binds: binds}}}
}
func warrant() asks.Warrant {
return asks.Warrant{Ask: "d-1", Asker: "mesh-delivery", Outcome: asks.OutcomeChosen, Option: "release",
Label: "Release", Level: asks.Approve, At: now.Add(time.Minute), AskDigest: held().Digest(),
By: &asks.Person{Who: asks.Operator, Kind: "telegram", Identity: "42", Verified: "user id verified"}}
}
func TestAnAskIsKeptThenPublishedUnderTheModulesOwnName(t *testing.T) {
c, sent := client()
if err := c.Ask(held()); err != nil {
t.Fatal(err)
}
if got := sent[asks.AskSubject("mesh-delivery")]; len(got) != 1 || got[0] != "d-1" {
t.Fatalf("%v", sent)
}
if err := c.Ask(held()); err == nil || !strings.Contains(err.Error(), "already made") {
t.Errorf("the same id was asked twice: %v", err)
}
bad := held()
bad.Who = "agent"
if err := c.Ask(bad); err == nil {
t.Error("an ask the contract refuses was published")
}
}
func TestAWarrantIsActedOnOnceAndOnlyForItsOwnAsk(t *testing.T) {
c, _ := client()
_ = c.Ask(held())
acted := 0
act := func(o asks.Option, _ asks.Warrant) error {
if err := o.Performs(releaseHQ); err != nil {
t.Errorf("the bound act: %v", err)
}
acted++
return nil
}
if h, err := c.Take(warrant(), act); h != Acted || err != nil || acted != 1 {
t.Fatalf("%s %v %d", h, err, acted)
}
if h, _ := c.Take(warrant(), act); h != Done || acted != 1 {
t.Errorf("a redelivery was acted on: %s", h)
}
for why, change := range map[string]func(*asks.Warrant){
"another asker": func(w *asks.Warrant) { w.Asker = "mesh-controller" },
"an ask not made": func(w *asks.Warrant) { w.Ask = "d-9" },
"another level": func(w *asks.Warrant) { w.Level = asks.Acknowledge },
"an option not offered": func(w *asks.Warrant) { w.Option = "delete" },
"after its expiry": func(w *asks.Warrant) { w.At = now.Add(2 * time.Hour) },
"another ask's digest": func(w *asks.Warrant) { w.AskDigest = "sha256:00" },
} {
c2, _ := client()
_ = c2.Ask(held())
w := warrant()
change(&w)
if h, _ := c2.Take(w, act); h == Acted {
t.Errorf("a warrant from %s was acted on", why)
}
}
if acted != 1 {
t.Errorf("acted %d times", acted)
}
}
func TestAnAskEndedWithoutAChoiceIsRecordedAndNothingDone(t *testing.T) {
c, _ := client()
_ = c.Ask(held())
w := warrant()
w.Outcome, w.Option, w.By = asks.OutcomeExpired, "", nil
if h, err := c.Take(w, func(asks.Option, asks.Warrant) error { t.Fatal("acted"); return nil }); h != Recorded || err != nil {
t.Fatalf("%s %v", h, err)
}
if h, _ := c.Take(warrant(), func(asks.Option, asks.Warrant) error { t.Fatal("acted after it ended"); return nil }); h != Done {
t.Errorf("%s", h)
}
}
+509
View File
@@ -0,0 +1,509 @@
// Package asks is the contract of asking a person and answering on a channel (novox/hq ADR 0259): the
// shapes an asker, the router and a channel exchange on the bus, and the subjects they travel on. No
// transport and no channel's service: an asker publishes an Ask under its own name and acts on the Warrant
// it hears; the router holds the ask, sends channels a Message, and judges the Choice a channel says; a
// channel shows a Message and says what was chosen and by whom, as its service authenticated it.
package asks
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
// The seats (novox/hq ADR 0259 §3).
const (
// Seat is held by the router: an ask and its cancel are its accepts, a warrant its event, each named by
// the asker.
Seat = "operator-channel"
// ChannelSeat is the kinded bench a channel holds to show and say: its accepts carry the kind.
ChannelSeat = "channel"
// IntakeSeat is the kinded bench a channel holds to say what was chosen: its events and proofs carry
// the kind.
IntakeSeat = "intake"
)
// AskSubject is where an asker publishes an ask, CancelSubject its cancel, and DecidedSubject where it
// hears the warrant, or the ask's end without one.
func AskSubject(asker string) string { return "mesh.seat." + Seat + ".accept.ask." + asker }
func CancelSubject(asker string) string { return "mesh.seat." + Seat + ".accept.cancel." + asker }
func DecidedSubject(asker string) string { return "mesh.seat." + Seat + ".event.decided." + asker }
// The work a channel takes, on ChannelSubject.
const (
Show = "show" // a message offering answers
Edit = "edit" // a message shown before, replaced
Send = "send" // a message offering nothing
)
// ChannelSubject is where the router sends a channel of a kind its work.
func ChannelSubject(verb, kind string) string {
return "mesh.seat." + ChannelSeat + ".accept." + verb + "." + kind
}
// What a channel says, on IntakeSubject.
const (
Chosen = "choice" // a button tapped
Link = "link" // somebody asked to be linked as the operator
)
// IntakeSubject is where a channel of a kind says what arrived.
func IntakeSubject(what, kind string) string {
return "mesh.seat." + IntakeSeat + ".event." + what + "." + kind
}
// CodeProof is the one proof verb: a code the operator typed, carried by request and reply, never kept.
const CodeProof = "code"
// ProofSubject is where a channel of a kind asks a proof.
func ProofSubject(verb, kind string) string {
return "mesh.seat." + IntakeSeat + ".proof." + verb + "." + kind
}
// A Level is how much proof an option's answer needs (novox/hq ADR 0234 §8, the glossary's assurance level).
type Level string
const (
// Acknowledge performs only what any granted principal may already do: silencing, details. No proof.
Acknowledge Level = "acknowledge"
// Approve needs one proof: a verified sender (a linked account, linked an hour or more) or a code.
Approve Level = "approve"
// Destroy needs two proofs, one of them a code.
Destroy Level = "destroy"
)
// Rank orders the levels; an unknown level ranks above every known one, so it is never taken as less.
func (l Level) Rank() int {
switch l {
case Acknowledge:
return 0
case Approve:
return 1
case Destroy:
return 2
}
return 3
}
// Operator is the one role an ask may be answered by today.
const Operator = "operator"
// Option is one answer an ask offers: a label for the button, what it does in plain words, its level.
type Option struct {
ID string `json:"id"`
Label string `json:"label"`
Does string `json:"does"`
Level Level `json:"level"`
// Binds is the digest of exactly what the asker performs when this option is chosen — the verb, the
// machine and every argument — as ActDigest gives it. It travels in the ask, so the router's warrant,
// which names the ask's digest, names it too: a warrant then authorises that act and no other, and an
// asker whose record of the act changed after it asked finds the digests differ and does nothing.
// Required on an option above acknowledge.
Binds string `json:"binds,omitempty"`
}
// An Act is what an option binds: named fields, each a string — the verb, the machine, the level, and each
// argument under a name of its own ("arg.delivery"). Flat on purpose: its digest is over these names and
// values alone, never over how a language happens to encode a struct.
type Act map[string]string
// ActDigest is the digest an asker puts in Option.Binds: SHA-256 over the act's canonical encoding (canonical),
// written "sha256:<hex>". The same names and values give the same digest in any language, whatever order
// they were set in; a field renamed, added or emptied gives another.
func ActDigest(act Act) (string, error) {
if len(act) == 0 {
return "", fmt.Errorf("the act cannot be digested: it names nothing")
}
keys := make([]string, 0, len(act))
for k := range act {
if k == "" {
return "", fmt.Errorf("the act cannot be digested: a field has no name")
}
keys = append(keys, k)
}
sort.Strings(keys)
var b strings.Builder
b.WriteString("novox.act.v1\n")
for _, k := range keys {
canonical(&b, k)
canonical(&b, act[k])
}
sum := sha256.Sum256([]byte(b.String()))
return "sha256:" + hex.EncodeToString(sum[:]), nil
}
// canonical writes one value as its length in bytes, a colon, the bytes and a newline: no value can be read
// as another's end or start, so two different sequences of values never encode the same.
func canonical(b *strings.Builder, v string) {
b.WriteString(strconv.Itoa(len(v)))
b.WriteByte(':')
b.WriteString(v)
b.WriteByte('\n')
}
// Digest is the digest of the ask exactly as its asker published it: its id, words, options with what each
// binds, who answers, and its expiry. The router puts it in the warrant (Warrant.AskDigest), and an asker
// acts only on a warrant whose digest is that of the ask it keeps — so a warrant answers one ask, as the
// person was shown it, and nothing published under the same id before or after.
//
// It is over the ask's named fields in a fixed order, each written canonically, and the expiry as UTC
// RFC 3339 to the nanosecond — never over a language's encoding of the struct, so a field added to Ask
// later changes no digest until it is added here, on purpose. Whole and Details (novox/hq issue 383) follow
// the options only when the ask gives either: an ask without them digests as it did before they existed, so
// a router and an asker of different builds still agree on every such ask.
func (a Ask) Digest() string {
var b strings.Builder
b.WriteString("novox.ask.v1\n")
for _, v := range []string{a.ID, a.Headline, a.Explanation, a.Who,
a.Expires.UTC().Format(time.RFC3339Nano), a.OnExpiry, a.About, strconv.FormatBool(a.Urgent),
strconv.Itoa(len(a.Options))} {
canonical(&b, v)
}
for _, o := range a.Options {
for _, v := range []string{o.ID, o.Label, o.Does, string(o.Level), o.Binds} {
canonical(&b, v)
}
}
if a.Whole != "" || a.Details != "" {
canonical(&b, a.Whole)
canonical(&b, a.Details)
}
sum := sha256.Sum256([]byte(b.String()))
return "sha256:" + hex.EncodeToString(sum[:])
}
// Ask is a request for a person's word (novox/hq ADR 0259 §4).
type Ask struct {
// ID is the asker's own, unique to it.
ID string `json:"id"`
// Headline names the thing and what is wrong, in a few plain words; Explanation is what happened and
// what it means. Both are held to the plain rule and the content rule by the router.
Headline string `json:"headline"`
Explanation string `json:"explanation"`
Options []Option `json:"options"`
// Who may answer: Operator.
Who string `json:"who"`
// Expires is when the ask ends unanswered; OnExpiry is what the asker then does, in words the person
// is shown ("the delivery stays held"). An ask that authorises never defaults.
Expires time.Time `json:"expires"`
OnExpiry string `json:"on-expiry"`
// About is what the ask is about (a condition's key): a newer ask about it replaces the older.
About string `json:"about,omitempty"`
Urgent bool `json:"urgent,omitempty"`
// Whole is the explanation with its exact values whole, shown in place of Explanation on a channel kind
// that proves who answers (verified-sender) and carries the ask's answers (novox/hq issue 383): what the
// person approves — a mount point, a share, a private address — must be readable where they approve it.
// The asker withholds a value shaped like a secret in it, and the router refuses the ask when one is left;
// Explanation stays under the whole content rule everywhere else. Empty, Explanation is shown everywhere.
Whole string `json:"whole,omitempty"`
// Details is what the Details answer on the ask's message shows, line by line under the content rule: a
// fingerprint, how to read the proposal whole at the terminal. Empty, an ask's own message offers no Details.
Details string `json:"details,omitempty"`
}
// The bounds of an ask (novox/hq ADR 0234 §8, ADR 0259 §4).
const (
MostOptions = 4
MostOpen = 3
ApproveLasts = 24 * time.Hour
DestroyLasts = 10 * time.Minute
HeadlineLength = 60
LabelLength = 24
)
var usableID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`)
// UsableID says whether a name can be an ask's or an option's id: a key and a subject token both.
func UsableID(id string) bool { return usableID.MatchString(id) }
// Highest is the highest level among the ask's options.
func (a Ask) Highest() Level {
high := Acknowledge
for _, o := range a.Options {
if o.Level.Rank() > high.Rank() {
high = o.Level
}
}
return high
}
// Option is the option of this id, or false.
func (a Ask) Option(id string) (Option, bool) {
for _, o := range a.Options {
if o.ID == id {
return o, true
}
}
return Option{}, false
}
// Check is what an ask is held to before anything is shown: every refusal, in words its asker can act on.
func (a Ask) Check(now time.Time) error {
var problems []string
say := func(format string, args ...any) { problems = append(problems, fmt.Sprintf(format, args...)) }
if !UsableID(a.ID) {
say("its id %q is not letters, digits, - and _, at most 64", a.ID)
}
if strings.TrimSpace(a.Headline) == "" || len([]rune(a.Headline)) > HeadlineLength {
say("its headline is empty or longer than %d characters", HeadlineLength)
}
if strings.TrimSpace(a.Explanation) == "" {
say("it explains nothing")
}
if a.Who != Operator {
say("it is answered by %q, and only the operator answers today", a.Who)
}
if len(a.Options) == 0 || len(a.Options) > MostOptions {
say("it offers %d options, and an ask offers one to %d", len(a.Options), MostOptions)
}
seen := map[string]bool{}
for _, o := range a.Options {
switch {
case !UsableID(o.ID):
say("an option's id %q is not letters, digits, - and _", o.ID)
case seen[o.ID]:
say("the option %s is offered twice", o.ID)
}
seen[o.ID] = true
if strings.TrimSpace(o.Label) == "" || len([]rune(o.Label)) > LabelLength {
say("the option %s's label is empty or longer than %d characters", o.ID, LabelLength)
}
if strings.TrimSpace(o.Does) == "" {
say("the option %s does not say what it does", o.ID)
}
if o.Level.Rank() > Destroy.Rank() {
say("the option %s has the level %q, which is none of acknowledge, approve, destroy", o.ID, o.Level)
}
if o.Level != Acknowledge && !strings.HasPrefix(o.Binds, "sha256:") {
say("the option %s authorises and does not bind what it performs (its binds is not an ActDigest)", o.ID)
}
}
if !a.Expires.After(now) {
say("it expires before it is asked")
}
switch a.Highest() {
case Approve:
if a.Expires.After(now.Add(ApproveLasts)) {
say("an ask that approves lasts at most %s", ApproveLasts)
}
case Destroy:
if a.Expires.After(now.Add(DestroyLasts)) {
say("an ask that destroys lasts at most %s", DestroyLasts)
}
}
if a.Highest() != Acknowledge && strings.TrimSpace(a.OnExpiry) == "" {
say("it does not say what happens when nobody answers, and an ask that authorises never defaults")
}
if a.About != "" && strings.ContainsAny(a.About, " \n") {
say("what it is about is a key, without spaces")
}
if len(problems) > 0 {
return errors.New("the ask is refused: " + strings.Join(problems, "; "))
}
return nil
}
// Outcome is how an ask ended.
type Outcome string
const (
OutcomeChosen Outcome = "chosen" // a person chose an option: a warrant
OutcomeExpired Outcome = "expired" // nobody answered in time
OutcomeCancelled Outcome = "cancelled" // its asker took it back
OutcomeReplaced Outcome = "replaced" // a newer ask about the same thing replaced it
OutcomeRefused Outcome = "refused" // it was never shown: Words says why
)
// Person is who chose, as the router verified them.
type Person struct {
// Who is the role: Operator.
Who string `json:"who"`
// Kind is the channel kind they answered on, Identity their account on that service, Display the name
// the service shows, and Verified how the router knew it was them.
Kind string `json:"kind"`
Identity string `json:"identity"`
Display string `json:"display,omitempty"`
Verified string `json:"verified"`
}
// Warrant is the router's record that a person chose one option of one ask, or the ask's end without one
// (novox/hq ADR 0259 §6). It carries no secret.
type Warrant struct {
Ask string `json:"ask"`
Asker string `json:"asker"`
About string `json:"about,omitempty"`
Outcome Outcome `json:"outcome"`
// Option, Label and Level are the option chosen; By who chose it, Channel the module it came through,
// Proofs which proofs were present (P1, P2, P3).
Option string `json:"option,omitempty"`
Label string `json:"label,omitempty"`
Level Level `json:"level,omitempty"`
By *Person `json:"by,omitempty"`
Channel string `json:"channel,omitempty"`
Proofs []string `json:"proofs,omitempty"`
At time.Time `json:"at"`
// AskDigest is the digest of the ask as the router took it (Ask.Digest): the warrant answers that ask
// alone, with the options it bound.
AskDigest string `json:"ask-digest,omitempty"`
// Words are why an ask ended without a choice, or what refused it.
Words string `json:"words,omitempty"`
}
// Says is the warrant in the words an asker records with its act: "the operator, via telegram (user id
// verified), chose Release".
func (w Warrant) Says() string {
if w.Outcome != OutcomeChosen || w.By == nil {
return fmt.Sprintf("no person chose: the ask %s %s", w.Ask, w.Outcome)
}
via := w.By.Kind
if w.By.Verified != "" {
via += " (" + w.By.Verified + ")"
}
return fmt.Sprintf("the %s, via %s, chose %s", w.By.Who, via, w.Label)
}
// For checks a warrant against the ask its asker made: the same asker and ask, the same ask's digest (so the
// same words, options and binds), a choice, an option the ask offered, at that option's level, before the
// ask expired. An asker acts on nothing else, and then performs only what the option's Binds names.
func (w Warrant) For(asker string, a Ask) (Option, error) {
if w.Asker != asker || w.Ask != a.ID {
return Option{}, fmt.Errorf("the warrant is for %s's ask %s, not %s's %s", w.Asker, w.Ask, asker, a.ID)
}
if w.Outcome != OutcomeChosen || w.By == nil || w.By.Who != a.Who {
return Option{}, fmt.Errorf("the ask %s ended %s; no person chose", a.ID, w.Outcome)
}
if d := a.Digest(); w.AskDigest != d {
return Option{}, fmt.Errorf("the warrant answers an ask whose digest is %q, and the ask %s kept here is %s: "+
"it was not the ask the person was shown", w.AskDigest, a.ID, d)
}
o, offered := a.Option(w.Option)
if !offered {
return Option{}, fmt.Errorf("the ask %s offered no option %s", a.ID, w.Option)
}
if w.Level != o.Level {
return Option{}, fmt.Errorf("the option %s is %s, and the warrant says %s", o.ID, o.Level, w.Level)
}
// A choice made after the ask expired is no answer to it, whatever the router said. An ask that says no
// expiry, or a warrant that says no time, is no answer either: neither can be shown to be in time (the
// confirmation review of 2026-10-09).
if a.Expires.IsZero() {
return Option{}, fmt.Errorf("the ask %s says no expiry, so no answer to it can be in time", a.ID)
}
if w.At.IsZero() {
return Option{}, fmt.Errorf("the warrant for the ask %s says no time it was given, so it cannot be shown to be in time", a.ID)
}
if w.At.After(a.Expires) {
return Option{}, fmt.Errorf("the warrant was given at %s, after the ask %s expired at %s",
w.At.UTC().Format(time.RFC3339), a.ID, a.Expires.UTC().Format(time.RFC3339))
}
return o, nil
}
// Performs checks that the act an asker is about to perform is the one the chosen option bound when it
// asked: the act's digest equals the option's Binds. An acknowledge option that bound nothing passes.
func (o Option) Performs(act Act) error {
if o.Binds == "" && o.Level == Acknowledge {
return nil
}
d, err := ActDigest(act)
if err != nil {
return err
}
if d != o.Binds {
return fmt.Errorf("the option %s bound %s, and the act about to be performed is %s: nothing is done", o.ID, o.Binds, d)
}
return nil
}
// Button is one answer a channel offers: its label and the router's one-time ticket for it.
type Button struct {
Label string `json:"label"`
Ticket string `json:"ticket"`
}
// Message is the work a channel takes: shown with buttons (Show), shown again in place (Edit), or said
// (Send). Handle is the router's name for it, the same across a show and its edits; the channel keeps
// which of its own messages that is. The words are the router's, shown as given.
type Message struct {
Handle string `json:"handle"`
Title string `json:"title"`
Body string `json:"body"`
Buttons []Button `json:"buttons,omitempty"`
Urgent bool `json:"urgent,omitempty"`
Silent bool `json:"silent,omitempty"`
// Reply is the Choice or LinkAsked this answers, by its ID: the channel shows it where that was made.
Reply string `json:"reply,omitempty"`
// To is the account linked as the operator on this kind, for a channel that verifies its sender: where
// the channel sends what is not a reply. The router's word, from its list; empty when none is linked.
To string `json:"to,omitempty"`
// Secret says the words carry something shown once (a link's code): the channel shows it and keeps no
// copy of it — no state, no history of its own.
Secret bool `json:"secret,omitempty"`
}
// Sender is who a channel's service says sent something: the account, the name it shows, and whether the
// service authenticated it. The router alone judges whether that is the operator.
type Sender struct {
Identity string `json:"identity"`
Display string `json:"display,omitempty"`
Authenticated bool `json:"authenticated"`
}
// Failed is a message a channel could not deliver: its handle, why, and whether trying again could help.
type Failed struct {
Handle string `json:"handle"`
Why string `json:"why"`
Permanent bool `json:"permanent,omitempty"`
At time.Time `json:"at"`
}
// Standing is what a channel says of itself, at least every five minutes and whenever it changes:
// whether it can send now, why not, and whether its edits notify nobody.
type Standing struct {
Ready bool `json:"ready"`
Why string `json:"why,omitempty"`
EditsSilently bool `json:"edits-silently,omitempty"`
At time.Time `json:"at"`
}
// What a channel says of its own delivery, on IntakeSubject.
const (
FailedWhat = "failed"
StandingWhat = "standing"
)
// Choice is a button chosen on a channel.
type Choice struct {
// ID is the channel's own for this arrival, unique, so the router acts on it once.
ID string `json:"id"`
Ticket string `json:"ticket"`
Handle string `json:"handle,omitempty"`
Sender Sender `json:"sender"`
At time.Time `json:"at"`
}
// LinkAsked is somebody on a channel asking to be linked as the operator.
type LinkAsked struct {
ID string `json:"id"`
Sender Sender `json:"sender"`
At time.Time `json:"at"`
}
// Code is a code a person typed on a channel, asked as a proof: never in an event, never kept.
type Code struct {
Sender Sender `json:"sender"`
Code string `json:"code"`
Purpose string `json:"purpose"`
}
// ProofAnswer is the router's answer to a proof: whether it was taken, and words to say to the person.
type ProofAnswer struct {
Accepted bool `json:"accepted"`
Words string `json:"words"`
}
+281
View File
@@ -0,0 +1,281 @@
package asks
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"reflect"
"strings"
"testing"
"time"
)
var now = time.Date(2026, 10, 8, 14, 0, 0, 0, time.UTC)
func held() Ask {
return Ask{ID: "d-1", Headline: "openrazer delivery held", Explanation: "Needs you: release it, or stop it.",
Who: Operator, Expires: now.Add(time.Hour), OnExpiry: "the delivery stays held", About: "delivery.openrazer",
Options: []Option{
{ID: "release", Label: "Release", Does: "the delivery goes on", Level: Approve, Binds: bind("release", "openrazer")},
{ID: "stop", Label: "Stop", Does: "the delivery ends", Level: Approve, Binds: bind("stop", "openrazer")},
{ID: "silence", Label: "Silence for a week", Does: "nothing more is said for a week", Level: Acknowledge},
}}
}
func bind(verb, what string) string {
d, err := ActDigest(Act{"verb": verb, "delivery": what})
if err != nil {
panic(err)
}
return d
}
func TestASoundAskPasses(t *testing.T) {
if err := held().Check(now); err != nil {
t.Fatal(err)
}
}
func TestAnAskIsRefusedInWordsForEachFault(t *testing.T) {
for want, change := range map[string]func(*Ask){
"is not letters": func(a *Ask) { a.ID = "a.b" },
"headline is empty": func(a *Ask) { a.Headline = "" },
"explains nothing": func(a *Ask) { a.Explanation = " " },
"only the operator answers": func(a *Ask) { a.Who = "agent" },
"offers 0 options": func(a *Ask) { a.Options = nil },
"offers 5 options": func(a *Ask) { a.Options = append(a.Options, a.Options[0], a.Options[1]) },
"is offered twice": func(a *Ask) { a.Options[1].ID = "release" },
"does not say what it does": func(a *Ask) { a.Options[0].Does = "" },
"none of acknowledge": func(a *Ask) { a.Options[0].Level = "admin" },
"expires before it is asked": func(a *Ask) { a.Expires = now },
"approves lasts at most": func(a *Ask) { a.Expires = now.Add(25 * time.Hour) },
"destroys lasts at most": func(a *Ask) { a.Options[0].Level = Destroy },
"never defaults": func(a *Ask) { a.OnExpiry = "" },
"is a key, without spaces": func(a *Ask) { a.About = "a b" },
"does not bind what it": func(a *Ask) { a.Options[0].Binds = "" },
} {
a := held()
change(&a)
if err := a.Check(now); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("want a refusal saying %q, got %v", want, err)
}
}
ack := held()
ack.Options = ack.Options[2:]
ack.OnExpiry = ""
ack.Expires = now.Add(7 * 24 * time.Hour)
if err := ack.Check(now); err != nil {
t.Errorf("an ask that only acknowledges needs no expiry words and may last a week: %v", err)
}
}
func TestAnAskerActsOnlyOnAWarrantForItsOwnAskAndOption(t *testing.T) {
w := Warrant{Ask: "d-1", Asker: "mesh-delivery", Outcome: OutcomeChosen, Option: "release", Label: "Release",
Level: Approve, By: &Person{Who: Operator, Kind: "telegram", Identity: "42", Verified: "user id verified"},
AskDigest: held().Digest(), At: now.Add(time.Minute)}
if o, err := w.For("mesh-delivery", held()); err != nil || o.ID != "release" {
t.Fatalf("a sound warrant was refused: %v", err)
}
if got := w.Says(); got != "the operator, via telegram (user id verified), chose Release" {
t.Errorf("the warrant says %q", got)
}
for why, change := range map[string]func(*Warrant){
"another asker": func(w *Warrant) { w.Asker = "mesh-controller" },
"another ask": func(w *Warrant) { w.Ask = "d-2" },
"no choice": func(w *Warrant) { w.Outcome = OutcomeExpired },
"nobody": func(w *Warrant) { w.By = nil },
"not offered": func(w *Warrant) { w.Option = "delete" },
"a lower level": func(w *Warrant) { w.Level = Acknowledge },
"another role": func(w *Warrant) { w.By = &Person{Who: "agent"} },
"no digest": func(w *Warrant) { w.AskDigest = "" },
"no time given": func(w *Warrant) { w.At = time.Time{} },
"after expiry": func(w *Warrant) { w.At = now.Add(2 * time.Hour) },
"another ask's digest": func(w *Warrant) {
other := held()
other.Options[0].Binds = bind("release", "another")
w.AskDigest = other.Digest()
},
} {
c := w
by := *w.By
c.By = &by
change(&c)
if _, err := c.For("mesh-delivery", held()); err == nil {
t.Errorf("a warrant with %s was acted on", why)
}
}
}
func TestTheSubjectsNameTheirPublisher(t *testing.T) {
for got, want := range map[string]string{
AskSubject("mesh-delivery"): "mesh.seat.operator-channel.accept.ask.mesh-delivery",
DecidedSubject("mesh-delivery"): "mesh.seat.operator-channel.event.decided.mesh-delivery",
ChannelSubject(Show, "telegram"): "mesh.seat.channel.accept.show.telegram",
IntakeSubject(Chosen, "desktop"): "mesh.seat.intake.event.choice.desktop",
ProofSubject(CodeProof, "telegram"): "mesh.seat.intake.proof.code.telegram",
} {
if got != want {
t.Errorf("%s, want %s", got, want)
}
}
}
// A warrant answers one ask as it was shown, and authorises the act its option bound and no other
// (novox/hq ADR 0259 §6: the warrant is bound to the exact ask and its arguments).
func TestAWarrantAuthorisesOnlyTheActItsOptionBound(t *testing.T) {
a := held()
// The digest survives the trip through the bus: what the router decodes and digests is what was sent.
raw, err := json.Marshal(a)
if err != nil {
t.Fatal(err)
}
var decoded Ask
if err := json.Unmarshal(raw, &decoded); err != nil {
t.Fatal(err)
}
if decoded.Digest() != a.Digest() {
t.Fatalf("the ask's digest changed on the way: %s, %s", decoded.Digest(), a.Digest())
}
local := a
local.Expires = a.Expires.In(time.FixedZone("CEST", 2*3600))
if local.Digest() != a.Digest() {
t.Error("the same instant in another zone digests differently")
}
// Changing anything the person was shown, or what an option binds, changes the digest.
for what, change := range map[string]func(*Ask){
"the headline": func(a *Ask) { a.Headline += "!" },
"the explanation": func(a *Ask) { a.Explanation += " " },
"a label": func(a *Ask) { a.Options[0].Label = "Go" },
"what it binds": func(a *Ask) { a.Options[0].Binds = bind("release", "another") },
"the expiry": func(a *Ask) { a.Expires = a.Expires.Add(time.Second) },
"what it is about": func(a *Ask) { a.About = "delivery.other" },
} {
c := held()
change(&c)
if c.Digest() == a.Digest() {
t.Errorf("changing %s leaves the digest", what)
}
}
o, _ := a.Option("release")
if err := o.Performs(Act{"verb": "release", "delivery": "openrazer"}); err != nil {
t.Errorf("the bound act was refused: %v", err)
}
if err := o.Performs(Act{"verb": "release", "delivery": "another"}); err == nil {
t.Error("an act the option did not bind was let through")
}
ack, _ := a.Option("silence")
if err := ack.Performs(Act{"anything": "x"}); err != nil {
t.Errorf("an acknowledgement that bound nothing: %v", err)
}
}
// The digests are over named fields in a canonical encoding (the review of 2026-10-09): not over Go's
// encoding of a struct, so a field added to Ask or Option, a JSON tag renamed, or a map built in another
// order changes nothing it should not — and every field that is shown or bound is in it.
func TestDigestsAreCanonicalOverNamedFields(t *testing.T) {
a1, _ := ActDigest(Act{"verb": "release", "arg.delivery": "hq"})
b := Act{}
b["arg.delivery"] = "hq"
b["verb"] = "release"
a2, _ := ActDigest(b)
if a1 != a2 {
t.Error("the order an act was built in changed its digest")
}
// A value cannot be read as two: "a"+"b=c" is not "a=b"+"c".
x, _ := ActDigest(Act{"a": "b\n1:c"})
y, _ := ActDigest(Act{"a": "b", "c": ""})
if x == y {
t.Error("two different acts encode the same")
}
if _, err := ActDigest(Act{}); err == nil {
t.Error("an empty act was digested")
}
// The encoding, by hand: any language reproduces it.
sum := sha256.Sum256([]byte("novox.act.v1\n4:verb\n7:release\n"))
if got, _ := ActDigest(Act{"verb": "release"}); got != "sha256:"+hex.EncodeToString(sum[:]) {
t.Errorf("the act's encoding is not the one written down: %s", got)
}
// Every exported field of Ask and Option is in the digest: changing any one changes it.
base := held()
mutations := map[string]func(*Ask){
"ID": func(a *Ask) { a.ID = "other" },
"Headline": func(a *Ask) { a.Headline += "!" },
"Explanation": func(a *Ask) { a.Explanation += "!" },
"Who": func(a *Ask) { a.Who = "someone" },
"Expires": func(a *Ask) { a.Expires = a.Expires.Add(time.Nanosecond) },
"OnExpiry": func(a *Ask) { a.OnExpiry += "!" },
"About": func(a *Ask) { a.About += "!" },
"Urgent": func(a *Ask) { a.Urgent = !a.Urgent },
"Options": func(a *Ask) { a.Options = a.Options[:1] },
"Option.ID": func(a *Ask) { a.Options = append([]Option(nil), a.Options...); a.Options[0].ID = "x" },
"Option.Label": func(a *Ask) {
a.Options = append([]Option(nil), a.Options...)
a.Options[0].Label += "!"
},
"Option.Does": func(a *Ask) { a.Options = append([]Option(nil), a.Options...); a.Options[0].Does += "!" },
"Option.Level": func(a *Ask) {
a.Options = append([]Option(nil), a.Options...)
a.Options[0].Level = Destroy
},
"Option.Binds": func(a *Ask) {
a.Options = append([]Option(nil), a.Options...)
a.Options[0].Binds = "sha256:00"
},
}
for name, mutate := range mutations {
c := base
mutate(&c)
if c.Digest() == base.Digest() {
t.Errorf("changing %s left the digest the same", name)
}
}
// Whole and Details (issue 383) are in the digest once given, and change it; an ask without either digests
// exactly as before they existed — the encoding by hand, so no build can drift from it unseen.
plain := Ask{ID: "p", Headline: "h", Explanation: "e", Who: Operator, Expires: now, OnExpiry: "o", About: "a",
Options: []Option{{ID: "ok", Label: "OK", Does: "d", Level: Acknowledge}}}
byHand := sha256.Sum256([]byte("novox.ask.v1\n1:p\n1:h\n1:e\n8:operator\n20:2026-10-08T14:00:00Z\n1:o\n1:a\n5:false\n1:1\n" +
"2:ok\n2:OK\n1:d\n11:acknowledge\n0:\n"))
if plain.Digest() != "sha256:"+hex.EncodeToString(byHand[:]) {
t.Errorf("an ask without Whole and Details does not digest as it did before them: %s", plain.Digest())
}
withWhole, withDetails := plain, plain
withWhole.Whole = "e, whole"
withDetails.Details = "fingerprint 1234"
if withWhole.Digest() == plain.Digest() || withDetails.Digest() == plain.Digest() || withWhole.Digest() == withDetails.Digest() {
t.Error("Whole or Details left the digest the same")
}
both := withWhole
both.Details = "fingerprint 1234"
changed := both
changed.Whole += "!"
if changed.Digest() == both.Digest() {
t.Error("changing Whole beside Details left the digest the same")
}
// A field added to Ask or Option without being added to Digest fails here.
if n := reflect.TypeOf(Ask{}).NumField(); n != 11 {
t.Errorf("Ask has %d fields, and Digest covers 11: add the new one to Digest and to this test", n)
}
if n := reflect.TypeOf(Option{}).NumField(); n != 5 {
t.Errorf("Option has %d fields, and Digest covers 5: add the new one to Digest and to this test", n)
}
// The same instant in another zone is the same ask.
z := base
z.Expires = z.Expires.In(time.FixedZone("x", 3600))
if z.Digest() != base.Digest() {
t.Error("the expiry's zone changed the digest")
}
}
// An ask that says no expiry is answered by no warrant (the confirmation review of 2026-10-09): nothing could
// show the answer was in time.
func TestAWarrantForAnAskWithNoExpiryIsRefused(t *testing.T) {
a := held()
a.Expires = time.Time{}
w := Warrant{Ask: "d-1", Asker: "mesh-delivery", Outcome: OutcomeChosen, Option: "release", Label: "Release",
Level: Approve, By: &Person{Who: Operator, Kind: "telegram", Identity: "42"}, AskDigest: a.Digest(),
At: now.Add(time.Minute)}
if _, err := w.For("mesh-delivery", a); err == nil {
t.Error("a warrant for an ask with no expiry was taken")
}
}
+59
View File
@@ -0,0 +1,59 @@
package stdio
import (
"reflect"
"regexp"
"sync"
"unsafe"
)
// Unproven is the caller of a call the runtime named no caller for: one that arrived on the subject that names
// none, or from a runtime that names none (novox/hq issue 365). Said as a word, never left empty, so a record
// shows it was not proven.
const Unproven = "unproven"
// MetaCaller is where in a `tools/call`'s `_meta` the runtime names the caller: the bus user that published the
// call, which the runtime takes from the subject the call arrived on — that subject's last token, which the
// bus lets each user publish with its own name alone (novox/hq issue 365, by ADR 0259 §3's precedent). The
// runtime writes `_meta`; a caller writes only `arguments`, so no caller can name another.
const MetaCaller = "mesh/caller"
// busUser is the shape of a bus user's name: `<node>.<module>`, `person.<name>`, `controller` — names whose
// parts are safe in a subject. Anything else the runtime named is not a caller and reads as Unproven.
var busUser = regexp.MustCompile(`^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$`)
// calls holds the caller of every call while its tool runs, by the arguments map that call was handed.
var calls sync.Map // unsafe.Pointer → string
func argsKey(args map[string]any) unsafe.Pointer {
return reflect.ValueOf(args).UnsafePointer()
}
// CallerOf is who called the tool that was handed args, as the runtime proved it: the bus user that
// published the call, or Unproven. Read from the runtime, never from the arguments' contents — a `caller`
// argument names nobody. Valid while the tool runs; arguments no call was handed have no caller.
func CallerOf(args map[string]any) string {
if args == nil {
return Unproven
}
if c, ok := calls.Load(argsKey(args)); ok {
return c.(string)
}
return Unproven
}
// callerIn is the caller a `tools/call`'s `_meta` names, or Unproven.
func callerIn(meta map[string]any) string {
if s, ok := meta[MetaCaller].(string); ok && busUser.MatchString(s) {
return s
}
return Unproven
}
// runAs runs a tool with the caller held for its arguments for as long as it runs.
func runAs(t Tool, caller string, args map[string]any) (any, error) {
key := argsKey(args)
calls.Store(key, caller)
defer calls.Delete(key)
return t.Run(args)
}
+105
View File
@@ -0,0 +1,105 @@
package stdio
import (
"bufio"
"encoding/json"
"io"
"testing"
"time"
)
// callWith serves one tool that answers the caller CallerOf reads from its arguments, sends it one tools/call
// with the params given, and returns the caller it answered.
func callWith(t *testing.T, params map[string]any) string {
t.Helper()
inR, inW := io.Pipe()
outR, outW := io.Pipe()
go func() {
_ = ServeOn("tracker", []Tool{{Name: "who", Run: func(args map[string]any) (any, error) {
return map[string]any{"caller": CallerOf(args)}, nil
}}}, inR, outW)
}()
defer inW.Close()
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params})
_, _ = inW.Write(append(b, '\n'))
lines := bufio.NewScanner(outR)
done := make(chan string, 1)
go func() {
if lines.Scan() {
var m struct {
Result struct {
Content []struct {
Text string `json:"text"`
} `json:"content"`
} `json:"result"`
}
_ = json.Unmarshal(lines.Bytes(), &m)
var answer struct {
Caller string `json:"caller"`
}
if len(m.Result.Content) > 0 {
_ = json.Unmarshal([]byte(m.Result.Content[0].Text), &answer)
}
done <- answer.Caller
}
}()
select {
case got := <-done:
return got
case <-time.After(3 * time.Second):
t.Fatal("the bundle did not answer the call")
return ""
}
}
// **A tool reads its caller from the runtime, never from the call's arguments** (novox/hq issue 365): the
// runtime names the caller it took from the subject the call arrived on in the call's `_meta`, and CallerOf
// hands it to the tool by the arguments the tool was given.
func TestAToolReadsTheCallerTheRuntimeNamed(t *testing.T) {
got := callWith(t, map[string]any{"name": "who", "arguments": map[string]any{"title": "x"},
"_meta": map[string]any{MetaCaller: "shanks.node-tools"}})
if got != "shanks.node-tools" {
t.Fatalf("the tool read caller %q, want the one the runtime named", got)
}
}
// A caller named in the arguments is not the caller: an argument is the caller's to write.
func TestACallerInTheArgumentsIsNeverTheCaller(t *testing.T) {
got := callWith(t, map[string]any{"name": "who", "arguments": map[string]any{"caller": "novox.node-tools",
"_meta": map[string]any{MetaCaller: "novox.node-tools"}, MetaCaller: "novox.node-tools"}})
if got != Unproven {
t.Fatalf("a caller the arguments claimed was read as %q, want %q", got, Unproven)
}
got = callWith(t, map[string]any{"name": "who", "arguments": map[string]any{"caller": "novox.node-tools"},
"_meta": map[string]any{MetaCaller: "shanks.node-tools"}})
if got != "shanks.node-tools" {
t.Fatalf("with a caller in the arguments the tool read %q, want the runtime's", got)
}
}
// A runtime that names no caller — one from before issue 365, or a call on the subject that names none — is
// said as Unproven, explicitly; a caller that is not a bus user's name is Unproven too.
func TestACallTheRuntimeNamedNoCallerForIsUnproven(t *testing.T) {
for _, params := range []map[string]any{
{"name": "who", "arguments": map[string]any{}},
{"name": "who"},
{"name": "who", "arguments": map[string]any{}, "_meta": map[string]any{}},
{"name": "who", "arguments": map[string]any{}, "_meta": map[string]any{MetaCaller: ""}},
{"name": "who", "arguments": map[string]any{}, "_meta": map[string]any{MetaCaller: "a b"}},
{"name": "who", "arguments": map[string]any{}, "_meta": map[string]any{MetaCaller: 7}},
} {
if got := callWith(t, params); got != Unproven {
t.Errorf("%v: the tool read caller %q, want %q", params, got, Unproven)
}
}
}
// Arguments the runtime never handed a tool have no caller.
func TestArgumentsOfNoCallHaveNoCaller(t *testing.T) {
if got := CallerOf(map[string]any{"x": 1}); got != Unproven {
t.Fatalf("CallerOf of a map no call was given answered %q", got)
}
if got := CallerOf(nil); got != Unproven {
t.Fatalf("CallerOf(nil) answered %q", got)
}
}
+44 -7
View File
@@ -24,9 +24,13 @@ import (
// address (ADR 0272 §3).
const Socket = "/run/nox-mesh-host/cli.sock"
// MaxRequest bounds what the node-engine reads of a request. A command line is a few hundred bytes; settings given
// inline are a few kilobytes.
const MaxRequest = 64 << 10
// MaxStdin bounds the standard input mesh-cli carries for a line: a secret, a key, a settings file — kilobytes. More
// is refused by mesh-cli before anything is asked, and by the node-engine and the controller again.
const MaxStdin = 64 << 10
// MaxRequest bounds what the node-engine reads of a request: a command line of a few hundred bytes, settings given
// inline of a few kilobytes, and standard input of at most MaxStdin, which JSON writes as base64 (4 bytes for every 3).
const MaxRequest = 64<<10 + MaxStdin*4/3 + 4
// MaxAnswer bounds what mesh-cli reads of an answer. The controller cuts what it runs to fit one bus message, and
// says so; this is the local bound above that.
@@ -36,9 +40,16 @@ const MaxAnswer = 16 << 20
// and a minute for the link on either side.
const AskWithin = 6 * time.Minute
// Request is what mesh-cli asks: the controller's command line, as words.
// Request is what mesh-cli asks: the controller's command line, as words, and what mesh-cli's own standard input
// held when it was not a terminal.
//
// **Stdin is for the controller's terminal alone** (novox/hq ADR 0259 §10, ADR 0272): a secret given with
// `secret accept … --from -`, so it never stands on a command line. The controller gives it to a line that runs as
// its terminal and refuses any other line that carries it; nobody keeps it — not the node-engine, not the
// controller's record of calls, not its journal.
type Request struct {
Line []string `json:"line"`
Line []string `json:"line"`
Stdin []byte `json:"stdin,omitempty"`
}
// Answer is what comes back: what the command printed, how it exited, and whether it ran as the controller's
@@ -87,6 +98,9 @@ func ReadRequest(r io.Reader) (Request, error) {
if len(req.Line) == 0 {
return Request{}, errors.New("the request names no command")
}
if len(req.Stdin) > MaxStdin {
return Request{}, fmt.Errorf("%w: standard input of more than %d bytes", ErrTooLong, MaxStdin)
}
return req, nil
}
@@ -102,9 +116,18 @@ func ReadAnswer(r io.Reader) (Answer, error) {
// Ask is mesh-cli's side: connect to the socket, ask, and wait for the answer within AskWithin or ctx.
func Ask(ctx context.Context, socket string, line []string) (Answer, error) {
return AskWith(ctx, socket, Request{Line: line})
}
// AskWith asks a whole request: a line, and the standard input it carries, at most MaxStdin.
func AskWith(ctx context.Context, socket string, req Request) (Answer, error) {
line := req.Line
if len(line) == 0 {
return Answer{}, errors.New("no command given")
}
if len(req.Stdin) > MaxStdin {
return Answer{}, fmt.Errorf("standard input is more than %d bytes, which mesh-cli does not carry; nothing was asked", MaxStdin)
}
ctx, cancel := context.WithTimeout(ctx, AskWithin)
defer cancel()
var d net.Dialer
@@ -116,8 +139,22 @@ func Ask(ctx context.Context, socket string, line []string) (Answer, error) {
if deadline, ok := ctx.Deadline(); ok {
_ = conn.SetDeadline(deadline)
}
if err := WriteRequest(conn, Request{Line: line}); err != nil {
return Answer{}, fmt.Errorf("asking the node-engine: %w", err)
if err := WriteRequest(conn, req); err != nil {
// The engine may have answered before it read the request — a refusal (busy, an unknown account) written
// and the connection closed — and the write then fails on the close. That answer is already waiting, and
// it says why where the write error says only that the pipe broke (novox/hq issue 444, found under issue
// 434). So read it, within the deadline the connection already has, and only when none came say the write.
// Only a refusal is taken: the request was never wholly written, so nothing can have run, and any other
// answer here is not one a correct engine gives — passing it on as success would hide the failure.
a, rerr := ReadAnswer(conn)
if rerr != nil {
return Answer{}, fmt.Errorf("asking the node-engine: %w; and no answer came (%v)", err, rerr)
}
if a.Refused == "" {
return Answer{}, fmt.Errorf("asking the node-engine: %w; and the answer that came is not a refusal, "+
"though the request was never wholly written", err)
}
return a, nil
}
a, err := ReadAnswer(conn)
if err != nil {
+36
View File
@@ -3,6 +3,7 @@ package cli
import (
"bytes"
"context"
"encoding/json"
"errors"
"net"
"path/filepath"
@@ -44,6 +45,17 @@ func TestARequestAndAnAnswerSurviveTheirRoundTrip(t *testing.T) {
// A request over the bound is refused, not read whole; one naming no command is refused.
func TestARequestOverTheBoundOrNamingNothingIsRefused(t *testing.T) {
long := Request{Line: []string{strings.Repeat("x", MaxRequest)}}
big := Request{Line: []string{"secret"}, Stdin: bytes.Repeat([]byte("s"), MaxStdin+1)}
var bb bytes.Buffer
if err := WriteRequest(&bb, big); err != nil {
t.Fatal(err)
}
if _, err := ReadRequest(&bb); !errors.Is(err, ErrTooLong) {
t.Fatalf("standard input over its bound was read: %v", err)
}
if _, err := AskWith(context.Background(), "/nonexistent.sock", big); err == nil || !strings.Contains(err.Error(), "nothing was asked") {
t.Fatalf("mesh-cli would ask with standard input over its bound: %v", err)
}
var b bytes.Buffer
if err := WriteRequest(&b, long); err != nil {
t.Fatal(err)
@@ -103,3 +115,27 @@ func TestAnUnknownOutcomeIsNotARefusal(t *testing.T) {
t.Fatalf("an unknown outcome with no call names one: %+v", b)
}
}
// Standard input up to its bound travels whole, beside the line: a secret given with --from -.
func TestStandardInputTravelsWithItsLine(t *testing.T) {
given := append(bytes.Repeat([]byte{0, 0xff, '\n', 'x'}, MaxStdin/4-1), "end"...)
var b bytes.Buffer
if err := WriteRequest(&b, Request{Line: []string{"secret", "accept", "anchor", "telegram", "telegram-token", "--from", "-"},
Stdin: given}); err != nil {
t.Fatal(err)
}
if b.Len() > MaxRequest {
t.Fatalf("a request with standard input at its bound is %d bytes, over MaxRequest %d", b.Len(), MaxRequest)
}
got, err := ReadRequest(&b)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got.Stdin, given) || got.Line[1] != "accept" {
t.Fatalf("standard input did not travel whole: %d bytes, want %d", len(got.Stdin), len(given))
}
none, _ := json.Marshal(Request{Line: []string{"status"}})
if strings.Contains(string(none), "stdin") {
t.Fatalf("a request without standard input says it has one: %s", none)
}
}
+123
View File
@@ -0,0 +1,123 @@
package cli
import (
"context"
"errors"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// anEngineThatClosesFirst listens like the node-engine before mesh-host#80: it writes its answer, if any, and
// closes without reading the request (novox/hq issue 434). It answers one connection.
func anEngineThatClosesFirst(t *testing.T, answer *Answer) string {
t.Helper()
socket := filepath.Join(t.TempDir(), "cli.sock")
l, err := net.Listen("unix", socket)
if err != nil {
t.Skipf("no unix socket here: %v", err)
}
t.Cleanup(func() { l.Close() })
go func() {
conn, err := l.Accept()
if err != nil {
return
}
if answer != nil {
_ = WriteAnswer(conn, *answer)
}
conn.Close()
}()
return socket
}
// aLineTheSocketCannotHold is a request larger than a unix socket buffers, so its write cannot finish before
// the engine reads it — and an engine that closes first makes it fail every time, not only when it loses a race.
func aLineTheSocketCannotHold() []string { return []string{"status", strings.Repeat("x", 4<<20)} }
// An engine that refuses and closes before reading the request is heard: its refusal reaches the caller, not
// the broken pipe its close left the client's write (novox/hq issue 444).
func TestARefusalWrittenBeforeTheRequestIsReadReachesTheCaller(t *testing.T) {
busy := Refusal("the node-engine is busy: too many lines at once")
socket := anEngineThatClosesFirst(t, &busy)
a, err := Ask(context.Background(), socket, aLineTheSocketCannotHold())
if err != nil {
t.Fatalf("the engine said %q and the caller heard: %v", busy.Refused, err)
}
if a.Refused != busy.Refused || a.Exit != 1 {
t.Fatalf("the engine said %q and the caller heard %+v", busy.Refused, a)
}
}
// When the write fails and no answer is waiting, the error says both: what failed, and that no answer came.
func TestAFailedWriteWithNoAnswerSaysBoth(t *testing.T) {
socket := anEngineThatClosesFirst(t, nil)
start := time.Now()
_, err := Ask(context.Background(), socket, aLineTheSocketCannotHold())
if err == nil {
t.Fatal("a request the engine never read, and never answered, came back without an error")
}
if !strings.Contains(err.Error(), "asking the node-engine") || !strings.Contains(err.Error(), "no answer came") {
t.Fatalf("the error does not say what failed and that no answer came: %v", err)
}
if waited := time.Since(start); waited > 30*time.Second {
t.Fatalf("waited %s on a connection the engine had closed", waited)
}
}
// After a failed write only a refusal is taken: nothing can have run, so an answer saying it ran and exited 0
// is an error, never a success (novox/hq issue 444).
func TestAnAnswerOtherThanARefusalAfterAFailedWriteIsAnError(t *testing.T) {
ran := Answer{Exit: 0, Stdout: []byte("ok")}
socket := anEngineThatClosesFirst(t, &ran)
a, err := Ask(context.Background(), socket, aLineTheSocketCannotHold())
if err == nil {
t.Fatalf("a request never wholly written came back as success: %+v", a)
}
if !strings.Contains(err.Error(), "not a refusal") {
t.Fatalf("the error does not say the answer was not a refusal: %v", err)
}
}
// Reading after a failed write never waits longer than the ask already allowed: a peer that never reads and
// never answers is given up on at the context's deadline, not later (novox/hq issue 444).
func TestAFailedWriteWaitsNoLongerThanTheDeadline(t *testing.T) {
socket := filepath.Join(t.TempDir(), "cli.sock")
l, err := net.Listen("unix", socket)
if err != nil {
t.Skipf("no unix socket here: %v", err)
}
t.Cleanup(func() { l.Close() })
held := make(chan net.Conn, 1)
go func() {
conn, err := l.Accept()
if err != nil {
return
}
held <- conn // neither read nor answered, nor closed, until the test ends
}()
t.Cleanup(func() {
select {
case c := <-held:
c.Close()
default:
}
})
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
start := time.Now()
_, err = Ask(ctx, socket, aLineTheSocketCannotHold())
waited := time.Since(start)
if err == nil {
t.Fatal("a peer that never read nor answered gave no error")
}
if !errors.Is(err, os.ErrDeadlineExceeded) {
t.Fatalf("the error is not the deadline: %v", err)
}
if waited > 3*time.Second {
t.Fatalf("waited %s with a deadline of 1s", waited)
}
}
+191
View File
@@ -0,0 +1,191 @@
// Package health is the answer a module's health tool gives, and how the node-engine reads it (novox/hq ADR 0240
// rule 2, ADR 0283).
//
// A health tool answers one of three:
//
// - healthy: everything the module runs works;
// - unhealthy: something is wrong, said in Why;
// - waits: nothing is wrong but a part that cannot work until the operator gives something — one of the module's
// own secrets, or one of its settings. Each Wait names exactly one of them, the part, and what the operator
// gives, in words with no path, address or value.
//
// The answer keeps `healthy` beside `state`, so a node-engine older than ADR 0283 reads a wait as not healthy, as
// it did before. An answer without `state` is read from `healthy`.
//
// The module writes its answer with Healthy, Unhealthy or Waiting, and the node-engine reads it with Read. Read
// never trusts a shape it cannot check: a wait it cannot read makes the answer unhealthy, saying why.
package health
import (
"encoding/json"
"fmt"
"regexp"
"strings"
)
// The three states an answer says.
const (
StateHealthy = "healthy"
StateUnhealthy = "unhealthy"
StateWaits = "waits"
)
// Answer is a health tool's answer.
type Answer struct {
// State is healthy, unhealthy or waits.
State string `json:"state"`
// Healthy is State == healthy, kept for a reader older than State.
Healthy bool `json:"healthy"`
// Why is the answer in one or more plain sentences.
Why string `json:"why"`
// Waits is what the module waits for, when State is waits; and, beside a fault, what it also waits for.
Waits []Wait `json:"waits,omitempty"`
}
// Wait is one thing a module waits for the operator to give: exactly one of Secret and Setting.
type Wait struct {
// Part is what waits, in words: "the source games".
Part string `json:"part"`
// Secret is one of the module's own secrets, by name (a member of a secret family by its full name).
Secret string `json:"secret,omitempty"`
// Setting is one of the module's settings, by name.
Setting string `json:"setting,omitempty"`
// What is what the operator gives, in words: "the password of the source games".
What string `json:"what"`
}
// Healthy is a healthy answer.
func Healthy(why string) Answer {
return Answer{State: StateHealthy, Healthy: true, Why: why}
}
// Unhealthy is an unhealthy answer. Waits may be given beside the fault: they are said, and excuse nothing.
func Unhealthy(why string, waits ...Wait) Answer {
return Answer{State: StateUnhealthy, Why: why, Waits: waits}
}
// Waiting is an answer that says nothing is wrong but what the operator has yet to give. With no wait it is
// unhealthy: a module that waits names what for.
func Waiting(why string, waits ...Wait) Answer {
if len(waits) == 0 {
return Unhealthy(orSaid(why, "it says it waits") + " (and names nothing it waits for)")
}
for _, w := range waits {
if err := w.Check(); err != nil {
return Unhealthy(orSaid(why, "it says it waits") + " (" + err.Error() + ")")
}
}
return Answer{State: StateWaits, Why: why, Waits: waits}
}
// name is a secret's or a setting's name: what a manifest may declare.
var name = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
// looksLikeAddress finds what the operator's words never carry: a URL, an IPv4 or IPv6 address, a host and port, a
// path (absolute, from a home or relative, on its own or after a bracket or a quote), a UNC path or a drive path.
// It cannot find a value typed in plain words ("the password hunter2"): a module never puts one there, and the
// words are its own, not the operator's.
var looksLikeAddress = regexp.MustCompile(strings.Join([]string{
`://`,
`\b[0-9]{1,3}(\.[0-9]{1,3}){3}\b`,
`[0-9A-Fa-f]{0,4}::[0-9A-Fa-f]{0,4}`,
`\b[0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){3,}\b`,
`\b[A-Za-z0-9.-]+:[0-9]{1,5}\b`,
`(^|[\s(\[{"'\x60])[~.]{0,2}/`,
`\\\\`,
`\b[A-Za-z]:\\`,
}, "|"))
// Check says why a wait cannot be read, or nil.
func (w Wait) Check() error {
switch {
case w.Secret != "" && w.Setting != "":
return fmt.Errorf("a wait names both the secret %q and the setting %q; it names one", w.Secret, w.Setting)
case w.Secret == "" && w.Setting == "":
return fmt.Errorf("a wait names neither a secret nor a setting")
case w.Secret != "" && !name.MatchString(w.Secret):
return fmt.Errorf("a wait names the secret %q, which is not a name", w.Secret)
case w.Setting != "" && !name.MatchString(w.Setting):
return fmt.Errorf("a wait names the setting %q, which is not a name", w.Setting)
case strings.TrimSpace(w.What) == "":
return fmt.Errorf("a wait for %s does not say what the operator gives", w.Names())
case strings.TrimSpace(w.Part) == "":
return fmt.Errorf("a wait for %s does not say which part waits", w.Names())
}
for _, words := range []string{w.What, w.Part} {
if strings.ContainsAny(words, "\n\r") {
return fmt.Errorf("a wait for %s says more than one line", w.Names())
}
if looksLikeAddress.MatchString(words) {
return fmt.Errorf("a wait for %s says a path or an address, which the operator's words never carry", w.Names())
}
}
return nil
}
// Names is what the wait names, as "the secret x" or "the setting y".
func (w Wait) Names() string {
if w.Secret != "" {
return "the secret " + w.Secret
}
if w.Setting != "" {
return "the setting " + w.Setting
}
return "nothing"
}
// Read reads a health tool's result. An answer it cannot read at all is an error; an answer whose wait it cannot
// read is unhealthy, saying why, so a malformed wait never excuses anything.
func Read(result []byte) (Answer, error) {
var a Answer
if err := json.Unmarshal(result, &a); err != nil {
return Answer{}, fmt.Errorf("it answered something other than healthy or not: %w", err)
}
switch a.State {
case "":
if a.Healthy {
a.State = StateHealthy
} else {
a.State = StateUnhealthy
}
case StateHealthy:
if !a.Healthy {
return Unhealthy(fmt.Sprintf("it answered the state healthy and healthy false, which contradict each other (%s)",
orSaid(a.Why, "and said nothing more"))), nil
}
// A healthy module waits for nothing: a wait beside healthy is a contradiction, and is dropped.
a.Waits = nil
case StateUnhealthy:
a.Healthy = false
case StateWaits:
a.Healthy = false
if len(a.Waits) == 0 {
return Unhealthy(orSaid(a.Why, "it says it waits") + " (and names nothing it waits for)"), nil
}
for _, w := range a.Waits {
if err := w.Check(); err != nil {
return Unhealthy(orSaid(a.Why, "it says it waits") + " (" + err.Error() + ")"), nil
}
}
default:
return Unhealthy(fmt.Sprintf("it answered the state %q, which is none of healthy, unhealthy or waits", a.State)), nil
}
if a.State != StateWaits {
// Waits beside a fault are said and excuse nothing; one that cannot be read is dropped, not believed.
var kept []Wait
for _, w := range a.Waits {
if w.Check() == nil {
kept = append(kept, w)
}
}
a.Waits = kept
}
return a, nil
}
func orSaid(s, otherwise string) string {
if strings.TrimSpace(s) == "" {
return otherwise
}
return s
}
+150
View File
@@ -0,0 +1,150 @@
package health
import (
"encoding/json"
"strings"
"testing"
)
func roundTrip(t *testing.T, a Answer) Answer {
t.Helper()
b, err := json.Marshal(a)
if err != nil {
t.Fatal(err)
}
got, err := Read(b)
if err != nil {
t.Fatal(err)
}
return got
}
var password = Wait{Part: "the source games", Secret: "smb-password-games", What: "the password of the source games"}
func TestEachConstructorSaysItsStateAndKeepsHealthyForAnOlderReader(t *testing.T) {
for _, c := range []struct {
a Answer
state string
healthy bool
}{
{Healthy("all armed"), StateHealthy, true},
{Unhealthy("the share is unreachable"), StateUnhealthy, false},
{Waiting("the source games waits for its password", password), StateWaits, false},
} {
b, _ := json.Marshal(c.a)
var old struct {
Healthy bool `json:"healthy"`
Why string `json:"why"`
}
if err := json.Unmarshal(b, &old); err != nil || old.Healthy != c.healthy || old.Why == "" {
t.Fatalf("an older reader of %s reads %+v (%v)", b, old, err)
}
if got := roundTrip(t, c.a); got.State != c.state || got.Healthy != c.healthy {
t.Fatalf("%s read as %+v", b, got)
}
}
}
func TestAWaitIsReadWithWhatItNames(t *testing.T) {
got := roundTrip(t, Waiting("waits", password, Wait{Part: "the source games", Setting: "smb-users", What: "the username of the source games"}))
if got.State != StateWaits || len(got.Waits) != 2 || got.Waits[0].Secret != "smb-password-games" || got.Waits[1].Setting != "smb-users" {
t.Fatalf("read as %+v", got)
}
}
func TestAnAnswerWithoutStateIsReadFromHealthy(t *testing.T) {
for raw, want := range map[string]string{`{"healthy":true,"why":"ok"}`: StateHealthy, `{"healthy":false,"why":"down"}`: StateUnhealthy} {
got, err := Read([]byte(raw))
if err != nil || got.State != want {
t.Fatalf("%s read as %+v, %v", raw, got, err)
}
}
}
func TestAWaitThatCannotBeReadIsUnhealthyAndSaysWhy(t *testing.T) {
for name, c := range map[string]struct {
w []Wait
says string
}{
"no wait": {nil, "names nothing"},
"neither": {[]Wait{{Part: "p", What: "w"}}, "neither a secret nor a setting"},
"both": {[]Wait{{Part: "p", Secret: "a", Setting: "b", What: "w"}}, "both"},
"not a name": {[]Wait{{Part: "p", Secret: "Smb Password", What: "w"}}, "not a name"},
"no what": {[]Wait{{Part: "p", Secret: "a"}}, "does not say what"},
"no part": {[]Wait{{Secret: "a", What: "w"}}, "which part"},
"two lines": {[]Wait{{Part: "p", Secret: "a", What: "the password\nhunter2"}}, "more than one line"},
"an address": {[]Wait{{Part: "p", Secret: "a", What: "the password of 192.0.2.76"}}, "path or an address"},
"a url": {[]Wait{{Part: "p", Secret: "a", What: "the password of smb://host/share"}}, "path or an address"},
"a path": {[]Wait{{Part: "the source at /mnt/games", Secret: "a", What: "the password"}}, "path or an address"},
} {
b, _ := json.Marshal(Answer{State: StateWaits, Why: "it waits", Waits: c.w})
got, err := Read(b)
if err != nil {
t.Fatalf("%s: %v", name, err)
}
if got.State != StateUnhealthy || got.Healthy || !strings.Contains(got.Why, c.says) {
t.Fatalf("%s: read as %+v, want unhealthy saying %q", name, got, c.says)
}
}
}
func TestAnUnknownStateIsUnhealthy(t *testing.T) {
got, err := Read([]byte(`{"state":"fine","healthy":true}`))
if err != nil || got.State != StateUnhealthy || got.Healthy {
t.Fatalf("read as %+v, %v", got, err)
}
}
func TestWaitsBesideAFaultAreSaidAndExcuseNothing(t *testing.T) {
got := roundTrip(t, Unhealthy("the share is unreachable", password, Wait{Part: "p", What: "w"}))
if got.State != StateUnhealthy || len(got.Waits) != 1 {
t.Fatalf("read as %+v: the readable wait is kept, the other dropped, the state stays unhealthy", got)
}
if h := roundTrip(t, Answer{State: StateHealthy, Healthy: true, Why: "ok", Waits: []Wait{password}}); len(h.Waits) != 0 {
t.Fatalf("a healthy answer kept its waits: %+v", h)
}
}
func TestWaitingWithNothingIsUnhealthy(t *testing.T) {
if a := Waiting("it waits"); a.State != StateUnhealthy {
t.Fatalf("Waiting with no wait is %+v", a)
}
}
func TestNotAnAnswerIsAnError(t *testing.T) {
if _, err := Read([]byte(`"yes"`)); err == nil {
t.Fatal("a string read as an answer")
}
}
func TestEveryFormOfPathOrAddressIsRefused(t *testing.T) {
for _, words := range []string{
"the source (/mnt/games)", `the source "/mnt/games"`, "the folder ~/games", "the folder ./games",
"2001:db8::1", "fe80::1%eth0", "2001:0db8:0000:0000:0000:0000:0000:0001", "nas.lan:445", "192.0.2.7:445",
`\\nas\games`, `C:\Users\x`, "smb://nas/games", "198.51.100.4",
} {
w := Wait{Part: "the source games", Secret: "smb-password-games", What: "the password of " + words}
if err := w.Check(); err == nil {
t.Errorf("%q passed as words for the operator", words)
}
}
for _, words := range []string{"the password of the source games", "the username of the source games-2", "the API key, issued by the vendor"} {
w := Wait{Part: "the source games", Secret: "smb-password-games", What: words}
if err := w.Check(); err != nil {
t.Errorf("%q refused: %v", words, err)
}
}
}
func TestHealthyStateWithHealthyFalseIsUnhealthy(t *testing.T) {
got, err := Read([]byte(`{"state":"healthy","healthy":false,"why":"x"}`))
if err != nil || got.State != StateUnhealthy || !strings.Contains(got.Why, "contradict") {
t.Fatalf("read as %+v, %v", got, err)
}
}
func TestWaitingChecksItsWaits(t *testing.T) {
if a := Waiting("it waits", Wait{Part: "p", What: "w"}); a.State != StateUnhealthy || !strings.Contains(a.Why, "neither") {
t.Fatalf("Waiting with a malformed wait is %+v", a)
}
}
+123
View File
@@ -0,0 +1,123 @@
package stdio
import (
"encoding/json"
"fmt"
"time"
)
// Log — a module's record of operations on the bus, kept as long as the log is (novox/hq ADR 0297). Not the
// current value: that is state, and a log's state is its fold. Each entry is one operation on one key, its
// sequence in the log is its identity, and the order of the log is the order of the operations. A module
// declares each log it owns in its manifest (`logs`) and names it here as it named it there; a log is its
// owner's alone, and the runtime refuses, with the reason, one it did not issue.
// LogEntry is one operation on one key, as the log holds it.
type LogEntry struct {
Sequence uint64 `json:"sequence"`
Key string `json:"key"`
Value json.RawMessage `json:"value"`
At time.Time `json:"at"`
}
// LogPage is one page of a read: its entries, in order, the sequence to read on from (0 when nothing
// follows) and the log's last sequence when it was read.
type LogPage struct {
Entries []LogEntry `json:"entries"`
Next uint64 `json:"next"`
Last uint64 `json:"last"`
}
// LogInfo is how much a log holds: its entries and bytes, its cap in bytes, and its first and last sequence.
type LogInfo struct {
Entries uint64 `json:"entries"`
Bytes uint64 `json:"bytes"`
MaxBytes uint64 `json:"max_bytes"`
First uint64 `json:"first"`
Last uint64 `json:"last"`
}
// KeptLog is one log this module owns.
type KeptLog struct{ name string }
// Log is a log this module owns, by its local name.
func Log(name string) KeptLog { return KeptLog{name: name} }
const logTimeout = 30 * time.Second
func (l KeptLog) ask(verb string, params map[string]any) (json.RawMessage, error) {
c, err := live()
if err != nil {
return nil, err
}
params["log"] = l.name
return c.ask("mesh/log."+verb, params, logTimeout)
}
func (l KeptLog) append(params map[string]any) (uint64, error) {
raw, err := l.ask("append", params)
if err != nil {
return 0, err
}
var appended struct {
Sequence uint64 `json:"sequence"`
}
return appended.Sequence, json.Unmarshal(raw, &appended)
}
// Append writes an entry for key, whatever came before it, and returns its sequence. A key is one or more
// names of letters, digits, `-` and `_`, joined by `.`; a value is JSON of at most 256 KiB. A full log
// refuses the entry: it never drops an older one to make room.
func (l KeptLog) Append(key string, value any) (uint64, error) {
return l.append(map[string]any{"key": key, "value": value})
}
// AppendAt writes an entry for key only if the key's last entry is still at expect — the sequence the caller
// read, 0 for a key with no entry yet — and returns its sequence. When another entry for the key came in
// between, nothing is written and the error is ErrChanged, as for a lost State update: read again and
// decide again.
func (l KeptLog) AppendAt(key string, value any, expect uint64) (uint64, error) {
return l.append(map[string]any{"key": key, "value": value, "expect": expect})
}
// Read is the entries from the sequence from on, oldest first, at most limit of them (0 is the runtime's
// page, 100; it gives at most 1000). keys narrows it: a key, with `*` for one name and `>` for the rest;
// empty is every key. Read on from the page's Next until it is 0.
func (l KeptLog) Read(from uint64, keys string, limit int) (*LogPage, error) {
if limit < 0 {
return nil, fmt.Errorf("a read of %s asks for at least no entries: limit %d", l.name, limit)
}
params := map[string]any{"from": from}
if keys != "" {
params["keys"] = keys
}
if limit > 0 {
params["limit"] = limit
}
raw, err := l.ask("read", params)
if err != nil {
return nil, err
}
var p LogPage
return &p, json.Unmarshal(raw, &p)
}
// Last is a key's last entry, or nil when the key has none.
func (l KeptLog) Last(key string) (*LogEntry, error) {
raw, err := l.ask("last", map[string]any{"key": key})
if err != nil || len(raw) == 0 || string(raw) == "null" {
return nil, err
}
var e LogEntry
return &e, json.Unmarshal(raw, &e)
}
// Info is how much the log holds and how much it may.
func (l KeptLog) Info() (*LogInfo, error) {
raw, err := l.ask("info", map[string]any{})
if err != nil {
return nil, err
}
var i LogInfo
return &i, json.Unmarshal(raw, &i)
}
+354
View File
@@ -0,0 +1,354 @@
package stdio
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"sync"
"testing"
"time"
)
// logRuntime is the runtime's side of mesh/log.append, read, last and info as the bus does them (novox/hq
// ADR 0297): one sequence per entry across the log, an append with expect refused unless the key's last
// entry is still at it (0 for a key with none), that refusal answered with CodeChanged as a lost state
// update is, and a read paged by its limit with the sequence to read on from. asked keeps every ask's
// method and params, as the bundle sent them.
type logRuntime struct {
mu sync.Mutex
entries []LogEntry
asked []message
}
func (r *logRuntime) last(key string) uint64 {
for i := len(r.entries) - 1; i >= 0; i-- {
if r.entries[i].Key == key {
return r.entries[i].Sequence
}
}
return 0
}
// matches is a key pattern as the runtime reads it: `*` one name, `>` the rest.
func matches(pattern, key string) bool {
if pattern == "" {
return true
}
p, k := strings.Split(pattern, "."), strings.Split(key, ".")
for i, t := range p {
if t == ">" {
return len(k) > i
}
if i >= len(k) || (t != "*" && t != k[i]) {
return false
}
}
return len(p) == len(k)
}
func (r *logRuntime) answer(m message) map[string]any {
var p struct {
Log string `json:"log"`
Key string `json:"key"`
Value json.RawMessage `json:"value"`
Expect *uint64 `json:"expect"`
From uint64 `json:"from"`
Keys string `json:"keys"`
Limit int `json:"limit"`
}
_ = json.Unmarshal(m.Params, &p)
r.mu.Lock()
defer r.mu.Unlock()
r.asked = append(r.asked, m)
if p.Log != "changes" {
return map[string]any{"error": map[string]any{"code": -32000, "message": "issues was issued no log " + p.Log}}
}
switch strings.TrimPrefix(m.Method, "mesh/log.") {
case "append":
if p.Expect != nil && r.last(p.Key) != *p.Expect {
return map[string]any{"error": map[string]any{"code": CodeChanged, "message": p.Key + ": the key was written by another writer first"}}
}
seq := uint64(len(r.entries)) + 1
r.entries = append(r.entries, LogEntry{Sequence: seq, Key: p.Key, Value: p.Value,
At: time.Date(2026, 10, 11, 18, 0, int(seq), 0, time.UTC)})
return map[string]any{"result": map[string]any{"sequence": seq}}
case "read":
limit := p.Limit
if limit == 0 {
limit = 100
}
page := map[string]any{"entries": []LogEntry{}, "next": 0, "last": len(r.entries)}
var got []LogEntry
for _, e := range r.entries {
if e.Sequence < p.From || !matches(p.Keys, e.Key) {
continue
}
if len(got) == limit {
page["next"] = e.Sequence
break
}
got = append(got, e)
}
if got != nil {
page["entries"] = got
}
return map[string]any{"result": page}
case "last":
seq := r.last(p.Key)
if seq == 0 {
return map[string]any{"result": nil}
}
return map[string]any{"result": r.entries[seq-1]}
case "info":
var bytes int
for _, e := range r.entries {
bytes += len(e.Value)
}
info := map[string]any{"entries": len(r.entries), "bytes": bytes, "max_bytes": 1 << 30, "first": 0, "last": len(r.entries)}
if len(r.entries) > 0 {
info["first"] = 1
}
return map[string]any{"result": info}
}
return map[string]any{"error": map[string]any{"code": -32601, "message": "no " + m.Method}}
}
// logging serves a bundle whose one tool, "log", runs run against r, answering each mesh/log ask beside
// the loop as the runtime does. It returns what the tool answered.
func logging(t *testing.T, r *logRuntime, run func() (any, error)) map[string]any {
t.Helper()
t.Setenv(ServedAs, "issues")
inR, inW := io.Pipe()
outR, outW := io.Pipe()
go func() {
_ = ServeOn("", []Tool{{Name: "log", Run: func(map[string]any) (any, error) { return run() }}}, inR, outW)
}()
var wmu sync.Mutex
send := func(m map[string]any) {
m["jsonrpc"] = "2.0"
b, _ := json.Marshal(m)
wmu.Lock()
defer wmu.Unlock()
_, _ = inW.Write(append(b, '\n'))
}
done := make(chan map[string]any, 1)
go func() {
lines := bufio.NewScanner(outR)
lines.Buffer(make([]byte, 1<<20), 1<<24)
for lines.Scan() {
var m message
if json.Unmarshal(lines.Bytes(), &m) != nil {
continue
}
if strings.HasPrefix(m.Method, "mesh/log.") {
go func(m message) {
a := r.answer(m)
a["id"] = m.ID
send(a)
}(m)
continue
}
var answer map[string]any
_ = json.Unmarshal(lines.Bytes(), &answer)
if answer["id"] == float64(1) {
done <- answer
return
}
}
}()
send(map[string]any{"id": 1, "method": "tools/call", "params": map[string]any{"name": "log"}})
t.Cleanup(func() { _ = inW.Close() })
select {
case a := <-done:
return a
case <-time.After(10 * time.Second):
t.Fatal("the bundle did not answer")
return nil
}
}
// params is what the bundle sent with its n-th ask, and the ask's method.
func (r *logRuntime) params(t *testing.T, n int) (string, map[string]any) {
t.Helper()
r.mu.Lock()
defer r.mu.Unlock()
if n >= len(r.asked) {
t.Fatalf("the bundle asked %d times, not %d", len(r.asked), n+1)
}
var p map[string]any
_ = json.Unmarshal(r.asked[n].Params, &p)
return r.asked[n].Method, p
}
// A bundle appends to, reads, and measures its log through the runtime (novox/hq ADR 0297): each verb is
// asked as mesh/log.<verb> naming the log, its answer is handed back whole, a key with no entry is nil,
// and a read pages on from Next until it is 0.
func TestABundleKeepsALogThroughTheRuntime(t *testing.T) {
r := &logRuntime{}
var (
first, second, third uint64
pages []*LogPage
last, none *LogEntry
info *LogInfo
narrowed *LogPage
)
got := logging(t, r, func() (any, error) {
changes := Log("changes")
var err error
if first, err = changes.Append("401", map[string]any{"op": "opened", "by": "fix@g14"}); err != nil {
return nil, err
}
if second, err = changes.Append("402", map[string]any{"op": "opened"}); err != nil {
return nil, err
}
if third, err = changes.AppendAt("401", map[string]any{"op": "moved", "to": "fixing"}, first); err != nil {
return nil, err
}
for _, k := range []string{"403", "404", "405"} {
if _, err = changes.Append(k, map[string]any{"op": "opened"}); err != nil {
return nil, err
}
}
for from := uint64(1); ; {
p, err := changes.Read(from, "", 2)
if err != nil {
return nil, err
}
pages = append(pages, p)
if p.Next == 0 {
break
}
from = p.Next
}
if narrowed, err = changes.Read(0, "401", 0); err != nil {
return nil, err
}
if last, err = changes.Last("401"); err != nil {
return nil, err
}
if none, err = changes.Last("999"); err != nil {
return nil, err
}
info, err = changes.Info()
return "done", err
})
if out, isError := text(t, got); isError || out != `"done"` {
t.Fatalf("the tool answered %s", out)
}
if first != 1 || second != 2 || third != 3 {
t.Fatalf("appended at %d, %d, %d", first, second, third)
}
// Asked as the contract names them: the verb, the log, and only what was given.
method, p := r.params(t, 0)
if method != "mesh/log.append" || p["log"] != "changes" || p["key"] != "401" || p["value"].(map[string]any)["by"] != "fix@g14" {
t.Fatalf("an append asked %s %v", method, p)
}
if _, has := p["expect"]; has {
t.Fatalf("an Append without expect named one: %v", p)
}
if method, p = r.params(t, 2); method != "mesh/log.append" || p["expect"] != float64(1) {
t.Fatalf("an AppendAt asked %s %v", method, p)
}
if method, p = r.params(t, 6); method != "mesh/log.read" || p["from"] != float64(1) || p["limit"] != float64(2) || p["keys"] != nil {
t.Fatalf("a read asked %s %v", method, p)
}
// Paged two at a time through six entries: three pages, every entry once, in order.
if len(pages) != 3 {
t.Fatalf("read %d pages, not 3", len(pages))
}
var seqs []uint64
for _, pg := range pages {
if pg.Last != 6 {
t.Fatalf("a page said the last sequence is %d", pg.Last)
}
for _, e := range pg.Entries {
seqs = append(seqs, e.Sequence)
}
}
if fmt.Sprint(seqs) != "[1 2 3 4 5 6]" || pages[0].Next != 3 || pages[2].Next != 0 {
t.Fatalf("paged %v, next %d then %d", seqs, pages[0].Next, pages[2].Next)
}
if e := pages[1].Entries[0]; e.Key != "401" || string(e.Value) != `{"op":"moved","to":"fixing"}` ||
!e.At.Equal(time.Date(2026, 10, 11, 18, 0, 3, 0, time.UTC)) {
t.Fatalf("an entry read as %+v", e)
}
// Narrowed to a key, with the runtime's page: no limit sent.
method, p = r.params(t, 9)
if method != "mesh/log.read" || p["keys"] != "401" || p["limit"] != nil {
t.Fatalf("a narrowed read asked %s %v", method, p)
}
if len(narrowed.Entries) != 2 || narrowed.Entries[0].Sequence != 1 || narrowed.Entries[1].Sequence != 3 || narrowed.Next != 0 {
t.Fatalf("narrowed to 401: %+v", narrowed)
}
if last == nil || last.Sequence != 3 || last.Key != "401" {
t.Fatalf("the last of 401 is %+v", last)
}
if method, p = r.params(t, 10); method != "mesh/log.last" || p["key"] != "401" {
t.Fatalf("a last asked %s %v", method, p)
}
if none != nil {
t.Fatalf("a key with no entry has a last: %+v", none)
}
if info == nil || info.Entries != 6 || info.MaxBytes != 1<<30 || info.First != 1 || info.Last != 6 || info.Bytes == 0 {
t.Fatalf("the log's info is %+v", info)
}
if method, p = r.params(t, 12); method != "mesh/log.info" || p["log"] != "changes" || len(p) != 1 {
t.Fatalf("an info asked %s %v", method, p)
}
}
// An AppendAt on a stale expect is ErrChanged and writes nothing: another entry for the key came in
// between. Expect 0 is a key with no entry yet, and is ErrChanged once the key has one. A log not issued
// is refused with the runtime's reason, and is not ErrChanged.
func TestAnAppendAtAStaleSequenceIsErrChangedAndWritesNothing(t *testing.T) {
r := &logRuntime{}
var errs []error
got := logging(t, r, func() (any, error) {
changes := Log("changes")
read, err := changes.AppendAt("401", map[string]any{"op": "opened"}, 0)
if err != nil {
return nil, err
}
// Another writer is first.
if _, err := changes.Append("401", map[string]any{"op": "noted"}); err != nil {
return nil, err
}
_, stale := changes.AppendAt("401", map[string]any{"op": "moved"}, read)
_, again := changes.AppendAt("401", map[string]any{"op": "opened"}, 0)
_, other := Log("elsewhere").Append("401", map[string]any{})
errs = []error{stale, again, other}
return "done", nil
})
if out, isError := text(t, got); isError || out != `"done"` {
t.Fatalf("the tool answered %s", out)
}
if !errors.Is(errs[0], ErrChanged) || !errors.Is(errs[1], ErrChanged) {
t.Fatalf("a stale expect answered %v and %v, not ErrChanged", errs[0], errs[1])
}
if errs[2] == nil || errors.Is(errs[2], ErrChanged) || !strings.Contains(errs[2].Error(), "no log elsewhere") {
t.Fatalf("a log not issued answered %v", errs[2])
}
if len(r.entries) != 2 {
t.Fatalf("the log holds %d entries, not 2: a refused append wrote", len(r.entries))
}
}
// A read asking for fewer than no entries is refused before the runtime is asked.
func TestAReadOfANegativeLimitIsRefused(t *testing.T) {
r := &logRuntime{}
var err error
logging(t, r, func() (any, error) {
_, err = Log("changes").Read(0, "", -1)
return "done", nil
})
if err == nil || len(r.asked) != 0 {
t.Fatalf("a negative limit answered %v after %d asks", err, len(r.asked))
}
}
+153
View File
@@ -0,0 +1,153 @@
package stdio
import (
"encoding/json"
"strings"
"time"
)
// Seats that name their caller or their kind (novox/hq ADR 0259 §3): a module submits an accept or says an
// event under its own name or kind, takes a held seat's work, asks a proof and answers one, and reads a
// record a seat keeps for it. The runtime does each as the module, only as far as its membership lists,
// and refuses the rest with the reason.
// Work is one piece of a seat's work this bundle takes: the subject it was submitted on, its body, and the
// headers the submitter's runtime set (x-source is the submitting module, x-event-id its id).
type Work struct {
Worker string `json:"worker,omitempty"`
Subject string `json:"subject"`
Body json.RawMessage `json:"body"`
Headers map[string]string `json:"headers,omitempty"`
}
const seatTimeout = 30 * time.Second
// SeatPublish submits an accept, or says an event, on a seat, de-duplicated by id: the same id twice is
// one message. An empty id is the runtime's to make.
func SeatPublish(subject string, body any, id string) error {
c, err := live()
if err != nil {
return err
}
_, err = c.ask("mesh/seat.publish", map[string]any{"subject": subject, "body": body, "id": id}, seatTimeout)
return err
}
// SeatProve asks a proof — core request and reply, never kept — and returns its answer.
func SeatProve(subject string, body any) (json.RawMessage, error) {
c, err := live()
if err != nil {
return nil, err
}
return c.ask("mesh/seat.prove", map[string]any{"subject": subject, "body": body}, seatTimeout)
}
// SeatAnswer answers every proof on a subject (a pattern, `*` one token) with what handle returns.
func SeatAnswer(subject string, handle func(subject string, body json.RawMessage) (any, error)) error {
c, err := live()
if err != nil {
return err
}
c.mu.Lock()
c.provers[subject] = handle
c.mu.Unlock()
_, err = c.ask("mesh/seat.answer", map[string]any{"subject": subject}, seatTimeout)
return err
}
// SeatTake takes a held seat's work from a worker, handing each piece to handle: taken when it returns
// nil, offered again after an error. Make the work safe to do twice, or skip an x-event-id already done.
func SeatTake(worker string, handle func(Work) error) error {
c, err := live()
if err != nil {
return err
}
c.mu.Lock()
c.takers[worker] = handle
c.mu.Unlock()
_, err = c.ask("mesh/seat.take", map[string]any{"worker": worker}, seatTimeout)
return err
}
// SeatRecord reads one key of a record a seat keeps for this module, under its own name, or nil.
func SeatRecord(bucket, key string) (*StateEntry, error) {
c, err := live()
if err != nil {
return nil, err
}
raw, err := c.ask("mesh/seat.record", map[string]any{"bucket": bucket, "key": key}, seatTimeout)
if err != nil || len(raw) == 0 || string(raw) == "null" {
return nil, err
}
var e StateEntry
return &e, json.Unmarshal(raw, &e)
}
// KindHeld is one kind of a kinded bench and who holds it, with what it promises (novox/hq ADR 0259 §5).
type KindHeld struct {
Seat string `json:"seat"`
Kind string `json:"kind"`
Module string `json:"module"`
Node string `json:"node"`
Capabilities []string `json:"capabilities,omitempty"`
}
// Promises says whether this kind's claim declares a capability.
func (k KindHeld) Promises(capability string) bool {
for _, c := range k.Capabilities {
if c == capability {
return true
}
}
return false
}
// SeatKinds is every kind of the kinded benches this module uses or watches, as the controller issued
// them in its membership: the one account of which channel is which, never a channel's own word.
func SeatKinds() ([]KindHeld, error) {
c, err := live()
if err != nil {
return nil, err
}
raw, err := c.ask("mesh/seat.kinds", map[string]any{}, seatTimeout)
if err != nil {
return nil, err
}
var out []KindHeld
return out, json.Unmarshal(raw, &out)
}
// Create writes a key only when it has none, and returns the revision; a key that has one is refused.
func (s KeptState) Create(key string, value any) (uint64, error) {
return s.revisionOf(s.ask("create", map[string]any{"key": key, "value": value}))
}
// Update writes a key only when it is still at revision, and returns the new one; a key changed
// meanwhile is refused, so of two writers that read one value only the first writes.
func (s KeptState) Update(key string, value any, revision uint64) (uint64, error) {
return s.revisionOf(s.ask("update", map[string]any{"key": key, "value": value, "revision": revision}))
}
func (s KeptState) revisionOf(raw json.RawMessage, err error) (uint64, error) {
if err != nil {
return 0, err
}
var put struct {
Revision uint64 `json:"revision"`
}
return put.Revision, json.Unmarshal(raw, &put)
}
// subjectMatches is a subject against a pattern in the bus's wildcards: `*` one token, `>` the rest.
func subjectMatches(pattern, subject string) bool {
p, s := strings.Split(pattern, "."), strings.Split(subject, ".")
for i, part := range p {
if part == ">" {
return len(s) > i
}
if i >= len(s) || (part != "*" && part != s[i]) {
return false
}
}
return len(p) == len(s)
}
+98
View File
@@ -0,0 +1,98 @@
package stdio
import (
"bufio"
"encoding/json"
"errors"
"io"
"testing"
"time"
)
// novox/hq ADR 0259 §3: a bundle takes a seat's work and answers proofs through the runtime; a piece of
// work it fails is answered as an error, so the runtime offers it again, and a proof's error is said.
func TestABundleTakesWorkAndAnswersProofsThroughTheRuntime(t *testing.T) {
t.Setenv(ServedAs, "router")
inR, inW := io.Pipe()
outR, outW := io.Pipe()
taken := make(chan string, 4)
go func() {
_ = ServeOn("", []Tool{{Name: "start", Run: func(map[string]any) (any, error) {
if err := SeatTake("SEAT_OPERATOR_CHANNEL_worker", func(w Work) error {
taken <- w.Subject
if string(w.Body) == `{"fail":true}` {
return errors.New("not recorded")
}
return nil
}); err != nil {
return nil, err
}
if err := SeatAnswer("mesh.seat.intake.proof.code.*", func(subject string, body json.RawMessage) (any, error) {
if subject != "mesh.seat.intake.proof.code.telegram" {
return nil, errors.New("no such kind")
}
return map[string]any{"accepted": true}, nil
}); err != nil {
return nil, err
}
return map[string]any{}, nil
}}}, inR, outW)
}()
lines := bufio.NewScanner(outR)
next := func() map[string]any {
done := make(chan map[string]any, 1)
go func() {
if lines.Scan() {
var m map[string]any
_ = json.Unmarshal(lines.Bytes(), &m)
done <- m
}
}()
select {
case m := <-done:
return m
case <-time.After(3 * time.Second):
t.Fatal("the bundle said nothing")
return nil
}
}
send := func(m map[string]any) { b, _ := json.Marshal(m); _, _ = inW.Write(append(b, '\n')) }
send(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": map[string]any{"name": "start"}})
asked := next()
if asked["method"] != "mesh/seat.take" || asked["params"].(map[string]any)["worker"] != "SEAT_OPERATOR_CHANNEL_worker" {
t.Fatalf("the take was not asked of the runtime: %v", asked)
}
send(map[string]any{"jsonrpc": "2.0", "id": asked["id"], "result": map[string]any{}})
asked = next()
if asked["method"] != "mesh/seat.answer" {
t.Fatalf("the answer was not asked of the runtime: %v", asked)
}
send(map[string]any{"jsonrpc": "2.0", "id": asked["id"], "result": map[string]any{}})
next() // the tool's answer
send(map[string]any{"jsonrpc": "2.0", "id": 2, "method": "mesh/work", "params": map[string]any{"work": map[string]any{
"worker": "SEAT_OPERATOR_CHANNEL_worker", "subject": "mesh.seat.operator-channel.accept.ask.x", "body": map[string]any{"fail": true}}}})
if got := next(); got["error"] == nil {
t.Errorf("work the handler failed was answered as taken: %v", got)
}
send(map[string]any{"jsonrpc": "2.0", "id": 3, "method": "mesh/work", "params": map[string]any{"work": map[string]any{
"worker": "SEAT_OPERATOR_CHANNEL_worker", "subject": "mesh.seat.operator-channel.accept.ask.x", "body": map[string]any{}}}})
if got := next(); got["error"] != nil {
t.Errorf("work the handler took was answered as an error: %v", got)
}
send(map[string]any{"jsonrpc": "2.0", "id": 4, "method": "mesh/proof", "params": map[string]any{
"subject": "mesh.seat.intake.proof.code.telegram", "body": map[string]any{"code": "1"}}})
if got := next(); got["result"].(map[string]any)["accepted"] != true {
t.Errorf("the proof was answered %v", got)
}
send(map[string]any{"jsonrpc": "2.0", "id": 5, "method": "mesh/proof", "params": map[string]any{
"subject": "mesh.seat.intake.proof.code.desktop", "body": map[string]any{}}})
if got := next(); got["error"] == nil {
t.Errorf("a proof the handler refused was answered as accepted: %v", got)
}
if len(taken) != 2 {
t.Errorf("the handler was handed %d pieces of work, want 2", len(taken))
}
_ = inW.Close()
}
+72
View File
@@ -2,6 +2,8 @@ package stdio
import (
"encoding/json"
"errors"
"fmt"
"time"
)
@@ -29,6 +31,16 @@ type StateChange struct {
Current bool `json:"current"`
}
// StateRevision is one value a bucket still keeps for a key: what was written, at which revision, by which
// operation ("put" or "delete", whose value is null) and when (novox/hq ADR 0307).
type StateRevision struct {
Key string `json:"key"`
Value json.RawMessage `json:"value"`
Revision uint64 `json:"revision"`
Op string `json:"op"`
At time.Time `json:"at"`
}
// KeptState is one state this module keeps, or reads.
type KeptState struct{ name string }
@@ -56,6 +68,21 @@ func (s KeptState) Get(key string) (*StateEntry, error) {
return &e, json.Unmarshal(raw, &e)
}
// History is every value the bucket still keeps for key, oldest first — as many as the state declared it
// keeps, deletes included — and empty for a key it holds nothing for (novox/hq ADR 0307). A read, like Get:
// the owner's instances and its readers may ask it, and it writes nothing.
func (s KeptState) History(key string) ([]StateRevision, error) {
raw, err := s.ask("history", map[string]any{"key": key})
if err != nil {
return nil, err
}
revisions := []StateRevision{}
if len(raw) == 0 || string(raw) == "null" {
return revisions, nil
}
return revisions, json.Unmarshal(raw, &revisions)
}
// Put writes a key — the owner's instances only — and returns the revision written.
func (s KeptState) Put(key string, value any) (uint64, error) {
raw, err := s.ask("put", map[string]any{"key": key, "value": value})
@@ -74,6 +101,51 @@ func (s KeptState) Delete(key string) error {
return err
}
// Increment adds one to a counter kept at key and returns the number it now holds: one for a key with no
// value. Read, then written only if the key is still at the revision read (Create when it had none, Update
// when it had one), so of any number of writers each number is handed out once and no increment is lost.
// A write another writer won is read again and tried again, at most attempts times in all; past that the
// error is ErrChanged and nothing was counted. Any other error is returned at once, as is a value that is
// not a whole number (null included): nothing is ever reported counted that was not written. The reverse
// does not hold: an error that is not ErrChanged — a timeout above all — may come after the write landed, so
// that number may be spent and never handed out. A caller tolerates gaps, never a number handed out twice.
// Deleting the key starts the count again at one; a key whose numbers must stay unique is never deleted.
func (s KeptState) Increment(key string, attempts int) (uint64, error) {
if attempts < 1 {
return 0, fmt.Errorf("an increment of %s is tried at least once: %d attempts", key, attempts)
}
for i := 0; i < attempts; i++ {
e, err := s.Get(key)
if err != nil {
return 0, err
}
var next uint64 = 1
if e == nil {
_, err = s.Create(key, next)
} else {
var n uint64
if string(e.Value) == "null" {
return 0, fmt.Errorf("%s holds null, not a counter", key)
}
if err := json.Unmarshal(e.Value, &n); err != nil {
return 0, fmt.Errorf("%s holds %s, not a counter: %w", key, e.Value, err)
}
if n == ^uint64(0) {
return 0, fmt.Errorf("%s is at the largest number a counter holds", key)
}
next = n + 1
_, err = s.Update(key, next, e.Revision)
}
if err == nil {
return next, nil
}
if !errors.Is(err, ErrChanged) {
return 0, err
}
}
return 0, fmt.Errorf("%s was written by another writer first %d times: %w", key, attempts, ErrChanged)
}
// Keys is every key with a current value, sorted.
func (s KeptState) Keys() ([]string, error) {
raw, err := s.ask("keys", map[string]any{})
+278
View File
@@ -0,0 +1,278 @@
package stdio
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"sync"
"testing"
"time"
)
// casRuntime is the runtime's side of mesh/state.get, create and update as the bus does them (novox/hq ADR
// 0201, ADR 0259): one revision per write across the bucket, create refused when the key has a value,
// update refused unless the key is still at the revision named, each refusal answered with CodeChanged.
// refuse, when set, is asked before each write and may refuse it with an error of its own.
type casRuntime struct {
mu sync.Mutex
revision uint64
keys map[string]StateEntry
writes map[string]int
lost int
refuse func(verb string) (code int, message string, refused bool)
}
func (r *casRuntime) answer(m message) map[string]any {
var p struct {
Key string `json:"key"`
Value json.RawMessage `json:"value"`
Revision uint64 `json:"revision"`
}
_ = json.Unmarshal(m.Params, &p)
r.mu.Lock()
defer r.mu.Unlock()
verb := strings.TrimPrefix(m.Method, "mesh/state.")
lost := func() map[string]any {
r.lost++
return map[string]any{"error": map[string]any{"code": CodeChanged, "message": p.Key + ": the key was written by another writer first"}}
}
if verb != "get" && r.refuse != nil {
if code, msg, refused := r.refuse(verb); refused {
return map[string]any{"error": map[string]any{"code": code, "message": msg}}
}
}
e, has := r.keys[p.Key]
switch verb {
case "get":
if !has {
return map[string]any{"result": nil}
}
return map[string]any{"result": e}
case "create":
if has {
return lost()
}
case "update":
if p.Revision == 0 {
return map[string]any{"error": map[string]any{"code": -32000, "message": "an update names the revision it read"}}
}
if !has || e.Revision != p.Revision {
return lost()
}
case "put":
default:
return map[string]any{"error": map[string]any{"code": -32601, "message": "no " + m.Method}}
}
r.revision++
r.keys[p.Key] = StateEntry{Key: p.Key, Value: p.Value, Revision: r.revision}
r.writes[verb]++
return map[string]any{"result": map[string]any{"revision": r.revision}}
}
// counting serves a bundle whose one tool, "count", runs run, against r; it answers the bundle's asks each
// beside the loop, as the runtime does, so two writers' reads and writes interleave. It returns what the
// tool answered.
func counting(t *testing.T, r *casRuntime, run func() (any, error)) map[string]any {
t.Helper()
t.Setenv(ServedAs, "issues")
inR, inW := io.Pipe()
outR, outW := io.Pipe()
go func() {
_ = ServeOn("", []Tool{{Name: "count", Run: func(map[string]any) (any, error) { return run() }}}, inR, outW)
}()
var wmu sync.Mutex
send := func(m map[string]any) {
m["jsonrpc"] = "2.0"
b, _ := json.Marshal(m)
wmu.Lock()
defer wmu.Unlock()
_, _ = inW.Write(append(b, '\n'))
}
done := make(chan map[string]any, 1)
go func() {
lines := bufio.NewScanner(outR)
lines.Buffer(make([]byte, 1<<20), 1<<24)
for lines.Scan() {
var m message
if json.Unmarshal(lines.Bytes(), &m) != nil {
continue
}
if strings.HasPrefix(m.Method, "mesh/state.") {
go func(m message) {
a := r.answer(m)
a["id"] = m.ID
send(a)
}(m)
continue
}
var answer map[string]any
_ = json.Unmarshal(lines.Bytes(), &answer)
if answer["id"] == float64(1) {
done <- answer
return
}
}
}()
send(map[string]any{"id": 1, "method": "tools/call", "params": map[string]any{"name": "count"}})
t.Cleanup(func() { _ = inW.Close() })
select {
case a := <-done:
return a
case <-time.After(60 * time.Second):
t.Fatal("the bundle did not answer the count")
return nil
}
}
func text(t *testing.T, a map[string]any) (string, bool) {
t.Helper()
res, _ := a["result"].(map[string]any)
content, _ := res["content"].([]any)
if len(content) != 1 {
t.Fatalf("answered %v", a)
}
isError, _ := res["isError"].(bool)
return content[0].(map[string]any)["text"].(string), isError
}
// Two writers incrementing one counter a thousand times each end at two thousand: every number handed out
// once, none lost, each writer's numbers rising — read, then written only at the revision read.
func TestTwoWritersIncrementingOneCounterLoseNoUpdate(t *testing.T) {
r := &casRuntime{keys: map[string]StateEntry{}, writes: map[string]int{}}
const each = 1000
got := counting(t, r, func() (any, error) {
var wg sync.WaitGroup
numbers := make([][]uint64, 2)
errs := make([]error, 2)
for w := range numbers {
wg.Add(1)
go func(w int) {
defer wg.Done()
for i := 0; i < each; i++ {
n, err := State("numbers").Increment("issue", 1000)
if err != nil {
errs[w] = err
return
}
numbers[w] = append(numbers[w], n)
}
}(w)
}
wg.Wait()
if err := errors.Join(errs...); err != nil {
return nil, err
}
seen := map[uint64]bool{}
for w, ns := range numbers {
for i, n := range ns {
if seen[n] {
t.Errorf("the number %d was handed out twice", n)
}
seen[n] = true
if i > 0 && n <= ns[i-1] {
t.Errorf("writer %d was handed %d after %d", w, n, ns[i-1])
}
}
}
return len(seen), nil
})
if out, isError := text(t, got); isError || out != "2000" {
t.Fatalf("two writers counted %s (error: %v)", out, isError)
}
var final uint64
_ = json.Unmarshal(r.keys["issue"].Value, &final)
if final != 2*each {
t.Fatalf("the counter ended at %d, not %d: an increment was lost", final, 2*each)
}
if r.lost == 0 {
t.Fatal("the two writers never collided: the test proved nothing about contention")
}
t.Logf("2000 increments, %d writes lost to the other writer and tried again", r.lost)
if r.writes["create"] != 1 || r.writes["update"] != 2*each-1 || r.writes["put"] != 0 {
t.Fatalf("written by %v: one create, then updates at the revision read, never a put", r.writes)
}
}
// A lost write is read again and tried again, never reported counted; past its attempts it is ErrChanged
// with nothing counted; any other refusal, and a value that is no counter, is returned at once.
func TestAnIncrementThatLosesIsTriedAgainAndNeverReportedCounted(t *testing.T) {
t.Run("lost twice then won", func(t *testing.T) {
lost := 0
r := &casRuntime{keys: map[string]StateEntry{"issue": {Key: "issue", Value: json.RawMessage(`41`), Revision: 7}},
writes: map[string]int{}, revision: 7}
r.refuse = func(string) (int, string, bool) {
if lost < 2 {
lost++
// Another writer was first: the counter moved on by one, to 42 and then 43.
r.revision++
r.keys["issue"] = StateEntry{Key: "issue", Value: json.RawMessage(fmt.Sprint(41 + lost)), Revision: r.revision}
return CodeChanged, "issue: the key was written by another writer first", true
}
return 0, "", false
}
got := counting(t, r, func() (any, error) { return State("numbers").Increment("issue", 3) })
if out, isError := text(t, got); isError || out != "44" {
t.Fatalf("answered %s (error: %v), not 44", out, isError)
}
})
t.Run("lost every time", func(t *testing.T) {
tries := 0
r := &casRuntime{keys: map[string]StateEntry{}, writes: map[string]int{}}
r.refuse = func(string) (int, string, bool) {
tries++
return CodeChanged, "issue: the key was written by another writer first", true
}
var err error
got := counting(t, r, func() (any, error) {
n, e := State("numbers").Increment("issue", 5)
err = e
return n, e
})
if _, isError := text(t, got); !isError || !errors.Is(err, ErrChanged) || tries != 5 {
t.Fatalf("after %d tries: %v", tries, err)
}
})
t.Run("refused otherwise", func(t *testing.T) {
tries := 0
r := &casRuntime{keys: map[string]StateEntry{}, writes: map[string]int{}}
r.refuse = func(string) (int, string, bool) {
tries++
return -32000, "issues keeps no state numbers", true
}
var err error
got := counting(t, r, func() (any, error) {
n, e := State("numbers").Increment("issue", 5)
err = e
return n, e
})
if _, isError := text(t, got); !isError || errors.Is(err, ErrChanged) || tries != 1 {
t.Fatalf("after %d tries: %v", tries, err)
}
})
t.Run("no counter", func(t *testing.T) {
r := &casRuntime{keys: map[string]StateEntry{"issue": {Key: "issue", Value: json.RawMessage(`"x"`), Revision: 1}},
writes: map[string]int{}, revision: 1}
got := counting(t, r, func() (any, error) { return State("numbers").Increment("issue", 5) })
if _, isError := text(t, got); !isError || len(r.writes) != 0 {
t.Fatalf("a value that is no counter was counted: %v, writes %v", got, r.writes)
}
})
t.Run("null", func(t *testing.T) {
r := &casRuntime{keys: map[string]StateEntry{"issue": {Key: "issue", Value: json.RawMessage(`null`), Revision: 1}},
writes: map[string]int{}, revision: 1}
got := counting(t, r, func() (any, error) { return State("numbers").Increment("issue", 5) })
if _, isError := text(t, got); !isError || len(r.writes) != 0 {
t.Fatalf("a null was counted from zero: %v, writes %v", got, r.writes)
}
})
t.Run("no attempts", func(t *testing.T) {
r := &casRuntime{keys: map[string]StateEntry{}, writes: map[string]int{}}
got := counting(t, r, func() (any, error) { return State("numbers").Increment("issue", 0) })
if _, isError := text(t, got); !isError || len(r.writes) != 0 {
t.Fatalf("zero attempts counted: %v", got)
}
})
}
+142
View File
@@ -0,0 +1,142 @@
package stdio
import (
"bufio"
"encoding/json"
"io"
"strings"
"sync"
"testing"
"time"
)
// historying serves a bundle whose one tool, "history", runs run, answering each mesh/state ask with
// answer beside the loop, as the runtime does; it returns what the bundle asked.
func historying(t *testing.T, answer func(message) map[string]any, run func()) []message {
t.Helper()
t.Setenv(ServedAs, "issues")
inR, inW := io.Pipe()
outR, outW := io.Pipe()
go func() {
_ = ServeOn("", []Tool{{Name: "history", Run: func(map[string]any) (any, error) { run(); return "done", nil }}}, inR, outW)
}()
var wmu, amu sync.Mutex
var asked []message
send := func(m map[string]any) {
m["jsonrpc"] = "2.0"
b, _ := json.Marshal(m)
wmu.Lock()
defer wmu.Unlock()
_, _ = inW.Write(append(b, '\n'))
}
done := make(chan struct{})
go func() {
lines := bufio.NewScanner(outR)
for lines.Scan() {
var m message
if json.Unmarshal(lines.Bytes(), &m) != nil {
continue
}
if strings.HasPrefix(m.Method, "mesh/state.") {
amu.Lock()
asked = append(asked, m)
amu.Unlock()
a := answer(m)
a["id"] = m.ID
send(a)
continue
}
if m.Method == "" {
close(done)
return
}
}
}()
send(map[string]any{"id": 1, "method": "tools/call", "params": map[string]any{"name": "history"}})
t.Cleanup(func() { _ = inW.Close() })
select {
case <-done:
case <-time.After(10 * time.Second):
t.Fatal("the bundle did not answer")
}
amu.Lock()
defer amu.Unlock()
return asked
}
// History asks mesh/state.history with the state and the key alone, and hands back every kept value oldest
// first, a delete with its null value; nothing kept is an empty history; a refusal is the runtime's error
// (novox/hq ADR 0307).
func TestHistoryIsEveryKeptValueOldestFirst(t *testing.T) {
kept := []map[string]any{
{"key": "401", "value": map[string]any{"status": "open"}, "revision": 4, "op": "put", "at": "2026-10-10T19:46:00Z"},
{"key": "401", "value": map[string]any{"status": "fixing"}, "revision": 9, "op": "put", "at": "2026-10-11T08:01:02Z"},
{"key": "401", "value": nil, "revision": 12, "op": "delete", "at": "2026-10-11T09:30:00+02:00"},
}
var got, none, null []StateRevision
var refused error
asked := historying(t, func(m message) map[string]any {
var p map[string]any
_ = json.Unmarshal(m.Params, &p)
switch {
case p["state"] != "issues":
return map[string]any{"error": map[string]any{"code": -32000, "message": "issues was issued no state " + p["state"].(string)}}
case p["key"] == "401":
return map[string]any{"result": kept}
case p["key"] == "402":
return map[string]any{"result": nil}
}
return map[string]any{"result": []any{}}
}, func() {
var err error
if got, err = State("issues").History("401"); err != nil {
t.Errorf("history of 401: %v", err)
}
if none, err = State("issues").History("999"); err != nil {
t.Errorf("history of 999: %v", err)
}
if null, err = State("issues").History("402"); err != nil {
t.Errorf("history of 402: %v", err)
}
var h []StateRevision
h, refused = State("elsewhere.issues").History("401")
if h != nil {
t.Errorf("a refused history handed back %v", h)
}
})
if len(asked) != 4 {
t.Fatalf("asked %d times, not 4", len(asked))
}
var p map[string]any
_ = json.Unmarshal(asked[0].Params, &p)
if asked[0].Method != "mesh/state.history" || p["state"] != "issues" || p["key"] != "401" || len(p) != 2 {
t.Fatalf("asked %s %v", asked[0].Method, p)
}
if len(got) != 3 {
t.Fatalf("history of 401 is %d values, not 3: %+v", len(got), got)
}
want := []struct {
rev uint64
op string
value string
at time.Time
}{
{4, "put", `{"status":"open"}`, time.Date(2026, 10, 10, 19, 46, 0, 0, time.UTC)},
{9, "put", `{"status":"fixing"}`, time.Date(2026, 10, 11, 8, 1, 2, 0, time.UTC)},
{12, "delete", `null`, time.Date(2026, 10, 11, 7, 30, 0, 0, time.UTC)},
}
for i, w := range want {
r := got[i]
if r.Key != "401" || r.Revision != w.rev || r.Op != w.op || string(r.Value) != w.value || !r.At.Equal(w.at) {
t.Fatalf("value %d is %+v, not %+v", i, r, w)
}
}
if none == nil || len(none) != 0 || null == nil || len(null) != 0 {
t.Fatalf("nothing kept read as %v and %v, not an empty history", none, null)
}
if refused == nil || !strings.Contains(refused.Error(), "issued no state elsewhere.issues") {
t.Fatalf("a state not issued answered %v", refused)
}
}
+85 -7
View File
@@ -39,7 +39,8 @@ type Tool struct {
Description string
// Input is the JSON schema of the arguments; nil is a tool that takes nothing.
Input map[string]any
Run func(args map[string]any) (any, error)
// Run answers one call. Who called is CallerOf(args): the bus user the runtime proved, or Unproven.
Run func(args map[string]any) (any, error)
}
type message struct {
@@ -48,6 +49,7 @@ type message struct {
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
}
@@ -64,6 +66,9 @@ type channel struct {
subscribed int
// watches are this bundle's state watches by the id each was asked with (ADR 0201).
watches map[string]func(StateChange) error
// takers and provers are this bundle's seat work and proof handlers, by worker and subject (ADR 0259).
takers map[string]func(Work) error
provers map[string]func(subject string, body json.RawMessage) (any, error)
}
type listener struct {
@@ -111,7 +116,7 @@ func (c *channel) askAs(id, method string, params any, timeout time.Duration) (j
select {
case m := <-answer:
if m.Error != nil {
return nil, &refused{m.Error.Message}
return nil, &refused{message: m.Error.Message, code: m.Error.Code}
}
return m.Result, nil
case <-time.After(timeout):
@@ -123,10 +128,23 @@ func (c *channel) askAs(id, method string, params any, timeout time.Duration) (j
}
// refused is the runtime's error answer, as opposed to no answer: what it refused, it did not do.
type refused struct{ message string }
type refused struct {
message string
code int
}
func (r *refused) Error() string { return r.message }
// Is makes a compare-and-set the runtime refused because another writer was first ErrChanged.
func (r *refused) Is(target error) bool { return target == ErrChanged && r.code == CodeChanged }
// ErrChanged is a compare-and-set that lost: the key was made or changed by another writer first (novox/hq
// ADR 0259). Told apart by the runtime's error code, never by its words.
var ErrChanged = errors.New("the key was written by another writer first")
// CodeChanged is the error code the runtime answers a lost compare-and-set with.
const CodeChanged = -32010
var (
current *channel
currentMu sync.Mutex
@@ -150,7 +168,8 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error {
for _, t := range tools {
byName[t.Name] = t
}
c := &channel{enc: json.NewEncoder(out), waiting: map[string]chan message{}, watches: map[string]func(StateChange) error{}}
c := &channel{enc: json.NewEncoder(out), waiting: map[string]chan message{}, watches: map[string]func(StateChange) error{},
takers: map[string]func(Work) error{}, provers: map[string]func(string, json.RawMessage) (any, error){}}
currentMu.Lock()
current = c
currentMu.Unlock()
@@ -205,6 +224,8 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error {
var p struct {
Name string `json:"name"`
Arguments map[string]any `json:"arguments"`
// Meta is the runtime's, never the caller's: who called, taken from the subject (CallerOf).
Meta map[string]any `json:"_meta"`
}
_ = json.Unmarshal(m.Params, &p)
t, ok := byName[p.Name]
@@ -214,18 +235,18 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error {
}
// Beside the loop, never in it: a tool that emits waits for the runtime's answer, which
// arrives on the line this loop reads next — and calls do not queue behind a slow one.
go func(id any, t Tool, args map[string]any) {
go func(id any, t Tool, args map[string]any, caller string) {
if args == nil {
args = map[string]any{}
}
result, err := t.Run(args)
result, err := runAs(t, caller, args)
if err != nil {
c.say(map[string]any{"id": id, "result": map[string]any{"content": []map[string]any{{"type": "text", "text": err.Error()}}, "isError": true}})
return
}
text, _ := json.Marshal(result)
c.say(map[string]any{"id": id, "result": map[string]any{"content": []map[string]any{{"type": "text", "text": string(text)}}}})
}(id, t, p.Arguments)
}(id, t, p.Arguments, callerIn(p.Meta))
case "mesh/event":
// One event the runtime read from this module's consumer (ADR 0198), answered once every
// handler it is for has taken it; an error is answered as one, so the runtime does not
@@ -276,6 +297,63 @@ func ServeOn(name string, tools []Tool, in io.Reader, out io.Writer) error {
}
c.say(map[string]any{"id": id, "result": map[string]any{}})
}(id, *p.Change)
case "mesh/work":
// One piece of a seat's work this bundle takes (novox/hq ADR 0259): taken by an answer that is
// not an error, offered again after one. Beside the loop, like a tool call.
var p struct {
Work *Work `json:"work"`
}
if json.Unmarshal(m.Params, &p) != nil || p.Work == nil {
c.say(map[string]any{"id": id, "error": map[string]any{"code": -32602, "message": "mesh/work carries no work"}})
continue
}
c.mu.Lock()
handle := c.takers[p.Work.Worker]
if handle == nil && len(c.takers) == 1 {
for _, h := range c.takers {
handle = h
}
}
c.mu.Unlock()
go func(id any, w Work) {
if handle == nil {
c.say(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": "nothing here takes " + w.Subject}})
return
}
if err := handle(w); err != nil {
c.say(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": err.Error()}})
return
}
c.say(map[string]any{"id": id, "result": map[string]any{}})
}(id, *p.Work)
case "mesh/proof":
// One proof this bundle answers (novox/hq ADR 0259): what the handler returns is the answer; an
// error is answered in words, never as silence.
var p struct {
Subject string `json:"subject"`
Body json.RawMessage `json:"body"`
}
_ = json.Unmarshal(m.Params, &p)
c.mu.Lock()
var handle func(string, json.RawMessage) (any, error)
for pattern, h := range c.provers {
if subjectMatches(pattern, p.Subject) {
handle = h
}
}
c.mu.Unlock()
go func(id any, subject string, body json.RawMessage) {
if handle == nil {
c.say(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": "nothing here answers " + subject}})
return
}
out, err := handle(subject, body)
if err != nil {
c.say(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": err.Error()}})
return
}
c.say(map[string]any{"id": id, "result": out})
}(id, p.Subject, p.Body)
default:
if id != nil {
c.say(map[string]any{"id": id, "error": map[string]any{"code": -32601, "message": "no " + m.Method}})