csync-local 0.1.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.
Files changed (98) hide show
  1. csync_local-0.1.0.dist-info/METADATA +251 -0
  2. csync_local-0.1.0.dist-info/RECORD +98 -0
  3. csync_local-0.1.0.dist-info/WHEEL +5 -0
  4. csync_local-0.1.0.dist-info/entry_points.txt +2 -0
  5. csync_local-0.1.0.dist-info/licenses/LICENSE +21 -0
  6. csync_local-0.1.0.dist-info/top_level.txt +1 -0
  7. localcsync/__init__.py +3 -0
  8. localcsync/__main__.py +6 -0
  9. localcsync/_vendor/VENDORED_FROM +1 -0
  10. localcsync/_vendor/__init__.py +1 -0
  11. localcsync/_vendor/csync/backend/app/__init__.py +2 -0
  12. localcsync/_vendor/csync/backend/app/log_redaction.py +66 -0
  13. localcsync/_vendor/csync/backend/app/runtime_assets/__init__.py +1 -0
  14. localcsync/_vendor/csync/backend/app/runtime_assets/contract.py +168 -0
  15. localcsync/_vendor/csync/backend/app/sentry.py +415 -0
  16. localcsync/_vendor/csync/backend/app/validation/__init__.py +0 -0
  17. localcsync/_vendor/csync/backend/app/validation/codebuild_entry.py +96 -0
  18. localcsync/_vendor/csync/backend/app/validation/codebuild_run.py +291 -0
  19. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/__init__.py +14 -0
  20. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/checker.py +170 -0
  21. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/gather.py +72 -0
  22. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/prompt.py +121 -0
  23. localcsync/_vendor/csync/backend/app/validation/config_yaml_check/rules.py +823 -0
  24. localcsync/_vendor/csync/backend/app/validation/datetime_utc/__init__.py +0 -0
  25. localcsync/_vendor/csync/backend/app/validation/datetime_utc/checker.py +145 -0
  26. localcsync/_vendor/csync/backend/app/validation/datetime_utc/gather.py +541 -0
  27. localcsync/_vendor/csync/backend/app/validation/docker_manager.py +726 -0
  28. localcsync/_vendor/csync/backend/app/validation/engine.py +2787 -0
  29. localcsync/_vendor/csync/backend/app/validation/env_validator/__init__.py +0 -0
  30. localcsync/_vendor/csync/backend/app/validation/env_validator/batch_validators.py +238 -0
  31. localcsync/_vendor/csync/backend/app/validation/env_validator/models.py +64 -0
  32. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/__init__.py +0 -0
  33. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/async_http.py +233 -0
  34. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/docker_utils.py +334 -0
  35. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/http_utils.py +338 -0
  36. localcsync/_vendor/csync/backend/app/validation/env_validator/utils/port_utils.py +113 -0
  37. localcsync/_vendor/csync/backend/app/validation/env_validator/validators.py +661 -0
  38. localcsync/_vendor/csync/backend/app/validation/eval_awareness/__init__.py +0 -0
  39. localcsync/_vendor/csync/backend/app/validation/eval_awareness/checker.py +565 -0
  40. localcsync/_vendor/csync/backend/app/validation/external_network.py +1691 -0
  41. localcsync/_vendor/csync/backend/app/validation/feature_coverage/__init__.py +0 -0
  42. localcsync/_vendor/csync/backend/app/validation/feature_coverage/checker.py +97 -0
  43. localcsync/_vendor/csync/backend/app/validation/feature_coverage/gather.py +385 -0
  44. localcsync/_vendor/csync/backend/app/validation/file_scope.py +293 -0
  45. localcsync/_vendor/csync/backend/app/validation/fingerprint.py +265 -0
  46. localcsync/_vendor/csync/backend/app/validation/github_reporter.py +493 -0
  47. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/__init__.py +0 -0
  48. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/checker.py +275 -0
  49. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/fetch.py +491 -0
  50. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/keys.py +106 -0
  51. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/manifest.py +164 -0
  52. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/models.py +50 -0
  53. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/reference.py +115 -0
  54. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/scanner.py +169 -0
  55. localcsync/_vendor/csync/backend/app/validation/keyboard_shortcuts/search_provider.py +200 -0
  56. localcsync/_vendor/csync/backend/app/validation/live_log.py +135 -0
  57. localcsync/_vendor/csync/backend/app/validation/mcp_parity/__init__.py +9 -0
  58. localcsync/_vendor/csync/backend/app/validation/mcp_parity/detect.py +164 -0
  59. localcsync/_vendor/csync/backend/app/validation/mcp_parity/prompt.py +161 -0
  60. localcsync/_vendor/csync/backend/app/validation/mcp_parity/runner.py +115 -0
  61. localcsync/_vendor/csync/backend/app/validation/multi_rl/__init__.py +35 -0
  62. localcsync/_vendor/csync/backend/app/validation/multi_rl/app_contract.py +378 -0
  63. localcsync/_vendor/csync/backend/app/validation/multi_rl/ci_image.py +542 -0
  64. localcsync/_vendor/csync/backend/app/validation/multi_rl/em_dash.py +225 -0
  65. localcsync/_vendor/csync/backend/app/validation/multi_rl/findings.py +157 -0
  66. localcsync/_vendor/csync/backend/app/validation/multi_rl/image_checks.py +876 -0
  67. localcsync/_vendor/csync/backend/app/validation/multi_rl/pins.py +357 -0
  68. localcsync/_vendor/csync/backend/app/validation/multi_rl/profile_config.py +328 -0
  69. localcsync/_vendor/csync/backend/app/validation/multi_rl/runner.py +356 -0
  70. localcsync/_vendor/csync/backend/app/validation/multi_rl/secrets.py +241 -0
  71. localcsync/_vendor/csync/backend/app/validation/multi_rl/seed_cache.py +112 -0
  72. localcsync/_vendor/csync/backend/app/validation/multi_rl/suite_rules.py +424 -0
  73. localcsync/_vendor/csync/backend/app/validation/naming_audit/__init__.py +6 -0
  74. localcsync/_vendor/csync/backend/app/validation/naming_audit/candidates.py +159 -0
  75. localcsync/_vendor/csync/backend/app/validation/naming_audit/detectors.py +166 -0
  76. localcsync/_vendor/csync/backend/app/validation/naming_audit/prompt.py +181 -0
  77. localcsync/_vendor/csync/backend/app/validation/naming_audit/providers.py +137 -0
  78. localcsync/_vendor/csync/backend/app/validation/naming_audit/runner.py +206 -0
  79. localcsync/_vendor/csync/backend/app/validation/recovery.py +680 -0
  80. localcsync/_vendor/csync/backend/app/validation/registry.py +615 -0
  81. localcsync/_vendor/csync/backend/app/validation/restricted_terms/__init__.py +0 -0
  82. localcsync/_vendor/csync/backend/app/validation/restricted_terms/checker.py +321 -0
  83. localcsync/_vendor/csync/backend/app/validation/runtime_assets.py +121 -0
  84. localcsync/_vendor/csync/backend/app/validation/seed_paths.py +7 -0
  85. localcsync/_vendor/csync/backend/app/validation/single_rl_checks.py +326 -0
  86. localcsync/_vendor/csync/backend/app/validation/worker.py +210 -0
  87. localcsync/_vendor/csync/backend/tools/feature-mapping/action-facts.mjs +142 -0
  88. localcsync/_vendor/csync/backend/tools/feature-mapping/census.mjs +53 -0
  89. localcsync/_vendor/csync/backend/tools/feature-mapping/chain-facts.mjs +286 -0
  90. localcsync/_vendor/csync/backend/tools/feature-mapping/extract.mjs +806 -0
  91. localcsync/_vendor/csync/backend/tools/feature-mapping/keyboard-chords.mjs +211 -0
  92. localcsync/_vendor/csync/backend/tools/feature-mapping/package-lock.json +132 -0
  93. localcsync/_vendor/csync/backend/tools/feature-mapping/package.json +13 -0
  94. localcsync/cli.py +749 -0
  95. localcsync/docker_mode.py +351 -0
  96. localcsync/llm.py +138 -0
  97. localcsync/runtime.py +68 -0
  98. localcsync/verdicts.py +115 -0
