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

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 (241) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +194 -2
  3. package/THIRD-PARTY-NOTICES.md +61 -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 +99 -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 +1493 -0
  13. package/app/cvss.py +357 -0
  14. package/app/db.py +6382 -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/example_tree.py +48 -0
  27. package/app/examples.py +622 -0
  28. package/app/executors.py +670 -0
  29. package/app/feeds.py +1231 -0
  30. package/app/guard.py +164 -0
  31. package/app/hub_block_builder.py +200 -0
  32. package/app/hub_block_version.py +220 -0
  33. package/app/hub_defects.py +4469 -0
  34. package/app/hub_effects.py +421 -0
  35. package/app/hub_entity_versions.py +108 -0
  36. package/app/hub_import.py +2054 -0
  37. package/app/hub_onboarding.py +114 -0
  38. package/app/hub_ops.py +330 -0
  39. package/app/hub_pull.py +1195 -0
  40. package/app/hub_state.py +255 -0
  41. package/app/hub_status.py +237 -0
  42. package/app/hub_sync.py +619 -0
  43. package/app/hub_sync_api.py +241 -0
  44. package/app/hub_sync_compare.py +1054 -0
  45. package/app/hub_sync_contract.py +75 -0
  46. package/app/hub_template_model.py +74 -0
  47. package/app/hub_text_scale.py +159 -0
  48. package/app/journal.py +250 -0
  49. package/app/llm.py +850 -0
  50. package/app/llm_chat.py +596 -0
  51. package/app/llm_http.py +319 -0
  52. package/app/llm_messages.py +401 -0
  53. package/app/llm_net.py +764 -0
  54. package/app/llm_ollama.py +571 -0
  55. package/app/lockfile.py +510 -0
  56. package/app/logsafe.py +54 -0
  57. package/app/main.py +373 -0
  58. package/app/mask_display.py +132 -0
  59. package/app/masking.py +814 -0
  60. package/app/metrics.py +194 -0
  61. package/app/model_traffic.py +519 -0
  62. package/app/models.py +483 -0
  63. package/app/navigation.py +121 -0
  64. package/app/osv.py +279 -0
  65. package/app/package_identity.py +189 -0
  66. package/app/package_transition.py +824 -0
  67. package/app/profile_gate.py +71 -0
  68. package/app/prompts.py +1108 -0
  69. package/app/provider_keys.py +189 -0
  70. package/app/providers.py +529 -0
  71. package/app/routes/__init__.py +10 -0
  72. package/app/routes/api.py +153 -0
  73. package/app/routes/capec.py +186 -0
  74. package/app/routes/common.py +407 -0
  75. package/app/routes/components.py +1499 -0
  76. package/app/routes/cwe.py +168 -0
  77. package/app/routes/decision_selected.py +153 -0
  78. package/app/routes/defect_add.py +223 -0
  79. package/app/routes/defect_card_routes.py +363 -0
  80. package/app/routes/defect_selected.py +342 -0
  81. package/app/routes/examples.py +661 -0
  82. package/app/routes/feeds.py +155 -0
  83. package/app/routes/findings.py +2758 -0
  84. package/app/routes/hub.py +402 -0
  85. package/app/routes/hub_bulk.py +288 -0
  86. package/app/routes/hub_defect_routes.py +1945 -0
  87. package/app/routes/hub_status_routes.py +1132 -0
  88. package/app/routes/hub_sync_routes.py +463 -0
  89. package/app/routes/journal.py +132 -0
  90. package/app/routes/projects.py +1665 -0
  91. package/app/routes/providers.py +403 -0
  92. package/app/routes/references.py +26 -0
  93. package/app/routes/runs.py +219 -0
  94. package/app/routes/sca.py +2722 -0
  95. package/app/routes/settings.py +163 -0
  96. package/app/run_errors.py +151 -0
  97. package/app/sca.py +1662 -0
  98. package/app/sca_contract.py +1289 -0
  99. package/app/sca_research.py +1089 -0
  100. package/app/sca_research_net.py +1007 -0
  101. package/app/sca_text.py +965 -0
  102. package/app/serve.py +70 -0
  103. package/app/settings_store.py +262 -0
  104. package/app/static/app.css +2820 -0
  105. package/app/static/app.js +3772 -0
  106. package/app/static/capec-license.txt +9 -0
  107. package/app/static/favicon.svg +1 -0
  108. package/app/static/fonts/Golos-Text_DemiBold.woff2 +0 -0
  109. package/app/static/fonts/Golos-Text_Regular.woff2 +0 -0
  110. package/app/static/fonts/OFL.txt +90 -0
  111. package/app/static/navigation.js +234 -0
  112. package/app/static/observability.js +121 -0
  113. package/app/static/theme.js +82 -0
  114. package/app/storage/__init__.py +16 -0
  115. package/app/storage/local_state.py +246 -0
  116. package/app/storage/migrate.py +110 -0
  117. package/app/storage/migrations/postgresql/0001_baseline.sql +896 -0
  118. package/app/storage/migrations/postgresql/0002_feeds_and_secrets.sql +55 -0
  119. package/app/storage/migrations/postgresql/0003_project_mask_display.sql +5 -0
  120. package/app/storage/migrations/postgresql/0004_package_identity.sql +36 -0
  121. package/app/storage/postgresql.py +573 -0
  122. package/app/storage/schema.py +619 -0
  123. package/app/storage/sql.py +57 -0
  124. package/app/storage/tools.py +254 -0
  125. package/app/telemetry.py +307 -0
  126. package/app/templates/base.html +93 -0
  127. package/app/templates/capec/context.html +3 -0
  128. package/app/templates/capec/detail.html +27 -0
  129. package/app/templates/capec/index.html +128 -0
  130. package/app/templates/components/_archive.html +11 -0
  131. package/app/templates/components/archived.html +19 -0
  132. package/app/templates/components/batch.html +35 -0
  133. package/app/templates/components/detail.html +332 -0
  134. package/app/templates/components/index.html +338 -0
  135. package/app/templates/components/research_preview.html +80 -0
  136. package/app/templates/components/research_run.html +54 -0
  137. package/app/templates/cwe/bdu.html +56 -0
  138. package/app/templates/cwe/detail.html +233 -0
  139. package/app/templates/cwe/index.html +97 -0
  140. package/app/templates/error.html +8 -0
  141. package/app/templates/examples/index.html +67 -0
  142. package/app/templates/examples/mapping.html +26 -0
  143. package/app/templates/feeds/index.html +65 -0
  144. package/app/templates/findings/card.html +641 -0
  145. package/app/templates/findings/decision_selected.html +41 -0
  146. package/app/templates/findings/defect_add.html +46 -0
  147. package/app/templates/findings/defect_selected.html +47 -0
  148. package/app/templates/findings/list.html +153 -0
  149. package/app/templates/findings/send_selected.html +53 -0
  150. package/app/templates/findings/trace.html +72 -0
  151. package/app/templates/help.html +50 -0
  152. package/app/templates/journal/detail.html +19 -0
  153. package/app/templates/journal/index.html +19 -0
  154. package/app/templates/macros.html +440 -0
  155. package/app/templates/navigation-fields.html +1 -0
  156. package/app/templates/navigation.html +11 -0
  157. package/app/templates/projects/_identity_summary.html +42 -0
  158. package/app/templates/projects/defect_card.html +153 -0
  159. package/app/templates/projects/defect_create_preview.html +17 -0
  160. package/app/templates/projects/defect_fields_diff.html +6 -0
  161. package/app/templates/projects/defect_fields_form.html +40 -0
  162. package/app/templates/projects/defect_references.html +17 -0
  163. package/app/templates/projects/defect_sync_preview.html +28 -0
  164. package/app/templates/projects/defect_update_actions.html +6 -0
  165. package/app/templates/projects/defect_update_preview.html +24 -0
  166. package/app/templates/projects/defects.html +126 -0
  167. package/app/templates/projects/delete.html +31 -0
  168. package/app/templates/projects/external.html +62 -0
  169. package/app/templates/projects/folders.html +64 -0
  170. package/app/templates/projects/hub_accepted.html +10 -0
  171. package/app/templates/projects/hub_assignment.html +50 -0
  172. package/app/templates/projects/hub_pending.html +20 -0
  173. package/app/templates/projects/hub_pending_list.html +17 -0
  174. package/app/templates/projects/hub_state_note.html +23 -0
  175. package/app/templates/projects/hub_step_note.html +5 -0
  176. package/app/templates/projects/hub_sync.html +105 -0
  177. package/app/templates/projects/hub_sync_confirm.html +32 -0
  178. package/app/templates/projects/hub_sync_worker.html +5 -0
  179. package/app/templates/projects/hub_text_rules.html +64 -0
  180. package/app/templates/projects/identity_report.html +74 -0
  181. package/app/templates/projects/list.html +90 -0
  182. package/app/templates/projects/project.html +436 -0
  183. package/app/templates/reference-missing.html +14 -0
  184. package/app/templates/runs/run.html +166 -0
  185. package/app/templates/sca/card.html +476 -0
  186. package/app/templates/sca/index.html +321 -0
  187. package/app/templates/settings/hub_url.html +31 -0
  188. package/app/templates/settings/index.html +216 -0
  189. package/app/templates/settings/provider.html +231 -0
  190. package/app/templates/settings/providers.html +37 -0
  191. package/app/templates/worklists.html +52 -0
  192. package/app/textsafe.py +117 -0
  193. package/app/timing.py +245 -0
  194. package/app/triage.py +1746 -0
  195. package/app/view.py +430 -0
  196. package/app/worklists.py +204 -0
  197. package/examples/catalog/NOTICE.md +70 -0
  198. package/examples/catalog/catalog.json +978 -0
  199. package/examples/catalog/crapi/export.xlsx +0 -0
  200. package/examples/catalog/dvga/export.xlsx +0 -0
  201. package/examples/catalog/dvwa/export.xlsx +0 -0
  202. package/examples/catalog/go-test-bench/export.xlsx +0 -0
  203. package/examples/catalog/juice-shop/export.xlsx +0 -0
  204. package/examples/catalog/nodegoat/export.xlsx +0 -0
  205. package/examples/catalog/pygoat/export.xlsx +0 -0
  206. package/examples/catalog/railsgoat/export.xlsx +0 -0
  207. package/examples/catalog/vulnerablelightapp/export.xlsx +0 -0
  208. package/examples/catalog/webgoat/export.xlsx +0 -0
  209. package/examples/demo/demo-hub-report-v2.xlsx +0 -0
  210. package/examples/demo/demo-hub-report.xlsx +0 -0
  211. package/examples/demo/repos/billing-core/pom.xml +30 -0
  212. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/Invoice.java +9 -0
  213. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceRepository.java +51 -0
  214. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceStatus.java +11 -0
  215. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/config/DatabaseSettings.java +18 -0
  216. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/payment/PaymentTokenService.java +35 -0
  217. package/examples/demo/repos/billing-core/src/main/java/org/example/billing/web/InvoiceExportController.java +57 -0
  218. package/examples/demo/repos/catalog-api/catalog_api/__init__.py +1 -0
  219. package/examples/demo/repos/catalog-api/catalog_api/products.py +24 -0
  220. package/examples/demo/repos/catalog-api/catalog_api/tasks.py +24 -0
  221. package/examples/demo/repos/catalog-api/catalog_api/views.py +17 -0
  222. package/examples/demo/repos/catalog-api/requirements.txt +3 -0
  223. package/npm/build.json +5 -0
  224. package/npm/cli.js +357 -0
  225. package/npm/files.manifest +242 -0
  226. package/npm/lib/binding.js +65 -0
  227. package/npm/lib/cluster.js +330 -0
  228. package/npm/lib/env.js +88 -0
  229. package/npm/lib/fsx.js +125 -0
  230. package/npm/lib/http.js +53 -0
  231. package/npm/lib/metrics.js +73 -0
  232. package/npm/lib/paths.js +150 -0
  233. package/npm/lib/pg.js +348 -0
  234. package/npm/lib/proc.js +101 -0
  235. package/npm/lib/python.js +133 -0
  236. package/npm/lib/stand.js +46 -0
  237. package/npm/lib/supervisor.js +1200 -0
  238. package/npm/lib/version.js +21 -0
  239. package/npm/requirements.txt +476 -0
  240. package/npm-shrinkwrap.json +111 -0
  241. package/package.json +37 -4
