ci: три статические проверки — coredns/nginx, listen.addr, .agent

#10 check-domains.py: DNS-запись в зоне zeroq.su без nginx-vhost'а.
Известные расхождения (снятые сервисы, coturn/netdata/uptime-kuma в
архиве) вынесены в .ci/tests/known-domain-gaps.txt; новые расхождения
роняют проверку. Обратное направление (vhost без локальной записи) —
информация: публичные домены резолвятся через публичный DNS.

#11 check-listen-addrs.py: listen.addr должен называть интерфейс, а не
сеть (192.168.1.0/24 — ошибка, 100.64.0.0 — tailscale-адрес, не сеть).
Рядом self-test: проверка, которая не может упасть, — не проверка.

#12 check-agent-consistency.py: AGENTS.md, manifest.md, manifest.json и
decisions/index.json не должны противоречить друг другу. Сейчас
противоречили: в сводке AGENTS.md значилась закрытая T52 и не значились
T58/T60/T61, а manifest.md утверждал, что T38+ не внесены в JSON.

Все три — python без зависимостей, запускаются из .ci/checks.sh, который
и CI, и pre-commit вызывают одинаково.
This commit is contained in:
oqyude committed 2026-11-15 06:34:10 +03:00
1 parent b9f533be4f
commit 86b58fc576
6 files changed
+566 -1

No files matched your search

