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,227 @@
1
+ """The Markdown a pull request shows: bounded, and honest about the cut.
2
+
3
+ GitHub refuses a check output over 65 536 characters, and a render that silently drops the tail
4
+ is worse than a short one: the reader sees a complete-looking table over a truncated population.
5
+ So the render budgets itself, keeps the summary table first, and when it has to cut, it says how
6
+ many characters it cut and points at the JSON receipt that carries all of them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Mapping
12
+
13
+ from .runner import APLICABLE, NO_APLICABLE, NO_EJECUTADO, NO_MEDIDO
14
+ from .recibo import lectura, salida_global
15
+
16
+ #: The hard limit GitHub applies to a check output / check run text.
17
+ TOPE = 65_536
18
+
19
+ ESTADO_LEGIBLE = {
20
+ APLICABLE: "APLICABLE",
21
+ NO_APLICABLE: "NO_APLICABLE",
22
+ NO_MEDIDO: "NO_MEDIDO",
23
+ NO_EJECUTADO: "NO_EJECUTADO",
24
+ }
25
+
26
+
27
+ def _celda(valor) -> str:
28
+ if valor is None:
29
+ return "`NO_MEDIDO`"
30
+ if isinstance(valor, bool):
31
+ return "sí" if valor else "no"
32
+ if isinstance(valor, (list, tuple)):
33
+ return ", ".join(str(v) for v in valor) if valor else "—"
34
+ return str(valor)
35
+
36
+
37
+ def _denominador_celda(denominador: Mapping) -> str:
38
+ if not denominador:
39
+ return "—"
40
+ return " · ".join(f"{k}={_celda(v)}" for k, v in sorted(denominador.items()))
41
+
42
+
43
+ def _n(cantidad: int, singular: str, plural: str) -> str:
44
+ return f"{cantidad} {singular if cantidad == 1 else plural}"
45
+
46
+
47
+ def _cabecera(recibo: Mapping, rc: int, motivo: str) -> list[str]:
48
+ generador = recibo["generador"]
49
+ denominador = recibo["denominador"]
50
+ sujeto = recibo["sujeto"]
51
+ return [
52
+ f"# Frontera · {_n(denominador['instrumentos'], 'instrumento', 'instrumentos')} · "
53
+ f"{_n(denominador['aplicables'], 'aplicable', 'aplicables')} · {motivo}",
54
+ "",
55
+ f"`{generador['nombre']} {generador['version']}` · "
56
+ f"`commit {generador['commit'] or 'NO_MEDIDO'}` · "
57
+ f"`sello {recibo['sello']}` · RC `{rc}`",
58
+ "",
59
+ f"Modo: `{recibo.get('modo', 'NO_MEDIDO')}` · "
60
+ f"Sujeto: `HEAD {sujeto.get('head') or 'NO_MEDIDO'}` · "
61
+ f"archivos leídos `{sujeto['superficie']['archivos']}` · "
62
+ f"python `{sujeto['superficie']['python']}` · "
63
+ f"pruebas `{sujeto['superficie']['pruebas']}` · "
64
+ f"typescript `{sujeto['superficie']['typescript']}`",
65
+ "",
66
+ ]
67
+
68
+
69
+ def _tabla(recibo: Mapping) -> list[str]:
70
+ filas = ["| instrumento | estado | razón | rc | hallazgos | denominador | versión | commit |",
71
+ "|---|---|---|---|---|---|---|---|"]
72
+ for nombre, registro in sorted(recibo["ejecutores"].items()):
73
+ filas.append(
74
+ f"| `{nombre}` | {ESTADO_LEGIBLE.get(registro['estado'], registro['estado'])} | "
75
+ f"{registro['razon'] or '—'} | "
76
+ f"{_celda(registro['rc'])} | {_celda(registro['hallazgos'])} | "
77
+ f"{_denominador_celda(registro['denominador'])} | "
78
+ f"{_celda(registro['version'])} | `{(registro['commit'] or 'NO_MEDIDO')[:12]}` |")
79
+ filas.append("")
80
+ return filas
81
+
82
+
83
+ def _detalle(recibo: Mapping) -> list[str]:
84
+ lineas = ["## Detalle", ""]
85
+ for nombre, registro in sorted(recibo["ejecutores"].items()):
86
+ estado = ESTADO_LEGIBLE.get(registro["estado"], registro["estado"])
87
+ lineas.append(f"### `{nombre}` — {estado}")
88
+ lineas.append("")
89
+ lineas.append(f"- comando: `{' '.join(registro['comando'])}`")
90
+ lineas.append(f"- razón: {registro['razon'] or '—'}")
91
+ lineas.append(f"- huella del ejecutor: `{registro['huella'] or 'NO_MEDIDO'}`")
92
+ lineas.append(f"- salida sellada: `{registro['salida_sha256'] or 'NO_MEDIDO'}`")
93
+ lineas.append(f"- procedencia: `{registro.get('procedencia') or 'NO_MEDIDO'}` · "
94
+ f"commit: `{(registro.get('commit') or 'NO_MEDIDO')[:12]}`")
95
+ if registro.get("pin"):
96
+ pin = registro["pin"]
97
+ lineas.append(f"- pin declarado: `{pin.get('estado')}` · "
98
+ f"commit `{str(pin.get('commit_declarado') or 'NO_MEDIDO')[:12]}`")
99
+ denominador = _denominador_celda(registro["denominador"])
100
+ lineas.append(f"- denominador: {denominador}")
101
+ if registro.get("hallazgos_declarados") is not None:
102
+ lineas.append(f"- hallazgos declarados por el instrumento: "
103
+ f"`{registro['hallazgos_declarados']}` en unidades de "
104
+ f"`{registro.get('unidad_declarada')}`")
105
+ lineas.append("")
106
+ return lineas
107
+
108
+
109
+ def _leyes(recibo: Mapping) -> list[str]:
110
+ lineas = ["## Leyes del recibo", ""]
111
+ for nombre, valor in sorted(recibo["leyes"].items()):
112
+ if isinstance(valor, bool):
113
+ lineas.append(f"- `{nombre}`: {'cierra' if valor else 'NO CIERRA'}")
114
+ lineas.append("")
115
+ return lineas
116
+
117
+
118
+ def recortar(texto: str, tope: int = TOPE) -> str:
119
+ """Cut at a line boundary and declare the cut. Never return a silently shorter body."""
120
+ if len(texto) <= tope:
121
+ return texto
122
+ marca = "\n<!-- RECORTADO: {n} carácter(es) omitidos; el recibo JSON lleva el detalle completo -->\n"
123
+ margen = len(marca.format(n=len(texto)))
124
+ corte = texto[: max(0, tope - margen)]
125
+ corte = corte[: corte.rfind("\n") + 1] if "\n" in corte else corte
126
+ return corte + marca.format(n=len(texto) - len(corte))
127
+
128
+
129
+ def markdown(recibo: Mapping, tope: int = TOPE) -> str:
130
+ rc, motivo = salida_global(recibo)
131
+ lineas = _cabecera(recibo, rc, motivo) + _tabla(recibo) + _leyes(recibo) + _detalle(recibo)
132
+ return recortar("\n".join(lineas).rstrip("\n") + "\n", tope)
133
+
134
+
135
+ #: How many identities of one kind a pull-request comment lists. The receipt carries all of them;
136
+ #: a comment that pastes ten thousand lines is a comment nobody reads, and GitHub truncates it.
137
+ TOPE_IDENTIDADES = 25
138
+
139
+
140
+ def _identidades(titulo: str, claves: list[str]) -> list[str]:
141
+ if not claves:
142
+ return []
143
+ lineas = [f"- {titulo}: {len(claves)}"]
144
+ for clave in claves[:TOPE_IDENTIDADES]:
145
+ lineas.append(f" - `{clave}`")
146
+ if len(claves) > TOPE_IDENTIDADES:
147
+ lineas.append(f" - … {len(claves) - TOPE_IDENTIDADES} más en el recibo JSON")
148
+ return lineas
149
+
150
+
151
+ def _parrafo(fila: Mapping) -> str | None:
152
+ """The note's own paragraph, read off the catalogue instead of branched on here.
153
+
154
+ A paragraph about a note belongs to the note, so it lives in `recibo.NOTAS` and this function
155
+ only formats it: a note added there arrives explained without anyone remembering to add a
156
+ branch here. A paragraph about a *count* is a different thing -- `hallazgos_de_base_perdidos`
157
+ and `hallazgos_de_head_sin_base` stay keyed by their field, because the field can be missing
158
+ while the note is not, and a paragraph that printed "`None` hallazgo(s)" would be worse than
159
+ no paragraph at all.
160
+ """
161
+ if not fila["nota"]:
162
+ return None
163
+ detalle = lectura(fila["nota"])["detalle"]
164
+ if not detalle:
165
+ return None
166
+ return detalle.format(nuevos=len(fila["nuevos"]), resueltos=len(fila["resueltos"]))
167
+
168
+
169
+ def markdown_diff(delta: Mapping, tope: int = TOPE) -> str:
170
+ """The one comment a pull request gets: what base said, what head says, and the verdict."""
171
+ resumen = delta["resumen"]
172
+ lineas = [
173
+ f"# Frontera · diff base→head · {delta['veredicto']} · RC `{delta.get('rc')}`",
174
+ "",
175
+ f"base `HEAD {(delta['sujeto']['base'] or 'NO_MEDIDO')[:12]}` · "
176
+ f"head `HEAD {(delta['sujeto']['head'] or 'NO_MEDIDO')[:12]}`",
177
+ "",
178
+ f"nuevos `{resumen['nuevos']}` · resueltos `{resumen['resueltos']}` · "
179
+ f"pérdidas de medición `{resumen['perdidas_de_medicion']}` · "
180
+ f"mediciones no hechas `{resumen['mediciones_no_hechas']}` · "
181
+ f"instrumentos sin base medida `{resumen['ganancias_de_medicion']}` · "
182
+ f"superficies nuevas `{resumen['superficies_nuevas']}` · "
183
+ f"no atribuibles `{resumen['no_atribuibles']}`",
184
+ "",
185
+ "## Instrumentos",
186
+ "",
187
+ "| instrumento | base | head | nuevos | resueltos | lectura |",
188
+ "|---|---|---|---|---|---|",
189
+ ]
190
+ for nombre, fila in sorted(delta["instrumentos"].items()):
191
+ lineas.append(
192
+ f"| `{nombre}` | {fila['estado_base']} | {fila['estado_head']} | "
193
+ f"{len(fila['nuevos'])} | {len(fila['resueltos'])} | "
194
+ f"{fila['nota'] or ('delta atribuible' if fila['atribuible'] else '—')} |")
195
+ lineas.append("")
196
+
197
+ detalle = []
198
+ for nombre, fila in sorted(delta["instrumentos"].items()):
199
+ bloque = [f"### `{nombre}`", ""]
200
+ bloque += _identidades("nuevos en head", fila["nuevos"])
201
+ bloque += _identidades("resueltos desde base", fila["resueltos"])
202
+ if fila.get("hallazgos_de_base_perdidos") is not None:
203
+ bloque.append(f"- la medición de base nombraba "
204
+ f"`{fila['hallazgos_de_base_perdidos']}` hallazgo(s) que head ya no mide: "
205
+ "una pérdida de medición no es una resolución")
206
+ parrafo = _parrafo(fila)
207
+ if parrafo:
208
+ bloque.append(parrafo)
209
+ if fila.get("hallazgos_de_head_sin_base") is not None:
210
+ bloque.append(f"- base no medía este instrumento; head declara "
211
+ f"`{fila['hallazgos_de_head_sin_base']}` hallazgo(s) sin base contra la "
212
+ "cual compararlos")
213
+ if bloque[-1] != "":
214
+ detalle += bloque + [""]
215
+ if detalle:
216
+ lineas += ["## Detalle", ""] + detalle
217
+
218
+ lineas += ["## Sellos verificados", "",
219
+ f"- base: `{'recompone' if delta['verificacion']['base'] else 'NO RECOMPONE'}` · "
220
+ f"`{delta['sello']['base']}`",
221
+ f"- head: `{'recompone' if delta['verificacion']['head'] else 'NO RECOMPONE'}` · "
222
+ f"`{delta['sello']['head']}`",
223
+ ""]
224
+ return recortar("\n".join(lineas).rstrip("\n") + "\n", tope)
225
+
226
+
227
+ __all__ = ["markdown", "markdown_diff", "recortar", "TOPE", "TOPE_IDENTIDADES"]
@@ -0,0 +1,336 @@
1
+ """Run the instruments the triage admitted, and read them without flattering them.
2
+
3
+ Every call is a subprocess with the subject as its working directory. Nothing is imported: an
4
+ instrument that mutates module state, caches a parse or keeps a global baseline cannot reach
5
+ this process, and the isolation works in both directions -- this runner never edits the
6
+ instrument's repository, and never reads its internals.
7
+
8
+ The environment is an allowlist, not an inheritance. A runner that forwards whatever the CI
9
+ machine happened to export produces a receipt that cannot be reproduced anywhere else.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+ from typing import Mapping
20
+
21
+ from . import instrumentos as inst
22
+ from .triaje_frontera import superficie, triar
23
+
24
+ #: Terminal states of one instrument in one run. There is no "skipped without saying so".
25
+ APLICABLE = "APLICABLE"
26
+ NO_APLICABLE = "NO_APLICABLE"
27
+ NO_MEDIDO = "NO_MEDIDO"
28
+ NO_EJECUTADO = "NO_EJECUTADO"
29
+
30
+ #: How the bytes that ran were found. Both are legitimate; they are not interchangeable, because
31
+ #: only a checkout has a repository to read a commit from.
32
+ CLON = "CLON"
33
+ PAQUETE = "PAQUETE"
34
+
35
+ #: Variables the instruments may read. Everything else is dropped, so two machines that export
36
+ #: different things still produce the same receipt.
37
+ ENTORNO_PERMITIDO = ("PATH", "HOME", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "SYSTEMROOT")
38
+ ENTORNO_FIJO = {
39
+ "PYTHONDONTWRITEBYTECODE": "1",
40
+ "PYTHONHASHSEED": "0",
41
+ "PYTHONIOENCODING": "utf-8",
42
+ }
43
+
44
+ TIEMPO_LIMITE_POR_DEFECTO = 300
45
+ _RECORTE_MENSAJE = 400
46
+
47
+
48
+ def entorno_de(repo: str | None, base: Mapping[str, str] | None = None, subruta: str = "") -> dict:
49
+ """The environment one instrument runs in: allowlist, plus its package on `PYTHONPATH`.
50
+
51
+ `repo=None` means the instrument is installed in this interpreter's environment: there is no
52
+ checkout to put on the path, and setting one would shadow the installation with whatever
53
+ happens to sit beside this repository on the machine that runs it.
54
+ """
55
+ base = os.environ if base is None else base
56
+ entorno = {k: base[k] for k in ENTORNO_PERMITIDO if k in base}
57
+ entorno.update(ENTORNO_FIJO)
58
+ if repo is not None:
59
+ entorno["PYTHONPATH"] = os.path.join(repo, subruta) if subruta else repo
60
+ return entorno
61
+
62
+
63
+ def _limpiar(texto: str, *rutas: tuple[str | None, str]) -> str:
64
+ """Keep absolute paths out of the receipt: they name a machine, not a subject.
65
+
66
+ A route may have no path at all -- an installed package has no checkout, and there is no
67
+ `--raiz` to name -- so an absent one is skipped instead of aborting the measurement. The
68
+ package root is scrubbed too: a traceback from `site-packages` carries the runner's own
69
+ interpreter path, which would make the same tree seal differently on two machines.
70
+ """
71
+ for ruta, token in rutas:
72
+ if not ruta:
73
+ continue
74
+ texto = texto.replace(os.path.abspath(ruta), token).replace(os.path.realpath(ruta), token)
75
+ return texto[:_RECORTE_MENSAJE]
76
+
77
+
78
+ def _registro_base(instrumento: inst.Instrumento, manifiesto: str | None = None) -> dict:
79
+ return {
80
+ "comando": [instrumento.modulo, *[a.format(manifiesto=manifiesto or "")
81
+ for a in instrumento.argumentos]],
82
+ "rc_contrato": {str(c): {"clase": v[0], "etiqueta": v[1]}
83
+ for c, v in sorted(instrumento.rc_contrato.items())},
84
+ }
85
+
86
+
87
+ def _sin_ejecutar(instrumento: inst.Instrumento, estado: str, razon: str,
88
+ resolucion: Mapping | None = None) -> dict:
89
+ registro = _registro_base(instrumento)
90
+ registro.update({"estado": estado, "razon": razon, "rc": None, "version": None,
91
+ "commit": None, "huella": None, "procedencia": None, "pin": None,
92
+ "salida_sha256": None, "denominador": {}, "hallazgos": None,
93
+ "hallazgos_declarados": None, "unidad_declarada": instrumento.unidad,
94
+ "huellas_de_hallazgo": None, "identidades_reconcilian": None})
95
+ if resolucion:
96
+ registro.update({k: resolucion.get(k) for k in
97
+ ("version", "commit", "huella", "procedencia", "pin")})
98
+ return registro
99
+
100
+
101
+ def resolver(instrumento: inst.Instrumento, raiz: str | None = None,
102
+ pines: Mapping | None = None) -> dict:
103
+ """Find the instrument and identify the bytes that will run.
104
+
105
+ Two routes, and the difference between them is a promise. An explicit `--raiz` means "measure
106
+ exactly these checkouts": a missing sibling is then `INSTRUMENTO_AUSENTE`, because silently
107
+ substituting an installed copy would answer about a tree nobody asked about. Without `--raiz`
108
+ the sibling convention is tried first and the installed package second, which is the only
109
+ route a consumer repository has -- it has no four sibling clones to point at.
110
+
111
+ A pin is a declaration, never a measurement: an installed package has no repository to read a
112
+ commit from, so the declared commit is published as declared and a mismatch with the version
113
+ that is installed is reported as a mismatch instead of being smoothed over.
114
+ """
115
+ pin = None
116
+ if pines and instrumento.nombre in pines:
117
+ pin = dict(pines[instrumento.nombre])
118
+ if raiz is not None:
119
+ repo = os.path.join(raiz, instrumento.nombre)
120
+ if not os.path.isdir(repo):
121
+ return {"modo": CLON, "repo": None, "razon": "INSTRUMENTO_AUSENTE", "pin": pin}
122
+ return {"modo": CLON, "repo": repo, "procedencia": CLON, "pin": pin,
123
+ **inst.identificar(repo, instrumento)}
124
+
125
+ vecino = os.path.join(raiz_por_defecto(), instrumento.nombre)
126
+ if os.path.isdir(vecino):
127
+ return {"modo": CLON, "repo": vecino, "procedencia": CLON, "pin": pin,
128
+ **inst.identificar(vecino, instrumento)}
129
+
130
+ ubicacion = inst.ubicacion_instalada(instrumento.modulo.split(".")[0])
131
+ if ubicacion is None:
132
+ return {"modo": PAQUETE, "repo": None, "razon": "INSTRUMENTO_AUSENTE", "pin": pin}
133
+ return {"modo": PAQUETE, "repo": None, "procedencia": PAQUETE, "pin": pin,
134
+ "version": ubicacion.get("version"),
135
+ "commit": None,
136
+ # The located directory *is* the package root, so the digest is taken there: the same
137
+ # bytes installed and checked out under `src/` share relative paths and seal equally.
138
+ "huella": inst.huella_de_arbol(ubicacion["ruta"]),
139
+ # Scrubbed out of any instrument message, never published: it names this machine's
140
+ # interpreter, and a receipt that carries it seals differently on another one.
141
+ "ruta_de_paquete": ubicacion["ruta"]}
142
+
143
+
144
+ def _juzgar_pin(instrumento: inst.Instrumento, resolucion: Mapping) -> dict | None:
145
+ """Compare the declaration with what is installed. Absent pin, absent evidence.
146
+
147
+ A declared commit cannot be verified against an installation -- that is the whole reason it
148
+ is published as declared -- so only the version is checked, and an unverifiable pin is
149
+ reported as `NO_VERIFICABLE`, which is not the same word as `VERIFICADO`.
150
+ """
151
+ pin = resolucion.get("pin")
152
+ if not pin:
153
+ return None
154
+ declarado = (pin.get("version"), pin.get("commit"))
155
+ medido = (resolucion.get("version"), resolucion.get("commit"))
156
+ veredicto = {"version_declarada": declarado[0], "commit_declarado": declarado[1],
157
+ "version_medida": medido[0], "commit_medido": medido[1]}
158
+ if declarado[0] and medido[0] and str(declarado[0]) != str(medido[0]):
159
+ veredicto.update({"estado": "DIVERGE", "razon": "LA_VERSION_INSTALADA_NO_ES_LA_DECLARADA"})
160
+ elif declarado[1] and medido[1]:
161
+ vale = _pin_apunta_a(declarado[1], medido[1])
162
+ veredicto.update({"estado": "VERIFICADO" if vale else "DIVERGE",
163
+ "razon": None if vale else "EL_COMMIT_MEDIDO_NO_ES_EL_DECLARADO"})
164
+ else:
165
+ veredicto.update({"estado": "NO_VERIFICABLE",
166
+ "razon": "LA_INSTALACION_NO_DECLARA_COMMIT"})
167
+ return veredicto
168
+
169
+
170
+ def _pin_apunta_a(declarado: str, medido: str) -> bool:
171
+ """A declared commit may be abbreviated, exactly as `git rev-parse` reads one.
172
+
173
+ Anything shorter than seven characters is not an identifier in this repository, so it is not
174
+ honoured as one here either: a two-character prefix matches everything and proves nothing.
175
+ """
176
+ declarado, medido = str(declarado).strip().lower(), str(medido).strip().lower()
177
+ if len(declarado) < 7:
178
+ return False
179
+ return medido.startswith(declarado)
180
+
181
+
182
+ def ejecutar(instrumento: inst.Instrumento, sujeto: str, raiz: str | None, triaje: Mapping,
183
+ tiempo_limite: int = TIEMPO_LIMITE_POR_DEFECTO,
184
+ base_entorno: Mapping[str, str] | None = None,
185
+ pines: Mapping | None = None) -> dict:
186
+ """One instrument, one subprocess, one record. Never raises on a bad subject."""
187
+ decision = triaje[instrumento.nombre]
188
+ if decision["estado"] == NO_APLICABLE:
189
+ return _sin_ejecutar(instrumento, NO_APLICABLE, decision["razon"])
190
+
191
+ resolucion = resolver(instrumento, raiz, pines)
192
+ if resolucion["repo"] is None and resolucion.get("razon"):
193
+ return _sin_ejecutar(instrumento, NO_EJECUTADO, resolucion["razon"], resolucion)
194
+ repo = resolucion["repo"]
195
+ rutas_a_limpiar = ((sujeto, "<sujeto>"), (raiz or repo, "<herramientas>"),
196
+ (resolucion.get("ruta_de_paquete"), "<paquete>"))
197
+
198
+ manifiesto = decision["insumos"].get("manifiesto")
199
+ argv = [sys.executable, "-m", *instrumento.comando(manifiesto)]
200
+ registro = _registro_base(instrumento, manifiesto)
201
+ registro.update({k: resolucion.get(k) for k in
202
+ ("version", "commit", "huella", "procedencia")})
203
+ registro.update({"pin": _juzgar_pin(instrumento, resolucion),
204
+ "modo_resolucion": resolucion["modo"],
205
+ "denominador": {}, "hallazgos": None, "hallazgos_declarados": None,
206
+ "unidad_declarada": instrumento.unidad, "huellas_de_hallazgo": None,
207
+ "identidades_reconcilian": None, "salida_sha256": None})
208
+
209
+ try:
210
+ hecho = subprocess.run(argv, cwd=sujeto,
211
+ env=entorno_de(repo, base_entorno, instrumento.subruta),
212
+ capture_output=True, timeout=tiempo_limite)
213
+ except subprocess.TimeoutExpired:
214
+ registro.update({"estado": NO_MEDIDO, "razon": "TIEMPO_AGOTADO", "rc": None})
215
+ return registro
216
+ except (OSError, subprocess.SubprocessError) as fallo:
217
+ razon = _limpiar(f"NO_ARRANCO: {fallo}", *rutas_a_limpiar)
218
+ registro.update({"estado": NO_MEDIDO, "razon": razon, "rc": None})
219
+ return registro
220
+
221
+ crudo = hecho.stdout or b""
222
+ registro["salida_sha256"] = "sha256:" + _sha256(crudo)
223
+
224
+ clase, etiqueta = instrumento.rc_contrato.get(hecho.returncode, (NO_MEDIDO, "RC_NO_DECLARADO"))
225
+ registro["rc"] = hecho.returncode
226
+ if clase == inst.SIN_SUJETO:
227
+ registro.update({"estado": NO_APLICABLE, "razon": f"EL_INSTRUMENTO_NO_VIO_SUJETO: {etiqueta}"})
228
+ return registro
229
+ if clase == NO_MEDIDO:
230
+ detalle = _limpiar((hecho.stderr or b"").decode("utf-8", "replace").strip(),
231
+ *rutas_a_limpiar)
232
+ razon = f"{etiqueta}" if not detalle else f"{etiqueta}: {detalle}"
233
+ registro.update({"estado": NO_MEDIDO, "razon": razon})
234
+ return registro
235
+
236
+ try:
237
+ salida = json.loads(crudo.decode("utf-8"))
238
+ except (UnicodeDecodeError, json.JSONDecodeError):
239
+ # An instrument that exits on a contract code and prints no JSON has crashed; its last
240
+ # stderr line is the only evidence of why, so it travels with the state.
241
+ cola = [l for l in _limpiar((hecho.stderr or b"").decode("utf-8", "replace"),
242
+ *rutas_a_limpiar).splitlines() if l.strip()]
243
+ razon = "SALIDA_NO_JSON" + (f": {cola[-1][:200]}" if cola else "")
244
+ registro.update({"estado": NO_MEDIDO, "razon": razon})
245
+ return registro
246
+ if not isinstance(salida, dict):
247
+ registro.update({"estado": NO_MEDIDO, "razon": "SALIDA_NO_ES_OBJETO"})
248
+ return registro
249
+
250
+ hallazgos = instrumento.hallazgos(salida)
251
+ if hallazgos is None:
252
+ # A "measured" exit code over a payload without the counters is not a zero: the
253
+ # instrument did not say how many, and the receipt must not say it for it.
254
+ registro.update({"estado": NO_MEDIDO, "razon": "SALIDA_SIN_HALLAZGOS_DECLARADOS",
255
+ "denominador": instrumento.denominador(salida)})
256
+ return registro
257
+
258
+ identidades = instrumento.identidades(salida)
259
+ if identidades is None:
260
+ # The count without the names is a number no diff can act on: a gate that reported
261
+ # "two findings became two findings" would pass a pull request that swapped both.
262
+ registro.update({"estado": NO_MEDIDO, "razon": "SALIDA_SIN_IDENTIDADES",
263
+ "hallazgos_declarados": hallazgos,
264
+ "denominador": instrumento.denominador(salida)})
265
+ return registro
266
+
267
+ # Sorted here, not trusted from the payload: two runs must seal the same bytes even if an
268
+ # instrument walks a filesystem whose iteration order is not stable.
269
+ nombres = sorted(identidades)
270
+ if instrumento.reconciliar is not None:
271
+ reconcilia = bool(instrumento.reconciliar(salida, nombres))
272
+ else:
273
+ reconcilia = len(nombres) == hallazgos
274
+ if not reconcilia:
275
+ registro.update({"estado": NO_MEDIDO, "razon": "IDENTIDADES_NO_RECONCILIAN",
276
+ "hallazgos_declarados": hallazgos,
277
+ "denominador": instrumento.denominador(salida),
278
+ "huellas_de_hallazgo": nombres})
279
+ return registro
280
+
281
+ registro.update({
282
+ "estado": APLICABLE,
283
+ "razon": etiqueta,
284
+ "denominador": instrumento.denominador(salida),
285
+ "hallazgos": len(nombres),
286
+ "hallazgos_declarados": hallazgos,
287
+ "huellas_de_hallazgo": nombres,
288
+ "identidades_reconcilian": True,
289
+ })
290
+ return registro
291
+
292
+
293
+ def _sha256(datos: bytes) -> str:
294
+ return hashlib.sha256(datos).hexdigest()
295
+
296
+
297
+ def correr(sujeto: str, raiz: str | None = None, tiempo_limite: int = TIEMPO_LIMITE_POR_DEFECTO,
298
+ base_entorno: Mapping[str, str] | None = None, forzar: bool = False,
299
+ pines: Mapping | None = None) -> dict:
300
+ """Triage, run what the triage admitted, and return the measured body of the receipt.
301
+
302
+ `forzar` runs every instrument regardless of the gate. It exists to measure what the gate
303
+ saves: without it, "the triage makes runs shorter" would be a claim with no instrument.
304
+ """
305
+ sup = superficie(sujeto)
306
+ triaje = triar(sujeto, sup)
307
+ if forzar:
308
+ triaje = {nombre: {"estado": APLICABLE, "razon": "TRIAJE_FORZADO", "insumos": t["insumos"]}
309
+ for nombre, t in triaje.items()}
310
+ ejecutores = {}
311
+ for instrumento in inst.INSTRUMENTOS:
312
+ ejecutores[instrumento.nombre] = ejecutar(
313
+ instrumento, sujeto, raiz, triaje, tiempo_limite, base_entorno, pines)
314
+ return {"superficie": sup, "triaje": triaje, "ejecutores": ejecutores,
315
+ "modo": "FORZADO" if forzar else "TRIADO"}
316
+
317
+
318
+ def sujeto_git(sujeto: str) -> dict:
319
+ """The subject's identity: `HEAD`, without the path that names this machine."""
320
+ try:
321
+ hecho = subprocess.run(["git", "-C", sujeto, "rev-parse", "HEAD"],
322
+ capture_output=True, text=True, timeout=60)
323
+ except (OSError, subprocess.SubprocessError):
324
+ return {"head": None}
325
+ head = hecho.stdout.strip() if hecho.returncode == 0 else None
326
+ return {"head": head or None}
327
+
328
+
329
+ def raiz_por_defecto() -> str:
330
+ """Sibling-clone convention: the instruments live beside this repository, not inside it."""
331
+ # __file__ is <parent>/frontera_runner/runner.py, so the parent is three levels up.
332
+ return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
333
+
334
+
335
+ __all__ = ["correr", "ejecutar", "entorno_de", "resolver", "sujeto_git", "raiz_por_defecto",
336
+ "APLICABLE", "NO_APLICABLE", "NO_MEDIDO", "NO_EJECUTADO", "CLON", "PAQUETE"]