File size: 15,857 Bytes
c373be7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f239372
c373be7
2a7e750
 
 
 
 
 
2c1b7e7
2a7e750
c373be7
 
 
 
 
 
 
19aab86
c373be7
19aab86
c373be7
19aab86
c373be7
 
 
19aab86
c373be7
19aab86
c373be7
19aab86
c373be7
 
 
19aab86
c373be7
19aab86
c373be7
19aab86
c373be7
19aab86
c373be7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a7e750
 
 
 
 
 
 
 
 
 
 
 
 
 
cad04d1
 
2a7e750
 
 
cad04d1
 
 
c373be7
 
4751562
c373be7
 
 
2a7e750
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
 
 
 
 
 
 
 
 
 
c373be7
 
 
 
 
 
 
 
 
4eef289
c373be7
 
 
81b05f3
 
c373be7
 
2c1b7e7
4751562
cad04d1
f239372
 
 
 
 
 
 
 
 
c373be7
 
 
d69eb01
 
 
 
c373be7
2c1b7e7
 
 
 
 
 
 
6121445
 
 
 
 
 
 
 
 
 
 
 
 
 
2c1b7e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c373be7
2c1b7e7
 
 
 
 
 
 
 
 
 
 
c373be7
2c1b7e7
 
 
 
 
 
 
 
 
 
 
c373be7
2c1b7e7
 
 
 
 
 
c373be7
 
2c1b7e7
 
 
 
 
 
 
 
 
 
4751562
2c1b7e7
c373be7
2c1b7e7
 
c373be7
2c1b7e7
19aab86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c1b7e7
4eef289
6121445
 
 
 
 
 
 
 
 
 
 
 
4eef289
c373be7
 
2c1b7e7
c373be7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c1b7e7
c373be7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cad04d1
c373be7
 
cad04d1
 
 
 
c373be7
 
 
 
 
 
 
 
 
 
 
 
cad04d1
 
 
 
 
 
 
 
 
 
c373be7
 
 
 
 
 
 
 
2c1b7e7
 
c373be7
 
 
 
2a7e750
 
 
 
 
 
 
 
 
f239372
 
 
 
 
 
 
 
 
 
 
 
 
 
c373be7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c1b7e7
c373be7
2c1b7e7
 
 
 
c373be7
 
 
 
 
 
 
 
 
 
 
f239372
 
 
 
 
4eef289
 
 
 
 
c373be7
 
 
 
 
4eef289
 
 
c373be7
f239372
2a7e750
f239372
c373be7
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
"""Run local checks that mirror the required GitHub PR gates.

This is intentionally conservative: it uses the same path classifier as
`.github/workflows/test.yml`, runs the local equivalents of required jobs, and
prints any CI-only coverage that cannot be reproduced on the current OS.
"""

from __future__ import annotations

import argparse
from dataclasses import dataclass
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time

REPO_ROOT = Path(__file__).resolve().parents[1]
if str(REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(REPO_ROOT))

from scripts.ci_classifier import classify_paths  # noqa: E402
from scripts.ci_no_test_policy import evaluate_policy  # noqa: E402

PUBLIC_DOCS_TRACKER_TESTS = (
    "src/tests/test_bug_smoke_tracker.py",
    "src/tests/test_feature_user_story_tracker.py",
    "src/tests/test_dashboard_user_story_tracker.py",
    "src/tests/test_toolbox_cli.py",
)
PROFILE_CHOICES = ("smoke", "pr", "full")


GRAPH_VALIDATE_ARGS = (
    "src/validate_graph_artifacts.py",
    "--graph-dir",
    "graph",
    "--deep",
    "--min-nodes",
    "79000",
    "--min-edges",
    "1700000",
    "--min-skills-sh-nodes",
    "67000",
    "--min-semantic-edges",
    "1000000",
    "--expected-nodes",
    "79958",
    "--expected-edges",
    "1778069",
    "--expected-semantic-edges",
    "1088763",
    "--expected-harness-nodes",
    "207",
    "--expected-skills-sh-nodes",
    "67028",
    "--expected-skills-sh-catalog-entries",
    "67024",
    "--expected-skills-sh-converted",
    "67024",
    "--expected-skill-pages",
    "68494",
    "--expected-agent-pages",
    "467",
    "--expected-mcp-pages",
    "10790",
    "--expected-harness-pages",
    "207",
    "--line-threshold",
    "180",
    "--max-stage-lines",
    "40",
)