package/app/ask.py ADDED
@@ -0,0 +1,300 @@
1
+ """«Спросить модель»: вопрос специалиста по находке и ответ локальной модели.
2
+
3
+ Модель получает то же, что при разборе: сведения о находке и срез кода, который она видела (cases.context_json),
4
+ свой прежний разбор (вердикт, привязанный к находке) и прежние вопросы с ответами по этой находке. Вопрос
5
+ специалиста идёт вне блока данных (prompts.build_ask_messages). Перед отправкой текст сообщения с данными
6
+ маскируется ещё раз, как в прогоне. Модель – только локальная: клиент Ollama проверяет адрес (разрешённые хосты)
7
+ и саму модель (облачные отклоняются) перед каждой отправкой.
8
+
9
+ Вопрос и ответ сохраняются (таблица questions): сначала вопрос без ответа, затем ответ с замерами скорости или
10
+ ошибка. Если приложение перезапустится, пока модель отвечает, вопрос без ответа закроется с пояснением
11
+ (Database.recover_interrupted). Одновременно модель отвечает только на один вопрос: видеокарта одна, а прогон
12
+ триажа может идти параллельно. Текст вопроса и ответа в журнал не пишется.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ from collections.abc import Callable, Iterable
19
+ from typing import Any
20
+
21
+ from app import model_traffic
22
+ from app.config import Settings
23
+ from app.db import QUESTION_UNKNOWN, Database
24
+ from app.executors import (REMOTE_KINDS, ProfileError, applied_think, choose_profile, client_for, execution_values,
25
+ fit_options, fit_thinking, json_overhead, planned_think, prompt_size, send_guard,
26
+ snapshot_options, thinking_limit)
27
+ from app.llm import (GENERATION, LlmError, PromptOverflowError, gate_for, outcome_unknown, prompt_budget,
28
+ prompt_fits, prompt_tokens)
29
+ from app.llm_ollama import OllamaClient
30
+ from app.logsafe import failure_text, log_failure
31
+ from app.masking import mask_text
32
+ from app.models import CodeContext, Finding, Verdict
33
+ from app.prompts import (ASK_ENUMS, ASK_FIELDS, ASK_HISTORY_MAX, ASK_REQUIRED, ASK_TYPES, build_ask_messages,
34
+ parse_ask)
35
+
36
+ log = logging.getLogger("local_triage.ask")
37
+
38
+ MAX_QUESTION = 2000 # знаков в вопросе
39
+ ASK_NUM_PREDICT = 1536 # предел длины ответа, токенов: ответ на вопрос короче разбора
40
+ MIN_CODE_LINES = 9 # меньше строк вокруг строки срабатывания срез для вопроса не сокращается
41
+ PROMPT_DOUBT = ("Вопрос с кодом, по счёту модели, не поместился в окно контекста вместе с ответом: начало могло быть "
42
+ "обрезано, ответ не принят. Сократите вопрос или увеличьте окно контекста в настройках.")
43
+
44
+ # К модели – по одному обращению на процесс (ADR-0099): вопрос, пока модель отвечает на другой вопрос или разбирает
45
+ # находку в прогоне, получает понятный отказ; текст вопроса остаётся в форме
46
+ ASK_BUSY = "Модель ещё отвечает на предыдущий вопрос – дождитесь ответа и спросите снова."
47
+ RUN_BUSY = ("Модель сейчас разбирает находки в прогоне – спросите, когда прогон закончится или встанет на паузу. "
48
+ "Текст вопроса сохранён в форме.")
49
+ REANALYZED = ("Пока вопрос ждал модель, разбор находки обновился: проверьте вопрос по новому разбору и спросите "
50
+ "снова.")
51
+
52
+
53
+ class AskError(Exception):
54
+ """Вопрос не задан. Текст – по-русски, для показа в интерфейсе; status – код ответа HTTP."""
55
+
56
+ def __init__(self, message: str, status: int = 400) -> None:
57
+ super().__init__(message)
58
+ self.status = status
59
+
60
+
61
+ def clean_question(text: Any) -> str:
62
+ """Вопрос из формы: переводы строк – «\\n», без пробелов по краям и лишних пустых строк."""
63
+ lines = [line.rstrip() for line in str(text or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")]
64
+ out: list[str] = []
65
+ for line in lines:
66
+ if not line.strip() and out and not out[-1].strip():
67
+ continue
68
+ out.append(line)
69
+ return "\n".join(out).strip()
70
+
71
+
72
+ def ask_options(settings: Settings) -> dict[str, int]:
73
+ """Параметры генерации ответа на вопрос: окно контекста из настроек, предел ответа – не больше четверти окна."""
74
+ num_ctx = int(settings.num_ctx)
75
+ return {"num_ctx": num_ctx, "num_predict": min(ASK_NUM_PREDICT, num_ctx // 4)}
76
+
77
+
78
+ def _around_target(ctx: CodeContext, keep: int) -> CodeContext:
79
+ """Срез, сокращённый до keep строк вокруг строки срабатывания (номера строк сохраняются)."""
80
+ if len(ctx.lines) <= keep:
81
+ return ctx
82
+ if ctx.start_line >= 1 and ctx.target_line:
83
+ center = ctx.target_line - ctx.start_line
84
+ else:
85
+ center = len(ctx.lines) // 2
86
+ first = max(0, min(center - keep // 2, len(ctx.lines) - keep))
87
+ start = ctx.start_line + first if ctx.start_line >= 1 else ctx.start_line
88
+ end = start + keep - 1 if ctx.start_line >= 1 else ctx.end_line
89
+ return CodeContext(**{**ctx.to_dict(), "lines": ctx.lines[first:first + keep], "start_line": start,
90
+ "end_line": end})
91
+
92
+
93
+ def fit_messages(f: Finding, ctx: CodeContext, verdict: Verdict, question: str,
94
+ history: list[tuple[str, str]], mask_key: bytes | None,
95
+ options: dict[str, int], size: Any = None) -> list[dict[str, str]]:
96
+ """Сообщения, которые помещаются в окно контекста вместе с ответом. Что сокращается по очереди: прежние
97
+ вопросы и ответы (от ранних), подробности прежнего разбора, затем срез кода вокруг строки срабатывания.
98
+ Не помещается и так – AskError."""
99
+ def build(code: CodeContext, past: list[tuple[str, str]], brief: bool) -> list[dict[str, str]]:
100
+ messages = build_ask_messages(f, code, verdict, question, past, mask_key=mask_key, brief=brief)
101
+ # последняя сетка перед отправкой – как в прогоне: маскирование всего текста с данными находки
102
+ return [{**m, "content": mask_text(m["content"], mask_key, env_style=False)[0]}
103
+ if mask_key and m["role"] == "user" else m for m in messages]
104
+
105
+ past = list(history)
106
+ while True:
107
+ messages = build(ctx, past, False)
108
+ if prompt_fits(messages, options, size):
109
+ return messages
110
+ if not past:
111
+ break
112
+ past = past[1:]
113
+ messages = build(ctx, [], True)
114
+ if prompt_fits(messages, options, size):
115
+ return messages
116
+ keep = len(ctx.lines)
117
+ while keep > MIN_CODE_LINES:
118
+ keep = max(MIN_CODE_LINES, keep * 2 // 3)
119
+ messages = build(_around_target(ctx, keep), [], True)
120
+ if prompt_fits(messages, options, size):
121
+ return messages
122
+ # Наименьший срез не уложился в запас на ошибку оценки (llm.PROMPT_SAFETY_SHARE), но всё окно ещё не занимает:
123
+ # он и уходит модели – меньше уже некуда; что промпт действительно поместился, сверяет счёт самой модели
124
+ full = prompt_budget(options, safety=False)
125
+ if full is None or (size or prompt_tokens)(messages) <= full:
126
+ return messages
127
+ # size задан только у удалённого API (executors.prompt_size): окно и предел ответа – из профиля провайдера, а не
128
+ # из настроек Ollama (ревью Codex, круг 19)
129
+ where = ("увеличьте «Окно контекста модели» или уменьшите «Предел ответа» в профиле провайдера" if size is not None
130
+ else "увеличьте окно контекста в настройках")
131
+ raise AskError(f"Вопрос вместе с кодом находки не помещается в окно контекста модели: сократите вопрос или {where}.")
132
+
133
+
134
+ def history_for(questions: Iterable[dict], verdict_id: Any) -> list[tuple[str, str]]:
135
+ """Прежние вопросы с ответами к этому же ответу модели (verdict_id) – последние ASK_HISTORY_MAX: вопросы
136
+ к прежнему вердикту относятся к другому разбору."""
137
+ done = [(q["question"], q["answer"]) for q in questions
138
+ if q.get("state") == "done" and q.get("answer") and q.get("verdict_id") == verdict_id]
139
+ return done[-ASK_HISTORY_MAX:]
140
+
141
+
142
+ def ask_question(db: Database, settings: Settings, client: OllamaClient | Callable[[str], OllamaClient],
143
+ mask_key: bytes | None, project_id: int, hub_id: str, question: str, model: str) -> dict:
144
+ """Задать модели вопрос по находке и дождаться ответа. Возвращает сохранённый вопрос (Database.get_question):
145
+ state = done и answer, или state = error и текст ошибки (модель не ответила, ответ не по формату). Вопрос
146
+ не задан (пустой, длинный, нет разбора модели, модель уже отвечает на другой вопрос, промпт не помещается
147
+ в окно, профиль модели выключен) – AskError, и ничего не сохраняется.
148
+
149
+ Профиль (ADR-0102 п. 4): у ответа модели есть снимок исполнителя – тем же профилем, если он включён, выключен –
150
+ отказ; ответ до 0.9.12 (снимка нет) – профиль проекта. Снимок вопроса пишется вместе с вопросом. client – фабрика
151
+ клиента по адресу (как у прогона) или готовый клиент (тесты)."""
152
+ text = clean_question(question)
153
+ if not text:
154
+ raise AskError("Напишите вопрос.")
155
+ if len(text) > MAX_QUESTION:
156
+ raise AskError(f"Вопрос слишком длинный: не больше {MAX_QUESTION} знаков.")
157
+ name = str(model or "").strip()
158
+ if not name or any(ord(ch) < 32 for ch in name):
159
+ raise AskError("Не выбрана модель.")
160
+ case = db.get_case(project_id, hub_id)
161
+ source = db.case_input(project_id, hub_id)
162
+ if source is None:
163
+ raise AskError("Находка не найдена.", 404)
164
+ if case is None or not case.get("verdict"):
165
+ raise AskError("Модель эту находку ещё не разбирала: сначала запустите разбор, потом задавайте вопросы.",
166
+ 409)
167
+ f = Finding.from_dict(source["data"])
168
+ ctx = CodeContext.from_dict(case["context"]) # ровно тот срез, который видела модель
169
+ verdict = Verdict.from_dict(case["verdict"]["data"])
170
+ history = history_for(db.list_questions(project_id, hub_id), case["verdict_id"])
171
+ profile = question_profile(db, settings, project_id, case["verdict_id"])
172
+ execution = execution_values(profile, name, "ask", settings.num_ctx, settings.model_json_schema)
173
+ options, _, rule = snapshot_options(execution)
174
+ # фабрика (класс клиента или функция от адреса) или готовый клиент (тесты): у класса тоже есть chat_json
175
+ ready = hasattr(client, "chat_json") and not isinstance(client, type)
176
+ factory = (lambda url, given=client: given) if ready else client
177
+ # рассуждает ли модель – до сборки промпта: у рассуждающего вопроса свой предел ответа, а с ним и место под срез
178
+ # удалённый API сведений о рассуждении не отдаёт – запись модели у него не запрашивается (лишний GET /models)
179
+ remote = str(execution.get("kind") or "ollama") in REMOTE_KINDS
180
+ planned = client_for(factory, execution, send_guard(db, execution, project_id=project_id), db=db,
181
+ project_id=project_id)
182
+ try:
183
+ info = {} if remote else dict(planned.model_info(name))
184
+ except (LlmError, AttributeError):
185
+ info = {}
186
+ think = applied_think(rule, name, info or None)
187
+ think_limit, call_timeout = thinking_limit(execution, think)
188
+ # окно и предел ответа – того сервера, куда уйдёт вопрос (у удалённого API – из профиля за вычетом схемы ответа,
189
+ # которую клиент добавит к сообщениям; KIMI-01)
190
+ messages = fit_messages(f, ctx, verdict, text, history, mask_key,
191
+ fit_options(execution, options,
192
+ json_overhead(planned, ASK_FIELDS, ASK_REQUIRED, ASK_ENUMS, ASK_TYPES)),
193
+ prompt_size(execution))
194
+ if think_limit: # рассуждающий вопрос: остаток окна после промпта, не больше предела рассуждения
195
+ options = fit_thinking(options, think_limit, messages)
196
+ gate = gate_for(execution) # группа права – из снимка вопроса (ADR-0104 п. 6), не пересчитывается
197
+ if not gate.try_acquire("ask"):
198
+ raise AskError(busy_text(gate), 409)
199
+ try:
200
+ # срез и разбор для вопроса собраны до права на генерацию: если разбор находки за это время сменился,
201
+ # вопрос к прежнему разбору не задаётся
202
+ now = db.get_case(project_id, hub_id) or {}
203
+ if now.get("verdict_id") != case["verdict_id"] or now.get("case_hash") != case["case_hash"]:
204
+ raise AskError(REANALYZED, 409)
205
+ question_id = db.add_question(project_id, hub_id, text, name, case_hash=case["case_hash"],
206
+ verdict_id=case["verdict_id"], execution=execution)
207
+ saved = db.get_question(question_id) or {}
208
+ snapshot = db.get_execution(saved.get("execution_id")) or execution
209
+ asking = client_for(factory, snapshot, send_guard(db, snapshot, project_id=project_id), db=db,
210
+ project_id=project_id)
211
+ asking.timeout = call_timeout
212
+ try:
213
+ # Контекст журнала обмена с моделью: обращения вопроса помечаются назначением ask и находкой.
214
+ with model_traffic.context(purpose="ask", project_id=project_id, hub_id=hub_id):
215
+ # уровень рассуждения – на каждую отправку, по модели, которая в этот момент лежит на сервере
216
+ obj, stats = asking.chat_json(name, messages, ASK_FIELDS, ASK_REQUIRED, ASK_ENUMS, options=options,
217
+ think=planned_think(rule, name, think), types=ASK_TYPES,
218
+ json_schema=str(snapshot.get("schema_mode") or
219
+ settings.model_json_schema))
220
+ answer = parse_ask(obj)
221
+ # последняя проверка перед сохранением – после всей нормализации ответа (сервер с ключом мог вернуть его)
222
+ if model_traffic.shows_secret([answer, stats.to_dict()], getattr(asking, "secrets", ())):
223
+ raise LlmError(model_traffic.KEY_IN_ANSWER)
224
+ except PromptOverflowError as e:
225
+ # по счёту модели промпт одной из попыток длиннее окна: начало могло быть обрезано – ответу не доверяем;
226
+ # у удалённого API это отказ его клиента до отправки по окну профиля – совет про профиль (ревью круг 18)
227
+ text = (f"{e} Увеличьте «Окно контекста модели» или уменьшите «Предел ответа» в профиле провайдера."
228
+ if remote and not getattr(e, "sent", False) else PROMPT_DOUBT)
229
+ db.finish_question(question_id, error=text, stats=e.stats.to_dict() if e.stats else None)
230
+ except LlmError as e:
231
+ # К11: вопрос ушёл внешнему провайдеру без ответа – «результат неизвестен», повторно не отправляется
232
+ unknown = str(snapshot.get("trust") or "") == "external" and outcome_unknown(e)
233
+ db.finish_question(question_id, error=f"{QUESTION_UNKNOWN} {e}" if unknown else str(e),
234
+ stats=e.stats.to_dict() if e.stats else None)
235
+ except Exception as e: # сбой разбора или записи – ошибка этого вопроса, без текста вопроса в журнале
236
+ eid = log_failure(log, "вопрос к модели не обработан", e)
237
+ db.finish_question(question_id, error=failure_text("Не удалось получить ответ модели", e, eid))
238
+ else:
239
+ db.finish_question(question_id, answer=answer["answer"], answer_data=answer, stats=stats.to_dict())
240
+ return db.get_question(question_id) or {}
241
+ finally:
242
+ gate.release()
243
+
244
+
245
+ def answer_execution(db: Database, verdict_id: int | None) -> dict | None:
246
+ """Снимок исполнителя ответа, профилем которого задаётся вопрос по нему (ADR-0102 п. 4): с профилем и адресом.
247
+ Ответ до 0.9.12 и ответ, полученный при сборке образа (адрес исполнителя не сохраняется), – None: вопрос идёт
248
+ профилем проекта. Одно правило для формы вопроса в карточке и для его обработки."""
249
+ execution = db.verdict_execution(verdict_id)
250
+ if execution is not None and execution.get("provider_id") and str(execution.get("base_url") or ""):
251
+ return execution
252
+ return None
253
+
254
+
255
+ def question_profile(db: Database, settings: Settings, project_id: int, verdict_id: int | None) -> dict:
256
+ """Профиль вопроса (ADR-0102 п. 4): ответ модели получен известным исполнителем – его профиль (выключен – отказ);
257
+ ответ до 0.9.12 и ответ сборки образа – профиль проекта (выключен – отказ)."""
258
+ execution = answer_execution(db, verdict_id)
259
+ try:
260
+ if execution is not None:
261
+ profile = db.get_provider(int(execution["provider_id"]))
262
+ if profile is None or not profile.get("enabled"):
263
+ name = (profile or {}).get("name") or execution.get("base_url")
264
+ raise AskError(f"Разбор получен моделью профиля «{name}», а он выключен: включите профиль на странице "
265
+ "«Настройки» или пересмотрите находку на действующем профиле. Текст вопроса сохранён "
266
+ "в форме.", 409)
267
+ return choose_profile(db, settings, db.get_project(project_id), int(profile["id"]))
268
+ return choose_profile(db, settings, db.get_project(project_id))
269
+ except ProfileError as e:
270
+ raise AskError(f"{e} Текст вопроса сохранён в форме.", 409) from None
271
+
272
+
273
+ def busy_text(gate: Any) -> str:
274
+ """Почему вопрос не задан: кто держит право на генерацию группы (ADR-0104 п. 6) – словами."""
275
+ holder = gate.busy()
276
+ if holder == "triage":
277
+ return RUN_BUSY
278
+ if holder == "ask":
279
+ return ASK_BUSY
280
+ return (f"Модель ({gate.label}) сейчас занята проверкой или прогревом – спросите через минуту. Текст вопроса "
281
+ "сохранён в форме.")
282
+
283
+
284
+ def card_executor(db: Database, settings: Settings, project_id: int, verdict_id: int | None) -> Any:
285
+ """Исполнитель, которым пойдёт вопрос по этому разбору (question_profile), – для подсказок занятости в карточке;
286
+ профиль недоступен – None (свой контур)."""
287
+ try:
288
+ return question_profile(db, settings, project_id, verdict_id)
289
+ except AskError:
290
+ return None
291
+
292
+
293
+ def busy(executor: Any = None) -> bool:
294
+ """Модель группы этого исполнителя (по умолчанию – свой контур) сейчас отвечает на вопрос."""
295
+ return (gate_for(executor) if executor is not None else GENERATION).busy() == "ask"
296
+
297
+
298
+ def run_busy(executor: Any = None) -> bool:
299
+ """Модель группы этого исполнителя сейчас разбирает находку в прогоне: вопрос получит отказ."""
300
+ return (gate_for(executor) if executor is not None else GENERATION).busy() == "triage"
@@ -0,0 +1,99 @@
1
+ """Сведения о сборке для плашки внизу страниц и /healthz: версия приложения, коммит и время сборки образа.
2
+
3
+ Коммит и время передаются при сборке образа (start.ps1, deploy/vm/build.sh → аргументы BUILD_COMMIT, BUILD_DIRTY,
4
+ BUILD_TIME → переменные LT_BUILD_*). Без них – при запуске из рабочей копии репозитория – коммит читается из git.
5
+ Значения проверяются по формату: в разметку попадает только то, что похоже на коммит и дату."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import re
13
+ import subprocess
14
+ from functools import lru_cache
15
+ from pathlib import Path
16
+
17
+ from app import __version__
18
+
19
+ _STATIC_DIR = Path(__file__).resolve().parent / "static"
20
+
21
+ _COMMIT = re.compile(r"^[0-9a-f]{7,40}$")
22
+ _BUILT = re.compile(r"^\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}$")
23
+
24
+
25
+ def _git(root: Path, *args: str) -> subprocess.CompletedProcess | None:
26
+ try:
27
+ return subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True, timeout=3)
28
+ except (OSError, subprocess.SubprocessError):
29
+ return None
30
+
31
+
32
+ # что определяет содержимое образа (Dockerfile, .dockerignore, COPY): правки в этом, включая новые файлы, –
33
+ # «правки вне коммита»
34
+ _IMAGE_PATHS = ("app", "Dockerfile", ".dockerignore", "requirements.lock", "examples/demo/demo-hub-report.xlsx",
35
+ "examples/catalog")
36
+
37
+
38
+ def _from_git(root: Path | None = None) -> tuple[str, bool | None]:
39
+ """Коммит рабочей копии и признак правок вне коммита в том, что входит в образ: True / False / None (проверить не
40
+ удалось – это не «чисто»). Нет git или репозитория – ("", None)."""
41
+ root = root or Path(__file__).resolve().parents[1]
42
+ if not (root / ".git").exists():
43
+ return "", None
44
+ head = _git(root, "rev-parse", "--short", "HEAD")
45
+ if head is None or head.returncode != 0:
46
+ return "", None
47
+ # новые файлы показываются явно: настройка status.showUntrackedFiles=no их бы скрыла
48
+ status = _git(root, "status", "--porcelain", "--untracked-files=all", "--", *_IMAGE_PATHS)
49
+ dirty = None if status is None or status.returncode != 0 else bool(status.stdout.strip())
50
+ return head.stdout.strip(), dirty
51
+
52
+
53
+ def _from_file(root: Path | None = None) -> tuple[str, bool | None, str]:
54
+ """Сведения о сборке пакета npm (ADR-0155): build.json рядом с папкой app – его пишет сборщик пакета, потому что в
55
+ пакете нет .git. {"commit": "...", "dirty": bool, "time": "ДД.ММ.ГГГГ ЧЧ:ММ"}; нет файла или он испорчен – пусто."""
56
+ root = root or Path(__file__).resolve().parents[1]
57
+ try:
58
+ data = json.loads((root / "build.json").read_text(encoding="utf-8"))
59
+ except (OSError, ValueError):
60
+ return "", None, ""
61
+ if not isinstance(data, dict):
62
+ return "", None, ""
63
+ commit = str(data.get("commit") or "").strip().lower()
64
+ dirty = data.get("dirty") if isinstance(data.get("dirty"), bool) else None
65
+ return commit, dirty, str(data.get("time") or "").strip()
66
+
67
+
68
+ @lru_cache(maxsize=1)
69
+ def build_info() -> dict:
70
+ """{version, commit, dirty, built}: commit – "" если неизвестен; dirty – True / False / None (не проверено, в том
71
+ числе при неизвестном коммите); built – время сборки образа «ДД.ММ.ГГГГ ЧЧ:ММ» или ""."""
72
+ commit = os.environ.get("LT_BUILD_COMMIT", "").strip().lower()
73
+ flag = os.environ.get("LT_BUILD_DIRTY", "").strip()
74
+ dirty: bool | None = True if flag == "1" else (False if flag == "0" else None)
75
+ built = os.environ.get("LT_BUILD_TIME", "").strip()
76
+ if not _COMMIT.match(commit):
77
+ commit, dirty = _from_git()
78
+ commit = commit.lower() if _COMMIT.match(commit.lower()) else ""
79
+ if not commit: # пакет npm: git нет, сведения записаны при сборке пакета
80
+ commit, dirty, file_built = _from_file()
81
+ commit = commit if _COMMIT.match(commit) else ""
82
+ built = built or file_built
83
+ return {"version": __version__, "commit": commit, "dirty": dirty if commit else None,
84
+ "built": built if _BUILT.match(built) else ""}
85
+
86
+
87
+ @lru_cache(maxsize=1)
88
+ def asset_version(static_dir: Path | None = None) -> str:
89
+ """Версия для адресов статических файлов (`?v=` в base.html): версия приложения и отпечаток содержимого `app/static`,
90
+ чтобы адрес менялся с каждой сборкой, где менялись скрипты или стили, и браузер не держал старый скрипт: при
91
+ перезапусках с одним и тем же `?v=<версия>` Chrome оставлял прежний app.js, и новое поведение карточки не
92
+ включалось. Отпечаток – SHA-256 по относительным именам и содержимому файлов, первые 10 знаков."""
93
+ root = static_dir or _STATIC_DIR
94
+ digest = hashlib.sha256()
95
+ for path in sorted(p for p in root.rglob("*") if p.is_file()) if root.is_dir() else []:
96
+ digest.update(path.relative_to(root).as_posix().encode("utf-8"))
97
+ digest.update(b"\0")
98
+ digest.update(path.read_bytes())
99
+ return f"{__version__}-{digest.hexdigest()[:10]}"
package/app/capec.py ADDED
@@ -0,0 +1,168 @@
1
+ """Каталог CAPEC: структура источника и прямые справочные связи, без вывода о применимости."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import re
7
+ from collections import Counter
8
+
9
+ NS = "http://capec.mitre.org/capec-3"
10
+ TABLES = ("capec", "capec_index", "capec_refs", "capec_links", "capec_cwe", "capec_meta") # таблицы – миграция 0002, ADR-0133
11
+ KNOWN = set("Description Extended_Description Likelihood_Of_Attack Typical_Severity Related_Attack_Patterns Execution_Flow Prerequisites Skills_Required Resources_Required Consequences Mitigations Example_Instances Related_Weaknesses Taxonomy_Mappings Content_History Indicators References Notes Alternate_Terms Summary Relationships Objective Members Filter Audience".split())
12
+ KINDS = {"Attack_Pattern": "pattern", "Category": "category", "View": "view"}
13
+ MAX_JSON = 1024 * 1024
14
+
15
+
16
+ def identifier(value, prefix="CAPEC"):
17
+ match = re.fullmatch(r"\s*(?:" + prefix + r"\s*-?\s*)?0*(\d{1,7})\s*", str(value or ""), re.I)
18
+ return f"{prefix}-{int(match[1])}" if match and int(match[1]) else ""
19
+
20
+
21
+ def _tag(elem):
22
+ return elem.tag.rsplit("}", 1)[-1]
23
+
24
+
25
+ def _node(elem):
26
+ # Полное дерево записи: текст, атрибуты, хвосты и порядок не теряются при появлении нового поля.
27
+ return {"tag": _tag(elem), "namespace": elem.tag.rsplit('}',1)[0].lstrip('{') if '}' in elem.tag else '',
28
+ "attrs": _attributes(elem), "text": elem.text or "",
29
+ "tail": elem.tail or "", "children": [_node(x) for x in elem]}
30
+
31
+
32
+ def _attributes(elem):
33
+ return {('{' + key if '}' in key and not key.startswith('{') else key):value for key,value in elem.attrib.items()}
34
+
35
+
36
+ def parse_record(elem):
37
+ from .feeds import FeedError
38
+ for part in elem.iter():
39
+ if '}' in part.tag and not part.tag.startswith('{'):
40
+ part.tag = '{' + part.tag
41
+ ident = identifier(elem.get("ID"))
42
+ if not ident or not elem.get("Name") or not elem.tag.startswith("{" + NS + "}"):
43
+ raise FeedError("Некорректная запись CAPEC: нужны ID, Name и пространство имён CAPEC.")
44
+ def elements(path): return elem.findall(path, {"c": NS})
45
+ def text(name): return elem.findtext("c:" + name, default="", namespaces={"c": NS}).strip()
46
+ links = [{"rel": x.get("Nature", ""), "id": identifier(x.get("CAPEC_ID"))}
47
+ for x in elements("c:Related_Attack_Patterns/c:Related_Attack_Pattern")]
48
+ links += [{"rel": "HasMember", "id": identifier(x.get("CAPEC_ID"))}
49
+ for path in ("c:Relationships/c:Has_Member", "c:Members/c:Has_Member") for x in elements(path)]
50
+ row = {"id": ident, "kind": KINDS[_tag(elem)], "name": elem.get("Name"), "attributes": _attributes(elem), "text":elem.text or '',
51
+ "abstraction": elem.get("Abstraction", ""), "status": elem.get("Status", ""),
52
+ "view_type": elem.get("Type", ""), "filter": text("Filter"),
53
+ "severity": text("Typical_Severity"), "likelihood": text("Likelihood_Of_Attack"),
54
+ "description": text("Description") or text("Summary") or text("Objective"),
55
+ "has_flow": bool(elements("c:Execution_Flow")),
56
+ "cwes": sorted({identifier(x.get("CWE_ID"), "CWE") for x in elements("c:Related_Weaknesses/c:Related_Weakness")} - {""}),
57
+ "links": [x for x in links if x["id"]],
58
+ "exclude": [identifier(x.get("Exclude_ID")) for x in elements(".//c:Exclude_Related")],
59
+ "taxonomies": [x.get("Taxonomy_Name", "") for x in elements("c:Taxonomy_Mappings/c:Taxonomy_Mapping")],
60
+ "sections": [_node(x) for x in elem],
61
+ "unknown_fields": [_tag(x) for x in elem if _tag(x) not in KNOWN]}
62
+ row["search_text"] = " ".join(elem.itertext()).casefold() + " " + row["name"].casefold()
63
+ if len(json.dumps(row, ensure_ascii=False).encode()) > MAX_JSON:
64
+ raise FeedError("Запись CAPEC слишком велика: полный текст не был сохранён, каталог не заменён.")
65
+ return row
66
+
67
+
68
+ def parse_reference(elem):
69
+ """Источник целиком, без сокращения полей и количества авторов."""
70
+ from .feeds import FeedError
71
+ def text(name):
72
+ return ' '.join(''.join(x.itertext()).strip() for x in elem if _tag(x) == name)
73
+ ident = elem.get('Reference_ID', '')
74
+ if not ident:
75
+ raise FeedError('В источнике CAPEC нет Reference_ID.')
76
+ row = {'id': ident, 'title': text('Title'), 'url': text('URL'),
77
+ 'authors': [''.join(x.itertext()) for x in elem if _tag(x) == 'Author'], 'tree': _node(elem)}
78
+ if len(json.dumps(row, ensure_ascii=False).encode()) > MAX_JSON:
79
+ raise FeedError('Источник CAPEC слишком велик: каталог не заменён.')
80
+ return row
81
+
82
+
83
+ def fill(store, archive, info, check):
84
+ """Потоковый импорт в подготовленный imp; подмена остаётся общей операцией FeedStore."""
85
+ from .feeds import FeedError, guarded_chunks, iter_records, MAX_RECORDS
86
+ root_attrs, seen, counts, statuses = {}, set(), Counter(), Counter()
87
+ refs = pairs = 0
88
+ xml_hash = hashlib.sha256()
89
+ def root(elem):
90
+ root_attrs.update(elem.attrib)
91
+ if elem.tag.lstrip('{') != NS + "}Attack_Pattern_Catalog" or elem.get("Name") != "CAPEC":
92
+ raise FeedError("Нужен полный архив capec_latest.zip с каталогом CAPEC, не отдельное представление.")
93
+ schema = next((v for k,v in elem.attrib.items() if k.lstrip('{') == 'http://www.w3.org/2001/XMLSchema-instance}schemaLocation'), '')
94
+ if not re.search(r"ap_schema_v3\.5\.xsd(?:\s|$)", schema):
95
+ raise FeedError("Версия XML-схемы CAPEC не поддерживается: ожидается 3.5.")
96
+ def chunks(stream):
97
+ for piece in guarded_chunks(stream, compressed=info.compress_size):
98
+ xml_hash.update(piece)
99
+ yield piece
100
+ with archive.open(info) as stream:
101
+ for elem in iter_records(chunks(stream), set(KINDS) | {"External_Reference"}, on_root=root, check=check):
102
+ check()
103
+ is_ref = _tag(elem) == "External_Reference"
104
+ row = parse_reference(elem) if is_ref else parse_record(elem)
105
+ if row is None: raise FeedError("Некорректный источник CAPEC.")
106
+ key = ("ref" if is_ref else "record", row["id"])
107
+ if key in seen: raise FeedError(f"Повтор ID {row['id']} в каталоге CAPEC.")
108
+ seen.add(key)
109
+ if len(seen) > MAX_RECORDS["capec"]: raise FeedError("Слишком много записей CAPEC.")
110
+ encoded = json.dumps(row, ensure_ascii=False)
111
+ store._check_space(len(encoded.encode()) * 4 + 65536)
112
+ with store._tx() as conn:
113
+ if is_ref:
114
+ refs += 1
115
+ conn.execute("INSERT INTO feeds_imp.capec_refs VALUES (?,?)", (row["id"], encoded))
116
+ else:
117
+ counts[row["kind"]] += 1
118
+ statuses[row["status"]] += 1
119
+ conn.execute("INSERT INTO feeds_imp.capec VALUES (?,?)", (row["id"], encoded))
120
+ conn.execute("INSERT INTO feeds_imp.capec_index VALUES (?,?,?,?)", (row["id"], row["kind"], row["name"], row["search_text"]))
121
+ conn.executemany("INSERT INTO feeds_imp.capec_links VALUES (?,?,?) ON CONFLICT DO NOTHING", [(row['id'],x['rel'],x['id']) for x in row['links']])
122
+ conn.executemany("INSERT INTO feeds_imp.capec_cwe VALUES (?,?) ON CONFLICT DO NOTHING", [(row['id'],x) for x in row['cwes']])
123
+ pairs += len(row['cwes'])
124
+ if not all(counts[x] for x in ('pattern','category','view')) or not refs:
125
+ raise FeedError("В архиве нет полного состава CAPEC: нужны шаблоны, категории, представления и источники.")
126
+ profile = {"counts": dict(counts), "statuses": dict(statuses), "cwe_pairs": pairs,
127
+ "sha256": xml_hash.hexdigest(), "schema": "3.5", "namespace": NS, "storage_version": 1}
128
+ with store._tx() as conn:
129
+ conn.execute("INSERT INTO feeds_imp.capec_meta VALUES ('catalog',?)", (json.dumps(profile),))
130
+ return {"records": sum(counts.values()), "ref_records": refs,
131
+ "version": root_attrs.get("Version", ""), "source_date": root_attrs.get("Date", "")}
132
+
133
+
134
+ def view_members(records, ident):
135
+ """Состав представления; исключения относятся к пути, а не к записи целиком."""
136
+ view=records.get(ident,{})
137
+ if view.get('kind')!='view': return set(),'Представление не найдено.'
138
+ if view['view_type']=='Implicit':
139
+ expr=re.sub(r"\s+(?=(?:[^']*'[^']*')*[^']*$)",'',view['filter'])
140
+ if expr=='/Attack_Pattern_Catalog/*[not(self::External_References)]/*': return set(records),''
141
+ m=re.fullmatch(r"/Attack_Pattern_Catalog/Attack_Patterns/Attack_Pattern\[@Abstraction='(Meta|Standard|Detailed)'\]",expr)
142
+ if m:return {k for k,v in records.items() if v['kind']=='pattern' and v['abstraction']==m[1]},''
143
+ m=re.fullmatch(r"/Attack_Pattern_Catalog/\*/\*\[@Status='([^']+)'\]",expr)
144
+ if m:return {k for k,v in records.items() if v['status']==m[1]},''
145
+ m=re.fullmatch(r"/Attack_Pattern_Catalog/\*/\*\[Taxonomy_Mappings/Taxonomy_Mapping\[@Taxonomy_Name='([^']+)'\]\]",expr)
146
+ if m:return {k for k,v in records.items() if m[1] in v['taxonomies']},''
147
+ m=re.fullmatch(r'/Attack_Pattern_Catalog/\*/\*\[@ID=\(([\d,]+)\)\]',expr)
148
+ if m:return {identifier(x) for x in m[1].split(',')} & records.keys(),''
149
+ return set(),'Условие представления пока не поддерживается.'
150
+ roots=[x['id'] for x in view['links'] if x['rel']=='HasMember']
151
+ if view['view_type']=='Explicit':return set(roots),''
152
+ children={}
153
+ for k,v in records.items():
154
+ for e in v['links']:
155
+ if e['rel']=='ChildOf':children.setdefault(e['id'],set()).add(k)
156
+ if e['rel']=='HasMember':children.setdefault(k,set()).add(e['id'])
157
+ result,note,stack,steps=set(),'',[(x,(ident,)) for x in roots],0
158
+ while stack:
159
+ key,path=stack.pop();steps+=1
160
+ if steps>20000:return result,'Обход ограничен: слишком много путей в представлении.'
161
+ if key in path:
162
+ note='В связях обнаружен цикл; повторный путь пропущен.'
163
+ continue
164
+ row=records.get(key)
165
+ if not row or set(row['exclude']) & set(path):continue
166
+ result.add(key)
167
+ stack.extend((child,path+(key,)) for child in children.get(key,()))
168
+ return result,note
@@ -0,0 +1,27 @@
1
+ """Структурированный текст CAPEC: таблицы, списки и примеры кода."""
2
+ from markupsafe import Markup, escape
3
+
4
+ HTML = {'p', 'div', 'span', 'b', 'i', 'strong', 'em', 'br', 'ul', 'ol', 'li', 'pre', 'code',
5
+ 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'blockquote', 'sub', 'sup'}
6
+
7
+
8
+ def plain(node):
9
+ return node['text'] + ''.join(plain(child) + child['tail'] for child in node['children'])
10
+
11
+
12
+ def rich(node, heading=True):
13
+ tag = node['tag']
14
+ content = str(escape(node['text'])) + ''.join(str(rich(c)) for c in node['children'])
15
+ if tag in HTML and node.get('namespace','') in ('','http://www.w3.org/1999/xhtml'):
16
+ attrs = ''
17
+ if tag in ('td', 'th'):
18
+ for key in ('colspan', 'rowspan'):
19
+ value = node['attrs'].get(key, '')
20
+ if str(value).isdigit() and 1 <= int(value) <= 100:
21
+ attrs += f' {key}="{int(value)}"'
22
+ result = '<br>' if tag == 'br' else f'<{tag}{attrs}>{content}</{tag}>'
23
+ else:
24
+ title = '<strong>' + str(escape(tag.replace('_', ' '))) + '</strong>' if heading else ''
25
+ attrs = ' '.join(str(escape(f'{key}: {value}')) for key, value in node['attrs'].items())
26
+ result = f'<div class="capec-node">{title}<small class="muted">{attrs}</small><div>{content}</div></div>'
27
+ return Markup(result + str(escape(node['tail'])))