oc-pilot 0.97.0 → 0.98.0

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.
@@ -0,0 +1,225 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { describeDiffSource, loadDiff } from "../core/diff-source.js";
4
+ import { PilotError } from "../core/errors.js";
5
+ import { runGit } from "../core/git.js";
6
+ import { writeOutput } from "../core/io.js";
7
+ import { log } from "../core/log.js";
8
+ import { COMMON_HELP, parseCommandArgs, resolveContext, withCommon } from "../core/options.js";
9
+ import { asBoolean, asString } from "../core/parse.js";
10
+ import { buildPolygraphPrompt, evaluatePolygraph, parsePolygraphClaims, renderPolygraph, } from "../core/polygraph.js";
11
+ import { detectProjectType } from "../core/project.js";
12
+ import { executeRecipeDetailed } from "../core/run.js";
13
+ const OPTIONS = withCommon({
14
+ commit: { type: "string" },
15
+ message: { type: "string" },
16
+ "message-file": { type: "string" },
17
+ claims: { type: "string" },
18
+ diff: { type: "string" },
19
+ stdin: { type: "boolean" },
20
+ staged: { type: "boolean" },
21
+ unstaged: { type: "boolean" },
22
+ base: { type: "string" },
23
+ "include-untracked": { type: "boolean" },
24
+ "fail-on": { type: "string" },
25
+ strict: { type: "boolean" },
26
+ });
27
+ const HELP = `Использование:
28
+ oc-pilot polygraph --commit HEAD
29
+ oc-pilot polygraph --message "текст PR" [опции diff]
30
+ oc-pilot polygraph --message-file pr.md --base main
31
+ oc-pilot polygraph --claims claims.json --staged
32
+
33
+ Проверяет утверждения из сообщения коммита или PR против реального diff.
34
+ Модель извлекает утверждения, а детерминированные проверки подтверждают
35
+ или опровергают их по diff. Статусы: supported, contradicted, unverifiable.
36
+ Supported означает согласованность с diff, а не истинность в мире.
37
+
38
+ Опции:
39
+ --commit <ref> сообщение и diff указанного коммита
40
+ --message <text> текст сообщения или PR
41
+ --message-file <f> прочитать сообщение из файла
42
+ --claims <file> готовый JSON с утверждениями, без вызова модели
43
+ --diff <file|-> готовый unified diff
44
+ --stdin читать diff из stdin
45
+ --staged только staged-изменения
46
+ --unstaged только unstaged-изменения
47
+ --base <ref> diff против ветки
48
+ --include-untracked добавить неотслеживаемые файлы
49
+ --fail-on <level> contradicted (по умолчанию) или unverifiable
50
+ --strict то же, что --fail-on unverifiable
51
+ ${COMMON_HELP}
52
+
53
+ Коды выхода:
54
+ 0 утверждения подтверждены или проверка неполная
55
+ 1 есть опровергнутое утверждение (или unverifiable при --strict)
56
+ 2 ошибка модели, парсинга или git
57
+
58
+ Примеры:
59
+ oc-pilot polygraph --commit HEAD
60
+ oc-pilot polygraph --message-file pr.md --base main
61
+ oc-pilot polygraph --claims claims.json --staged --strict`;
62
+ function readTextFile(cwd, path) {
63
+ try {
64
+ return readFileSync(resolve(cwd, path), "utf8");
65
+ }
66
+ catch {
67
+ throw new PilotError(`Не удалось прочитать ${path}`, {
68
+ hint: "Проверьте путь к файлу.",
69
+ exitCode: 2,
70
+ });
71
+ }
72
+ }
73
+ function parseFailOn(raw, strict) {
74
+ if (raw === undefined || raw.trim() === "")
75
+ return strict ? "unverifiable" : "contradicted";
76
+ const value = raw.trim();
77
+ if (value === "contradicted" || value === "unverifiable")
78
+ return value;
79
+ throw new PilotError(`Неизвестный уровень --fail-on: ${raw}`, {
80
+ hint: "Используйте contradicted или unverifiable.",
81
+ exitCode: 2,
82
+ });
83
+ }
84
+ function errorReport(source, summary) {
85
+ const report = {
86
+ source,
87
+ claims: [],
88
+ counts: { supported: 0, contradicted: 0, unverifiable: 0 },
89
+ status: "error",
90
+ summary,
91
+ content: "",
92
+ };
93
+ report.content = renderPolygraph(report);
94
+ return report;
95
+ }
96
+ function commitInputs(cwd, ref) {
97
+ const message = runGit(["show", "-s", "--format=%B", ref], cwd);
98
+ if (message.status !== 0) {
99
+ throw new PilotError(`Не удалось прочитать коммит ${ref}`, {
100
+ hint: message.stderr.trim() || "Проверьте ref.",
101
+ exitCode: 2,
102
+ });
103
+ }
104
+ const patch = runGit(["show", "--format=", "--no-color", "--no-ext-diff", "--first-parent", ref], cwd);
105
+ if (patch.status !== 0) {
106
+ throw new PilotError(`Не удалось получить diff коммита ${ref}`, {
107
+ hint: patch.stderr.trim(),
108
+ exitCode: 2,
109
+ });
110
+ }
111
+ return { message: message.stdout.trim(), diff: patch.stdout, source: `commit ${ref}` };
112
+ }
113
+ export async function runPolygraph(argv) {
114
+ const { values, positionals } = parseCommandArgs(argv, OPTIONS);
115
+ if (asBoolean(values, "help")) {
116
+ process.stdout.write(`${HELP}\n`);
117
+ return 0;
118
+ }
119
+ if (positionals.length > 0) {
120
+ throw new PilotError("polygraph не принимает позиционных аргументов", {
121
+ hint: "Передайте сообщение через --message, --message-file или --commit.",
122
+ exitCode: 2,
123
+ });
124
+ }
125
+ const ctx = resolveContext(values);
126
+ const commit = asString(values, "commit");
127
+ const message = asString(values, "message");
128
+ const messageFile = asString(values, "message-file");
129
+ const claimsPath = asString(values, "claims");
130
+ const sources = [commit, message, messageFile].filter((value) => Boolean(value));
131
+ if (claimsPath && sources.length > 0) {
132
+ throw new PilotError("Укажите только один источник: --claims или сообщение/--commit", {
133
+ hint: "--claims уже содержит готовые утверждения.",
134
+ exitCode: 2,
135
+ });
136
+ }
137
+ if (!claimsPath && sources.length === 0) {
138
+ throw new PilotError("Нужно указать источник утверждений", {
139
+ hint: "Используйте --commit, --message, --message-file или --claims.",
140
+ exitCode: 2,
141
+ });
142
+ }
143
+ if (sources.length > 1) {
144
+ throw new PilotError("Укажите только один источник сообщения", {
145
+ hint: "Выберите --commit, --message или --message-file.",
146
+ exitCode: 2,
147
+ });
148
+ }
149
+ let source;
150
+ let diff;
151
+ let messageText = "";
152
+ if (commit) {
153
+ const inputs = commitInputs(ctx.cwd, commit);
154
+ source = inputs.source;
155
+ diff = inputs.diff;
156
+ messageText = inputs.message;
157
+ }
158
+ else {
159
+ const data = await loadDiff(values, ctx, [], { optionalGit: true });
160
+ source = describeDiffSource(data.source);
161
+ diff = data.diff;
162
+ if (messageFile)
163
+ messageText = readTextFile(ctx.cwd, messageFile).trim();
164
+ else if (message)
165
+ messageText = message.trim();
166
+ }
167
+ if (!diff.trim()) {
168
+ log.info("Изменений нет — проверять утверждения нечего.");
169
+ return 0;
170
+ }
171
+ let claims;
172
+ if (claimsPath) {
173
+ claims = parsePolygraphClaims(readTextFile(ctx.cwd, claimsPath));
174
+ source = `claims ${claimsPath}`;
175
+ }
176
+ else {
177
+ if (!messageText) {
178
+ throw new PilotError("Сообщение пустое", {
179
+ hint: "Передайте непустой --message, --message-file или --commit.",
180
+ exitCode: 2,
181
+ });
182
+ }
183
+ const result = await executeRecipeDetailed({
184
+ recipe: "custom",
185
+ projectType: detectProjectType(ctx.cwd, []),
186
+ additionalContext: buildPolygraphPrompt(messageText, diff),
187
+ diff: "",
188
+ secretFindings: [],
189
+ changedFiles: [],
190
+ failOnSecrets: false,
191
+ noSecretScan: true,
192
+ meta: { source },
193
+ }, ctx);
194
+ claims = parsePolygraphClaims(result.analysis ?? "");
195
+ }
196
+ if (!claims) {
197
+ const report = errorReport(source, "[POLYGRAPH ERROR]: модель не вернула JSON-утверждения.");
198
+ const wrote = ctx.flags.json
199
+ ? writeOutput(JSON.stringify(report, null, 2), ctx.flags.output)
200
+ : writeOutput(report.content, ctx.flags.output);
201
+ if (wrote)
202
+ log.success(`Отчёт сохранён: ${wrote}`);
203
+ log.error(report.summary);
204
+ return 2;
205
+ }
206
+ const report = evaluatePolygraph(diff, claims, source);
207
+ const wrote = ctx.flags.json
208
+ ? writeOutput(JSON.stringify(report, null, 2), ctx.flags.output)
209
+ : writeOutput(report.content, ctx.flags.output);
210
+ if (wrote)
211
+ log.success(`Отчёт сохранён: ${wrote}`);
212
+ if (report.status === "contradicted")
213
+ log.error(report.summary);
214
+ else if (report.status === "verified")
215
+ log.success(report.summary);
216
+ else
217
+ log.warn(report.summary);
218
+ if (report.status === "error")
219
+ return 2;
220
+ const threshold = parseFailOn(asString(values, "fail-on"), asBoolean(values, "strict"));
221
+ const failed = report.status === "contradicted" ||
222
+ (threshold === "unverifiable" && report.status === "inconclusive");
223
+ return failed ? 1 : 0;
224
+ }
225
+ //# sourceMappingURL=polygraph.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"polygraph.js","sourceRoot":"","sources":["../../src/commands/polygraph.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,cAAc,EAAE,UAAU,EAAmB,MAAM,oBAAoB,CAAC;AAChH,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,oBAAoB,EACpB,eAAe,GAGhB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,MAAM,OAAO,GAAe,UAAU,CAAC;IACrC,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IAC1B,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IAC3B,cAAc,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IAClC,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IAC1B,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;IACxB,KAAK,EAAE,EAAE,I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CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACxB,CAAC"}
@@ -0,0 +1,402 @@
1
+ import { collectAddedLines } from "./alien-dna.js";
2
+ import { splitDiffBlocks } from "./diff.js";
3
+ import { scanSource } from "./sast.js";
4
+ import { isCodeFile, isTestFile } from "./slop/source.js";
5
+ const KINDS = new Set([
6
+ "test-added",
7
+ "file-added",
8
+ "file-removed",
9
+ "api-change",
10
+ "dependency",
11
+ "docs",
12
+ "security",
13
+ "behavior",
14
+ "refactor",
15
+ "other",
16
+ ]);
17
+ const MAX_CLAIMS = 20;
18
+ const MAX_CLAIM_CHARS = 500;
19
+ const DOC_PATH = /^(?:docs\/|readme|changelog|contributing|license|authors)/i;
20
+ const DOC_EXT = /\.(?:md|mdx|rst)$/i;
21
+ const LOCKFILE = /(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock)$/i;
22
+ const API_PATTERN = /^\s*(?:export\s+(?:default\s+)?(?:async\s+)?(?:function|class|const|let|var|interface|type|enum)\b|export\s*\{|(?:async\s+)?def\s+[A-Za-z_]|func\s+(?:\([^)]*\)\s*)?[A-Z]|pub\s+(?:fn|struct|enum|trait|mod)\b|public\s+(?:static\s+)?(?:class|interface|enum|void|final|[A-Z]\w*))/;
23
+ const SECURITY_PATTERN = /(?:auth|sanitiz|escape|csrf|csp|permission|encrypt|decrypt|hash|bcrypt|argon|validate|secret|token|tls|https|helmet|rate.?limit|allowlist|denylist|content-security)/i;
24
+ const DEPENDENCY_KEY_BLOCKLIST = new Set(["name", "version", "node", "npm", "engines", "packageManager", "type"]);
25
+ function isDoc(path) {
26
+ return DOC_PATH.test(path) || DOC_EXT.test(path);
27
+ }
28
+ function isBehaviorPath(path) {
29
+ if (isDoc(path) || isTestFile(path) || LOCKFILE.test(path))
30
+ return false;
31
+ return !path.startsWith(".oc-pilot/");
32
+ }
33
+ function unique(values) {
34
+ return [...new Set(values)];
35
+ }
36
+ function dependenciesFrom(line) {
37
+ const found = [];
38
+ const json = /"(@?[A-Za-z0-9._/-]+)"\s*:\s*"[~^<>=0-9]/.exec(line);
39
+ if (json?.[1] && !DEPENDENCY_KEY_BLOCKLIST.has(json[1]))
40
+ found.push(json[1]);
41
+ const requirement = /^\s*([A-Za-z0-9_.-]+)\s*(?:==|>=|<=|~=|!=)/.exec(line);
42
+ if (requirement?.[1] && requirement[1].toLowerCase() !== "python")
43
+ found.push(requirement[1]);
44
+ const go = /^\s*([A-Za-z0-9._/-]+\.[A-Za-z0-9._/-]+)\s+v[0-9]/.exec(line);
45
+ if (go?.[1])
46
+ found.push(go[1]);
47
+ return found;
48
+ }
49
+ function collectRemovedLines(diff) {
50
+ const removed = [];
51
+ for (const block of splitDiffBlocks(diff)) {
52
+ if (block.path === "(unknown)" || block.path === "(diff)")
53
+ continue;
54
+ let inHunk = false;
55
+ for (const raw of block.text.split(/\r?\n/)) {
56
+ if (raw === "")
57
+ continue;
58
+ if (/^@@ /.test(raw)) {
59
+ inHunk = true;
60
+ continue;
61
+ }
62
+ if (!inHunk)
63
+ continue;
64
+ if (raw.startsWith("---") || raw.startsWith("+++"))
65
+ continue;
66
+ if (raw.startsWith("-"))
67
+ removed.push({ path: block.path, text: raw.slice(1), kind: "removed" });
68
+ }
69
+ }
70
+ return removed;
71
+ }
72
+ /** Turns a unified diff into deterministic facts that claims can be checked against. */
73
+ export function buildDiffFacts(diff) {
74
+ const added = [];
75
+ const removed = [];
76
+ const modified = [];
77
+ for (const block of splitDiffBlocks(diff)) {
78
+ if (block.path === "(unknown)" || block.path === "(diff)")
79
+ continue;
80
+ if (/^new file mode /m.test(block.text))
81
+ added.push(block.path);
82
+ else if (/^deleted file mode /m.test(block.text))
83
+ removed.push(block.path);
84
+ else
85
+ modified.push(block.path);
86
+ }
87
+ const changed = unique([...added, ...removed, ...modified]);
88
+ const addedLines = collectAddedLines(diff);
89
+ const removedLines = collectRemovedLines(diff);
90
+ const changedLines = [
91
+ ...addedLines.map((line) => ({ path: line.path, text: line.text, kind: "added" })),
92
+ ...removedLines,
93
+ ];
94
+ return {
95
+ changed,
96
+ added: unique(added),
97
+ removed: unique(removed),
98
+ modified: unique(modified),
99
+ addedLines,
100
+ changedLines,
101
+ dependencies: unique(addedLines.flatMap((line) => dependenciesFrom(line.text))),
102
+ removedDependencies: unique(removedLines.flatMap((line) => dependenciesFrom(line.text))),
103
+ testsTouched: changed.some((path) => isTestFile(path)),
104
+ docsTouched: changed.some((path) => isDoc(path)),
105
+ behaviorTouched: changed.some((path) => isBehaviorPath(path)),
106
+ };
107
+ }
108
+ function check(target, status, evidence) {
109
+ return { claim: target, status, evidence };
110
+ }
111
+ function claimedPaths(text) {
112
+ const found = text.match(/`?[A-Za-z0-9_@./-]+\.[A-Za-z0-9]+`?/g) ?? [];
113
+ return unique(found
114
+ .map((value) => value.replace(/`/g, "").replace(/^\.\//, "").replace(/[.,;:]+$/, ""))
115
+ .filter((value) => /\.(?:ts|tsx|js|jsx|mjs|cjs|go|py|rs|java|kt|rb|php|cs|c|h|cc|cpp|hpp|swift|scala|sh|ps1|lua|dart|json|md|mdx|yml|yaml|toml|lock|txt)$/i.test(value)));
116
+ }
117
+ function matchPath(candidates, pool) {
118
+ for (const candidate of candidates) {
119
+ const hit = pool.find((path) => path === candidate || path.endsWith(`/${candidate}`));
120
+ if (hit)
121
+ return hit;
122
+ }
123
+ return undefined;
124
+ }
125
+ function quotedNames(text) {
126
+ const names = [];
127
+ const pattern = /[`"]([^`"]{1,80})[`"]/g;
128
+ for (let match = pattern.exec(text); match; match = pattern.exec(text)) {
129
+ const value = match[1]?.trim() ?? "";
130
+ if (!value || value.includes(" "))
131
+ continue;
132
+ if (/^@?[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value))
133
+ names.push(value);
134
+ }
135
+ return unique(names);
136
+ }
137
+ /** Checks one claim against the diff facts. Pure and deterministic. */
138
+ export function checkClaim(target, facts) {
139
+ const negative = target.polarity === "negative";
140
+ switch (target.kind) {
141
+ case "test-added": {
142
+ const testFile = facts.added.find((path) => isTestFile(path));
143
+ const testLine = facts.addedLines.find((line) => isTestFile(line.path));
144
+ if (negative) {
145
+ if (testFile)
146
+ return check(target, "contradicted", `diff добавляет тестовый файл ${testFile}`);
147
+ if (testLine)
148
+ return check(target, "contradicted", `diff добавляет строки в тест ${testLine.path}`);
149
+ return check(target, "supported", "diff не добавляет тестов");
150
+ }
151
+ if (testFile)
152
+ return check(target, "supported", `добавлен тестовый файл ${testFile}`);
153
+ if (testLine)
154
+ return check(target, "supported", `добавлены строки в тест ${testLine.path}`);
155
+ if (facts.testsTouched)
156
+ return check(target, "unverifiable", "тестовые файлы изменены, но новых тестов не добавлено");
157
+ return check(target, "contradicted", "diff не содержит тестовых файлов или строк");
158
+ }
159
+ case "file-added":
160
+ case "file-removed": {
161
+ const paths = claimedPaths(target.text);
162
+ if (paths.length === 0)
163
+ return check(target, "unverifiable", "в утверждении нет пути файла");
164
+ const pool = target.kind === "file-added" ? facts.added : facts.removed;
165
+ const opposite = target.kind === "file-added" ? facts.removed : facts.added;
166
+ const hit = matchPath(paths, pool);
167
+ if (negative) {
168
+ if (hit) {
169
+ return check(target, "contradicted", `diff ${target.kind === "file-added" ? "добавляет" : "удаляет"} ${hit}`);
170
+ }
171
+ return check(target, "supported", `diff не ${target.kind === "file-added" ? "добавляет" : "удаляет"} указанный файл`);
172
+ }
173
+ if (hit) {
174
+ return check(target, "supported", `diff ${target.kind === "file-added" ? "добавляет" : "удаляет"} ${hit}`);
175
+ }
176
+ const other = matchPath(paths, facts.changed);
177
+ if (other) {
178
+ return check(target, "contradicted", `файл ${other} изменён, но не ${target.kind === "file-added" ? "добавлен" : "удалён"}`);
179
+ }
180
+ const oppositeHit = matchPath(paths, opposite);
181
+ if (oppositeHit) {
182
+ return check(target, "contradicted", `файл ${oppositeHit} ${target.kind === "file-added" ? "удалён" : "добавлен"}, а не наоборот`);
183
+ }
184
+ return check(target, "contradicted", `файла ${paths[0]} нет в diff`);
185
+ }
186
+ case "api-change": {
187
+ const apiLines = facts.changedLines.filter((line) => API_PATTERN.test(line.text));
188
+ if (negative) {
189
+ if (apiLines.length > 0) {
190
+ return check(target, "contradicted", `изменена экспортируемая строка ${apiLines[0]?.path}: ${apiLines[0]?.text.trim().slice(0, 120)}`);
191
+ }
192
+ return check(target, "supported", "в diff нет изменений экспортируемого API");
193
+ }
194
+ if (apiLines.length > 0) {
195
+ const first = apiLines[0];
196
+ return check(target, "supported", `изменён API в ${first.path}: ${first.text.trim().slice(0, 120)}`);
197
+ }
198
+ if (facts.addedLines.length === 0)
199
+ return check(target, "contradicted", "diff не добавляет строк кода");
200
+ return check(target, "unverifiable", "в diff нет явных изменений экспортируемого API");
201
+ }
202
+ case "dependency": {
203
+ if (negative) {
204
+ if (facts.dependencies.length > 0) {
205
+ return check(target, "contradicted", `добавлены зависимости: ${facts.dependencies.slice(0, 3).join(", ")}`);
206
+ }
207
+ return check(target, "supported", "манифесты не добавляют зависимостей");
208
+ }
209
+ if (facts.dependencies.length === 0) {
210
+ if (facts.removedDependencies.length > 0) {
211
+ return check(target, "contradicted", `diff удаляет зависимости (${facts.removedDependencies.slice(0, 3).join(", ")}), но не добавляет`);
212
+ }
213
+ return check(target, "contradicted", "в diff нет изменений манифестов зависимостей");
214
+ }
215
+ const named = quotedNames(target.text).find((name) => facts.dependencies.some((dependency) => dependency === name || dependency.endsWith(`/${name}`)));
216
+ if (named)
217
+ return check(target, "supported", `добавлена зависимость ${named}`);
218
+ const quoted = quotedNames(target.text);
219
+ if (quoted.length > 0) {
220
+ return check(target, "contradicted", `в diff нет зависимости ${quoted[0]}`);
221
+ }
222
+ return check(target, "supported", `добавлены зависимости: ${facts.dependencies.slice(0, 3).join(", ")}`);
223
+ }
224
+ case "docs": {
225
+ if (negative) {
226
+ if (facts.docsTouched)
227
+ return check(target, "contradicted", `изменена документация: ${facts.changed.find((path) => isDoc(path))}`);
228
+ return check(target, "supported", "diff не меняет документацию");
229
+ }
230
+ if (facts.docsTouched) {
231
+ return check(target, "supported", `изменена документация: ${facts.changed.find((path) => isDoc(path))}`);
232
+ }
233
+ if (facts.behaviorTouched)
234
+ return check(target, "contradicted", "код изменён, но документация не тронута");
235
+ return check(target, "contradicted", "diff не меняет документацию");
236
+ }
237
+ case "security": {
238
+ const findings = facts.addedLines
239
+ .filter((line) => isCodeFile(line.path))
240
+ .slice(0, 200)
241
+ .flatMap((line) => scanSource(line.path, line.text).findings);
242
+ if (findings.length > 0) {
243
+ const first = findings[0];
244
+ return check(target, "contradicted", `добавлена строка с потенциальной уязвимостью (${first.rule}): ${first.snippet.slice(0, 120)}`);
245
+ }
246
+ if (negative)
247
+ return check(target, "unverifiable", "отсутствие проблем безопасности по diff не доказывается");
248
+ const securityLine = facts.addedLines.find((line) => SECURITY_PATTERN.test(line.text));
249
+ if (securityLine) {
250
+ return check(target, "supported", `добавлены строки про безопасность в ${securityLine.path}: ${securityLine.text.trim().slice(0, 120)}`);
251
+ }
252
+ return check(target, "unverifiable", "по diff нельзя подтвердить улучшение безопасности");
253
+ }
254
+ case "behavior": {
255
+ const source = facts.changed.filter((path) => isBehaviorPath(path));
256
+ if (negative) {
257
+ if (source.length > 0) {
258
+ return check(target, "contradicted", `изменены исходники: ${source.slice(0, 3).join(", ")}`);
259
+ }
260
+ return check(target, "supported", "diff не меняет исходники");
261
+ }
262
+ if (source.length > 0) {
263
+ return check(target, "supported", `изменены исходники: ${source.slice(0, 3).join(", ")}`);
264
+ }
265
+ return check(target, "contradicted", "diff меняет только тесты и документацию");
266
+ }
267
+ case "refactor": {
268
+ if (negative)
269
+ return check(target, "unverifiable", "отрицание рефакторинга по diff не проверяется");
270
+ if (!facts.behaviorTouched)
271
+ return check(target, "contradicted", "diff не меняет исходный код");
272
+ if (facts.testsTouched) {
273
+ return check(target, "unverifiable", "исходники и тесты изменены вместе, поведение могло измениться");
274
+ }
275
+ return check(target, "supported", "исходники изменены без изменения тестов");
276
+ }
277
+ default:
278
+ return check(target, "unverifiable", "нет детерминированной проверки для этого утверждения");
279
+ }
280
+ }
281
+ /** Parses strict JSON claims from a model answer, a file or a test fixture. */
282
+ export function parsePolygraphClaims(text) {
283
+ const objectStart = text.indexOf("{");
284
+ const arrayStart = text.indexOf("[");
285
+ let start = -1;
286
+ if (objectStart === -1 && arrayStart === -1)
287
+ return undefined;
288
+ if (objectStart === -1)
289
+ start = arrayStart;
290
+ else if (arrayStart === -1)
291
+ start = objectStart;
292
+ else
293
+ start = Math.min(objectStart, arrayStart);
294
+ const objectEnd = text.lastIndexOf("}");
295
+ const arrayEnd = text.lastIndexOf("]");
296
+ const end = Math.max(objectEnd, arrayEnd);
297
+ if (end <= start)
298
+ return undefined;
299
+ let parsed;
300
+ try {
301
+ parsed = JSON.parse(text.slice(start, end + 1));
302
+ }
303
+ catch {
304
+ return undefined;
305
+ }
306
+ let list;
307
+ if (Array.isArray(parsed))
308
+ list = parsed;
309
+ else if (parsed && typeof parsed === "object" && Array.isArray(parsed.claims)) {
310
+ list = parsed.claims;
311
+ }
312
+ else {
313
+ return undefined;
314
+ }
315
+ const claims = [];
316
+ for (const item of list) {
317
+ if (!item || typeof item !== "object")
318
+ continue;
319
+ const record = item;
320
+ const value = typeof record.text === "string" ? record.text.trim() : "";
321
+ if (!value)
322
+ continue;
323
+ const kind = typeof record.kind === "string" && KINDS.has(record.kind)
324
+ ? record.kind
325
+ : "other";
326
+ const polarity = record.polarity === "negative" || record.negated === true ? "negative" : "positive";
327
+ claims.push({ kind, text: value.slice(0, MAX_CLAIM_CHARS), polarity });
328
+ if (claims.length >= MAX_CLAIMS)
329
+ break;
330
+ }
331
+ return claims;
332
+ }
333
+ export function buildPolygraphPrompt(message, diff) {
334
+ const cappedMessage = message.length > 20_000 ? message.slice(0, 20_000) : message;
335
+ const cappedDiff = diff.length > 60_000 ? diff.slice(0, 60_000) : diff;
336
+ return [
337
+ "You are a polygraph for code changes. Extract every factual claim from the message that can be checked against the diff.",
338
+ "Do not praise, summarize or judge the code. Only extract claims that the author asserts as facts about this change.",
339
+ "Return strict JSON only, with no markdown and no prose outside the object:",
340
+ '{"claims":[{"kind":"test-added","text":"adds a regression test for the timeout","polarity":"positive"}]}',
341
+ "Allowed kinds: test-added, file-added, file-removed, api-change, dependency, docs, security, behavior, refactor, other.",
342
+ "Rules: quote or closely paraphrase the claim; one claim per object; at most 12 claims; skip pure intentions and future work.",
343
+ 'Use polarity "negative" for claims such as "no behavior change", "without new dependencies" or "does not touch the API".',
344
+ 'Use "other" only when no specific kind fits.',
345
+ "",
346
+ "MESSAGE:",
347
+ cappedMessage,
348
+ "",
349
+ "DIFF:",
350
+ cappedDiff,
351
+ ].join("\n");
352
+ }
353
+ export function renderPolygraph(report) {
354
+ const lines = [
355
+ `Polygraph: ${report.status}`,
356
+ `Source: ${report.source}`,
357
+ `Claims: supported ${String(report.counts.supported)}, contradicted ${String(report.counts.contradicted)}, unverifiable ${String(report.counts.unverifiable)}`,
358
+ "",
359
+ ];
360
+ if (report.claims.length === 0) {
361
+ lines.push("Утверждений не найдено.");
362
+ }
363
+ for (const entry of report.claims) {
364
+ lines.push(` [${entry.status.toUpperCase()}] ${entry.claim.kind} (${entry.claim.polarity}): ${entry.claim.text}`);
365
+ lines.push(` ${entry.evidence}`);
366
+ }
367
+ lines.push("", report.summary);
368
+ return `${lines.join("\n")}\n`;
369
+ }
370
+ /** Evaluates claims against the diff and builds the final report. */
371
+ export function evaluatePolygraph(diff, claims, source) {
372
+ const facts = buildDiffFacts(diff);
373
+ const checks = claims.map((entry) => checkClaim(entry, facts));
374
+ const counts = {
375
+ supported: 0,
376
+ contradicted: 0,
377
+ unverifiable: 0,
378
+ };
379
+ for (const entry of checks)
380
+ counts[entry.status] += 1;
381
+ const status = counts.contradicted > 0
382
+ ? "contradicted"
383
+ : checks.length === 0 || counts.unverifiable > 0
384
+ ? "inconclusive"
385
+ : "verified";
386
+ const summary = status === "contradicted"
387
+ ? `[CLAIM CONTRADICTED]: сообщение расходится с diff (${String(counts.contradicted)}).`
388
+ : status === "inconclusive"
389
+ ? `[POLYGRAPH INCONCLUSIVE]: проверяемых утверждений нет или им не хватает доказательств (${String(counts.unverifiable)}).`
390
+ : "[POLYGRAPH VERIFIED]: все проверяемые утверждения согласуются с diff.";
391
+ const report = {
392
+ source,
393
+ claims: checks,
394
+ counts,
395
+ status,
396
+ summary,
397
+ content: "",
398
+ };
399
+ report.content = renderPolygraph(report);
400
+ return report;
401
+ }
402
+ //# sourceMappingURL=polygraph.js.map