second-source 0.5.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 (71) hide show
  1. second_source/__init__.py +3 -0
  2. second_source/action/__init__.py +4 -0
  3. second_source/action/commands.py +88 -0
  4. second_source/action/event.py +89 -0
  5. second_source/action/inputs.py +118 -0
  6. second_source/action/main.py +203 -0
  7. second_source/action/publish.py +184 -0
  8. second_source/action/setup.py +143 -0
  9. second_source/action/sweep.py +85 -0
  10. second_source/action/wait.py +49 -0
  11. second_source/benchmark/__init__.py +1 -0
  12. second_source/benchmark/aidev.py +248 -0
  13. second_source/benchmark/aidev_local.py +85 -0
  14. second_source/benchmark/golden.py +314 -0
  15. second_source/benchmark/redact.py +45 -0
  16. second_source/benchmark/rescore.py +388 -0
  17. second_source/benchmark/runner.py +159 -0
  18. second_source/benchmark/sample.py +243 -0
  19. second_source/benchmark/stats.py +363 -0
  20. second_source/cli/__init__.py +1 -0
  21. second_source/cli/bench.py +427 -0
  22. second_source/cli/main.py +182 -0
  23. second_source/core/__init__.py +4 -0
  24. second_source/core/aggregate.py +102 -0
  25. second_source/core/checks.py +470 -0
  26. second_source/core/engine.py +98 -0
  27. second_source/core/evidence.py +29 -0
  28. second_source/core/expr.py +206 -0
  29. second_source/core/hashing.py +41 -0
  30. second_source/core/model.py +112 -0
  31. second_source/core/pack.py +156 -0
  32. second_source/packs/__init__.py +1 -0
  33. second_source/packs/coding/__init__.py +16 -0
  34. second_source/packs/coding/checks/ci_config_caution.yaml +23 -0
  35. second_source/packs/coding/checks/ci_result.yaml +133 -0
  36. second_source/packs/coding/checks/ci_weakening_caution.yaml +27 -0
  37. second_source/packs/coding/checks/deployed.yaml +36 -0
  38. second_source/packs/coding/checks/docs_updated.yaml +22 -0
  39. second_source/packs/coding/checks/fixes_issue.yaml +58 -0
  40. second_source/packs/coding/checks/fixes_issue_durable.yaml +60 -0
  41. second_source/packs/coding/checks/integrity_guard.yaml +34 -0
  42. second_source/packs/coding/checks/integrity_inspection.yaml +21 -0
  43. second_source/packs/coding/checks/lint_caution.yaml +22 -0
  44. second_source/packs/coding/checks/matching_jobs_caution.yaml +22 -0
  45. second_source/packs/coding/checks/not_reverted.yaml +38 -0
  46. second_source/packs/coding/checks/tests_added.yaml +25 -0
  47. second_source/packs/coding/checks/tests_added_guard.yaml +26 -0
  48. second_source/packs/coding/checks/tests_removed_caution.yaml +23 -0
  49. second_source/packs/coding/detection.py +94 -0
  50. second_source/packs/coding/diff_facts.py +665 -0
  51. second_source/packs/coding/extract.py +911 -0
  52. second_source/packs/coding/functions.py +241 -0
  53. second_source/packs/coding/pack.yaml +33 -0
  54. second_source/packs/coding/trusted_rules.yaml +50 -0
  55. second_source/pipeline.py +112 -0
  56. second_source/report/__init__.py +1 -0
  57. second_source/report/render.py +503 -0
  58. second_source/sources/__init__.py +1 -0
  59. second_source/sources/github/__init__.py +4 -0
  60. second_source/sources/github/auth.py +48 -0
  61. second_source/sources/github/cache.py +67 -0
  62. second_source/sources/github/client.py +261 -0
  63. second_source/sources/github/mappers.py +454 -0
  64. second_source/sources/github/source.py +385 -0
  65. second_source/sources/github/urls.py +51 -0
  66. second_source-0.5.0.dist-info/METADATA +311 -0
  67. second_source-0.5.0.dist-info/RECORD +71 -0
  68. second_source-0.5.0.dist-info/WHEEL +4 -0
  69. second_source-0.5.0.dist-info/entry_points.txt +2 -0
  70. second_source-0.5.0.dist-info/licenses/LICENSE +202 -0
  71. second_source-0.5.0.dist-info/licenses/NOTICE +9 -0