@dataclass(frozen=True)
class Check:
    name: str
    argv: tuple[str, ...]
    env: dict[str, str] | None = None


def _run_git(args: list[str], *, allow_failure: bool = False) -> list[str]:
    proc = subprocess.run(
        ["git", *args],
        check=False,
        capture_output=True,
        text=True,
    )
    if proc.returncode != 0:
        if allow_failure:
            return []
        raise RuntimeError(proc.stderr.strip() or proc.stdout.strip())
    return [line.strip() for line in proc.stdout.splitlines() if line.strip()]


def _run_git_text(args: list[str], *, allow_failure: bool = False) -> str:
    proc = subprocess.run(
        ["git", *args],
        check=False,
        capture_output=True,
        text=True,
    )
    if proc.returncode != 0:
        if allow_failure:
            return ""
        raise RuntimeError(proc.stderr.strip() or proc.stdout.strip())
    return proc.stdout


def _diff_base(base_ref: str, head_ref: str = "HEAD") -> str:
    merge_base = _run_git(["merge-base", base_ref, head_ref], allow_failure=True)
    return merge_base[0] if merge_base else base_ref


def changed_files(base_ref: str, *, head_ref: str = "HEAD") -> list[str]:
    base = _diff_base(base_ref, head_ref)
    paths = set(_run_git(["diff", "--name-only", base, head_ref], allow_failure=True))
    paths.update(_run_git(["diff", "--name-only"], allow_failure=True))
    paths.update(_run_git(["diff", "--cached", "--name-only"], allow_failure=True))
    paths.update(_run_git(["ls-files", "--others", "--exclude-standard"], allow_failure=True))
    return sorted(path.replace("\\", "/") for path in paths)


def _diffs_for_files(base_ref: str, files: list[str]) -> dict[str, str]:
    base = _diff_base(base_ref)
    diffs: dict[str, str] = {}
    for path in files:
        parts = (
            _run_git_text(["diff", "--unified=0", base, "HEAD", "--", path], allow_failure=True),
            _run_git_text(["diff", "--cached", "--unified=0", "--", path], allow_failure=True),
            _run_git_text(["diff", "--unified=0", "--", path], allow_failure=True),
        )
        diff_text = "\n".join(part for part in parts if part)
        if diff_text:
            diffs[path] = diff_text
    return diffs


def _run_whitespace_check(base_ref: str) -> int:
    base = _diff_base(base_ref)
    commands = (
        ["diff", "--check", base, "HEAD"],
        ["diff", "--cached", "--check"],
        ["diff", "--check"],
    )
    for args in commands:
        proc = subprocess.run(["git", *args], check=False)
        if proc.returncode != 0:
            return proc.returncode
    return 0