+65 -1
View File
@@ -18,19 +18,34 @@
# 2026-10-20, R1.5/ADR-0007) # 2026-10-20, R1.5/ADR-0007)
# #8 every import reference resolves (no dangling imports) — added 2026-10-24 # #8 every import reference resolves (no dangling imports) — added 2026-10-24
# #9 .agent JSON artefacts validate against their schemas — added 2026-10-25 # #9 .agent JSON artefacts validate against their schemas — added 2026-10-25
# #10 CoreDNS records and nginx vhosts agree — added 2026-11-15
# #11 `listen.addr` names an interface, not a network — added 2026-11-15
# #12 AGENTS.md / manifest.md / manifest.json / decisions index agree
# — added 2026-11-15
#
# Every python check below is also a standalone script, so it can be run
# directly: `python3 .ci/tests/<script>.py .`. They deliberately are NOT
# exposed as `checks.*` flake outputs: on the pinned nixpkgs, `nix flake
# check` fails with "'outPath' is not a valid system type" on any
# derivation output built from it (see the note in flake.nix).
# #
# Not yet implemented (candidates from analysis-report.md §5): # Not yet implemented (candidates from analysis-report.md §5):
# #3 coredns domains ↔ nginx vhosts bidirectional match # #3 coredns domains ↔ nginx vhosts bidirectional match
# (PARTIALLY implemented as #10: the "DNS record without a vhost"
# direction is enforced; the reverse direction is informational)
# #4 mkStorageGuard consumers have an existing External dir # #4 mkStorageGuard consumers have an existing External dir
# (lib/xlib/helpers.nix — note the helper is mkStorageGuard, not # (lib/xlib/helpers.nix — note the helper is mkStorageGuard, not
# mkServiceStorage; the two names referred to the same idea historically. # mkServiceStorage; the two names referred to the same idea historically.
# The helper now returns a `unitConfig` fragment, and vds hosts are # The helper now returns a `unitConfig` fragment, and vds hosts are
# excluded: otreca has no External, its 3x-ui data lives on the root fs) # excluded: otreca has no External, its 3x-ui data lives on the root fs.
# The runtime half lives in .ci/verify/runtime-drift.sh, which needs a
# live host and therefore cannot run in CI)
# #5 nftables policy (T3 CLOSED 2026-10-25: no check needed — the generated # #5 nftables policy (T3 CLOSED 2026-10-25: no check needed — the generated
# `inet nixos-fw` chain already has `policy drop`; the hand-written # `inet nixos-fw` chain already has `policy drop`; the hand-written
# `inet filter` chain is policy accept on purpose and must NOT get a drop, # `inet filter` chain is policy accept on purpose and must NOT get a drop,
# because a drop in any base chain is final and would blackhole the VDS) # because a drop in any base chain is final and would blackhole the VDS)
# #6 listen.addr is interface, not network (e.g. 0.0.0.0 is OK, 192.168.0.0/24 is not) # #6 listen.addr is interface, not network (e.g. 0.0.0.0 is OK, 192.168.0.0/24 is not)
# — IMPLEMENTED as #11
set -euo pipefail set -euo pipefail
@@ -186,12 +201,61 @@ check_metadata_schemas() {
fi fi
} }
check_domains() {
echo "Check #10: CoreDNS records and nginx vhosts agree ..."
if ! command -v python3 >/dev/null 2>&1; then
echo " SKIP: python3 not in PATH"
return 0
fi
if python3 .ci/tests/check-domains.py . ; then
report 0 "coredns/nginx domains"
else
report 1 "coredns/nginx domains"
fi
}
check_listen_addrs() {
echo "Check #11: listen.addr names an interface, not a network ..."
if ! command -v python3 >/dev/null 2>&1; then
echo " SKIP: python3 not in PATH"
return 0
fi
# The self-test first: it proves the classifier still rejects the cases it
# is supposed to reject. A check that cannot fail is not a check.
if ! python3 .ci/tests/self-test-listen-addrs.py; then
echo " FAIL: the listen.addr classifier no longer behaves as expected" >&2
report 1 "listen.addr classifier self-test"
return 0
fi
if python3 .ci/tests/check-listen-addrs.py . ; then
report 0 "listen.addr values"
else
report 1 "listen.addr values"
fi
}
check_agent_consistency() {
echo "Check #12: AGENTS.md / manifest.md / manifest.json / decisions index agree ..."
if ! command -v python3 >/dev/null 2>&1; then
echo " SKIP: python3 not in PATH"
return 0
fi
if python3 .ci/tests/check-agent-consistency.py . ; then
report 0 "agent metadata consistency"
else
report 1 "agent metadata consistency"
fi
}
echo "=== nixos flake checks ===" echo "=== nixos flake checks ==="
check_nix_flake_check check_nix_flake_check
check_sops_path_regex check_sops_path_regex
check_no_latest_images check_no_latest_images
check_import_graph check_import_graph
check_metadata_schemas check_metadata_schemas
check_domains
check_listen_addrs
check_agent_consistency
echo "===" echo "==="
echo "PASS: $PASS FAIL: $FAIL" echo "PASS: $PASS FAIL: $FAIL"
if [ "$FAIL" -gt 0 ]; then if [ "$FAIL" -gt 0 ]; then
+197
View File
@@ -0,0 +1,197 @@
#!/usr/bin/env python3
"""Consistency between the three places the repo talks about tasks.
The repo tracks tasks in three places and they drift:
* `.agent/tasks/manifest.json` — the machine-readable source of truth
(status per task id).
* `.agent/tasks/manifest.md` — the human-readable registry of the T38+
series, with a status column.
* `AGENTS.md` — the entry point for the next agent, with a
one-line summary of which tasks are still open.
plus `.agent/decisions/index.json`, which indexes the ADR files on disk.
Nothing enforces agreement, so a task can be "done" in one file and "pending"
in another — and the next agent reads whichever it happens to open. This check
compares them and fails on a contradiction.
Rules
-----
1. AGENTS.md's "Открытые задачи" line must list exactly the tasks that
`manifest.json` does not mark completed (pending + in_progress).
2. For every task present in both `manifest.json` and the `manifest.md`
table: "done" in one and not-done in the other is a contradiction.
A task in `manifest.json` but missing from the `manifest.md` table is
reported as drift (the md is a registry, not a mirror — but a task that
nobody can find is a task that will be re-discovered by hand).
3. Every ADR in `decisions/index.json` must have its file on disk, and every
ADR file on disk must be indexed.
Usage: python3 .ci/tests/check-agent-consistency.py [repo-root]
Exit: 0 = consistent, 1 = at least one contradiction.
"""
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
MANIFEST_JSON = Path(".agent/tasks/manifest.json")
MANIFEST_MD = Path(".agent/tasks/manifest.md")
AGENTS_MD = Path("AGENTS.md")
DECISIONS_INDEX = Path(".agent/decisions/index.json")
DECISIONS_DIR = Path(".agent/decisions")
DONE_STATES = {"completed", "done", "closed"}
ID_RE = re.compile(r"T(\d+)")
def expand_ids(text: str) -> set[int]:
"""T10, T28-T31, T49–T56 -> {10, 28, 29, 30, 31, 49, ...}."""
found: set[int] = set()
for match in re.finditer(r"T(\d+)\s*(?:[-–—]\s*T?(\d+))?", text):
start = int(match.group(1))
end = int(match.group(2)) if match.group(2) else start
if end < start:
start, end = end, start
found.update(range(start, end + 1))
return found
def md_table_statuses(text: str) -> dict[int, str]:
"""Task id -> raw status cell from the markdown table."""
statuses: dict[int, str] = {}
for line in text.split("\n"):
if not line.startswith("|"):
continue
cells = [cell.strip() for cell in line.strip("|").split("|")]
if len(cells) < 5:
continue
match = re.fullmatch(r"\*?\*?T(\d+)\*?\*?", cells[0])
if not match:
continue
statuses[int(match.group(1))] = cells[4]
return statuses
def main() -> int:
root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
problems: list[str] = []
manifest_path = root / MANIFEST_JSON
if not manifest_path.exists():
print(f" MISSING: {MANIFEST_JSON}")
return 1
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
tasks = {int(ID_RE.fullmatch(t["id"]).group(1)): t for t in manifest["tasks"] if ID_RE.fullmatch(t["id"])}
open_ids = {tid for tid, t in tasks.items() if t.get("status") not in DONE_STATES}
# 1. AGENTS.md summary line.
agents_path = root / AGENTS_MD
if agents_path.exists():
agents_text = agents_path.read_text(encoding="utf-8")
summary = None
agents_lines = agents_text.split("\n")
for index, line in enumerate(agents_lines):
if "Открытые задачи" in line:
# The summary may wrap over several lines — take the whole
# paragraph, otherwise the wrapped task ids are invisible to
# the comparison.
paragraph = [line]
for follow_up in agents_lines[index + 1 :]:
if not follow_up.strip():
break
paragraph.append(follow_up)
summary = "\n".join(paragraph)
break
if summary is None:
problems.append("AGENTS.md: no 'Открытые задачи' line — the task summary is missing")
else:
listed = expand_ids(summary)
missing = sorted(open_ids - listed)
extra = sorted(tid for tid in listed - open_ids if tid in tasks)
unknown = sorted(tid for tid in listed - set(tasks))
if missing:
problems.append(
f"AGENTS.md: open task(s) not mentioned in the summary line: "
+ ", ".join(f"T{tid}" for tid in missing)
)
if extra:
problems.append(
f"AGENTS.md: summary line lists task(s) that are already completed: "
+ ", ".join(f"T{tid}" for tid in extra)
)
if unknown:
problems.append(
"AGENTS.md: summary line lists unknown task(s): "
+ ", ".join(f"T{tid}" for tid in unknown)
)
else:
problems.append(f"MISSING: {AGENTS_MD}")
# 2. manifest.md table vs manifest.json.
md_path = root / MANIFEST_MD
if md_path.exists():
md_statuses = md_table_statuses(md_path.read_text(encoding="utf-8"))
for tid, cell in sorted(md_statuses.items()):
if tid not in tasks:
problems.append(f"manifest.md: T{tid} is not in manifest.json")
continue
md_done = "done" in cell.lower()
json_done = tasks[tid].get("status") in DONE_STATES
if md_done != json_done:
problems.append(
f"manifest.md T{tid}: table says '{cell}' but manifest.json says "
f"'{tasks[tid].get('status')}'"
)
listed_in_md = set(md_statuses)
missing_in_md = sorted(tid for tid in tasks if tid >= 38 and tid not in listed_in_md)
if missing_in_md:
problems.append(
"manifest.md: task(s) from the T38+ series are not in the table: "
+ ", ".join(f"T{tid}" for tid in missing_in_md)
)
else:
problems.append(f"MISSING: {MANIFEST_MD}")
# 3. ADR index vs ADR files.
index_path = root / DECISIONS_INDEX
if index_path.exists():
index = json.loads(index_path.read_text(encoding="utf-8"))
indexed_files = set()
for decision in index.get("decisions", []):
rel = decision.get("file")
if not rel:
problems.append(f"decisions/index.json: {decision.get('id')} has no file")
continue
indexed_files.add(Path(rel).name)
if not (root / rel).exists():
problems.append(f"decisions/index.json: {decision.get('id')} points at a missing file {rel}")
on_disk = {
p.name
for p in (root / DECISIONS_DIR).glob("*.md")
if re.match(r"^\d{4}-", p.name)
}
for name in sorted(on_disk - indexed_files):
problems.append(f"decisions: {name} exists on disk but is not in decisions/index.json")
else:
problems.append(f"MISSING: {DECISIONS_INDEX}")
print(
f"agent-consistency: {len(tasks)} task(s), {len(open_ids)} open, "
f"{len(md_statuses) if md_path.exists() else 0} row(s) in the manifest.md table"
)
if problems:
print("agent-consistency: INCONSISTENCIES", file=sys.stderr)
for problem in problems:
print(f" {problem}", file=sys.stderr)
return 1
print("agent-consistency: OK")
return 0
if __name__ == "__main__":
sys.exit(main())
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""CoreDNS zone ↔ nginx vhost consistency check.
The repo serves the `zeroq.su` zone from CoreDNS (`modules/server/coredns.nix`)
and terminates the matching vhosts in nginx (`modules/server/nginx.nix`,
`modules/vds/nginx.nix`). Both lists are maintained by hand, so they drift:
a service gets removed from nginx while its DNS record stays behind, and the
name keeps resolving to a vhost that answers 502 (or nothing).
This check finds records that point at a vhost which no longer exists.
Policy
------
* A record in the `zeroq.su` zone with no vhost is a **gap**.
* Gaps that are already known are listed in `.ci/tests/known-domain-gaps.txt`
(one name per line). A known gap is reported as a warning; a NEW gap fails
the check. That way the check never blocks a pipeline on pre-existing debt,
but any future removal of a vhost without touching DNS is caught.
* `home.arpa` is a LAN-only zone: those names intentionally have no public
vhost, so they are reported as information, not as gaps.
* A vhost without a local DNS record is normal — public domains resolve
through public DNS and wildcard records cover the `*.opencodes.zeroq.su`
subdomains. Reported as information only.
Usage: python3 .ci/tests/check-domains.py [repo-root]
Exit: 0 = no new gaps, 1 = at least one new gap.
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
COREDNS = Path("modules/server/coredns.nix")
NGINX_FILES = [
Path("modules/server/nginx.nix"),
Path("modules/vds/nginx.nix"),
]
KNOWN_GAPS = Path(".ci/tests/known-domain-gaps.txt")
ZONE_RE = re.compile(r"^\s*([\w.-]+):\d+\s*\{")
# The address is either a literal IP or an interpolation from the fleet
# registry (`${xlib.net.hosts.sapphira.lan}`) — both are one token followed
# by the record name.
RECORD_RE = re.compile(r"^\s*(?:\$\{[^}]+\}|\d+\.\d+\.\d+\.\d+)\s+([\w.-]+)\s*$")
DOMAIN_LITERAL_RE = re.compile(r'"([a-z0-9][a-z0-9.-]*\.(?:zeroq\.su|home\.arpa))"')
def code_lines(text: str) -> list[str]:
"""Drop full-line comments. Inline comments are kept on purpose: a domain
inside a comment is a claim about the world, but a commented-out vhost
block is code the reader will mistake for live code."""
return [line for line in text.split("\n") if not line.strip().startswith("#")]
def parse_zone(text: str) -> dict[str, list[str]]:
"""zone name -> list of record names."""
zones: dict[str, list[str]] = {}
current = None
for line in code_lines(text):
zone = ZONE_RE.match(line)
if zone:
current = zone.group(1)
zones.setdefault(current, [])
continue
if current is None:
continue
record = RECORD_RE.match(line)
if record:
zones[current].append(record.group(1))
return zones
def parse_vhosts(paths: list[Path], root: Path) -> set[str]:
names: set[str] = set()
for path in paths:
full = root / path
if not full.exists():
continue
for line in code_lines(full.read_text(encoding="utf-8", errors="ignore")):
for match in DOMAIN_LITERAL_RE.finditer(line):
names.add(match.group(1))
return names
def known_gaps(root: Path) -> set[str]:
full = root / KNOWN_GAPS
if not full.exists():
return set()
out = set()
for line in full.read_text(encoding="utf-8", errors="ignore").split("\n"):
line = line.split("#", 1)[0].strip()
if line:
out.add(line)
return out
def main() -> int:
root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
coredns = root / COREDNS
if not coredns.exists():
print(f" MISSING: {COREDNS.relative_to(root)}")
return 1
zones = parse_zone(coredns.read_text(encoding="utf-8", errors="ignore"))
vhosts = parse_vhosts(NGINX_FILES, root)
allowed = known_gaps(root)
public_zone = "zeroq.su"
records = set(zones.get(public_zone, []))
lan_records = set(zones.get("home.arpa", []))
gaps = sorted(records - vhosts)
new_gaps = [name for name in gaps if name not in allowed]
stale_allowed = [name for name in gaps if name in allowed]
print(f"domains: {len(records)} record(s) in {public_zone}, {len(vhosts)} vhost(s) known")
if stale_allowed:
print(f" NOTE: {len(stale_allowed)} known gap(s) (recorded in {KNOWN_GAPS}):")
for name in stale_allowed:
print(f" - {name}")
if lan_records:
print(f" INFO: {len(lan_records)} LAN-only record(s) in home.arpa have no public vhost (expected)")
vhost_only = sorted(vhosts - records - lan_records)
if vhost_only:
print(f" INFO: {len(vhost_only)} vhost(s) without a local DNS record (public DNS / wildcard):")
for name in vhost_only:
print(f" - {name}")
if new_gaps:
print(f"domains: NEW GAPS — {len(new_gaps)} DNS record(s) without a vhost", file=sys.stderr)
for name in new_gaps:
print(f" {name}", file=sys.stderr)
print(
" Either restore the vhost, remove the DNS record from "
f"{COREDNS}, or add the name to {KNOWN_GAPS}",
file=sys.stderr,
)
return 1
print("domains: OK (no new gaps)")
return 0
if __name__ == "__main__":
sys.exit(main())
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""`listen.addr` must name an interface, not a network.
nginx's `listen <addr>:<port>` takes the address of an interface. A network
with a prefix length (`192.168.1.0/24`) or a multicast/broadcast address is
not an interface address: nginx either refuses to start or, worse, binds
nothing while the config looks fine. The same value in `allowedTCPPorts` /
`allowedUDPPorts` is a different thing entirely (a port, not an address), so
only `addr =` is inspected.
Note what is deliberately NOT flagged: an address that merely *looks* like a
network prefix (`100.64.0.0` is the Tailscale address of sapphira, not the
`100.64.0.0/10` network). Only an explicit prefix length is an error.
Usage: python3 .ci/tests/check-listen-addrs.py [repo-root]
Exit: 0 = every `addr` is an interface address, 1 otherwise.
"""
from __future__ import annotations
import os
import re
import sys
from pathlib import Path
SKIP_DIRS = {".git", "archive", ".temp", ".omo", ".metaagent-director", "result"}
ADDR_RE = re.compile(r'\baddr\s*=\s*"([^"]+)"')
IPV4_RE = re.compile(r"^\d{1,3}(\.\d{1,3}){3}$")
def nix_files(root: Path) -> list[Path]:
out = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.startswith("."))
for name in filenames:
if name.endswith(".nix"):
out.append(Path(dirpath) / name)
return sorted(out)
def classify(addr: str) -> str | None:
"""Return an error message, or None when the address is fine."""
if "/" in addr:
return "network prefix — listen takes an interface address, not a network"
host = addr
if host.startswith("["):
host = host.split("]", 1)[0].lstrip("[")
elif host.count(":") == 1:
host = host.split(":", 1)[0]
if IPV4_RE.match(host):
octets = [int(part) for part in host.split(".")]
if octets[0] >= 224 and octets[0] <= 239:
return "multicast address"
if octets == [255, 255, 255, 255]:
return "broadcast address"
# `0.0.0.0` is explicitly allowed: nginx treats it as "every
# interface", which is a legitimate listen target (see the rule in
# .ci/checks.sh: "0.0.0.0 is OK, 192.168.0.0/24 is not").
return None
def main() -> int:
root = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
problems = []
for path in nix_files(root):
rel = path.relative_to(root)
for lineno, line in enumerate(path.read_text(encoding="utf-8", errors="ignore").split("\n"), 1):
if line.lstrip().startswith("#"):
continue
for match in ADDR_RE.finditer(line):
addr = match.group(1)
problem = classify(addr)
if problem:
problems.append((rel.as_posix(), lineno, addr, problem))
if not problems:
print("listen-addrs: OK (every addr is an interface address)")
return 0
print("listen-addrs: INVALID listen.addr", file=sys.stderr)
for rel, lineno, addr, problem in problems:
print(f" {rel}:{lineno} addr = \"{addr}\" — {problem}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
+34
View File
@@ -0,0 +1,34 @@
# Known CoreDNS→nginx gaps (pre-existing debt, not a regression).
#
# A name listed here has a DNS record in the `zeroq.su` zone but no nginx
# vhost. The check `.ci/tests/check-domains.py` treats these as warnings and
# fails only when a NEW gap appears — so removing a vhost without touching
# CoreDNS is caught, while this pre-existing debt does not block the pipeline.
#
# Format: one name per line, `#` starts a comment.
# The CoreDNS server's own name. Served by coredns on :53, never by nginx.
dns.zeroq.su
# netdata/glances: disabled 2026-10-30 (modules/server/default.nix). The DNS
# record was deliberately left behind — it points at a closed port.
glances.zeroq.su
# uptime-kuma: disabled 2026-10-30 (the unit timed out). Vhost removed,
# DNS record left behind.
kuma.zeroq.su
# Open WebUI: container removed 2026-10-30 (4.69 GiB image, the container
# kept crashing). Vhost commented out in modules/server/nginx.nix:494.
open.zeroq.su
# Syncthing is deployed (modules/server/syncthing.nix) but has never been
# published through nginx — its web UI is reached directly on its port.
syncthing.zeroq.su
# No Matrix/talk service exists in this repo; the record is a leftover.
talk.zeroq.su
# TURN server: the coturn module lives in archive/server-modules/ (disabled).
# modules/server/nextcloud.nix:50 still points the client at turn.zeroq.su.
turn.zeroq.su
+33
View File
@@ -0,0 +1,33 @@
import importlib.util
import sys
from pathlib import Path
# Resolve the module next to this script, so the self-test works from any
# working directory (the CI script runs it from the repo root, a developer
# may run it from anywhere).
TARGET = Path(__file__).resolve().parent / "check-listen-addrs.py"
spec = importlib.util.spec_from_file_location("check_listen_addrs", TARGET)
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
cases = {
"192.168.1.0/24": "bad",
"0.0.0.0": "ok",
"127.0.0.1": "ok",
"100.64.0.0": "ok",
"127.0.0.1:9101": "ok",
"224.0.0.1": "bad",
"255.255.255.255": "bad",
"[::1]:443": "ok",
}
bad = 0
for addr, expected in cases.items():
problem = m.classify(addr)
verdict = "bad" if problem else "ok"
status = "OK " if verdict == expected else "FAIL"
if verdict != expected:
bad = 1
print(f"{status} {addr:20} expected={expected} got={verdict} {problem or ''}")
sys.exit(bad)