search-visibility 1.2.0 → 1.3.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.es.md +39 -3
  3. package/README.ja.md +39 -3
  4. package/README.ko.md +47 -10
  5. package/README.md +47 -10
  6. package/README.zh.md +39 -3
  7. package/package.json +2 -1
  8. package/skills/seo-orchestrator/scripts/ai-performance.mjs +107 -0
  9. package/skills/seo-orchestrator/scripts/canonical.mjs +175 -0
  10. package/skills/seo-orchestrator/scripts/command.mjs +6 -0
  11. package/skills/seo-orchestrator/scripts/comparison-pairs.mjs +89 -0
  12. package/skills/seo-orchestrator/scripts/crawl-report.mjs +34 -0
  13. package/skills/seo-orchestrator/scripts/fetch-page.mjs +2 -5
  14. package/skills/seo-orchestrator/scripts/hreflang.mjs +273 -0
  15. package/skills/seo-orchestrator/scripts/html.mjs +7 -80
  16. package/skills/seo-orchestrator/scripts/index-status.mjs +181 -0
  17. package/skills/seo-orchestrator/scripts/indexing.mjs +28 -39
  18. package/skills/seo-orchestrator/scripts/internal-crawl.mjs +16 -46
  19. package/skills/seo-orchestrator/scripts/link-header.mjs +93 -0
  20. package/skills/seo-orchestrator/scripts/mcp.mjs +45 -8
  21. package/skills/seo-orchestrator/scripts/naver-advisor.mjs +147 -0
  22. package/skills/seo-orchestrator/scripts/observations.mjs +42 -8
  23. package/skills/seo-orchestrator/scripts/report-html.mjs +35 -0
  24. package/skills/seo-orchestrator/scripts/report-input.mjs +142 -0
  25. package/skills/seo-orchestrator/scripts/report-sources.mjs +202 -0
  26. package/skills/seo-orchestrator/scripts/robots.mjs +270 -0
  27. package/skills/seo-orchestrator/scripts/scope.mjs +185 -0
  28. package/skills/seo-orchestrator/scripts/search-performance.mjs +1 -1
  29. package/skills/seo-orchestrator/scripts/seo-check.mjs +203 -263
  30. package/skills/seo-orchestrator/scripts/site-audit.mjs +102 -46
  31. package/skills/seo-orchestrator/scripts/structured-data.mjs +316 -0
  32. package/skills/seo-orchestrator/scripts/url-inspection.mjs +150 -0
  33. package/skills/seo-orchestrator/scripts/visibility-comparison.mjs +218 -39
  34. package/skills/seo-orchestrator/scripts/visibility-report.mjs +71 -48
  35. package/skills/seo-orchestrator/scripts/visibility.mjs +53 -50
