local-triage 0.0.0-stage → 0.10.0-dev.32

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 (223) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/THIRD-PARTY-NOTICES.md +48 -0
  4. package/app/__init__.py +3 -0
  5. package/app/affiliation.py +137 -0
  6. package/app/ask.py +300 -0
  7. package/app/build_info.py +98 -0
  8. package/app/capec.py +168 -0
  9. package/app/capec_view.py +27 -0
  10. package/app/codecmp.py +59 -0
  11. package/app/config.py +411 -0
  12. package/app/context.py +1451 -0
  13. package/app/cvss.py +357 -0
  14. package/app/db.py +6234 -0
  15. package/app/defect.py +670 -0
  16. package/app/defect_check.py +323 -0
  17. package/app/defect_drafts.py +612 -0
  18. package/app/defect_dto.py +149 -0
  19. package/app/defect_fields.py +248 -0
  20. package/app/defect_form.py +124 -0
  21. package/app/defect_links.py +107 -0
  22. package/app/defect_local_text.py +103 -0
  23. package/app/defect_references.py +164 -0
  24. package/app/defect_where.py +147 -0
  25. package/app/ecosystem.py +51 -0
  26. package/app/executors.py +660 -0
  27. package/app/feeds.py +1231 -0
  28. package/app/guard.py +164 -0
  29. package/app/hub_block_builder.py +200 -0
  30. package/app/hub_block_version.py +220 -0
  31. package/app/hub_defects.py +4469 -0
  32. package/app/hub_effects.py +421 -0
  33. package/app/hub_entity_versions.py +108 -0
  34. package/app/hub_import.py +2054 -0
  35. package/app/hub_onboarding.py +114 -0
  36. package/app/hub_ops.py +330 -0
  37. package/app/hub_pull.py +1195 -0
  38. package/app/hub_state.py +255 -0
  39. package/app/hub_status.py +237 -0
  40. package/app/hub_sync.py +619 -0
  41. package/app/hub_sync_api.py +241 -0
  42. package/app/hub_sync_compare.py +1054 -0
  43. package/app/hub_sync_contract.py +75 -0
  44. package/app/hub_template_model.py +74 -0
  45. package/app/hub_text_scale.py +159 -0
  46. package/app/journal.py +250 -0
  47. package/app/llm.py +850 -0
  48. package/app/llm_chat.py +596 -0
  49. package/app/llm_http.py +319 -0
  50. package/app/llm_messages.py +401 -0
  51. package/app/llm_net.py +764 -0
  52. package/app/llm_ollama.py +571 -0
  53. package/app/lockfile.py +505 -0
  54. package/app/logsafe.py +54 -0
  55. package/app/main.py +367 -0
  56. package/app/mask_display.py +132 -0
  57. package/app/masking.py +814 -0
  58. package/app/metrics.py +194 -0
  59. package/app/model_traffic.py +519 -0
  60. package/app/models.py +483 -0
  61. package/app/navigation.py +121 -0
  62. package/app/osv.py +279 -0
  63. package/app/package_identity.py +189 -0
  64. package/app/package_transition.py +824 -0
  65. package/app/profile_gate.py +71 -0
  66. package/app/prompts.py +1108 -0
  67. package/app/provider_keys.py +189 -0
  68. package/app/providers.py +511 -0
  69. package/app/routes/__init__.py +10 -0
  70. package/app/routes/api.py +153 -0
  71. package/app/routes/capec.py +186 -0
  72. package/app/routes/common.py +407 -0
  73. package/app/routes/components.py +1499 -0
  74. package/app/routes/cwe.py +168 -0
  75. package/app/routes/decision_selected.py +153 -0
  76. package/app/routes/defect_add.py +223 -0
  77. package/app/routes/defect_card_routes.py +363 -0
  78. package/app/routes/defect_selected.py +342 -0
  79. package/app/routes/feeds.py +155 -0
  80. package/app/routes/findings.py +2736 -0
  81. package/app/routes/hub.py +402 -0
  82. package/app/routes/hub_bulk.py +288 -0
  83. package/app/routes/hub_defect_routes.py +1945 -0
  84. package/app/routes/hub_status_routes.py +1132 -0
  85. package/app/routes/hub_sync_routes.py +463 -0
  86. package/app/routes/journal.py +132 -0
  87. package/app/routes/projects.py +1601 -0
  88. package/app/routes/providers.py +336 -0
  89. package/app/routes/references.py +26 -0
  90. package/app/routes/runs.py +219 -0
  91. package/app/routes/sca.py +2722 -0
  92. package/app/routes/settings.py +163 -0
  93. package/app/run_errors.py +151 -0
  94. package/app/sca.py +1662 -0
  95. package/app/sca_contract.py +1289 -0
  96. package/app/sca_research.py +1089 -0
  97. package/app/sca_research_net.py +1007 -0
  98. package/app/sca_text.py +965 -0
  99. package/app/serve.py +70 -0
  100. package/app/settings_store.py +262 -0
  101. package/app/static/app.css +2802 -0
  102. package/app/static/app.js +3772 -0
  103. package/app/static/capec-license.txt +9 -0
  104. package/app/static/favicon.svg +1 -0
  105. package/app/static/fonts/Golos-Text_DemiBold.woff2 +0 -0
  106. package/app/static/fonts/Golos-Text_Regular.woff2 +0 -0
  107. package/app/static/fonts/OFL.txt +90 -0
  108. package/app/static/navigation.js +234 -0
  109. package/app/static/observability.js +121 -0
  110. package/app/static/theme.js +49 -0
  111. package/app/storage/__init__.py +16 -0
  112. package/app/storage/local_state.py +246 -0
  113. package/app/storage/migrate.py +110 -0
  114. package/app/storage/migrations/postgresql/0001_baseline.sql +896 -0
  115. package/app/storage/migrations/postgresql/0002_feeds_and_secrets.sql +55 -0
  116. package/app/storage/migrations/postgresql/0003_project_mask_display.sql +5 -0
  117. package/app/storage/migrations/postgresql/0004_package_identity.sql +36 -0
  118. package/app/storage/postgresql.py +573 -0
  119. package/app/storage/schema.py +619 -0
  120. package/app/storage/sql.py +57 -0
  121. package/app/storage/tools.py +254 -0
  122. package/app/telemetry.py +307 -0
  123. package/app/templates/base.html +91 -0
  124. package/app/templates/capec/context.html +3 -0
  125. package/app/templates/capec/detail.html +27 -0
  126. package/app/templates/capec/index.html +128 -0
  127. package/app/templates/components/_archive.html +11 -0
  128. package/app/templates/components/archived.html +19 -0
  129. package/app/templates/components/batch.html +35 -0
  130. package/app/templates/components/detail.html +332 -0
  131. package/app/templates/components/index.html +338 -0
  132. package/app/templates/components/research_preview.html +80 -0
  133. package/app/templates/components/research_run.html +54 -0
  134. package/app/templates/cwe/bdu.html +56 -0
  135. package/app/templates/cwe/detail.html +233 -0
  136. package/app/templates/cwe/index.html +97 -0
  137. package/app/templates/error.html +8 -0
  138. package/app/templates/feeds/index.html +65 -0
  139. package/app/templates/findings/card.html +639 -0
  140. package/app/templates/findings/decision_selected.html +41 -0
  141. package/app/templates/findings/defect_add.html +46 -0
  142. package/app/templates/findings/defect_selected.html +47 -0
  143. package/app/templates/findings/list.html +153 -0
  144. package/app/templates/findings/send_selected.html +53 -0
  145. package/app/templates/findings/trace.html +72 -0
  146. package/app/templates/journal/detail.html +19 -0
  147. package/app/templates/journal/index.html +19 -0
  148. package/app/templates/macros.html +440 -0
  149. package/app/templates/navigation-fields.html +1 -0
  150. package/app/templates/navigation.html +11 -0
  151. package/app/templates/projects/_identity_summary.html +42 -0
  152. package/app/templates/projects/defect_card.html +153 -0
  153. package/app/templates/projects/defect_create_preview.html +17 -0
  154. package/app/templates/projects/defect_fields_diff.html +6 -0
  155. package/app/templates/projects/defect_fields_form.html +40 -0
  156. package/app/templates/projects/defect_references.html +17 -0
  157. package/app/templates/projects/defect_sync_preview.html +28 -0
  158. package/app/templates/projects/defect_update_actions.html +6 -0
  159. package/app/templates/projects/defect_update_preview.html +24 -0
  160. package/app/templates/projects/defects.html +126 -0
  161. package/app/templates/projects/delete.html +31 -0
  162. package/app/templates/projects/external.html +61 -0
  163. package/app/templates/projects/folders.html +64 -0
  164. package/app/templates/projects/hub_accepted.html +10 -0
  165. package/app/templates/projects/hub_assignment.html +50 -0
  166. package/app/templates/projects/hub_pending.html +20 -0
  167. package/app/templates/projects/hub_pending_list.html +17 -0
  168. package/app/templates/projects/hub_state_note.html +23 -0
  169. package/app/templates/projects/hub_step_note.html +5 -0
  170. package/app/templates/projects/hub_sync.html +105 -0
  171. package/app/templates/projects/hub_sync_confirm.html +32 -0
  172. package/app/templates/projects/hub_sync_worker.html +5 -0
  173. package/app/templates/projects/hub_text_rules.html +64 -0
  174. package/app/templates/projects/identity_report.html +74 -0
  175. package/app/templates/projects/list.html +90 -0
  176. package/app/templates/projects/project.html +433 -0
  177. package/app/templates/reference-missing.html +14 -0
  178. package/app/templates/runs/run.html +166 -0
  179. package/app/templates/sca/card.html +476 -0
  180. package/app/templates/sca/index.html +321 -0
  181. package/app/templates/settings/hub_url.html +31 -0
  182. package/app/templates/settings/index.html +216 -0
  183. package/app/templates/settings/provider.html +229 -0
  184. package/app/templates/settings/providers.html +37 -0
  185. package/app/templates/worklists.html +52 -0
  186. package/app/textsafe.py +117 -0
  187. package/app/timing.py +245 -0
  188. package/app/triage.py +1743 -0
  189. package/app/view.py +430 -0
  190. package/app/worklists.py +204 -0
  191. package/examples/demo/demo-hub-report-v2.xlsx +0 -0
  192. package/examples/demo/demo-hub-report.xlsx +0 -0
  193. package/examples/demo/repos/billing-core/pom.xml +30 -0
  194. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/Invoice.java +9 -0
  195. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceRepository.java +51 -0
  196. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceStatus.java +11 -0
  197. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/config/DatabaseSettings.java +18 -0
  198. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/payment/PaymentTokenService.java +35 -0
  199. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/web/InvoiceExportController.java +57 -0
  200. package/examples/demo/repos/catalog-api/catalog_api/__init__.py +1 -0
  201. package/examples/demo/repos/catalog-api/catalog_api/products.py +24 -0
  202. package/examples/demo/repos/catalog-api/catalog_api/tasks.py +24 -0
  203. package/examples/demo/repos/catalog-api/catalog_api/views.py +17 -0
  204. package/examples/demo/repos/catalog-api/requirements.txt +3 -0
  205. package/npm/build.json +5 -0
  206. package/npm/cli.js +346 -0
  207. package/npm/files.manifest +224 -0
  208. package/npm/lib/binding.js +64 -0
  209. package/npm/lib/cluster.js +330 -0
  210. package/npm/lib/env.js +88 -0
  211. package/npm/lib/fsx.js +125 -0
  212. package/npm/lib/http.js +53 -0
  213. package/npm/lib/metrics.js +73 -0
  214. package/npm/lib/paths.js +150 -0
  215. package/npm/lib/pg.js +351 -0
  216. package/npm/lib/proc.js +101 -0
  217. package/npm/lib/python.js +133 -0
  218. package/npm/lib/stand.js +46 -0
  219. package/npm/lib/supervisor.js +1141 -0
  220. package/npm/lib/version.js +21 -0
  221. package/npm/requirements.txt +476 -0
  222. package/npm-shrinkwrap.json +111 -0
  223. package/package.json +37 -4
