codejury 0.1.0__tar.gz

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 (94) hide show
  1. codejury-0.1.0/LICENSE +21 -0
  2. codejury-0.1.0/PKG-INFO +110 -0
  3. codejury-0.1.0/README.md +81 -0
  4. codejury-0.1.0/codejury/__init__.py +8 -0
  5. codejury-0.1.0/codejury/agents/__init__.py +6 -0
  6. codejury-0.1.0/codejury/agents/base.py +21 -0
  7. codejury-0.1.0/codejury/agents/debate.py +188 -0
  8. codejury-0.1.0/codejury/agents/mock.py +38 -0
  9. codejury-0.1.0/codejury/agents/parsing.py +42 -0
  10. codejury-0.1.0/codejury/agents/verifier.py +106 -0
  11. codejury-0.1.0/codejury/assembly.py +76 -0
  12. codejury-0.1.0/codejury/cli.py +196 -0
  13. codejury-0.1.0/codejury/data/capabilities/authentication.yaml +67 -0
  14. codejury-0.1.0/codejury/data/capabilities/authorization.yaml +55 -0
  15. codejury-0.1.0/codejury/data/capabilities/business_logic.yaml +58 -0
  16. codejury-0.1.0/codejury/data/capabilities/crypto.yaml +78 -0
  17. codejury-0.1.0/codejury/data/capabilities/data_protection.yaml +57 -0
  18. codejury-0.1.0/codejury/data/capabilities/dependency_config.yaml +52 -0
  19. codejury-0.1.0/codejury/data/capabilities/error_logging.yaml +49 -0
  20. codejury-0.1.0/codejury/data/capabilities/input_validation.yaml +92 -0
  21. codejury-0.1.0/codejury/data/capabilities/output_encoding.yaml +56 -0
  22. codejury-0.1.0/codejury/data/capabilities/secrets.yaml +51 -0
  23. codejury-0.1.0/codejury/data/capabilities/session.yaml +60 -0
  24. codejury-0.1.0/codejury/data/golden/authn_bcrypt_password.yaml +5 -0
  25. codejury-0.1.0/codejury/data/golden/authn_sha256_password.yaml +5 -0
  26. codejury-0.1.0/codejury/data/golden/sqli_fstring_query.yaml +5 -0
  27. codejury-0.1.0/codejury/data/golden/sqli_parameterized_query.yaml +5 -0
  28. codejury-0.1.0/codejury/data/tasks/audit_diff_debate.yaml +4 -0
  29. codejury-0.1.0/codejury/data/tasks/quick_scan_single.yaml +4 -0
  30. codejury-0.1.0/codejury/domain/__init__.py +5 -0
  31. codejury-0.1.0/codejury/domain/artifact.py +20 -0
  32. codejury-0.1.0/codejury/domain/capability.py +123 -0
  33. codejury-0.1.0/codejury/domain/context.py +26 -0
  34. codejury-0.1.0/codejury/domain/observation.py +104 -0
  35. codejury-0.1.0/codejury/domain/result.py +19 -0
  36. codejury-0.1.0/codejury/evaluation.py +107 -0
  37. codejury-0.1.0/codejury/infrastructure/__init__.py +4 -0
  38. codejury-0.1.0/codejury/infrastructure/json_parse.py +57 -0
  39. codejury-0.1.0/codejury/orchestrators/__init__.py +6 -0
  40. codejury-0.1.0/codejury/orchestrators/base.py +19 -0
  41. codejury-0.1.0/codejury/orchestrators/debate.py +57 -0
  42. codejury-0.1.0/codejury/orchestrators/pipeline.py +32 -0
  43. codejury-0.1.0/codejury/orchestrators/reflexion.py +58 -0
  44. codejury-0.1.0/codejury/orchestrators/single.py +24 -0
  45. codejury-0.1.0/codejury/providers/__init__.py +5 -0
  46. codejury-0.1.0/codejury/providers/anthropic.py +68 -0
  47. codejury-0.1.0/codejury/providers/base.py +42 -0
  48. codejury-0.1.0/codejury/providers/litellm.py +68 -0
  49. codejury-0.1.0/codejury/providers/mock.py +32 -0
  50. codejury-0.1.0/codejury/providers/openai.py +57 -0
  51. codejury-0.1.0/codejury/providers/openai_format.py +30 -0
  52. codejury-0.1.0/codejury/providers/retry.py +48 -0
  53. codejury-0.1.0/codejury/reporting.py +114 -0
  54. codejury-0.1.0/codejury/resources.py +13 -0
  55. codejury-0.1.0/codejury/sources/__init__.py +6 -0
  56. codejury-0.1.0/codejury/sources/base.py +17 -0
  57. codejury-0.1.0/codejury/sources/chunker.py +33 -0
  58. codejury-0.1.0/codejury/sources/diff.py +69 -0
  59. codejury-0.1.0/codejury/sources/function.py +35 -0
  60. codejury-0.1.0/codejury/sources/mock.py +25 -0
  61. codejury-0.1.0/codejury/sources/repo.py +44 -0
  62. codejury-0.1.0/codejury/tasks/__init__.py +6 -0
  63. codejury-0.1.0/codejury/tasks/base.py +55 -0
  64. codejury-0.1.0/codejury/tasks/registry.py +22 -0
  65. codejury-0.1.0/codejury.egg-info/PKG-INFO +110 -0
  66. codejury-0.1.0/codejury.egg-info/SOURCES.txt +92 -0
  67. codejury-0.1.0/codejury.egg-info/dependency_links.txt +1 -0
  68. codejury-0.1.0/codejury.egg-info/entry_points.txt +2 -0
  69. codejury-0.1.0/codejury.egg-info/requires.txt +13 -0
  70. codejury-0.1.0/codejury.egg-info/top_level.txt +1 -0
  71. codejury-0.1.0/pyproject.toml +47 -0
  72. codejury-0.1.0/setup.cfg +4 -0
  73. codejury-0.1.0/tests/test_anthropic_provider.py +53 -0
  74. codejury-0.1.0/tests/test_assembly.py +36 -0
  75. codejury-0.1.0/tests/test_audit_pipeline.py +63 -0
  76. codejury-0.1.0/tests/test_capability.py +81 -0
  77. codejury-0.1.0/tests/test_cli_audit.py +99 -0
  78. codejury-0.1.0/tests/test_context.py +30 -0
  79. codejury-0.1.0/tests/test_debate_agents.py +87 -0
  80. codejury-0.1.0/tests/test_debate_orchestrator.py +77 -0
  81. codejury-0.1.0/tests/test_diff_source.py +63 -0
  82. codejury-0.1.0/tests/test_evaluation.py +55 -0
  83. codejury-0.1.0/tests/test_function_source.py +49 -0
  84. codejury-0.1.0/tests/test_json_parse.py +27 -0
  85. codejury-0.1.0/tests/test_litellm_provider.py +68 -0
  86. codejury-0.1.0/tests/test_openai_provider.py +42 -0
  87. codejury-0.1.0/tests/test_orchestrator.py +39 -0
  88. codejury-0.1.0/tests/test_pipeline_orchestrator.py +59 -0
  89. codejury-0.1.0/tests/test_reflexion_orchestrator.py +67 -0
  90. codejury-0.1.0/tests/test_repo_source.py +38 -0
  91. codejury-0.1.0/tests/test_reporting.py +52 -0
  92. codejury-0.1.0/tests/test_retry_provider.py +49 -0
  93. codejury-0.1.0/tests/test_tasks.py +47 -0
  94. codejury-0.1.0/tests/test_verifier.py +63 -0