@@ -0,0 +1,291 @@
1
+ """Running a validation on CodeBuild instead of on the worker that picked it up.
2
+
3
+ A large RL's validation builds a tens-of-gigabyte image and then runs it. On a worker
4
+ that work shares one 120 GB disk with every other job on the instance, and a deploy of
5
+ the fleet kills it outright -- an hour of build lost for a reason that has nothing to do
6
+ with the RL. Above ``validation.codebuild_min_gb`` the run moves to a CodeBuild machine
7
+ of its own, sized to the release (infra/modules/csync/codebuild-validate.tf).
8
+
9
+ It is the *same* ValidationEngine, not a second implementation of one: the build runs
10
+ the worker's own image and writes its checks to the same database and its live log to
11
+ the same Redis, so every check, every log line and every GitHub report is what it has
12
+ always been. Only the machine differs, and only above the threshold -- a validation
13
+ under it still runs here, exactly as before.
14
+
15
+ What this buys, beyond the disk: the build outlives the worker. The build id goes in
16
+ the job's lease checkpoint, so when a deploy stops the worker mid-run, the worker that
17
+ takes the job over rejoins the running build instead of starting the hour again. That
18
+ is the pattern the large Push to ECR builds already use
19
+ (services/image_builder/builders/codebuild.py).
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import logging
24
+ import os
25
+ from typing import Optional
26
+
27
+ from ..services.image_builder.builders import codebuild_api as api
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ #: Terraform names it <RESOURCE_PREFIX>-validate (infra/modules/csync/codebuild-validate.tf).
32
+ PROJECT = (os.getenv("CSYNC_VALIDATE_CODEBUILD_PROJECT")
33
+ or f"{os.getenv('RESOURCE_PREFIX') or 'csync'}-validate")
34
+
35
+ #: The engine's image, when this worker cannot work out its own (below).
36
+ IMAGE = os.getenv("CSYNC_VALIDATE_CODEBUILD_IMAGE", "")
37
+
38
+ #: A build that has not ended is one a run taking the job over can rejoin.
39
+ ALIVE = ("IN_PROGRESS", "SUCCEEDED")
40
+
41
+ #: Where the build id lives in the job's lease checkpoint.
42
+ CHECKPOINT_KEY = "validate_codebuild"
43
+
44
+
45
+ class CodeBuildUnavailable(RuntimeError):
46
+ """The validation could not be put on CodeBuild, so it runs here instead."""
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Whether this validation belongs on CodeBuild
51
+ # ---------------------------------------------------------------------------
52
+
53
+ def threshold_bytes() -> Optional[int]:
54
+ """Staged bytes at or above which a validation runs on CodeBuild; None keeps them all here.
55
+
56
+ Read per job rather than at import, so an admin changing it in Foundry changes where
57
+ the next validation runs without a deployment.
58
+ """
59
+ from ..runtime_settings import store
60
+ from ..runtime_settings.definitions import VALIDATE_ON_CODEBUILD
61
+
62
+ try:
63
+ value = store.get(VALIDATE_ON_CODEBUILD)
64
+ except Exception:
65
+ # A database blip must not change where a validation runs: keep it here, which is
66
+ # what every validation did before this existed.
67
+ logger.warning("Could not read %s; running this validation on the worker",
68
+ VALIDATE_ON_CODEBUILD.key, exc_info=True)
69
+ return None
70
+ if value is None or value.gb is None:
71
+ return None
72
+ return int(value.gb * 1024**3)
73
+
74
+
75
+ def release_bytes(db, job) -> int:
76
+ """How much this validation will stage from S3, without cloning anything.
77
+
78
+ Where a validation runs has to be settled before any work starts, and the only thing
79
+ known that early is the release: the pin the job already carries, or the one its branch
80
+ resolves to now. Resolving it reads the same S3 pointers the engine reads minutes later,
81
+ so this is the number the run will actually stage, not a guess at it.
82
+
83
+ It is the signal Push to ECR already routes on (services/image_builder/routing.py), and
84
+ for the RLs that drove this it is most of the image: Khan Academy's data.db alone is 86%
85
+ of theirs. It does not see a large *repository* -- rl_walmart's 31 GB of git history --
86
+ and a release that cannot be read at all reads as 0. Both keep the validation on the
87
+ worker, which is where every validation ran before this existed.
88
+ """
89
+ from ..config import get_settings
90
+ from ..db import SessionLocal
91
+ from ..models import Repository
92
+ from ..runtime_assets.models import AssetRelease
93
+ from ..runtime_assets.service import resolve_release
94
+ from .runtime_assets import storage_client
95
+
96
+ # Its own short session, ended here, never ``db``: resolving a release caches it, which
97
+ # locks the branch's asset channel (catalog.cache_release) until the transaction ends.
98
+ # In the job's session that lock outlived this check: the worker held it while it
99
+ # followed the CodeBuild validation, whose own staging waits for the same lock, so each
100
+ # waited for the other until the build timed out, and every upload, build and
101
+ # validation of the branch queued behind them for hours.
102
+ try:
103
+ with SessionLocal() as own:
104
+ release = None
105
+ pin = (job.build_config or {}).get("runtime_asset_release") or {}
106
+ if pin.get("release_id"):
107
+ # A retry stages the release its first run pinned, whatever the branch holds now.
108
+ release = own.get(AssetRelease, pin["release_id"])
109
+ if release is None:
110
+ repo = own.get(Repository, job.repository_id) if job.repository_id else None
111
+ if repo is None or repo.is_deleted:
112
+ return 0
113
+ settings = get_settings()
114
+ from ..runtime_assets import buckets
115
+ # Sizing only: a branch Foundry cannot read app.config for falls back
116
+ # to the default, and a miss here just runs the job on the worker.
117
+ try:
118
+ bucket = buckets.for_branch(repo, job.branch)["bucket"]
119
+ except Exception:
120
+ bucket = settings.artifacts_s3_bucket
121
+ release, _ = resolve_release(own, repo, job.branch, s3=storage_client(settings),
122
+ bucket=bucket,
123
+ # A branch with no release of its own is
124
+ # sized by main's, which is in main's
125
+ # bucket. Without this the lookup finds
126
+ # nothing, the size reads 0, and a release
127
+ # far too large for the worker is routed
128
+ # to it rather than to CodeBuild.
129
+ main_bucket=lambda: buckets.for_branch(
130
+ repo, 'main')['bucket'])
131
+ entries = ((release.manifest or {}).get("entries") or {}) if release is not None else {}
132
+ size = sum(int((item or {}).get("size") or 0) for item in entries.values())
133
+ own.commit() # keeps the cached release, and releases the channel lock now
134
+ return size
135
+ except Exception:
136
+ logger.warning("Could not size job %s's runtime assets; running it on the worker",
137
+ getattr(job, "id", "?"), exc_info=True)
138
+ return 0
139
+
140
+
141
+ def is_suite(job) -> bool:
142
+ """Whether this job is a multi-RL suite rather than a single RL, by the same name the
143
+ engine decides on (engine._is_multi_rl_suite) and before any clone."""
144
+ from .multi_rl import is_suite_name
145
+
146
+ name = (getattr(job, "repo_url", "") or "").rstrip("/").rsplit("/", 1)[-1]
147
+ return is_suite_name(name.removesuffix(".git"))
148
+
149
+
150
+ def wanted(db, job) -> Optional[tuple]:
151
+ """``(bytes, limit)`` when this validation belongs on CodeBuild, else None."""
152
+ limit = threshold_bytes()
153
+ if limit is None:
154
+ return None
155
+ if is_suite(job):
156
+ # A suite run reads MULTI_RL_SUITE_CHECKS, PERSONA_SEED_* and their like, which no
157
+ # Terraform sets: they reach a worker from docker/eb/worker/docker-compose.yml and
158
+ # the console, so this project cannot be given the deployment's values. Their code
159
+ # defaults are not the compose ones -- suite checks block by code and warn by
160
+ # compose -- so a suite moved here would fail check runs that pass on a worker.
161
+ # It is also not the case this exists for: a whole suite is 8-10 minutes against
162
+ # the quarter hour a single RL takes to build and boot its image (worker.py).
163
+ return None
164
+ staged = release_bytes(db, job)
165
+ return (staged, limit) if staged >= limit else None
166
+
167
+
168
+ # ---------------------------------------------------------------------------
169
+ # Starting, rejoining and following one
170
+ # ---------------------------------------------------------------------------
171
+
172
+ def running(lease) -> Optional[str]:
173
+ """The build a stopped run of this job left running, if it has not ended.
174
+
175
+ Asked before the job is reset for a rerun, by the worker taking it over and by recovery
176
+ alike -- so ``lease`` is either a held Lease or the JobLease row, which both carry the
177
+ checkpoint and the subject. That build is writing this job's checks right now, and
178
+ clearing them would delete its work while it was still doing it. So a build whose state
179
+ cannot be read counts as running: following a build that has in fact ended costs one more
180
+ poll, while starting a second engine against one job costs the job.
181
+ """
182
+ build_id = (lease.checkpoint or {}).get(CHECKPOINT_KEY)
183
+ if not build_id:
184
+ return None
185
+ try:
186
+ states = api.build_states([build_id])
187
+ except Exception:
188
+ logger.warning("Job %s: could not check on CodeBuild %s; following it",
189
+ lease.subject, build_id, exc_info=True)
190
+ return build_id
191
+ if states.get(build_id, ("",))[0] in ALIVE:
192
+ return build_id
193
+ logger.info("Job %s: CodeBuild %s did not finish; it runs again", lease.subject, build_id)
194
+ return None
195
+
196
+
197
+ _IMAGE: list = [] # worked out once per process
198
+
199
+
200
+ def worker_image() -> str:
201
+ """The image this worker runs, which the build runs the engine out of.
202
+
203
+ A validation must run the engine the worker following it is running -- a build of the
204
+ engine against a database its own release has already migrated past is not a validation
205
+ of anything. The deployment publishes one immutable tag per release and no moving one,
206
+ so there is nothing to look the current image up by; what there is, is this container,
207
+ and the machine's Docker socket it already works through. So it asks that: what image is
208
+ the container I am?
209
+
210
+ ``CSYNC_VALIDATE_CODEBUILD_IMAGE`` overrides it, for a deployment that would rather say.
211
+ """
212
+ if IMAGE:
213
+ return IMAGE
214
+ if not _IMAGE:
215
+ import socket
216
+ import subprocess
217
+
218
+ try:
219
+ found = subprocess.run(
220
+ ["docker", "inspect", "--format", "{{.Config.Image}}", socket.gethostname()],
221
+ capture_output=True, text=True, timeout=30, check=True).stdout.strip()
222
+ except Exception as exc:
223
+ raise CodeBuildUnavailable(f"Could not read this worker's own image: {exc}") from exc
224
+ if not found:
225
+ raise CodeBuildUnavailable("This worker's own image could not be read")
226
+ _IMAGE.append(found)
227
+ return _IMAGE[0]
228
+
229
+
230
+ def start(lease, job, staged_bytes: int) -> str:
231
+ """Start the build and record it in the lease, before following it."""
232
+ import boto3
233
+
234
+ variables = {
235
+ "VALIDATION_JOB_ID": str(job.id),
236
+ "VALIDATION_HOLDER": str(lease.holder or ""),
237
+ "VALIDATION_ATTEMPT": str(lease.attempt or 1),
238
+ "WORKER_IMAGE": worker_image(),
239
+ }
240
+ # Starting a build is the irreversible step here: a machine, and an engine writing this
241
+ # job's checks. A run that has lost its lease must not take either.
242
+ lease.ensure_held()
243
+ try:
244
+ client = boto3.client("codebuild", region_name=api.REGION)
245
+ response = client.start_build(
246
+ projectName=PROJECT,
247
+ computeTypeOverride=api.compute_type(staged_bytes),
248
+ environmentVariablesOverride=[
249
+ {"name": k, "value": v, "type": "PLAINTEXT"} for k, v in variables.items()
250
+ ],
251
+ )
252
+ except Exception as exc:
253
+ raise CodeBuildUnavailable(f"Could not start a CodeBuild validation: {exc}") from exc
254
+ build_id = response["build"]["id"]
255
+ # Saved before a single line of work, so a worker stopped in the next second still
256
+ # finds it rather than starting a second engine against the same job.
257
+ #
258
+ # Which is also why a failed save has to stop the build. The lease is the only record
259
+ # of it; without that row nothing will ever follow it, stop it, or know not to start a
260
+ # second one, and it holds a 2XLarge machine for the four hours its timeout allows.
261
+ try:
262
+ lease.save(**{CHECKPOINT_KEY: build_id})
263
+ except Exception:
264
+ try:
265
+ stop_build(build_id)
266
+ except Exception:
267
+ # Say so, but let the save's own failure be the one that is raised: it is the
268
+ # reason this run is ending, and the build may yet be stopped by its timeout.
269
+ logger.warning("Could not stop the unrecorded CodeBuild %s", build_id, exc_info=True)
270
+ raise
271
+ return build_id
272
+
273
+
274
+ def follow(job_id: str, build_id: str, log) -> None:
275
+ """Wait for the build. Raises api.BuildFailed if it does not succeed.
276
+
277
+ The engine inside it streams its own progress to the same Redis the UI reads, so the
278
+ build's log is not forwarded there as well; it goes to this worker's log, where it is
279
+ the record of what the machine itself did.
280
+ """
281
+ log(f"Running this validation on CodeBuild: {api.log_url(build_id)}")
282
+ api.follow_builds(
283
+ {"validate": build_id},
284
+ lambda lines, _a: [logger.info("[codebuild %s] %s", job_id, line) for line in lines],
285
+ )
286
+
287
+
288
+ def stop_build(build_id: str) -> None:
289
+ """Best-effort, for a job that has ended while its build has not: a build left running
290
+ against a failed job would go on writing to it and go on costing a 2XLarge machine."""
291
+ api.stop_builds([build_id])
@@ -0,0 +1,14 @@
1
+ """Runtime-config integrity checks for RL env repos.
2
+
3
+ config_yaml_check (code rules, rules.py) checks that config.yaml and config.schema.json
4
+ are present and schema-valid, that the mandatory keys and database_seed are set, and that
5
+ runtime values aren't read around the config: env reads outside the settings layer,
6
+ entrypoint exports that ignore config, and legacy app.config reads. The same commit
7
+ always gets the same verdict.
8
+
9
+ config_yaml_advisory (LLM, checker.py + prompt.py) looks for bypasses the rules can't
10
+ see: hardcoded runtime values, indirect env reads and second config sources. Findings
11
+ are code-verified and count only when all three calls agree; such a finding fails the job
12
+ (engine.CONFIG_ADVISORY_BLOCKING, False = warn only). It shares the naming audit's LLM config
13
+ (CSYNC_NAMING_AUDIT_LLM).
14
+ """
@@ -0,0 +1,170 @@
1
+ """Runtime-config verdicts: code rules decide, an LLM advisory adds what they can't see.
2
+
3
+ config_yaml_check run_rules() -> pass / warn / fail. Same commit, same verdict.
4
+ config_yaml_advisory run_advisory() -> pass / fail / skip; warn instead of fail when
5
+ engine.CONFIG_ADVISORY_BLOCKING is False.
6
+
7
+ The rules run first and synchronously, so their verdict never waits on, or depends on,
8
+ the model. The advisory is made as repeatable as an LLM can be:
9
+ 1. a narrow question with a closed rule list, given the rules' settled lines;
10
+ 2. every finding must quote its line, and code verifies the quote;
11
+ 3. ADVISORY_VOTES independent calls, and a finding counts only if every call agrees.
12
+ There is no verdict cache: every run, re-runs included, asks the model afresh, because a
13
+ cache would only replay the first answer, wrong or right.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from concurrent.futures import ThreadPoolExecutor
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Callable, Dict, List, Optional, Tuple
21
+
22
+ from .gather import LLMInput, gather
23
+ from .prompt import SYSTEM_PROMPT, build_schema, format_inputs, prompt_hash, verify
24
+ from .rules import Finding, RulesOutcome, SettledLine
25
+
26
+ Log = Callable[[str], None]
27
+
28
+ ADVISORY_VOTES = 3
29
+
30
+
31
+ @dataclass
32
+ class AdvisoryOutcome:
33
+ findings: List[Dict] = field(default_factory=list) # verified and agreed by every vote
34
+ unconfirmed: List[Dict] = field(default_factory=list)
35
+ dropped: int = 0
36
+ error: Optional[str] = None
37
+ skipped_reason: Optional[str] = None
38
+ provider: str = ""
39
+ model: str = ""
40
+ prompt_hash: str = ""
41
+ votes: int = 0
42
+ response_ids: List[str] = field(default_factory=list)
43
+
44
+
45
+ def _first(findings: List[Finding]) -> str:
46
+ f = findings[0]
47
+ return f"[{f.rule}] {f.where + ' ' if f.where else ''}{f.message}"
48
+
49
+
50
+ def rules_verdict(outcome: RulesOutcome) -> Tuple[str, str, List[str]]:
51
+ lines = []
52
+ for r in outcome.results:
53
+ mode = "enforced" if r.mode == "enforce" else "warn-only"
54
+ if r.status == "error":
55
+ lines.append(f"[RULE ERROR] {r.rule} ({mode}, not blocking): {r.error}")
56
+ elif r.status == "finding":
57
+ tag = "FAIL" if r.mode == "enforce" else "WARN"
58
+ lines += [f"[{tag}] {r.rule} ({mode}): {f.where + ' ' if f.where else ''}{f.message}" for f in r.findings]
59
+ elif r.status == "n/a":
60
+ lines.append(f"[N/A] {r.rule}: {r.not_applicable}")
61
+ else:
62
+ lines.append(f"[PASS] {r.rule}")
63
+
64
+ # The headline leads with the first finding: the GitHub summary keeps 200 chars.
65
+ blocking, warnings, errors = outcome.blocking, outcome.warnings, outcome.errors
66
+ if blocking:
67
+ return "fail", f"{len(blocking)} blocking runtime-config violation(s): {_first(blocking)}", lines
68
+ if warnings or errors:
69
+ bits = []
70
+ if warnings:
71
+ bits.append(f"{len(warnings)} warn-only finding(s): {_first(warnings)}")
72
+ if errors:
73
+ bits.append(f"{len(errors)} rule error(s): {', '.join(r.rule for r in errors)}")
74
+ return "warn", "Not blocking. " + "; ".join(bits), lines
75
+ return "pass", "Runtime-config rules passed: " + ", ".join(r.rule for r in outcome.results), lines
76
+
77
+
78
+ def advisory_verdict(a: AdvisoryOutcome, blocking: bool = False) -> Tuple[str, str, List[str]]:
79
+ if a.skipped_reason:
80
+ return "skip", a.skipped_reason, []
81
+ if a.error: # an LLM outage never fails a job, even when blocking
82
+ return "skip", f"advisory did not complete: {a.error}", []
83
+ meta = f"{a.provider}/{a.model}, prompt {a.prompt_hash}, {a.votes} votes"
84
+ lines = [f"[ADVISORY] {f['rule_id']} {f['file']}:{f['line']}"
85
+ f"{' (' + f['config_key'] + ')' if f.get('config_key') else ''}: {f['reason']}" for f in a.findings]
86
+ lines += [f"[UNCONFIRMED, ignored] {f['rule_id']} {f['file']}:{f['line']} ({f['votes']}/{a.votes} votes): "
87
+ f"{f['reason']}" for f in a.unconfirmed]
88
+ if a.findings:
89
+ f = a.findings[0]
90
+ prefix = "Advisory" if blocking else "Advisory, not blocking"
91
+ return ("fail" if blocking else "warn",
92
+ f"{prefix}: {len(a.findings)} config bypass(es) every vote agreed on: "
93
+ f"{f['rule_id']} {f['file']}:{f['line']} {f['reason']} ({meta})", lines)
94
+ return "pass", f"Advisory: no config bypasses found ({meta})", lines
95
+
96
+
97
+ def _same_place(a: Dict, b: Dict) -> bool:
98
+ return a["file"] == b["file"] and abs(int(a["line"]) - int(b["line"])) <= 2
99
+
100
+
101
+ def _agree(votes: List[List[Dict]]) -> Tuple[List[Dict], List[Dict]]:
102
+ agreed: List[Dict] = []
103
+ for f in votes[0]:
104
+ if all(any(_same_place(f, g) for g in v) for v in votes[1:]) and not any(_same_place(f, a) for a in agreed):
105
+ agreed.append(f)
106
+ partial: List[Dict] = []
107
+ for v in votes:
108
+ for f in v:
109
+ if any(_same_place(f, a) for a in agreed) or any(_same_place(f, p) for p in partial):
110
+ continue
111
+ partial.append({**f, "votes": sum(any(_same_place(f, g) for g in w) for w in votes)})
112
+ return agreed, partial
113
+
114
+
115
+ def _one_vote(provider: str, model: str, api_key: str, user: str, inp: LLMInput,
116
+ settled: List[SettledLine]) -> Tuple[List[Dict], int, Optional[str]]:
117
+ from ..naming_audit.providers import get_provider
118
+ prov = get_provider(provider, model, api_key) # one per vote so last_response_id isn't shared
119
+ payload = prov.run(SYSTEM_PROMPT, build_schema(), user)
120
+ if not isinstance(payload, dict) or not isinstance(payload.get("findings"), list):
121
+ raise ValueError("model output had no findings list")
122
+ kept, dropped = [], 0
123
+ for f in payload["findings"]:
124
+ ok, _why, fixed = verify(f, inp, settled)
125
+ if ok:
126
+ kept.append(fixed)
127
+ else:
128
+ dropped += 1
129
+ return kept, dropped, prov.last_response_id
130
+
131
+
132
+ def run_advisory(repo_path: Path, rules: RulesOutcome, provider: str, model: str, api_key: str,
133
+ log: Optional[Log] = None, scope=None) -> AdvisoryOutcome:
134
+ def _log(m: str) -> None:
135
+ if log:
136
+ try:
137
+ log(m)
138
+ except Exception:
139
+ pass
140
+
141
+ votes = ADVISORY_VOTES
142
+ out = AdvisoryOutcome(provider=provider, model=model, votes=votes)
143
+ if not rules.config_present:
144
+ out.skipped_reason = "no config.yaml at the repo root (config_yaml_check reports it)"
145
+ return out
146
+
147
+ inp = gather(Path(repo_path), scope)
148
+ user = format_inputs(inp, rules.settled)
149
+ out.prompt_hash = prompt_hash(user, model)
150
+ _log(f"config_yaml_advisory: {len(inp.files)} file(s), {len(inp.skipped)} skipped, "
151
+ f"prompt {out.prompt_hash}, {votes} vote(s) via {provider}/{model}")
152
+ if inp.skipped:
153
+ _log(f"config_yaml_advisory: skipped {', '.join(inp.skipped[:10])}"
154
+ + (f" and {len(inp.skipped) - 10} more" if len(inp.skipped) > 10 else ""))
155
+
156
+ try:
157
+ with ThreadPoolExecutor(max_workers=votes) as pool:
158
+ results = list(pool.map(lambda _i: _one_vote(provider, model, api_key, user, inp, rules.settled),
159
+ range(votes)))
160
+ except Exception as exc:
161
+ out.error = f"{type(exc).__name__}: {str(exc)[:300]}"
162
+ return out
163
+
164
+ out.findings, out.unconfirmed = _agree([kept for kept, _, _ in results])
165
+ out.dropped = sum(d for _, d, _ in results)
166
+ out.response_ids = [rid for _, _, rid in results if rid]
167
+ _log(f"config_yaml_advisory: {len(out.findings)} finding(s) all {votes} votes agree on, "
168
+ f"{len(out.unconfirmed)} unconfirmed, {out.dropped} dropped by verification, "
169
+ f"responses {', '.join(out.response_ids) or 'n/a'}")
170
+ return out
@@ -0,0 +1,72 @@
1
+ """Collect the code the LLM advisory reads.
2
+
3
+ Only the advisory uses this; the deterministic rules scan the repo themselves. The walk
4
+ is sorted, so the same commit always yields the same input and the same prompt hash.
5
+ Symlinks and minified bundles are skipped (a 772 KB redoc bundle once made up 84% of the
6
+ prompt), every file is capped at MAX_LINES_PER_FILE, and the total cap is checked before
7
+ a file is added, never after.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass, field
13
+ from pathlib import Path
14
+ from typing import List, Optional, Tuple
15
+
16
+ from ..file_scope import Scope, scope as file_scope
17
+ from .rules import read_repo_file, repo_file
18
+
19
+ EXTENSIONS = {".py", ".ts", ".tsx", ".js"}
20
+ CORE = ["backend/app/runtime_config.py", "backend/app/config.py"]
21
+
22
+ RUNTIME_RE = re.compile(
23
+ r"runtime_config|config\.yaml|app\.config|current_user|user_id|app_url|project_name"
24
+ r"|auth_key|auth_keys|basic_auth|current_date|frozen.?date|database_seed|os\.getenv"
25
+ r"|os\.environ|getenv",
26
+ re.IGNORECASE,
27
+ )
28
+
29
+ MAX_LINE_CHARS = 1_000 # longer means minified
30
+ MAX_LINES_PER_FILE = 400
31
+ MAX_TOTAL_CHARS = 200_000
32
+
33
+
34
+ @dataclass
35
+ class LLMInput:
36
+ files: List[Tuple[str, List[str]]] = field(default_factory=list)
37
+ skipped: List[str] = field(default_factory=list)
38
+ config_yaml: str = ""
39
+
40
+
41
+ def _minified(name: str, raw: str) -> bool:
42
+ return name.endswith(".min.js") or max((len(x) for x in raw.splitlines()), default=0) > MAX_LINE_CHARS
43
+
44
+
45
+ def gather(repo_path: Path, scope: Optional[Scope] = None) -> LLMInput:
46
+ root = Path(repo_path)
47
+ config_yaml = read_repo_file(root, root / "config.yaml").splitlines()[:MAX_LINES_PER_FILE]
48
+ out = LLMInput(config_yaml="\n".join(config_yaml))
49
+ total = 0
50
+ candidates = [root / rel for rel in CORE]
51
+ for p in (scope or file_scope("config_yaml_advisory")).walk(root):
52
+ if p.suffix in EXTENSIONS and str(p.relative_to(root)) not in CORE:
53
+ candidates.append(p)
54
+
55
+ for p in candidates:
56
+ rel = str(p.relative_to(root))
57
+ if p.is_symlink() or not repo_file(root, p):
58
+ continue
59
+ raw = read_repo_file(root, p)
60
+ if rel not in CORE and not RUNTIME_RE.search(raw):
61
+ continue
62
+ if _minified(p.name, raw):
63
+ out.skipped.append(f"{rel} (minified)")
64
+ continue
65
+ lines = raw.splitlines()[:MAX_LINES_PER_FILE]
66
+ size = sum(len(x) + 1 for x in lines)
67
+ if total + size > MAX_TOTAL_CHARS:
68
+ out.skipped.append(f"{rel} (total size cap)")
69
+ continue
70
+ out.files.append((rel, lines))
71
+ total += size
72
+ return out
@@ -0,0 +1,121 @@
1
+ """LLM contract for config_yaml_advisory: a narrow question with a closed rule list.
2
+
3
+ The model is shown the lines the deterministic rules already decided (SETTLED FACTS) and
4
+ asked only about bypasses those rules can't see. Every finding must quote its line;
5
+ verify() drops any finding without a reason, whose quote isn't on that line, that points
6
+ at a settled line, or that cites a file the model wasn't shown (such as the entrypoint).
7
+
8
+ Measured on 5 RL repos + 8 planted violations (gpt-5.5, 98 calls): 0 findings on the good
9
+ repos, every planted violation found at its exact line. checker.py's 3-vote agreement
10
+ builds on these single-call numbers.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import re
16
+ from typing import Dict, List, Tuple
17
+
18
+ from .gather import LLMInput
19
+ from .rules import SettledLine
20
+
21
+ PROMPT_VERSION = "advisory-v1"
22
+ RULE_IDS = ["H1", "H2", "H3"]
23
+ MAX_REASON_CHARS = 300
24
+
25
+ SYSTEM_PROMPT = """You audit ONE RL environment repository for ONE thing: places where a RUNTIME VALUE bypasses the repo's config. Report a finding only when you are certain. An empty findings list is the expected answer for a well-behaved repo.
26
+
27
+ RUNTIME VALUES and their config.yaml keys:
28
+ - logged-in user id: apps.<app>.login.user_id (code should use settings.current_user_id)
29
+ - public app URL: apps.<app>.app_url (settings.app_url)
30
+ - project name: project_name (settings.project_name)
31
+ - basic-auth switch and keys: basic_auth.enabled, basic_auth.keys
32
+ - frozen current date: apps.<app>.reference_current_timestamp
33
+ - control hub URL: control_hub_url
34
+ - seed database: apps.<app>.database_seed
35
+
36
+ THE CONTRACT: these values come from config.yaml through backend/app/runtime_config.py (cfg_* accessors) and reach application code through the Settings object in backend/app/config.py, which may also accept environment-variable overrides. All other application code must use settings.* or cfg_*.
37
+
38
+ Report a finding ONLY if it matches exactly one of these rules:
39
+ H1 hardcoded_primary: a literal (number, string, URL, name) does the job of a runtime value on a code path that runs in the app (API handlers, services, URL building, middleware, MCP tools) instead of settings.* / cfg_*. Examples: get_account(db, 1) for the current user; return "http://localhost:3000" for the app URL; title="acme" for the project name.
40
+ H2 indirect_env: a runtime value is read from the process environment OUTSIDE backend/app/config.py and backend/app/runtime_config.py through an indirection: a helper or wrapper around os.environ / os.getenv, an aliased import of environ, or a copied environment mapping. Report the line where the runtime value's variable name is used.
41
+ H3 second_source: a runtime value is read from a file or store other than config.yaml-through-runtime_config.py, e.g. package.json, another JSON/YAML/INI file, a database row used as configuration, or config.yaml opened directly outside runtime_config.py.
42
+
43
+ NEVER report:
44
+ - any line listed in SETTLED FACTS (code has already decided it);
45
+ - defaults and fallbacks: default= / default_factory= in Settings, default arguments of cfg_* accessors, `<settings or cfg value> or <literal>`;
46
+ - direct os.environ / os.getenv / process.env reads, and docker/start.sh (code checks both);
47
+ - seed data, migrations, fixtures, tests, grader code, or scripts that are not part of the running app;
48
+ - comments, docstrings, log or print messages, OpenAPI examples= / description= / summary= text;
49
+ - anything that is not one of the RUNTIME VALUES above.
50
+
51
+ For each finding give: rule_id; file (exactly as written in its ----- header -----); line (the number printed before the code); quote (the code on that line copied exactly, without the line number); config_key; reason (one sentence)."""
52
+
53
+
54
+ def build_schema() -> Dict:
55
+ return {
56
+ "type": "object", "additionalProperties": False, "required": ["findings"],
57
+ "properties": {"findings": {"type": "array", "items": {
58
+ "type": "object", "additionalProperties": False,
59
+ "required": ["rule_id", "file", "line", "quote", "config_key", "reason"],
60
+ "properties": {
61
+ "rule_id": {"type": "string", "enum": RULE_IDS},
62
+ "file": {"type": "string"}, "line": {"type": "integer"}, "quote": {"type": "string"},
63
+ "config_key": {"type": "string"}, "reason": {"type": "string"},
64
+ }}}},
65
+ }
66
+
67
+
68
+ def format_inputs(inp: LLMInput, settled: List[SettledLine]) -> str:
69
+ shown = {rel for rel, _ in inp.files}
70
+ parts = ["===== SETTLED FACTS (decided by code; never report these lines) ====="]
71
+ facts = [s for s in settled if s.file in shown]
72
+ parts += [f"- {s.file}:{s.line}{'-' + str(s.end) if s.end != s.line else ''} {s.what} => {s.decided}"
73
+ for s in facts] or ["(none)"]
74
+ parts.append("\n===== config.yaml =====")
75
+ parts += [f"{i:>4} {ln}" for i, ln in enumerate(inp.config_yaml.splitlines(), 1)] or ["(absent)"]
76
+ parts.append("\n===== CODE FILES =====")
77
+ for rel, lines in inp.files:
78
+ parts.append(f"\n----- {rel} -----")
79
+ parts += [f"{i:>4} {ln}" for i, ln in enumerate(lines, 1)]
80
+ return "\n".join(parts)
81
+
82
+
83
+ def prompt_hash(user_text: str, model: str) -> str:
84
+ return hashlib.sha256(f"{PROMPT_VERSION}\0{model}\0{SYSTEM_PROMPT}\0{user_text}".encode()).hexdigest()[:16]
85
+
86
+
87
+ def _norm(s: str) -> str:
88
+ return re.sub(r"\s+", " ", s).strip()
89
+
90
+
91
+ def verify(finding: Dict, inp: LLMInput, settled: List[SettledLine]) -> Tuple[bool, str, Dict]:
92
+ if not isinstance(finding, dict):
93
+ return False, "finding is not an object", {}
94
+ f = dict(finding)
95
+ rel = str(f.get("file", ""))
96
+ reason = f.get("reason")
97
+ if not isinstance(reason, str) or not reason.strip():
98
+ return False, "reason is missing", f
99
+ f["reason"] = _norm(reason)[:MAX_REASON_CHARS] # it is shown in the check message
100
+ f["config_key"] = str(f.get("config_key") or "")
101
+ quote = _norm(str(f.get("quote", "")))
102
+ try:
103
+ line = int(f.get("line", 0))
104
+ except (TypeError, ValueError):
105
+ return False, "line is not a number", f
106
+ if f.get("rule_id") not in RULE_IDS:
107
+ return False, "unknown rule id", f
108
+ lines = dict(inp.files).get(rel)
109
+ if lines is None:
110
+ return False, "file was not in the input", f
111
+ if len(quote) < 6:
112
+ return False, "quote too short to verify", f
113
+ hit = next((n for n in (line, line - 1, line + 1, line - 2, line + 2)
114
+ if 1 <= n <= len(lines) and quote in _norm(lines[n - 1])), None)
115
+ if hit is None:
116
+ return False, "quote is not on the cited line", f
117
+ f["line"] = hit
118
+ if any(s.file == rel and s.line - 1 <= hit <= s.end + 1 for s in settled):
119
+ return False, "line is already decided by a code rule", f
120
+ return True, "ok", f
121
+