gunk-dev/the-valley

flake.nix

source36458df40860main's published tip history
48.7 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 in
66 {
67 nixosModules.valley-host = ./nix/valley-host.nix;
68 nixosModules.default = self.nixosModules.valley-host;
69
70 # The knowledge lint, for any project that keeps a `.the-valley/` graph.
71 # This is the check's primary form: a consuming project takes this flake
72 # as an input and instantiates the derivation over its own source, so the
73 # check a policy names is supplied by the instance rather than written
74 # again by every project the policy covers (dcr-f41f718). A whole
75 # consuming flake is:
76 #
77 # {
78 # inputs.the-valley.url = "github:gunk-dev/the-valley";
79 # outputs =
80 # { self, the-valley }:
81 # {
82 # checks.x86_64-linux.knowledge-lint = the-valley.lib.knowledgeLint {
83 # system = "x86_64-linux";
84 # src = self;
85 # };
86 # };
87 # }
88 #
89 # There is no nixpkgs input in that flake on purpose: cue and python come
90 # from this flake's pinned nixpkgs, so every project in a group runs the
91 # same lint against the same toolchain. `root` names the graph directory
92 # for a project that keeps its graph somewhere other than `.the-valley/`.
93 lib.knowledgeLint =
94 {
95 system,
96 src,
97 root ? ".the-valley",
98 }:
99 import ./nix/knowledge-lint.nix {
100 inherit src root;
101 pkgs = nixpkgs.legacyPackages.${system};
102 };
103
104 apps = lib.genAttrs systems (system: {
105 fmt = {
106 type = "app";
107 program = lib.getExe (proseFmtFor nixpkgs.legacyPackages.${system});
108 };
109 });
110
111 packages = lib.genAttrs systems (
112 system:
113 let
114 valley = valleyCliFor nixpkgs.legacyPackages.${system};
115 in
116 {
117 inherit valley;
118 default = valley;
119 }
120 );
121
122 checks = lib.genAttrs systems (
123 system:
124 let
125 pkgs = nixpkgs.legacyPackages.${system};
126
127 # Eval-only instantiation of the module — catches option-surface
128 # and cue-export regressions without building or booting anything.
129 # Each check host shares the machine baseline and supplies its own
130 # declaration (and, where the declaration asks for backup, the
131 # secret paths).
132 mkHost =
133 module:
134 lib.nixosSystem {
135 inherit system;
136 modules = [
137 self.nixosModules.default
138 {
139 fileSystems."/" = {
140 device = "/dev/disk/by-label/nixos";
141 fsType = "ext4";
142 };
143 boot.loader.grub.enable = false;
144 system.stateVersion = "25.11";
145 services.valley = {
146 enable = true;
147 authorizedKeys = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPlaceholderKeyForEvalOnlyCheck0 valley-check" ];
148 };
149 }
150 module
151 ];
152 };
153
154 # The example declaration enables backup, so this host supplies
155 # the four secret paths (eval-only placeholders).
156 host = mkHost {
157 services.valley = {
158 config = ./examples/host.cue;
159 backup = {
160 repositoryFile = "/run/agenix/valley-restic-repo";
161 passwordFile = "/run/agenix/valley-restic-password";
162 sshKeyFile = "/run/agenix/valley-git-ssh-key";
163 knownHostsFile = "/var/lib/valley-backup/known_hosts";
164 };
165 };
166 };
167
168 # A declaration without a backup block predates the field and must
169 # keep evaluating exactly as before: zero restic machinery.
170 noBackupHost = mkHost {
171 services.valley.config = pkgs.writeText "no-backup-host.cue" ''
172 package valley
173 projects: "the-valley": {}
174 '';
175 };
176
177 # The example declaration with the secret paths left unset: the
178 # module must refuse with assertions naming the missing options.
179 noSecretsHost = mkHost {
180 services.valley.config = ./examples/host.cue;
181 };
182
183 # Bus enabled, minimal declaration. The bus-e2e check drives this
184 # host's rendered hooks and stream-init against a real server.
185 busHost = mkHost {
186 services.valley = {
187 config = pkgs.writeText "bus-host.cue" ''
188 package valley
189 projects: "events-pilot": {}
190 '';
191 bus.enable = true;
192 };
193 };
194
195 # Two mirror URLs the sandbox can serve: git resolves a relative
196 # URL against the pushing repo's directory, so the mirror-e2e
197 # check drives the rendered script with no substitution at all —
198 # one reachable sibling repo, one that does not exist.
199 mirrorHost = mkHost {
200 services.valley.config = pkgs.writeText "mirror-host.cue" ''
201 package valley
202 projects: "mirror-pilot": mirrors: ["../mirror.git"]
203 projects: "dead-mirror": mirrors: ["../nope.git"]
204 '';
205 };
206
207 failedAssertions = builtins.filter (a: !a.assertion) (
208 host.config.assertions
209 ++ noBackupHost.config.assertions
210 ++ busHost.config.assertions
211 ++ mirrorHost.config.assertions
212 );
213
214 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
215
216 resticRenderedWithoutDeclaration =
217 noBackupHost.config.systemd.services ? "restic-backups-valley"
218 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
219
220 # The bus defaults off; a host that never asked for one must
221 # render zero bus machinery.
222 busRenderedWithoutEnable =
223 noBackupHost.config.systemd.services ? valley-bus
224 || noBackupHost.config.systemd.services ? valley-bus-init;
225
226 # A tree in the store, written from a path -> contents map. The
227 # knowledge lint reads a whole graph rather than a file, so every
228 # fixture below is small but complete.
229 mkTree =
230 name: files:
231 pkgs.runCommand name { } (
232 lib.concatStrings (
233 lib.mapAttrsToList (path: text: ''
234 install -Dm444 ${pkgs.writeText "knowledge-lint-fixture" text} $out/${path}
235 '') files
236 )
237 );
238
239 # A project that is nearly nothing: a README, a docs directory, and
240 # two nodes. This is the shape the first consuming project has, and
241 # the knowledge-lint-consumer check instantiates lib.knowledgeLint
242 # over it exactly as that project's own flake would.
243 consumerProject = mkTree "knowledge-lint-consumer-project" {
244 "README.md" = ''
245 # A project
246
247 It keeps its knowledge in [.the-valley](./.the-valley/).
248 '';
249 "docs/design.md" = ''
250 # Design
251
252 ## The shape
253 '';
254 ".the-valley/ideas/ida-0a1b2c3-the-shape.md" = ''
255 ---
256 type: idea
257 id: ida-0a1b2c3
258 status: raw
259 title: The shape the design should take
260 created: 2026-08-02
261 ---
262
263 # The shape the design should take
264
265 As sketched in [design.md](../../docs/design.md#the-shape).
266 '';
267 ".the-valley/outcomes/oc-4d5e6f7-the-design-lands.md" = ''
268 ---
269 type: outcome
270 id: oc-4d5e6f7
271 status: open
272 title: The design lands
273 created: 2026-08-02
274 blocked_by: [ida-0a1b2c3]
275 ---
276
277 # The design lands
278
279 Waits on [[ida-0a1b2c3]].
280 '';
281 };
282
283 # A project with no graph at all. Adding the check must not require
284 # having written a node yet, or no project would ever adopt it
285 # before its first one.
286 graphlessProject = mkTree "knowledge-lint-graphless-project" {
287 "README.md" = ''
288 # A project with no knowledge graph yet
289 '';
290 };
291
292 # What the lint must reject, and the words its failure must contain.
293 # A lint that fails without naming the file and the defect costs the
294 # reader the whole diagnosis, so both are pinned.
295 rejectedGraphs = {
296 unknown-status = {
297 names = ''ida-0000001-a-node.md".status'';
298 files.".the-valley/ideas/ida-0000001-a-node.md" = ''
299 ---
300 type: idea
301 id: ida-0000001
302 status: nonsense
303 title: A node in a state ideas do not have
304 created: 2026-08-02
305 ---
306 '';
307 };
308
309 edge-on-the-wrong-type = {
310 names = "blocked_by: field not allowed";
311 files.".the-valley/ideas/ida-0000002-a-node.md" = ''
312 ---
313 type: idea
314 id: ida-0000002
315 status: raw
316 title: An idea carrying the one edge only outcomes carry
317 created: 2026-08-02
318 blocked_by: []
319 ---
320 '';
321 };
322
323 node-in-the-wrong-directory = {
324 names = "a bug node belongs in .the-valley/bugs/";
325 files.".the-valley/ideas/bd-0000003-a-bug.md" = ''
326 ---
327 type: bug
328 id: bd-0000003
329 status: open
330 title: A bug filed among the ideas
331 created: 2026-08-02
332 ---
333 '';
334 };
335
336 filename-id-mismatch = {
337 names = "filename says id ida-0000004, frontmatter says ida-0000005";
338 files.".the-valley/ideas/ida-0000004-a-node.md" = ''
339 ---
340 type: idea
341 id: ida-0000005
342 status: raw
343 title: A node whose filename and frontmatter disagree
344 created: 2026-08-02
345 ---
346 '';
347 };
348
349 duplicate-id = {
350 names = "is already used by";
351 files = {
352 ".the-valley/ideas/ida-0000006-one.md" = ''
353 ---
354 type: idea
355 id: ida-0000006
356 status: raw
357 title: One node
358 created: 2026-08-02
359 ---
360 '';
361 ".the-valley/ideas/ida-0000006-two.md" = ''
362 ---
363 type: idea
364 id: ida-0000006
365 status: raw
366 title: Another node wearing the same id
367 created: 2026-08-02
368 ---
369 '';
370 };
371 };
372
373 missing-frontmatter = {
374 names = "no YAML frontmatter";
375 files.".the-valley/ideas/ida-0000007-a-node.md" = ''
376 # A node that is only prose
377 '';
378 };
379
380 dangling-wiki-link = {
381 names = "[[ida-9999999]] is not a node id";
382 files.".the-valley/ideas/ida-0000008-a-node.md" = ''
383 ---
384 type: idea
385 id: ida-0000008
386 status: raw
387 title: A node pointing at nothing
388 created: 2026-08-02
389 ---
390
391 It builds on [[ida-9999999]].
392 '';
393 };
394
395 dangling-blocked-by = {
396 names = "blocked_by names oc-9999999, which is not a node";
397 files.".the-valley/outcomes/oc-0000009-an-outcome.md" = ''
398 ---
399 type: outcome
400 id: oc-0000009
401 status: open
402 title: An outcome waiting on nothing that exists
403 created: 2026-08-02
404 blocked_by: [oc-9999999]
405 ---
406 '';
407 };
408
409 broken-link = {
410 names = "./nowhere.md does not exist";
411 files.".the-valley/ideas/ida-000000a-a-node.md" = ''
412 ---
413 type: idea
414 id: ida-000000a
415 status: raw
416 title: A node linking to a file that is not there
417 created: 2026-08-02
418 ---
419
420 See [nowhere](./nowhere.md).
421 '';
422 };
423
424 broken-anchor = {
425 names = "names no heading";
426 files.".the-valley/ideas/ida-000000b-a-node.md" = ''
427 ---
428 type: idea
429 id: ida-000000b
430 status: raw
431 title: A node linking to a heading that is not there
432 created: 2026-08-02
433 ---
434
435 # A heading
436
437 See [above](./ida-000000b-a-node.md#not-this-heading).
438 '';
439 };
440 };
441 in
442 {
443 # The CLI must stay a lint-clean script whose help verb answers
444 # without a repo or a remote — the cheap end of its eviction clause
445 # (dcr-74c3158); anything needing more graduates instead. The
446 # completions are held to the same bar, and the installed package
447 # must carry them at the auto-linked paths.
448 valley-cli =
449 let
450 valley = valleyCliFor pkgs;
451 in
452 pkgs.runCommand "valley-cli"
453 {
454 nativeBuildInputs = [
455 pkgs.shellcheck
456 pkgs.zsh
457 valley
458 ];
459 }
460 ''
461 shellcheck ${./bin/valley}
462 shellcheck ${./completions/valley.bash}
463 # shellcheck cannot lint zsh; a bare parse is the cheap check.
464 zsh -n ${./completions/_valley}
465 valley help > help.txt
466 grep -q '^usage: valley' help.txt
467 test -f ${valley}/share/bash-completion/completions/valley
468 test -f ${valley}/share/zsh/site-functions/_valley
469 touch $out
470 '';
471
472 # Markdown prose format (ida-1ec03b1): the check is formatter
473 # idempotence — formatting the tree must change nothing. On failure,
474 # fix with `nix run .#fmt`.
475 prose-format =
476 pkgs.runCommand "valley-prose-format"
477 {
478 nativeBuildInputs = [ pkgs.prettier ];
479 }
480 ''
481 cd ${self}
482 find . -name '*.md' -print0 | xargs -0 --no-run-if-empty \
483 prettier ${proseFmtArgs} --check
484 touch $out
485 '';
486
487 # This repo's own graph, checked by the derivation the flake
488 # exposes rather than by a second implementation of it. Whatever a
489 # consuming project runs, this repo runs.
490 knowledge-lint = self.lib.knowledgeLint {
491 inherit system;
492 src = self;
493 };
494
495 # The reusable form, exercised over a foreign tree: a project that
496 # is a README, a docs directory and two nodes, and a project with no
497 # graph at all. Both must pass, and both are checked by depending on
498 # the instantiated derivations rather than by re-running the lint.
499 knowledge-lint-consumer =
500 pkgs.runCommand "valley-knowledge-lint-consumer"
501 {
502 consumer = self.lib.knowledgeLint {
503 inherit system;
504 src = consumerProject;
505 };
506 graphless = self.lib.knowledgeLint {
507 inherit system;
508 src = graphlessProject;
509 };
510 }
511 ''
512 test -e "$consumer" && test -e "$graphless"
513 touch $out
514 '';
515
516 # The lint must fail on a broken graph, and its failure must name
517 # the file and the defect — a check that only says "no" leaves the
518 # reader to find the breakage themselves. The script and the schema
519 # here are the same store paths lib.knowledgeLint uses, so the
520 # rejections cannot drift from what a consumer runs.
521 knowledge-lint-rejects =
522 pkgs.runCommand "valley-knowledge-lint-rejects"
523 {
524 nativeBuildInputs = [
525 pkgs.cue
526 pkgs.python3
527 ];
528 }
529 ''
530 ${lib.concatStrings (
531 lib.mapAttrsToList (case: spec: ''
532 mkdir -p work/${case}
533 if python3 ${./nix/knowledge-lint.py} \
534 --tree ${mkTree "knowledge-lint-${case}" spec.files} \
535 --schema ${./schema/node.cue} \
536 --work work/${case} 2> ${case}.err
537 then
538 echo "knowledge-lint: expected graph '${case}' to be rejected" >&2
539 exit 1
540 fi
541 if ! grep -qF -- ${lib.escapeShellArg spec.names} ${case}.err; then
542 echo "knowledge-lint: '${case}' was rejected without naming" \
543 ${lib.escapeShellArg spec.names} >&2
544 cat ${case}.err >&2
545 exit 1
546 fi
547 '') rejectedGraphs
548 )}
549 touch $out
550 '';
551
552 # The example host declaration must vet against the schema, and the
553 # schema must reject what it claims to reject: unsafe project names,
554 # unknown project fields, stray top-level fields (typos, deployment
555 # concerns), and malformed backup policy (machine concerns, targets
556 # without an implementation, non-positive retention). CUE closedness
557 # is easy to regress silently — e.g. embedding #Host instead of
558 # referencing it opens the schema — so the rejections are pinned
559 # here.
560 cue-vet =
561 let
562 invalidConfigs = {
563 unsafe-project-name = ''
564 package valley
565 projects: ".hidden": {}
566 '';
567 unknown-project-field = ''
568 package valley
569 projects: ok: dataDir: "/srv/git"
570 '';
571 top-level-typo = ''
572 package valley
573 project: oops: {}
574 '';
575 deployment-concern-in-cue = ''
576 package valley
577 user: "git"
578 projects: ok: {}
579 '';
580 machine-concern-in-backup = ''
581 package valley
582 projects: ok: {}
583 backup: repositoryFile: "/run/agenix/valley-restic-repo"
584 '';
585 unimplemented-backup-target = ''
586 package valley
587 projects: ok: {}
588 backup: target: "restic-s3"
589 '';
590 negative-retention = ''
591 package valley
592 projects: ok: {}
593 backup: retention: daily: -1
594 '';
595 };
596 in
597 pkgs.runCommand "valley-cue-vet"
598 {
599 nativeBuildInputs = [ pkgs.cue ];
600 }
601 ''
602 cue vet -c ${./schema/valley.cue} ${./examples/host.cue}
603 cue export ${./schema/valley.cue} ${./examples/host.cue} > example.json
604 grep -q 'gunk-dev/the-valley' example.json
605 grep -q 'restic-sftp' example.json
606
607 # A declaration without a backup block must stay valid —
608 # consumers written before the field existed keep vetting.
609 cue vet -c ${./schema/valley.cue} ${pkgs.writeText "no-backup.cue" ''
610 package valley
611 projects: "the-valley": {}
612 ''}
613
614 # The event schema accepts what the publisher hook emits …
615 cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated.json" ''
616 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"}
617 ''}
618 # … and stays closed: a field outside the git-derivable
619 # identity — wall-clock time, a hostname — must be rejected,
620 # or replay determinism silently dies.
621 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-timestamped.json" ''
622 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3","time":"2026-07-16T00:00:00Z"}
623 ''}; then
624 echo "cue-vet: expected the timestamped ref-updated payload to be rejected" >&2
625 exit 1
626 fi
627 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-short-sha.json" ''
628 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe"}
629 ''}; then
630 echo "cue-vet: expected the abbreviated object id to be rejected" >&2
631 exit 1
632 fi
633
634 ${lib.concatStrings (
635 lib.mapAttrsToList (name: cfg: ''
636 if cue vet -c ${./schema/valley.cue} ${pkgs.writeText "${name}.cue" cfg}; then
637 echo "cue-vet: expected invalid config '${name}' to be rejected" >&2
638 exit 1
639 fi
640 '') invalidConfigs
641 )}
642 touch $out
643 '';
644
645 # The verification-policy deriver (dcr-f41f718). Composing the two
646 # layers is CUE's job and is pinned by cue-vet above; matching
647 # paths is the script's own, and a path matcher is wrong exactly at
648 # the glob boundaries — `*` inside one segment against `**` across
649 # segments, `**` matching no segment at all — and at the sides of a
650 # diff a naive reader drops: a rename's old path and a deletion.
651 # Each is pinned by driving the real script over a scratch
652 # repository and a scratch policy, never by reading the code.
653 policy-deriver =
654 let
655 # A floor whose classes are one glob boundary each, and whose
656 # check names say which class matched.
657 deriverFloor = pkgs.writeText "deriver-floor.cue" ''
658 package verification
659 floor: {
660 checks: {
661 "c-docs": {runner: "nix", attribute: "c-docs"}
662 "c-notes": {runner: "nix", attribute: "c-notes"}
663 "c-flat": {runner: "nix", attribute: "c-flat"}
664 "c-deep": {runner: "nix", attribute: "c-deep"}
665 "c-nested": {runner: "nix", attribute: "c-nested"}
666 "c-uncovered": {runner: "nix", attribute: "c-uncovered"}
667 }
668 classes: {
669 docs: {paths: "docs/**": true, requires: "c-docs": true}
670 notes: {paths: "notes/**": true, requires: "c-notes": true}
671 flat: {paths: "src/*.rs": true, requires: "c-flat": true}
672 deep: {paths: "src/**/*.rs": true, requires: "c-deep": true}
673 nested: {paths: "a/**/b": true, requires: "c-nested": true}
674 }
675 unclassified: "c-uncovered": true
676 }
677 '';
678 # One requirement that is a template default rather than a
679 # rule, so the two forms are told apart on real output.
680 deriverTemplate = pkgs.writeText "deriver-template.cue" ''
681 package verification
682 #tmpl: #Policy & {
683 checks: "c-tmpl": {runner: "nix", attribute: "c-tmpl"}
684 classes: docs: requires: "c-tmpl": bool | *true
685 }
686 '';
687 deriverProject = pkgs.writeText "deriver-project.cue" ''
688 package verification
689 project: {
690 #tmpl
691 }
692 '';
693 in
694 pkgs.runCommand "valley-policy-deriver"
695 {
696 nativeBuildInputs = [
697 pkgs.git
698 pkgs.cue
699 (valleyScriptFor pkgs)
700 ];
701 }
702 ''
703 export HOME="$TMPDIR"
704 export GIT_CONFIG_NOSYSTEM=1
705 git config --global user.name valley-check
706 git config --global user.email valley-check@localhost
707 git config --global init.defaultBranch main
708
709 policy="$TMPDIR/policy"
710 mkdir -p "$policy/instance" "$policy/project"
711 cp ${deriverFloor} "$policy/instance/floor.cue"
712 cp ${deriverTemplate} "$policy/instance/template.cue"
713 cp ${deriverProject} "$policy/project/policy.cue"
714
715 repo="$TMPDIR/tree"
716 git init --quiet "$repo"
717 cd "$repo"
718 mkdir -p docs notes src/deep a/x/y
719 echo moved > docs/moved.md
720 for f in docs/kept.md docs/gone.md src/one.rs src/deep/two.rs \
721 a/b a/x/y/b Makefile; do
722 echo seed > "$f"
723 done
724 git add -A
725 git commit --quiet -m base
726 base="$(git rev-parse HEAD)"
727
728 derive() {
729 valley checks --schema ${./schema/verification.cue} \
730 --instance "$policy/instance" --project "$policy/project" \
731 "$base" HEAD
732 }
733
734 # The check names in the deriver's table, sorted, on one line.
735 named() {
736 awk '/^required checks:$/ {f = 1; next}
737 /^$/ {f = 0}
738 f && /^ / {print $1}' <<<"$report" | sort | paste -sd' ' -
739 }
740
741 # Start a case from the base tree; assert its check table.
742 case_start() { git checkout --quiet -B "$1" "$base"; }
743 expect() {
744 local got
745 got="$(named)"
746 if [ "$got" != "$1" ]; then
747 echo "policy-deriver: $2" >&2
748 echo " expected: $1" >&2
749 echo " got: $got" >&2
750 echo "$report" >&2
751 exit 1
752 fi
753 }
754
755 # `**` crosses segments, `*` does not. One file under src/
756 # matches both patterns; one a segment deeper matches only
757 # the `**` one.
758 case_start flat
759 echo edit > src/one.rs
760 git commit --quiet -am flat
761 report="$(derive)"
762 expect "c-deep c-flat" "src/*.rs must match a file directly under src/"
763
764 case_start deep
765 echo edit > src/deep/two.rs
766 git commit --quiet -am deep
767 report="$(derive)"
768 expect "c-deep" "src/*.rs must not match across a path separator"
769
770 # A `**` between two segments matches no segment at all …
771 case_start nested-none
772 echo edit > a/b
773 git commit --quiet -am nested-none
774 report="$(derive)"
775 expect "c-nested" "a/**/b must match a/b"
776
777 # … and any number of them.
778 case_start nested-many
779 echo edit > a/x/y/b
780 git commit --quiet -am nested-many
781 report="$(derive)"
782 expect "c-nested" "a/**/b must match a/x/y/b"
783
784 # A rename counts on both sides: the class covering the old
785 # path is required as much as the one covering the new.
786 case_start renamed
787 git mv docs/moved.md notes/moved.md
788 git commit --quiet -m renamed
789 git diff --name-status -M "$base" HEAD | grep -q '^R' \
790 || { echo "policy-deriver: the rename case is not a rename" >&2; exit 1; }
791 report="$(derive)"
792 expect "c-docs c-notes c-tmpl" "a rename must count on both sides"
793
794 # A deleted path is still a changed path.
795 case_start deleted
796 git rm --quiet docs/gone.md
797 git commit --quiet -m deleted
798 report="$(derive)"
799 expect "c-docs c-tmpl" "a deletion must count"
800
801 # The form of the value is the mandatory bit: the floor's
802 # concrete `true` against the template's `bool | *true`.
803 grep -qE '^ c-docs +mandatory +docs$' <<<"$report"
804 grep -qE '^ c-tmpl +default +docs$' <<<"$report"
805
806 # A path no class covers takes the unclassified set, and says
807 # so by name.
808 case_start uncovered
809 echo edit > Makefile
810 git commit --quiet -am uncovered
811 report="$(derive)"
812 expect "c-uncovered" "an uncovered path must take the unclassified set"
813 grep -q '^classes matched: unclassified$' <<<"$report"
814 grep -q '^unclassified: 1 path(s) matched no class$' <<<"$report"
815 grep -q '^ Makefile$' <<<"$report"
816
817 touch $out
818 '';
819
820 module-eval =
821 if failedAssertions != [ ] then
822 throw "valley module-eval: failed assertions: ${lib.concatMapStringsSep "; " (a: a.message) failedAssertions}"
823 else if resticRenderedWithoutDeclaration then
824 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
825 else if busRenderedWithoutEnable then
826 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
827 else if
828 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
829 then
830 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
831 else
832 pkgs.runCommand "valley-module-eval"
833 {
834 initScript = host.config.systemd.services.valley-init.script;
835 sshdConfig = host.config.services.openssh.extraConfig;
836 resticService = host.config.systemd.units."restic-backups-valley.service".text;
837 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
838 passAsFile = [
839 "initScript"
840 "sshdConfig"
841 "resticService"
842 "resticTimer"
843 ];
844 }
845 ''
846 # The repo init list and mirror hook must be generated from
847 # the CUE export, and the git user's sshd Match block must
848 # be terminated so it cannot scope later config.
849 grep -q "the-valley" "$initScriptPath"
850 grep -q "valley-mirrors" "$initScriptPath"
851 grep -q "Match All" "$sshdConfigPath"
852
853 # The mirror publishes main and tags only — a heads glob
854 # would publish every topic branch awaiting review — with
855 # --prune for tag deletions and a sweep that unpublishes
856 # any other head (--prune cannot: it ignores non-glob
857 # refspecs). Never --mirror: it also deletes remote-only
858 # refs, and GitHub's read-only refs/pull/* fails every such
859 # push. Follow the hook chain from the init script to the
860 # rendered push script and pin the invocation there.
861 mirrorHook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-[^ ]*' "$initScriptPath" | head -n1)"
862 mirrorPush="$(grep -o '/nix/store/[^ ]*-valley-mirror-push-[^ ]*' "$mirrorHook" | head -n1)"
863 grep -q -- 'push --prune' "$mirrorPush"
864 grep -qF -- '+refs/heads/main:refs/heads/main' "$mirrorPush"
865 grep -qF -- '+refs/tags/*:refs/tags/*' "$mirrorPush"
866 grep -qF -- 'ls-remote --heads' "$mirrorPush"
867 grep -qF -- 'push "$url" --delete' "$mirrorPush"
868 if grep -qF -- '+refs/heads/*:refs/heads/*' "$mirrorPush"; then
869 echo "module-eval: mirror push regressed to publishing every head" >&2
870 exit 1
871 fi
872 if grep -q -- '--mirror' "$mirrorPush"; then
873 echo "module-eval: mirror push regressed to --mirror" >&2
874 exit 1
875 fi
876 # Deletions must never reach a namespace the mirror owns.
877 if grep -q 'refs/pull' "$mirrorPush"; then
878 echo "module-eval: mirror push must not name refs/pull/*" >&2
879 exit 1
880 fi
881
882 # The rendered restic units must back up the data directory
883 # to the consumer-supplied repository with the declared
884 # retention over a pinned host key, on the declared cadence.
885 grep -q "RESTIC_REPOSITORY_FILE=/run/agenix/valley-restic-repo" "$resticServicePath"
886 grep -q -- "--keep-daily 7 --keep-weekly 4 --keep-monthly 6" "$resticServicePath"
887 grep -q "UserKnownHostsFile=/var/lib/valley-backup/known_hosts" "$resticServicePath"
888 grep -q "BatchMode=yes" "$resticServicePath"
889 grep -q "OnCalendar=03:30" "$resticTimerPath"
890
891 # The backup paths render as a --files-from list: follow
892 # ExecStartPre to that list and pin the data directory.
893 preStart="$(sed -n 's/^ExecStartPre=//p' "$resticServicePath" | head -n1)"
894 staticPaths="$(grep -o '/nix/store/[^ ]*-staticPaths' "$preStart" | head -n1)"
895 grep -qx "/srv/git" "$staticPaths"
896 touch $out
897 '';
898
899 # What a mirror ends up holding, end to end and unmocked: a bare
900 # repo wired with the real rendered hooks, pushed to for real, and
901 # a second bare repo standing in for the mirror. The refspec is
902 # easy to get subtly wrong — --prune ignores the non-glob heads
903 # refspec, so pruning heads is the sweep's job — and only running
904 # git can tell. Relative mirror URLs (mirrorHost) resolve against
905 # the pushing repo, so the shipped scripts run with no
906 # substitution: this is exactly what a host executes.
907 mirror-e2e =
908 pkgs.runCommand "valley-mirror-e2e"
909 {
910 nativeBuildInputs = [ pkgs.git ];
911 initScript = mirrorHost.config.systemd.services.valley-init.script;
912 passAsFile = [ "initScript" ];
913 }
914 ''
915 export HOME="$TMPDIR"
916 export GIT_CONFIG_NOSYSTEM=1
917 git config --global user.name valley-check
918 git config --global user.email valley-check@localhost
919 git config --global init.defaultBranch main
920 cd "$TMPDIR"
921
922 wait_for() {
923 for _ in $(seq 1 150); do
924 "$@" >/dev/null 2>&1 && return 0
925 sleep 0.2
926 done
927 echo "mirror-e2e: timed out waiting for: $*" >&2
928 return 1
929 }
930 heads() { git -C mirror.git for-each-ref --format='%(refname)' refs/heads; }
931 tags() { git -C mirror.git for-each-ref --format='%(refname)' refs/tags; }
932 mirror_main_is() { [ "$(git -C mirror.git rev-parse main)" = "$tip" ]; }
933 only_main() { [ "$(heads)" = refs/heads/main ]; }
934
935 # A primary repo wired exactly as valley-init wires it, with
936 # the real store paths followed from the rendered init script.
937 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
938 mhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-mirror-pilot' "$initScriptPath" | head -n1)"
939 deadhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-dead-mirror' "$initScriptPath" | head -n1)"
940 test -x "$dispatch" && test -x "$mhook" && test -x "$deadhook"
941 wire() {
942 mkdir -p "$1/hooks/post-receive.d"
943 ln -s "$dispatch" "$1/hooks/post-receive"
944 ln -s "$2" "$1/hooks/post-receive.d/valley-mirrors"
945 }
946
947 # The mirror as it stands today: every head and tag of the
948 # primary, topic branches included. Seeded before the hook is
949 # wired, so nothing sweeps it out from under the setup.
950 git init --quiet --bare mirror-pilot.git
951 git init --quiet --bare mirror.git
952 git clone --quiet "$PWD/mirror-pilot.git" work
953 git -C work commit --quiet --allow-empty -m one
954 git -C work tag v1
955 git -C work tag doomed
956 for b in idea/one idea/two; do git -C work branch "$b"; done
957 git -C work push --quiet origin \
958 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
959 git -C mirror-pilot.git push --quiet ../mirror.git \
960 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
961 [ "$(heads | wc -l)" -eq 3 ]
962 wire mirror-pilot.git "$mhook"
963
964 # A real push to the primary — a topic branch alongside main,
965 # and a tag deleted. The hook replicates asynchronously, so
966 # wait on main's new tip before judging the rest.
967 git -C work commit --quiet --allow-empty -m two
968 git -C work tag -d doomed >/dev/null
969 git -C work branch idea/three
970 git -C work push --quiet --follow-tags origin main idea/three
971 git -C work push --quiet --delete origin doomed
972 tip="$(git -C work rev-parse HEAD)"
973 wait_for mirror_main_is
974
975 # main and the tags are published; nothing else is, and the
976 # topic branches that were on the mirror are gone. The sweep
977 # is a second push, so it converges just after main lands.
978 wait_for only_main
979 [ "$(tags)" = refs/tags/v1 ]
980
981 # A branch that appears on the mirror by any other route is
982 # unpublished on the next push.
983 git -C mirror.git branch sneaky main
984 git -C work commit --quiet --allow-empty -m three
985 git -C work push --quiet origin main
986 tip="$(git -C work rev-parse HEAD)"
987 wait_for mirror_main_is
988 wait_for only_main
989
990 # An unreachable mirror costs a log line, never the push: the
991 # hook must return promptly and the push must succeed.
992 git init --quiet --bare dead-mirror.git
993 wire dead-mirror.git "$deadhook"
994 git clone --quiet "$PWD/dead-mirror.git" deadwork
995 git -C deadwork commit --quiet --allow-empty -m one
996 timeout 60 git -C deadwork push --quiet origin main
997 [ "$(git -C dead-mirror.git rev-parse main)" = "$(git -C deadwork rev-parse HEAD)" ]
998
999 touch $out
1000 '';
1001
1002 # Phase 1's exit criteria, end to end and unmocked: a push to a
1003 # bare repo wired with the real rendered hooks produces a
1004 # ref-updated event on a real JetStream server within seconds,
1005 # visible in `valley tail`; replaying the repo's refs is
1006 # deterministic; and a dead bus never fails a push. The hook and
1007 # stream-init scripts are followed from the rendered unit scripts,
1008 # so the check exercises exactly what a host would run — only the
1009 # server invocation differs (the sandbox cannot write /srv), same
1010 # binary and flags, relocated storage.
1011 bus-e2e =
1012 pkgs.runCommand "valley-bus-e2e"
1013 {
1014 nativeBuildInputs = [
1015 pkgs.git
1016 pkgs.natscli
1017 pkgs.nats-server
1018 pkgs.jq
1019 pkgs.cue
1020 (valleyScriptFor pkgs)
1021 ];
1022 initScript = busHost.config.systemd.services.valley-init.script;
1023 busInitScript = busHost.config.systemd.services.valley-bus-init.script;
1024 passAsFile = [
1025 "initScript"
1026 "busInitScript"
1027 ];
1028 }
1029 ''
1030 export HOME="$TMPDIR"
1031 export NATS_URL=nats://127.0.0.1:4222
1032 export GIT_CONFIG_NOSYSTEM=1
1033 git config --global user.name valley-check
1034 git config --global user.email valley-check@localhost
1035 git config --global init.defaultBranch main
1036
1037 wait_for() {
1038 for _ in $(seq 1 150); do
1039 "$@" >/dev/null 2>&1 && return 0
1040 sleep 0.2
1041 done
1042 echo "bus-e2e: timed out waiting for: $*" >&2
1043 return 1
1044 }
1045
1046 nats-server --addr 127.0.0.1 --port 4222 --jetstream \
1047 --store_dir "$TMPDIR/js" &
1048 server_pid=$!
1049
1050 # The real stream-init script the module renders.
1051 bash -eu "$busInitScriptPath"
1052 nats stream info valley >/dev/null
1053
1054 # A bare repo wired exactly as valley-init wires it, with the
1055 # real store paths followed from the rendered init script.
1056 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
1057 bushook="$(grep -o '/nix/store/[^ ]*-valley-bus-events' "$initScriptPath" | head -n1)"
1058 test -x "$dispatch"
1059 test -x "$bushook"
1060 repo="$TMPDIR/events-pilot.git"
1061 git init --quiet --bare "$repo"
1062 mkdir -p "$repo/hooks/post-receive.d"
1063 ln -s "$dispatch" "$repo/hooks/post-receive"
1064 ln -s "$bushook" "$repo/hooks/post-receive.d/valley-bus"
1065
1066 git clone --quiet "$repo" "$TMPDIR/work"
1067 cd "$TMPDIR/work"
1068 echo one > file
1069 git add file
1070 git commit --quiet -m one
1071 git push --quiet origin main
1072 first="$(git rev-parse HEAD)"
1073 zeros="$(printf '%040d' 0)"
1074
1075 # Exit criterion 1: the event arrives within seconds, with a
1076 # payload that is exactly the git facts of the push …
1077 msgs_is() { [ "$(nats stream info valley --json | jq .state.messages)" -eq "$1" ]; }
1078 wait_for msgs_is 1
1079 got="$(nats stream get valley 1 --json)"
1080 [ "$(jq -r .subject <<<"$got")" = valley.git.events-pilot.ref-updated ]
1081 payload="$(jq -r .data <<<"$got" | base64 -d)"
1082 expected='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$first"'"}'
1083 [ "$payload" = "$expected" ]
1084
1085 # … valid against the shipped event schema.
1086 echo "$payload" > "$TMPDIR/payload.json"
1087 cue vet -d '#RefUpdated' ${./schema/events.cue} "$TMPDIR/payload.json"
1088
1089 # … and visible in `valley tail`. Subscribe first, then push.
1090 valley tail > "$TMPDIR/tail.out" 2>&1 &
1091 tail_pid=$!
1092 subscribed() { grep -q 'valley.>' "$TMPDIR/tail.out"; }
1093 wait_for subscribed
1094 echo two > file
1095 git commit --quiet -am two
1096 git push --quiet origin main
1097 second="$(git rev-parse HEAD)"
1098 wait_for msgs_is 2
1099 payload2="$(nats stream get valley 2 --json | jq -r .data | base64 -d)"
1100 expected2='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$first"'","new":"'"$second"'"}'
1101 [ "$payload2" = "$expected2" ]
1102 tail_saw() { grep -qF "$expected2" "$TMPDIR/tail.out"; }
1103 wait_for tail_saw
1104 kill "$tail_pid" 2>/dev/null || true
1105
1106 # Exit criterion 2: rebuilding the stream from the repo's
1107 # refs is deterministic — two replays from scratch produce
1108 # identical events, landing on the pushed tip with the
1109 # all-zero id as old.
1110 dump_stream() {
1111 local info first_seq last_seq i
1112 info="$(nats stream info valley --json)"
1113 first_seq="$(jq .state.first_seq <<<"$info")"
1114 last_seq="$(jq .state.last_seq <<<"$info")"
1115 for i in $(seq "$first_seq" "$last_seq"); do
1116 nats stream get valley "$i" --json | jq -c '{subject: .subject, data: .data}'
1117 done
1118 }
1119 nats stream purge valley --force >/dev/null
1120 valley replay "$repo"
1121 wait_for msgs_is 1
1122 run1="$(dump_stream)"
1123 nats stream purge valley --force >/dev/null
1124 valley replay "$repo"
1125 wait_for msgs_is 1
1126 run2="$(dump_stream)"
1127 [ "$run1" = "$run2" ]
1128 replayed="$(jq -r .data <<<"$run1" | base64 -d)"
1129 [ "$replayed" = '{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$second"'"}' ]
1130
1131 # A dead bus never blocks a push: the event is simply lost
1132 # (and rebuildable by replay).
1133 kill "$server_pid"
1134 wait "$server_pid" || true
1135 echo three > file
1136 git commit --quiet -am three
1137 git push --quiet origin main
1138
1139 touch $out
1140 '';
1141 }
1142 );
1143 };
1144}