gunk-dev/the-valley

flake.nix

source8fc23bb2bc1bmain's published tip history
84.1 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 pkgs.cue # checks only — it composes the policy layers
25 ];
26 text = builtins.readFile ./bin/valley;
27 };
28
29 # The installed package: the wrapped script plus the shell completions,
30 # at the standard paths home-manager/NixOS auto-link.
31 valleyCliFor =
32 pkgs:
33 pkgs.symlinkJoin {
34 name = "valley";
35 paths = [ (valleyScriptFor pkgs) ];
36 nativeBuildInputs = [ pkgs.installShellFiles ];
37 postBuild = ''
38 installShellCompletion --bash --name valley ${./completions/valley.bash}
39 installShellCompletion --zsh --name _valley ${./completions/_valley}
40 '';
41 };
42
43 # Markdown prose is filled paragraphs hard-wrapped at 100 columns
44 # (ida-1ec03b1). One prettier invocation backs both the formatter app
45 # and the prose-format check, so the two cannot drift.
46 # Embedded-language formatting is off so fenced code blocks pass
47 # through byte-for-byte.
48 proseFmtArgs = "--prose-wrap always --print-width 100 --embedded-language-formatting off";
49
50 # `nix run .#fmt` — rewrap every tracked *.md in the repo to 100 columns.
51 proseFmtFor =
52 pkgs:
53 pkgs.writeShellApplication {
54 name = "valley-fmt";
55 runtimeInputs = [
56 pkgs.git
57 pkgs.prettier
58 ];
59 text = ''
60 cd "$(git rev-parse --show-toplevel)"
61 git ls-files -z -- '*.md' | xargs -0 --no-run-if-empty \
62 prettier ${proseFmtArgs} --write
63 '';
64 };
65
66 # The Phase 2 attestation helper (dcr-0de694f). Go, standard library
67 # only, note format included — hence vendorHash = null, and hence no
68 # module fetch at build time. Its unit tests run in the checkPhase and
69 # need git and ssh-keygen.
70 attestUnwrappedFor =
71 pkgs:
72 pkgs.buildGoModule {
73 pname = "valley-attest";
74 version = "0";
75 src = ./attest;
76 vendorHash = null;
77 nativeCheckInputs = [
78 pkgs.git
79 pkgs.openssh
80 ];
81 meta.mainProgram = "attest";
82 };
83
84 # The shipping form. git and cue are pinned to this flake's nixpkgs,
85 # so every host composes and vets a statement with the same tools.
86 # Signing needs no tool at all: a note is signed on crypto/ed25519
87 # inside the binary. `nix` is deliberately NOT pinned: the check being
88 # attested to must be built by the nix the machine actually runs, and
89 # a nix carried in here would be a second one.
90 attestFor =
91 pkgs:
92 pkgs.runCommand "valley-attest"
93 {
94 nativeBuildInputs = [ pkgs.makeWrapper ];
95 meta.mainProgram = "attest";
96 }
97 ''
98 mkdir -p $out/bin
99 makeWrapper ${lib.getExe (attestUnwrappedFor pkgs)} $out/bin/attest \
100 --prefix PATH : ${
101 lib.makeBinPath [
102 pkgs.git
103 pkgs.cue
104 ]
105 } \
106 --set-default VALLEY_ATTEST_SCHEMA ${./schema/attestation.cue}
107 '';
108 in
109 {
110 nixosModules.valley-host = ./nix/valley-host.nix;
111 nixosModules.default = self.nixosModules.valley-host;
112
113 # The knowledge lint, for any project that keeps a `.the-valley/` graph.
114 # This is the check's primary form: a consuming project takes this flake
115 # as an input and instantiates the derivation over its own source, so the
116 # check a policy names is supplied by the instance rather than written
117 # again by every project the policy covers (dcr-f41f718). A whole
118 # consuming flake is:
119 #
120 # {
121 # inputs.the-valley.url = "github:gunk-dev/the-valley";
122 # outputs =
123 # { self, the-valley }:
124 # {
125 # checks.x86_64-linux.knowledge-lint = the-valley.lib.knowledgeLint {
126 # system = "x86_64-linux";
127 # src = self;
128 # };
129 # };
130 # }
131 #
132 # There is no nixpkgs input in that flake on purpose: cue and python come
133 # from this flake's pinned nixpkgs, so every project in a group runs the
134 # same lint against the same toolchain. `root` names the graph directory
135 # for a project that keeps its graph somewhere other than `.the-valley/`.
136 lib.knowledgeLint =
137 {
138 system,
139 src,
140 root ? ".the-valley",
141 }:
142 import ./nix/knowledge-lint.nix {
143 inherit src root;
144 pkgs = nixpkgs.legacyPackages.${system};
145 };
146
147 apps = lib.genAttrs systems (system: {
148 fmt = {
149 type = "app";
150 program = lib.getExe (proseFmtFor nixpkgs.legacyPackages.${system});
151 };
152 attest = {
153 type = "app";
154 program = lib.getExe (attestFor nixpkgs.legacyPackages.${system});
155 };
156 });
157
158 packages = lib.genAttrs systems (
159 system:
160 let
161 valley = valleyCliFor nixpkgs.legacyPackages.${system};
162 in
163 {
164 inherit valley;
165 default = valley;
166 attest = attestFor nixpkgs.legacyPackages.${system};
167 }
168 );
169
170 checks = lib.genAttrs systems (
171 system:
172 let
173 pkgs = nixpkgs.legacyPackages.${system};
174
175 # Eval-only instantiation of the module — catches option-surface
176 # and cue-export regressions without building or booting anything.
177 # Each check host shares the machine baseline and supplies its own
178 # declaration (and, where the declaration asks for backup, the
179 # secret paths).
180 mkHost =
181 module:
182 lib.nixosSystem {
183 inherit system;
184 modules = [
185 self.nixosModules.default
186 {
187 fileSystems."/" = {
188 device = "/dev/disk/by-label/nixos";
189 fsType = "ext4";
190 };
191 boot.loader.grub.enable = false;
192 system.stateVersion = "25.11";
193 services.valley = {
194 enable = true;
195 authorizedKeys = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPlaceholderKeyForEvalOnlyCheck0 valley-check" ];
196 };
197 }
198 module
199 ];
200 };
201
202 # The example declaration enables backup, so this host supplies
203 # the four secret paths (eval-only placeholders).
204 host = mkHost {
205 services.valley = {
206 config = ./examples/host.cue;
207 backup = {
208 repositoryFile = "/run/agenix/valley-restic-repo";
209 passwordFile = "/run/agenix/valley-restic-password";
210 sshKeyFile = "/run/agenix/valley-git-ssh-key";
211 knownHostsFile = "/var/lib/valley-backup/known_hosts";
212 };
213 };
214 };
215
216 # A declaration without a backup block predates the field and must
217 # keep evaluating exactly as before: zero restic machinery.
218 noBackupHost = mkHost {
219 services.valley.config = pkgs.writeText "no-backup-host.cue" ''
220 package valley
221 projects: "the-valley": {}
222 '';
223 };
224
225 # The example declaration with the secret paths left unset: the
226 # module must refuse with assertions naming the missing options.
227 noSecretsHost = mkHost {
228 services.valley.config = ./examples/host.cue;
229 };
230
231 # Bus enabled, minimal declaration. The bus-e2e check drives this
232 # host's rendered hooks and stream-init against a real server.
233 busHost = mkHost {
234 services.valley = {
235 config = pkgs.writeText "bus-host.cue" ''
236 package valley
237 projects: "events-pilot": {}
238 '';
239 bus.enable = true;
240 };
241 };
242
243 # Two mirror URLs the sandbox can serve: git resolves a relative
244 # URL against the pushing repo's directory, so the mirror-e2e
245 # check drives the rendered script with no substitution at all —
246 # one reachable sibling repo, one that does not exist.
247 mirrorHost = mkHost {
248 services.valley.config = pkgs.writeText "mirror-host.cue" ''
249 package valley
250 projects: "mirror-pilot": mirrors: ["../mirror.git"]
251 projects: "dead-mirror": mirrors: ["../nope.git"]
252 '';
253 };
254
255 failedAssertions = builtins.filter (a: !a.assertion) (
256 host.config.assertions
257 ++ noBackupHost.config.assertions
258 ++ busHost.config.assertions
259 ++ mirrorHost.config.assertions
260 );
261
262 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
263
264 resticRenderedWithoutDeclaration =
265 noBackupHost.config.systemd.services ? "restic-backups-valley"
266 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
267
268 # The bus defaults off; a host that never asked for one must
269 # render zero bus machinery.
270 busRenderedWithoutEnable =
271 noBackupHost.config.systemd.services ? valley-bus
272 || noBackupHost.config.systemd.services ? valley-bus-init;
273
274 # A tree in the store, written from a path -> contents map. The
275 # knowledge lint reads a whole graph rather than a file, so every
276 # fixture below is small but complete.
277 mkTree =
278 name: files:
279 pkgs.runCommand name { } (
280 lib.concatStrings (
281 lib.mapAttrsToList (path: text: ''
282 install -Dm444 ${pkgs.writeText "knowledge-lint-fixture" text} $out/${path}
283 '') files
284 )
285 );
286
287 # A project that is nearly nothing: a README, a docs directory, and
288 # four nodes carrying one of each typed edge. This is the shape the
289 # first consuming project has, and the knowledge-lint-consumer check
290 # instantiates lib.knowledgeLint over it exactly as that project's
291 # own flake would.
292 consumerProject = mkTree "knowledge-lint-consumer-project" {
293 "README.md" = ''
294 # A project
295
296 It keeps its knowledge in [.the-valley](./.the-valley/).
297 '';
298 "docs/design.md" = ''
299 # Design
300
301 ## The shape
302 '';
303 ".the-valley/ideas/ida-0a1b2c3-the-shape.md" = ''
304 ---
305 type: idea
306 id: ida-0a1b2c3
307 status: raw
308 title: The shape the design should take
309 created: 2026-08-02
310 ---
311
312 # The shape the design should take
313
314 As sketched in [design.md](../../docs/design.md#the-shape).
315 '';
316 ".the-valley/outcomes/oc-4d5e6f7-the-design-lands.md" = ''
317 ---
318 type: outcome
319 id: oc-4d5e6f7
320 status: open
321 title: The design lands
322 created: 2026-08-02
323 blocked_by: [ida-0a1b2c3]
324 ---
325
326 # The design lands
327
328 Waits on [[ida-0a1b2c3]].
329 '';
330 ".the-valley/decisions/dcr-1122334-where-the-graph-lives.md" = ''
331 ---
332 type: decision
333 id: dcr-1122334
334 status: superseded
335 title: Where the graph lives
336 created: 2026-08-02
337 ---
338
339 # Where the graph lives
340
341 The graph is a directory of markdown files under the project root.
342 '';
343 ".the-valley/decisions/dcr-5566778-where-the-graph-lives.md" = ''
344 ---
345 type: decision
346 id: dcr-5566778
347 status: decided
348 title: Where the graph lives
349 created: 2026-08-02
350 supersedes: [dcr-1122334]
351 ---
352
353 # Where the graph lives
354
355 The graph is a directory of markdown files at `.the-valley/`, alongside the code.
356 '';
357 };
358
359 # A project with no graph at all. Adding the check must not require
360 # having written a node yet, or no project would ever adopt it
361 # before its first one.
362 graphlessProject = mkTree "knowledge-lint-graphless-project" {
363 "README.md" = ''
364 # A project with no knowledge graph yet
365 '';
366 };
367
368 # What the lint must reject, and the words its failure must contain.
369 # A lint that fails without naming the file and the defect costs the
370 # reader the whole diagnosis, so both are pinned.
371 rejectedGraphs = {
372 unknown-status = {
373 names = ''ida-0000001-a-node.md".status'';
374 files.".the-valley/ideas/ida-0000001-a-node.md" = ''
375 ---
376 type: idea
377 id: ida-0000001
378 status: nonsense
379 title: A node in a state ideas do not have
380 created: 2026-08-02
381 ---
382 '';
383 };
384
385 edge-on-the-wrong-type = {
386 names = "blocked_by: field not allowed";
387 files.".the-valley/ideas/ida-0000002-a-node.md" = ''
388 ---
389 type: idea
390 id: ida-0000002
391 status: raw
392 title: An idea carrying the one edge only outcomes carry
393 created: 2026-08-02
394 blocked_by: []
395 ---
396 '';
397 };
398
399 node-in-the-wrong-directory = {
400 names = "a bug node belongs in .the-valley/bugs/";
401 files.".the-valley/ideas/bd-0000003-a-bug.md" = ''
402 ---
403 type: bug
404 id: bd-0000003
405 status: open
406 title: A bug filed among the ideas
407 created: 2026-08-02
408 ---
409 '';
410 };
411
412 filename-id-mismatch = {
413 names = "filename says id ida-0000004, frontmatter says ida-0000005";
414 files.".the-valley/ideas/ida-0000004-a-node.md" = ''
415 ---
416 type: idea
417 id: ida-0000005
418 status: raw
419 title: A node whose filename and frontmatter disagree
420 created: 2026-08-02
421 ---
422 '';
423 };
424
425 duplicate-id = {
426 names = "is already used by";
427 files = {
428 ".the-valley/ideas/ida-0000006-one.md" = ''
429 ---
430 type: idea
431 id: ida-0000006
432 status: raw
433 title: One node
434 created: 2026-08-02
435 ---
436 '';
437 ".the-valley/ideas/ida-0000006-two.md" = ''
438 ---
439 type: idea
440 id: ida-0000006
441 status: raw
442 title: Another node wearing the same id
443 created: 2026-08-02
444 ---
445 '';
446 };
447 };
448
449 missing-frontmatter = {
450 names = "no YAML frontmatter";
451 files.".the-valley/ideas/ida-0000007-a-node.md" = ''
452 # A node that is only prose
453 '';
454 };
455
456 dangling-wiki-link = {
457 names = "[[ida-9999999]] is not a node id";
458 files.".the-valley/ideas/ida-0000008-a-node.md" = ''
459 ---
460 type: idea
461 id: ida-0000008
462 status: raw
463 title: A node pointing at nothing
464 created: 2026-08-02
465 ---
466
467 It builds on [[ida-9999999]].
468 '';
469 };
470
471 dangling-blocked-by = {
472 names = "blocked_by names oc-9999999, which is not a node";
473 files.".the-valley/outcomes/oc-0000009-an-outcome.md" = ''
474 ---
475 type: outcome
476 id: oc-0000009
477 status: open
478 title: An outcome waiting on nothing that exists
479 created: 2026-08-02
480 blocked_by: [oc-9999999]
481 ---
482 '';
483 };
484
485 dangling-supersedes = {
486 names = "supersedes names dcr-9999999, which is not a node";
487 files.".the-valley/decisions/dcr-000000c-a-decision.md" = ''
488 ---
489 type: decision
490 id: dcr-000000c
491 status: decided
492 title: A decision replacing nothing that exists
493 created: 2026-08-02
494 supersedes: [dcr-9999999]
495 ---
496 '';
497 };
498
499 # The edge alone is half a supersession. A node declared replaced
500 # while its own status still reads otherwise leaves the graph
501 # saying two things, which is the defect the edge exists to end.
502 supersedes-a-node-still-standing = {
503 names = "whose status is adopted, not superseded";
504 files = {
505 ".the-valley/ideas/ida-000000d-the-replacement.md" = ''
506 ---
507 type: idea
508 id: ida-000000d
509 status: adopted
510 title: An idea replacing one that has not been told
511 created: 2026-08-02
512 supersedes: [ida-000000e]
513 ---
514 '';
515 ".the-valley/ideas/ida-000000e-the-replaced.md" = ''
516 ---
517 type: idea
518 id: ida-000000e
519 status: adopted
520 title: An idea replaced in fact but not in its status
521 created: 2026-08-02
522 ---
523 '';
524 };
525 };
526
527 supersedes-on-the-wrong-type = {
528 names = "supersedes: field not allowed";
529 files.".the-valley/outcomes/oc-000000f-an-outcome.md" = ''
530 ---
531 type: outcome
532 id: oc-000000f
533 status: open
534 title: An outcome carrying the edge only ideas and decisions carry
535 created: 2026-08-02
536 blocked_by: []
537 supersedes: []
538 ---
539 '';
540 };
541
542 # Only ideas and decisions have a `superseded` status, so an edge
543 # naming any other type is rejected on shape by the schema.
544 supersedes-a-type-that-cannot-be = {
545 names = ''supersedes.0: invalid value "bd-0000011"'';
546 files.".the-valley/ideas/ida-0000010-a-node.md" = ''
547 ---
548 type: idea
549 id: ida-0000010
550 status: adopted
551 title: An idea claiming to replace a bug
552 created: 2026-08-02
553 supersedes: [bd-0000011]
554 ---
555 '';
556 };
557
558 broken-link = {
559 names = "./nowhere.md does not exist";
560 files.".the-valley/ideas/ida-000000a-a-node.md" = ''
561 ---
562 type: idea
563 id: ida-000000a
564 status: raw
565 title: A node linking to a file that is not there
566 created: 2026-08-02
567 ---
568
569 See [nowhere](./nowhere.md).
570 '';
571 };
572
573 broken-anchor = {
574 names = "names no heading";
575 files.".the-valley/ideas/ida-000000b-a-node.md" = ''
576 ---
577 type: idea
578 id: ida-000000b
579 status: raw
580 title: A node linking to a heading that is not there
581 created: 2026-08-02
582 ---
583
584 # A heading
585
586 See [above](./ida-000000b-a-node.md#not-this-heading).
587 '';
588 };
589 };
590 in
591 {
592 # The CLI must stay a lint-clean script whose help verb answers
593 # without a repo or a remote — the cheap end of its eviction clause
594 # (dcr-74c3158); anything needing more graduates instead. The
595 # completions are held to the same bar, and the installed package
596 # must carry them at the auto-linked paths.
597 valley-cli =
598 let
599 valley = valleyCliFor pkgs;
600 in
601 pkgs.runCommand "valley-cli"
602 {
603 nativeBuildInputs = [
604 pkgs.shellcheck
605 pkgs.zsh
606 valley
607 ];
608 }
609 ''
610 shellcheck ${./bin/valley}
611 shellcheck ${./completions/valley.bash}
612 # shellcheck cannot lint zsh; a bare parse is the cheap check.
613 zsh -n ${./completions/_valley}
614 valley help > help.txt
615 grep -q '^usage: valley' help.txt
616 test -f ${valley}/share/bash-completion/completions/valley
617 test -f ${valley}/share/zsh/site-functions/_valley
618 touch $out
619 '';
620
621 # Markdown prose format (ida-1ec03b1): the check is formatter
622 # idempotence — formatting the tree must change nothing. On failure,
623 # fix with `nix run .#fmt`.
624 prose-format =
625 pkgs.runCommand "valley-prose-format"
626 {
627 nativeBuildInputs = [ pkgs.prettier ];
628 }
629 ''
630 cd ${self}
631 find . -name '*.md' -print0 | xargs -0 --no-run-if-empty \
632 prettier ${proseFmtArgs} --check
633 touch $out
634 '';
635
636 # This repo's own graph, checked by the derivation the flake
637 # exposes rather than by a second implementation of it. Whatever a
638 # consuming project runs, this repo runs.
639 knowledge-lint = self.lib.knowledgeLint {
640 inherit system;
641 src = self;
642 };
643
644 # The reusable form, exercised over a foreign tree: a project that
645 # is a README, a docs directory and two nodes, and a project with no
646 # graph at all. Both must pass, and both are checked by depending on
647 # the instantiated derivations rather than by re-running the lint.
648 knowledge-lint-consumer =
649 pkgs.runCommand "valley-knowledge-lint-consumer"
650 {
651 consumer = self.lib.knowledgeLint {
652 inherit system;
653 src = consumerProject;
654 };
655 graphless = self.lib.knowledgeLint {
656 inherit system;
657 src = graphlessProject;
658 };
659 }
660 ''
661 test -e "$consumer" && test -e "$graphless"
662 touch $out
663 '';
664
665 # The lint must fail on a broken graph, and its failure must name
666 # the file and the defect — a check that only says "no" leaves the
667 # reader to find the breakage themselves. The script and the schema
668 # here are the same store paths lib.knowledgeLint uses, so the
669 # rejections cannot drift from what a consumer runs.
670 knowledge-lint-rejects =
671 pkgs.runCommand "valley-knowledge-lint-rejects"
672 {
673 nativeBuildInputs = [
674 pkgs.cue
675 pkgs.python3
676 ];
677 }
678 ''
679 ${lib.concatStrings (
680 lib.mapAttrsToList (case: spec: ''
681 mkdir -p work/${case}
682 if python3 ${./nix/knowledge-lint.py} \
683 --tree ${mkTree "knowledge-lint-${case}" spec.files} \
684 --schema ${./schema/node.cue} \
685 --work work/${case} 2> ${case}.err
686 then
687 echo "knowledge-lint: expected graph '${case}' to be rejected" >&2
688 exit 1
689 fi
690 if ! grep -qF -- ${lib.escapeShellArg spec.names} ${case}.err; then
691 echo "knowledge-lint: '${case}' was rejected without naming" \
692 ${lib.escapeShellArg spec.names} >&2
693 cat ${case}.err >&2
694 exit 1
695 fi
696 '') rejectedGraphs
697 )}
698 touch $out
699 '';
700
701 # The example host declaration must vet against the schema, and the
702 # schema must reject what it claims to reject: unsafe project names,
703 # unknown project fields, stray top-level fields (typos, deployment
704 # concerns), and malformed backup policy (machine concerns, targets
705 # without an implementation, non-positive retention). CUE closedness
706 # is easy to regress silently — e.g. embedding #Host instead of
707 # referencing it opens the schema — so the rejections are pinned
708 # here.
709 cue-vet =
710 let
711 invalidConfigs = {
712 unsafe-project-name = ''
713 package valley
714 projects: ".hidden": {}
715 '';
716 unknown-project-field = ''
717 package valley
718 projects: ok: dataDir: "/srv/git"
719 '';
720 top-level-typo = ''
721 package valley
722 project: oops: {}
723 '';
724 deployment-concern-in-cue = ''
725 package valley
726 user: "git"
727 projects: ok: {}
728 '';
729 machine-concern-in-backup = ''
730 package valley
731 projects: ok: {}
732 backup: repositoryFile: "/run/agenix/valley-restic-repo"
733 '';
734 unimplemented-backup-target = ''
735 package valley
736 projects: ok: {}
737 backup: target: "restic-s3"
738 '';
739 negative-retention = ''
740 package valley
741 projects: ok: {}
742 backup: retention: daily: -1
743 '';
744 };
745 in
746 pkgs.runCommand "valley-cue-vet"
747 {
748 nativeBuildInputs = [ pkgs.cue ];
749 }
750 ''
751 cue vet -c ${./schema/valley.cue} ${./examples/host.cue}
752 cue export ${./schema/valley.cue} ${./examples/host.cue} > example.json
753 grep -q 'gunk-dev/the-valley' example.json
754 grep -q 'restic-sftp' example.json
755
756 # A declaration without a backup block must stay valid —
757 # consumers written before the field existed keep vetting.
758 cue vet -c ${./schema/valley.cue} ${pkgs.writeText "no-backup.cue" ''
759 package valley
760 projects: "the-valley": {}
761 ''}
762
763 # The event schema accepts what the publisher hook emits …
764 cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated.json" ''
765 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"}
766 ''}
767 # … and stays closed: a field outside the git-derivable
768 # identity — wall-clock time, a hostname — must be rejected,
769 # or replay determinism silently dies.
770 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-timestamped.json" ''
771 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3","time":"2026-07-16T00:00:00Z"}
772 ''}; then
773 echo "cue-vet: expected the timestamped ref-updated payload to be rejected" >&2
774 exit 1
775 fi
776 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-short-sha.json" ''
777 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe"}
778 ''}; then
779 echo "cue-vet: expected the abbreviated object id to be rejected" >&2
780 exit 1
781 fi
782
783 ${lib.concatStrings (
784 lib.mapAttrsToList (name: cfg: ''
785 if cue vet -c ${./schema/valley.cue} ${pkgs.writeText "${name}.cue" cfg}; then
786 echo "cue-vet: expected invalid config '${name}' to be rejected" >&2
787 exit 1
788 fi
789 '') invalidConfigs
790 )}
791 touch $out
792 '';
793
794 # The attestation statement schema (dcr-0de694f). A statement the
795 # helper composes must vet, and the schema must reject what it
796 # claims to reject. Two rejections carry the decision's whole
797 # weight and are pinned by name below: a subject with no
798 # content-addressed digest has no identity at all, and a
799 # predicate that crosses the pure/effectful line would let a
800 # notarization pass itself off as re-derivable.
801 attest-schema =
802 let
803 treeDigest = "73847e0b723a444df8c677e5e67d2e7858327259323c76b24f8f11b650b66d69";
804 subject = ''
805 "subject": {
806 "primary": "valley-tree-v1",
807 "digest": {
808 "valley-tree-v1": "${treeDigest}",
809 "git-sha1": "99b5f2f7971e2c8e37a7a579cb761d80272a9a3d"
810 }
811 }
812 '';
813 pureStatement = ''
814 {
815 "statementType": "the-valley/attestation/v1",
816 ${subject},
817 "predicateType": "the-valley/check/pure/v1",
818 "predicate": {
819 "check": {"name": "prose-format", "runner": "nix", "attribute": "prose-format"},
820 "result": "passed",
821 "inputs": {"valley-inputs-v1": "8df8c199decb43eb715790d6fc3a9dd96adaaf3a75073a50acfa51d73aaf3253"},
822 "derivation": {"sha256": "ef69ed0ccc0546a38a40eebbfcac610cedd7cf4f81036cd21ddff483f08d3ad7"},
823 "output": {"valley-tree-v1": "cf1f5a9c96bbdf1d69da451c94168fa3a760f91f94827ba88bdb72de8dfa8af9"}
824 },
825 "provenance": {
826 "harness": "a harness",
827 "model": "a model",
828 "prompt": {"sha256": "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03"},
829 "delegation": [{"principal": "human:integrator", "grant": "land changes"}]
830 }
831 }
832 '';
833 effectfulStatement = ''
834 {
835 "statementType": "the-valley/attestation/v1",
836 ${subject},
837 "predicateType": "the-valley/check/effectful/v1",
838 "predicate": {
839 "check": {"name": "live-api", "runner": "command", "command": "curl -sf https://example.invalid"},
840 "result": "passed",
841 "environment": "a sealed environment",
842 "observedAt": "2026-08-02T13:02:00Z"
843 }
844 }
845 '';
846 # Each case is the pure statement with one thing wrong.
847 invalidStatements = {
848 # Carriage is not statement: a signature inside the signed
849 # bytes is a category error, and the sentinel names it.
850 signature-in-statement = builtins.replaceStrings [ "\"statementType\"" ] [
851 "\"signature\": \"-----BEGIN SSH SIGNATURE-----\", \"statementType\""
852 ] pureStatement;
853 # A subject with only advisory members.
854 no-content-addressed-subject =
855 builtins.replaceStrings [ "\"valley-tree-v1\": \"${treeDigest}\"," ] [ "" ]
856 pureStatement;
857 # A notarization wearing a re-derivable predicate type.
858 effectful-claiming-pure = builtins.replaceStrings [ "the-valley/check/effectful/v1" ] [
859 "the-valley/check/pure/v1"
860 ] effectfulStatement;
861 # A re-derivable claim that drops what it is re-derived
862 # against.
863 pure-without-output = builtins.replaceStrings [ "\"output\"" ] [ "\"outputs\"" ] pureStatement;
864 # A predicate type nobody has published a shape for.
865 unversioned-predicate-type =
866 builtins.replaceStrings [ "the-valley/check/pure/v1" ] [ "the-valley/check/pure" ]
867 pureStatement;
868 # A digest under a scheme no verifier can check.
869 unknown-digest-scheme = builtins.replaceStrings [ "\"git-sha1\"" ] [ "\"md5\"" ] pureStatement;
870 # An abbreviated digest.
871 short-digest = builtins.replaceStrings [ treeDigest ] [ "73847e0b" ] pureStatement;
872 # A check name outside the shape schema/verification.cue
873 # holds check names to.
874 unsafe-check-name = builtins.replaceStrings [ "\"prose-format\", \"runner\"" ] [
875 "\"Prose Format\", \"runner\""
876 ] pureStatement;
877 # A nix check carrying a command line.
878 nix-check-with-a-command = builtins.replaceStrings [ "\"runner\": \"nix\"" ] [
879 "\"runner\": \"nix\", \"command\": \"make\""
880 ] pureStatement;
881 # A value with no written form. The statement is written
882 # out as lines and the form has no escapes, so a command
883 # spanning two of them is stopped at the gate rather than
884 # in a renderer after the check has already run.
885 command-over-two-lines = builtins.replaceStrings [ "curl -sf https://example.invalid" ] [
886 "curl -sf https://example.invalid \\\\\\n --retry 3"
887 ] effectfulStatement;
888 # And the other value a line cannot carry.
889 empty-environment = builtins.replaceStrings [ "\"a sealed environment\"" ] [
890 "\"\""
891 ] effectfulStatement;
892 };
893 in
894 pkgs.runCommand "valley-attest-schema"
895 {
896 nativeBuildInputs = [ pkgs.cue ];
897 }
898 ''
899 cue vet -c ${./schema/attestation.cue} ${pkgs.writeText "pure.json" pureStatement}
900 cue vet -c ${./schema/attestation.cue} ${pkgs.writeText "effectful.json" effectfulStatement}
901
902 ${lib.concatStrings (
903 lib.mapAttrsToList (name: text: ''
904 if cue vet -c ${./schema/attestation.cue} ${pkgs.writeText "${name}.json" text} \
905 > ${name}.err 2>&1; then
906 echo "attest-schema: expected invalid statement '${name}' to be rejected" >&2
907 exit 1
908 fi
909 '') invalidStatements
910 )}
911
912 # A map whose keys come from a caller is written as
913 # #SegmentKeyed. A field's name is written into the key that
914 # names its line, so a name holding the dot that separates
915 # segments, the space that separates key from value, or
916 # anything a line cannot carry is a statement with no written
917 # form. It fails vet rather than reaching a signer.
918 cue vet -d '#SegmentKeyed' ${./schema/attestation.cue} ${
919 pkgs.writeText "segment-keys.json" ''
920 {"harness": "a harness", "run-id": "1", "z9": "the last shape a segment takes"}
921 ''
922 }
923 ${lib.concatStrings (
924 lib.mapAttrsToList (name: key: ''
925 if cue vet -d '#SegmentKeyed' ${./schema/attestation.cue} ${
926 pkgs.writeText "${name}.json" ''
927 {"harness": "a harness", ${builtins.toJSON key}: "a key with no written form"}
928 ''
929 } > ${name}.err 2>&1; then
930 echo "attest-schema: expected the key '${key}' to be rejected" >&2
931 exit 1
932 fi
933 grep -q 'field not allowed' ${name}.err
934 '') {
935 non-ascii-key = "café";
936 dotted-key = "a.b";
937 spaced-key = "a b";
938 index-shaped-key = "0";
939 }
940 )}
941
942 # A rejection that does not name the field leaves the reader
943 # to find the breakage themselves.
944 grep -q 'signature: conflicting values' signature-in-statement.err
945 grep -q 'subject.digest."valley-tree-v1"' no-content-addressed-subject.err
946 grep -q 'predicate.environment: field not allowed' effectful-claiming-pure.err
947 grep -q 'predicate.check.command' command-over-two-lines.err
948 touch $out
949 '';
950
951 # The written form and the note envelope, held to fixed vectors.
952 # These bytes are an interop contract rather than an
953 # implementation detail: a regenerated or independently written
954 # attest must produce them identically or every signature already
955 # made stops verifying. So the vectors are checked-in files with a
956 # README saying they are the contract (attest/conformance/), and
957 # this check is what holds a second implementation to them.
958 attest-conformance =
959 pkgs.runCommand "valley-attest-conformance"
960 {
961 nativeBuildInputs = [
962 pkgs.cue
963 (attestFor pkgs)
964 ];
965 }
966 ''
967 vectors=${./attest/conformance}
968
969 # One vector written out and compared, quietly, so the
970 # perturbed run at the end can expect it to fail without
971 # saying so.
972 writes() { attest render "$1/input.json" | cmp -s - "$1/statement.txt"; }
973
974 found=0
975 signed=0
976 for dir in "$vectors"/vectors/*/; do
977 name="$(basename "$dir")"
978 found=$((found + 1))
979
980 if ! writes "$dir"; then
981 echo "attest-conformance: $name is not written as its recorded bytes" >&2
982 diff -u "$dir/statement.txt" <(attest render "$dir/input.json") >&2 || true
983 exit 1
984 fi
985
986 # The written form is a fixed point, or a statement written
987 # out again anywhere downstream stops matching what was
988 # signed.
989 if ! attest render "$dir/statement.txt" | cmp -s - "$dir/statement.txt"; then
990 echo "attest-conformance: $name is not a fixed point of the written form" >&2
991 exit 1
992 fi
993
994 # Every vector is a whole statement — order is defined per
995 # predicate type, so a fragment has no written form — and is
996 # held to the schema too, so the set cannot drift into
997 # documents no verifier would accept.
998 cue vet -c ${./schema/attestation.cue} "$dir/input.json"
999
1000 # The signed vector pins the whole path from a statement to
1001 # a note something else can check, not just the written
1002 # form. No --repo: the subject tree is not what this check
1003 # is about.
1004 if [ -e "$dir/statement.note" ]; then
1005 signed=$((signed + 1))
1006 attest verify --note "$dir/statement.note" \
1007 --known-keys "$vectors/known_keys" > "$name.verify"
1008 grep -q '^signature ok' "$name.verify"
1009 grep -q '^text ok' "$name.verify"
1010
1011 # The text a verifier reads back is the text on disk: a
1012 # note is its statement, and reading one gives the other.
1013 sed '/^$/q' "$dir/statement.note" | sed '$d' | cmp - "$dir/statement.txt"
1014 fi
1015 done
1016
1017 # Two signers over one statement is the property the note
1018 # format is here for, so the set must actually hold one.
1019 siblings="$(grep -c '^— ' "$vectors"/vectors/04-two-signers/statement.note)"
1020 if [ "$siblings" -ne 2 ]; then
1021 echo "attest-conformance: the two-signer vector carries $siblings signatures" >&2
1022 exit 1
1023 fi
1024 attest verify --note "$vectors"/vectors/04-two-signers/statement.note \
1025 --known-keys "$vectors/known_keys" \
1026 --signer conformance.the-valley.invalid/attestations \
1027 --signer witness.the-valley.invalid/attestations > siblings.verify
1028 if [ "$(grep -c '^signature ok' siblings.verify)" -ne 2 ]; then
1029 echo "attest-conformance: both sibling signatures must verify" >&2
1030 cat siblings.verify >&2
1031 exit 1
1032 fi
1033
1034 if [ "$found" -lt 4 ] || [ "$signed" -lt 2 ]; then
1035 echo "attest-conformance: $found vectors, $signed signed — the set has been emptied" >&2
1036 exit 1
1037 fi
1038
1039 # The other half of the contract: what must not be written or
1040 # read at all. A document with no written form, and text that
1041 # is not the written form of anything.
1042 refused=0
1043 for file in "$vectors"/refused/*; do
1044 refused=$((refused + 1))
1045 if attest render "$file" > /dev/null 2> "$(basename "$file").err"; then
1046 echo "attest-conformance: $(basename "$file") was accepted" >&2
1047 exit 1
1048 fi
1049 done
1050 if [ "$refused" -lt 30 ]; then
1051 echo "attest-conformance: only $refused refusals — the set has been emptied" >&2
1052 exit 1
1053 fi
1054
1055 # The comparison must be able to fail. One recorded byte
1056 # sequence with a single value changed is what a divergent
1057 # implementation looks like, and it must not pass.
1058 mkdir -p perturbed
1059 cp "$vectors/vectors/01-statement-minimal/input.json" perturbed/
1060 sed 's/^predicate.result passed$/predicate.result failed/' \
1061 "$vectors/vectors/01-statement-minimal/statement.txt" > perturbed/statement.txt
1062 cmp -s perturbed/statement.txt "$vectors/vectors/01-statement-minimal/statement.txt" \
1063 && { echo "attest-conformance: the perturbation changed nothing" >&2; exit 1; }
1064 if writes perturbed; then
1065 echo "attest-conformance: a perturbed vector passed; the comparison proves nothing" >&2
1066 exit 1
1067 fi
1068
1069 # And so must the signature check. One byte of the signed
1070 # text changed is a signature that no longer covers it.
1071 sed 's/a sealed environment/a sealed environmenT/' \
1072 "$vectors"/vectors/04-two-signers/statement.note > perturbed/statement.note
1073 if attest verify --note perturbed/statement.note \
1074 --known-keys "$vectors/known_keys" > perturbed.verify 2>&1; then
1075 echo "attest-conformance: a note whose text was edited still verified" >&2
1076 exit 1
1077 fi
1078 grep -q 'does not check out over this text' perturbed.verify
1079
1080 echo "attest-conformance: $found vectors written byte for byte, $signed signed, $refused refused"
1081 touch $out
1082 '';
1083
1084 # The helper itself, driven end to end over scratch repositories
1085 # and a throwaway key: what it publishes, what it refuses to
1086 # publish, and what a verifier makes of both.
1087 #
1088 # Every check here uses the command runner. The nix runner cannot
1089 # be exercised from inside a nix build — there is no daemon in the
1090 # sandbox — so what a pure statement looks like is pinned by
1091 # attest-schema above and by the unit tests over the digest
1092 # scheme, and the runner itself is exercised by running the helper
1093 # outside the sandbox.
1094 attest-e2e =
1095 pkgs.runCommand "valley-attest-e2e"
1096 {
1097 nativeBuildInputs = [
1098 pkgs.git
1099 pkgs.openssh
1100 (attestFor pkgs)
1101 ];
1102 }
1103 ''
1104 export HOME="$TMPDIR"
1105 export GIT_CONFIG_NOSYSTEM=1
1106 git config --global user.name valley-check
1107 git config --global user.email valley-check@localhost
1108 git config --global init.defaultBranch main
1109
1110 # Throwaway keys in a scratch directory. The signer is a
1111 # parameter: provisioning a host identity is deployment, and
1112 # nothing here reads or writes anything under a real ~/.ssh.
1113 # A verifier is given key names and hashes, so what it holds
1114 # is what `attest key` prints and nothing more.
1115 ssh-keygen -q -t ed25519 -N "" -C valley-check -f "$TMPDIR/host"
1116 ssh-keygen -q -t ed25519 -N "" -C witness -f "$TMPDIR/witness"
1117 ssh-keygen -q -t ed25519 -N "" -C stranger -f "$TMPDIR/stranger"
1118 host=host.valley.invalid/attestations
1119 witness=witness.valley.invalid/attestations
1120 stranger=stranger.elsewhere.invalid/attestations
1121 attest key --key "$TMPDIR/host" --name "$host" > "$TMPDIR/known_keys"
1122 attest key --key "$TMPDIR/witness" --name "$witness" >> "$TMPDIR/known_keys"
1123 attest key --key "$TMPDIR/stranger" --name "$stranger" > "$TMPDIR/other_keys"
1124 grep -q "^$host+[0-9a-f]\{8\}+A" "$TMPDIR/known_keys"
1125
1126 # A key behind a passphrase is refused rather than prompted
1127 # for: attest runs unattended.
1128 ssh-keygen -q -t ed25519 -N "a passphrase" -C locked -f "$TMPDIR/locked"
1129 if attest key --key "$TMPDIR/locked" --name "$host" 2> locked.err; then
1130 echo "attest-e2e: an encrypted key must be refused" >&2
1131 exit 1
1132 fi
1133 grep -q 'cannot ask for a passphrase' locked.err
1134
1135 repo="$TMPDIR/tree"
1136 git init --quiet "$repo"
1137 cd "$repo"
1138 echo hello > hello.txt
1139 mkdir -p sub
1140 echo nested > sub/nested.txt
1141 ln -s hello.txt link
1142 printf '#!/bin/sh\ntrue\n' > run.sh
1143 chmod 755 run.sh
1144 git add -A
1145 git commit --quiet -m base
1146
1147 digest="$(attest digest | sed 's/^valley-tree-v1://')"
1148 case "$digest" in
1149 [0-9a-f][0-9a-f]*) ;;
1150 *) echo "attest-e2e: no tree digest: $digest" >&2; exit 1 ;;
1151 esac
1152
1153 refs() { git for-each-ref --format='%(refname)' refs/the-valley; }
1154 nothing_published() {
1155 if [ -n "$(refs)" ]; then
1156 echo "attest-e2e: $1" >&2
1157 git for-each-ref refs/the-valley >&2
1158 exit 1
1159 fi
1160 }
1161
1162 # Without a key, nothing is emitted — an unsigned statement
1163 # is not an attestation.
1164 if attest run --command 'ok=true' 2> nokey.err; then
1165 echo "attest-e2e: a run with no signing key must fail" >&2
1166 exit 1
1167 fi
1168 grep -q 'no signing key' nokey.err
1169 nothing_published "a run with no signing key stored a ref"
1170
1171 # A failing check publishes nothing, and says which check.
1172 if attest run --key "$TMPDIR/host" --name "$host" \
1173 --command 'ok=true' --command 'nope=false' > failing.out 2> failing.err; then
1174 echo "attest-e2e: a failing check must fail the run" >&2
1175 exit 1
1176 fi
1177 grep -qE '^check nope +command failed$' failing.out
1178 grep -q 'nothing published' failing.err
1179 nothing_published "a failing check left a ref behind"
1180
1181 # A statement the schema rejects is stopped before it is
1182 # signed or stored. Provenance is the caller's, so a
1183 # malformed one is how a malformed statement gets composed
1184 # at all.
1185 echo '{"harness":"valley-check","authority":"root"}' > bad-provenance.json
1186 if attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1187 --provenance bad-provenance.json > malformed.out 2> malformed.err; then
1188 echo "attest-e2e: a malformed statement must fail the run" >&2
1189 exit 1
1190 fi
1191 grep -q 'provenance.authority: field not allowed' malformed.err
1192 grep -q 'nothing published' malformed.err
1193 nothing_published "a malformed statement left a ref behind"
1194
1195 # A statement the schema admits but no line can carry is
1196 # stopped too, at the same point and for the same reason.
1197 printf '{"harness":"valley\\ncheck"}\n' > unwritable-provenance.json
1198 if attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1199 --provenance unwritable-provenance.json > unwritable.out 2> unwritable.err; then
1200 echo "attest-e2e: a statement with no written form must fail the run" >&2
1201 exit 1
1202 fi
1203 grep -q 'nothing published' unwritable.err
1204 nothing_published "a statement with no written form left a ref behind"
1205
1206 # The successful run.
1207 echo '{"harness":"valley-check","model":"none","delegation":[{"principal":"human:integrator","grant":"land changes"}]}' > provenance.json
1208 attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1209 --provenance provenance.json > run.out
1210 grep -q "^subject valley-tree-v1:$digest\$" run.out
1211 grep -q '^check ok *command passed$' run.out
1212 grep -q "^signer $host+" run.out
1213
1214 # Stored at a ref keyed by the subject digest, as one note
1215 # rather than a statement and a signature beside it.
1216 ref="$(refs)"
1217 case "$ref" in
1218 refs/the-valley/attestations/"$digest"/*) ;;
1219 *) echo "attest-e2e: ref $ref is not keyed by the subject digest" >&2; exit 1 ;;
1220 esac
1221 git cat-file -p "$ref:ok/statement.note" > statement.note
1222 head -n 1 statement.note | grep -qx 'the-valley/attestation/v1'
1223 grep -qx "subject.digest.valley-tree-v1 $digest" statement.note
1224 grep -qx 'provenance.harness valley-check' statement.note
1225 grep -q "^— $host " statement.note
1226
1227 # No git object is signed: the signature is over the
1228 # statement's text and nothing else.
1229 if git cat-file commit HEAD | grep -q '^gpgsig'; then
1230 echo "attest-e2e: attest signed a git object" >&2
1231 exit 1
1232 fi
1233
1234 verify() {
1235 attest verify --note "$1" --known-keys "$2" --repo "$repo"
1236 }
1237
1238 verify statement.note "$TMPDIR/known_keys" > verify.out
1239 grep -q "^signature ok $host+" verify.out
1240 grep -q 'matches the recorded subject digest' verify.out
1241
1242 # One atomic native-git push carries the branch and the
1243 # attestation ref together.
1244 git init --quiet --bare "$TMPDIR/host.git"
1245 git remote add valley "$TMPDIR/host.git"
1246 attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1247 --push valley > push.out
1248 grep -q -- '--atomic' push.out
1249 git -C "$TMPDIR/host.git" for-each-ref --format='%(refname)' > published.txt
1250 grep -qx 'refs/heads/main' published.txt
1251 grep -qx "$ref" published.txt
1252
1253 # A second party attests to the same statement, and its
1254 # signature lands beside the first under the text both cover.
1255 # This is what the note format is here for.
1256 attest sign --key "$TMPDIR/witness" --name "$witness" statement.note \
1257 > countersigned.note
1258 if [ "$(grep -c '^— ' countersigned.note)" -ne 2 ]; then
1259 echo "attest-e2e: countersigning did not add a sibling signature line" >&2
1260 cat countersigned.note >&2
1261 exit 1
1262 fi
1263 sed '/^$/q' countersigned.note | sed '$d' | cmp - <(sed '/^$/q' statement.note | sed '$d')
1264 attest verify --note countersigned.note --known-keys "$TMPDIR/known_keys" \
1265 --repo "$repo" --signer "$host" --signer "$witness" > countersigned.out
1266 if [ "$(grep -c '^signature ok' countersigned.out)" -ne 2 ]; then
1267 echo "attest-e2e: both signatures over one statement must verify" >&2
1268 cat countersigned.out >&2
1269 exit 1
1270 fi
1271
1272 # A verifier that does not hold the witness's key still
1273 # accepts the note, and says which signature it cannot speak
1274 # to. Requiring that signer is how it refuses instead.
1275 attest key --key "$TMPDIR/host" --name "$host" > "$TMPDIR/host_only"
1276 attest verify --note countersigned.note --known-keys "$TMPDIR/host_only" \
1277 --repo "$repo" > partial.out
1278 grep -q "^signature ok $host+" partial.out
1279 grep -q "^signature unknown $witness+" partial.out
1280 if attest verify --note countersigned.note --known-keys "$TMPDIR/host_only" \
1281 --repo "$repo" --signer "$witness" > required.out 2>&1; then
1282 echo "attest-e2e: a required signer with no verified signature must fail" >&2
1283 exit 1
1284 fi
1285 grep -q "no signature on this note is by $witness" required.out
1286
1287 # A note signed by a key the verifier does not hold is not a
1288 # bad signature — it is not a signer.
1289 if verify statement.note "$TMPDIR/other_keys" > stranger.out 2>&1; then
1290 echo "attest-e2e: a note signed by nobody we hold a key for must not verify" >&2
1291 exit 1
1292 fi
1293 grep -q 'no signature on this note is by a key the verifier holds' stranger.out
1294
1295 # Tampering with the signed bytes: one byte of the text the
1296 # signature covers.
1297 sed "s/$digest/00000000000000000000000000000000000000000000000000000000000000ff/" \
1298 statement.note > tampered.note
1299 if verify tampered.note "$TMPDIR/known_keys" > tampered.out 2>&1; then
1300 echo "attest-e2e: a tampered statement must not verify" >&2
1301 exit 1
1302 fi
1303 grep -q 'does not check out over this text' tampered.out
1304
1305 # A signature cannot be lifted onto a statement it was not
1306 # made about: it sits under the text it covers, so moving it
1307 # means moving that text with it.
1308 sed '/^$/q' statement.note | sed '$d' > lifted.txt
1309 sed 's/^provenance.harness .*/provenance.harness somebody-else/' lifted.txt > lifted.body
1310 sed -n '/^$/,$p' statement.note | tail -n +2 > lifted.sigs
1311 { cat lifted.body; echo; cat lifted.sigs; } > lifted.note
1312 if verify lifted.note "$TMPDIR/known_keys" > lifted.out 2>&1; then
1313 echo "attest-e2e: a signature was lifted onto another statement" >&2
1314 exit 1
1315 fi
1316 grep -q 'does not check out over this text' lifted.out
1317
1318 # A statement written some other way than the one written
1319 # form, signed properly over those bytes. The signature is
1320 # good and the statement is still refused: it would verify
1321 # here and fail wherever it was written out again, so the
1322 # form is a rule rather than a convention.
1323 { head -n 1 lifted.txt; tail -n +2 lifted.txt | sort -r; } > loose.txt
1324 cmp -s loose.txt lifted.txt \
1325 && { echo "attest-e2e: the reordering changed nothing" >&2; exit 1; }
1326 attest sign --key "$TMPDIR/host" --name "$host" loose.txt > loose.note
1327 if verify loose.note "$TMPDIR/known_keys" > loose.out 2>&1; then
1328 echo "attest-e2e: a statement not in the written form must not verify" >&2
1329 exit 1
1330 fi
1331 grep -q 'not the written form of what it says' loose.out
1332
1333 # The subject is the tree. Change the tree and the same
1334 # signed statement stops being about it …
1335 echo goodbye > hello.txt
1336 git commit --quiet -am "change the tree"
1337 if verify statement.note "$TMPDIR/known_keys" > moved.out 2>&1; then
1338 echo "attest-e2e: a statement about another tree must not verify" >&2
1339 exit 1
1340 fi
1341 grep -q 'tree digest mismatch' moved.out
1342
1343 # … while rewriting the commit over the same tree leaves the
1344 # attestation standing, which is what a subject that is a
1345 # tree digest buys.
1346 git commit --quiet --amend -m "same tree, new commit"
1347 rewritten="$(attest digest | sed 's/^valley-tree-v1://')"
1348 git revert --quiet --no-edit HEAD
1349 restored="$(attest digest | sed 's/^valley-tree-v1://')"
1350 if [ "$restored" != "$digest" ]; then
1351 echo "attest-e2e: restoring the tree did not restore its digest" >&2
1352 echo " original $digest" >&2
1353 echo " restored $restored" >&2
1354 exit 1
1355 fi
1356 if [ "$rewritten" = "$digest" ]; then
1357 echo "attest-e2e: a changed tree kept its digest" >&2
1358 exit 1
1359 fi
1360 verify statement.note "$TMPDIR/known_keys" > rebased.out
1361 grep -q 'matches the recorded subject digest' rebased.out
1362 touch $out
1363 '';
1364
1365 # The verification-policy deriver (dcr-f41f718). Composing the two
1366 # layers is CUE's job and is pinned by cue-vet above; matching
1367 # paths is the script's own, and a path matcher is wrong exactly at
1368 # the glob boundaries — `*` inside one segment against `**` across
1369 # segments, `**` matching no segment at all — and at the sides of a
1370 # diff a naive reader drops: a rename's old path and a deletion.
1371 # Each is pinned by driving the real script over a scratch
1372 # repository and a scratch policy, never by reading the code.
1373 policy-deriver =
1374 let
1375 # A floor whose classes are one glob boundary each, and whose
1376 # check names say which class matched.
1377 deriverFloor = pkgs.writeText "deriver-floor.cue" ''
1378 package verification
1379 floor: {
1380 checks: {
1381 "c-docs": {runner: "nix", attribute: "c-docs"}
1382 "c-notes": {runner: "nix", attribute: "c-notes"}
1383 "c-flat": {runner: "nix", attribute: "c-flat"}
1384 "c-deep": {runner: "nix", attribute: "c-deep"}
1385 "c-nested": {runner: "nix", attribute: "c-nested"}
1386 "c-uncovered": {runner: "nix", attribute: "c-uncovered"}
1387 }
1388 classes: {
1389 docs: {paths: "docs/**": true, requires: "c-docs": true}
1390 notes: {paths: "notes/**": true, requires: "c-notes": true}
1391 flat: {paths: "src/*.rs": true, requires: "c-flat": true}
1392 deep: {paths: "src/**/*.rs": true, requires: "c-deep": true}
1393 nested: {paths: "a/**/b": true, requires: "c-nested": true}
1394 }
1395 unclassified: "c-uncovered": true
1396 }
1397 '';
1398 # One requirement that is a template default rather than a
1399 # rule, so the two forms are told apart on real output.
1400 deriverTemplate = pkgs.writeText "deriver-template.cue" ''
1401 package verification
1402 #tmpl: #Policy & {
1403 checks: "c-tmpl": {runner: "nix", attribute: "c-tmpl"}
1404 classes: docs: requires: "c-tmpl": bool | *true
1405 }
1406 '';
1407 deriverProject = pkgs.writeText "deriver-project.cue" ''
1408 package verification
1409 project: {
1410 #tmpl
1411 }
1412 '';
1413 in
1414 pkgs.runCommand "valley-policy-deriver"
1415 {
1416 nativeBuildInputs = [
1417 pkgs.git
1418 pkgs.cue
1419 (valleyScriptFor pkgs)
1420 ];
1421 }
1422 ''
1423 export HOME="$TMPDIR"
1424 export GIT_CONFIG_NOSYSTEM=1
1425 git config --global user.name valley-check
1426 git config --global user.email valley-check@localhost
1427 git config --global init.defaultBranch main
1428
1429 policy="$TMPDIR/policy"
1430 mkdir -p "$policy/instance" "$policy/project"
1431 cp ${deriverFloor} "$policy/instance/floor.cue"
1432 cp ${deriverTemplate} "$policy/instance/template.cue"
1433 cp ${deriverProject} "$policy/project/policy.cue"
1434
1435 repo="$TMPDIR/tree"
1436 git init --quiet "$repo"
1437 cd "$repo"
1438 mkdir -p docs notes src/deep a/x/y
1439 echo moved > docs/moved.md
1440 for f in docs/kept.md docs/gone.md src/one.rs src/deep/two.rs \
1441 a/b a/x/y/b Makefile; do
1442 echo seed > "$f"
1443 done
1444 git add -A
1445 git commit --quiet -m base
1446 base="$(git rev-parse HEAD)"
1447
1448 derive() {
1449 valley checks --schema ${./schema/verification.cue} \
1450 --instance "$policy/instance" --project "$policy/project" \
1451 "$base" HEAD
1452 }
1453
1454 # The check names in the deriver's table, sorted, on one line.
1455 named() {
1456 awk '/^required checks:$/ {f = 1; next}
1457 /^$/ {f = 0}
1458 f && /^ / {print $1}' <<<"$report" | sort | paste -sd' ' -
1459 }
1460
1461 # Start a case from the base tree; assert its check table.
1462 case_start() { git checkout --quiet -B "$1" "$base"; }
1463 expect() {
1464 local got
1465 got="$(named)"
1466 if [ "$got" != "$1" ]; then
1467 echo "policy-deriver: $2" >&2
1468 echo " expected: $1" >&2
1469 echo " got: $got" >&2
1470 echo "$report" >&2
1471 exit 1
1472 fi
1473 }
1474
1475 # `**` crosses segments, `*` does not. One file under src/
1476 # matches both patterns; one a segment deeper matches only
1477 # the `**` one.
1478 case_start flat
1479 echo edit > src/one.rs
1480 git commit --quiet -am flat
1481 report="$(derive)"
1482 expect "c-deep c-flat" "src/*.rs must match a file directly under src/"
1483
1484 case_start deep
1485 echo edit > src/deep/two.rs
1486 git commit --quiet -am deep
1487 report="$(derive)"
1488 expect "c-deep" "src/*.rs must not match across a path separator"
1489
1490 # A `**` between two segments matches no segment at all …
1491 case_start nested-none
1492 echo edit > a/b
1493 git commit --quiet -am nested-none
1494 report="$(derive)"
1495 expect "c-nested" "a/**/b must match a/b"
1496
1497 # … and any number of them.
1498 case_start nested-many
1499 echo edit > a/x/y/b
1500 git commit --quiet -am nested-many
1501 report="$(derive)"
1502 expect "c-nested" "a/**/b must match a/x/y/b"
1503
1504 # A rename counts on both sides: the class covering the old
1505 # path is required as much as the one covering the new.
1506 case_start renamed
1507 git mv docs/moved.md notes/moved.md
1508 git commit --quiet -m renamed
1509 git diff --name-status -M "$base" HEAD | grep -q '^R' \
1510 || { echo "policy-deriver: the rename case is not a rename" >&2; exit 1; }
1511 report="$(derive)"
1512 expect "c-docs c-notes c-tmpl" "a rename must count on both sides"
1513
1514 # A deleted path is still a changed path.
1515 case_start deleted
1516 git rm --quiet docs/gone.md
1517 git commit --quiet -m deleted
1518 report="$(derive)"
1519 expect "c-docs c-tmpl" "a deletion must count"
1520
1521 # The form of the value is the mandatory bit: the floor's
1522 # concrete `true` against the template's `bool | *true`.
1523 grep -qE '^ c-docs +mandatory +docs$' <<<"$report"
1524 grep -qE '^ c-tmpl +default +docs$' <<<"$report"
1525
1526 # A path no class covers takes the unclassified set, and says
1527 # so by name.
1528 case_start uncovered
1529 echo edit > Makefile
1530 git commit --quiet -am uncovered
1531 report="$(derive)"
1532 expect "c-uncovered" "an uncovered path must take the unclassified set"
1533 grep -q '^classes matched: unclassified$' <<<"$report"
1534 grep -q '^unclassified: 1 path(s) matched no class$' <<<"$report"
1535 grep -q '^ Makefile$' <<<"$report"
1536
1537 touch $out
1538 '';
1539
1540 module-eval =
1541 if failedAssertions != [ ] then
1542 throw "valley module-eval: failed assertions: ${lib.concatMapStringsSep "; " (a: a.message) failedAssertions}"
1543 else if resticRenderedWithoutDeclaration then
1544 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
1545 else if busRenderedWithoutEnable then
1546 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
1547 else if
1548 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
1549 then
1550 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
1551 else
1552 pkgs.runCommand "valley-module-eval"
1553 {
1554 initScript = host.config.systemd.services.valley-init.script;
1555 sshdConfig = host.config.services.openssh.extraConfig;
1556 resticService = host.config.systemd.units."restic-backups-valley.service".text;
1557 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
1558 passAsFile = [
1559 "initScript"
1560 "sshdConfig"
1561 "resticService"
1562 "resticTimer"
1563 ];
1564 }
1565 ''
1566 # The repo init list and mirror hook must be generated from
1567 # the CUE export, and the git user's sshd Match block must
1568 # be terminated so it cannot scope later config.
1569 grep -q "the-valley" "$initScriptPath"
1570 grep -q "valley-mirrors" "$initScriptPath"
1571 grep -q "Match All" "$sshdConfigPath"
1572
1573 # The mirror publishes main and tags only — a heads glob
1574 # would publish every topic branch awaiting review — with
1575 # --prune for tag deletions and a sweep that unpublishes
1576 # any other head (--prune cannot: it ignores non-glob
1577 # refspecs). Never --mirror: it also deletes remote-only
1578 # refs, and GitHub's read-only refs/pull/* fails every such
1579 # push. Follow the hook chain from the init script to the
1580 # rendered push script and pin the invocation there.
1581 mirrorHook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-[^ ]*' "$initScriptPath" | head -n1)"
1582 mirrorPush="$(grep -o '/nix/store/[^ ]*-valley-mirror-push-[^ ]*' "$mirrorHook" | head -n1)"
1583 grep -q -- 'push --prune' "$mirrorPush"
1584 grep -qF -- '+refs/heads/main:refs/heads/main' "$mirrorPush"
1585 grep -qF -- '+refs/tags/*:refs/tags/*' "$mirrorPush"
1586 grep -qF -- 'ls-remote --heads' "$mirrorPush"
1587 grep -qF -- 'push "$url" --delete' "$mirrorPush"
1588 if grep -qF -- '+refs/heads/*:refs/heads/*' "$mirrorPush"; then
1589 echo "module-eval: mirror push regressed to publishing every head" >&2
1590 exit 1
1591 fi
1592 if grep -q -- '--mirror' "$mirrorPush"; then
1593 echo "module-eval: mirror push regressed to --mirror" >&2
1594 exit 1
1595 fi
1596 # Deletions must never reach a namespace the mirror owns.
1597 if grep -q 'refs/pull' "$mirrorPush"; then
1598 echo "module-eval: mirror push must not name refs/pull/*" >&2
1599 exit 1
1600 fi
1601
1602 # The rendered restic units must back up the data directory
1603 # to the consumer-supplied repository with the declared
1604 # retention over a pinned host key, on the declared cadence.
1605 grep -q "RESTIC_REPOSITORY_FILE=/run/agenix/valley-restic-repo" "$resticServicePath"
1606 grep -q -- "--keep-daily 7 --keep-weekly 4 --keep-monthly 6" "$resticServicePath"
1607 grep -q "UserKnownHostsFile=/var/lib/valley-backup/known_hosts" "$resticServicePath"
1608 grep -q "BatchMode=yes" "$resticServicePath"
1609 grep -q "OnCalendar=03:30" "$resticTimerPath"
1610
1611 # The backup paths render as a --files-from list: follow
1612 # ExecStartPre to that list and pin the data directory.
1613 preStart="$(sed -n 's/^ExecStartPre=//p' "$resticServicePath" | head -n1)"
1614 staticPaths="$(grep -o '/nix/store/[^ ]*-staticPaths' "$preStart" | head -n1)"
1615 grep -qx "/srv/git" "$staticPaths"
1616 touch $out
1617 '';
1618
1619 # What a mirror ends up holding, end to end and unmocked: a bare
1620 # repo wired with the real rendered hooks, pushed to for real, and
1621 # a second bare repo standing in for the mirror. The refspec is
1622 # easy to get subtly wrong — --prune ignores the non-glob heads
1623 # refspec, so pruning heads is the sweep's job — and only running
1624 # git can tell. Relative mirror URLs (mirrorHost) resolve against
1625 # the pushing repo, so the shipped scripts run with no
1626 # substitution: this is exactly what a host executes.
1627 mirror-e2e =
1628 pkgs.runCommand "valley-mirror-e2e"
1629 {
1630 nativeBuildInputs = [ pkgs.git ];
1631 initScript = mirrorHost.config.systemd.services.valley-init.script;
1632 passAsFile = [ "initScript" ];
1633 }
1634 ''
1635 export HOME="$TMPDIR"
1636 export GIT_CONFIG_NOSYSTEM=1
1637 git config --global user.name valley-check
1638 git config --global user.email valley-check@localhost
1639 git config --global init.defaultBranch main
1640 cd "$TMPDIR"
1641
1642 wait_for() {
1643 for _ in $(seq 1 150); do
1644 "$@" >/dev/null 2>&1 && return 0
1645 sleep 0.2
1646 done
1647 echo "mirror-e2e: timed out waiting for: $*" >&2
1648 return 1
1649 }
1650 heads() { git -C mirror.git for-each-ref --format='%(refname)' refs/heads; }
1651 tags() { git -C mirror.git for-each-ref --format='%(refname)' refs/tags; }
1652 mirror_main_is() { [ "$(git -C mirror.git rev-parse main)" = "$tip" ]; }
1653 only_main() { [ "$(heads)" = refs/heads/main ]; }
1654
1655 # A primary repo wired exactly as valley-init wires it, with
1656 # the real store paths followed from the rendered init script.
1657 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
1658 mhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-mirror-pilot' "$initScriptPath" | head -n1)"
1659 deadhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-dead-mirror' "$initScriptPath" | head -n1)"
1660 test -x "$dispatch" && test -x "$mhook" && test -x "$deadhook"
1661 wire() {
1662 mkdir -p "$1/hooks/post-receive.d"
1663 ln -s "$dispatch" "$1/hooks/post-receive"
1664 ln -s "$2" "$1/hooks/post-receive.d/valley-mirrors"
1665 }
1666
1667 # The mirror as it stands today: every head and tag of the
1668 # primary, topic branches included. Seeded before the hook is
1669 # wired, so nothing sweeps it out from under the setup.
1670 git init --quiet --bare mirror-pilot.git
1671 git init --quiet --bare mirror.git
1672 git clone --quiet "$PWD/mirror-pilot.git" work
1673 git -C work commit --quiet --allow-empty -m one
1674 git -C work tag v1
1675 git -C work tag doomed
1676 for b in idea/one idea/two; do git -C work branch "$b"; done
1677 git -C work push --quiet origin \
1678 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
1679 git -C mirror-pilot.git push --quiet ../mirror.git \
1680 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
1681 [ "$(heads | wc -l)" -eq 3 ]
1682 wire mirror-pilot.git "$mhook"
1683
1684 # A real push to the primary — a topic branch alongside main,
1685 # and a tag deleted. The hook replicates asynchronously, so
1686 # wait on main's new tip before judging the rest.
1687 git -C work commit --quiet --allow-empty -m two
1688 git -C work tag -d doomed >/dev/null
1689 git -C work branch idea/three
1690 git -C work push --quiet --follow-tags origin main idea/three
1691 git -C work push --quiet --delete origin doomed
1692 tip="$(git -C work rev-parse HEAD)"
1693 wait_for mirror_main_is
1694
1695 # main and the tags are published; nothing else is, and the
1696 # topic branches that were on the mirror are gone. The sweep
1697 # is a second push, so it converges just after main lands.
1698 wait_for only_main
1699 [ "$(tags)" = refs/tags/v1 ]
1700
1701 # A branch that appears on the mirror by any other route is
1702 # unpublished on the next push.
1703 git -C mirror.git branch sneaky main
1704 git -C work commit --quiet --allow-empty -m three
1705 git -C work push --quiet origin main
1706 tip="$(git -C work rev-parse HEAD)"
1707 wait_for mirror_main_is
1708 wait_for only_main
1709
1710 # An unreachable mirror costs a log line, never the push: the
1711 # hook must return promptly and the push must succeed.
1712 git init --quiet --bare dead-mirror.git
1713 wire dead-mirror.git "$deadhook"
1714 git clone --quiet "$PWD/dead-mirror.git" deadwork
1715 git -C deadwork commit --quiet --allow-empty -m one
1716 timeout 60 git -C deadwork push --quiet origin main
1717 [ "$(git -C dead-mirror.git rev-parse main)" = "$(git -C deadwork rev-parse HEAD)" ]
1718
1719 touch $out
1720 '';
1721
1722 # Phase 1's exit criteria, end to end and unmocked: a push to a
1723 # bare repo wired with the real rendered hooks produces a
1724 # ref-updated event on a real JetStream server within seconds,
1725 # visible in `valley tail`; replaying the repo's refs is
1726 # deterministic; and a dead bus never fails a push. The hook and
1727 # stream-init scripts are followed from the rendered unit scripts,
1728 # so the check exercises exactly what a host would run — only the
1729 # server invocation differs (the sandbox cannot write /srv), same
1730 # binary and flags, relocated storage.
1731 bus-e2e =
1732 pkgs.runCommand "valley-bus-e2e"
1733 {
1734 nativeBuildInputs = [
1735 pkgs.git
1736 pkgs.natscli
1737 pkgs.nats-server
1738 pkgs.jq
1739 pkgs.cue
1740 (valleyScriptFor pkgs)
1741 ];
1742 initScript = busHost.config.systemd.services.valley-init.script;
1743 busInitScript = busHost.config.systemd.services.valley-bus-init.script;
1744 passAsFile = [
1745 "initScript"
1746 "busInitScript"
1747 ];
1748 }
1749 ''
1750 export HOME="$TMPDIR"
1751 export NATS_URL=nats://127.0.0.1:4222
1752 export GIT_CONFIG_NOSYSTEM=1
1753 git config --global user.name valley-check
1754 git config --global user.email valley-check@localhost
1755 git config --global init.defaultBranch main
1756
1757 wait_for() {
1758 for _ in $(seq 1 150); do
1759 "$@" >/dev/null 2>&1 && return 0
1760 sleep 0.2
1761 done
1762 echo "bus-e2e: timed out waiting for: $*" >&2
1763 return 1
1764 }
1765
1766 nats-server --addr 127.0.0.1 --port 4222 --jetstream \
1767 --store_dir "$TMPDIR/js" &
1768 server_pid=$!
1769
1770 # The real stream-init script the module renders.
1771 bash -eu "$busInitScriptPath"
1772 nats stream info valley >/dev/null
1773
1774 # A bare repo wired exactly as valley-init wires it, with the
1775 # real store paths followed from the rendered init script.
1776 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
1777 bushook="$(grep -o '/nix/store/[^ ]*-valley-bus-events' "$initScriptPath" | head -n1)"
1778 test -x "$dispatch"
1779 test -x "$bushook"
1780 repo="$TMPDIR/events-pilot.git"
1781 git init --quiet --bare "$repo"
1782 mkdir -p "$repo/hooks/post-receive.d"
1783 ln -s "$dispatch" "$repo/hooks/post-receive"
1784 ln -s "$bushook" "$repo/hooks/post-receive.d/valley-bus"
1785
1786 git clone --quiet "$repo" "$TMPDIR/work"
1787 cd "$TMPDIR/work"
1788 echo one > file
1789 git add file
1790 git commit --quiet -m one
1791 git push --quiet origin main
1792 first="$(git rev-parse HEAD)"
1793 zeros="$(printf '%040d' 0)"
1794
1795 # Exit criterion 1: the event arrives within seconds, with a
1796 # payload that is exactly the git facts of the push …
1797 msgs_is() { [ "$(nats stream info valley --json | jq .state.messages)" -eq "$1" ]; }
1798 wait_for msgs_is 1
1799 got="$(nats stream get valley 1 --json)"
1800 [ "$(jq -r .subject <<<"$got")" = valley.git.events-pilot.ref-updated ]
1801 payload="$(jq -r .data <<<"$got" | base64 -d)"
1802 expected='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$first"'"}'
1803 [ "$payload" = "$expected" ]
1804
1805 # … valid against the shipped event schema.
1806 echo "$payload" > "$TMPDIR/payload.json"
1807 cue vet -d '#RefUpdated' ${./schema/events.cue} "$TMPDIR/payload.json"
1808
1809 # … and visible in `valley tail`. Subscribe first, then push.
1810 valley tail > "$TMPDIR/tail.out" 2>&1 &
1811 tail_pid=$!
1812 subscribed() { grep -q 'valley.>' "$TMPDIR/tail.out"; }
1813 wait_for subscribed
1814 echo two > file
1815 git commit --quiet -am two
1816 git push --quiet origin main
1817 second="$(git rev-parse HEAD)"
1818 wait_for msgs_is 2
1819 payload2="$(nats stream get valley 2 --json | jq -r .data | base64 -d)"
1820 expected2='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$first"'","new":"'"$second"'"}'
1821 [ "$payload2" = "$expected2" ]
1822 tail_saw() { grep -qF "$expected2" "$TMPDIR/tail.out"; }
1823 wait_for tail_saw
1824 kill "$tail_pid" 2>/dev/null || true
1825
1826 # Exit criterion 2: rebuilding the stream from the repo's
1827 # refs is deterministic — two replays from scratch produce
1828 # identical events, landing on the pushed tip with the
1829 # all-zero id as old.
1830 dump_stream() {
1831 local info first_seq last_seq i
1832 info="$(nats stream info valley --json)"
1833 first_seq="$(jq .state.first_seq <<<"$info")"
1834 last_seq="$(jq .state.last_seq <<<"$info")"
1835 for i in $(seq "$first_seq" "$last_seq"); do
1836 nats stream get valley "$i" --json | jq -c '{subject: .subject, data: .data}'
1837 done
1838 }
1839 nats stream purge valley --force >/dev/null
1840 valley replay "$repo"
1841 wait_for msgs_is 1
1842 run1="$(dump_stream)"
1843 nats stream purge valley --force >/dev/null
1844 valley replay "$repo"
1845 wait_for msgs_is 1
1846 run2="$(dump_stream)"
1847 [ "$run1" = "$run2" ]
1848 replayed="$(jq -r .data <<<"$run1" | base64 -d)"
1849 [ "$replayed" = '{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$second"'"}' ]
1850
1851 # A dead bus never blocks a push: the event is simply lost
1852 # (and rebuildable by replay).
1853 kill "$server_pid"
1854 wait "$server_pid" || true
1855 echo three > file
1856 git commit --quiet -am three
1857 git push --quiet origin main
1858
1859 touch $out
1860 '';
1861 }
1862 );
1863 };
1864}