gunk-dev/the-valley

flake.nix

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