gunk-dev/the-valley

flake.nix

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