def select_checks(
    *,
    base_ref: str,
    files: list[str],
    profile: str,
    python: str,
) -> tuple[list[Check], list[str]]:
    flags = classify_paths(files)
    checks: list[Check] = [
        Check("whitespace", (python, __file__, "--base", base_ref, "--internal-whitespace")),
        Check("repo stats", (python, "src/update_repo_stats.py", "--check")),
    ]
    notes = [
        "GitHub runs Linux/macOS matrix jobs; local preflight covers the same "
        "contracts on this host."
    ]

    smoke_profile = profile == "smoke"
    source_required = profile == "full" or (not flags["docs_only"] and not flags["graph_only"])
    package_required = profile == "full" or flags["package_changed"]
    policy_required = not flags["docs_only"] and not flags["graph_only"]
    if policy_required:
        checks.append(
            Check(
                "no-test policy",
                (python, __file__, "--base", base_ref, "--internal-no-test-policy"),
            )
        )

    if source_required:
        checks.extend(
            [
                Check(
                    "ruff format",
                    (python, "-m", "ruff", "format", "--check", "src", "hooks", "scripts"),
                ),
                Check("ruff", (python, "-m", "ruff", "check", "src", "hooks", "scripts")),
            ]
        )
        if not smoke_profile:
            checks.extend(
                [
                    Check("mypy", (python, "-m", "mypy", "src")),
                    Check("pip check", (python, "-m", "pip", "check")),
                    Check(
                        "hydrate benchmark catalog",
                        (
                            python,
                            "scripts/graph_release_manifest.py",
                            "hydrate",
                            "--manifest",
                            "graph/release-artifacts.json",
                            "--repo-root",
                            ".",
                            "--artifact",
                            "graph/wiki-graph-runtime.tar.gz",
                        ),
                    ),
                    Check(
                        "unit-linux equivalent",
                        (
                            python,
                            "-m",
                            "pytest",
                            "-q",
                            "-m",
                            "not browser and not integration",
                            "--cov=src",
                            "--cov-report=term-missing",
                            "--cov-fail-under=40",
                            "-n",
                            "auto",
                            "--dist=loadfile",
                            "--max-worker-restart=0",
                        ),
                    ),
                    Check(
                        "A-Z canary",
                        (
                            python,
                            "-m",
                            "pytest",
                            "-q",
                            "--no-cov",
                            "src/tests/test_alive_loop_e2e.py",
                            "src/tests/test_fuzz_yaml_rendering.py",
                        ),
                    ),
                    Check(
                        "contract compatibility local",
                        (
                            python,
                            "-m",
                            "pytest",
                            "-q",
                            "--no-cov",
                            "src/tests/test_clean_host_contract.py",
                            "src/tests/test_package_scaffold.py",
                        ),
                    ),
                    Check(
                        "clean host contract",
                        (python, "scripts/clean_host_contract.py", "--fast"),
                    ),
                ]
            )

    if flags["docs_changed"]:
        checks.append(
            Check(
                "public docs tracker",
                (
                    python,
                    "-m",
                    "pytest",
                    "-q",
                    "--no-cov",
                    *PUBLIC_DOCS_TRACKER_TESTS,
                ),
            )
        )
        if not smoke_profile:
            checks.append(Check("docs strict build", (python, "-m", "mkdocs", "build", "--strict")))

    if not smoke_profile and (profile == "full" or flags["telemetry_changed"]):
        checks.append(
            Check(
                "telemetry enterprise",
                (
                    python,
                    "-m",
                    "pytest",
                    "-q",
                    "--no-cov",
                    "src/tests/test_enterprise_telemetry.py",
                    "src/tests/test_harness_cli_run.py",
                    "-k",
                    "telemetry or runtime_lifecycle",
                ),
            )
        )

    if not smoke_profile and flags["graph_artifact_changed"]:
        checks.append(
            Check(
                "hydrate graph release assets",
                (
                    python,
                    "scripts/graph_release_manifest.py",
                    "hydrate",
                    "--manifest",
                    "graph/release-artifacts.json",
                    "--repo-root",
                    ".",
                ),
            )
        )
        checks.append(Check("graph artifact validation", (python, *GRAPH_VALIDATE_ARGS)))

    if not smoke_profile and source_required and flags["similarity_changed"]:
        checks.append(
            Check(
                "similarity precision/recall",
                (
                    python,
                    "-m",
                    "pytest",
                    "-q",
                    "--no-cov",
                    "-m",
                    "integration",
                    "src/tests/test_similarity_precision_recall.py",
                ),
                env={"CTX_REQUIRE_SIMILARITY_EVAL": "1"},
            )
        )

    if not smoke_profile and source_required and flags["browser_changed"]:
        checks.append(
            Check(
                "browser monitor security",
                (
                    python,
                    "-m",
                    "pytest",
                    "-q",
                    "--no-cov",
                    "-m",
                    "browser",
                    "src/tests/test_ctx_monitor_browser.py",
                ),
            )
        )

    if not smoke_profile and package_required:
        out_dir = ".ci-preflight-dist"
        twine_script = (
            "import subprocess, sys; from pathlib import Path; "
            "from scripts.build_reproducible_dist import verified_artifact_paths; "
            f"files=verified_artifact_paths(Path({out_dir!r})); "
            "sys.exit(subprocess.call("
            "[sys.executable, '-m', 'twine', 'check', *files]))"
        )
        checks.extend(
            [
                Check(
                    "clean preflight dist",
                    (
                        python,
                        "-c",
                        f"import shutil; shutil.rmtree({out_dir!r}, ignore_errors=True)",
                    ),
                ),
                Check(
                    "build wheel",
                    (
                        python,
                        "scripts/build_reproducible_dist.py",
                        "--verify",
                        "--output-dir",
                        out_dir,
                    ),
                ),
                Check("twine check", (python, "-c", twine_script)),
            ]
        )

    if files:
        notes.insert(0, f"Changed files vs {base_ref}: {len(files)}")
    else:
        notes.insert(0, "No changed files detected; running baseline cheap checks only.")
    if smoke_profile:
        notes.append("Smoke profile skips slow PR gates; run --profile pr before no-mistakes/PR.")

    return checks, notes


