gunk-dev/the-valley

flake.nix

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