gunk-dev/the-valley

flake.nix

source0e7b0770dfbemain's published tip history
29.8 KiB
1{
2 description = "the-valley: the CUE domain schema for a valley host, and the NixOS module that installs one";
3
4 inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
5
6 outputs =
7 { self, nixpkgs }:
8 let
9 lib = nixpkgs.lib;
10 # Checks use import-from-derivation (the module's cue export), so they
11 # are only defined for the system that can actually build them here.
12 systems = [ "x86_64-linux" ];
13
14 # The integrator's CLI (bin/valley) wrapped for `nix run`. The script
15 # itself must keep running bare from any checkout — the package is the
16 # second of its two shipping modes, never a dependency of the first.
17 valleyScriptFor =
18 pkgs:
19 pkgs.writeShellApplication {
20 name = "valley";
21 runtimeInputs = [
22 pkgs.git
23 pkgs.natscli # tail and replay only; every other verb needs just git
24 ];
25 text = builtins.readFile ./bin/valley;
26 };
27
28 # The installed package: the wrapped script plus the shell completions,
29 # at the standard paths home-manager/NixOS auto-link.
30 valleyCliFor =
31 pkgs:
32 pkgs.symlinkJoin {
33 name = "valley";
34 paths = [ (valleyScriptFor pkgs) ];
35 nativeBuildInputs = [ pkgs.installShellFiles ];
36 postBuild = ''
37 installShellCompletion --bash --name valley ${./completions/valley.bash}
38 installShellCompletion --zsh --name _valley ${./completions/_valley}
39 '';
40 };
41
42 # Markdown prose is filled paragraphs hard-wrapped at 100 columns
43 # (ida-1ec03b1). One prettier invocation backs both the formatter app
44 # and the prose-format check, so the two cannot drift.
45 # Embedded-language formatting is off so fenced code blocks pass
46 # through byte-for-byte.
47 proseFmtArgs = "--prose-wrap always --print-width 100 --embedded-language-formatting off";
48
49 # `nix run .#fmt` — rewrap every tracked *.md in the repo to 100 columns.
50 proseFmtFor =
51 pkgs:
52 pkgs.writeShellApplication {
53 name = "valley-fmt";
54 runtimeInputs = [
55 pkgs.git
56 pkgs.prettier
57 ];
58 text = ''
59 cd "$(git rev-parse --show-toplevel)"
60 git ls-files -z -- '*.md' | xargs -0 --no-run-if-empty \
61 prettier ${proseFmtArgs} --write
62 '';
63 };
64 in
65 {
66 nixosModules.valley-host = ./nix/valley-host.nix;
67 nixosModules.default = self.nixosModules.valley-host;
68
69 apps = lib.genAttrs systems (system: {
70 fmt = {
71 type = "app";
72 program = lib.getExe (proseFmtFor nixpkgs.legacyPackages.${system});
73 };
74 });
75
76 packages = lib.genAttrs systems (
77 system:
78 let
79 valley = valleyCliFor nixpkgs.legacyPackages.${system};
80 in
81 {
82 inherit valley;
83 default = valley;
84 }
85 );
86
87 checks = lib.genAttrs systems (
88 system:
89 let
90 pkgs = nixpkgs.legacyPackages.${system};
91
92 # Eval-only instantiation of the module — catches option-surface
93 # and cue-export regressions without building or booting anything.
94 # Each check host shares the machine baseline and supplies its own
95 # declaration (and, where the declaration asks for backup, the
96 # secret paths).
97 mkHost =
98 module:
99 lib.nixosSystem {
100 inherit system;
101 modules = [
102 self.nixosModules.default
103 {
104 fileSystems."/" = {
105 device = "/dev/disk/by-label/nixos";
106 fsType = "ext4";
107 };
108 boot.loader.grub.enable = false;
109 system.stateVersion = "25.11";
110 services.valley = {
111 enable = true;
112 authorizedKeys = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPlaceholderKeyForEvalOnlyCheck0 valley-check" ];
113 };
114 }
115 module
116 ];
117 };
118
119 # The example declaration enables backup, so this host supplies
120 # the four secret paths (eval-only placeholders).
121 host = mkHost {
122 services.valley = {
123 config = ./examples/host.cue;
124 backup = {
125 repositoryFile = "/run/agenix/valley-restic-repo";
126 passwordFile = "/run/agenix/valley-restic-password";
127 sshKeyFile = "/run/agenix/valley-git-ssh-key";
128 knownHostsFile = "/var/lib/valley-backup/known_hosts";
129 };
130 };
131 };
132
133 # A declaration without a backup block predates the field and must
134 # keep evaluating exactly as before: zero restic machinery.
135 noBackupHost = mkHost {
136 services.valley.config = pkgs.writeText "no-backup-host.cue" ''
137 package valley
138 projects: "the-valley": {}
139 '';
140 };
141
142 # The example declaration with the secret paths left unset: the
143 # module must refuse with assertions naming the missing options.
144 noSecretsHost = mkHost {
145 services.valley.config = ./examples/host.cue;
146 };
147
148 # Bus enabled, minimal declaration. The bus-e2e check drives this
149 # host's rendered hooks and stream-init against a real server.
150 busHost = mkHost {
151 services.valley = {
152 config = pkgs.writeText "bus-host.cue" ''
153 package valley
154 projects: "events-pilot": {}
155 '';
156 bus.enable = true;
157 };
158 };
159
160 # Two mirror URLs the sandbox can serve: git resolves a relative
161 # URL against the pushing repo's directory, so the mirror-e2e
162 # check drives the rendered script with no substitution at all —
163 # one reachable sibling repo, one that does not exist.
164 mirrorHost = mkHost {
165 services.valley.config = pkgs.writeText "mirror-host.cue" ''
166 package valley
167 projects: "mirror-pilot": mirrors: ["../mirror.git"]
168 projects: "dead-mirror": mirrors: ["../nope.git"]
169 '';
170 };
171
172 failedAssertions = builtins.filter (a: !a.assertion) (
173 host.config.assertions
174 ++ noBackupHost.config.assertions
175 ++ busHost.config.assertions
176 ++ mirrorHost.config.assertions
177 );
178
179 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
180
181 resticRenderedWithoutDeclaration =
182 noBackupHost.config.systemd.services ? "restic-backups-valley"
183 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
184
185 # The bus defaults off; a host that never asked for one must
186 # render zero bus machinery.
187 busRenderedWithoutEnable =
188 noBackupHost.config.systemd.services ? valley-bus
189 || noBackupHost.config.systemd.services ? valley-bus-init;
190 in
191 {
192 # The CLI must stay a lint-clean script whose help verb answers
193 # without a repo or a remote — the cheap end of its eviction clause
194 # (dcr-74c3158); anything needing more graduates instead. The
195 # completions are held to the same bar, and the installed package
196 # must carry them at the auto-linked paths.
197 valley-cli =
198 let
199 valley = valleyCliFor pkgs;
200 in
201 pkgs.runCommand "valley-cli"
202 {
203 nativeBuildInputs = [
204 pkgs.shellcheck
205 pkgs.zsh
206 valley
207 ];
208 }
209 ''
210 shellcheck ${./bin/valley}
211 shellcheck ${./completions/valley.bash}
212 # shellcheck cannot lint zsh; a bare parse is the cheap check.
213 zsh -n ${./completions/_valley}
214 valley help > help.txt
215 grep -q '^usage: valley' help.txt
216 test -f ${valley}/share/bash-completion/completions/valley
217 test -f ${valley}/share/zsh/site-functions/_valley
218 touch $out
219 '';
220
221 # Markdown prose format (ida-1ec03b1): the check is formatter
222 # idempotence — formatting the tree must change nothing. On failure,
223 # fix with `nix run .#fmt`.
224 prose-format =
225 pkgs.runCommand "valley-prose-format"
226 {
227 nativeBuildInputs = [ pkgs.prettier ];
228 }
229 ''
230 cd ${self}
231 find . -name '*.md' -print0 | xargs -0 --no-run-if-empty \
232 prettier ${proseFmtArgs} --check
233 touch $out
234 '';
235
236 # The example host declaration must vet against the schema, and the
237 # schema must reject what it claims to reject: unsafe project names,
238 # unknown project fields, stray top-level fields (typos, deployment
239 # concerns), and malformed backup policy (machine concerns, targets
240 # without an implementation, non-positive retention). CUE closedness
241 # is easy to regress silently — e.g. embedding #Host instead of
242 # referencing it opens the schema — so the rejections are pinned
243 # here.
244 cue-vet =
245 let
246 invalidConfigs = {
247 unsafe-project-name = ''
248 package valley
249 projects: ".hidden": {}
250 '';
251 unknown-project-field = ''
252 package valley
253 projects: ok: dataDir: "/srv/git"
254 '';
255 top-level-typo = ''
256 package valley
257 project: oops: {}
258 '';
259 deployment-concern-in-cue = ''
260 package valley
261 user: "git"
262 projects: ok: {}
263 '';
264 machine-concern-in-backup = ''
265 package valley
266 projects: ok: {}
267 backup: repositoryFile: "/run/agenix/valley-restic-repo"
268 '';
269 unimplemented-backup-target = ''
270 package valley
271 projects: ok: {}
272 backup: target: "restic-s3"
273 '';
274 negative-retention = ''
275 package valley
276 projects: ok: {}
277 backup: retention: daily: -1
278 '';
279 };
280 in
281 pkgs.runCommand "valley-cue-vet"
282 {
283 nativeBuildInputs = [ pkgs.cue ];
284 }
285 ''
286 cue vet -c ${./schema/valley.cue} ${./examples/host.cue}
287 cue export ${./schema/valley.cue} ${./examples/host.cue} > example.json
288 grep -q 'gunk-dev/the-valley' example.json
289 grep -q 'restic-sftp' example.json
290
291 # A declaration without a backup block must stay valid —
292 # consumers written before the field existed keep vetting.
293 cue vet -c ${./schema/valley.cue} ${pkgs.writeText "no-backup.cue" ''
294 package valley
295 projects: "the-valley": {}
296 ''}
297
298 # The event schema accepts what the publisher hook emits …
299 cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated.json" ''
300 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"}
301 ''}
302 # … and stays closed: a field outside the git-derivable
303 # identity — wall-clock time, a hostname — must be rejected,
304 # or replay determinism silently dies.
305 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-timestamped.json" ''
306 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3","time":"2026-07-16T00:00:00Z"}
307 ''}; then
308 echo "cue-vet: expected the timestamped ref-updated payload to be rejected" >&2
309 exit 1
310 fi
311 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-short-sha.json" ''
312 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe"}
313 ''}; then
314 echo "cue-vet: expected the abbreviated object id to be rejected" >&2
315 exit 1
316 fi
317
318 ${lib.concatStrings (
319 lib.mapAttrsToList (name: cfg: ''
320 if cue vet -c ${./schema/valley.cue} ${pkgs.writeText "${name}.cue" cfg}; then
321 echo "cue-vet: expected invalid config '${name}' to be rejected" >&2
322 exit 1
323 fi
324 '') invalidConfigs
325 )}
326 touch $out
327 '';
328
329 module-eval =
330 if failedAssertions != [ ] then
331 throw "valley module-eval: failed assertions: ${lib.concatMapStringsSep "; " (a: a.message) failedAssertions}"
332 else if resticRenderedWithoutDeclaration then
333 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
334 else if busRenderedWithoutEnable then
335 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
336 else if
337 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
338 then
339 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
340 else
341 pkgs.runCommand "valley-module-eval"
342 {
343 initScript = host.config.systemd.services.valley-init.script;
344 sshdConfig = host.config.services.openssh.extraConfig;
345 resticService = host.config.systemd.units."restic-backups-valley.service".text;
346 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
347 passAsFile = [
348 "initScript"
349 "sshdConfig"
350 "resticService"
351 "resticTimer"
352 ];
353 }
354 ''
355 # The repo init list and mirror hook must be generated from
356 # the CUE export, and the git user's sshd Match block must
357 # be terminated so it cannot scope later config.
358 grep -q "the-valley" "$initScriptPath"
359 grep -q "valley-mirrors" "$initScriptPath"
360 grep -q "Match All" "$sshdConfigPath"
361
362 # The mirror publishes main and tags only — a heads glob
363 # would publish every topic branch awaiting review — with
364 # --prune for tag deletions and a sweep that unpublishes
365 # any other head (--prune cannot: it ignores non-glob
366 # refspecs). Never --mirror: it also deletes remote-only
367 # refs, and GitHub's read-only refs/pull/* fails every such
368 # push. Follow the hook chain from the init script to the
369 # rendered push script and pin the invocation there.
370 mirrorHook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-[^ ]*' "$initScriptPath" | head -n1)"
371 mirrorPush="$(grep -o '/nix/store/[^ ]*-valley-mirror-push-[^ ]*' "$mirrorHook" | head -n1)"
372 grep -q -- 'push --prune' "$mirrorPush"
373 grep -qF -- '+refs/heads/main:refs/heads/main' "$mirrorPush"
374 grep -qF -- '+refs/tags/*:refs/tags/*' "$mirrorPush"
375 grep -qF -- 'ls-remote --heads' "$mirrorPush"
376 grep -qF -- 'push "$url" --delete' "$mirrorPush"
377 if grep -qF -- '+refs/heads/*:refs/heads/*' "$mirrorPush"; then
378 echo "module-eval: mirror push regressed to publishing every head" >&2
379 exit 1
380 fi
381 if grep -q -- '--mirror' "$mirrorPush"; then
382 echo "module-eval: mirror push regressed to --mirror" >&2
383 exit 1
384 fi
385 # Deletions must never reach a namespace the mirror owns.
386 if grep -q 'refs/pull' "$mirrorPush"; then
387 echo "module-eval: mirror push must not name refs/pull/*" >&2
388 exit 1
389 fi
390
391 # The rendered restic units must back up the data directory
392 # to the consumer-supplied repository with the declared
393 # retention over a pinned host key, on the declared cadence.
394 grep -q "RESTIC_REPOSITORY_FILE=/run/agenix/valley-restic-repo" "$resticServicePath"
395 grep -q -- "--keep-daily 7 --keep-weekly 4 --keep-monthly 6" "$resticServicePath"
396 grep -q "UserKnownHostsFile=/var/lib/valley-backup/known_hosts" "$resticServicePath"
397 grep -q "BatchMode=yes" "$resticServicePath"
398 grep -q "OnCalendar=03:30" "$resticTimerPath"
399
400 # The backup paths render as a --files-from list: follow
401 # ExecStartPre to that list and pin the data directory.
402 preStart="$(sed -n 's/^ExecStartPre=//p' "$resticServicePath" | head -n1)"
403 staticPaths="$(grep -o '/nix/store/[^ ]*-staticPaths' "$preStart" | head -n1)"
404 grep -qx "/srv/git" "$staticPaths"
405 touch $out
406 '';
407
408 # What a mirror ends up holding, end to end and unmocked: a bare
409 # repo wired with the real rendered hooks, pushed to for real, and
410 # a second bare repo standing in for the mirror. The refspec is
411 # easy to get subtly wrong — --prune ignores the non-glob heads
412 # refspec, so pruning heads is the sweep's job — and only running
413 # git can tell. Relative mirror URLs (mirrorHost) resolve against
414 # the pushing repo, so the shipped scripts run with no
415 # substitution: this is exactly what a host executes.
416 mirror-e2e =
417 pkgs.runCommand "valley-mirror-e2e"
418 {
419 nativeBuildInputs = [ pkgs.git ];
420 initScript = mirrorHost.config.systemd.services.valley-init.script;
421 passAsFile = [ "initScript" ];
422 }
423 ''
424 export HOME="$TMPDIR"
425 export GIT_CONFIG_NOSYSTEM=1
426 git config --global user.name valley-check
427 git config --global user.email valley-check@localhost
428 git config --global init.defaultBranch main
429 cd "$TMPDIR"
430
431 wait_for() {
432 for _ in $(seq 1 150); do
433 "$@" >/dev/null 2>&1 && return 0
434 sleep 0.2
435 done
436 echo "mirror-e2e: timed out waiting for: $*" >&2
437 return 1
438 }
439 heads() { git -C mirror.git for-each-ref --format='%(refname)' refs/heads; }
440 tags() { git -C mirror.git for-each-ref --format='%(refname)' refs/tags; }
441 mirror_main_is() { [ "$(git -C mirror.git rev-parse main)" = "$tip" ]; }
442 only_main() { [ "$(heads)" = refs/heads/main ]; }
443
444 # A primary repo wired exactly as valley-init wires it, with
445 # the real store paths followed from the rendered init script.
446 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
447 mhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-mirror-pilot' "$initScriptPath" | head -n1)"
448 deadhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-dead-mirror' "$initScriptPath" | head -n1)"
449 test -x "$dispatch" && test -x "$mhook" && test -x "$deadhook"
450 wire() {
451 mkdir -p "$1/hooks/post-receive.d"
452 ln -s "$dispatch" "$1/hooks/post-receive"
453 ln -s "$2" "$1/hooks/post-receive.d/valley-mirrors"
454 }
455
456 # The mirror as it stands today: every head and tag of the
457 # primary, topic branches included. Seeded before the hook is
458 # wired, so nothing sweeps it out from under the setup.
459 git init --quiet --bare mirror-pilot.git
460 git init --quiet --bare mirror.git
461 git clone --quiet "$PWD/mirror-pilot.git" work
462 git -C work commit --quiet --allow-empty -m one
463 git -C work tag v1
464 git -C work tag doomed
465 for b in idea/one idea/two; do git -C work branch "$b"; done
466 git -C work push --quiet origin \
467 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
468 git -C mirror-pilot.git push --quiet ../mirror.git \
469 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
470 [ "$(heads | wc -l)" -eq 3 ]
471 wire mirror-pilot.git "$mhook"
472
473 # A real push to the primary — a topic branch alongside main,
474 # and a tag deleted. The hook replicates asynchronously, so
475 # wait on main's new tip before judging the rest.
476 git -C work commit --quiet --allow-empty -m two
477 git -C work tag -d doomed >/dev/null
478 git -C work branch idea/three
479 git -C work push --quiet --follow-tags origin main idea/three
480 git -C work push --quiet --delete origin doomed
481 tip="$(git -C work rev-parse HEAD)"
482 wait_for mirror_main_is
483
484 # main and the tags are published; nothing else is, and the
485 # topic branches that were on the mirror are gone. The sweep
486 # is a second push, so it converges just after main lands.
487 wait_for only_main
488 [ "$(tags)" = refs/tags/v1 ]
489
490 # A branch that appears on the mirror by any other route is
491 # unpublished on the next push.
492 git -C mirror.git branch sneaky main
493 git -C work commit --quiet --allow-empty -m three
494 git -C work push --quiet origin main
495 tip="$(git -C work rev-parse HEAD)"
496 wait_for mirror_main_is
497 wait_for only_main
498
499 # An unreachable mirror costs a log line, never the push: the
500 # hook must return promptly and the push must succeed.
501 git init --quiet --bare dead-mirror.git
502 wire dead-mirror.git "$deadhook"
503 git clone --quiet "$PWD/dead-mirror.git" deadwork
504 git -C deadwork commit --quiet --allow-empty -m one
505 timeout 60 git -C deadwork push --quiet origin main
506 [ "$(git -C dead-mirror.git rev-parse main)" = "$(git -C deadwork rev-parse HEAD)" ]
507
508 touch $out
509 '';
510
511 # Phase 1's exit criteria, end to end and unmocked: a push to a
512 # bare repo wired with the real rendered hooks produces a
513 # ref-updated event on a real JetStream server within seconds,
514 # visible in `valley tail`; replaying the repo's refs is
515 # deterministic; and a dead bus never fails a push. The hook and
516 # stream-init scripts are followed from the rendered unit scripts,
517 # so the check exercises exactly what a host would run — only the
518 # server invocation differs (the sandbox cannot write /srv), same
519 # binary and flags, relocated storage.
520 bus-e2e =
521 pkgs.runCommand "valley-bus-e2e"
522 {
523 nativeBuildInputs = [
524 pkgs.git
525 pkgs.natscli
526 pkgs.nats-server
527 pkgs.jq
528 pkgs.cue
529 (valleyScriptFor pkgs)
530 ];
531 initScript = busHost.config.systemd.services.valley-init.script;
532 busInitScript = busHost.config.systemd.services.valley-bus-init.script;
533 passAsFile = [
534 "initScript"
535 "busInitScript"
536 ];
537 }
538 ''
539 export HOME="$TMPDIR"
540 export NATS_URL=nats://127.0.0.1:4222
541 export GIT_CONFIG_NOSYSTEM=1
542 git config --global user.name valley-check
543 git config --global user.email valley-check@localhost
544 git config --global init.defaultBranch main
545
546 wait_for() {
547 for _ in $(seq 1 150); do
548 "$@" >/dev/null 2>&1 && return 0
549 sleep 0.2
550 done
551 echo "bus-e2e: timed out waiting for: $*" >&2
552 return 1
553 }
554
555 nats-server --addr 127.0.0.1 --port 4222 --jetstream \
556 --store_dir "$TMPDIR/js" &
557 server_pid=$!
558
559 # The real stream-init script the module renders.
560 bash -eu "$busInitScriptPath"
561 nats stream info valley >/dev/null
562
563 # A bare repo wired exactly as valley-init wires it, with the
564 # real store paths followed from the rendered init script.
565 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
566 bushook="$(grep -o '/nix/store/[^ ]*-valley-bus-events' "$initScriptPath" | head -n1)"
567 test -x "$dispatch"
568 test -x "$bushook"
569 repo="$TMPDIR/events-pilot.git"
570 git init --quiet --bare "$repo"
571 mkdir -p "$repo/hooks/post-receive.d"
572 ln -s "$dispatch" "$repo/hooks/post-receive"
573 ln -s "$bushook" "$repo/hooks/post-receive.d/valley-bus"
574
575 git clone --quiet "$repo" "$TMPDIR/work"
576 cd "$TMPDIR/work"
577 echo one > file
578 git add file
579 git commit --quiet -m one
580 git push --quiet origin main
581 first="$(git rev-parse HEAD)"
582 zeros="$(printf '%040d' 0)"
583
584 # Exit criterion 1: the event arrives within seconds, with a
585 # payload that is exactly the git facts of the push …
586 msgs_is() { [ "$(nats stream info valley --json | jq .state.messages)" -eq "$1" ]; }
587 wait_for msgs_is 1
588 got="$(nats stream get valley 1 --json)"
589 [ "$(jq -r .subject <<<"$got")" = valley.git.events-pilot.ref-updated ]
590 payload="$(jq -r .data <<<"$got" | base64 -d)"
591 expected='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$first"'"}'
592 [ "$payload" = "$expected" ]
593
594 # … valid against the shipped event schema.
595 echo "$payload" > "$TMPDIR/payload.json"
596 cue vet -d '#RefUpdated' ${./schema/events.cue} "$TMPDIR/payload.json"
597
598 # … and visible in `valley tail`. Subscribe first, then push.
599 valley tail > "$TMPDIR/tail.out" 2>&1 &
600 tail_pid=$!
601 subscribed() { grep -q 'valley.>' "$TMPDIR/tail.out"; }
602 wait_for subscribed
603 echo two > file
604 git commit --quiet -am two
605 git push --quiet origin main
606 second="$(git rev-parse HEAD)"
607 wait_for msgs_is 2
608 payload2="$(nats stream get valley 2 --json | jq -r .data | base64 -d)"
609 expected2='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$first"'","new":"'"$second"'"}'
610 [ "$payload2" = "$expected2" ]
611 tail_saw() { grep -qF "$expected2" "$TMPDIR/tail.out"; }
612 wait_for tail_saw
613 kill "$tail_pid" 2>/dev/null || true
614
615 # Exit criterion 2: rebuilding the stream from the repo's
616 # refs is deterministic — two replays from scratch produce
617 # identical events, landing on the pushed tip with the
618 # all-zero id as old.
619 dump_stream() {
620 local info first_seq last_seq i
621 info="$(nats stream info valley --json)"
622 first_seq="$(jq .state.first_seq <<<"$info")"
623 last_seq="$(jq .state.last_seq <<<"$info")"
624 for i in $(seq "$first_seq" "$last_seq"); do
625 nats stream get valley "$i" --json | jq -c '{subject: .subject, data: .data}'
626 done
627 }
628 nats stream purge valley --force >/dev/null
629 valley replay "$repo"
630 wait_for msgs_is 1
631 run1="$(dump_stream)"
632 nats stream purge valley --force >/dev/null
633 valley replay "$repo"
634 wait_for msgs_is 1
635 run2="$(dump_stream)"
636 [ "$run1" = "$run2" ]
637 replayed="$(jq -r .data <<<"$run1" | base64 -d)"
638 [ "$replayed" = '{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$second"'"}' ]
639
640 # A dead bus never blocks a push: the event is simply lost
641 # (and rebuildable by replay).
642 kill "$server_pid"
643 wait "$server_pid" || true
644 echo three > file
645 git commit --quiet -am three
646 git push --quiet origin main
647
648 touch $out
649 '';
650 }
651 );
652 };
653}