def _run_no_test_policy_for_files(
    files: list[str],
    *,
    base_ref: str = "origin/main",
    diffs_by_file: dict[str, str] | None = None,
) -> int:
    if diffs_by_file is None:
        diffs_by_file = _diffs_for_files(base_ref, files)
    result = evaluate_policy(files, (), diffs_by_file)
    print(result.message)
    if result.contract_files:
        print("Contract files:")
        print("\n".join(result.contract_files))
    if result.test_files:
        print("Test files:")
        print("\n".join(result.test_files))
    if not result.passed:
        print("::error::Policy violation - contract files changed but no tests changed.")
        print("Fix: add/update tests, or use release metadata-only changes.")
        return 1
    return 0


def run_checks(checks: list[Check], *, dry_run: bool) -> int:
    for index, check in enumerate(checks, start=1):
        print(f"[{index}/{len(checks)}] {check.name}: {' '.join(check.argv)}", flush=True)
        if dry_run:
            continue
        env = os.environ.copy()
        if check.env:
            env.update(check.env)
        start = time.monotonic()
        proc = subprocess.run(check.argv, check=False, env=env)
        elapsed = time.monotonic() - start
        if proc.returncode != 0:
            print(
                f"[fail] {check.name} exited {proc.returncode} after {elapsed:.1f}s",
                file=sys.stderr,
            )
            return proc.returncode
        print(f"[pass] {check.name} in {elapsed:.1f}s", flush=True)
    return 0


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--base",
        default="origin/main",
        help="base ref for changed-file detection",
    )
    parser.add_argument(
        "--profile",
        choices=PROFILE_CHOICES,
        default="pr",
        help=(
            "smoke runs cheap first-pass checks; pr mirrors required PR checks; "
            "full forces source gates for any change set"
        ),
    )
    parser.add_argument(
        "--python",
        default=sys.executable,
        help="Python executable to run checks with",
    )
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="print selected checks without running them",
    )
    parser.add_argument(
        "--internal-no-test-policy",
        action="store_true",
        help=argparse.SUPPRESS,
    )
    parser.add_argument(
        "--internal-whitespace",
        action="store_true",
        help=argparse.SUPPRESS,
    )
    args = parser.parse_args(argv)

    if not shutil.which("git"):
        raise SystemExit("git is required for ci_preflight")

    if args.internal_whitespace:
        return _run_whitespace_check(args.base)

    files = changed_files(args.base)
    if args.internal_no_test_policy:
        return _run_no_test_policy_for_files(files, base_ref=args.base)

    checks, notes = select_checks(
        base_ref=args.base,
        files=files,
        profile=args.profile,
        python=args.python,
    )
    for note in notes:
        print(f"[note] {note}")
    return run_checks(checks, dry_run=args.dry_run)


if __name__ == "__main__":
    raise SystemExit(main())