@@ -0,0 +1,241 @@
1
+ """Helper functions the coding pack's checks can call from their expressions.
2
+
3
+ They classify CI job names (is this a test job?) and file paths (is this a test file?).
4
+ All of them are pure, case-insensitive and deliberately conservative: a name that does not
5
+ clearly match is *not* counted, so checks report UNVERIFIABLE instead of guessing.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ from second_source.core.expr import FunctionRegistry, to_cel
13
+
14
+
15
+ def _words(*terms: str) -> re.Pattern[str]:
16
+ """Match any term as a whole word inside a job name.
17
+
18
+ Job names are free text such as "CI / pytest (3.12)" or "unit-tests", so a "word" boundary
19
+ here is any character that is not a letter. This makes "test" match "unit-tests" but
20
+ not "attestation".
21
+ """
22
+ alternatives = "|".join(terms)
23
+ return re.compile(rf"(?<![a-z])(?:{alternatives})(?![a-z])")
24
+
25
+
26
+ # CI job names ---------------------------------------------------------------------------------
27
+
28
+ _TEST_JOB = _words(
29
+ r"tests?",
30
+ r"testing",
31
+ r"pytest",
32
+ r"unittest",
33
+ r"jest",
34
+ r"vitest",
35
+ r"mocha",
36
+ r"karma",
37
+ r"cypress",
38
+ r"playwright",
39
+ r"specs?",
40
+ r"rspec",
41
+ r"junit",
42
+ r"unit",
43
+ r"integration",
44
+ r"e2e",
45
+ r"go test",
46
+ r"cargo test",
47
+ r"tox",
48
+ r"nox",
49
+ )
50
+ _BUILD_JOB = _words(r"build", r"builds", r"compile", r"compilation", r"bundle", r"webpack")
51
+ _LINT_JOB = _words(
52
+ r"lint",
53
+ r"linter",
54
+ r"linting",
55
+ r"eslint",
56
+ r"ruff",
57
+ r"flake8",
58
+ r"pylint",
59
+ r"clippy",
60
+ r"golangci(?:-lint)?",
61
+ r"prettier",
62
+ r"format",
63
+ r"fmt",
64
+ r"black",
65
+ r"typecheck",
66
+ r"type-check",
67
+ r"mypy",
68
+ r"tsc",
69
+ r"stylelint",
70
+ r"rubocop",
71
+ )
72
+
73
+
74
+ def is_test_check(name: str) -> bool:
75
+ return bool(_TEST_JOB.search(name.lower()))
76
+
77
+
78
+ def is_build_check(name: str) -> bool:
79
+ return bool(_BUILD_JOB.search(name.lower()))
80
+
81
+
82
+ def is_lint_check(name: str) -> bool:
83
+ return bool(_LINT_JOB.search(name.lower()))
84
+
85
+
86
+ # File paths -----------------------------------------------------------------------------------
87
+
88
+ # Common test-file conventions across ecosystems. Matched against the full, lower-cased path.
89
+ _TEST_PATH = re.compile(
90
+ r"(^|/)(tests?|__tests__|spec|specs|testing)/" # test directories
91
+ r"|(^|/)test_[^/]+\.py$" # pytest: test_x.py
92
+ r"|_test\.(py|go|exs?|dart)$" # x_test.py, x_test.go, Elixir, Dart
93
+ r"|\.(test|spec)\.[cm]?[jt]sx?$" # x.test.ts, x.spec.jsx, x.test.mjs
94
+ r"|(test|tests|spec)\.(java|kt|cs|scala|swift)$" # FooTest.java, FooSpec.scala
95
+ r"|_spec\.rb$" # RSpec
96
+ r"|(^|/)[^/]*[._-]tests?/" # .NET Foo.Tests/, unit-tests/, integration_tests/
97
+ r"|(^|/)(e2e|cypress)/" # end-to-end suites
98
+ # foo_unittest.cc, foo_test.rs, foo_tests.rs: source files only, not run_tests.yml or
99
+ # requirements_test.txt
100
+ r"|_(unit)?tests?\.(c|cc|cpp|cxx|h|hpp|rs|go|py|rb|php|java|kt|swift|m|mm|cs|scala|exs?|dart|"
101
+ r"[cm]?[jt]sx?)$"
102
+ r"|\.cy\.[cm]?[jt]sx?$" # Cypress: x.cy.ts
103
+ r"|\.slt$" # sqllogictest files
104
+ r"|(^|/)tests?\.rs$" # Rust test modules: src/tests.rs, src/parser/test.rs
105
+ )
106
+ _DOC_PATH = re.compile(
107
+ r"(^|/)(docs?|documentation)/" # documentation directories
108
+ r"|(^|/)(readme|changelog|contributing)(\.[a-z]+)?$" # top-level project docs
109
+ r"|\.(md|mdx|rst|adoc)$" # documentation formats
110
+ r"|(^|/)man/[^/]+\.(rd|[1-9])$" # R roxygen output (man/*.Rd) and man pages
111
+ # Changelog fragments (towncrier, changesets, per-PR entry files) are changelog entries,
112
+ # which count as documentation (golden-set guide, rule 12).
113
+ # At the repository root only: "src/changes/diff.ts" is code.
114
+ r"|^\.?(changelogs?|changes|newsfragments|changelog\.d|changeset)/"
115
+ r"|(^|/)changelog_entry\.ya?ml$"
116
+ )
117
+
118
+
119
+ def is_test_path(path: str) -> bool:
120
+ lowered = path.lower()
121
+ # CI configuration that runs tests is not a test ("".github/workflows/tests.yml").
122
+ if lowered.startswith(".github/"):
123
+ return False
124
+ return bool(_TEST_PATH.search(lowered))
125
+
126
+
127
+ def is_doc_path(path: str) -> bool:
128
+ return bool(_DOC_PATH.search(path.lower()))
129
+
130
+
131
+ # CI, test and lint configuration (integrity guards) -----------------------------------------
132
+ # Files that decide how a PR's own checks run. A PR that changes them can change what "CI
133
+ # passed" means, so the guards caution about it. pyproject.toml, package.json, setup.cfg and
134
+ # Makefile are left out on purpose: almost every PR touches them for dependencies; their test
135
+ # command and coverage edits are caught line by line in diff_facts instead.
136
+
137
+ _CI_PATH = re.compile(
138
+ r"^\.github/workflows/[^/]+\.ya?ml$|^\.github/actions/|^\.gitlab-ci\.yml$|^\.circleci/"
139
+ r"|^azure-pipelines[^/]*\.ya?ml$|^\.travis\.yml$|^jenkinsfile$|^\.buildkite/"
140
+ )
141
+ _TEST_CONFIG_NAMES = re.compile(
142
+ r"^(pytest\.ini|tox\.ini|noxfile\.py|conftest\.py|\.coveragerc|\.?codecov\.ya?ml"
143
+ r"|jest\.config\.[\w.]+|vitest\.(config|workspace)\.[\w.]+|karma\.conf\.[\w.]+"
144
+ r"|playwright\.config\.[\w.]+|cypress\.config\.[\w.]+|\.mocharc[\w.]*"
145
+ r"|phpunit\.xml(\.dist)?|\.nycrc[\w.]*|nyc\.config\.[\w.]+)$"
146
+ )
147
+ _LINT_CONFIG_NAMES = re.compile(
148
+ r"^(\.eslintrc[\w.]*|eslint\.config\.[\w.]+|\.?ruff\.toml|\.flake8|\.golangci\.ya?ml"
149
+ r"|biome\.jsonc?|clippy\.toml|\.rubocop\.yml|\.pylintrc|\.prettierrc[\w.]*)$"
150
+ )
151
+
152
+
153
+ def is_ci_path(path: str) -> bool:
154
+ return bool(_CI_PATH.search(path.lower()))
155
+
156
+
157
+ def is_test_config_path(path: str) -> bool:
158
+ return bool(_TEST_CONFIG_NAMES.match(path.lower().rsplit("/", 1)[-1]))
159
+
160
+
161
+ def is_lint_config_path(path: str) -> bool:
162
+ return bool(_LINT_CONFIG_NAMES.match(path.lower().rsplit("/", 1)[-1]))
163
+
164
+
165
+ # Matching a claim to CI jobs ------------------------------------------------------------------
166
+
167
+ # Which job classifier verifies which claim type. One shared CI check uses this, so the
168
+ # decision logic for tests, builds and linting lives in a single place.
169
+ _JOB_CLASSIFIERS = {
170
+ "TESTS_PASS": is_test_check,
171
+ "BUILD_OK": is_build_check,
172
+ "LINT_OK": is_lint_check,
173
+ }
174
+
175
+
176
+ def job_matches(claim_type: str, job_name: str) -> bool:
177
+ """True if a CI job with this name is relevant evidence for this claim type."""
178
+ classifier = _JOB_CLASSIFIERS.get(claim_type)
179
+ return classifier is not None and classifier(job_name)
180
+
181
+
182
+ # Repositories and environments ----------------------------------------------------------------
183
+
184
+
185
+ def same_repo(first: str, second: str) -> bool:
186
+ """GitHub repository names are case-insensitive: "Octo/Infra" is "octo/infra"."""
187
+ return first.strip().lower() == second.strip().lower()
188
+
189
+
190
+ # Common short names for deployment environments. Applied to both the claim ("deployed to
191
+ # prod") and the evidence (an environment named "prod"), so they always meet in the middle.
192
+ ENVIRONMENT_ALIASES = {
193
+ "prod": "production",
194
+ "prd": "production",
195
+ "dev": "development",
196
+ "stg": "staging",
197
+ "stage": "staging",
198
+ }
199
+
200
+
201
+ def normalise_environment(name: str) -> str:
202
+ """Lower-case an environment name and expand a known short form at its start.
203
+
204
+ "Prod-EU" -> "production-eu"; "staging" -> "staging".
205
+ """
206
+ lowered = name.strip().lower()
207
+ head, separator, tail = lowered.partition("-")
208
+ return ENVIRONMENT_ALIASES.get(head, head) + separator + tail
209
+
210
+
211
+ def env_matches(evidence_env: str, claimed_env: str) -> bool:
212
+ """True if a deployment environment satisfies the environment the agent named.
213
+
214
+ Both sides are normalised, then the evidence must start with the claim, so a claim of
215
+ "staging" is satisfied by "staging" or "staging-eu" but not by "production".
216
+ """
217
+ return normalise_environment(evidence_env).startswith(normalise_environment(claimed_env))
218
+
219
+
220
+ # Registration ---------------------------------------------------------------------------------
221
+
222
+ _FUNCTIONS = {
223
+ "is_test_check": is_test_check,
224
+ "is_build_check": is_build_check,
225
+ "is_lint_check": is_lint_check,
226
+ "is_test_path": is_test_path,
227
+ "is_doc_path": is_doc_path,
228
+ "job_matches": job_matches,
229
+ "same_repo": same_repo,
230
+ "env_matches": env_matches,
231
+ }
232
+
233
+
234
+ def register(registry: FunctionRegistry) -> None:
235
+ """Make the helpers available to expressions (referenced from pack.yaml).
236
+
237
+ Helpers receive CEL strings and must return CEL booleans, so each plain Python function
238
+ above is wrapped: arguments are converted to str, the result back to a CEL value.
239
+ """
240
+ for name, function in _FUNCTIONS.items():
241
+ registry.register(name, lambda *args, f=function: to_cel(f(*(str(arg) for arg in args))))
@@ -0,0 +1,33 @@
1
+ # Coding pack: verifies what coding agents claim in pull requests.
2
+ # Design and evidence contract: docs/packs/coding.md
3
+ id: coding
4
+ version: 0.5.0
5
+ kind: agent_type
6
+ description: Claims made by coding agents in pull requests, checked against CI and Git evidence.
7
+ claim_types:
8
+ - TESTS_PASS
9
+ - BUILD_OK
10
+ - LINT_OK
11
+ - TESTS_ADDED
12
+ - FIXES_ISSUE
13
+ - DOCS_UPDATED
14
+ - DEPLOYED
15
+ - MERGE_HOLDS
16
+ checks:
17
+ - checks/ci_result.yaml
18
+ - checks/tests_added.yaml
19
+ - checks/docs_updated.yaml
20
+ - checks/fixes_issue.yaml
21
+ - checks/fixes_issue_durable.yaml
22
+ - checks/deployed.yaml
23
+ - checks/not_reverted.yaml
24
+ # Integrity guards: withdraw or caution a VERIFIED, never accuse (docs/packs/coding.md)
25
+ - checks/integrity_guard.yaml
26
+ - checks/tests_added_guard.yaml
27
+ - checks/ci_config_caution.yaml
28
+ - checks/tests_removed_caution.yaml
29
+ - checks/lint_caution.yaml
30
+ - checks/integrity_inspection.yaml
31
+ - checks/matching_jobs_caution.yaml
32
+ - checks/ci_weakening_caution.yaml
33
+ functions: second_source.packs.coding.functions:register
@@ -0,0 +1,50 @@
1
+ # Extraction rules trusted for the benchmark: each fired at least min_hits times on the
2
+ # selection split with at least min_precision precision. Claims from other rules are kept but
3
+ # marked low confidence. Generated by `second-source bench rules --select`; do not edit by hand.
4
+ selected_on:
5
+ cases: cases.jsonl
6
+ split: dev
7
+ size: 212
8
+ min_hits: 5
9
+ min_precision: 0.95
10
+ trusted:
11
+ - type: DOCS_UPDATED
12
+ rule: changed_file.doc
13
+ hits: 11
14
+ precision: 1.0
15
+ - type: DOCS_UPDATED
16
+ rule: docs_updated.verb
17
+ hits: 19
18
+ precision: 1.0
19
+ - type: FIXES_ISSUE
20
+ rule: fixes_issue.closing_ref
21
+ hits: 34
22
+ precision: 1.0
23
+ - type: LINT_OK
24
+ rule: lint_ok.lint_list
25
+ hits: 5
26
+ precision: 1.0
27
+ - type: TESTS_ADDED
28
+ rule: changed_file.test
29
+ hits: 13
30
+ precision: 1.0
31
+ - type: TESTS_ADDED
32
+ rule: tests_added.count
33
+ hits: 5
34
+ precision: 1.0
35
+ - type: TESTS_ADDED
36
+ rule: tests_added.verb
37
+ hits: 28
38
+ precision: 0.964
39
+ - type: TESTS_PASS
40
+ rule: command.prose
41
+ hits: 6
42
+ precision: 1.0
43
+ - type: TESTS_PASS
44
+ rule: tests_pass.plain
45
+ hits: 15
46
+ precision: 1.0
47
+ - type: TESTS_PASS
48
+ rule: tests_pass.quantified
49
+ hits: 13
50
+ precision: 1.0
@@ -0,0 +1,112 @@
1
+ """Application pipeline: check one pull request end to end.
2
+
3
+ load PR -> detect agent -> extract claims (+ implicit merge claim)
4
+ -> fetch only the evidence those claims need -> verify -> report
5
+
6
+ Used by the CLI, the GitHub Action and the benchmark, so all three give identical verdicts
7
+ for the same pull request.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Sequence
13
+ from dataclasses import dataclass
14
+ from datetime import UTC, datetime
15
+ from functools import lru_cache
16
+
17
+ from second_source.core.engine import Engine
18
+ from second_source.core.model import Claim, Episode, Evidence, Verdict
19
+ from second_source.packs import coding
20
+ from second_source.packs.coding.detection import AgentMatch, detect_agent
21
+ from second_source.packs.coding.extract import extract_claims, merge_claim
22
+ from second_source.sources.github import mappers
23
+ from second_source.sources.github.source import GitHubSource
24
+ from second_source.sources.github.urls import PullRequestRef
25
+
26
+ UNKNOWN_AGENT = "unknown"
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class PullRequestReport:
31
+ ref: PullRequestRef
32
+ episode: Episode
33
+ agent: AgentMatch | None # None when no agent signal was found (likely a human PR)
34
+ claims: Sequence[Claim]
35
+ verdicts: Sequence[Verdict]
36
+ stale: frozenset[str]
37
+ errors: Sequence[str]
38
+ checked_at: datetime
39
+ api_requests: int
40
+ rate_limited: bool = False # evidence fetching stopped at the rate limit (see stale)
41
+ head_sha: str = "" # the PR's head commit, where the GitHub Action attaches its check run
42
+ labels: tuple[str, ...] = () # PR labels (the Action records disputes as a label)
43
+ evidence: tuple[Evidence, ...] = () # the records the verdicts were computed from
44
+ # Evidence types requested from the source: a type absent here was never fetched, which a
45
+ # later re-score must not read as "fetched and empty".
46
+ fetched: frozenset[str] = frozenset()
47
+
48
+ def verdict_for(self, claim: Claim) -> Verdict:
49
+ return next(v for v in self.verdicts if v.claim_id == claim.id)
50
+
51
+
52
+ @lru_cache(maxsize=1)
53
+ def default_engine() -> Engine:
54
+ """The engine with the bundled coding pack (built once per process)."""
55
+ return Engine.from_packs([coding.load()])
56
+
57
+
58
+ def check_pull_request(
59
+ ref: PullRequestRef,
60
+ source: GitHubSource,
61
+ *,
62
+ engine: Engine | None = None,
63
+ now: datetime | None = None,
64
+ extra_evidence: frozenset[str] = frozenset(),
65
+ ignore_claims: frozenset[str] = frozenset(),
66
+ ) -> PullRequestReport:
67
+ """Verify every claim in a pull request. Raises PullRequestNotFound for missing PRs.
68
+
69
+ ``extra_evidence`` names evidence types to fetch even when no claim needs them. The
70
+ benchmark uses it to keep every PR's file list in its evidence snapshot, so integrity
71
+ signals (CI config or tests changed) can be re-scored later without new requests.
72
+ """
73
+ engine = engine or default_engine()
74
+ checked_at = now or datetime.now(UTC)
75
+ # The client may be shared across many PRs (benchmark runs), so count this PR's requests
76
+ # as a difference rather than reading the client's running total.
77
+ requests_before = source.client.stats.requests
78
+
79
+ loaded = source.load(ref)
80
+ agent = detect_agent(loaded.signals)
81
+ episode = mappers.episode_from_pull(loaded.pull, agent.agent if agent else UNKNOWN_AGENT)
82
+
83
+ claims = extract_claims(episode.id, loaded.texts, repo=ref.full_name)
84
+ # Claim types the repository switched off are neither checked nor shown.
85
+ claims = [claim for claim in claims if claim.type not in ignore_claims]
86
+ merged_at = mappers.parse_time(loaded.pull.get("merged_at"))
87
+ merge_sha = loaded.pull.get("merge_commit_sha")
88
+ if merged_at and merge_sha:
89
+ # Merging asserts the change is good; durability checks verify it over time.
90
+ claims.append(merge_claim(episode.id, merged_at, merge_sha))
91
+
92
+ needed = set(engine.evidence_types_for(claims)) | set(extra_evidence)
93
+ evidence = source.fetch_evidence(loaded, claims, needed)
94
+ verdicts = engine.verify(
95
+ episode, claims, evidence.records, now=checked_at, stale=frozenset(evidence.stale)
96
+ )
97
+ return PullRequestReport(
98
+ ref=ref,
99
+ episode=episode,
100
+ agent=agent,
101
+ claims=claims,
102
+ verdicts=verdicts,
103
+ stale=frozenset(evidence.stale),
104
+ errors=tuple(evidence.errors),
105
+ checked_at=checked_at,
106
+ api_requests=source.client.stats.requests - requests_before,
107
+ rate_limited=evidence.rate_limited,
108
+ head_sha=(loaded.pull.get("head") or {}).get("sha", ""),
109
+ labels=tuple(label["name"] for label in loaded.pull.get("labels", [])),
110
+ evidence=tuple(evidence.records),
111
+ fetched=frozenset(needed),
112
+ )
@@ -0,0 +1 @@
1
+ """Report renderers: terminal text, Markdown (GitHub checks) and JSON."""