gunk-dev/the-valley

flake.nix

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