codejury-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 4234288
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: codejury
3
+ Version: 0.1.0
4
+ Summary: General-purpose Application Security AI audit framework -- five-layer architecture, capabilities as first-class data
5
+ Author: 4234288
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/4234288/codejury
8
+ Project-URL: Repository, https://github.com/4234288/codejury
9
+ Keywords: security,appsec,static analysis,llm,owasp,asvs,code review
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Security
13
+ Classifier: Topic :: Software Development :: Quality Assurance
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Operating System :: OS Independent
16
+ Requires-Python: >=3.12
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: pyyaml>=6.0
20
+ Provides-Extra: anthropic
21
+ Requires-Dist: anthropic>=0.40; extra == "anthropic"
22
+ Provides-Extra: openai
23
+ Requires-Dist: openai>=1.0; extra == "openai"
24
+ Provides-Extra: litellm
25
+ Requires-Dist: litellm>=1.0; extra == "litellm"
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8.0; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # codejury
31
+
32
+ A general-purpose **Application Security AI audit framework**. Domain knowledge (11
33
+ capabilities aligned with OWASP ASVS) lives in versioned YAML files as
34
+ first-class data, keeping the framework core small.
35
+
36
+ The name comes from the core orchestration metaphor: code goes before a "jury"
37
+ of adversarial roles -- Finder / Challenger / Judge -- that converge on a verdict.
38
+
39
+ ## Five-layer architecture
40
+
41
+ ```
42
+ Layer 5 Task task configuration (source + capabilities + orchestrator + agents)
43
+ Layer 4 Capability YAML domain knowledge (authn / authz / input_validation ...)
44
+ Layer 3 Orchestrator strategy (single / debate / pipeline / reflexion)
45
+ Source input (diff / function / repo)
46
+ Agent audit role (finder / challenger / judge / verifier)
47
+ Layer 2 Provider model backend (anthropic / openai / litellm / mock)
48
+ Layer 1 Infrastructure cross-cutting utilities (json parsing, ...)
49
+ ```
50
+
51
+ Layers talk only through typed data. Each layer is an abstract base class (ABC)
52
+ plus implementations, so the four axes (task / orchestration / model / input)
53
+ compose independently.
54
+
55
+ ## Design notes
56
+
57
+ - **Domain knowledge is data, not prompts**: a capability YAML is readable by
58
+ the LLM, by a rule engine, and by a human, and is versioned alongside code.
59
+ - **Explains both "why it's wrong" and "why it's fine"**: every capability
60
+ yields a `Verdict`, recording safe matches too -- a checkup dimension rather
61
+ than an anomaly filter.
62
+
63
+ ## Status
64
+
65
+ Usable end to end across all five layers:
66
+
67
+ - **Orchestrators**: single, pipeline, debate, reflexion
68
+ - **Sources**: diff, function, repo (with chunking)
69
+ - **Providers**: anthropic, openai, litellm, mock (plus an opt-in retry wrapper)
70
+ - **Capabilities**: all 11 OWASP ASVS areas
71
+ - **Tasks**: named presets in `tasks/` (e.g. `audit_diff_debate`)
72
+ - **Reporting**: text, markdown, json
73
+ - **Evaluation**: a golden-case precision/recall harness
74
+
75
+ The golden set ships with seed cases; real precision/recall numbers need a model
76
+ (`codejury eval` with a provider key).
77
+
78
+ ## Install
79
+
80
+ ```bash
81
+ pip install codejury # core + CLI
82
+ pip install 'codejury[anthropic]' # add the provider you'll use (anthropic / openai / litellm)
83
+ ```
84
+
85
+ ## Usage
86
+
87
+ ```bash
88
+ # Audit a unified diff against the capability library
89
+ git diff | codejury audit --orchestrator debate --provider anthropic --format markdown -
90
+
91
+ # Run a named task preset (tasks/*.yaml)
92
+ git diff | codejury run audit_diff_debate -
93
+
94
+ # Score detection quality against the golden cases (needs a provider key)
95
+ codejury eval --provider anthropic
96
+
97
+ # No API key needed: prove the pipeline composes with mock layers
98
+ codejury dry-run
99
+ ```
100
+
101
+ `audit` and `run` read a diff from a file argument or stdin (`-`). Real providers
102
+ read their key from the environment (e.g. `ANTHROPIC_API_KEY`).
103
+
104
+ ## Development
105
+
106
+ ```bash
107
+ python -m venv .venv && source .venv/bin/activate
108
+ pip install -e ".[dev]"
109
+ pytest
110
+ ```
@@ -0,0 +1,81 @@
1
+ # codejury
2
+
3
+ A general-purpose **Application Security AI audit framework**. Domain knowledge (11
4
+ capabilities aligned with OWASP ASVS) lives in versioned YAML files as
5
+ first-class data, keeping the framework core small.
6
+
7
+ The name comes from the core orchestration metaphor: code goes before a "jury"
8
+ of adversarial roles -- Finder / Challenger / Judge -- that converge on a verdict.
9
+
10
+ ## Five-layer architecture
11
+
12
+ ```
13
+ Layer 5 Task task configuration (source + capabilities + orchestrator + agents)
14
+ Layer 4 Capability YAML domain knowledge (authn / authz / input_validation ...)
15
+ Layer 3 Orchestrator strategy (single / debate / pipeline / reflexion)
16
+ Source input (diff / function / repo)
17
+ Agent audit role (finder / challenger / judge / verifier)
18
+ Layer 2 Provider model backend (anthropic / openai / litellm / mock)
19
+ Layer 1 Infrastructure cross-cutting utilities (json parsing, ...)
20
+ ```
21
+
22
+ Layers talk only through typed data. Each layer is an abstract base class (ABC)
23
+ plus implementations, so the four axes (task / orchestration / model / input)
24
+ compose independently.
25
+
26
+ ## Design notes
27
+
28
+ - **Domain knowledge is data, not prompts**: a capability YAML is readable by
29
+ the LLM, by a rule engine, and by a human, and is versioned alongside code.
30
+ - **Explains both "why it's wrong" and "why it's fine"**: every capability
31
+ yields a `Verdict`, recording safe matches too -- a checkup dimension rather
32
+ than an anomaly filter.
33
+
34
+ ## Status
35
+
36
+ Usable end to end across all five layers:
37
+
38
+ - **Orchestrators**: single, pipeline, debate, reflexion
39
+ - **Sources**: diff, function, repo (with chunking)
40
+ - **Providers**: anthropic, openai, litellm, mock (plus an opt-in retry wrapper)
41
+ - **Capabilities**: all 11 OWASP ASVS areas
42
+ - **Tasks**: named presets in `tasks/` (e.g. `audit_diff_debate`)
43
+ - **Reporting**: text, markdown, json
44
+ - **Evaluation**: a golden-case precision/recall harness
45
+
46
+ The golden set ships with seed cases; real precision/recall numbers need a model
47
+ (`codejury eval` with a provider key).
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ pip install codejury # core + CLI
53
+ pip install 'codejury[anthropic]' # add the provider you'll use (anthropic / openai / litellm)
54
+ ```
55
+
56
+ ## Usage
57
+
58
+ ```bash
59
+ # Audit a unified diff against the capability library
60
+ git diff | codejury audit --orchestrator debate --provider anthropic --format markdown -
61
+
62
+ # Run a named task preset (tasks/*.yaml)
63
+ git diff | codejury run audit_diff_debate -
64
+
65
+ # Score detection quality against the golden cases (needs a provider key)
66
+ codejury eval --provider anthropic
67
+
68
+ # No API key needed: prove the pipeline composes with mock layers
69
+ codejury dry-run
70
+ ```
71
+
72
+ `audit` and `run` read a diff from a file argument or stdin (`-`). Real providers
73
+ read their key from the environment (e.g. `ANTHROPIC_API_KEY`).
74
+
75
+ ## Development
76
+
77
+ ```bash
78
+ python -m venv .venv && source .venv/bin/activate
79
+ pip install -e ".[dev]"
80
+ pytest
81
+ ```
@@ -0,0 +1,8 @@
1
+ """codejury -- a general-purpose Application Security AI audit framework.
2
+
3
+ Five layers: Task / (Capability + Orchestrator + Source + Agent) / Provider / Infrastructure.
4
+ Domain knowledge lives in YAML capability files as a first-class citizen,
5
+ aligned with OWASP ASVS.
6
+ """
7
+
8
+ __version__ = "0.0.0"
@@ -0,0 +1,6 @@
1
+ """codejury.agents -- the audit roles (finder / challenger / judge / verifier).
2
+
3
+ An agent reads an AnalysisContext and emits observations. It talks to a model
4
+ only through a Provider, never a vendor SDK, so the role logic stays independent
5
+ of the backend.
6
+ """
@@ -0,0 +1,21 @@
1
+ """Agent ABC.
2
+
3
+ An agent runs once over an AnalysisContext and returns a list of observations:
4
+ a single run typically yields several (a verifier emits one Verdict per
5
+ sub_capability; a finder reports several Findings).
6
+
7
+ The base only declares ``run``. Concrete agents take a Provider in their own
8
+ __init__; the orchestrator constructs and addresses them by role.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from abc import ABC, abstractmethod
14
+
15
+ from codejury.domain.context import AnalysisContext
16
+ from codejury.domain.observation import Observation
17
+
18
+
19
+ class Agent(ABC):
20
+ @abstractmethod
21
+ def run(self, ctx: AnalysisContext) -> list[Observation]: ...
@@ -0,0 +1,188 @@
1
+ """Finder / Challenger / Judge agents for the debate orchestrator.
2
+
3
+ Each reads the artifact, the capability hints, and the accumulated history
4
+ (prior findings and rebuttals) from the context, calls the provider once, and
5
+ maps its JSON reply onto observations:
6
+
7
+ - Finder -> Finding (claims) + Concession (its own retractions)
8
+ - Challenger -> Concession (moves to dismiss findings) + Finding (ones it missed)
9
+ - Judge -> Finding (surviving) + Concession (dismissed)
10
+
11
+ The orchestrator threads history and round_num across rounds; convergence is the
12
+ orchestrator's job, not encoded here.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from codejury.agents.base import Agent
18
+ from codejury.agents.parsing import one_of, str_list, to_evidence, to_float
19
+ from codejury.domain.artifact import CodeArtifact
20
+ from codejury.domain.capability import Capability
21
+ from codejury.domain.context import AnalysisContext
22
+ from codejury.domain.observation import Concession, Finding, Observation
23
+ from codejury.infrastructure.json_parse import extract_json_object
24
+ from codejury.providers.base import Message, Provider
25
+
26
+ _SEVERITY = {"CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"}
27
+
28
+ _FINDING_SHAPE = (
29
+ '{"capability": "id.sub", "title": "...", "severity": "HIGH", "cwe": "CWE-89", '
30
+ '"description": "...", "evidence": [{"file": "...", "line": 0, "code": "..."}], "confidence": 0.0}'
31
+ )
32
+
33
+
34
+ class _DebateAgent(Agent):
35
+ """Shared provider plumbing for the three debate roles."""
36
+
37
+ role = "agent"
38
+ system = ""
39
+
40
+ def __init__(self, *, provider: Provider, model: str, max_tokens: int = 2048) -> None:
41
+ self._provider = provider
42
+ self._model = model
43
+ self._max_tokens = max_tokens
44
+
45
+ def _ask(self, prompt: str) -> dict:
46
+ result = self._provider.complete(
47
+ system=self.system,
48
+ messages=[Message(role="user", content=prompt)],
49
+ model=self._model,
50
+ max_tokens=self._max_tokens,
51
+ )
52
+ return extract_json_object(result.text) or {}
53
+
54
+
55
+ class FinderAgent(_DebateAgent):
56
+ role = "finder"
57
+ system = (
58
+ "You are a security finder. Identify real, exploitable vulnerabilities in the code, "
59
+ "being precise and avoiding false positives. Respond with a single JSON object and nothing else."
60
+ )
61
+
62
+ def run(self, ctx: AnalysisContext) -> list[Observation]:
63
+ parts = ["Review the code for security vulnerabilities.", _hints(ctx.capabilities), _code(ctx.artifact)]
64
+ if ctx.round_num > 1 and ctx.history:
65
+ parts.append(_render_history(ctx.history))
66
+ parts.append("Concede findings the rebuttals refute, keep the valid ones, and add any you missed.")
67
+ parts.append(
68
+ 'Respond as JSON: {"findings": [' + _FINDING_SHAPE + '], '
69
+ '"concessions": [{"target": "finding title", "reason": "..."}]}'
70
+ )
71
+ obj = self._ask("\n\n".join(p for p in parts if p))
72
+ return _findings(obj.get("findings"), self.role, ctx.round_num) + _concessions(
73
+ obj.get("concessions"), self.role, ctx.round_num
74
+ )
75
+
76
+
77
+ class ChallengerAgent(_DebateAgent):
78
+ role = "challenger"
79
+ system = (
80
+ "You are a skeptical security reviewer. Challenge each reported finding and try to refute it "
81
+ "with concrete reasoning. Respond with a single JSON object and nothing else."
82
+ )
83
+
84
+ def run(self, ctx: AnalysisContext) -> list[Observation]:
85
+ parts = [
86
+ "Challenge the findings below. For each one you believe is a false positive, write a rebuttal. "
87
+ "Add new_findings for any real issue that was missed.",
88
+ _code(ctx.artifact),
89
+ _render_history(ctx.history),
90
+ 'Respond as JSON: {"rebuttals": [{"target": "finding title", "reason": "..."}], '
91
+ '"new_findings": [' + _FINDING_SHAPE + "]}",
92
+ ]
93
+ obj = self._ask("\n\n".join(p for p in parts if p))
94
+ return _concessions(obj.get("rebuttals"), self.role, ctx.round_num) + _findings(
95
+ obj.get("new_findings"), self.role, ctx.round_num
96
+ )
97
+
98
+
99
+ class JudgeAgent(_DebateAgent):
100
+ role = "judge"
101
+ system = (
102
+ "You are an impartial security judge. Weighing the findings and rebuttals, decide which findings "
103
+ "survive scrutiny and which are dismissed. Respond with a single JSON object and nothing else."
104
+ )
105
+
106
+ def run(self, ctx: AnalysisContext) -> list[Observation]:
107
+ parts = [
108
+ "Rule on the debate below. Keep findings that withstand the rebuttals; dismiss the rest.",
109
+ _code(ctx.artifact),
110
+ _render_history(ctx.history),
111
+ 'Respond as JSON: {"surviving": [' + _FINDING_SHAPE + '], '
112
+ '"dismissed": [{"target": "finding title", "reason": "..."}]}',
113
+ ]
114
+ obj = self._ask("\n\n".join(p for p in parts if p))
115
+ return _findings(obj.get("surviving"), self.role, ctx.round_num) + _concessions(
116
+ obj.get("dismissed"), self.role, ctx.round_num
117
+ )
118
+
119
+
120
+ def _code(artifact: CodeArtifact) -> str:
121
+ return f"Code under review ({artifact.path}):\n```\n{artifact.content}\n```"
122
+
123
+
124
+ def _hints(capabilities: list[Capability]) -> str:
125
+ lines = []
126
+ for cap in capabilities:
127
+ for sub_name, sub in cap.sub_capabilities.items():
128
+ for ap in sub.anti_patterns:
129
+ tag = f"{ap.cwe} {ap.severity}" if ap.cwe else ap.severity
130
+ lines.append(f"- {cap.id}.{sub_name} [{tag}]: {ap.description}")
131
+ return "Look especially for:\n" + "\n".join(lines) if lines else ""
132
+
133
+
134
+ def _render_history(history: list[Observation]) -> str:
135
+ findings = [o for o in history if isinstance(o, Finding)]
136
+ concessions = [o for o in history if isinstance(o, Concession)]
137
+ blocks = []
138
+ if findings:
139
+ lines = [
140
+ f'- [{f.produced_by} r{f.round_num}] "{f.title}" ({f.severity}{", " + f.cwe if f.cwe else ""}): '
141
+ f"{f.description}"
142
+ for f in findings
143
+ ]
144
+ blocks.append("Findings so far:\n" + "\n".join(lines))
145
+ if concessions:
146
+ lines = [f'- [{c.produced_by} r{c.round_num}] dismiss "{c.target}": {c.reason}' for c in concessions]
147
+ blocks.append("Rebuttals / concessions so far:\n" + "\n".join(lines))
148
+ return "\n\n".join(blocks)
149
+
150
+
151
+ def _findings(items: object, produced_by: str, round_num: int) -> list[Finding]:
152
+ out: list[Finding] = []
153
+ for f in _dicts(items):
154
+ title = str(f.get("title", "")).strip()
155
+ if not title:
156
+ continue
157
+ out.append(
158
+ Finding(
159
+ produced_by=produced_by,
160
+ round_num=round_num,
161
+ capability=str(f.get("capability", "")),
162
+ title=title,
163
+ description=str(f.get("description", "")),
164
+ severity=one_of(f.get("severity"), _SEVERITY, "MEDIUM"),
165
+ cwe=str(f.get("cwe", "")),
166
+ evidence=to_evidence(f.get("evidence")),
167
+ recommendation=str(f.get("recommendation", "")),
168
+ matched_anti=str_list(f.get("matched_anti")),
169
+ confidence=to_float(f.get("confidence"), 0.5),
170
+ )
171
+ )
172
+ return out
173
+
174
+
175
+ def _concessions(items: object, produced_by: str, round_num: int) -> list[Concession]:
176
+ out: list[Concession] = []
177
+ for c in _dicts(items):
178
+ target = str(c.get("target", "")).strip()
179
+ if not target:
180
+ continue
181
+ out.append(
182
+ Concession(produced_by=produced_by, round_num=round_num, target=target, reason=str(c.get("reason", "")))
183
+ )
184
+ return out
185
+
186
+
187
+ def _dicts(items: object) -> list[dict]:
188
+ return [x for x in items if isinstance(x, dict)] if isinstance(items, list) else []
@@ -0,0 +1,38 @@
1
+ """MockAgent -- a minimal Agent for the dry-run and tests.
2
+
3
+ It really calls the provider (so the dry-run exercises the agent -> provider
4
+ path), then emits one Verdict per in-scope capability, parking the model's reply
5
+ in ``reasoning``. It does no real parsing or judgement; the Phase 3 VerifierAgent
6
+ will.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from codejury.agents.base import Agent
12
+ from codejury.domain.context import AnalysisContext
13
+ from codejury.domain.observation import Observation, Verdict
14
+ from codejury.providers.base import Message, Provider
15
+
16
+
17
+ class MockAgent(Agent):
18
+ def __init__(self, *, provider: Provider, role: str = "verifier", model: str = "mock-model") -> None:
19
+ self._provider = provider
20
+ self._role = role
21
+ self._model = model
22
+
23
+ def run(self, ctx: AnalysisContext) -> list[Observation]:
24
+ result = self._provider.complete(
25
+ system=f"You are a {self._role}.",
26
+ messages=[Message(role="user", content=ctx.artifact.content)],
27
+ model=self._model,
28
+ max_tokens=256,
29
+ )
30
+ return [
31
+ Verdict(
32
+ capability=cap.id,
33
+ produced_by=self._role,
34
+ status="UNKNOWN",
35
+ reasoning=result.text,
36
+ )
37
+ for cap in ctx.capabilities
38
+ ]
@@ -0,0 +1,42 @@
1
+ """Shared coercion from loosely-typed model JSON into domain values.
2
+
3
+ Agents parse model output that may omit, mistype, or invent fields. These
4
+ helpers coerce defensively -- they never raise on bad input, they fall back.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from codejury.domain.observation import Evidence
10
+
11
+
12
+ def str_list(value: object) -> list[str]:
13
+ return [str(x) for x in value] if isinstance(value, list) else []
14
+
15
+
16
+ def to_float(value: object, default: float) -> float:
17
+ try:
18
+ return float(value) # type: ignore[arg-type]
19
+ except (TypeError, ValueError):
20
+ return default
21
+
22
+
23
+ def one_of(value: object, allowed: set[str], default: str) -> str:
24
+ return value if value in allowed else default
25
+
26
+
27
+ def to_evidence(items: object) -> list[Evidence]:
28
+ if not isinstance(items, list):
29
+ return []
30
+ out: list[Evidence] = []
31
+ for e in items:
32
+ if not isinstance(e, dict):
33
+ continue
34
+ line = e.get("line")
35
+ out.append(
36
+ Evidence(
37
+ file=str(e.get("file", "")),
38
+ line=line if isinstance(line, int) else None,
39
+ code=str(e.get("code", "")),
40
+ )
41
+ )
42
+ return out
@@ -0,0 +1,106 @@
1
+ """VerifierAgent -- check code against a capability's correct/anti patterns.
2
+
3
+ It renders the capability into a prompt, calls the provider once per capability,
4
+ and parses the JSON reply into Verdicts. It asks for one verdict per
5
+ sub_capability including SECURE / NOT_PRESENT, so a report can say what was
6
+ checked and what passed -- not only what failed.
7
+
8
+ Parsing is defensive: a missing or malformed reply yields no verdicts rather
9
+ than raising, and unknown status values fall back to UNKNOWN.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from codejury.agents.base import Agent
15
+ from codejury.agents.parsing import one_of, str_list, to_evidence, to_float
16
+ from codejury.domain.capability import Capability
17
+ from codejury.domain.context import AnalysisContext
18
+ from codejury.domain.observation import Observation, Verdict
19
+ from codejury.infrastructure.json_parse import extract_json_object
20
+ from codejury.providers.base import Message, Provider
21
+
22
+ _VALID_STATUS = {"SECURE", "VULNERABLE", "PARTIAL", "NOT_PRESENT", "UNKNOWN"}
23
+
24
+ _SYSTEM = (
25
+ "You are a security verifier. You check code against a checklist of correct and "
26
+ "anti patterns and rule on each dimension, reporting what is fine as well as what "
27
+ "is wrong. Respond with a single JSON object and nothing else."
28
+ )
29
+
30
+ _JSON_SHAPE = (
31
+ '{"verdicts": [{"sub_capability": "...", '
32
+ '"status": "SECURE|VULNERABLE|PARTIAL|NOT_PRESENT|UNKNOWN", "reasoning": "...", '
33
+ '"matched_correct": ["id"], "matched_anti": ["id"], '
34
+ '"evidence": [{"file": "path", "line": 0, "code": "..."}], "confidence": 0.0}]}'
35
+ )
36
+
37
+
38
+ class VerifierAgent(Agent):
39
+ def __init__(self, *, provider: Provider, model: str, max_tokens: int = 2048) -> None:
40
+ self._provider = provider
41
+ self._model = model
42
+ self._max_tokens = max_tokens
43
+
44
+ def run(self, ctx: AnalysisContext) -> list[Observation]:
45
+ verdicts: list[Observation] = []
46
+ for cap in ctx.capabilities:
47
+ prompt = _build_prompt(ctx.artifact.path, ctx.artifact.content, cap)
48
+ result = self._provider.complete(
49
+ system=_SYSTEM,
50
+ messages=[Message(role="user", content=prompt)],
51
+ model=self._model,
52
+ max_tokens=self._max_tokens,
53
+ )
54
+ verdicts.extend(_parse_verdicts(result.text, cap))
55
+ return verdicts
56
+
57
+
58
+ def _render_capability(cap: Capability) -> str:
59
+ lines = [f"Capability: {cap.id} ({cap.name})"]
60
+ for sub_name, sub in cap.sub_capabilities.items():
61
+ lines.append(f"\nsub_capability: {sub_name}")
62
+ if sub.correct_patterns:
63
+ lines.append(" correct patterns:")
64
+ lines += [f" - {p.id}: {p.description}" for p in sub.correct_patterns]
65
+ if sub.anti_patterns:
66
+ lines.append(" anti patterns:")
67
+ for p in sub.anti_patterns:
68
+ tag = f"[{p.cwe} {p.severity}]" if p.cwe else f"[{p.severity}]"
69
+ lines.append(f" - {p.id} {tag}: {p.description}")
70
+ return "\n".join(lines)
71
+
72
+
73
+ def _build_prompt(path: str, content: str, cap: Capability) -> str:
74
+ sub_names = ", ".join(cap.sub_capabilities) or "(none)"
75
+ return (
76
+ "Check the code below against this capability.\n\n"
77
+ f"{_render_capability(cap)}\n\n"
78
+ f"Code under review ({path}):\n```\n{content}\n```\n\n"
79
+ f"For EVERY sub_capability ({sub_names}) output one verdict, even if SECURE "
80
+ "or NOT_PRESENT. Cite matched pattern ids and evidence lines.\n\n"
81
+ "Respond with a single JSON object exactly like:\n" + _JSON_SHAPE
82
+ )
83
+
84
+
85
+ def _parse_verdicts(text: str, cap: Capability) -> list[Verdict]:
86
+ obj = extract_json_object(text)
87
+ if not obj:
88
+ return []
89
+ out: list[Verdict] = []
90
+ for v in obj.get("verdicts", []):
91
+ if not isinstance(v, dict):
92
+ continue
93
+ sub = str(v.get("sub_capability", "")).strip()
94
+ out.append(
95
+ Verdict(
96
+ capability=f"{cap.id}.{sub}" if sub else cap.id,
97
+ produced_by="verifier",
98
+ status=one_of(v.get("status"), _VALID_STATUS, "UNKNOWN"),
99
+ reasoning=str(v.get("reasoning", "")),
100
+ matched_correct=str_list(v.get("matched_correct")),
101
+ matched_anti=str_list(v.get("matched_anti")),
102
+ evidence=to_evidence(v.get("evidence")),
103
+ confidence=to_float(v.get("confidence"), 0.5),
104
+ )
105
+ )
106
+ return out