package/app/models.py ADDED
@@ -0,0 +1,483 @@
1
+ """Модели данных: находка, итог разбора выгрузки, контекст кода, вердикт модели, замеры работы модели, ответ
2
+ внешнего агента по компоненту SCA.
3
+
4
+ Все классы – dataclass. Метод to_dict() отдаёт обычный словарь (для JSON и базы), from_dict() собирает объект
5
+ обратно: лишние ключи пропускаются, недостающие получают значения по умолчанию, типы приводятся мягко
6
+ («58» -> 58, «9.8» -> 9.8, строка CWE через запятую -> список).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses
12
+ import hashlib
13
+ import json
14
+ import math
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ KINDS = ("SAST", "SCA", "SCA-license", "DAST")
19
+ SEVERITIES = ("critical", "high", "medium", "low", "info") # от самой высокой
20
+ CONTEXT_STATUSES = ("ok", "export_line_only", "file_missing", "no_repo", "too_large", "binary")
21
+ EXPORT_LINE_CHECKS = ("match", "near", "commented", "partial", "differs", "no_export_line", "short_export_line",
22
+ "masked_export_line", "n/a")
23
+ # Сверки, при которых фрагмент из выгрузки не подтверждён показанным кодом: уверенность ограничена (ADR-0080, ADR-0082)
24
+ UNCONFIRMED_EXPORT_CHECKS = ("differs", "commented", "partial")
25
+ TARGET_MARK = ">>" # метка строки срабатывания в CodeContext.numbered()
26
+ SCA_CONCLUSIONS = ("update", "not_applicable", "unclear") # вывод по компоненту: обновить / не применимо / неясно
27
+
28
+
29
+ @dataclass
30
+ class Finding:
31
+ """Находка из выгрузки AppSec.Hub (одна строка листа практики)."""
32
+
33
+ hub_id: str
34
+ kind: str # 'SAST' | 'SCA' | 'SCA-license' | 'DAST'
35
+ tool: str = "" # колонка Found By
36
+ application: str = ""
37
+ severity: str = "" # critical/high/medium/low/info; у SCA отчёта Hub – "" (см. policy_severity)
38
+ policy_severity: str = "" # у SCA отчёта Hub колонка Severity – уровень политики Hub, а не тяжесть уязвимости
39
+ cvss: float | None = None
40
+ rule: str = "" # колонка Category
41
+ cwe: list[str] = field(default_factory=list) # ['CWE-89']
42
+ cwe_links: list[str] = field(default_factory=list)
43
+ codebase: str = ""
44
+ file: str = "" # прямые слэши, от корня кодовой базы
45
+ line: int | None = None
46
+ snippet: str = "" # Source code без хвоста « : N»
47
+ status: str = ""
48
+ language: str = ""
49
+ build_type: str = "" # колонка Type: тип сборки или экосистема пакета, а не вид находки
50
+ component: str = ""
51
+ version: str = ""
52
+ fixed_version: str = ""
53
+ dep_path: str = "" # колонка Path у SCA – путь зависимости, а не файл
54
+ vuln_ids: list[str] = field(default_factory=list) # идентификаторы уязвимостей, кроме CVE (AST-…, GHSA-…)
55
+ cve: list[str] = field(default_factory=list)
56
+ licenses: str = ""
57
+ location: str = "" # адрес проверки DAST
58
+ extra: dict[str, str] = field(default_factory=dict) # колонки выгрузки без своего поля
59
+ sheet: str = "" # лист книги
60
+ row: int = 0 # номер строки на листе, как в Excel
61
+ # эффективная идентичность пакета SCA из колонок findings.pkg_* (план dev17, п. 4.2): только во время работы,
62
+ # в data_json, finding_data_sig и отпечатки не входит – to_dict поля с метаданными runtime исключает
63
+ package: dict = field(default_factory=dict, metadata={"runtime": True})
64
+
65
+ def to_dict(self) -> dict[str, Any]:
66
+ data = dataclasses.asdict(self)
67
+ for f in dataclasses.fields(self):
68
+ if f.metadata.get("runtime"):
69
+ data.pop(f.name, None)
70
+ return data
71
+
72
+ def _identity_data(self) -> dict[str, Any]:
73
+ return {"build_type": self.build_type, "component": self.component, "version": self.version,
74
+ "package": self.package}
75
+
76
+ @property
77
+ def package_ecosystem(self) -> str:
78
+ """Эффективная экосистема пакета (сведения Hub о библиотеке или Type выгрузки)."""
79
+ from app import package_identity
80
+ return package_identity.of(self._identity_data())[0]
81
+
82
+ @property
83
+ def package_name(self) -> str:
84
+ """Эффективное имя пакета: координаты Maven, имя npm с областью или компонент выгрузки."""
85
+ from app import package_identity
86
+ return package_identity.of(self._identity_data())[1]
87
+
88
+ @property
89
+ def identity_marks(self) -> list[str]:
90
+ """Пометки идентичности пакета для оператора (план dev17, п. 4.6)."""
91
+ from app import package_identity
92
+ return package_identity.mark_texts(self._identity_data())
93
+
94
+ @property
95
+ def package_display_name(self) -> str:
96
+ """Короткое имя для текстов Hub: у Maven – artifactId, у остальных – эффективное имя."""
97
+ from app import package_identity
98
+ return package_identity.display_name(self._identity_data())
99
+
100
+ @classmethod
101
+ def from_dict(cls, data: dict[str, Any] | None) -> Finding:
102
+ return _from_dict(cls, data)
103
+
104
+
105
+ @dataclass
106
+ class ImportResult:
107
+ """Итог разбора выгрузки.
108
+
109
+ format – 'hub' (отчёт AppSec.Hub) или 'table' (одна таблица с заголовками);
110
+ sheets – по записи на лист книги: {'name', 'rows', 'skipped', 'reason', ...};
111
+ summary – {'application', 'by_practice', 'by_severity', 'total', 'report_created', ...};
112
+ warnings – предупреждения по-русски.
113
+ """
114
+
115
+ findings: list[Finding]
116
+ format: str
117
+ sheets: list[dict]
118
+ summary: dict
119
+ warnings: list[str]
120
+
121
+ def to_dict(self) -> dict[str, Any]:
122
+ data = dataclasses.asdict(self)
123
+ data["findings"] = [f.to_dict() for f in self.findings] # без полей времени работы (Finding.package)
124
+ return data
125
+
126
+ @classmethod
127
+ def from_dict(cls, data: dict[str, Any] | None) -> ImportResult:
128
+ return _from_dict(cls, data)
129
+
130
+
131
+ @dataclass
132
+ class CodeContext:
133
+ """Срез кода вокруг находки.
134
+
135
+ status – 'ok' | 'export_line_only' | 'file_missing' | 'no_repo' | 'too_large' | 'binary';
136
+ file – путь файла от корня репозитория (если файл не найден – путь из находки);
137
+ start_line, end_line – номера первой и последней строки среза (0 – номеров нет);
138
+ target_line – строка срабатывания (None – неизвестна или вне среза);
139
+ lines – строки среза без номеров (после маскирования, если был ключ);
140
+ enclosing – сигнатура объемлющего метода или функции;
141
+ export_line_check – match, near (фрагмент найден), commented (только в комментарии), partial (совпала часть),
142
+ differs; нейтральные no_export_line, short_export_line, masked_export_line, n/a;
143
+ export_line_at – номер строки найденного фрагмента, иначе None;
144
+ export_line_check_version – 0: прежняя сверка, 1: сверка по фрагменту до маскирования (вхождение в обе стороны),
145
+ 2: точное совпадение отдельно от частичного и закомментированного (ADR-0082);
146
+ masked – сколько значений замаскировано в срезе, по типам: {'SECRET': 1, 'EMAIL': 2};
147
+ note – пояснения по-русски (почему нет кода, что сокращено);
148
+ reason – причина отсутствия кода из файла; пусто для «ok» и срезов прежних версий.
149
+ """
150
+
151
+ status: str
152
+ file: str
153
+ language: str
154
+ start_line: int
155
+ end_line: int
156
+ target_line: int | None
157
+ lines: list[str] = field(metadata={"code_lines": True}) # пустые строки кода сохраняются: на них нумерация
158
+ enclosing: str = ""
159
+ export_line_check: str = ""
160
+ masked: dict[str, int] = field(default_factory=dict)
161
+ note: str = ""
162
+ reason: str = ""
163
+ export_line_at: int | None = None
164
+ export_line_check_version: int = 0
165
+ # Сверка версии 1 по коду до маскирования – только для отпечатка случая (triage.case_hash, ADR-0082): уточнение
166
+ # сверки не меняет отпечаток неизменного кода. У срезов версий 0–1 пусто: отпечаток берёт export_line_check.
167
+ hash_check: str = ""
168
+ hash_check_at: int | None = None
169
+
170
+ def text_at(self, number: int | None) -> str:
171
+ """Строка среза по номеру в файле; вне среза – пусто."""
172
+ if number is None or not self.start_line or not self.start_line <= number < self.start_line + len(self.lines):
173
+ return ""
174
+ return self.lines[number - self.start_line]
175
+
176
+ def rows(self) -> list[tuple[int, str, bool]]:
177
+ """Строки среза для показа: (номер, текст, это строка срабатывания). Без номеров – номер 0."""
178
+ result = []
179
+ for k, text in enumerate(self.lines):
180
+ n = self.start_line + k if self.start_line >= 1 else 0
181
+ result.append((n, text, bool(n) and n == self.target_line))
182
+ return result
183
+
184
+ def numbered(self) -> str:
185
+ """Строки среза с номерами для промпта: «>> 58| код» у строки срабатывания, « 57| код» у остальных.
186
+
187
+ Если номеров нет (строка из выгрузки без номера строки), строки отдаются как есть.
188
+ """
189
+ if not self.lines:
190
+ return ""
191
+ if self.start_line < 1:
192
+ return "\n".join(self.lines)
193
+ width = max(5, len(str(self.start_line + len(self.lines) - 1)))
194
+ out = []
195
+ for n, text, is_target in self.rows():
196
+ mark = TARGET_MARK if is_target else " " * len(TARGET_MARK)
197
+ out.append(f"{mark}{n:>{width}}| {text}")
198
+ return "\n".join(out)
199
+
200
+ def to_dict(self) -> dict[str, Any]:
201
+ return dataclasses.asdict(self)
202
+
203
+ @classmethod
204
+ def from_dict(cls, data: dict[str, Any] | None) -> CodeContext:
205
+ return _from_dict(cls, data)
206
+
207
+
208
+ @dataclass
209
+ class Verdict:
210
+ """Ответ модели по находке.
211
+
212
+ Поля обеих версий промпта: verdict, confidence, summary (одна фраза), data_flow (шаги пути данных), fix,
213
+ hub_comment, cwe_fit. Только sast-v2: explanation (обоснование одним текстом), evidence_lines (номера строк-
214
+ доказательств). Только sast-v3 – объяснение для человека, который читает код, но давно не программирует:
215
+ what_code_does (что делает фрагмент, простыми словами), why (почему такой вердикт – по шагам, со ссылками
216
+ «строка N»), check_by_eye (2–4 пункта «что проверить глазами»), terms (словарик: [{"term", "meaning"}]).
217
+ Вердикт одной версии читается с пустыми полями другой.
218
+
219
+ why и check_by_eye – списки пунктов: строка из базы делится на пункты по переводам строк, а не по запятым
220
+ (пункт – это фраза, запятые в нём свои). Разбор ответа модели (prompts.py) приводит поля к этим типам сам.
221
+ """
222
+
223
+ verdict: str # 'true_positive' | 'false_positive' | 'uncertain'
224
+ confidence: int
225
+ summary: str = ""
226
+ explanation: str = ""
227
+ data_flow: list[str] = field(default_factory=list)
228
+ evidence_lines: list[int] = field(default_factory=list)
229
+ fix: str = ""
230
+ hub_comment: str = ""
231
+ cwe_fit: str = "" # 'да' | 'нет' | 'частично'
232
+ raw: dict = field(default_factory=dict)
233
+ what_code_does: str = ""
234
+ why: list[str] = field(default_factory=list, metadata={"text_list": True})
235
+ check_by_eye: list[str] = field(default_factory=list, metadata={"text_list": True})
236
+ terms: list[dict[str, str]] = field(default_factory=list, metadata={"terms": True})
237
+ # sast-v7 (ADR-0109): цитаты кода со статусом сверки приложением ([{"line", "code", "status", "found_line",
238
+ # "note"}], prompts.check_quotes) и «какого кода не хватило»; у прежних версий пустые
239
+ evidence_quotes: list[dict] = field(default_factory=list)
240
+ missing_context: str = ""
241
+
242
+ def to_dict(self) -> dict[str, Any]:
243
+ return dataclasses.asdict(self)
244
+
245
+ @classmethod
246
+ def from_dict(cls, data: dict[str, Any] | None) -> Verdict:
247
+ return _from_dict(cls, data)
248
+
249
+
250
+ @dataclass
251
+ class ScaAnswer:
252
+ """Ответ внешнего агента по пакету SCA (группа «экосистема + компонент + версия»).
253
+
254
+ recommended_version – версия, до которой обновить; conclusion – 'update' (обновить), 'not_applicable'
255
+ (не применимо), 'unclear' (неясно) или "" (агент не ответил); explanation – пояснение; ids – соответствие
256
+ идентификаторов уязвимостей: {"AST-…": ["CVE-…", "GHSA-…"]}; links – ссылки на источники; vulnerabilities –
257
+ охват ответа: уязвимости, по которым агент отвечал (из ответа или из пакета на момент загрузки). Ответ
258
+ не относится к уязвимости, которой в охвате нет (новая CVE после повторной выгрузки).
259
+ """
260
+
261
+ component: str
262
+ version: str
263
+ recommended_version: str = ""
264
+ conclusion: str = ""
265
+ explanation: str = ""
266
+ ids: dict[str, list[str]] = field(default_factory=dict)
267
+ links: list[str] = field(default_factory=list)
268
+ vulnerabilities: list[str] = field(default_factory=list)
269
+ ecosystem: str = "" # экосистема пакета (app/ecosystem.py): часть идентичности вместе с именем и версией
270
+
271
+ def complete(self) -> bool:
272
+ """Ответ по существу: вывод распознан, пояснение есть, у «обновить» – версия для обновления."""
273
+ return (self.conclusion in SCA_CONCLUSIONS and bool(self.explanation.strip())
274
+ and (self.conclusion != "update" or bool(self.recommended_version.strip())))
275
+
276
+ def signature(self) -> str:
277
+ """Существенная часть ответа – вывод, версия, охват и соответствия идентификаторов (AST → CVE): от неё
278
+ зависит решение «Согласен с агентом». Смена CVE под тем же AST меняет описание БДУ и основания решения,
279
+ поэтому тоже снимает «Проверено». Идентификаторы сравниваются без учёта регистра и порядка."""
280
+ ids = {str(k).strip().upper(): sorted({str(x).strip().upper() for x in (v or []) if str(x).strip()})
281
+ for k, v in (self.ids or {}).items() if str(k).strip()}
282
+ data = {"conclusion": self.conclusion, "recommended_version": self.recommended_version,
283
+ "vulnerabilities": sorted(self.vulnerabilities), "ids": ids}
284
+ return hashlib.sha256(json.dumps(data, sort_keys=True).encode("utf-8")).hexdigest()[:24]
285
+
286
+ def to_dict(self) -> dict[str, Any]:
287
+ return dataclasses.asdict(self)
288
+
289
+ @classmethod
290
+ def from_dict(cls, data: dict[str, Any] | None) -> ScaAnswer:
291
+ answer = _from_dict(cls, data)
292
+ if answer.conclusion not in SCA_CONCLUSIONS:
293
+ answer.conclusion = ""
294
+ return answer
295
+
296
+
297
+ @dataclass
298
+ class LlmStats:
299
+ """Замеры одного ответа модели."""
300
+
301
+ model: str
302
+ prompt_tokens: int
303
+ output_tokens: int
304
+ eval_tps: float # токенов в секунду при выводе
305
+ prompt_tps: float # токенов в секунду при чтении промпта
306
+ total_s: float
307
+ load_s: float
308
+ attempts: int
309
+ # уровень рассуждения каждой попытки отправки после успешного допуска (ADR-0102): через запятую; low/medium/high
310
+ # – уровень gpt-oss, on/off – рассуждение другой модели включено/выключено, «-» – поле не передавалось; пусто –
311
+ # ответ до 0.9.12 или ни одна попытка не прошла допуск
312
+ think: str = ""
313
+ # 0.9.13, API чат-завершений: токены рассуждения и попадания в кэш провайдера (usage); timing – откуда время:
314
+ # "server" – длительности сервера, "app" – часы приложения (скорость токенов неизвестна, 0), "" – запись до 0.9.13
315
+ reasoning_tokens: int = 0
316
+ cache_hit_tokens: int = 0
317
+ timing: str = ""
318
+ # 0.9.14: сколько раз запрос автоматически отправлен заново после обрыва без ответа
319
+ # (отметка профиля внешнего провайдера «Повторять после обрыва без ответа»; не больше одного раза на находку)
320
+ drop_retries: int = 0
321
+
322
+ def to_dict(self) -> dict[str, Any]:
323
+ return dataclasses.asdict(self)
324
+
325
+ @classmethod
326
+ def from_dict(cls, data: dict[str, Any] | None) -> LlmStats:
327
+ return _from_dict(cls, data)
328
+
329
+
330
+ # ---------------------------------------------------------------- мягкое приведение типов для from_dict
331
+
332
+
333
+ def _to_str(value: Any) -> str:
334
+ return "" if value is None else str(value)
335
+
336
+
337
+ def _to_float_or_none(value: Any) -> float | None:
338
+ if value is None or isinstance(value, bool) or value == "":
339
+ return None
340
+ try:
341
+ number = float(str(value).replace(",", ".")) if isinstance(value, str) else float(value)
342
+ except (TypeError, ValueError):
343
+ return None
344
+ return None if math.isnan(number) or math.isinf(number) else number
345
+
346
+
347
+ def _to_int_or_none(value: Any) -> int | None:
348
+ number = _to_float_or_none(value)
349
+ return int(number) if number is not None and number.is_integer() else None
350
+
351
+
352
+ def _to_int(value: Any) -> int:
353
+ number = _to_int_or_none(value)
354
+ return 0 if number is None else number
355
+
356
+
357
+ def _to_float(value: Any) -> float:
358
+ number = _to_float_or_none(value)
359
+ return 0.0 if number is None else number
360
+
361
+
362
+ def _to_str_list(value: Any) -> list[str]:
363
+ if value is None or value == "":
364
+ return []
365
+ if isinstance(value, str):
366
+ return [part.strip() for part in value.split(",") if part.strip()]
367
+ if isinstance(value, (list, tuple, set)):
368
+ return [_to_str(x) for x in value if x is not None and _to_str(x) != ""]
369
+ return [_to_str(value)]
370
+
371
+
372
+ def _to_code_lines(value: Any) -> list[str]:
373
+ """Строки кода: пустая строка – тоже строка кода, её нельзя выбрасывать, иначе съедут номера строк."""
374
+ if value is None or value == "":
375
+ return []
376
+ if isinstance(value, str):
377
+ return value.split("\n")
378
+ if isinstance(value, (list, tuple)):
379
+ return ["" if x is None else _to_str(x) for x in value]
380
+ return []
381
+
382
+
383
+ def _to_text_list(value: Any) -> list[str]:
384
+ """Пункты текста (шаги, «что проверить»): строка делится по переводам строк, а не по запятым."""
385
+ if value is None or value == "":
386
+ return []
387
+ if isinstance(value, str):
388
+ return [part.strip() for part in value.split("\n") if part.strip()]
389
+ if isinstance(value, (list, tuple)):
390
+ return [_to_str(x).strip() for x in value if x is not None and _to_str(x).strip()]
391
+ return [_to_str(value)]
392
+
393
+
394
+ def _to_terms(value: Any) -> list[dict[str, str]]:
395
+ """Словарик терминов: [{"term", "meaning"}]; словарь «термин: пояснение» тоже принимается. Пункты без термина
396
+ пропускаются."""
397
+ if isinstance(value, dict):
398
+ value = [{"term": k, "meaning": v} for k, v in value.items()]
399
+ if not isinstance(value, (list, tuple)):
400
+ return []
401
+ result = []
402
+ for item in value:
403
+ if not isinstance(item, dict):
404
+ continue
405
+ term = _to_str(item.get("term")).strip()
406
+ if term:
407
+ result.append({"term": term, "meaning": _to_str(item.get("meaning")).strip()})
408
+ return result
409
+
410
+
411
+ def _to_str_list_dict(value: Any) -> dict[str, list[str]]:
412
+ return {_to_str(k): _to_str_list(v) for k, v in value.items()} if isinstance(value, dict) else {}
413
+
414
+
415
+ def _to_int_list(value: Any) -> list[int]:
416
+ items = _to_str_list(value) if isinstance(value, str) else (value if isinstance(value, (list, tuple)) else [])
417
+ result = []
418
+ for item in items:
419
+ number = _to_int_or_none(item)
420
+ if number is not None:
421
+ result.append(number)
422
+ return result
423
+
424
+
425
+ def _to_dict(value: Any) -> dict:
426
+ return dict(value) if isinstance(value, dict) else {}
427
+
428
+
429
+ def _to_str_dict(value: Any) -> dict[str, str]:
430
+ return {_to_str(k): _to_str(v) for k, v in value.items()} if isinstance(value, dict) else {}
431
+
432
+
433
+ def _to_int_dict(value: Any) -> dict[str, int]:
434
+ return {_to_str(k): _to_int(v) for k, v in value.items()} if isinstance(value, dict) else {}
435
+
436
+
437
+ def _to_findings(value: Any) -> list[Finding]:
438
+ if not isinstance(value, (list, tuple)):
439
+ return []
440
+ return [x if isinstance(x, Finding) else Finding.from_dict(x) for x in value if isinstance(x, (Finding, dict))]
441
+
442
+
443
+ def _to_dict_list(value: Any) -> list[dict]:
444
+ return [dict(x) for x in value if isinstance(x, dict)] if isinstance(value, (list, tuple)) else []
445
+
446
+
447
+ _COERCE = {
448
+ "str": _to_str,
449
+ "int": _to_int,
450
+ "float": _to_float,
451
+ "float | None": _to_float_or_none,
452
+ "int | None": _to_int_or_none,
453
+ "list[str]": _to_str_list,
454
+ "list[int]": _to_int_list,
455
+ "list[dict]": _to_dict_list,
456
+ "list[Finding]": _to_findings,
457
+ "dict": _to_dict,
458
+ "dict[str, str]": _to_str_dict,
459
+ "dict[str, int]": _to_int_dict,
460
+ "dict[str, list[str]]": _to_str_list_dict,
461
+ }
462
+ # Особые приведения по метаданным поля (тип у них общий, а правила свои)
463
+ _COERCE_META = {"code_lines": _to_code_lines, "text_list": _to_text_list, "terms": _to_terms}
464
+
465
+
466
+ def _coercer(f: dataclasses.Field):
467
+ for flag, coerce in _COERCE_META.items():
468
+ if f.metadata.get(flag):
469
+ return coerce
470
+ return _COERCE.get(str(f.type), lambda v: v)
471
+
472
+
473
+ def _from_dict(cls, data):
474
+ """Объект dataclass из словаря: лишние ключи пропускаются, недостающие – по умолчанию или «пустые»."""
475
+ data = data if isinstance(data, dict) else {}
476
+ kwargs = {}
477
+ for f in dataclasses.fields(cls):
478
+ coerce = _coercer(f)
479
+ if f.name in data:
480
+ kwargs[f.name] = coerce(data[f.name])
481
+ elif f.default is dataclasses.MISSING and f.default_factory is dataclasses.MISSING:
482
+ kwargs[f.name] = coerce(None)
483
+ return cls(**kwargs)
@@ -0,0 +1,121 @@
1
+ """Исходная рабочая задача и предыдущая справочная статья – независимые пути возврата."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from urllib.parse import parse_qsl, unquote, urlencode, urlsplit, urlunsplit
6
+
7
+ PROJECT_PAGE = re.compile(r"/projects/([0-9]+)/(findings|sca/findings|components|sca)(?:/([^/]+))?")
8
+ RUN_PAGE = re.compile(r"/(runs|journal)/([0-9]+)")
9
+
10
+
11
+ def local_url(value):
12
+ if not isinstance(value, str) or len(value) > 6000 or not value.startswith("/"):
13
+ return ""
14
+ try:
15
+ p = urlsplit(value)
16
+ except ValueError:
17
+ return ""
18
+ if p.scheme or p.netloc or "\\" in value or any(ord(c) < 32 for c in value):
19
+ return ""
20
+ return value
21
+
22
+
23
+ def clean_url(value, *, article=False):
24
+ value = local_url(value)
25
+ if not value:
26
+ return ""
27
+ p = urlsplit(value)
28
+ ignored = {"origin", "via", "ok", "err", "saved"}
29
+ if article:
30
+ ignored.add("back")
31
+ return urlunsplit(("", "", p.path, urlencode([(k, v) for k, v in parse_qsl(p.query)
32
+ if k not in ignored]), p.fragment))
33
+
34
+
35
+ def reference_url(value):
36
+ p = urlsplit(local_url(value))
37
+ return p.path in ("/cwe", "/capec", "/feeds", "/settings", "/journal") or \
38
+ p.path.startswith(("/cwe/", "/capec/", "/bdu/", "/journal/", "/runs/")) or \
39
+ bool(re.fullmatch(r"/projects/[0-9]+/capec", p.path))
40
+
41
+
42
+ def source_context(origin, db):
43
+ origin = clean_url(origin)
44
+ if not origin:
45
+ return None
46
+ p = urlsplit(origin)
47
+ m = PROJECT_PAGE.fullmatch(p.path)
48
+ if m:
49
+ pid, kind, ident = int(m[1]), m[2], unquote(m[3] or "")
50
+ if kind == "sca" and ident:
51
+ return None
52
+ project = db.get_project(pid)
53
+ if not project:
54
+ return None
55
+ fallback = f"/projects/{pid}/" + ("sca" if kind == "sca/findings" else kind)
56
+ title = {"findings": "Находки", "sca/findings": "SCA", "sca": "SCA", "components": "Компоненты"}[kind]
57
+ if ident:
58
+ if kind == "components":
59
+ from app.routes.components import views
60
+ row = next((r for r in views(db, pid)[0] if r["input_ref"] == ident), None)
61
+ if not row:
62
+ return None
63
+ label = f"{row['name']}@{row['version']}"
64
+ title = "К компоненту " + label
65
+ else:
66
+ row = db.get_finding(pid, int(ident)) if ident.isascii() and ident.isdigit() else None
67
+ if not row:
68
+ return None
69
+ label = str(row["hub_id"])
70
+ title = "К находке " + label
71
+ else:
72
+ label = title
73
+ title = "К списку: " + title
74
+ back = dict(parse_qsl(p.query)).get("back", "")
75
+ queue = local_url(back)
76
+ if not ident:
77
+ queue = origin
78
+ elif not queue or urlsplit(queue).path not in ({fallback, f"/projects/{pid}/findings"} if kind == "sca/findings" else {fallback}):
79
+ filters = [(k, v) for k, v in parse_qsl(p.query) if k not in ("back", "origin", "via")]
80
+ queue = fallback + ("?" + urlencode(filters) if filters else "")
81
+ return {"origin": origin, "queue": queue, "label": label, "title": title,
82
+ "project": project["name"], "missing": bool(ident and row.get("missing", row.get("export_missing")))}
83
+ if p.path == "/journal" or RUN_PAGE.fullmatch(p.path):
84
+ queue = local_url(dict(parse_qsl(p.query)).get("back", ""))
85
+ if not queue or urlsplit(queue).path != "/journal":
86
+ queue = origin if p.path == "/journal" else "/journal"
87
+ return {"origin": origin, "queue": queue, "label": "Журнал" if p.path == "/journal" else "Прогон №" + p.path.rsplit("/", 1)[-1],
88
+ "title": "К журналу" if p.path == "/journal" else "К прогону №" + p.path.rsplit("/", 1)[-1],
89
+ "project": "Локальная модель", "missing": False}
90
+ return None
91
+
92
+
93
+ def page_context(request, values, db):
94
+ path = request.url.path
95
+ current = clean_url(path + ("?" + request.url.query if request.url.query else ""))
96
+ # Самостоятельно открытая карточка начинает новую задачу; переходы по справочникам её не заменяют.
97
+ own = bool(PROJECT_PAGE.fullmatch(path) or RUN_PAGE.fullmatch(path)) or path == "/journal"
98
+ origin = current if own and not request.query_params.get("origin") else request.query_params.get("origin", "")
99
+ if not origin and request.method == "POST" and values.get("row"):
100
+ origin = clean_url(path.rsplit("/", 1)[0] + ("?" + request.url.query if request.url.query else ""))
101
+ task = source_context(origin, db)
102
+ via = clean_url(request.query_params.get("via", ""), article=True)
103
+ if not reference_url(via) or urlsplit(via).path == path:
104
+ via = ""
105
+ if task:
106
+ task.update(via=via, visible=reference_url(path) and current != task["origin"])
107
+
108
+ def link(value):
109
+ value = str(value or "")
110
+ if not task or not local_url(value) or not reference_url(value):
111
+ return value
112
+ target = urlsplit(value)
113
+ params = [(k, clean_url(v, article=True) if k == "back" and reference_url(v) else v)
114
+ for k, v in parse_qsl(target.query) if k not in ("origin", "via")]
115
+ params.append(("origin", task["origin"]))
116
+ previous = clean_url(current, article=True) if reference_url(path) and path != target.path else via
117
+ if previous and previous != task["origin"]:
118
+ params.append(("via", previous))
119
+ return urlunsplit(("", "", target.path, urlencode(params), target.fragment))
120
+
121
+ return {"task_context": task, "work_link": link}