@@ -0,0 +1,150 @@
1
+ // 운영자가 저장한 Google URL Inspection API 응답을 이번에 점검한 페이지와 대조한다.
2
+ // API 응답은 Google 색인에 있는 버전의 정보이며 실시간 테스트 결과가 아니다.
3
+ import { t } from "./locale.mjs";
4
+ import { requireObject, rejectUnknownKeys, optionalText } from "./scope.mjs";
5
+ import { comparableUrl, webUrlOrNull } from "./link-header.mjs";
6
+
7
+ const TIMESTAMP = /^(\d{4}-\d{2}-\d{2})T([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
8
+ const STATUS_FIELDS = ["verdict", "coverageState", "robotsTxtState", "indexingState", "pageFetchState", "lastCrawlTime", "userCanonical", "googleCanonical", "crawledAs"];
9
+
10
+ function timestamp(value, field) {
11
+ if (value === undefined || value === null) return null;
12
+ const text = typeof value === "string" ? value.trim() : "";
13
+ const day = TIMESTAMP.exec(text)?.[1];
14
+ const midnight = Date.parse(`${day}T00:00:00Z`);
15
+ if (!day || !Number.isFinite(Date.parse(text)) || !Number.isFinite(midnight) || new Date(midnight).toISOString().slice(0, 10) !== day) {
16
+ throw new Error(t(`${field}에는 시간대가 있는 ISO 일시를 입력하세요.`, `${field} must be an ISO timestamp with a time zone.`));
17
+ }
18
+ return text;
19
+ }
20
+
21
+ // 경로와 쿼리까지 같은 URL만 같은 페이지로 본다. 프래그먼트는 제외한다.
22
+ export function pageKey(value) {
23
+ const href = typeof value === "string" ? webUrlOrNull(value) : null;
24
+ return href ? comparableUrl(href) : null;
25
+ }
26
+
27
+ export function parseUrlInspections(input, label = "urlInspection") {
28
+ return [input].flat().map((record, index) => {
29
+ const field = `${label}[${index}]`;
30
+ requireObject(record, field);
31
+ rejectUnknownKeys(record, ["inspectionUrl", "inspectedAt", "deployedAt", "response"], field);
32
+ if (!pageKey(record.inspectionUrl)) {
33
+ throw new Error(t(`${field}.inspectionUrl에는 인증정보 없는 HTTP(S) 절대 URL을 입력하세요.`, `${field}.inspectionUrl must be an absolute HTTP(S) URL without credentials.`));
34
+ }
35
+ const response = requireObject(record.response, `${field}.response`);
36
+ const result = requireObject(response.inspectionResult, `${field}.response.inspectionResult`);
37
+ const status = result.indexStatusResult === undefined ? {} : requireObject(result.indexStatusResult, `${field}.response.inspectionResult.indexStatusResult`);
38
+ const values = Object.fromEntries(STATUS_FIELDS.map((key) => [key, optionalText(status[key], `${field}.indexStatusResult.${key}`)]));
39
+ values.lastCrawlTime = timestamp(status.lastCrawlTime, `${field}.indexStatusResult.lastCrawlTime`);
40
+ return {
41
+ inspectionUrl: record.inspectionUrl.trim(),
42
+ inspectedAt: timestamp(record.inspectedAt, `${field}.inspectedAt`),
43
+ deployedAt: timestamp(record.deployedAt, `${field}.deployedAt`),
44
+ index: values,
45
+ };
46
+ });
47
+ }
48
+
49
+ function currentPage(key, pages) {
50
+ const final = pages.find((page) => pageKey(page.finalUrl) === key);
51
+ const page = final ?? pages.find((candidate) => pageKey(candidate.target) === key);
52
+ if (!page) return { observed: false, reason: "not-audited", html: [], header: [] };
53
+ if (page.error) return { observed: false, reason: "fetch-error", error: page.error, html: [], header: [] };
54
+ const base = { observed: true, target: page.target, finalUrl: page.finalUrl, status: page.status, checkedAt: page.checkedAt };
55
+ // 리다이렉트 대상의 선언은 다른 URL의 결과이므로 섞지 않는다.
56
+ if (!final) return { ...base, reason: "redirect", html: [], header: [] };
57
+ const declared = (entries) => (entries ?? []).map(({ href, url }) => ({ href, url: url ? pageKey(url) : null }));
58
+ // 의도적으로 제외한 페이지의 noindex는 확인 대상이 아니다.
59
+ const noindex = page.indexing?.intent === "exclude" ? [] : (page.indexing?.blocks ?? []).filter(({ scope }) => scope === "robots" || scope === "googlebot");
60
+ return {
61
+ ...base, reason: page.status === 200 ? null : "http-status", noindex: noindex.map(({ scope, directive }) => `${scope}: ${directive}`),
62
+ html: declared(page.canonical?.html), header: declared(page.canonical?.header),
63
+ ...(page.canonical?.omitted && { omitted: page.canonical.omitted }),
64
+ };
65
+ }
66
+
67
+ const held = (reason) => ({ state: "held", reason });
68
+
69
+ // canonical이 일치해도 색인 판정·가져오기 상태·현재 제외 지시에 문제가 있으면 따로 알린다.
70
+ function indexFlags({ verdict, indexingState, pageFetchState, robotsTxtState }, current) {
71
+ return [
72
+ ["verdict", verdict, ["FAIL", "NEUTRAL", "PARTIAL"].includes(verdict)],
73
+ ["indexingState", indexingState, Boolean(indexingState?.startsWith("BLOCKED_"))],
74
+ ["pageFetchState", pageFetchState, Boolean(pageFetchState) && !["SUCCESSFUL", "PAGE_FETCH_STATE_UNSPECIFIED"].includes(pageFetchState)],
75
+ ["robotsTxtState", robotsTxtState, robotsTxtState === "DISALLOWED"],
76
+ ["currentNoindex", current.noindex?.join(", "), Boolean(current.noindex?.length)],
77
+ ].filter(([, , flagged]) => flagged).map(([field, value]) => ({ field, value }));
78
+ }
79
+
80
+ function compare(record, current) {
81
+ const { lastCrawlTime, userCanonical, googleCanonical } = record.index;
82
+ const google = pageKey(googleCanonical);
83
+ const user = pageKey(userCanonical);
84
+ const usable = current.observed && !current.reason;
85
+ const entries = usable ? [...current.html, ...current.header] : [];
86
+ const declared = [...new Set(entries.map(({ url }) => url).filter(Boolean))];
87
+ // 해석할 수 없거나 생략한 선언을 버리면 충돌이 일치로 보일 수 있다.
88
+ const broken = entries.some(({ url }) => !url) || Boolean(current.omitted);
89
+ const unavailable = !usable ? current.reason ?? "not-audited" : declared.length ? null : broken ? "invalid-declaration" : "no-current-canonical";
90
+ const conflicting = declared.length > 1 || (declared.length === 1 && broken);
91
+
92
+ const recrawl = !record.deployedAt ? held("no-deployed-at") : !lastCrawlTime ? held("no-last-crawl")
93
+ : { state: Date.parse(lastCrawlTime) < Date.parse(record.deployedAt) ? "pending" : "recrawled" };
94
+ const currentVsGoogle = unavailable ? held(unavailable) : conflicting ? { state: "conflict" }
95
+ : !google ? held("no-google-canonical") : { state: declared[0] === google ? "match" : "mismatch" };
96
+ const userVsGoogle = !user ? held("no-user-canonical") : !google ? held("no-google-canonical") : { state: user === google ? "match" : "mismatch" };
97
+ const currentVsUser = unavailable ? held(unavailable) : conflicting ? { state: "conflict" }
98
+ : !user ? held("no-user-canonical") : { state: declared[0] === user ? "match" : "mismatch" };
99
+
100
+ let status = "held";
101
+ if (recrawl.state === "pending") status = "recrawl-needed";
102
+ else if (currentVsGoogle.state === "conflict") status = "declaration-conflict";
103
+ else if (recrawl.state === "recrawled" && currentVsGoogle.state === "mismatch") status = "review-mismatch";
104
+ else if (recrawl.state === "recrawled" && currentVsGoogle.state === "match") status = "consistent";
105
+ const flags = indexFlags(record.index, current);
106
+ if (flags.length && (status === "consistent" || status === "held")) status = "index-review";
107
+ return { status, indexFlags: flags, comparisons: { recrawl, currentVsGoogle, userVsGoogle, currentVsUser } };
108
+ }
109
+
110
+ export function analyzeUrlInspections(records, pages) {
111
+ return records.map((record) => {
112
+ const current = currentPage(pageKey(record.inspectionUrl), pages);
113
+ return { ...record, current, ...compare(record, current) };
114
+ });
115
+ }
116
+
117
+ export function inspectionStatusText(status) {
118
+ return {
119
+ "recrawl-needed": t("배포 후 재수집 확인 필요", "Check for a recrawl after deployment"),
120
+ "review-mismatch": t("불일치 검토 — 배포 후 수집됐지만 현재 선언과 Google 선택이 다름", "Review mismatch: recrawled after deployment, but the current declaration differs from Google's selection"),
121
+ "declaration-conflict": t("현재 canonical 선언 충돌 — HTML과 HTTP 헤더 확인", "Current canonical declarations conflict: check the HTML and HTTP header"),
122
+ consistent: t("배포 후 수집 확인 · 현재 선언과 Google 선택 canonical 일치", "Recrawled after deployment; the current canonical matches Google's selection"),
123
+ "index-review": t("색인 판정·가져오기 상태 확인 필요", "Check the index verdict and fetch state"),
124
+ held: t("비교 보류", "Comparison on hold"),
125
+ }[status];
126
+ }
127
+
128
+ export function comparisonText({ state, reason }) {
129
+ if (state === "held") {
130
+ return `${t("보류", "On hold")} — ${{
131
+ "no-deployed-at": t("배포 시각 없음", "no deployment time"),
132
+ "no-last-crawl": t("마지막 크롤링 시각 없음", "no last crawl time"),
133
+ "no-google-canonical": t("Google 선택 canonical 없음", "no Google-selected canonical"),
134
+ "no-user-canonical": t("수집 당시 사용자 선언 canonical 없음", "no user-declared canonical at crawl time"),
135
+ "no-current-canonical": t("현재 canonical 선언 없음", "no current canonical declaration"),
136
+ "invalid-declaration": t("현재 canonical 선언을 해석할 수 없음", "the current canonical declaration cannot be used"),
137
+ "not-audited": t("이 URL을 이번에 점검하지 않음", "this URL was not audited in this run"),
138
+ "fetch-error": t("현재 페이지 수집 실패", "the current page could not be fetched"),
139
+ redirect: t("현재 URL이 다른 URL로 리다이렉트됨", "the URL now redirects elsewhere"),
140
+ "http-status": t("현재 응답이 200이 아님", "the current response is not 200"),
141
+ }[reason]}`;
142
+ }
143
+ return {
144
+ pending: t("마지막 크롤링이 배포 전", "Last crawl predates the deployment"),
145
+ recrawled: t("마지막 크롤링이 배포 이후", "Last crawl is after the deployment"),
146
+ match: t("일치", "Match"),
147
+ mismatch: t("다름", "Different"),
148
+ conflict: t("현재 선언 충돌", "Current declarations conflict"),
149
+ }[state];
150
+ }
@@ -1,10 +1,30 @@
1
1
  import { currentLocale, t } from "./locale.mjs";
2
2
  import { html, renderCitationGaps } from "./visibility-report.mjs";
3
+ import { pairObservations } from "./comparison-pairs.mjs";
4
+ import { compareScopes, comparisonStatus, describeReason, fieldLabel, rowsOutsidePeriod, statusLabel, valueText } from "./scope.mjs";
5
+
6
+ const SEARCH_FIELDS = ["property", "reportType", "dimension", "searchType", "aggregation", "timeZone", "filters"];
3
7
 
4
8
  const count = value => Number.isSafeInteger(value) && value >= 0;
5
9
  const rate = value => value === null || (Number.isFinite(value) && value >= 0 && value <= 1);
6
10
  const engineKey = name => name.normalize("NFKC").toLowerCase();
7
11
 
12
+ // 보고서에는 담기지만 전후 비교를 계산하지 않는 자료. 키는 report.json의 위치이며 notCompared의 code로 쓴다.
13
+ const NOT_COMPARED = {
14
+ aiPerformance: () => t("Google 생성형 AI 실적·Bing AI Performance", "Google generative AI performance and Bing AI Performance"),
15
+ naverSearchAdvisor: () => t("네이버 서치어드바이저", "Naver Search Advisor"),
16
+ urlInspection: () => t("Google URL 검사", "Google URL Inspection"),
17
+ aiReferrals: () => t("AI 유입", "AI referrals"),
18
+ "site.crawl": () => t("내부 링크 크롤링", "Internal link crawl"),
19
+ };
20
+
21
+ function describeNotCompared({ code, sides }) {
22
+ const name = NOT_COMPARED[code]?.() ?? code;
23
+ const where = sides.map(side => (side === "before" ? t("변경 전", "before") : t("변경 후", "after"))).join(", ");
24
+ return t(`${name}: 전후 비교하지 않았습니다(자료가 있는 보고서: ${where}). 각 보고서에서 확인하세요.`,
25
+ `${name}: not compared (present in: ${where}). Review it in each report.`);
26
+ }
27
+
8
28
  function snapshot(report, label) {
9
29
  const invalid = () => new Error(t(
10
30
  `${label} 입력은 유효한 v1 검색 가시성 report.json이어야 합니다.`,
@@ -29,6 +49,14 @@ function snapshot(report, label) {
29
49
  }
30
50
  }
31
51
  const targets = report.site.pages.map(page => page.target).sort();
52
+ const ruleset = Number.isInteger(report.site.ruleset) ? report.site.ruleset : null;
53
+ // 지적 건수에 영향을 주는 관측 상태와 점검 설정
54
+ const observed = report.site.pages.map(page => ({
55
+ target: page.target,
56
+ unread: typeof page.robots?.fetch?.state === "string" && !["read", "no-file"].includes(page.robots.fetch.state),
57
+ unavailable: page.status === 429 || page.status >= 500,
58
+ intent: page.indexing?.intent ?? null,
59
+ }));
32
60
  const search = report.searchPerformance;
33
61
  if (search !== null && (!count(search?.clicks) || !count(search?.impressions) ||
34
62
  !count(search?.rowCount) || typeof search.dimension !== "string" ||
@@ -42,6 +70,12 @@ function snapshot(report, label) {
42
70
  if (engines.has(key)) throw invalid();
43
71
  engines.set(key, row);
44
72
  }
73
+ const records = report.ai.records ?? [];
74
+ const failures = report.ai.failures ?? [];
75
+ if (!Array.isArray(records) || !Array.isArray(failures) ||
76
+ ![...records, ...failures].every(row => typeof row?.engine === "string" && typeof row.query === "string")) throw invalid();
77
+ const definition = report.ai.definition ?? null;
78
+ if (definition && (typeof definition.brand !== "string" || ![definition.terms, definition.hosts, definition.prefixes].every(Array.isArray))) throw invalid();
45
79
  const competition = report.ai.competition ?? null;
46
80
  if (competition) {
47
81
  const names = new Set();
@@ -62,7 +96,12 @@ function snapshot(report, label) {
62
96
  }
63
97
  }
64
98
  const metadata = { generatedAt: report.generatedAt, brand: report.brand ?? "", sample: report.sample === true };
65
- return { metadata, site, targets, search, engines, competition };
99
+ // 이전 버전의 보고서에는 없는 자료이므로 있는지만 확인한다.
100
+ const inputs = Object.keys(NOT_COMPARED).filter(path => {
101
+ const value = path.split(".").reduce((parent, key) => parent?.[key], report);
102
+ return Array.isArray(value) ? value.length > 0 : Boolean(value);
103
+ });
104
+ return { metadata, site, targets, ruleset, observed, search, engines, competition, records, failures, definition, inputs };
66
105
  }
67
106
 
68
107
  function change(before, after, comparable = true) {
@@ -70,7 +109,117 @@ function change(before, after, comparable = true) {
70
109
  return { before, after, delta };
71
110
  }
72
111
 
73
- function compareCompetition(before, after) {
112
+ function siteReasons(before, after) {
113
+ const complete = site => site.pages > 0 && !site.auditErrors && !site.discoveryErrors && !site.truncated;
114
+ const reasons = JSON.stringify(before.targets) === JSON.stringify(after.targets) ? [] : [{ code: "targets-differ" }];
115
+ for (const [side, { site, observed }] of [["before", before], ["after", after]]) {
116
+ if (!complete(site)) reasons.push({ code: "incomplete-audit", side });
117
+ for (const [code, field] of [["robots-unread", "unread"], ["page-unavailable", "unavailable"]]) {
118
+ const count = observed.filter(page => page[field]).length;
119
+ if (count) reasons.push({ code, side, count });
120
+ }
121
+ }
122
+ if (before.ruleset !== after.ruleset) reasons.push({ code: "ruleset-differs", before: before.ruleset ?? "—", after: after.ruleset ?? "—" });
123
+ const intents = new Map(before.observed.map(page => [page.target, page.intent]));
124
+ const changed = after.observed.filter(page => intents.has(page.target) && page.intent && intents.get(page.target) && page.intent !== intents.get(page.target)).length;
125
+ if (changed) reasons.push({ code: "intent-differs", count: changed });
126
+ return reasons.map(reason => ({ ...reason, message: describeReason(reason) }));
127
+ }
128
+
129
+ function compareSearch(before, after) {
130
+ const scope = search => (search ? { ...(search.scope ?? {}), dimension: search.dimension } : null);
131
+ // 행이 없는 내보내기의 0은 측정한 0으로 확인되지 않는다.
132
+ const missing = [["before", before], ["after", after]].filter(([, search]) => !search || search.rowCount === 0)
133
+ .map(([side]) => ({ code: "missing-data", side }));
134
+ let { status, reasons } = missing.length ? { status: "unverified", reasons: missing }
135
+ : compareScopes(scope(before), scope(after), SEARCH_FIELDS);
136
+ const outside = [["before", before], ["after", after]].map(([side, search]) => ({ code: "date-outside-period", side, count: rowsOutsidePeriod(search) }))
137
+ .filter(reason => reason.count);
138
+ if (outside.length) {
139
+ reasons = [...reasons, ...outside];
140
+ status = "different";
141
+ }
142
+ const comparable = status === "comparable";
143
+ const metric = key => change(before?.[key] ?? null, after?.[key] ?? null, comparable);
144
+ return {
145
+ dimensions: { before: before?.dimension ?? null, after: after?.dimension ?? null },
146
+ scope: { before: before?.scope ?? null, after: after?.scope ?? null },
147
+ status, reasons: reasons.map(reason => ({ ...reason, message: describeReason(reason) })), comparable,
148
+ impressions: metric("impressions"), clicks: metric("clicks"), ctr: metric("ctr"),
149
+ };
150
+ }
151
+
152
+ // 언급·인용 판정에 영향을 주는 설정이 같아야 두 기간의 비율을 비교할 수 있다.
153
+ function definitionReasons(before, after) {
154
+ const missing = [["before", before], ["after", after]].filter(([, value]) => !value)
155
+ .map(([side]) => ({ code: "missing-definition", side }));
156
+ if (missing.length) return missing;
157
+ const same = (a, b) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
158
+ const fields = [
159
+ ...(before.brand.normalize("NFKC").toLowerCase() === after.brand.normalize("NFKC").toLowerCase() ? [] : ["brand"]),
160
+ ...["terms", "hosts", "prefixes"].filter(field => !same(before[field], after[field])),
161
+ ];
162
+ return fields.map(field => ({ code: "definition-changed", field }));
163
+ }
164
+
165
+ // 레코드를 엔진별로 한 번만 나눈다.
166
+ function byEngineKey(rows) {
167
+ const groups = new Map();
168
+ for (const row of rows) {
169
+ const key = engineKey(row.engine);
170
+ if (!groups.has(key)) groups.set(key, []);
171
+ groups.get(key).push(row);
172
+ }
173
+ return groups;
174
+ }
175
+
176
+ function compareEngine(key, before, after, definition, groups) {
177
+ const first = before.engines.get(key);
178
+ const last = after.engines.get(key);
179
+ const of = rows => groups.get(rows).get(key) ?? [];
180
+ const matched = pairObservations(of(before.records), of(after.records));
181
+ // 집계에 있는 답변의 레코드가 보고서에 없으면 조건을 확인할 수 없다.
182
+ const unlisted = [["before", before, first], ["after", after, last]]
183
+ .filter(([, side, row]) => row && of(side.records).length !== row.sampleSize)
184
+ .map(([side]) => ({ code: "missing-records", side }));
185
+ const failed = of(before.failures).length + of(after.failures).length;
186
+ const reasons = [...definition, ...unlisted, ...matched.reasons];
187
+ let status;
188
+ if (definition.length) status = comparisonStatus(definition);
189
+ else if (unlisted.length) status = "unverified";
190
+ else if (matched.pairs.length) status = "comparable";
191
+ else {
192
+ const uncertain = matched.unverified.before + matched.unverified.after > 0;
193
+ const unanswered = [["before", before], ["after", after]].filter(([, side]) => !of(side.records).length).map(([side]) => ({ code: "missing-answers", side }));
194
+ if (unanswered.length) reasons.push(...unanswered);
195
+ else if (!uncertain) reasons.push({ code: "no-common-pairs" });
196
+ status = unanswered.length || (uncertain && !matched.modelDiffers) ? "unverified" : "different";
197
+ }
198
+ const comparable = status === "comparable";
199
+ const complete = comparable && !matched.onlyBefore && !matched.onlyAfter && !matched.modelDiffers &&
200
+ !matched.unverified.before && !matched.unverified.after;
201
+ const overall = field => change(first?.[field] ?? null, last?.[field] ?? null, complete);
202
+ const paired = field => change(matched.beforeRates[field], matched.afterRates[field], comparable);
203
+ const evidence = side => ({ observedAt: side.observedAt, mentioned: side.mentioned, cited: side.cited });
204
+ const name = last?.engine ?? first?.engine ?? [...of(after.failures), ...of(before.failures)][0].engine;
205
+ return {
206
+ engine: name, status, complete,
207
+ reasons: reasons.map(reason => ({ ...reason, message: describeReason(reason) })),
208
+ sampleSize: overall("sampleSize"), mentionRate: overall("mentionRate"), citationRate: overall("citationRate"),
209
+ paired: {
210
+ pairs: matched.pairs.length, onlyBefore: matched.onlyBefore, onlyAfter: matched.onlyAfter,
211
+ unverified: matched.unverified, modelDiffers: matched.modelDiffers,
212
+ failures: { before: of(before.failures).length, after: of(after.failures).length, total: failed },
213
+ mentionRate: paired("mentionRate"), citationRate: paired("citationRate"),
214
+ observations: matched.pairs.map(({ before: a, after: b }) => ({
215
+ query: a.query, mode: a.mode, locale: a.locale, region: a.region, run: a.run, model: a.model ?? null,
216
+ before: evidence(a), after: evidence(b),
217
+ })),
218
+ },
219
+ };
220
+ }
221
+
222
+ function compareCompetition(before, after, completeSample) {
74
223
  if (!before && !after) return null;
75
224
  const index = competition => new Map((competition?.brands ?? []).map(row => [engineKey(row.brand), row]));
76
225
  const first = index(before);
@@ -83,16 +232,16 @@ function compareCompetition(before, after) {
83
232
  };
84
233
  const sameRoster = Boolean(before && after && keys.every(sameBrand));
85
234
  return {
86
- sameRoster,
235
+ sameRoster, completeSample,
87
236
  brands: keys.map(key => {
88
237
  const a = first.get(key);
89
238
  const b = last.get(key);
90
239
  return {
91
240
  brand: b?.brand ?? a.brand,
92
- sampleSize: change(a?.sampleSize ?? null, b?.sampleSize ?? null, Boolean(sameBrand(key))),
93
- mentionRate: change(a?.mentionRate ?? null, b?.mentionRate ?? null, Boolean(sameBrand(key))),
94
- citationRate: change(a?.citationRate ?? null, b?.citationRate ?? null, Boolean(sameBrand(key))),
95
- shareOfVoice: change(a?.shareOfVoice ?? null, b?.shareOfVoice ?? null, sameRoster),
241
+ sampleSize: change(a?.sampleSize ?? null, b?.sampleSize ?? null, Boolean(sameBrand(key)) && completeSample),
242
+ mentionRate: change(a?.mentionRate ?? null, b?.mentionRate ?? null, Boolean(sameBrand(key)) && completeSample),
243
+ citationRate: change(a?.citationRate ?? null, b?.citationRate ?? null, Boolean(sameBrand(key)) && completeSample),
244
+ shareOfVoice: change(a?.shareOfVoice ?? null, b?.shareOfVoice ?? null, sameRoster && completeSample),
96
245
  };
97
246
  }),
98
247
  before: before && { citationGaps: before.citationGaps, tracksCitationGaps: before.tracksCitationGaps },
@@ -103,41 +252,37 @@ function compareCompetition(before, after) {
103
252
  export function compareReports(beforeReport, afterReport) {
104
253
  const before = snapshot(beforeReport, t("변경 전", "before"));
105
254
  const after = snapshot(afterReport, t("변경 후", "after"));
106
- const complete = site => site.pages > 0 && !site.auditErrors && !site.discoveryErrors && !site.truncated;
107
255
  const sameTargets = JSON.stringify(before.targets) === JSON.stringify(after.targets);
108
- const siteComparable = sameTargets && complete(before.site) && complete(after.site);
256
+ const reasons = siteReasons(before, after);
257
+ const siteComparable = reasons.length === 0;
109
258
  const siteValue = (site, key) => site.pages > site.auditErrors ? site[key] : null;
110
- const searchComparable = Boolean(before.search && after.search && before.search.dimension === after.search.dimension);
111
- const keys = [...new Set([...before.engines.keys(), ...after.engines.keys()])].sort();
259
+ const keys = [...new Set([before, after].flatMap(side => [...side.engines.keys(), ...side.failures.map(row => engineKey(row.engine))]))].sort();
260
+ const definition = definitionReasons(before.definition, after.definition);
261
+ const groups = new Map([before.records, after.records, before.failures, after.failures].map(rows => [rows, byEngineKey(rows)]));
262
+ const byEngine = keys.map(key => compareEngine(key, before, after, definition, groups));
263
+ // 실패 기록만 있는 엔진에는 짝지을 답변이 없으므로 표본 완전성에서 제외한다.
264
+ const answered = keys.map((key, index) => ({ key, engine: byEngine[index] }))
265
+ .filter(({ key }) => before.engines.has(key) || after.engines.has(key));
266
+ const completeSample = answered.length > 0 && answered.every(({ engine }) => engine.complete);
267
+ const notCompared = Object.keys(NOT_COMPARED).flatMap(code => {
268
+ const sides = [["before", before], ["after", after]].filter(([, side]) => side.inputs.includes(code)).map(([name]) => name);
269
+ return sides.length ? [{ code, sides, message: describeNotCompared({ code, sides }) }] : [];
270
+ });
112
271
  return {
113
272
  schemaVersion: 1, kind: "comparison", locale: currentLocale(), generatedAt: new Date().toISOString(),
114
273
  before: before.metadata, after: after.metadata,
115
274
  site: {
116
- before: before.site, after: after.site, sameTargets, comparable: siteComparable,
275
+ before: before.site, after: after.site, sameTargets, comparable: siteComparable, reasons,
117
276
  fail: change(siteValue(before.site, "fail"), siteValue(after.site, "fail"), siteComparable),
118
277
  warn: change(siteValue(before.site, "warn"), siteValue(after.site, "warn"), siteComparable),
119
278
  },
120
- searchPerformance: {
121
- dimensions: { before: before.search?.dimension ?? null, after: after.search?.dimension ?? null },
122
- comparable: searchComparable,
123
- impressions: change(before.search?.impressions ?? null, after.search?.impressions ?? null, searchComparable),
124
- clicks: change(before.search?.clicks ?? null, after.search?.clicks ?? null, searchComparable),
125
- ctr: change(before.search?.ctr ?? null, after.search?.ctr ?? null, searchComparable),
126
- },
127
- ai: { competition: compareCompetition(before.competition, after.competition), byEngine: keys.map(key => {
128
- const first = before.engines.get(key);
129
- const last = after.engines.get(key);
130
- return {
131
- engine: last?.engine ?? first.engine,
132
- sampleSize: change(first?.sampleSize ?? null, last?.sampleSize ?? null),
133
- mentionRate: change(first?.mentionRate ?? null, last?.mentionRate ?? null),
134
- citationRate: change(first?.citationRate ?? null, last?.citationRate ?? null),
135
- };
136
- }) },
279
+ searchPerformance: compareSearch(before.search, after.search),
280
+ ai: { competition: compareCompetition(before.competition, after.competition, completeSample), byEngine },
281
+ notCompared,
137
282
  };
138
283
  }
139
284
 
140
- export function renderComparison({ before, after, site, searchPerformance: search, ai }) {
285
+ export function renderComparison({ before, after, site, searchPerformance: search, ai, notCompared = [] }) {
141
286
  const title = t("검색 가시성 전후 비교", "Search Visibility comparison");
142
287
  const beforeLabel = t("변경 전", "Before");
143
288
  const afterLabel = t("변경 후", "After");
@@ -154,9 +299,41 @@ export function renderComparison({ before, after, site, searchPerformance: searc
154
299
  const table = (caption, rows) => `<table><caption>${html(caption)}</caption><thead><tr><th scope="col">${t("지표", "Metric")}</th><th scope="col">${beforeLabel}</th><th scope="col">${afterLabel}</th><th scope="col">${t("증감", "Change")}</th></tr></thead><tbody>${rows}</tbody></table>`;
155
300
  const coverage = (label, key) => row(label, change(site.before[key], site.after[key], false));
156
301
  const source = (label, input) => `<li>${label} · ${html(input.generatedAt)} ${html(input.brand)} ${input.sample ? t("(합성 예시)", "(synthetic sample)") : ""}</li>`;
302
+ const verdict = result => `<p><strong>${html(statusLabel(result.status))}</strong></p>${result.reasons?.length ? `<ul>${result.reasons.map(reason => `<li>${html(describeReason(reason))}</li>`).join("")}</ul>` : ""}`;
303
+ const scopeTable = result => {
304
+ const fields = [...SEARCH_FIELDS.filter(field => field !== "dimension"), "period", "recordedAt"];
305
+ return `<table><caption>${t("조회 조건", "Query conditions")}</caption><thead><tr><th scope="col">${t("조건", "Condition")}</th><th scope="col">${beforeLabel}</th><th scope="col">${afterLabel}</th></tr></thead><tbody>${
306
+ fields.map(field => `<tr><th scope="row">${html(fieldLabel(field))}</th><td>${html(valueText(field, result.scope.before?.[field] ?? null))}</td><td>${html(valueText(field, result.scope.after?.[field] ?? null))}</td></tr>`).join("")}</tbody></table>`;
307
+ };
308
+ const answered = value => (value === null || value === undefined ? "—" : value ? t("있음", "Yes") : t("없음", "No"));
309
+ const engineSection = engine => {
310
+ const paired = engine.paired;
311
+ const counts = [
312
+ [t("공통 관측 쌍", "Common pairs"), paired.pairs],
313
+ [t("변경 전에만", "Only before"), paired.onlyBefore],
314
+ [t("변경 후에만", "Only after"), paired.onlyAfter],
315
+ [t("조건 미확인 (전 / 후)", "Unverified conditions (before / after)"), `${paired.unverified.before} / ${paired.unverified.after}`],
316
+ [t("모델이 다른 쌍", "Pairs with different models"), paired.modelDiffers],
317
+ [t("수집 실패·답변 없음 (전 / 후)", "Failed or unanswered (before / after)"), `${paired.failures.before} / ${paired.failures.after}`],
318
+ ];
319
+ return `<section><h3>${html(engine.engine)}</h3>${verdict(engine)}
320
+ <ul>${counts.map(([label, value]) => `<li>${label}: ${html(value)}</li>`).join("")}</ul>
321
+ ${table(`${engine.engine} · ${t("전체 표본", "Full sample")}`,
322
+ row(t("관측 답변", "Observed answers"), engine.sampleSize) +
323
+ row(t("브랜드 언급률", "Brand mention rate"), engine.mentionRate, true) +
324
+ row(t("소유 출처 인용률", "Owned-source citation rate"), engine.citationRate, true))}
325
+ ${table(`${engine.engine} · ${t(`공통 관측 쌍 ${paired.pairs}개`, `${paired.pairs} common pairs`)}`,
326
+ row(t("브랜드 언급률", "Brand mention rate"), paired.mentionRate, true) +
327
+ row(t("소유 출처 인용률", "Owned-source citation rate"), paired.citationRate, true))}
328
+ ${paired.observations.length ? `<details><summary>${t("짝지은 답변 근거", "Paired answer evidence")}</summary><ul>${paired.observations.map(pair =>
329
+ `<li><strong>${html(pair.query)}</strong> · ${html(pair.mode)} · ${html(pair.locale)} · ${html(pair.region)} · #${html(pair.run)}${pair.model ? ` · ${html(pair.model)}` : ""}<br>
330
+ ${[["before", beforeLabel], ["after", afterLabel]].map(([side, label]) => `${label} <time>${html(pair[side].observedAt)}</time> · ${t("언급", "Mention")} ${answered(pair[side].mentioned)} · ${t("인용", "Citation")} ${answered(pair[side].cited)}`).join("<br>")}</li>`).join("")}</ul></details>` : ""}</section>`;
331
+ };
332
+ const excludedSection = notCompared.length ? `<section><h2>${t("비교하지 않은 자료", "Inputs not compared")}</h2>
333
+ <ul>${notCompared.map(entry => `<li>${html(describeNotCompared(entry))}</li>`).join("")}</ul></section>` : "";
157
334
  const competition = ai.competition;
158
335
  const competitionSection = competition ? `<section><h2>${t("경쟁사 Share of Voice (SoV)", "Competitive Share of Voice (SoV)")}</h2>
159
- <p>${t("SoV 증감은 양쪽의 브랜드와 설정이 같을 때 표시합니다.", "SoV changes require the same brands and tracking settings on both sides.")}</p>
336
+ <p>${t("SoV 증감은 양쪽의 브랜드와 설정이 같고 모든 답변이 같은 조건으로 짝지어질 때 표시합니다.", "SoV changes require the same brands and tracking settings on both sides, with every answer paired under matching conditions.")}</p>
160
337
  ${competition.brands.map(brand => table(brand.brand,
161
338
  row(t("관측 답변", "Observed answers"), brand.sampleSize) +
162
339
  row(t("언급률", "Mention rate"), brand.mentionRate, true) +
@@ -171,26 +348,28 @@ export function renderComparison({ before, after, site, searchPerformance: searc
171
348
  <title>${title}</title><style>
172
349
  body{font:1rem/1.5 system-ui,sans-serif;color:#14243a;background:#f4f7fa;margin:auto;max-width:56rem;padding:1rem}
173
350
  table{width:100%;table-layout:fixed;border-collapse:collapse;background:white;margin:1rem 0;overflow-wrap:anywhere}
351
+ li{overflow-wrap:anywhere}
174
352
  caption,th,td{padding:.55rem;text-align:right;border-bottom:1px solid #d8e0e9}
175
353
  caption,th:first-child{text-align:left}caption{font-weight:bold;background:#dce8f2}
176
354
  @media print{body{background:white}table{break-inside:avoid}}
177
355
  </style></head><body><main><h1>${title}</h1><ul>${source(beforeLabel, before)}${source(afterLabel, after)}</ul>
178
356
  <p>${t("—는 측정값 또는 비교값이 없음을 뜻합니다. 비율 증감은 퍼센트포인트입니다.", "A dash marks an unavailable value or change. Rate changes use percentage points.")}</p>
179
- <section><h2>${t("사이트 진단", "Site audit")}</h2>
180
- <p>${t("동일한 페이지를 양쪽에서 오류나 잘림 없이 점검했을 때 증감을 표시합니다.", "Changes require the same page targets and complete audits without errors or truncation.")}</p>
357
+ ${excludedSection}<section><h2>${t("사이트 진단", "Site audit")}</h2>
358
+ <p>${t("동일한 페이지를 같은 색인 목표와 점검 규칙으로, 오류·잘림 없이 robots.txt까지 읽었을 때 증감을 표시합니다.", "Changes require the same pages, indexing intent and audit rules, with complete audits and readable robots.txt.")}</p>
359
+ ${site.reasons?.length ? `<ul>${site.reasons.map(reason => `<li>${html(describeReason(reason))}</li>`).join("")}</ul>` : ""}
181
360
  ${table(t("발견 항목", "Findings"), row("FAIL", site.fail) + row("WARN", site.warn) +
182
361
  coverage(t("페이지 대상", "Page targets"), "pages") +
183
362
  coverage(t("페이지 점검 오류", "Page audit errors"), "auditErrors") +
184
363
  coverage(t("사이트맵 탐색 오류", "Sitemap discovery errors"), "discoveryErrors"))}</section>
185
364
  <section><h2>Search Console</h2>
186
365
  <p>${t("차원", "Dimensions")} · ${html(search.dimensions.before ?? "—")} → ${html(search.dimensions.after ?? "—")}</p>
187
- <p>${t("같은 속성, 차원, 필터 및 동일한 길이의 기간을 사용하세요.", "Use the same property, dimension, filters and period length.")}</p>
366
+ <p>${t("같은 속성·보고서 종류·차원·검색 유형·집계 단위·시간대·필터이고 길이가 같은 완료된 기간일 때 증감을 계산합니다.", "Changes require the same property, report type, dimension, search type, aggregation, time zone and filters over completed periods of equal length.")}</p>
367
+ ${verdict(search)}
368
+ ${scopeTable(search)}
188
369
  ${table(t("검색 실적", "Search performance"), row(t("노출수", "Impressions"), search.impressions) + row(t("클릭수", "Clicks"), search.clicks) + row("CTR", search.ctr, true))}</section>
189
370
  <section><h2>${t("엔진별 AI 답변 관측", "AI answer observations by engine")}</h2>
190
- <p>${t("같은 질문, 수집 조건 및 소유 출처 설정의 표본끼리 비교하세요.", "Compare samples with the same questions, collection conditions and source ownership settings.")}</p>
191
- ${ai.byEngine.length ? ai.byEngine.map(engine => table(engine.engine,
192
- row(t("관측 답변", "Observed answers"), engine.sampleSize) +
193
- row(t("브랜드 언급률", "Brand mention rate"), engine.mentionRate, true) +
194
- row(t("소유 출처 인용률", "Owned-source citation rate"), engine.citationRate, true))).join("\n")
371
+ <p>${t("질문 원문·엔진·모드·로캘·접속 지역·반복 회차가 같은 답변끼리 짝지어 증감을 계산합니다. 전체 표본의 비율은 항상 표시하며, 두 표본이 모두 짝지어질 때만 전체 증감을 표시합니다.",
372
+ "Changes use answer pairs with the same question, engine, mode, locale, access region and run. Full-sample rates are always shown; a full-sample change appears only when every answer is paired.")}</p>
373
+ ${ai.byEngine.length ? ai.byEngine.map(engineSection).join("\n")
195
374
  : `<p>${t("관측 답변 없음", "No observed answers")}</p>`}</section>${competitionSection}</main></body></html>\n`;
196
375
  }