carlos / platform Public

grouproll: config, journal format 2 and the group lock

First core slice of carlos system group (Task 1). Config validation is
the script's validate_config from held-floor-sha-map; journals are
format 2 (spec V3: "format": 2 on begin, at_ms integer milliseconds,
one canonical encoding pinned by golden bytes); state lives in the
operator's own 0700 directory with euid ownership checks (V1, V4); the
approved operator copy is ported into text.go.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1ce5c0ba6587a0192c734cca1ef1accd5e1c7f30 parent a736258
12 files changed, +2,343 −0
  • internal/grouproll/config.go +277 −0
  • internal/grouproll/config_test.go +231 −0
  • internal/grouproll/journal.go +437 −0
  • internal/grouproll/journal_test.go +245 −0
  • internal/grouproll/state.go +373 −0
  • internal/grouproll/state_other.go +17 −0
  • internal/grouproll/state_test.go +394 −0
  • internal/grouproll/state_unix.go +77 −0
  • internal/grouproll/testdata/journal-format2.golden +2 −0
  • internal/grouproll/text.go +219 −0
  • internal/grouproll/text_test.go +65 −0
  • region_ha_boundary_test.go +6 −0

CI passed — run details

Intent

Human

<task-notification> <task-id>b5cfr8g0d</task-id> <tool-use-id>toolu_01RJvq7H5v1wPRyAtr6AsAbm</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/b5cfr8g0d.output</output-file> <status>completed</status> <summary>Background command "Wait for Luna copy review" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 29.3 g CO₂e (3,714,751 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on group-roll-verb, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/grouproll/config.go b/internal/grouproll/config.go
new file mode 100644
index 000000000..e5453c771
--- /dev/null
+++ b/internal/grouproll/config.go
@@ -0,0 +1,277 @@
+package grouproll
+
+import (
+ "encoding/base64"
+ "os"
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+// Config is the deployment's group config: exactly the script's keys and
+// JSON names (validate_config, held-floor-sha-map). An optional key that is
+// absent is nil. state_dir is parsed and validated as the script does, but
+// unused: the state directory comes from ResolveStateDir (spec V4).
+type Config struct {
+ Deployment string `json:"deployment"`
+ Account string `json:"account"`
+ Region string `json:"region"`
+ Group string `json:"group"`
+ GroupARN string `json:"group_arn"`
+ Hook string `json:"hook"`
+ TargetGroups []string `json:"target_groups"`
+ Bucket string `json:"bucket"`
+ Document string `json:"document"`
+ StateDir string `json:"state_dir"`
+ Profile string `json:"profile"`
+ MinRelease string `json:"min_release"`
+
+ // Planned handovers (region HA spec §25).
+ HAFloor *string `json:"ha_floor,omitempty"`
+ DataBucket *string `json:"data_bucket,omitempty"`
+ DataPrefix *string `json:"data_prefix,omitempty"`
+
+ // SHA-pinned release mapping (§25.9). ReleasePublicKey keeps the
+ // config's text, surrounding space included, as the script does.
+ ReleasePublicKey *string `json:"release_public_key,omitempty"`
+ ReleaseChannels []string `json:"release_channels,omitempty"`
+ ReleasePlatform *string `json:"release_platform,omitempty"`
+}
+
+// The script's patterns (:242-266 and validate_config), anchored as
+// re.fullmatch anchors them. Go's $ without (?m) matches only at the end of
+// the text, like \Z.
+var (
+ SHA = regexp.MustCompile(`^[0-9a-f]{64}$`)
+ IID = regexp.MustCompile(`^i-(?:[0-9a-f]{8}|[0-9a-f]{17})$`)
+ TX = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,80}$`)
+ EdgesKey = regexp.MustCompile(`^control/edges/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\.json$`)
+ Bucket = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$`)
+ HostName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,252}$`)
+ releaseChannel = regexp.MustCompile(`^[a-z0-9-]{1,64}$`)
+ releasePlatform = regexp.MustCompile(`^[a-z0-9]+-[a-z0-9]+$`)
+ releaseVersion = regexp.MustCompile(`^v?((?:0|[1-9][0-9]{0,8})\.(?:0|[1-9][0-9]{0,8})\.(?:0|[1-9][0-9]{0,8}))$`)
+ dataPrefix = regexp.MustCompile(`^[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$`)
+ configName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$`)
+ configAccount = regexp.MustCompile(`^[0-9]{12}$`)
+ configRegion = regexp.MustCompile(`^[a-z]{2}(?:-[a-z]+)+-[0-9]$`)
+)
+
+var requiredKeys = []string{"deployment", "account", "region", "group", "group_arn", "hook",
+ "target_groups", "bucket", "document", "state_dir", "profile", "min_release"}
+
+var optionalKeys = []string{"ha_floor", "data_prefix", "data_bucket",
+ "release_public_key", "release_channels", "release_platform"}
+
+// LoadConfig reads and validates the config at path. A file that cannot be
+// read or decoded is "record" (the script's decode and main); a decoded
+// config that fails validation is "config_invalid".
+func LoadConfig(path string) (Config, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return Config{}, refuse("record")
+ }
+ v, err := decodeStrict(raw)
+ if err != nil {
+ return Config{}, refuse("record")
+ }
+ return ValidateConfig(v)
+}
+
+// ValidateConfig is the script's validate_config over a decoded JSON value.
+func ValidateConfig(v any) (Config, error) {
+ invalid := refuse("config_invalid")
+ c, ok := v.(map[string]any)
+ if !ok {
+ return Config{}, invalid
+ }
+ allowed := map[string]bool{}
+ for _, k := range requiredKeys {
+ if _, ok := c[k]; !ok {
+ return Config{}, invalid
+ }
+ allowed[k] = true
+ }
+ for _, k := range optionalKeys {
+ allowed[k] = true
+ }
+ for k := range c {
+ if !allowed[k] {
+ return Config{}, invalid
+ }
+ }
+ var out Config
+ optional := func(key string, valid func(string) bool) (*string, bool) {
+ raw, present := c[key]
+ if !present {
+ return nil, true
+ }
+ s, ok := raw.(string)
+ if !ok || !valid(s) {
+ return nil, false
+ }
+ return &s, true
+ }
+ if out.ReleasePublicKey, ok = optional("release_public_key", func(s string) bool {
+ _, ok := ParseReleasePublicKey(s)
+ return ok
+ }); !ok {
+ return Config{}, invalid
+ }
+ if raw, present := c["release_channels"]; present {
+ list, ok := raw.([]any)
+ if !ok || len(list) < 1 || len(list) > 4 {
+ return Config{}, invalid
+ }
+ seen := map[string]bool{}
+ for _, e := range list {
+ s, ok := e.(string)
+ if !ok || !releaseChannel.MatchString(s) || seen[s] {
+ return Config{}, invalid
+ }
+ seen[s] = true
+ out.ReleaseChannels = append(out.ReleaseChannels, s)
+ }
+ }
+ if out.ReleasePlatform, ok = optional("release_platform", releasePlatform.MatchString); !ok {
+ return Config{}, invalid
+ }
+ if out.HAFloor, ok = optional("ha_floor", releaseVersion.MatchString); !ok {
+ return Config{}, invalid
+ }
+ if out.DataBucket, ok = optional("data_bucket", Bucket.MatchString); !ok {
+ return Config{}, invalid
+ }
+ if out.DataPrefix, ok = optional("data_prefix", func(s string) bool {
+ if utf8.RuneCountInString(s) > 1024 || (s != "" && !dataPrefix.MatchString(s)) {
+ return false
+ }
+ for _, part := range strings.Split(s, "/") {
+ if part == ".." {
+ return false
+ }
+ }
+ return true
+ }); !ok {
+ return Config{}, invalid
+ }
+ str := map[string]string{}
+ for _, k := range requiredKeys {
+ if k == "target_groups" {
+ continue
+ }
+ s, ok := c[k].(string)
+ if !ok || s == "" || utf8.RuneCountInString(s) > 1024 {
+ return Config{}, invalid
+ }
+ str[k] = s
+ }
+ if !releaseVersion.MatchString(str["min_release"]) {
+ return Config{}, invalid
+ }
+ for _, k := range []string{"deployment", "group", "hook", "profile", "document"} {
+ if !configName.MatchString(str[k]) {
+ return Config{}, invalid
+ }
+ }
+ if !configAccount.MatchString(str["account"]) || !configRegion.MatchString(str["region"]) ||
+ !Bucket.MatchString(str["bucket"]) {
+ return Config{}, invalid
+ }
+ // Path(state_dir).is_absolute() and ".." not in its parts.
+ if !strings.HasPrefix(str["state_dir"], "/") {
+ return Config{}, invalid
+ }
+ for _, part := range strings.Split(str["state_dir"], "/") {
+ if part == ".." {
+ return Config{}, invalid
+ }
+ }
+ doc := str["document"]
+ if doc == "SSM-SessionManagerRunShell" || (strings.HasPrefix(doc, "AWS-") && doc != "AWS-StartNonInteractiveCommand") {
+ return Config{}, invalid
+ }
+ regionAccount := regexp.QuoteMeta(str["region"] + ":" + str["account"])
+ groupARN := regexp.MustCompile(`^(?:arn:aws(?:-[a-z]+)*:autoscaling:` + regionAccount +
+ `:autoScalingGroup:[A-Za-z0-9-]+:autoScalingGroupName/` + regexp.QuoteMeta(str["group"]) + `)$`)
+ if !groupARN.MatchString(str["group_arn"]) {
+ return Config{}, invalid
+ }
+ tgs, ok := c["target_groups"].([]any)
+ if !ok || len(tgs) != 2 {
+ return Config{}, invalid
+ }
+ partition := strings.Split(str["group_arn"], ":")[1]
+ targetGroup := regexp.MustCompile(`^(?:arn:` + partition + `:elasticloadbalancing:` + regionAccount +
+ `:targetgroup/[A-Za-z0-9-]+/[0-9a-f]{16})$`)
+ for _, e := range tgs {
+ s, ok := e.(string)
+ if !ok || !targetGroup.MatchString(s) {
+ return Config{}, invalid
+ }
+ out.TargetGroups = append(out.TargetGroups, s)
+ }
+ if out.TargetGroups[0] == out.TargetGroups[1] {
+ return Config{}, invalid
+ }
+ out.Deployment, out.Account, out.Region = str["deployment"], str["account"], str["region"]
+ out.Group, out.GroupARN, out.Hook = str["group"], str["group_arn"], str["hook"]
+ out.Bucket, out.Document, out.StateDir = str["bucket"], str["document"], str["state_dir"]
+ out.Profile, out.MinRelease = str["profile"], str["min_release"]
+ return out, nil
+}
+
+// Map is the config as the script's dict: every required key and each
+// optional key that is present. The begin row records it, and Load
+// compares it with the loading config.
+func (c Config) Map() map[string]any {
+ tgs := make([]any, len(c.TargetGroups))
+ for i, s := range c.TargetGroups {
+ tgs[i] = s
+ }
+ m := map[string]any{
+ "deployment": c.Deployment, "account": c.Account, "region": c.Region,
+ "group": c.Group, "group_arn": c.GroupARN, "hook": c.Hook, "target_groups": tgs,
+ "bucket": c.Bucket, "document": c.Document, "state_dir": c.StateDir,
+ "profile": c.Profile, "min_release": c.MinRelease,
+ }
+ for k, p := range map[string]*string{
+ "ha_floor": c.HAFloor, "data_bucket": c.DataBucket, "data_prefix": c.DataPrefix,
+ "release_public_key": c.ReleasePublicKey, "release_platform": c.ReleasePlatform,
+ } {
+ if p != nil {
+ m[k] = *p
+ }
+ }
+ if c.ReleaseChannels != nil {
+ chs := make([]any, len(c.ReleaseChannels))
+ for i, s := range c.ReleaseChannels {
+ chs[i] = s
+ }
+ m["release_channels"] = chs
+ }
+ return m
+}
+
+// ParseReleasePublicKey is the script's release_public_key: standard base64
+// of a 32-byte Ed25519 public key, surrounding space ignored (Python's
+// str.strip), padding required, no space or line break inside.
+func ParseReleasePublicKey(s string) ([]byte, bool) {
+ s = strings.TrimFunc(s, pythonSpace)
+ if strings.ContainsAny(s, "\r\n") {
+ // Go's decoder skips these; Python's validate=True refuses them.
+ return nil, false
+ }
+ raw, err := base64.StdEncoding.DecodeString(s)
+ if err != nil || len(raw) != 32 {
+ return nil, false
+ }
+ return raw, true
+}
+
+// pythonSpace is str.isspace: Go's unicode.IsSpace plus the four ASCII
+// separators U+001C to U+001F.
+func pythonSpace(r rune) bool {
+ return unicode.IsSpace(r) || (r >= 0x1c && r <= 0x1f)
+}
diff --git a/internal/grouproll/config_test.go b/internal/grouproll/config_test.go
new file mode 100644
index 000000000..5c7da7aef
--- /dev/null
+++ b/internal/grouproll/config_test.go
@@ -0,0 +1,231 @@
+package grouproll
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+// goldenPub is scripts/testdata/router-pointer-golden.pub on
+// held-floor-sha-map: the release key for seed bytes 1..32.
+const goldenPub = "ebVWLo/mVPlAeLES6KmLp5AfhTrmlb7X4OORC60ElmQ="
+
+// baseConfig is test_config("/state") in scripts/region_group_roll_test.py.
+func baseConfig() map[string]any {
+ scope := "eu-west-1:000000000000"
+ return map[string]any{
+ "deployment": "example", "account": "000000000000", "region": "eu-west-1",
+ "group": "example-group", "hook": "example-launch",
+ "group_arn": "arn:aws:autoscaling:" + scope + ":autoScalingGroup:example:autoScalingGroupName/example-group",
+ "target_groups": []any{
+ "arn:aws:elasticloadbalancing:" + scope + ":targetgroup/example-8/8888888888888888",
+ "arn:aws:elasticloadbalancing:" + scope + ":targetgroup/example-4/4444444444444444",
+ },
+ "bucket": "example-deployment", "document": "AWS-StartNonInteractiveCommand",
+ "state_dir": "/state", "profile": "example", "min_release": "v0.34.0",
+ }
+}
+
+// heldConfig is held_config("/state") in scripts/region_group_held_test.py.
+func heldConfig() map[string]any {
+ c := baseConfig()
+ c["ha_floor"] = "v0.35.0"
+ c["data_prefix"] = "instances"
+ c["data_bucket"] = "example-bucket"
+ return c
+}
+
+func with(c map[string]any, kv ...any) map[string]any {
+ out := map[string]any{}
+ for k, v := range c {
+ out[k] = v
+ }
+ for i := 0; i < len(kv); i += 2 {
+ out[kv[i].(string)] = kv[i+1]
+ }
+ return out
+}
+
+func without(c map[string]any, key string) map[string]any {
+ out := with(c)
+ delete(out, key)
+ return out
+}
+
+func refusalKey(err error) string {
+ var r Refusal
+ if errors.As(err, &r) {
+ return r.Key
+ }
+ if err == nil {
+ return ""
+ }
+ return "not a refusal: " + err.Error()
+}
+
+// TestConfigMatchesScriptValidation ports every accept and refuse case of
+// validate_config in scripts/region_group_roll_test.py and
+// region_group_held_test.py (held-floor-sha-map).
+func TestConfigMatchesScriptValidation(t *testing.T) {
+ release := with(heldConfig(), "release_public_key", goldenPub)
+ accept := map[string]map[string]any{
+ "base": baseConfig(),
+ "held": heldConfig(),
+ "held empty prefix": with(heldConfig(), "data_prefix", ""),
+ "release key": release,
+ "one channel": with(release, "release_channels", []any{"stable"}),
+ "four channels": with(release, "release_channels", []any{"stable", "canary", "a-1", "b"}),
+ "platform": with(release, "release_platform", "linux-amd64"),
+ "key with space": with(release, "release_public_key", " "+goldenPub+"\n"),
+ "partition": with(baseConfig(), "group_arn", "arn:aws-cn:autoscaling:eu-west-1:000000000000:autoScalingGroup:example:autoScalingGroupName/example-group", "target_groups", []any{"arn:aws-cn:elasticloadbalancing:eu-west-1:000000000000:targetgroup/a/0123456789abcdef", "arn:aws-cn:elasticloadbalancing:eu-west-1:000000000000:targetgroup/b/0123456789abcdef"}),
+ "v-less min_release": with(baseConfig(), "min_release", "0.34.0"),
+ "nested prefix": with(heldConfig(), "data_prefix", "a/b.c/d_e-f"),
+ "other document": with(baseConfig(), "document", "Carlos-Group-Operator"),
+ "state_dir other absolute": with(baseConfig(), "state_dir", "/var/lib/x/./y"),
+ }
+ for name, c := range accept {
+ t.Run("accept "+name, func(t *testing.T) {
+ got, err := ValidateConfig(c)
+ if err != nil {
+ t.Fatalf("refused: %v", err)
+ }
+ if !reflect.DeepEqual(got.Map(), normalizeForTest(t, c)) {
+ t.Fatalf("Map() = %#v, want %#v", got.Map(), c)
+ }
+ })
+ }
+ refuse := map[string]map[string]any{
+ // region_group_roll_test.py test_config_strict_and_no_real_defaults
+ "account": with(baseConfig(), "account", "wrong"),
+ "group_arn": with(baseConfig(), "group_arn", "arn:wrong"),
+ "state_dir": with(baseConfig(), "state_dir", "relative"),
+ "run shell": with(baseConfig(), "document", "SSM-SessionManagerRunShell"),
+ "profile": with(baseConfig(), "profile", "a;touch invalid"),
+ "unknown": with(baseConfig(), "unknown", true),
+ "min_release dev": with(baseConfig(), "min_release", "dev"),
+ "min_release 0034": with(baseConfig(), "min_release", "v0.034.0"),
+ "min_release short": with(baseConfig(), "min_release", "v0.34"),
+ "min_release pre": with(baseConfig(), "min_release", "0.34.0-1"),
+ "min_release big": with(baseConfig(), "min_release", "v1000000000.0.0"),
+ "no min_release": without(baseConfig(), "min_release"),
+ // region_group_held_test.py ConfigTests
+ "ha_floor": with(heldConfig(), "ha_floor", "next"),
+ "prefix absolute": with(heldConfig(), "data_prefix", "/x"),
+ "prefix dotdot": with(heldConfig(), "data_prefix", "a/../b"),
+ "prefix trailing": with(heldConfig(), "data_prefix", "a/"),
+ "data_bucket": with(heldConfig(), "data_bucket", "Bad_Bucket"),
+ "held other": with(heldConfig(), "other", "x"),
+ "key empty": with(release, "release_public_key", ""),
+ "key not base64": with(release, "release_public_key", "not base64!"),
+ "key 31 bytes": with(release, "release_public_key", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="),
+ "key no padding": with(release, "release_public_key", "ebVWLo/mVPlAeLES6KmLp5AfhTrmlb7X4OORC60ElmQ"),
+ "key number": with(release, "release_public_key", int64(1)),
+ "key inner newline": with(release, "release_public_key", "ebVWLo/mVPlAeLES6KmLp5Af\nhTrmlb7X4OORC60ElmQ="),
+ "channels empty": with(release, "release_channels", []any{}),
+ "channels string": with(release, "release_channels", "stable"),
+ "channels duplicate": with(release, "release_channels", []any{"stable", "stable"}),
+ "channels five": with(release, "release_channels", []any{"a", "b", "c", "d", "e"}),
+ "channels case": with(release, "release_channels", []any{"Stable"}),
+ "channels slash": with(release, "release_channels", []any{"canary/x"}),
+ "channels star": with(release, "release_channels", []any{"*"}),
+ "channels blank": with(release, "release_channels", []any{""}),
+ "channels number": with(release, "release_channels", []any{int64(1)}),
+ "platform bare": with(release, "release_platform", "linux"),
+ "platform case": with(release, "release_platform", "Linux-arm64"),
+ "platform null": with(release, "release_platform", nil),
+ // validate_config's remaining rules
+ "not an object": nil,
+ "deployment empty": with(baseConfig(), "deployment", ""),
+ "deployment long": with(baseConfig(), "deployment", longName(129)),
+ "region": with(baseConfig(), "region", "eu-west"),
+ "bucket": with(baseConfig(), "bucket", "Example"),
+ "state_dir dotdot": with(baseConfig(), "state_dir", "/var/../etc"),
+ "state_dir long": with(baseConfig(), "state_dir", "/"+longName(1024)),
+ "AWS- document": with(baseConfig(), "document", "AWS-RunShellScript"),
+ "group mismatch": with(baseConfig(), "group", "other-group"),
+ "group_arn account": with(baseConfig(), "group_arn", "arn:aws:autoscaling:eu-west-1:111111111111:autoScalingGroup:example:autoScalingGroupName/example-group"),
+ "one target group": with(baseConfig(), "target_groups", []any{"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888"}),
+ "same target groups": with(baseConfig(), "target_groups", []any{"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888", "arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888"}),
+ "target partition": with(baseConfig(), "target_groups", []any{"arn:aws-cn:elasticloadbalancing:eu-west-1:000000000000:targetgroup/a/0123456789abcdef", "arn:aws-cn:elasticloadbalancing:eu-west-1:000000000000:targetgroup/b/0123456789abcdef"}),
+ "target short id": with(baseConfig(), "target_groups", []any{"arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/a/0123", "arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/b/0123456789abcdef"}),
+ "profile number": with(baseConfig(), "profile", int64(7)),
+ "trailing newline": with(baseConfig(), "account", "000000000000\n"),
+ "no state_dir": without(baseConfig(), "state_dir"),
+ "prefix long": with(heldConfig(), "data_prefix", longName(1025)),
+ "ha_floor not string": with(heldConfig(), "ha_floor", int64(1)),
+ }
+ for name, c := range refuse {
+ t.Run("refuse "+name, func(t *testing.T) {
+ var raw any = c
+ if c == nil {
+ raw = []any{}
+ }
+ _, err := ValidateConfig(raw)
+ if got := refusalKey(err); got != "config_invalid" {
+ t.Fatalf("refusal = %q, want config_invalid", got)
+ }
+ })
+ }
+}
+
+func longName(n int) string {
+ b := make([]byte, n)
+ for i := range b {
+ b[i] = 'a'
+ }
+ return string(b)
+}
+
+// normalizeForTest returns c as the strict decoder would hand it back.
+func normalizeForTest(t *testing.T, c map[string]any) map[string]any {
+ t.Helper()
+ raw, err := encodeRow(c)
+ if err != nil {
+ t.Fatal(err)
+ }
+ v, err := decodeStrict(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v.(map[string]any)
+}
+
+func TestLoadConfig(t *testing.T) {
+ dir := t.TempDir()
+ write := func(name, body string) string {
+ p := filepath.Join(dir, name)
+ if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return p
+ }
+ raw, err := encodeRow(heldConfig())
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, err := LoadConfig(write("good.json", string(raw)))
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+ if c.GroupARN != heldConfig()["group_arn"] || c.DataPrefix == nil || *c.DataPrefix != "instances" || c.StateDir != "/state" {
+ t.Fatalf("config = %+v", c)
+ }
+ // decode() refuses duplicates and constants as record, before validation.
+ for name, body := range map[string]string{
+ "dup.json": `{"account":"a","account":"b"}`,
+ "nan.json": `{"account":NaN}`,
+ "bad.json": `{`,
+ } {
+ if _, err := LoadConfig(write(name, body)); refusalKey(err) != "record" {
+ t.Errorf("%s: %v, want record", name, err)
+ }
+ }
+ if _, err := LoadConfig(write("float.json", `{"account":1.5}`)); refusalKey(err) != "config_invalid" {
+ t.Errorf("float: %v, want config_invalid", err)
+ }
+ if _, err := LoadConfig(filepath.Join(dir, "missing.json")); refusalKey(err) != "record" {
+ t.Errorf("missing: %v, want record", err)
+ }
+}
diff --git a/internal/grouproll/journal.go b/internal/grouproll/journal.go
new file mode 100644
index 000000000..f590bef96
--- /dev/null
+++ b/internal/grouproll/journal.go
@@ -0,0 +1,437 @@
+package grouproll
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "os"
+ "reflect"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+)
+
+// Journal format 2 (spec V3). A journal is append-only: one fsynced JSON
+// object per line, hash-chained by seq, previous and hash, as the script's
+// Journal class (:836-881). Format 2 differs from the script's journals in
+// three ways, and neither tool reads the other's files:
+//
+// - the first row, kind "begin", carries "format": 2, and a journal whose
+// first row lacks it is refused as a damaged record;
+// - rows are hashed and written in the one canonical encoding of
+// encodeRow below, not Python's json.dumps;
+// - times are integer milliseconds since the Unix epoch, never floats.
+// The script's float-seconds "at" field is "at_ms" here. Every other
+// field keeps the script's name and the script's row kinds are kept.
+//
+// Every error this package returns is a Refusal. Where the script let an
+// OSError reach main, which printed the "record" text, the error here is
+// Refusal{Key: "record"}.
+//
+// The script's rows are written by its Operator.event, which stamps "at";
+// the Go operator stamps "at_ms" the same way. The journal itself stamps
+// no time, as in the script.
+
+// FormatVersion is the "format" of a format 2 journal's begin row.
+const FormatVersion = 2
+
+// journalCap is the largest journal read (script :845-846). Rows hold
+// drain bodies of up to 1 MiB, so no smaller per-line cap applies.
+const journalCap = 64 * 1024 * 1024
+
+var zeroHash = strings.Repeat("0", 64)
+
+// Row is one journal row as decoded: nil, bool, string, int64, []any and
+// map[string]any values only.
+type Row map[string]any
+
+// Journal is one open transaction journal or plan log.
+type Journal struct {
+ path string
+ file *os.File
+ readonly bool
+ rows []Row
+}
+
+// encodeRow is the canonical format 2 encoding: object keys sorted, no
+// insignificant space, no HTML escaping, integers only. A float, a
+// non-integer number or a value that does not encode as JSON is refused.
+func encodeRow(v map[string]any) ([]byte, error) {
+ n, err := normalize(v)
+ if err != nil {
+ return nil, err
+ }
+ return encodeNormal(n)
+}
+
+func encodeNormal(v any) ([]byte, error) {
+ var b bytes.Buffer
+ enc := json.NewEncoder(&b)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(v); err != nil {
+ return nil, err
+ }
+ return bytes.TrimSuffix(b.Bytes(), []byte("\n")), nil
+}
+
+// normalize returns v as the decoder hands values back, refusing floats.
+func normalize(v any) (any, error) {
+ switch x := v.(type) {
+ case nil, bool, string, int64:
+ return x, nil
+ case int:
+ return int64(x), nil
+ case int8:
+ return int64(x), nil
+ case int16:
+ return int64(x), nil
+ case int32:
+ return int64(x), nil
+ case uint8:
+ return int64(x), nil
+ case uint16:
+ return int64(x), nil
+ case uint32:
+ return int64(x), nil
+ case uint:
+ if uint64(x) > math.MaxInt64 {
+ return nil, fmt.Errorf("grouproll: integer %d out of range", x)
+ }
+ return int64(x), nil
+ case uint64:
+ if x > math.MaxInt64 {
+ return nil, fmt.Errorf("grouproll: integer %d out of range", x)
+ }
+ return int64(x), nil
+ case float32, float64:
+ return nil, fmt.Errorf("grouproll: journal values are integers, not %v", x)
+ case json.Number:
+ i, ok := integer(string(x))
+ if !ok {
+ return nil, fmt.Errorf("grouproll: journal values are integers, not %s", x)
+ }
+ return i, nil
+ case Row:
+ return normalize(map[string]any(x))
+ case map[string]any:
+ out := make(map[string]any, len(x))
+ for k, e := range x {
+ n, err := normalize(e)
+ if err != nil {
+ return nil, err
+ }
+ out[k] = n
+ }
+ return out, nil
+ case []any:
+ out := make([]any, len(x))
+ for i, e := range x {
+ n, err := normalize(e)
+ if err != nil {
+ return nil, err
+ }
+ out[i] = n
+ }
+ return out, nil
+ case []string:
+ out := make([]any, len(x))
+ for i, e := range x {
+ out[i] = e
+ }
+ return out, nil
+ }
+ // Anything else (structs, typed maps and slices) goes through its JSON
+ // form, which the strict decoder then reads back.
+ if rv := reflect.ValueOf(v); (rv.Kind() == reflect.Pointer || rv.Kind() == reflect.Map || rv.Kind() == reflect.Slice) && rv.IsNil() {
+ return nil, nil
+ }
+ raw, err := json.Marshal(v)
+ if err != nil {
+ return nil, err
+ }
+ d, err := decodeStrict(raw)
+ if err != nil {
+ return nil, err
+ }
+ return normalize(d)
+}
+
+// integer parses s as a JSON integer literal within int64.
+func integer(s string) (int64, bool) {
+ if strings.ContainsAny(s, ".eE") {
+ return 0, false
+ }
+ i, err := strconv.ParseInt(s, 10, 64)
+ return i, err == nil
+}
+
+// decodeStrict is the script's decode (:508-513): one JSON value, refusing
+// duplicate object keys, NaN and Infinity, invalid UTF-8 and trailing data.
+// Integers within int64 come back as int64; any other number stays a
+// json.Number, which encodeRow refuses.
+func decodeStrict(raw []byte) (any, error) {
+ if !utf8.Valid(raw) {
+ return nil, errors.New("grouproll: invalid UTF-8")
+ }
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.UseNumber()
+ v, err := decodeValue(dec)
+ if err != nil {
+ return nil, err
+ }
+ if _, err := dec.Token(); err != io.EOF {
+ return nil, errors.New("grouproll: trailing data after JSON value")
+ }
+ return v, nil
+}
+
+func decodeValue(dec *json.Decoder) (any, error) {
+ tok, err := dec.Token()
+ if err != nil {
+ return nil, err
+ }
+ switch t := tok.(type) {
+ case json.Delim:
+ switch t {
+ case '{':
+ obj := map[string]any{}
+ for dec.More() {
+ kt, err := dec.Token()
+ if err != nil {
+ return nil, err
+ }
+ key, ok := kt.(string)
+ if !ok {
+ return nil, errors.New("grouproll: object key is not a string")
+ }
+ if _, dup := obj[key]; dup {
+ return nil, fmt.Errorf("grouproll: duplicate key %q", key)
+ }
+ v, err := decodeValue(dec)
+ if err != nil {
+ return nil, err
+ }
+ obj[key] = v
+ }
+ if _, err := dec.Token(); err != nil {
+ return nil, err
+ }
+ return obj, nil
+ case '[':
+ arr := []any{}
+ for dec.More() {
+ v, err := decodeValue(dec)
+ if err != nil {
+ return nil, err
+ }
+ arr = append(arr, v)
+ }
+ if _, err := dec.Token(); err != nil {
+ return nil, err
+ }
+ return arr, nil
+ }
+ return nil, fmt.Errorf("grouproll: unexpected %v", t)
+ case json.Number:
+ if i, ok := integer(string(t)); ok {
+ return i, nil
+ }
+ return t, nil
+ default:
+ return t, nil
+ }
+}
+
+// rowHash is the hex SHA-256 of the canonical encoding of row without its
+// hash field.
+func rowHash(row map[string]any) (string, error) {
+ raw, err := encodeRow(row)
+ if err != nil {
+ return "", err
+ }
+ sum := sha256.Sum256(raw)
+ return hex.EncodeToString(sum[:]), nil
+}
+
+// openJournal opens the journal at path as the script's Journal does: a
+// private file owned by owner, created exclusively when create is set, read
+// in full (at most journalCap bytes) and checked row by row.
+func openJournal(path string, owner int, create, readonly bool) (*Journal, error) {
+ if readonly && create {
+ return nil, refuse("record")
+ }
+ flags := os.O_RDWR | os.O_APPEND
+ if readonly {
+ flags = os.O_RDONLY
+ }
+ if create {
+ flags |= os.O_CREATE | os.O_EXCL
+ }
+ f, err := privateFile(path, flags, owner)
+ if err != nil {
+ return nil, err
+ }
+ j := &Journal{path: path, file: f, readonly: readonly}
+ if err := j.read(create); err != nil {
+ f.Close()
+ return nil, err
+ }
+ return j, nil
+}
+
+func (j *Journal) read(create bool) error {
+ raw, err := io.ReadAll(io.LimitReader(j.file, journalCap+1))
+ if err != nil {
+ return refuse("record")
+ }
+ if len(raw) > journalCap || (len(raw) > 0 && raw[len(raw)-1] != '\n') {
+ return refuse("record")
+ }
+ previous := zeroHash
+ if len(raw) > 0 {
+ for _, line := range bytes.Split(raw[:len(raw)-1], []byte("\n")) {
+ v, err := decodeStrict(line)
+ if err != nil {
+ return refuse("record")
+ }
+ row, ok := v.(map[string]any)
+ if !ok {
+ return refuse("record")
+ }
+ digest, ok := row["hash"].(string)
+ if !ok {
+ return refuse("record")
+ }
+ delete(row, "hash")
+ seq, ok := row["seq"].(int64)
+ if !ok || seq != int64(len(j.rows)) || row["previous"] != previous {
+ return refuse("record")
+ }
+ if h, err := rowHash(row); err != nil || h != digest {
+ return refuse("record")
+ }
+ row["hash"] = digest
+ j.rows = append(j.rows, Row(row))
+ previous = digest
+ }
+ }
+ if !create {
+ if len(j.rows) == 0 || j.rows[0]["kind"] != "begin" || j.rows[0]["format"] != int64(FormatVersion) {
+ return refuse("record")
+ }
+ }
+ return nil
+}
+
+// Path is the journal's file.
+func (j *Journal) Path() string { return j.path }
+
+// Rows are the journal's rows in order. The caller must not change them.
+func (j *Journal) Rows() []Row { return j.rows }
+
+// Close closes the journal's file.
+func (j *Journal) Close() error {
+ if j.file == nil {
+ return nil
+ }
+ err := j.file.Close()
+ j.file = nil
+ return err
+}
+
+// Add appends one row: seq, previous and kind, then fields, then the hash,
+// written and fsynced before it returns (script Journal.add). The first row
+// must be "begin" and gets "format": 2.
+func (j *Journal) Add(kind string, fields map[string]any) (Row, error) {
+ if j.readonly || j.file == nil {
+ return nil, refuse("record")
+ }
+ row := make(map[string]any, len(fields)+5)
+ for k, v := range fields {
+ switch k {
+ case "seq", "previous", "kind", "hash", "format":
+ return nil, refuse("record")
+ }
+ row[k] = v
+ }
+ if len(j.rows) == 0 {
+ if kind != "begin" {
+ return nil, refuse("record")
+ }
+ row["format"] = FormatVersion
+ }
+ row["seq"] = len(j.rows)
+ row["previous"] = zeroHash
+ if len(j.rows) > 0 {
+ row["previous"] = j.rows[len(j.rows)-1]["hash"]
+ }
+ row["kind"] = kind
+ n, err := normalize(row)
+ if err != nil {
+ return nil, refuse("record")
+ }
+ normal := n.(map[string]any)
+ digest, err := rowHash(normal)
+ if err != nil {
+ return nil, refuse("record")
+ }
+ normal["hash"] = digest
+ line, err := encodeNormal(normal)
+ if err != nil {
+ return nil, refuse("record")
+ }
+ if _, err := j.file.Write(append(line, '\n')); err != nil {
+ return nil, refuse("record")
+ }
+ if err := j.file.Sync(); err != nil {
+ return nil, refuse("record")
+ }
+ j.rows = append(j.rows, Row(normal))
+ return Row(normal), nil
+}
+
+// Last is the latest row of kind whose fields equal every value in match
+// (script Journal.last). A field absent from the row matches nil.
+func (j *Journal) Last(kind string, match map[string]any) (Row, bool) {
+ for i := len(j.rows) - 1; i >= 0; i-- {
+ r := j.rows[i]
+ if r["kind"] != kind {
+ continue
+ }
+ ok := true
+ for k, want := range match {
+ if !sameValue(r[k], want) {
+ ok = false
+ break
+ }
+ }
+ if ok {
+ return r, true
+ }
+ }
+ return nil, false
+}
+
+// sameValue compares a decoded value with any value by canonical encoding,
+// so 3 matches int64(3).
+func sameValue(have, want any) bool {
+ a, err := normalize(have)
+ if err != nil {
+ return false
+ }
+ b, err := normalize(want)
+ if err != nil {
+ return false
+ }
+ ea, err := encodeNormal(a)
+ if err != nil {
+ return false
+ }
+ eb, err := encodeNormal(b)
+ return err == nil && bytes.Equal(ea, eb)
+}
diff --git a/internal/grouproll/journal_test.go b/internal/grouproll/journal_test.go
new file mode 100644
index 000000000..8d509f6b1
--- /dev/null
+++ b/internal/grouproll/journal_test.go
@@ -0,0 +1,245 @@
+//go:build linux || darwin
+
+package grouproll
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func goldenRows() (map[string]any, map[string]any) {
+ begin := map[string]any{
+ "transaction": "golden", "config": baseConfig(), "iid": "i-0123456789abcdef0",
+ "new": strings.Repeat("b", 64), "attended_by": "a<b>&c",
+ }
+ intent := map[string]any{
+ "at_ms": int64(1762646400123), "op": "describe",
+ "args": map[string]any{"group": "example-group"}, "session": nil,
+ }
+ return begin, intent
+}
+
+func newJournal(t *testing.T) (*Journal, string) {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "tx.v2.jsonl")
+ j, err := openJournal(path, currentOwner(), true, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { j.Close() })
+ return j, path
+}
+
+// TestJournalFormat2Golden pins the canonical encoding (V3): keys sorted,
+// no spaces, no HTML escaping, integer milliseconds, "format":2 on begin.
+// The golden bytes were produced independently by Python's
+// json.dumps(sort_keys=True, separators=(",", ":")) over the same rows.
+func TestJournalFormat2Golden(t *testing.T) {
+ j, path := newJournal(t)
+ begin, intent := goldenRows()
+ if _, err := j.Add("begin", begin); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := j.Add("intent", intent); err != nil {
+ t.Fatal(err)
+ }
+ got, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want, err := os.ReadFile(filepath.Join("testdata", "journal-format2.golden"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("journal bytes\n got: %s\nwant: %s", got, want)
+ }
+ j.Close()
+ r, err := openJournal(path, currentOwner(), false, true)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ defer r.Close()
+ rows := r.Rows()
+ if len(rows) != 2 || rows[0]["format"] != int64(2) || rows[1]["at_ms"] != int64(1762646400123) {
+ t.Fatalf("rows = %#v", rows)
+ }
+ if !reflect.DeepEqual(rows, j.Rows()) {
+ t.Fatalf("reloaded rows differ from written rows")
+ }
+}
+
+func TestJournalAddAndLast(t *testing.T) {
+ j, _ := newJournal(t)
+ if _, err := j.Add("intent", map[string]any{"op": "x"}); refusalKey(err) != "record" {
+ t.Fatalf("first row not begin: %v", err)
+ }
+ begin, _ := goldenRows()
+ if _, err := j.Add("begin", begin); err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range []map[string]any{
+ {"op": "enter", "n": 1}, {"op": "exit", "n": 2}, {"op": "enter", "n": 3},
+ } {
+ if _, err := j.Add("intent", f); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if r, ok := j.Last("intent", map[string]any{"op": "enter"}); !ok || r["n"] != int64(3) || r["seq"] != int64(3) {
+ t.Fatalf("Last = %#v %v", r, ok)
+ }
+ if _, ok := j.Last("intent", map[string]any{"op": "terminate"}); ok {
+ t.Fatal("Last found a missing row")
+ }
+ if _, ok := j.Last("done", nil); ok {
+ t.Fatal("Last found done")
+ }
+ if _, err := j.Add("intent", map[string]any{"at": 1.5}); refusalKey(err) != "record" {
+ t.Fatalf("float: %v", err)
+ }
+ if _, err := j.Add("intent", map[string]any{"seq": 9}); refusalKey(err) != "record" {
+ t.Fatalf("reserved field: %v", err)
+ }
+ if len(j.Rows()) != 4 {
+ t.Fatalf("refused rows were kept: %d", len(j.Rows()))
+ }
+}
+
+// chained returns the journal lines for rows, each hashed as the journal
+// does, with mutate applied to row i before hashing.
+func chained(t *testing.T, rows []map[string]any) []byte {
+ t.Helper()
+ var out bytes.Buffer
+ previous := strings.Repeat("0", 64)
+ for i, r := range rows {
+ row := with(r)
+ if _, ok := row["seq"]; !ok {
+ row["seq"] = int64(i)
+ }
+ if _, ok := row["previous"]; !ok {
+ row["previous"] = previous
+ }
+ raw, err := encodeRow(row)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(raw)
+ row["hash"] = hex.EncodeToString(sum[:])
+ previous = row["hash"].(string)
+ line, err := encodeRow(row)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out.Write(line)
+ out.WriteByte('\n')
+ }
+ return out.Bytes()
+}
+
+func TestJournalRefusesDamage(t *testing.T) {
+ begin := map[string]any{"kind": "begin", "format": int64(2), "transaction": "t"}
+ intent := map[string]any{"kind": "intent", "op": "x"}
+ good := chained(t, []map[string]any{begin, intent})
+ cases := map[string][]byte{
+ "truncated last line": good[:len(good)-5],
+ "no final newline": good[:len(good)-1],
+ "duplicate key": bytes.Replace(good, []byte(`{"format":2,`), []byte(`{"format":2,"format":2,`), 1),
+ "NaN": bytes.Replace(good, []byte(`"op":"x"`), []byte(`"op":NaN`), 1),
+ "float": bytes.Replace(good, []byte(`"op":"x"`), []byte(`"op":1.5`), 1),
+ "bad previous": chained(t, []map[string]any{begin, with(intent, "previous", strings.Repeat("1", 64))}),
+ "bad hash": bytes.Replace(good, []byte(`"op":"x"`), []byte(`"op":"y"`), 1),
+ "seq gap": chained(t, []map[string]any{begin, with(intent, "seq", int64(2))}),
+ "empty line": append(append([]byte{}, good...), '\n'),
+ "not begin": chained(t, []map[string]any{intent}),
+ "no format": chained(t, []map[string]any{{"kind": "begin", "transaction": "t"}}),
+ "format 1": chained(t, []map[string]any{with(begin, "format", int64(1))}),
+ "empty": {},
+ "invalid utf-8": bytes.Replace(good, []byte(`"op":"x"`), []byte("\"op\":\"\xff\""), 1),
+ }
+ for name, raw := range cases {
+ t.Run(name, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "tx.v2.jsonl")
+ if err := os.WriteFile(path, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ for _, readonly := range []bool{true, false} {
+ j, err := openJournal(path, currentOwner(), false, readonly)
+ if err == nil {
+ j.Close()
+ }
+ if got := refusalKey(err); got != "record" {
+ t.Fatalf("readonly=%v: refusal %q, want record", readonly, got)
+ }
+ }
+ })
+ }
+ t.Run("good", func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "tx.v2.jsonl")
+ if err := os.WriteFile(path, good, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ j, err := openJournal(path, currentOwner(), false, false)
+ if err != nil {
+ t.Fatalf("good journal refused: %v", err)
+ }
+ j.Close()
+ })
+ t.Run("over 64 MiB", func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "tx.v2.jsonl")
+ if err := os.WriteFile(path, good, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ // Sparse: no 64 MiB of real writes.
+ if err := os.Truncate(path, journalCap+1); err != nil {
+ t.Fatal(err)
+ }
+ _, err := openJournal(path, currentOwner(), false, true)
+ if got := refusalKey(err); got != "record" {
+ t.Fatalf("refusal %q, want record", got)
+ }
+ })
+ t.Run("readonly add", func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "tx.v2.jsonl")
+ if err := os.WriteFile(path, good, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ j, err := openJournal(path, currentOwner(), false, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer j.Close()
+ if _, err := j.Add("intent", nil); refusalKey(err) != "record" {
+ t.Fatalf("readonly Add: %v", err)
+ }
+ })
+}
+
+// TestJournalLargeRow: journal rows hold drain bodies up to 1 MiB; the
+// 65,536-byte cap is only for the small state files.
+func TestJournalLargeRow(t *testing.T) {
+ j, path := newJournal(t)
+ begin, _ := goldenRows()
+ if _, err := j.Add("begin", begin); err != nil {
+ t.Fatal(err)
+ }
+ body := strings.Repeat("x", 74000)
+ if _, err := j.Add("response", map[string]any{"op": "session", "result": map[string]any{"stdout": body}}); err != nil {
+ t.Fatal(err)
+ }
+ j.Close()
+ r, err := openJournal(path, currentOwner(), false, true)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ defer r.Close()
+ row, ok := r.Last("response", nil)
+ if !ok || row["result"].(map[string]any)["stdout"] != body {
+ t.Fatal("large row did not round-trip")
+ }
+}
diff --git a/internal/grouproll/state.go b/internal/grouproll/state.go
new file mode 100644
index 000000000..c88cf2c7b
--- /dev/null
+++ b/internal/grouproll/state.go
@@ -0,0 +1,373 @@
+package grouproll
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// State is one group's directory under the operator account's state
+// directory (script State, :884-987, with spec V1 and V4): the group
+// directory is hex(sha256(group_arn))[:32], journals are <tx>.v2.jsonl, the
+// open transaction is named by active-v2.json, and group.lock serializes
+// every writing verb. The script's active.json and <tx>.jsonl are never
+// read.
+type State struct {
+ config Config
+ owner int
+ directory string
+ held bool
+}
+
+// Header is a transaction's begin row: the script's header dict. Kind is
+// "" for a roll and replace, remove or probe otherwise; as in the script it
+// is recorded as {"header": {"kind": Kind}}. New is the roll's artifact
+// SHA-256 and is omitted when empty. The config is the State's.
+type Header struct {
+ Kind string
+ Transaction string
+ IID string
+ New string
+ AttendedBy string
+}
+
+const (
+ activeFile = "active-v2.json"
+ journalSuffix = ".v2.jsonl"
+ lockFile = "group.lock"
+ observationFile = "provider-observation.json"
+ divergenceFile = "provider-divergence.json"
+ smallFileCap = 65536
+)
+
+// currentOwner is the uid that must own the state: the process's
+// effective uid (V1). Tests replace it.
+var currentOwner = os.Geteuid
+
+// ancestorStop, when set, ends the ancestor walk at that directory, which
+// is still checked. Production walks to /. Tests set it to their temporary
+// directory, whose own ancestors are the test machine's.
+var ancestorStop = ""
+
+// ResolveStateDir is the operator account's one state directory (V4):
+// $XDG_STATE_HOME/carlos/group, else $HOME/.local/state/carlos/group.
+// A relative XDG_STATE_HOME is ignored, as the XDG base directory spec
+// says. An empty or relative HOME is refused. There is no override.
+func ResolveStateDir(env func(string) string) (string, error) {
+ if x := env("XDG_STATE_HOME"); x != "" && filepath.IsAbs(x) {
+ return filepath.Join(x, "carlos", "group"), nil
+ }
+ home := env("HOME")
+ if home == "" || !filepath.IsAbs(home) {
+ return "", refuse("unsafe_state")
+ }
+ return filepath.Join(home, ".local", "state", "carlos", "group"), nil
+}
+
+// OpenState opens config's group directory under dir, the directory
+// ResolveStateDir returned. dir must exist, be owned by the effective uid
+// and be 0700 ("state_dir"); no ancestor may be a symlink, group- or
+// world-writable, or owned by anyone but root or that uid ("unsafe_state").
+// Unless readonly, the group directory is created when missing.
+func OpenState(dir string, c Config, readonly bool) (*State, error) {
+ owner := currentOwner()
+ dir = filepath.Clean(dir)
+ if !filepath.IsAbs(dir) {
+ return nil, refuse("state_dir", "path", dir)
+ }
+ info, err := lstatOwner(dir)
+ if err != nil {
+ return nil, refuse("state_dir", "path", dir)
+ }
+ if info.symlink {
+ return nil, refuse("unsafe_state")
+ }
+ if !info.dir || info.uid != owner || info.perm != 0o700 {
+ return nil, refuse("state_dir", "path", dir)
+ }
+ // Do not follow even an ancestor symlink (script :890-896).
+ for part := filepath.Dir(dir); ; part = filepath.Dir(part) {
+ if ancestorStop != "" && !strings.HasPrefix(part+"/", filepath.Clean(ancestorStop)+"/") {
+ break
+ }
+ a, err := lstatOwner(part)
+ if err != nil {
+ return nil, refuse("unsafe_state")
+ }
+ if a.symlink || !a.dir || (a.uid != 0 && a.uid != owner) || a.perm&0o022 != 0 {
+ return nil, refuse("unsafe_state")
+ }
+ if part == filepath.Dir(part) {
+ break
+ }
+ }
+ sum := sha256.Sum256([]byte(c.GroupARN))
+ s := &State{config: c, owner: owner, directory: filepath.Join(dir, hex.EncodeToString(sum[:])[:32])}
+ if !readonly {
+ switch err := os.Mkdir(s.directory, 0o700); {
+ case err == nil:
+ if err := syncDirectory(dir); err != nil {
+ return nil, refuse("record")
+ }
+ case errors.Is(err, fs.ErrExist):
+ default:
+ return nil, refuse("record")
+ }
+ }
+ g, err := lstatOwner(s.directory)
+ if err != nil {
+ return nil, refuse("record")
+ }
+ if g.symlink || !g.dir || g.uid != owner || g.perm != 0o700 {
+ return nil, refuse("unsafe_state")
+ }
+ return s, nil
+}
+
+// Directory is the group directory.
+func (s *State) Directory() string { return s.directory }
+
+// ObservationPath is the controller's provider-observation.json.
+func (s *State) ObservationPath() string { return filepath.Join(s.directory, observationFile) }
+
+// DivergencePath is provider-divergence.json, which blocks further rolls.
+func (s *State) DivergencePath() string { return filepath.Join(s.directory, divergenceFile) }
+
+// Held reports whether this process holds the group lock.
+func (s *State) Held() bool { return s.held }
+
+// Lock takes the group lock without waiting; another holder is "busy".
+// unlock releases it.
+func (s *State) Lock() (unlock func(), err error) {
+ f, err := privateFile(filepath.Join(s.directory, lockFile), os.O_RDWR|os.O_CREATE, s.owner)
+ if err != nil {
+ return nil, err
+ }
+ if err := lockExclusive(f); err != nil {
+ f.Close()
+ return nil, err
+ }
+ s.held = true
+ done := false
+ return func() {
+ if !done {
+ done = true
+ s.held = false
+ f.Close()
+ }
+ }, nil
+}
+
+// Read decodes a small state file (at most 65,536 bytes, script State.read).
+func (s *State) Read(path string) (any, error) {
+ f, err := privateFile(path, os.O_RDONLY, s.owner)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ raw, err := io.ReadAll(io.LimitReader(f, smallFileCap+1))
+ if err != nil || len(raw) > smallFileCap {
+ return nil, refuse("record")
+ }
+ v, err := decodeStrict(raw)
+ if err != nil {
+ return nil, refuse("record")
+ }
+ return v, nil
+}
+
+// Write replaces a small state file atomically under the lock (script
+// State.write): a private temporary file, fsync, rename, directory fsync.
+func (s *State) Write(path string, value map[string]any) error {
+ if !s.held {
+ return refuse("busy")
+ }
+ raw, err := encodeRow(value)
+ if err != nil {
+ return refuse("record")
+ }
+ temp := filepath.Join(s.directory, ".write-"+randomHex())
+ defer os.Remove(temp)
+ f, err := privateFile(temp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, s.owner)
+ if err != nil {
+ return err
+ }
+ _, werr := f.Write(append(raw, '\n'))
+ serr := f.Sync()
+ cerr := f.Close()
+ if werr != nil || serr != nil || cerr != nil {
+ return refuse("record")
+ }
+ if err := os.Rename(temp, path); err != nil {
+ return refuse("record")
+ }
+ if err := syncDirectory(s.directory); err != nil {
+ return refuse("record")
+ }
+ return nil
+}
+
+func (s *State) activePath() string { return filepath.Join(s.directory, activeFile) }
+
+func (s *State) journalPath(tx string) string {
+ return filepath.Join(s.directory, tx+journalSuffix)
+}
+
+// ActiveID is the open transaction, or "" when none (script active_id):
+// active-v2.json and the unfinished format 2 journals must agree.
+func (s *State) ActiveID() (string, error) {
+ current := ""
+ if _, err := os.Lstat(s.activePath()); err == nil {
+ v, err := s.Read(s.activePath())
+ if err != nil {
+ return "", err
+ }
+ m, _ := v.(map[string]any)
+ tx, ok := m["transaction"].(string)
+ if !ok || !TX.MatchString(tx) {
+ return "", refuse("record")
+ }
+ current = tx
+ } else if !errors.Is(err, fs.ErrNotExist) {
+ return "", refuse("record")
+ }
+ entries, err := os.ReadDir(s.directory)
+ if err != nil {
+ return "", refuse("record")
+ }
+ var unfinished []string
+ for _, e := range entries {
+ name := e.Name()
+ if !strings.HasSuffix(name, journalSuffix) {
+ continue
+ }
+ j, err := openJournal(filepath.Join(s.directory, name), s.owner, false, true)
+ if err != nil {
+ return "", err
+ }
+ if _, done := j.Last("done", nil); !done {
+ unfinished = append(unfinished, strings.TrimSuffix(name, journalSuffix))
+ }
+ j.Close()
+ }
+ if current == "" {
+ if len(unfinished) != 0 {
+ return "", refuse("record")
+ }
+ return "", nil
+ }
+ if !(len(unfinished) == 0 || (len(unfinished) == 1 && unfinished[0] == current)) {
+ return "", refuse("record")
+ }
+ if _, err := os.Lstat(s.journalPath(current)); err != nil {
+ return "", refuse("record")
+ }
+ return current, nil
+}
+
+// Create opens a new transaction under the lock: its journal with the
+// begin row, then active-v2.json naming it (script State.create).
+func (s *State) Create(header Header) (*Journal, error) {
+ if !s.held {
+ return nil, refuse("active")
+ }
+ active, err := s.ActiveID()
+ if err != nil {
+ return nil, err
+ }
+ if active != "" {
+ return nil, refuse("active")
+ }
+ if !TX.MatchString(header.Transaction) {
+ return nil, refuse("record")
+ }
+ j, err := openJournal(s.journalPath(header.Transaction), s.owner, true, false)
+ if err != nil {
+ return nil, err
+ }
+ fields := map[string]any{
+ "transaction": header.Transaction, "config": s.config.Map(),
+ "iid": header.IID, "attended_by": header.AttendedBy,
+ }
+ if header.New != "" {
+ fields["new"] = header.New
+ }
+ if header.Kind != "" {
+ fields["header"] = map[string]any{"kind": header.Kind}
+ }
+ if _, err := j.Add("begin", fields); err != nil {
+ j.Close()
+ return nil, err
+ }
+ if err := syncDirectory(s.directory); err != nil {
+ j.Close()
+ return nil, refuse("record")
+ }
+ if err := s.Write(s.activePath(), map[string]any{"transaction": header.Transaction}); err != nil {
+ j.Close()
+ return nil, err
+ }
+ return j, nil
+}
+
+// CreatePlanLog opens a new plan inspection log, plan-<hex>.log, under the
+// lock (script Operator.plan). The caller writes its begin row.
+func (s *State) CreatePlanLog() (*Journal, error) {
+ if !s.held {
+ return nil, refuse("busy")
+ }
+ return openJournal(filepath.Join(s.directory, "plan-"+randomHex()+".log"), s.owner, true, false)
+}
+
+// Load opens transaction tx's journal. Its begin row's config must equal
+// this State's config ("scope").
+func (s *State) Load(tx string, readonly bool) (*Journal, error) {
+ if !TX.MatchString(tx) {
+ return nil, refuse("record")
+ }
+ j, err := openJournal(s.journalPath(tx), s.owner, false, readonly)
+ if err != nil {
+ return nil, err
+ }
+ if !sameValue(j.rows[0]["config"], s.config.Map()) {
+ j.Close()
+ return nil, refuse("scope")
+ }
+ return j, nil
+}
+
+// Finish closes the open transaction by removing active-v2.json.
+func (s *State) Finish() error {
+ if !s.held {
+ return refuse("busy")
+ }
+ if err := os.Remove(s.activePath()); err != nil {
+ return refuse("record")
+ }
+ if err := syncDirectory(s.directory); err != nil {
+ return refuse("record")
+ }
+ return nil
+}
+
+// randomHex is uuid.uuid4().hex's role: 32 random hex digits.
+func randomHex() string {
+ var b [16]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ panic(err)
+ }
+ return hex.EncodeToString(b[:])
+}
+
+// fileInfo is what OpenState checks of a path, without following it.
+type fileInfo struct {
+ dir, symlink bool
+ uid int
+ perm uint32 // permission and set-id/sticky bits, as S_IMODE
+}
diff --git a/internal/grouproll/state_other.go b/internal/grouproll/state_other.go
new file mode 100644
index 000000000..0270c2e6f
--- /dev/null
+++ b/internal/grouproll/state_other.go
@@ -0,0 +1,17 @@
+//go:build !(linux || darwin)
+
+package grouproll
+
+import "os"
+
+// errUnsupportedSystem: carlos system group runs on Linux and macOS only
+// (spec §4); the session transport needs a pseudo-terminal.
+var errUnsupportedSystem = Refusal{Key: "windows"}
+
+func privateFile(string, int, int) (*os.File, error) { return nil, errUnsupportedSystem }
+
+func lstatOwner(string) (fileInfo, error) { return fileInfo{}, errUnsupportedSystem }
+
+func syncDirectory(string) error { return errUnsupportedSystem }
+
+func lockExclusive(*os.File) error { return errUnsupportedSystem }
diff --git a/internal/grouproll/state_test.go b/internal/grouproll/state_test.go
new file mode 100644
index 000000000..99a4369af
--- /dev/null
+++ b/internal/grouproll/state_test.go
@@ -0,0 +1,394 @@
+//go:build linux || darwin
+
+package grouproll
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// stateRoot returns a private state directory whose ancestors are checked
+// only up to the test's own temporary directory: the machine's TMPDIR
+// ancestry is not this package's to judge.
+func stateRoot(t *testing.T) string {
+ t.Helper()
+ base := t.TempDir()
+ // t.TempDir honours the umask, which may leave it group-writable.
+ must(t, os.Chmod(base, 0o700))
+ old := ancestorStop
+ ancestorStop = base
+ t.Cleanup(func() { ancestorStop = old })
+ root := filepath.Join(base, "state")
+ if err := os.Mkdir(root, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ return root
+}
+
+func testConfig(t *testing.T) Config {
+ t.Helper()
+ c, err := ValidateConfig(baseConfig())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c
+}
+
+func groupDir(root string, c Config) string {
+ sum := sha256.Sum256([]byte(c.GroupARN))
+ return filepath.Join(root, hex.EncodeToString(sum[:])[:32])
+}
+
+func TestStateRefusesUnsafe(t *testing.T) {
+ c := testConfig(t)
+ cases := map[string]struct {
+ setup func(t *testing.T, root string) string
+ want string
+ }{
+ "state dir 0755": {func(t *testing.T, root string) string {
+ must(t, os.Chmod(root, 0o755))
+ return root
+ }, "state_dir"},
+ "state dir missing": {func(t *testing.T, root string) string {
+ return filepath.Join(root, "absent")
+ }, "state_dir"},
+ "state dir owned by another uid": {func(t *testing.T, root string) string {
+ old := currentOwner
+ currentOwner = func() int { return old() + 1 }
+ t.Cleanup(func() { currentOwner = old })
+ return root
+ }, "state_dir"},
+ "state dir is a symlink": {func(t *testing.T, root string) string {
+ link := filepath.Join(filepath.Dir(root), "link")
+ must(t, os.Symlink(root, link))
+ return link
+ }, "unsafe_state"},
+ "symlinked ancestor": {func(t *testing.T, root string) string {
+ link := filepath.Join(filepath.Dir(root), "link")
+ must(t, os.Symlink(root, link))
+ inner := filepath.Join(root, "inner")
+ must(t, os.Mkdir(inner, 0o700))
+ return filepath.Join(link, "inner")
+ }, "unsafe_state"},
+ "group-writable ancestor": {func(t *testing.T, root string) string {
+ must(t, os.Chmod(root, 0o770))
+ inner := filepath.Join(root, "inner")
+ must(t, os.Mkdir(inner, 0o700))
+ return inner
+ }, "unsafe_state"},
+ "world-writable sticky ancestor": {func(t *testing.T, root string) string {
+ must(t, os.Chmod(root, 0o1777))
+ inner := filepath.Join(root, "inner")
+ must(t, os.Mkdir(inner, 0o700))
+ return inner
+ }, "unsafe_state"},
+ "group directory 0755": {func(t *testing.T, root string) string {
+ must(t, os.Mkdir(groupDir(root, c), 0o700))
+ must(t, os.Chmod(groupDir(root, c), 0o755))
+ return root
+ }, "unsafe_state"},
+ "group directory is a symlink": {func(t *testing.T, root string) string {
+ other := filepath.Join(root, "other")
+ must(t, os.Mkdir(other, 0o700))
+ must(t, os.Symlink(other, groupDir(root, c)))
+ return root
+ }, "unsafe_state"},
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ dir := tc.setup(t, stateRoot(t))
+ s, err := OpenState(dir, c, false)
+ if got := refusalKey(err); got != tc.want {
+ t.Fatalf("OpenState = %v, %q; want %q", s, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestStateRefusesUnsafeFiles(t *testing.T) {
+ c := testConfig(t)
+ root := stateRoot(t)
+ s, err := OpenState(root, c, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ active := filepath.Join(s.Directory(), "active-v2.json")
+ must(t, os.WriteFile(active, []byte(`{"transaction":"t"}`), 0o644))
+ if _, err := s.ActiveID(); refusalKey(err) != "unsafe_state" {
+ t.Fatalf("0644 active-v2.json: %v", err)
+ }
+ must(t, os.Remove(active))
+ must(t, os.Symlink(filepath.Join(root, "elsewhere"), active))
+ if _, err := s.ActiveID(); refusalKey(err) != "unsafe_state" {
+ t.Fatalf("symlinked active-v2.json: %v", err)
+ }
+ must(t, os.Remove(active))
+ must(t, os.WriteFile(filepath.Join(root, "x"), []byte(`{"transaction":"t"}`), 0o600))
+ must(t, os.Link(filepath.Join(root, "x"), active))
+ if _, err := s.ActiveID(); refusalKey(err) != "unsafe_state" {
+ t.Fatalf("hard-linked active-v2.json: %v", err)
+ }
+ must(t, os.Remove(active))
+ big := `{"transaction":"t","pad":"` + strings.Repeat("x", 65536) + `"}`
+ must(t, os.WriteFile(active, []byte(big), 0o600))
+ if _, err := s.ActiveID(); refusalKey(err) != "record" {
+ t.Fatalf("oversized active-v2.json: %v", err)
+ }
+}
+
+// TestStateIgnoresScriptFiles: V4. The script's files are invisible, and a
+// .v2.jsonl without "format":2 is refused.
+func TestStateIgnoresScriptFiles(t *testing.T) {
+ c := testConfig(t)
+ root := stateRoot(t)
+ s, err := OpenState(root, c, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ script := chained(t, []map[string]any{{"kind": "begin", "transaction": "abc", "config": c.Map()}})
+ must(t, os.WriteFile(filepath.Join(s.Directory(), "abc.jsonl"), script, 0o600))
+ must(t, os.WriteFile(filepath.Join(s.Directory(), "active.json"), []byte(`{"transaction":"abc"}`), 0o600))
+ if id, err := s.ActiveID(); err != nil || id != "" {
+ t.Fatalf("ActiveID = %q, %v; want none", id, err)
+ }
+ if _, err := s.Load("abc", true); refusalKey(err) != "record" {
+ t.Fatalf("Load of a script-only transaction: %v", err)
+ }
+ must(t, os.WriteFile(filepath.Join(s.Directory(), "abc.v2.jsonl"), script, 0o600))
+ for _, readonly := range []bool{true, false} {
+ if _, err := s.Load("abc", readonly); refusalKey(err) != "record" {
+ t.Fatalf("Load of a header without format 2 (readonly=%v): %v", readonly, err)
+ }
+ }
+ if _, err := s.ActiveID(); refusalKey(err) != "record" {
+ t.Fatalf("ActiveID with a format-less .v2.jsonl: %v", err)
+ }
+}
+
+func TestStateLifecycle(t *testing.T) {
+ c := testConfig(t)
+ root := stateRoot(t)
+ s, err := OpenState(root, c, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if s.Directory() != groupDir(root, c) {
+ t.Fatalf("Directory = %s", s.Directory())
+ }
+ header := Header{Transaction: "tx-1", IID: "i-0123456789abcdef0", New: strings.Repeat("b", 64), AttendedBy: "op"}
+ if _, err := s.Create(header); refusalKey(err) != "active" {
+ t.Fatalf("Create without the lock: %v", err)
+ }
+ if err := s.Finish(); refusalKey(err) != "busy" {
+ t.Fatalf("Finish without the lock: %v", err)
+ }
+ unlock, err := s.Lock()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer unlock()
+ j, err := s.Create(header)
+ if err != nil {
+ t.Fatal(err)
+ }
+ begin := j.Rows()[0]
+ if begin["kind"] != "begin" || begin["format"] != int64(2) || begin["transaction"] != "tx-1" ||
+ begin["new"] != header.New || begin["attended_by"] != "op" || begin["iid"] != header.IID {
+ t.Fatalf("begin = %#v", begin)
+ }
+ if _, ok := begin["header"]; ok {
+ t.Fatal("roll header carries a kind")
+ }
+ if _, err := j.Add("intent", map[string]any{"at_ms": int64(5), "op": "describe"}); err != nil {
+ t.Fatal(err)
+ }
+ j.Close()
+ if id, err := s.ActiveID(); err != nil || id != "tx-1" {
+ t.Fatalf("ActiveID = %q, %v", id, err)
+ }
+ if _, err := s.Create(Header{Transaction: "tx-2"}); refusalKey(err) != "active" {
+ t.Fatalf("second Create: %v", err)
+ }
+ for _, readonly := range []bool{true, false} {
+ l, err := s.Load("tx-1", readonly)
+ if err != nil {
+ t.Fatalf("Load(readonly=%v): %v", readonly, err)
+ }
+ if len(l.Rows()) != 2 {
+ t.Fatalf("rows = %d", len(l.Rows()))
+ }
+ l.Close()
+ }
+ if _, err := s.Load("../tx-1", true); refusalKey(err) != "record" {
+ t.Fatalf("Load of a bad id: %v", err)
+ }
+ other := testConfig(t)
+ other.Bucket = "other-bucket"
+ so, err := OpenState(root, other, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := so.Load("tx-1", true); refusalKey(err) != "scope" {
+ t.Fatalf("Load under another config: %v", err)
+ }
+
+ // A depart header's kind moves under "header", as the script does.
+ l, err := s.Load("tx-1", false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := l.Add("done", map[string]any{"outcome": "ok"}); err != nil {
+ t.Fatal(err)
+ }
+ l.Close()
+ if err := s.Finish(); err != nil {
+ t.Fatal(err)
+ }
+ if id, err := s.ActiveID(); err != nil || id != "" {
+ t.Fatalf("ActiveID after Finish = %q, %v", id, err)
+ }
+ d, err := s.Create(Header{Kind: "replace", Transaction: "tx-2", IID: "i-0123456789abcdef0", AttendedBy: "op"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ h := d.Rows()[0]
+ if hk, _ := h["header"].(map[string]any); hk["kind"] != "replace" {
+ t.Fatalf("depart begin = %#v", h)
+ }
+ if _, ok := h["new"]; ok {
+ t.Fatalf("depart begin carries new: %#v", h)
+ }
+
+ // The small state files.
+ if err := s.Write(s.DivergencePath(), map[string]any{"transaction": "tx-2", "phase": "Pending:Wait"}); err != nil {
+ t.Fatal(err)
+ }
+ v, err := s.Read(s.DivergencePath())
+ if err != nil || v.(map[string]any)["phase"] != "Pending:Wait" {
+ t.Fatalf("Read = %#v, %v", v, err)
+ }
+ if filepath.Base(s.ObservationPath()) != "provider-observation.json" || filepath.Base(s.DivergencePath()) != "provider-divergence.json" {
+ t.Fatal("state file names")
+ }
+ p, err := s.CreatePlanLog()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer p.Close()
+ if base := filepath.Base(p.Path()); !strings.HasPrefix(base, "plan-") || !strings.HasSuffix(base, ".log") || len(base) != len("plan-")+32+len(".log") {
+ t.Fatalf("plan log %s", base)
+ }
+ unlock()
+ if err := s.Write(s.DivergencePath(), map[string]any{}); refusalKey(err) != "busy" {
+ t.Fatalf("Write without the lock: %v", err)
+ }
+}
+
+func TestStateReadonlyCreatesNothing(t *testing.T) {
+ c := testConfig(t)
+ root := stateRoot(t)
+ if _, err := OpenState(root, c, true); refusalKey(err) != "record" {
+ t.Fatalf("readonly OpenState without a group directory: %v", err)
+ }
+ if _, err := os.Lstat(groupDir(root, c)); !os.IsNotExist(err) {
+ t.Fatalf("readonly OpenState created the group directory: %v", err)
+ }
+}
+
+func TestResolveStateDir(t *testing.T) {
+ env := func(m map[string]string) func(string) string {
+ return func(k string) string { return m[k] }
+ }
+ cases := []struct {
+ name string
+ env map[string]string
+ want string
+ }{
+ {"xdg", map[string]string{"XDG_STATE_HOME": "/x/state", "HOME": "/home/op"}, "/x/state/carlos/group"},
+ {"home", map[string]string{"HOME": "/home/op"}, "/home/op/.local/state/carlos/group"},
+ {"empty xdg", map[string]string{"XDG_STATE_HOME": "", "HOME": "/home/op"}, "/home/op/.local/state/carlos/group"},
+ {"relative xdg is ignored", map[string]string{"XDG_STATE_HOME": "rel", "HOME": "/home/op"}, "/home/op/.local/state/carlos/group"},
+ }
+ for _, tc := range cases {
+ got, err := ResolveStateDir(env(tc.env))
+ if err != nil || got != tc.want {
+ t.Errorf("%s: %q, %v; want %q", tc.name, got, err, tc.want)
+ }
+ }
+ for name, e := range map[string]map[string]string{
+ "empty home": {"HOME": ""},
+ "unset home": {},
+ "relative home": {"HOME": "home/op"},
+ "relative xdg, no home": {"XDG_STATE_HOME": "rel"},
+ } {
+ if _, err := ResolveStateDir(env(e)); refusalKey(err) != "unsafe_state" {
+ t.Errorf("%s: %v, want unsafe_state", name, err)
+ }
+ }
+}
+
+// TestLockRefusesSecondWriter: a second Lock in another process is busy.
+func TestLockRefusesSecondWriter(t *testing.T) {
+ if dir := os.Getenv("GROUPROLL_LOCK_HELPER"); dir != "" {
+ ancestorStop = os.Getenv("GROUPROLL_LOCK_STOP")
+ s, err := OpenState(dir, testConfig(t), false)
+ if err != nil {
+ os.Stdout.WriteString("open:" + refusalKey(err))
+ return
+ }
+ unlock, err := s.Lock()
+ if err != nil {
+ os.Stdout.WriteString("lock:" + refusalKey(err))
+ return
+ }
+ unlock()
+ os.Stdout.WriteString("lock:acquired")
+ return
+ }
+ c := testConfig(t)
+ root := stateRoot(t)
+ s, err := OpenState(root, c, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second := func() string {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestLockRefusesSecondWriter$")
+ cmd.Env = append(os.Environ(), "GROUPROLL_LOCK_HELPER="+root, "GROUPROLL_LOCK_STOP="+ancestorStop)
+ out, err := cmd.Output()
+ if err != nil {
+ t.Fatalf("helper: %v: %s", err, out)
+ }
+ s := string(out)
+ if i := strings.Index(s, "lock:"); i >= 0 {
+ s = s[i:]
+ }
+ if i := strings.IndexAny(s, "\n"); i >= 0 {
+ s = s[:i]
+ }
+ return strings.TrimSuffix(s, "PASS")
+ }
+ unlock, err := s.Lock()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := second(); got != "lock:busy" {
+ t.Fatalf("second writer while held: %q", got)
+ }
+ unlock()
+ if got := second(); got != "lock:acquired" {
+ t.Fatalf("second writer after release: %q", got)
+ }
+}
+
+func must(t *testing.T, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/grouproll/state_unix.go b/internal/grouproll/state_unix.go
new file mode 100644
index 000000000..a42e1af37
--- /dev/null
+++ b/internal/grouproll/state_unix.go
@@ -0,0 +1,77 @@
+//go:build linux || darwin
+
+package grouproll
+
+import (
+ "errors"
+ "os"
+ "syscall"
+)
+
+// privateFile opens path without following a symlink and refuses anything
+// but a regular 0600 file owned by owner with one link (script
+// private_file, :826-833). A symlink is "unsafe_state"; any other open
+// failure is "record".
+func privateFile(path string, flags int, owner int) (*os.File, error) {
+ fd, err := syscall.Open(path, flags|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0o600)
+ if err != nil {
+ if errors.Is(err, syscall.ELOOP) {
+ return nil, refuse("unsafe_state")
+ }
+ return nil, refuse("record")
+ }
+ var st syscall.Stat_t
+ if err := syscall.Fstat(fd, &st); err != nil {
+ syscall.Close(fd)
+ return nil, refuse("record")
+ }
+ if uint32(st.Mode)&syscall.S_IFMT != syscall.S_IFREG || int(st.Uid) != owner ||
+ uint32(st.Mode)&0o7777 != 0o600 || uint64(st.Nlink) != 1 {
+ syscall.Close(fd)
+ return nil, refuse("unsafe_state")
+ }
+ return os.NewFile(uintptr(fd), path), nil
+}
+
+// lstatOwner reads path's type, owner and mode without following it.
+func lstatOwner(path string) (fileInfo, error) {
+ var st syscall.Stat_t
+ if err := syscall.Lstat(path, &st); err != nil {
+ return fileInfo{}, err
+ }
+ mode := uint32(st.Mode)
+ return fileInfo{
+ dir: mode&syscall.S_IFMT == syscall.S_IFDIR,
+ symlink: mode&syscall.S_IFMT == syscall.S_IFLNK,
+ uid: int(st.Uid),
+ perm: mode & 0o7777,
+ }, nil
+}
+
+// syncDirectory fsyncs a directory so a create, rename or unlink in it is
+// durable (script sync_directory).
+func syncDirectory(path string) error {
+ fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
+ if err != nil {
+ return err
+ }
+ defer syscall.Close(fd)
+ return syscall.Fsync(fd)
+}
+
+// lockExclusive takes flock(LOCK_EX|LOCK_NB) on f; a held lock is "busy".
+func lockExclusive(f *os.File) error {
+ for {
+ err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
+ switch {
+ case err == nil:
+ return nil
+ case errors.Is(err, syscall.EINTR):
+ continue
+ case errors.Is(err, syscall.EWOULDBLOCK):
+ return refuse("busy")
+ default:
+ return refuse("record")
+ }
+ }
+}
diff --git a/internal/grouproll/testdata/journal-format2.golden b/internal/grouproll/testdata/journal-format2.golden
new file mode 100644
index 000000000..78c47f657
--- /dev/null
+++ b/internal/grouproll/testdata/journal-format2.golden
@@ -0,0 +1,2 @@
+{"attended_by":"a<b>&c","config":{"account":"000000000000","bucket":"example-deployment","deployment":"example","document":"AWS-StartNonInteractiveCommand","group":"example-group","group_arn":"arn:aws:autoscaling:eu-west-1:000000000000:autoScalingGroup:example:autoScalingGroupName/example-group","hook":"example-launch","min_release":"v0.34.0","profile":"example","region":"eu-west-1","state_dir":"/state","target_groups":["arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-8/8888888888888888","arn:aws:elasticloadbalancing:eu-west-1:000000000000:targetgroup/example-4/4444444444444444"]},"format":2,"hash":"dd7888abf28337ac141ae44b52595cdbf7645869c1cdec910f857b6303f123d8","iid":"i-0123456789abcdef0","kind":"begin","new":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","previous":"0000000000000000000000000000000000000000000000000000000000000000","seq":0,"transaction":"golden"}
+{"args":{"group":"example-group"},"at_ms":1762646400123,"hash":"86afb0917dcb32c4c7fb35374f9d0d7ea32f6fb3999e20a145af21932e832ce3","kind":"intent","op":"describe","previous":"dd7888abf28337ac141ae44b52595cdbf7645869c1cdec910f857b6303f123d8","seq":1,"session":null}
diff --git a/internal/grouproll/text.go b/internal/grouproll/text.go
new file mode 100644
index 000000000..d8c21e565
--- /dev/null
+++ b/internal/grouproll/text.go
@@ -0,0 +1,219 @@
+package grouproll
+
+import (
+ "fmt"
+ "regexp"
+ "sort"
+)
+
+// text is every operator string, keyed by the script's TEXT names. It is
+// the reviewed copy (copy review 2026-11-09) and changes only through a
+// copy review; no operator string is written anywhere else.
+var text = map[string]string{
+ "config": "Path to the deployment JSON config.",
+ "attended": "Name the person attending this run when no terminal is attached.",
+ "member": "Exact instance ID to maintain.",
+ "sha": "Verified release artifact SHA256 for this architecture.",
+ "transaction": "Transaction ID from the saved journal.",
+ "roll_transaction": "Choose an unused transaction ID before arming the fault harness. The `probe-` prefix is reserved.",
+ "plan": "Read readiness and list refusals. It changes no group or box state.",
+ "roll": "Roll one member to the named artifact.",
+ "rollback": "Restore this transaction's old artifact while in Standby.",
+ "resume": "Resume from the durable journal and current provider state.",
+ "return": "Return an already restarted and admitted member.",
+ "status": "Read the saved journal without contacting AWS.",
+ "abandon": "Close a transaction that has no group write intent.",
+ "close-lost": "Close an active transaction after confirming that its member is gone. Record failure.",
+ "close_lost_refused": "The member must be absent from the exact group and either terminated or absent from EC2.",
+ "lost_closed": "Transaction closed with outcome failed-member-lost. This does not record recovery.",
+ "divergence_retained": "Provider divergence flag retained: {path}",
+ "abandoned": "Transaction abandoned before any group write intent.",
+ "abandon_refused": "A write intent exists. Use resume, rollback or return.",
+ "line": "{phase}: {detail}",
+ "journal": "Journal: {path}",
+ "ready": "Ready for attended maintenance.",
+ "sequence": "Prepare, lower minimum, enter Standby, verify deregistration, permit, apply, verify, return, restore minimum, revoke.",
+ "refused": "Refused: {reason}",
+ "session_cleanup": "Session cleanup failed. The original session error is retained.",
+ "alert": "ALERT: {reason}. Keep the member and transaction for the operator.",
+ "fail": "FAIL: {reason}. Stop further rolls and resolve the provider contract.",
+ "done": "Member returned and permit revoked.",
+ "config_invalid": "Invalid deployment config",
+ "attended_required": "A terminal or --attended-by is required",
+ "unsafe_state": "State storage is missing, unsafe, or damaged.",
+ "busy": "Another operator holds the group lock",
+ "active": "An unfinished transaction already exists",
+ "record": "The transaction record is missing or corrupt",
+ "journal_kind": "This command cannot operate on this type of journal.",
+ "scope": "The configured group, account, region or target groups do not match",
+ "observation": "A matching approved no-hook provider observation is required",
+ "blocked": "Provider divergence blocks new rolls",
+ "shape": "The group must have min=desired=max=N, and N must be at least two.",
+ "members": "The member set or capacity changed outside this transaction",
+ "offline": "A required member is not Online in Session Manager",
+ "peer": "Every peer must be InService and healthy in both target groups",
+ "identity": "The identity reported by root status does not match this transaction.",
+ "admission": "The member is not ready: its edge is not healthy and admitted, or it has not published itself as a serving box",
+ "process": "The expected artifact and a new edge process are required",
+ "permit": "The permit is not accepted, unconsumed and bound to this action",
+ "prepare": "Signed artifact preparation or preserved configuration verification failed",
+ "already_applied": "The pointer was already applied",
+ "already_rolled_back": "The pointer was already rolled back",
+ "rollback_failed": "The pointer's previous rollback failed",
+ "release_floor": "The pointer version is below the configured min_release",
+ "release_version": "The pointer version is not a supported release version",
+ "held": "The member must remain in Standby with both target groups deregistered",
+ "timeout": "The 15-minute Standby wait expired",
+ "uncertain_action": "The consumed box action has no verified completion",
+ "return_intent": "A durable return intent for this process is required.",
+ "return_hook": "The provider used a return hook. No lifecycle action will be completed. Further rolls are blocked.",
+ "return_phase": "The provider has not completed this member's return",
+ "lost_member": "Member terminated or replaced. Probe failed.",
+ "unknown_phase": "The member's return phase is unknown. Probe failed.",
+ "hook": "The immutable launch hook must have a 900-second ABANDON default",
+ "remote": "The command on the member returned no complete result",
+ "api": "An AWS response is unavailable or invalid",
+ "rollback_refused": "Rollback requires this transaction's consumed apply in Standby",
+ "rollback_digest": "The installed artifact does not match the recorded old or new digest",
+ "unsupported": "Unsupported operation",
+ "divergence": "The provider used a return hook. The member is held in Standby. Further rolls are blocked.",
+ "replace": "Drain one member, terminate it and let the group launch its replacement.",
+ "remove": "Drain one member and terminate it without a replacement (scale-in).",
+ "depart_transaction": "Transaction ID to use. It may not start with - or probe-.",
+ "rule_drain": "Floor met: drain before the provider action (section 25).",
+ "rule_dr4": "Floor not met: DR-4's lock-free rule applies. Replace only lock-free members.",
+ "floor_refused": "The held-requests floor is not met, so this member cannot be drained. DR-4's lock-free rule applies.",
+ "floor_config": "The config has none of ha_floor, data_bucket, or data_prefix.",
+ "floor_error": "The held-requests floor could not be read, so the rule cannot be chosen. Nothing was changed.",
+ "lock_sweep_missed": "The lock sweep did not find the lock of moved host {host}",
+ "data_bucket_mismatch": "The member's edges file names data bucket {bucket}, not the configured data bucket.",
+ "cancel_drain": "End a failed drain of this member: drain --cancel on the box, which lifts the fence.",
+ "cancel_refused": "cancel-drain needs this member's transaction after a failed drain: closed, or stopped while its drain was still moving hosts",
+ "cancel_failed": "drain --cancel did not finish. The fence stays: {detail}",
+ "cancelled": "The drain was cancelled and the start fence removed.",
+ "floor_box": "Live box {box} does not publish ha_take: 1",
+ "floor_unreadable": "The edges file {key} cannot be read",
+ "floor_template": "The pinned launch template boots release {release}, below ha_floor",
+ "floor_version": "The roll's release {release} is below ha_floor",
+ "floor_template_sha": "The pinned launch template boots artifact {sha}, release {release}, below ha_floor",
+ "floor_sha": "Artifact {sha} cannot be mapped to its release: {why}",
+ "release_key": "the config has no release_public_key",
+ "release_unreadable": "the router pointer {key} cannot be read",
+ "release_scoped": "the router pointer {key} is signed by a scoped key, and router pointers take the root key only",
+ "release_signature": "the router pointer {key} does not verify under release_public_key",
+ "release_invalid": "the router pointer {key} is not a valid router pointer for channel {channel}",
+ "release_cancelled": "the router pointer {key} names no current release",
+ "release_unknown": "no release in channels {channels} has a {platform} artifact with this SHA256",
+ "release_ambiguous": "the SHA256 names more than one release: {versions}",
+ "release_uncomparable": "release {release} is not a vX.Y.Z version, so it cannot be compared",
+ "release_mismatch": "the member prepared release {prepared}, but the signed pointer says release {release}",
+ "drain_failed": "The drain failed. The member was returned to service, and the group shape was restored.",
+ "drain_cancel": "The member stays fenced and draining. To end the drain, run: carlos system group cancel-drain --config {config} --member {iid} --transaction {transaction}",
+ "drain_reason": "drain: {reason}",
+ "drain_report": "The drain printed no valid report for this transaction",
+ "drain_moving": "The member's agent may still be moving hosts for this transaction, so the member stays in Standby. Run carlos system group cancel-drain --config {config} --member {iid} --transaction {transaction}, then carlos system group return --config {config} --transaction {transaction}",
+ "fence_missing": "The start fence for this transaction is not in place.",
+ "drain_void": "The agent does not report a finished drain of this transaction",
+ "incarnation": "The member's agent restarted after the drain, so the drain no longer counts",
+ "lock_held": "A lock still names the member: {hosts}",
+ "data_bucket": "The member's edges file names no data bucket in this region",
+ "edge_running": "carlos-edge.service` is still running after the stop. The member is held in Standby.",
+ "h4": "Only the member's EnterStandby with decrement may lower desired capacity.",
+ "desired_changed": "Desired capacity or membership changed when the member was terminated",
+ "remove_minimum": "remove` must leave at least 2 members.",
+ "remove_pools": "The survivors would leave pool {pool} with no server",
+ "remove_pools_unknown": "The member's served_pools are unknown",
+ "watch_timeout": "The replacement or the departure did not finish in time",
+ "lock_held_after_stop": "A lock still names the member after its edge stopped. The member is held in Standby",
+ "terminate_failed": "The member's termination failed, was cancelled or never arrived, and was retried. It stays in Standby with its edge stopped and its fence in place. Resolve the provider error, then run resume to try again",
+ "terminate_left_standby": "The member left Standby without being terminated. Its edge is stopped and its fence is in place. Investigate before running resume or close-lost",
+ "terminate_unsettled": "The termination activity succeeded but the group still shows the member in Standby. Check the group, then run resume",
+ "terminate_stuck": "The termination activity is still running after 10 minutes. Check it in the console, then run resume",
+ "terminate_status": "The termination activity has an unknown status. Check it in the console, then run resume",
+ "fence_moot": "The member is gone, so its start fence went with it. No fence-clear is needed.",
+ "replaced": "Member replaced.",
+ "removed": "Member removed. Set box_count to {n} in the region's tofu and apply. The plan should show no instance change.",
+ "probe_help": "Probe an unchanged member through Auto Scaling Standby under the group lock.",
+ "probe_probe": "Observe an unchanged member leaving and returning without a lifecycle hook.",
+ "probe_unchanged": "The probe requires the original binary and edge process",
+ "probe_read_only": "The probe permits root status reads only",
+ "root_refused": "Run this as the deployment's operator account, not as root.",
+ "on_box": "This command runs on an operator machine, never on a carlos box.",
+ "windows": "carlos system group does not run on Windows.",
+ "profile_identity": "Profile {profile} does not provide one caller identity on every resolution ({why}). Use static keys, an SSO profile, or an assume-role profile with role_session_name.",
+ "plugin_missing": "The Session Manager plugin (session-manager-plugin) is not on PATH.",
+ "plugin_old": "session-manager-plugin {version} is too old. Version {floor} or later is required.",
+ "state_dir": "The state directory {path} is missing, is not owned by you, or is not private (0700).",
+ "usage_positional": "carlos system group takes flags only, for example --member i-0abc. Unexpected argument: {arg}",
+ "config_required": "--config is required. Name the deployment's group config file.",
+ "help_group": "Attended maintenance of one member of a region's Auto Scaling group: roll it to a new release, replace it, or remove it, one transaction at a time. Run it from the deployment's operator account.",
+ "help_probe": "The Standby observation probe: park an unchanged member and return it to record that the group has no return hook.",
+ "docs_cli_system_group": "#### carlos system group: maintain one group member\n\nAttended maintenance of one member of a region's Auto Scaling group. It replaces\n`scripts/region-group-roll.py`. Run it from the deployment's operator account on\nthe operator machine named in the card. Never run it as root or on a box. It\nneeds the AWS profile named in the group config and the Session Manager plugin\non PATH. Every command takes flags only. `--config` names the group config file.\n\n```sh\ncarlos system group plan --config ie.json --member i-0abc --to-sha256 <sha>\ncarlos system group roll --config ie.json --member i-0abc --to-sha256 <sha>\ncarlos system group replace --config ie.json --member i-0abc\ncarlos system group remove --config ie.json --member i-0abc\ncarlos system group resume --config ie.json --transaction <id>\ncarlos system group status --config ie.json --transaction <id>\ncarlos system group cancel-drain --config ie.json --member i-0abc --transaction <id>\ncarlos system group probe start --config ie.json --member i-0abc\n```\n\nOne transaction runs per group at a time. A replace or remove drains the member\nfirst, so its hosts move to other members before the member stops. If a step\ncannot be proved, the command stops and keeps the transaction for `resume`. It\nnever guesses. `plan` changes nothing. `status` reads the saved transaction\nwithout contacting AWS.",
+}
+
+var placeholder = regexp.MustCompile(`\{([a-z_]+)\}`)
+
+// Text renders the string for key, filling each {name} placeholder from
+// args, given as name, value pairs. An unknown key, an odd argument list, a
+// placeholder without a value, or a value no placeholder takes is a
+// programming error and panics; TestTextRendersEveryKey renders every key.
+func Text(key string, args ...string) string {
+ raw, ok := text[key]
+ if !ok {
+ panic(fmt.Sprintf("grouproll: unknown text key %q", key))
+ }
+ if len(args)%2 != 0 {
+ panic(fmt.Sprintf("grouproll: text %q: odd argument list", key))
+ }
+ values := make(map[string]string, len(args)/2)
+ for i := 0; i < len(args); i += 2 {
+ values[args[i]] = args[i+1]
+ }
+ used := map[string]bool{}
+ out := placeholder.ReplaceAllStringFunc(raw, func(m string) string {
+ name := m[1 : len(m)-1]
+ v, ok := values[name]
+ if !ok {
+ panic(fmt.Sprintf("grouproll: text %q: no value for {%s}", key, name))
+ }
+ used[name] = true
+ return v
+ })
+ for name := range values {
+ if !used[name] {
+ panic(fmt.Sprintf("grouproll: text %q takes no {%s}", key, name))
+ }
+ }
+ return out
+}
+
+// Refusal is a refused operation: the operator sees Text(Key, Args).
+type Refusal struct {
+ Key string
+ Args map[string]string
+}
+
+func (r Refusal) Error() string {
+ names := make([]string, 0, len(r.Args))
+ for name := range r.Args {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ args := make([]string, 0, 2*len(names))
+ for _, name := range names {
+ args = append(args, name, r.Args[name])
+ }
+ return Text(r.Key, args...)
+}
+
+// refuse returns the Refusal for key with name, value argument pairs.
+func refuse(key string, args ...string) error {
+ r := Refusal{Key: key}
+ if len(args) > 0 {
+ r.Args = make(map[string]string, len(args)/2)
+ for i := 0; i+1 < len(args); i += 2 {
+ r.Args[args[i]] = args[i+1]
+ }
+ }
+ return r
+}
diff --git a/internal/grouproll/text_test.go b/internal/grouproll/text_test.go
new file mode 100644
index 000000000..91f722e39
--- /dev/null
+++ b/internal/grouproll/text_test.go
@@ -0,0 +1,65 @@
+package grouproll
+
+import (
+ "regexp"
+ "strings"
+ "testing"
+)
+
+var placeholderPattern = regexp.MustCompile(`\{([a-z_]+)\}`)
+
+// TestTextRendersEveryKey renders each approved string with a dummy value
+// for every placeholder it names. A key whose text names a placeholder
+// Text cannot fill, or leaves a brace behind, fails here.
+func TestTextRendersEveryKey(t *testing.T) {
+ if len(text) != 139 {
+ t.Fatalf("text has %d keys, want the 139 approved", len(text))
+ }
+ for key, raw := range text {
+ var args []string
+ seen := map[string]bool{}
+ for _, m := range placeholderPattern.FindAllStringSubmatch(raw, -1) {
+ if !seen[m[1]] {
+ seen[m[1]] = true
+ args = append(args, m[1], "<"+m[1]+">")
+ }
+ }
+ got := Text(key, args...)
+ if strings.ContainsAny(got, "{}") {
+ t.Errorf("%s: unrendered brace in %q", key, got)
+ }
+ for name := range seen {
+ if !strings.Contains(got, "<"+name+">") {
+ t.Errorf("%s: %s not substituted: %q", key, name, got)
+ }
+ }
+ }
+}
+
+func TestTextRefusesProgrammingErrors(t *testing.T) {
+ for name, call := range map[string]func(){
+ "unknown key": func() { Text("no_such_key") },
+ "missing placeholder": func() { Text("journal") },
+ "odd args": func() { Text("journal", "path") },
+ "unused arg": func() { Text("journal", "path", "/p", "extra", "x") },
+ } {
+ t.Run(name, func(t *testing.T) {
+ defer func() {
+ if recover() == nil {
+ t.Fatal("no panic")
+ }
+ }()
+ call()
+ })
+ }
+ if got := Text("journal", "path", "/p"); got != "Journal: /p" {
+ t.Fatalf("Text = %q", got)
+ }
+ if got := Text("drain_moving", "config", "c.json", "iid", "i-1", "transaction", "t"); strings.Contains(got, "{") {
+ t.Fatalf("repeated placeholder: %q", got)
+ }
+ r := Refusal{Key: "state_dir", Args: map[string]string{"path": "/s"}}
+ if r.Error() != Text("state_dir", "path", "/s") {
+ t.Fatalf("Refusal.Error = %q", r.Error())
+ }
+}
diff --git a/region_ha_boundary_test.go b/region_ha_boundary_test.go
index fe75136a3..c8417ff5f 100644
--- a/region_ha_boundary_test.go
+++ b/region_ha_boundary_test.go
@@ -41,6 +41,12 @@ var regionHACoreFiles = []string{
"internal/host/boxreference.go",
"internal/status/fleet.go",
"internal/host/agententry.go",
+ "internal/grouproll/config.go",
+ "internal/grouproll/journal.go",
+ "internal/grouproll/state.go",
+ "internal/grouproll/state_unix.go",
+ "internal/grouproll/state_other.go",
+ "internal/grouproll/text.go",
}
// regionHAAdapterFiles are spec 2's AWS adapters. Each is named for AWS so