frontera-runner 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,512 @@
1
+ """One receipt: canonical bytes, one seal, and the identities it must carry to be checkable.
2
+
3
+ A composite report is only worth publishing if a reader can tell which code produced each of its
4
+ rows. So every executor travels with its version, the commit of its repository and a digest of
5
+ the package that ran, and the whole body is sealed with `sha256` over its own canonical form.
6
+ There is no timestamp anywhere: two runs over one tree must produce the same bytes, and a clock
7
+ in the receipt would make that false while looking harmless.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import platform
16
+ import subprocess
17
+ import sys
18
+ from collections import Counter
19
+
20
+ from . import __version__
21
+ from . import instrumentos as inst
22
+ from .runner import (APLICABLE, NO_APLICABLE, NO_EJECUTADO, NO_MEDIDO, PAQUETE, correr,
23
+ sujeto_git)
24
+
25
+ ESQUEMA = 2
26
+ NOMBRE = "frontera-runner"
27
+
28
+ #: Fields of an executor that say *which bytes* produced its rows. A delta across a change in any
29
+ #: of them is not attributable to the pull request, and the comparison says so instead of guessing.
30
+ IDENTIDAD_DE_EJECUTOR = ("version", "huella", "procedencia")
31
+
32
+ #: Every note a delta row can carry, and the four things a note is worth: which counter in the
33
+ #: summary it raises, which exit code it earns, where it sits in the published precedence, and
34
+ #: the paragraph a human reads in the pull-request comment. This table is the only place those
35
+ #: live; nothing downstream may restate any of them.
36
+ #:
37
+ #: It exists because the pair used to live in three -- the branch that wrote the note, the loop
38
+ #: that counted it, and the function that turned the count into an exit code -- and one note was
39
+ #: in none: `SIN_MEDICION_EN_NINGUNA_DE_LAS_DOS` was written, read by nobody, and a delta whose
40
+ #: only row carried it came out `0 SIN_REGRESION`. Worse, the early return for an unreadable
41
+ #: receipt built its summary from a hand-written list that already lagged the real one by a field.
42
+ #: A note is a promise that something reads it; `_nota` is where the promise is kept, and `orden`
43
+ #: is the published precedence among the codes that tie. A rank may hold two notes only if they
44
+ #: publish the same pair -- the tie is them being the same answer under two names, not a race that
45
+ #: `sorted` settles by the order the dict literal happens to be written in.
46
+ #:
47
+ #: `detalle` is the same promise kept for the reader who only sees the comment: it used to be an
48
+ #: `if fila["nota"] == ...` in `render.markdown_diff`, so a note added here was counted and gated
49
+ #: and still arrived as a bare row with no explanation. `None` means the note needs no paragraph;
50
+ #: a row that omits the key has not said which, and `validar_notas` refuses it at import.
51
+ #:
52
+ #: `rc_estricto` is the same note read by a frozen path: a base that never answered is not a
53
+ #: statement about the pull request, and a gate on a frozen route would rather stop than guess.
54
+ #: Endurecer es la unica direccion: `rc_estricto >= rc` y nunca `0`, o el flag que existe para
55
+ #: quitar verdes estaria firmando uno.
56
+ NOTAS = {
57
+ "PERDIDA_DE_MEDICION": {"contador": "perdidas_de_medicion",
58
+ "veredicto": "PERDIDA_DE_MEDICION", "rc": 2, "orden": 0,
59
+ "detalle": None},
60
+ "MEDICION_NO_HECHA": {"contador": "mediciones_no_hechas", "veredicto": "MEDICION_NO_HECHA",
61
+ "rc": 2, "orden": 1,
62
+ "detalle": "- uno de los dos lados no respondió -- agotamiento, caída "
63
+ "o salida ilegible: un hueco no es una ausencia, y no es "
64
+ "verde"},
65
+ "IDENTIDAD_DEL_EJECUTOR_DISTINTA": {"contador": "no_atribuibles",
66
+ "veredicto": "DELTA_NO_ATRIBUIBLE", "rc": 2, "orden": 2,
67
+ "detalle": None},
68
+ "INSTRUMENTO_SOLO_EN_UNA_DE_LAS_DOS": {"contador": "no_atribuibles",
69
+ "veredicto": "DELTA_NO_ATRIBUIBLE", "rc": 2, "orden": 2,
70
+ "detalle": None},
71
+ "SUPERFICIE_NUEVA": {"contador": "superficies_nuevas", "veredicto": None, "rc": 0, "orden": 3,
72
+ "detalle": "- base no tenía superficie que medir y head la trae: "
73
+ "`{nuevos}` hallazgo(s) sobre superficie que este cambio "
74
+ "crea, contados como regresión"},
75
+ "SIN_BASE_MEDIDA": {"contador": "ganancias_de_medicion", "veredicto": None, "rc": 0,
76
+ "orden": 4, "rc_estricto": 2, "veredicto_estricto": "SIN_BASE_MEDIDA",
77
+ "detalle": None},
78
+ "SIN_MEDICION_EN_NINGUNA_DE_LAS_DOS": {"contador": None, "veredicto": None, "rc": 0,
79
+ "orden": 5, "detalle": None},
80
+ }
81
+
82
+ #: What every row of `NOTAS` must say, and what it may say additionally. A row missing one of the
83
+ #: first is a promise nobody finished making; a row carrying anything else is a field no reader
84
+ #: will ever look at, which is the same defect seen from the other side.
85
+ COLUMNAS_DE_NOTA = ("contador", "veredicto", "rc", "orden", "detalle")
86
+ #: What a note publishes to the caller. Two notes at the same `orden` have to agree on all four or
87
+ #: the precedence between them is the insertion order of this file and nobody published it.
88
+ COLUMNAS_PUBLICADAS = ("rc", "veredicto", "rc_estricto", "veredicto_estricto")
89
+ COLUMNAS_OPCIONALES = ("rc_estricto", "veredicto_estricto")
90
+
91
+
92
+ def validar_notas(tabla: dict | None = None) -> dict:
93
+ """Refuse a catalogue row that is not a complete descriptor, at import and not at read time.
94
+
95
+ A note is worth exactly four things and it is only a note if all four are declared. The cost of
96
+ checking is one pass over seven rows at import; the cost of not checking is a note that is
97
+ counted and gated but arrives to the reader unexplained -- which is how the previous version of
98
+ this file lost the paragraph for every note whose prose lived in `render`.
99
+
100
+ A second pass refuses a tie in `orden` that is not a genuine equality: `salida_global` walks the
101
+ table sorted by rank and returns the first note with a non-zero counter, so two notes sharing a
102
+ rank are spent in the order this file lists them. While both publish the same pair that order is
103
+ invisible; the day one of them gains a distinct `veredicto` or `rc_estricto`, the winner is
104
+ decided by a dict literal and no test would say so.
105
+
106
+ And a row may not declare a strict rank that loosens: `--estricto-base` exists so a frozen route
107
+ stops where a normal route would continue, so `rc_estricto` is at least `rc` and never `0`. A
108
+ strict answer of `0` is the identity, and a strict answer below the normal one is the flag
109
+ signing the green it was added to withdraw.
110
+ """
111
+ tabla = NOTAS if tabla is None else tabla
112
+ for nota, lectura_de_la_nota in tabla.items():
113
+ faltan = [columna for columna in COLUMNAS_DE_NOTA if columna not in lectura_de_la_nota]
114
+ sobran = [columna for columna in lectura_de_la_nota
115
+ if columna not in COLUMNAS_DE_NOTA + COLUMNAS_OPCIONALES]
116
+ sueltas = (("rc_estricto" in lectura_de_la_nota)
117
+ != ("veredicto_estricto" in lectura_de_la_nota))
118
+ if faltan or sobran or sueltas:
119
+ raise KeyError(f"nota incompleta en NOTAS: {nota!r} "
120
+ f"(faltan={faltan}, sobran={sobran}, estricto_medio={sueltas})")
121
+ normal = lectura_de_la_nota["rc"]
122
+ estricto = lectura_de_la_nota.get("rc_estricto")
123
+ if estricto is not None and (estricto <= 0 or estricto < normal):
124
+ raise KeyError(f"modo estricto que afloja en NOTAS: {nota!r} publica rc={normal!r} y "
125
+ f"rc_estricto={estricto!r}; un rango estricto endurece (>= rc) y "
126
+ f"nunca es 0")
127
+ rangos = {}
128
+ for nota, lectura_de_la_nota in tabla.items():
129
+ rango = lectura_de_la_nota["orden"]
130
+ publica = tuple(lectura_de_la_nota.get(columna) for columna in COLUMNAS_PUBLICADAS)
131
+ previa = rangos.setdefault(rango, (nota, publica))
132
+ if previa[1] != publica:
133
+ raise KeyError(f"empate sin precedencia en NOTAS: {previa[0]!r} y {nota!r} comparten "
134
+ f"orden={rango!r} y publican distinto: {previa[1]} != {publica}")
135
+ return tabla
136
+
137
+
138
+ def lectura(nota: str) -> dict:
139
+ """The descriptor of one note. The single reader every consumer goes through."""
140
+ try:
141
+ return NOTAS[nota]
142
+ except KeyError:
143
+ raise KeyError(f"nota sin lector en NOTAS: {nota!r}") from None
144
+
145
+
146
+ def _nota(fila: dict, nota: str) -> dict:
147
+ """Write a note onto a row, refusing any note that has no descriptor in the table.
148
+
149
+ A note invented without a row in `NOTAS` fails here, in the branch that invented it, instead of
150
+ travelling as a string nobody counts. This is the mechanism; the test that walks the whole
151
+ catalogue is only its witness.
152
+ """
153
+ lectura(nota)
154
+ fila["nota"] = nota
155
+ return fila
156
+
157
+
158
+ validar_notas()
159
+
160
+
161
+ def _resumen_vacio() -> dict:
162
+ """A summary with every counter the table declares, at zero. Never a hand-written list."""
163
+ resumen = {"nuevos": 0, "resueltos": 0}
164
+ for lectura in NOTAS.values():
165
+ if lectura["contador"]:
166
+ resumen[lectura["contador"]] = 0
167
+ return resumen
168
+
169
+
170
+ def canonico(datos) -> str:
171
+ """The one serialisation: sorted keys, no ASCII escaping, one trailing newline."""
172
+ return json.dumps(datos, sort_keys=True, ensure_ascii=False, indent=2) + "\n"
173
+
174
+
175
+ def sha256_de(datos: bytes) -> str:
176
+ return "sha256:" + hashlib.sha256(datos).hexdigest()
177
+
178
+
179
+ def interprete() -> dict:
180
+ """What ran the code. Declared because a digest of the bytes does not name the runtime."""
181
+ return {"implementacion": platform.python_implementation(),
182
+ "version": platform.python_version(),
183
+ "ejecutable": os.path.basename(sys.executable)}
184
+
185
+
186
+ def _generador() -> dict:
187
+ aqui = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
188
+ return {
189
+ "nombre": NOMBRE,
190
+ "version": __version__,
191
+ "commit": inst.commit_de(aqui),
192
+ "huella": inst.huella_de(aqui, "frontera_runner"),
193
+ }
194
+
195
+
196
+ def _triaje_minimo(triaje: dict) -> dict:
197
+ return {nombre: {"estado": t["estado"], "razon": t["razon"], "insumos": t["insumos"]}
198
+ for nombre, t in sorted(triaje.items())}
199
+
200
+
201
+ def _denominador(ejecutores: dict) -> dict:
202
+ cuenta = {APLICABLE: 0, NO_APLICABLE: 0, NO_MEDIDO: 0, NO_EJECUTADO: 0}
203
+ con = sin = 0
204
+ for registro in ejecutores.values():
205
+ cuenta[registro["estado"]] += 1
206
+ if registro["estado"] == APLICABLE:
207
+ if registro["hallazgos"]:
208
+ con += 1
209
+ else:
210
+ sin += 1
211
+ return {
212
+ "instrumentos": len(ejecutores),
213
+ "aplicables": cuenta[APLICABLE],
214
+ "con_hallazgos": con,
215
+ "sin_hallazgos": sin,
216
+ "no_aplicables": cuenta[NO_APLICABLE],
217
+ "no_medidos": cuenta[NO_MEDIDO],
218
+ "no_ejecutados": cuenta[NO_EJECUTADO],
219
+ }
220
+
221
+
222
+ def leyes(cuerpo: dict) -> dict:
223
+ """Identities the receipt must satisfy about itself. A false one is a defect, not a footnote."""
224
+ ejecutores = cuerpo["ejecutores"]
225
+ cuenta = _denominador(ejecutores)
226
+ particion = (cuenta["aplicables"] + cuenta["no_aplicables"] + cuenta["no_medidos"]
227
+ + cuenta["no_ejecutados"])
228
+ # An installed package has no repository to read a commit from, so the commit cannot be
229
+ # demanded of it: the version, the digest of the bytes and the `procedencia` that says which
230
+ # route was taken are what a reader needs to know which code spoke.
231
+ identificados = all(
232
+ registro["estado"] != APLICABLE
233
+ or (registro["version"] and registro["huella"]
234
+ and (registro["commit"] or registro.get("procedencia") == PAQUETE))
235
+ for registro in ejecutores.values())
236
+ medidos = all(
237
+ registro["estado"] != APLICABLE or registro["hallazgos"] is not None
238
+ for registro in ejecutores.values())
239
+ # The count and the census must be the same number, or the delta downstream compares a
240
+ # quantity with a list and the gate passes a swap for a no-op.
241
+ nombrados = all(
242
+ registro["estado"] != APLICABLE
243
+ or (registro.get("huellas_de_hallazgo") is not None
244
+ and registro["hallazgos"] == len(registro["huellas_de_hallazgo"])
245
+ and registro.get("identidades_reconcilian") is True)
246
+ for registro in ejecutores.values())
247
+ razonados = all(
248
+ registro["estado"] == APLICABLE or bool(registro["razon"])
249
+ for registro in ejecutores.values())
250
+ return {
251
+ "particion": particion == cuenta["instrumentos"],
252
+ "identidad_de_ejecutores": identificados,
253
+ "medido_es_numero": medidos,
254
+ "hallazgos_nombrados": nombrados,
255
+ "estado_sin_medicion_nombra_su_razon": razonados,
256
+ "instrumentos": cuenta["instrumentos"],
257
+ "suma_estados": particion,
258
+ }
259
+
260
+
261
+ def construir(sujeto: str, raiz: str | None = None, tiempo_limite: int = 300,
262
+ base_entorno=None, forzar: bool = False, pines=None) -> dict:
263
+ """Measure the subject and return the sealed receipt. No wall clock, no paths.
264
+
265
+ `raiz=None` is not "the default directory": it is the absence of a promise about where the
266
+ instruments live, which lets the resolver try the sibling convention and then the installed
267
+ package. Passing `--raiz` promises checkouts, and a missing one is then a hole, not a
268
+ substitution.
269
+ """
270
+ cuerpo = correr(sujeto, raiz, tiempo_limite, base_entorno, forzar, pines)
271
+ recibo = {
272
+ "schema": ESQUEMA,
273
+ "generador": _generador(),
274
+ "interprete": interprete(),
275
+ "sujeto": {**sujeto_git(sujeto),
276
+ "superficie": {k: v for k, v in cuerpo["superficie"].items()}},
277
+ "modo": cuerpo["modo"],
278
+ "triaje": _triaje_minimo(cuerpo["triaje"]),
279
+ "ejecutores": {n: e for n, e in sorted(cuerpo["ejecutores"].items())},
280
+ "denominador": _denominador(cuerpo["ejecutores"]),
281
+ }
282
+ recibo["leyes"] = leyes(recibo)
283
+ recibo["sello"] = sha256_de(canonico(recibo).encode("utf-8"))
284
+ return recibo
285
+
286
+
287
+ def verificar(recibo: dict) -> bool:
288
+ """Recompute the seal over everything but the seal itself."""
289
+ sin_sello = {k: v for k, v in recibo.items() if k != "sello"}
290
+ return recibo.get("sello") == sha256_de(canonico(sin_sello).encode("utf-8"))
291
+
292
+
293
+ def salida_global(recibo: dict) -> tuple[int, str]:
294
+ """The composite exit code and its one-word reason.
295
+
296
+ Precedence is declared: a body whose seal or whose laws do not close is `3`, never a verdict,
297
+ because then nothing below it is worth reading. Then a subject with nothing measurable is `2`,
298
+ a finding is `1` because it is actionable, and anything unmeasured keeps the run at `2`.
299
+ """
300
+ if not verificar(recibo):
301
+ return 3, "RECIBO_INCONSISTENTE"
302
+ if not all(v for k, v in recibo["leyes"].items() if isinstance(v, bool)):
303
+ return 3, "RECIBO_INCONSISTENTE"
304
+ denominador = recibo["denominador"]
305
+ if denominador["aplicables"] == 0 and denominador["no_medidos"] == 0:
306
+ return 2, "SIN_SUPERFICIE"
307
+ if denominador["con_hallazgos"]:
308
+ return 1, "CON_HALLAZGOS"
309
+ if denominador["no_medidos"] or denominador["no_ejecutados"]:
310
+ return 2, "HUECO_DE_MEDICION"
311
+ return 0, "SIN_HALLAZGOS"
312
+
313
+
314
+ def escribir(recibo: dict, ruta: str) -> str:
315
+ with open(ruta, "w", encoding="utf-8") as f:
316
+ f.write(canonico(recibo))
317
+ return ruta
318
+
319
+
320
+ def _delta_de_ejecutor(nombre: str, antes: dict, despues: dict) -> dict:
321
+ """Classify one instrument's move from base to head. Every branch is a named verdict.
322
+
323
+ The trap this function exists to close is the unmeasured green: if a pull request deletes the
324
+ anchor manifest, the guard stops measuring and its zero findings would read as "nothing left
325
+ to fix". A measurement that disappears is a loss, and a loss never counts as a resolution.
326
+ """
327
+ fila = {"estado_base": antes["estado"], "estado_head": despues["estado"],
328
+ "nuevos": [], "resueltos": [], "atribuible": True, "nota": None}
329
+ identidades = [(antes.get(k), despues.get(k)) for k in IDENTIDAD_DE_EJECUTOR]
330
+ # An identity can only be *different* from another one. When the instrument never ran on one
331
+ # side -- `NO_APLICABLE` publishes no version -- there is nothing to reconcile, and calling
332
+ # that "a different executor" would withdraw attribution from a change that simply turned the
333
+ # instrument on. Divergence needs two identities to diverge.
334
+ if all(a is not None and b is not None for a, b in identidades) \
335
+ and any(a != b for a, b in identidades):
336
+ fila["atribuible"] = False
337
+ _nota(fila, "IDENTIDAD_DEL_EJECUTOR_DISTINTA")
338
+
339
+ if antes["estado"] == APLICABLE and despues["estado"] == APLICABLE:
340
+ cuenta_antes = Counter(antes.get("huellas_de_hallazgo") or [])
341
+ cuenta_despues = Counter(despues.get("huellas_de_hallazgo") or [])
342
+ fila["nuevos"] = sorted((cuenta_despues - cuenta_antes).elements())
343
+ fila["resueltos"] = sorted((cuenta_antes - cuenta_despues).elements())
344
+ return fila
345
+
346
+ if antes["estado"] == APLICABLE:
347
+ fila["atribuible"] = False
348
+ _nota(fila, "PERDIDA_DE_MEDICION")
349
+ fila["hallazgos_de_base_perdidos"] = antes.get("hallazgos")
350
+ return fila
351
+
352
+ if despues["estado"] == APLICABLE:
353
+ if antes["estado"] == NO_APLICABLE and fila["atribuible"]:
354
+ # The pull request created the surface, so what fails on it is the pull request's.
355
+ # Base was not blind here: it answered "nothing of mine to measure", which is a
356
+ # measurement of absence, not a hole. A hole is `NO_MEDIDO`, and only that is
357
+ # `SIN_BASE_MEDIDA` -- otherwise adding the first TypeScript file next to a
358
+ # diverging Python port would read as green.
359
+ _nota(fila, "SUPERFICIE_NUEVA")
360
+ fila["nuevos"] = sorted(despues.get("huellas_de_hallazgo") or [])
361
+ return fila
362
+ _nota(fila, "SIN_BASE_MEDIDA")
363
+ fila["hallazgos_de_head_sin_base"] = despues.get("hallazgos")
364
+ return fila
365
+
366
+ if NO_MEDIDO in (antes["estado"], despues["estado"]):
367
+ # A hole is not an absence, and only one of the two is green. `NO_APLICABLE` on both
368
+ # sides is a measurement of absence: the instrument looked and there was nothing of its
369
+ # universe. `NO_MEDIDO` is the instrument being pointed at the subject and not answering
370
+ # -- a timeout, a crash, a garbage line. Both used to land on the same note, so a run
371
+ # that timed out on head read exactly like a tree with nothing to measure: green.
372
+ fila["atribuible"] = False
373
+ _nota(fila, "MEDICION_NO_HECHA")
374
+ return fila
375
+ _nota(fila, "SIN_MEDICION_EN_NINGUNA_DE_LAS_DOS")
376
+ return fila
377
+
378
+
379
+ def comparar(base: dict, head: dict, estricto: bool = False) -> dict:
380
+ """The differential gate: verify both seals first, then say what the pull request changed.
381
+
382
+ The seal is recomputed before a single field is read. A comparison over a receipt whose body
383
+ does not match its own digest is a comparison over a document somebody edited, and it does
384
+ not matter what it says. Both receipts must also be the same schema: a v1 receipt has no
385
+ census and cannot be differenced, and pretending otherwise would report every finding of the
386
+ newer side as new.
387
+
388
+ `estricto` reads the same delta with a gate's eyes: a base that never answered stops being a
389
+ note about provenance and becomes RC 2. It is off by default because a pull request that adds
390
+ a surface where base had nothing to measure is normally the pull request's own business.
391
+ """
392
+ verificacion = {"base": verificar(base), "head": verificar(head)}
393
+ esquema = {"base": base.get("schema"), "head": head.get("schema")}
394
+ leyes_ok = {}
395
+ for lado, cuerpo in (("base", base), ("head", head)):
396
+ valores = cuerpo.get("leyes") or {}
397
+ leyes_ok[lado] = bool(valores) and all(v for v in valores.values() if isinstance(v, bool))
398
+
399
+ delta = {
400
+ "verificacion": verificacion,
401
+ "schema": esquema,
402
+ "leyes": leyes_ok,
403
+ "sujeto": {"base": (base.get("sujeto") or {}).get("head"),
404
+ "head": (head.get("sujeto") or {}).get("head")},
405
+ "sello": {"base": base.get("sello"), "head": head.get("sello")},
406
+ "instrumentos": {},
407
+ "resumen": {},
408
+ }
409
+ if not all(verificacion.values()) or not all(leyes_ok.values()) \
410
+ or esquema["base"] != esquema["head"] or esquema["base"] != ESQUEMA:
411
+ delta["resumen"] = _resumen_vacio()
412
+ delta["rc"], delta["veredicto"] = salida_de_comparacion(delta, estricto)
413
+ return delta
414
+
415
+ ejecutores_base = base.get("ejecutores") or {}
416
+ ejecutores_head = head.get("ejecutores") or {}
417
+ for nombre in sorted(set(ejecutores_base) | set(ejecutores_head)):
418
+ if nombre not in ejecutores_base or nombre not in ejecutores_head:
419
+ delta["instrumentos"][nombre] = _nota({
420
+ "estado_base": (ejecutores_base.get(nombre) or {}).get("estado"),
421
+ "estado_head": (ejecutores_head.get(nombre) or {}).get("estado"),
422
+ "nuevos": [], "resueltos": [], "atribuible": False, "nota": None},
423
+ "INSTRUMENTO_SOLO_EN_UNA_DE_LAS_DOS")
424
+ continue
425
+ delta["instrumentos"][nombre] = _delta_de_ejecutor(
426
+ nombre, ejecutores_base[nombre], ejecutores_head[nombre])
427
+
428
+ filas = delta["instrumentos"].values()
429
+ resumen = _resumen_vacio()
430
+ resumen["nuevos"] = sum(len(f["nuevos"]) for f in filas if f["atribuible"])
431
+ resumen["resueltos"] = sum(len(f["resueltos"]) for f in filas if f["atribuible"])
432
+ # One pass, one table: a note raises exactly the counter the table names, and a counter that
433
+ # is not in the table cannot be raised. `Counter` because two notes may share a counter --
434
+ # an identity divergence and an instrument present on one side only are both "no atribuible".
435
+ for nota, cuantas in Counter(f["nota"] for f in filas if f["nota"]).items():
436
+ contador = NOTAS[nota]["contador"]
437
+ if contador:
438
+ resumen[contador] += cuantas
439
+ delta["resumen"] = resumen
440
+ delta["rc"], delta["veredicto"] = salida_de_comparacion(delta, estricto)
441
+ return delta
442
+
443
+
444
+ def salida_de_comparacion(delta: dict, estricto: bool = False) -> tuple[int, str]:
445
+ """The comparison's exit code, with the same precedence discipline as the single receipt.
446
+
447
+ `3` before anything: an unreadable receipt is not a verdict. Then the notes, in the published
448
+ order they carry in `NOTAS` -- a measurement that disappeared, an instrument that never
449
+ answered, a delta produced by different bytes than the ones in base. Only then `1`, a finding
450
+ that was not in base, and `0`. A patch that merely bumps an instrument is therefore never
451
+ silently green.
452
+
453
+ The precedence is not restated here: it is read off the table, so a note added there with an
454
+ exit code is gated without anyone remembering to add a branch.
455
+ """
456
+ if delta.get("verificacion") and not all(delta["verificacion"].values()):
457
+ return 3, "SELLO_NO_RECOMPONE"
458
+ if delta.get("leyes") and not all(delta["leyes"].values()):
459
+ return 3, "LEYES_NO_CIERRAN"
460
+ if delta.get("schema") and delta["schema"]["base"] != delta["schema"]["head"]:
461
+ return 3, "ESQUEMAS_DISTINTOS"
462
+ if delta.get("schema") and ESQUEMA not in (delta["schema"]["base"], delta["schema"]["head"]):
463
+ return 3, "RECIBO_NO_COMPARABLE"
464
+ resumen = delta.get("resumen") or {}
465
+ for lectura in sorted(NOTAS.values(), key=lambda lectura: lectura["orden"]):
466
+ contador = lectura["contador"]
467
+ if not contador or not resumen.get(contador):
468
+ continue
469
+ if estricto and "rc_estricto" in lectura:
470
+ return lectura["rc_estricto"], lectura["veredicto_estricto"]
471
+ if lectura["rc"]:
472
+ return lectura["rc"], lectura["veredicto"]
473
+ if resumen.get("nuevos"):
474
+ return 1, "REGRESION"
475
+ return 0, "SIN_REGRESION"
476
+
477
+
478
+ __all__ = ["construir", "verificar", "salida_global", "canonico", "escribir", "leyes",
479
+ "comparar", "salida_de_comparacion", "ESQUEMA", "NOTAS", "COLUMNAS_DE_NOTA",
480
+ "lectura", "validar_notas", "COLUMNAS_PUBLICADAS"]
481
+
482
+
483
+ def _self_check() -> int: # pragma: no cover - exercised by the CLI flag, asserted by tests
484
+ """Smallest possible receipt: an empty temporary subject, built twice, compared byte by byte.
485
+
486
+ The tools directory is passed explicitly and does not exist, so four instruments are absent by
487
+ construction: this check must measure *this* runner, not whichever instrument checkouts happen
488
+ to sit beside it on the machine that runs it.
489
+ """
490
+ import tempfile
491
+
492
+ with tempfile.TemporaryDirectory() as caja:
493
+ ausente = os.path.join(caja, "sin-herramientas")
494
+ primero = construir(caja, ausente)
495
+ segundo = construir(caja, ausente)
496
+ iguales = canonico(primero) == canonico(segundo)
497
+ sello_ok = verificar(primero)
498
+ roto = dict(primero)
499
+ roto["denominador"] = dict(primero["denominador"], aplicables=99)
500
+ sello_roto = not verificar(roto)
501
+ delta = comparar(primero, segundo)
502
+ delta_ok = delta["rc"] == 0 and delta["resumen"]["nuevos"] == 0
503
+ manipulado = json.loads(canonico(segundo))
504
+ manipulado["sujeto"] = dict(manipulado["sujeto"], head="0" * 40)
505
+ delta_roto = comparar(primero, manipulado)["rc"]
506
+ print(f"destino vacío: {primero['denominador']['instrumentos']} instrumentos, "
507
+ f"{primero['denominador']['no_aplicables']} no aplicables")
508
+ print(f"dos corridas byte-idénticas: {iguales}")
509
+ print(f"sello recompone: {sello_ok} · cuerpo alterado no recompone: {sello_roto}")
510
+ print(f"comparación de un recibo consigo mismo: RC {delta['rc']} · "
511
+ f"recibo manipulado: RC {delta_roto}")
512
+ return 0 if (iguales and sello_ok and sello_roto and delta_ok and delta_roto == 3) else 1