From 4cbdf3b53e466478de8021e75f2c6962df25ad84 Mon Sep 17 00:00:00 2001 From: Jinsoo Shin <59598545+jsshin2022@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:27:15 +0900 Subject: [PATCH 1/5] =?UTF-8?q?feat(trust):=20'=EA=B7=B8=EB=9E=98=EB=8F=84?= =?UTF-8?q?=20=EB=A7=90=ED=95=A0=20=EC=88=98=20=EC=9E=88=EB=8A=94=20?= =?UTF-8?q?=EA=B2=83'=20=EC=A0=84=EB=A9=B4=20=EB=B0=B0=EC=B9=98,=20?= =?UTF-8?q?=EB=89=B4=EC=8A=A4=20=EB=AC=B8=EC=9E=A5=20=EA=B2=80=EC=A6=9D,?= =?UTF-8?q?=20=EA=B2=80=ED=86=A0=20=EB=B0=B0=EC=A7=80,=20=EA=B5=AC?= =?UTF-8?q?=EC=A1=B0=ED=99=94=20=EB=8D=B0=EC=9D=B4=ED=84=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 판정 옆 한 줄 (answers.takeaway) - 크기를 판별하지 못함 → 배제 범위("±X%보다 큰 변화는 자료와 맞지 않음"), 판단 불가 → 판단할 수 없는 이유, 관측 통계 → 인용 가능한 범위 - 답 페이지 판정 상자와 검색 판정 패널 맨 앞에 2. 뉴스 문장 검증 (search.js checkClaim) - 문장을 붙여 넣으면 가장 가까운 분석과 비교: 뒷받침 / 범위 안 / 결과를 넘어섬 / 결과와 다름 - '효과 없다'·'늘었다/줄었다'·'N%'를 키워드 규칙으로 읽고, 판정과 95% 범위(로그 지표는 %)로 판단 - 결과 안에서 말할 수 있는 문장(이렇게 쓰세요) 제안, 공식 팩트체크 아님을 고지 - usage_rules 로 결과 페이지와 같은 규칙을 공유 3. 검토 배지 (docs/ops/review-checklist.md) - 작성자 아닌 사람이 여덟 항목 확인 → projects.yaml reviewed_by → '검토됨' 배지·신뢰 항목·다음 할 일 - PR 템플릿에 검토 체크 항목 4. 구조화 데이터 (answers.jsonld) - 모든 답 페이지에 schema.org Dataset(CSV 배포 포함) - ClaimReview 는 사람이 projects.yaml claims 에 실제 주장·출처·평가를 적었을 때만 (질문을 주장처럼 꾸미지 않음) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EMnmZPBD5PQJW1UQAARN7q --- .github/PULL_REQUEST_TEMPLATE.md | 1 + README.md | 2 +- catalog/projects.yaml | 4 + docs/ops/review-checklist.md | 23 +++++ site/answers.py | 160 ++++++++++++++++++++++++++++++- site/build.py | 4 +- site/impact.py | 1 + site/quality.py | 21 ++++ site/search.js | 61 +++++++++++- site/search.py | 22 ++++- site/style.css | 18 ++++ tests/test_trust_claims.py | 98 +++++++++++++++++++ 12 files changed, 407 insertions(+), 8 deletions(-) create mode 100644 docs/ops/review-checklist.md create mode 100644 tests/test_trust_claims.py diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 384dfb2..5254d9e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -15,6 +15,7 @@ - [ ] `make check` (ruff + pytest)가 통과합니다 - [ ] 다른 사람의 폴더나 `core/`를 (합의 없이) 수정하지 않았습니다 - [ ] 원자료·가공 데이터 파일을 커밋하지 않았습니다 (시뮬레이션·조례 목록 제외) +- [ ] 결과 PR이면 작성자가 아닌 리뷰어가 [검토 체크리스트](docs/ops/review-checklist.md) 여덟 항목을 리뷰 댓글로 확인했습니다 ## 리뷰어에게 diff --git a/README.md b/README.md index 4bd5e9e..aeff5c4 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ "효과 있었다", "실패했다"는 말이 나올 때 **진짜 효과인지 확인하는 장치**입니다. 정책을 받은 동네와 안 받은 동네를 공공데이터로 비교하고, 데이터가 모르면 "판단 불가"라고 정직하게 말합니다. 질문부터 데이터·계보·분석·대시보드까지 전부 오픈소스입니다. -🔎 **[정책 이름으로 찾기](https://causalinferencelab.github.io/policy-effect-analytics-agent/search.html)** — 이미 확인한 결과와 판정, 쓸 수 있는 공공데이터, 데이터 계보가 한 번에 나옵니다. 결과가 없으면 그 자리에서 분석을 요청할 수 있습니다. +🔎 **[정책 이름으로 찾기](https://causalinferencelab.github.io/policy-effect-analytics-agent/search.html)** — 이미 확인한 결과와 판정, 쓸 수 있는 공공데이터, 데이터 계보가 한 번에 나옵니다. 결과가 없으면 그 자리에서 분석을 요청할 수 있습니다. **뉴스 문장을 통째로 붙여 넣으면** 그 문장이 결과로 뒷받침되는지(뒷받침 · 범위 안 · 결과를 넘어섬 · 결과와 다름) 보여 줍니다. [![사이트 열기](https://img.shields.io/badge/사이트-열기-1d4e89)](https://causalinferencelab.github.io/policy-effect-analytics-agent/) [![분석 결과](https://img.shields.io/badge/분석_결과-보기-1e6a4d)](https://causalinferencelab.github.io/policy-effect-analytics-agent/results.html) diff --git a/catalog/projects.yaml b/catalog/projects.yaml index d9583b7..3194bf7 100644 --- a/catalog/projects.yaml +++ b/catalog/projects.yaml @@ -4,6 +4,10 @@ # plan.yaml → 계획 · fetch.py → 수집 · flow_log.json → 분석 · discussion.md(템플릿과 다르면) → 해석 # reproduced_by: [GitHub ID, ...] — 다른 참여자가 make flow 로 같은 판정을 얻었으면 재현 이슈를 확인하고 추가합니다. # 답 페이지의 '이 결과를 얼마나 믿을 수 있나'와 카드의 '교차 재현됨' 배지로 나옵니다. +# reviewed_by: [GitHub ID, ...] — 작성자가 아닌 사람이 docs/ops/review-checklist.md 여덟 항목을 확인했으면 추가합니다('검토됨' 배지). +# claims: 뉴스·발표에서 나온 구체적인 주장을 이 결과로 검토했을 때만 적습니다 → 답 페이지에 팩트체크 표준 마크업(ClaimReview) +# - text: "주장 문장 그대로" by: "말한 사람·기관" url: "주장이 실린 곳" date: YYYY-MM-DD +# rating: "결과와 맞음" | "범위 안" | "결과를 넘어섬" | "결과와 다름" (검토한 사람이 고름) version: 1 projects: - case: sgim49697-ops-gangnam-bus-2024 diff --git a/docs/ops/review-checklist.md b/docs/ops/review-checklist.md new file mode 100644 index 0000000..8840e48 --- /dev/null +++ b/docs/ops/review-checklist.md @@ -0,0 +1,23 @@ +# 결과 검토 체크리스트 + +사이트의 판정은 '이 데이터와 이 비교로는'이라는 조건이 붙은 답입니다. 작성자가 아닌 사람이 아래 여덟 가지를 확인하면 그 결과에 **검토됨** 배지가 붙습니다. +검토는 결과가 맞다는 보증이 아니라, 결과가 **자기 규칙을 지켰다**는 확인입니다. 숫자를 다시 돌려 보는 것은 [교차 재현](../../.github/ISSUE_TEMPLATE/reproduction.yml)이 따로 맡습니다. + +| # | 확인할 것 | 어디서 보나 | 통과 기준 | +|---|---|---|---| +| 1 | 계획이 결과보다 먼저인가 | 답 페이지 '이 결과를 얼마나 믿을 수 있나' · `git log -- cases/<케이스>/plan.yaml` | 계획 먼저 커밋, 또는 결과 뒤 수정 이유가 discussion.md '계획에서 바뀐 것'에 있음 | +| 2 | 처치 시점이 공식 문서로 확인되나 | plan.yaml `treatment.definition` · README | 법령·고시·보도자료·조례 중 하나의 링크 | +| 3 | 비교 대상이 결과를 보고 고른 것이 아닌가 | plan.yaml `control.rationale` · fetch.py | 선정 규칙이 코드나 문장으로 고정돼 있음 | +| 4 | 데이터 이용 조건이 공개에 맞나 | plan.yaml `data_sources[].license` | 공공누리 1유형·이용허락 제한 없음, 또는 원자료를 커밋하지 않음 | +| 5 | 원자료·개인정보·키가 레포에 없나 | PR 파일 목록 | `data/`·`.env`·키 없음 | +| 6 | 판정 문장이 판정을 넘지 않나 | discussion.md '결과를 한 문장으로' · README | '크기를 판별하지 못함'·'판단 불가'를 '효과 없음'으로 쓰지 않음, 인과 단정 없음 | +| 7 | 한계가 적혀 있나 | discussion.md · plan.yaml `cautions` | 동시에 일어난 다른 사건, 대조군 오염, 측정 문제 중 해당하는 것 | +| 8 | 지표 정의가 재현 가능한가 | plan.yaml `outcomes[].definition` · fetch.py | 다른 사람이 같은 표를 만들 수 있을 만큼 구체적임 | + +## 절차 + +1. 결과 PR에서 위 표를 복사해 PR 리뷰 댓글에 ✅/❌로 채웁니다. ❌가 있으면 작성자가 고친 뒤 다시 봅니다. +2. 여덟 개가 모두 ✅면 `catalog/projects.yaml`의 그 케이스에 `reviewed_by: [내 GitHub ID]`를 더하는 커밋을 같은 PR에 올립니다. +3. 사이트가 다시 빌드되면 결과 카드·검색 판정 패널에 **검토됨**, 답 페이지 신뢰 항목에 '검토 · 통과'가 나옵니다. + +작성자 본인은 자기 결과를 검토할 수 없습니다. 멘토 예시도 같은 규칙을 따릅니다. diff --git a/site/answers.py b/site/answers.py index 7a85bc6..8b04efd 100644 --- a/site/answers.py +++ b/site/answers.py @@ -381,6 +381,10 @@ def load_answers() -> list[dict]: )[:10], "page": f"answers/{case.name}.html", "reproduced_by": list(meta.get("reproduced_by") or []), + "reviewed_by": list(meta.get("reviewed_by") or []), + "claims": [ + c for c in meta.get("claims") or [] if isinstance(c, dict) and c.get("text") + ], "prereg": prereg(case), **read_discussion(case), } @@ -569,6 +573,8 @@ def card(e, a: dict, topics_by_id: dict, up: str = "") -> str: tags.append('시뮬레이션 데이터 결과') if a["mentor"]: tags.append('멘토 예시') + if a.get("reviewed_by"): + tags.append('검토됨') if a.get("reproduced_by"): tags.append('교차 재현됨') if (a.get("prereg") or {}).get("level") == "go": @@ -634,7 +640,56 @@ def trust_block(e, a: dict) -> str:

교차 재현을 하셨나요? 재현 기록 남기기

""" -def _usage(e, a: dict) -> str: +def primary_range(a: dict) -> dict | None: + """주 지표의 추정치·95% 범위 (로그 지표는 % 로). 문장 검증·검색 패널이 쓴다.""" + r = next( + (x for x in a["results"] if x.get("est") is not None and x.get("lo") is not None), None + ) + if not r: + return None + col, unit = r.get("col") or "", r.get("unit") + pct = interpret.is_log(col, unit) + + def tx(v): + return round((math.exp(v) - 1) * 100 if pct else v, 4) + + return { + "name": r.get("name") or col, + "est": tx(r["est"]), + "lo": tx(r["lo"]), + "hi": tx(r["hi"]), + "unit": "%" if pct else (unit or ""), + } + + +def takeaway(a: dict) -> dict | None: + """판정 바로 옆에 둘 한 줄: '모른다'만 남기지 않고 그래도 말할 수 있는 것을 앞에 둔다.""" + if a.get("execution_kind") == "descriptive_only": + return { + "head": "말할 수 있는 것", + "text": "연도별 관측값은 지역·연도·단위와 함께 인용할 수 있어요. 정책 효과는 추정하지 않았어요.", + } + v = a["verdict"] + if v == "conditional": + r = next((r for r in a["results"] if (r.get("said") or {}).get("rule_out")), None) + if r: + return {"head": "그래도 말할 수 있는 것", "text": r["said"]["rule_out"]} + return None + if v == "not_identified": + why = ", ".join(dict.fromkeys(w for r in a["results"] for w in r.get("why") or [])) + return {"head": "판단할 수 없는 이유", "text": why or "설계 조건을 채우지 못했어요"} + if v == "identified": + p = next(iter(a["results"]), None) + if p: + return { + "head": "말할 수 있는 것", + "text": f"{p['name']} {p['effect']} (95% 범위 {p['range']})", + } + return None + + +def usage_rules(a: dict) -> tuple[list[str], list[str]]: + """이렇게 쓰세요 / 이렇게 쓰면 안 됩니다 — 결과 페이지와 문장 검증이 같은 규칙을 쓴다.""" v = a["verdict"] p = next(iter(a["results"]), None) eff = "" @@ -672,6 +727,13 @@ def _usage(e, a: dict) -> str: ) do = [f'"이 설계로는 효과를 판단할 수 없다. 이유: {reasons}."'] dont = ["표의 숫자·p값 인용 — 진단용입니다", "'효과가 있다' 또는 '없다'"] + return do, dont + + +def _usage(e, a: dict) -> str: + v = a["verdict"] + descriptive = a.get("execution_kind") == "descriptive_only" + do, dont = usage_rules(a) cite = ( f"{a['title']} — 판정: {DESCRIPTIVE_LABEL if descriptive else VERDICT.get(v, (v,))[0]}. 출처: 정책 효과 분석 플랫폼" f"(가짜연구소 인과추론팀 오픈소스), {a['finished'] or '날짜 미상'} 실행, {SITE}/{a['page']} · 공식 평가 아님" @@ -739,7 +801,7 @@ def _descriptive_page(e, a: dict, topics_by_id: dict) -> str:

{e(a["title"])}

{e(a["question"])}

{DESCRIPTIVE_LABEL} -

연도별 관측값을 정리했습니다. 인과효과 추정은 실행하지 않아 정책 효과를 판단할 수 없습니다.

{author}
+

연도별 관측값을 정리했습니다. 인과효과 추정은 실행하지 않아 정책 효과를 판단할 수 없습니다.

{takeaway_html(e, a)}{author} {_usage(e, a)}

관측 통계

{changed}
{figs}

연도별 관측값

{header}{rows}
@@ -757,6 +819,99 @@ def _descriptive_page(e, a: dict, topics_by_id: dict) -> str: """ +CLAIM_RATINGS = {"결과와 맞음": 4, "범위 안": 3, "결과를 넘어섬": 2, "결과와 다름": 1} + + +def jsonld(a: dict) -> str: + """검색엔진용 구조화 데이터. 결과 표(CSV)는 Dataset 으로, 사람이 적은 claims 가 있을 때만 ClaimReview. + + ClaimReview 는 '누군가 실제로 한 주장'을 검토했을 때만 쓴다(질문을 주장처럼 꾸미지 않는다). + """ + org = { + "@type": "Organization", + "name": "가짜연구소 인과추론팀 (정책 효과 분석 플랫폼)", + "url": SITE, + } + lab = ( + DESCRIPTIVE_LABEL + if a.get("execution_kind") == "descriptive_only" + else VERDICT.get(a["verdict"], (a["verdict"] or "-",))[0] + ) + csv_name = ( + f"{a['case']}-descriptive.csv" + if a.get("execution_kind") == "descriptive_only" + else f"{a['case']}.csv" + ) + items = [ + { + "@context": "https://schema.org", + "@type": "Dataset", + "name": a["title"], + "description": f"{a['question'] or a['title']} — 판정: {lab}. 공공데이터로 정책을 받은 곳과 안 받은 곳을 비교한 결과표. 공식 평가가 아닙니다.", + "url": f"{SITE}/{a['page']}", + "creator": org, + "isAccessibleForFree": True, + "inLanguage": "ko", + "keywords": ["정책 효과", "공공데이터", "인과추론", lab], + "variableMeasured": [r["name"] for r in a["results"]][:6] or None, + "dateModified": a["finished"] or None, + "distribution": [ + { + "@type": "DataDownload", + "encodingFormat": "text/csv", + "contentUrl": f"{SITE}/answers/{csv_name}", + } + ], + } + ] + for c in a.get("claims") or []: + rating = c.get("rating") + if rating not in CLAIM_RATINGS: + continue + items.append( + { + "@context": "https://schema.org", + "@type": "ClaimReview", + "url": f"{SITE}/{a['page']}", + "claimReviewed": c["text"], + "author": org, + "datePublished": a["finished"] or None, + "itemReviewed": { + "@type": "Claim", + "author": {"@type": "Organization", "name": c.get("by", "")}, + "datePublished": c.get("date"), + "appearance": {"@type": "CreativeWork", "url": c.get("url")} + if c.get("url") + else None, + }, + "reviewRating": { + "@type": "Rating", + "ratingValue": CLAIM_RATINGS[rating], + "bestRating": 4, + "worstRating": 1, + "alternateName": rating, + }, + } + ) + + def clean(x): + if isinstance(x, dict): + return {k: clean(v) for k, v in x.items() if v not in (None, "", [])} + if isinstance(x, list): + return [clean(v) for v in x] + return x + + body = json.dumps(clean(items if len(items) > 1 else items[0]), ensure_ascii=False) + return '" + + +def takeaway_html(e, a: dict) -> str: + t = takeaway(a) + if not t: + return "" + return f'
{e(t["head"])}

{e(t["text"])}

' + + def page_body(e, a: dict, topics_by_id: dict, datasets_by_url: dict) -> str: if a.get("execution_kind") == "descriptive_only": return _descriptive_page(e, a, topics_by_id) @@ -831,6 +986,7 @@ def page_body(e, a: dict, topics_by_id: dict, datasets_by_url: dict) -> str:
{e(lab)}

{e(VERDICT_PLAIN.get(a["verdict"], ""))}

+{takeaway_html(e, a)} {author}
파이프라인 자동 요약 보기

{e(auto_summary(a))}

{_usage(e, a)} diff --git a/site/build.py b/site/build.py index 37cf7d8..0d86264 100644 --- a/site/build.py +++ b/site/build.py @@ -122,6 +122,7 @@ def page( desc: str | None = None, path: str | None = None, image: str | None = None, + head: str = "", ) -> str: """공통 틀. path(사이트 안 경로)를 주면 공유 미리보기(Open Graph)용 주소·그림을 붙인다.""" up = "../" * depth @@ -149,7 +150,7 @@ def page( {e(title)} {og} - +{head} @@ -1158,6 +1159,7 @@ def main() -> None: desc=ans.share_text(a), path=a["page"], image=f"cases/{a['case']}/{fig}" if fig else None, + head=ans.jsonld(a), ), encoding="utf-8", ) diff --git a/site/impact.py b/site/impact.py index d76b437..864dc1e 100644 --- a/site/impact.py +++ b/site/impact.py @@ -30,6 +30,7 @@ "search": "결과 검색", "home-search": "홈 검색창 사용", "search-propose": "검색 후 분석 요청", + "claim-check": "뉴스 문장 검증", "reproduce": "재현 기록 열기", "flow-stage": "홈 흐름 띠의 단계 누름", } diff --git a/site/quality.py b/site/quality.py index 3c1f541..d0beb23 100644 --- a/site/quality.py +++ b/site/quality.py @@ -8,6 +8,7 @@ 얕은 clone(Actions 기본)이면 기록이 없으므로 None (화면에서 빠진다). 2. 교차 재현: catalog/projects.yaml 의 reproduced_by (다른 참여자가 make flow 로 같은 판정을 얻었음). 3. 작성자 해석: discussion.md 에 '결과를 한 문장으로'가 있는가. +5. 검토: catalog/projects.yaml 의 reviewed_by (작성자 외의 사람이 검토 체크리스트로 확인했음). 4. 다음 할 일: 위 항목과 진행 단계로 참여자에게 보여 줄 할 일 목록. """ @@ -103,6 +104,24 @@ def checks(a: dict) -> list[tuple[str, str, str]]: out.append( ("info", "사전 등록 · 기록 확인 안 됨", "이 빌드에서는 git 기록을 읽지 못했습니다.") ) + rev = a.get("reviewed_by") or [] + if rev: + who = ", ".join(f"@{x}" for x in rev) + out.append( + ( + "go", + "검토 · 통과", + f"{who} 이(가) 검토 체크리스트(docs/ops/review-checklist.md)로 확인했습니다.", + ) + ) + else: + out.append( + ( + "warn", + "검토 · 아직 없음", + "작성자 외의 사람이 검토 체크리스트로 확인하지 않았습니다.", + ) + ) rep = a.get("reproduced_by") or [] if rep: who = ", ".join(f"@{x}" for x in rep) @@ -150,6 +169,8 @@ def next_steps(p: dict, a: dict | None, registered: bool) -> list[str]: if a is not None: if st[3] and not a.get("has_one_line"): todo.append("discussion.md 에 '## 결과를 한 문장으로' 추가") + if not a.get("reviewed_by"): + todo.append("검토 요청 (docs/ops/review-checklist.md)") if not a.get("reproduced_by"): todo.append("다른 참여자에게 교차 재현 요청") pr = a.get("prereg") diff --git a/site/search.js b/site/search.js index cd97e08..d8792f8 100644 --- a/site/search.js +++ b/site/search.js @@ -59,6 +59,60 @@ (xs.length > 8 ? `
${xs.length - 8}개 더 보기
${xs.slice(8).map(draw).join("")}
` : "") + `
`; } + // ─── 문장 검증: 뉴스 문장이 결과가 말할 수 있는 범위를 넘는지 (키워드 규칙) ─────────── + const NULL_RE = /효과\s*(가|는|도)?\s*없|변화\s*(가|는|도)?\s*없|아무\s*변화|그대로였|실패|소용\s*없|안\s*먹혔|못\s*했|못했|헛수고/; + const UP_RE = /늘었|늘어|증가|올랐|오르|상승|개선|좋아|활성|살아났|많아/; + const DOWN_RE = /줄었|줄어|감소|떨어|내렸|하락|잡혔|잡았|억제|낮아|안정|적어/; + const EFFECT_RE = /효과|덕분|때문|성공|먹혔|통했|영향/; + const PCT_RE = /([+-]?\d+(?:\.\d+)?)\s*%/; + function looksLikeClaim(q) { + const t = q.trim(); + return t.length >= 12 && /\s/.test(t) && (NULL_RE.test(t) || UP_RE.test(t) || DOWN_RE.test(t) || EFFECT_RE.test(t) || PCT_RE.test(t)); + } + const RANK = { ok: 0, inside: 1, beyond: 2, conflict: 3 }; + const MARK = { ok: ["뒷받침", "go"], inside: ["범위 안", "info"], beyond: ["결과를 넘어섬", "warn"], conflict: ["결과와 다름", "stop"] }; + function checkClaim(q, r) { + const parts = [], v = r.v, pr = r.pr; + const isNull = NULL_RE.test(q), up = UP_RE.test(q), down = DOWN_RE.test(q) && !up, dir = up ? 1 : down ? -1 : 0; + const effect = !isNull && (dir !== 0 || EFFECT_RE.test(q)); + if (isNull) { + if (v === "identified") parts.push(["conflict", "'효과가 없다'고 했지만, 이 분석은 효과 근거가 있다고 판정했어요."]); + else if (v === "conditional") parts.push(["beyond", "판별하지 못한 것과 효과가 없는 것은 달라요. 이 자료로는 있다·없다 모두 단정할 수 없어요."]); + else parts.push(["beyond", "이 분석은 효과를 판단하지 않았어요(판단 불가·관측 통계). '없다'고 말할 근거도 없어요."]); + } else if (effect) { + if (v === "identified" && pr) { + const sign = Math.sign(pr.est); + if (dir && dir !== sign) parts.push(["conflict", `방향이 반대예요. 분석의 추정치는 ${pr.est > 0 ? "증가" : "감소"} 쪽이에요.`]); + else parts.push(["ok", "효과가 있었다는 말은 이 분석의 판정과 맞아요. 같은 지역·기간·지표에 한정해서 쓰세요."]); + } else if (v === "conditional") parts.push(["beyond", "효과가 '있었다'고 말할 근거는 부족해요. 이 자료로는 효과가 있었는지 판별하지 못했어요."]); + else if (v === "descriptive") parts.push(["beyond", "관측값의 변화는 인용할 수 있지만, 정책 '때문'이라고 할 근거는 없어요(효과 미추정)."]); + else parts.push(["beyond", "이 설계로는 효과를 판단할 수 없었어요. 원인이라고 말할 근거가 없어요."]); + } + const m = q.match(PCT_RE); + if (m) { + let n = parseFloat(m[1]); + if (!/^[+-]/.test(m[1]) && down) n = -n; + if (!pr || pr.unit !== "%") parts.push(["beyond", v === "not_identified" ? "판단 불가 결과의 숫자는 진단용이라 비교하지 않아요." : "이 분석의 주 지표는 %로 비교할 수 없어요."]); + else if (n < pr.lo || n > pr.hi) parts.push(["conflict", `${n > 0 ? "+" : ""}${n}%는 이 자료의 95% 범위(${pr.lo.toFixed(1)}% ~ ${pr.hi.toFixed(1)}%) 밖이라 자료와 맞지 않아요.`]); + else parts.push(["inside", `${n > 0 ? "+" : ""}${n}%는 95% 범위(${pr.lo.toFixed(1)}% ~ ${pr.hi.toFixed(1)}%) 안이에요. ` + (v === "identified" ? "자료와 맞는 크기예요." : "자료와 어긋나지는 않지만, 그 크기로 판별된 것은 아니에요.")]); + } + if (!parts.length) parts.push(["inside", "문장에서 효과·방향·크기 주장을 찾지 못했어요. 아래 결과에서 직접 확인해 보세요."]); + const worst = parts.reduce((a, b) => (RANK[b[0]] > RANK[a[0]] ? b : a))[0]; + return { worst, parts }; + } + function renderClaim(q, results) { + const box = $("#claim"); + if (!looksLikeClaim(q) || !results.length) { box.hidden = true; return; } + const r = results[0], c = checkClaim(q, r), [lab, cls] = MARK[c.worst]; + box.className = "c-panel c-" + cls; + box.innerHTML = `
이 문장, 분석 결과로 뒷받침되나요?${lab}
` + + `
${esc(q)}
` + + `` + + (r.rules && r.rules[0] && r.rules[0][0] ? `
이렇게 쓰면 결과 안에서 말할 수 있어요

${esc(r.rules[0][0])}

` : "") + + `

비교한 분석: ${esc(r.title)}. 키워드 규칙으로 읽은 결과라, 문장의 지역·기간·지표가 이 분석과 같은지는 직접 확인하세요. 법률 자문이나 공식 팩트체크가 아니에요.

`; + box.hidden = false; + if (window.track) window.track("claim-check"); + } function counts(hits) { document.querySelectorAll(".sf").forEach((b) => { const n = b.dataset.t ? hits.filter((it) => it.t === b.dataset.t).length : hits.length; @@ -69,20 +123,23 @@ function render(q) { const qn = norm(q), tks = tokens(q); idle.hidden = !!qn; - if (!qn) { res.innerHTML = ""; none.hidden = true; verdict.hidden = true; counts([]); return 0; } + if (!qn) { res.innerHTML = ""; none.hidden = true; verdict.hidden = true; $("#claim").hidden = true; counts([]); return 0; } const hits = items.map((it) => [it, score(it, tks, qn)]).filter(([, s]) => s > 0).sort((a, b) => b[1] - a[1]).map(([it]) => it); counts(hits); const shown = kind ? hits.filter((it) => it.t === kind) : hits; res.innerHTML = ORDER.map((t) => [t, shown.filter((it) => it.t === t)]).filter(([, xs]) => xs.length).map(([t, xs]) => group(t, xs)).join(""); const results = hits.filter((it) => it.t === "result"); + renderClaim(q, results); const propose = `${REPO}/issues/new?template=case-proposal.yml&title=${encodeURIComponent("[작업] " + q.trim().slice(0, 60))}`; $("#snone-propose").href = propose; if (results.length) { const top = results[0]; verdict.className = "v-panel v-" + top.cls; - verdict.innerHTML = `
가장 가까운 분석의 판정${esc(top.badge)}
` + + verdict.innerHTML = `
가장 가까운 분석의 판정${esc(top.badge)}` + + (top.rev ? `검토됨` : `검토 전`) + `
` + `

${esc(top.title)}

${esc(top.sub)}

` + `
${top.g || ""}
` + + (top.ro ? `
${esc(top.ro.head)}

${esc(top.ro.text)}

` : "") + `
인용해도 되는 문장숫자가 나온 길` + `직접 돌려 보기` + (results.length > 1 ? `비슷한 분석 ${results.length - 1}개 더` : "") + `
` + diff --git a/site/search.py b/site/search.py index a2d656a..9c0d6a1 100644 --- a/site/search.py +++ b/site/search.py @@ -38,7 +38,15 @@ def index(topics, issues, datasets, answers, projects, lineages) -> list[dict]: """검색 항목 목록. kw 는 찾는 데만 쓰는 글(화면에 안 보임).""" from html import escape - from answers import DESCRIPTIVE_LABEL, VERDICT, card_line, range_glyph + from answers import ( + DESCRIPTIVE_LABEL, + VERDICT, + card_line, + primary_range, + range_glyph, + takeaway, + usage_rules, + ) from core.discovery.links import dataset_users, is_auto @@ -60,6 +68,12 @@ def index(topics, issues, datasets, answers, projects, lineages) -> list[dict]: "cls": cls, "who": "멘토 예시" if a["mentor"] else f"@{a['owner']}", "g": range_glyph(escape, a), + # 판정 패널 · 문장 검증용 + "v": "descriptive" if desc else a["verdict"], + "ro": takeaway(a), + "pr": None if desc or a["verdict"] == "not_identified" else primary_range(a), + "rules": usage_rules(a), + "rev": bool(a.get("reviewed_by")), "kw": _j(a["question"], tname.get(a["topic"]), a["owner"], a["case"]), } ) @@ -150,6 +164,7 @@ def write(out_dir, items: list[dict]) -> None: ) +CLAIM_EXAMPLE = "토지거래허가구역 지정 뒤 옆 동네 집값이 20% 넘게 올랐다" EXAMPLES = [ ("토허제 풍선효과", "토허제 뒤 옆 동네 집값은?"), ("기후동행카드", "기후동행카드로 지하철 더 탔나?"), @@ -179,10 +194,13 @@ def body(e, n_items: int, n_results: int) -> str: -
{chips}
+
{chips}
+

뉴스 문장을 통째로 붙여 넣어도 돼요. 그 문장이 분석 결과로 뒷받침되는지 봐 드려요. +예: "{e(CLAIM_EXAMPLE)}"

{filters}
+
-

지금 찾을 수 있는 것: 분석 결과 {n_results}개를 포함해 이슈·법령·계보·공공데이터 {n_items}개.

+

지금 찾을 수 있는 것: 분석 결과 {n_results}개를 포함해 이슈·법령·계보·공공데이터 {n_items}개.

{hot_html(e, hot or [])}

검색은 이 브라우저 안에서만 합니다. 이용 통계가 켜진 경우에만 숫자·이메일·주소를 지운 30자 이내 검색어의 횟수를 쿠키 없이 셉니다(GoatCounter, '추적 안 함'을 따름). 결과가 없던 검색어는 성과에 공개되어 다음 분석 주제의 후보가 됩니다.

diff --git a/site/style.css b/site/style.css index 1b8a443..9705137 100644 --- a/site/style.css +++ b/site/style.css @@ -519,7 +519,7 @@ html.js:not(.calm) .lin-svg .edges path { transition: stroke-dashoffset 1.2s eas .show .who .avatar { width: 22px; height: 22px } .show-meta { margin-top: auto; display: flex; gap: 8px; align-items: center; flex-wrap: wrap } .crew { margin-top: 18px; display: flex; align-items: center; gap: 14px; flex-wrap: wrap } -.faces { display: flex } +.faces { display: flex; flex-wrap: wrap; row-gap: 6px; max-width: 100% } .faces a { margin-left: -8px } .faces a:first-child { margin-left: 0 } .faces img { width: 40px; height: 40px; border-radius: 50%; border: 3px solid var(--paper); background: var(--sunk); display: block } .faces a:hover img { transform: translateY(-3px) } @@ -679,3 +679,37 @@ details.ask > summary span { font-weight: 400; font-size: 14px; color: var(--mut .vb-side { flex-direction: row; flex-wrap: wrap; align-items: center; gap: 6px 10px } .vb-glyph { max-width: 240px } } + +/* 주제별: 결과를 한 축에 */ +.forest-wrap { background: var(--surface); border: 1px solid var(--hair); border-radius: 16px; padding: 18px 20px; margin: 0 0 16px } +.forest-wrap h3 { margin: 0 0 4px } +.forest { width: 100%; height: auto; display: block; margin-top: 8px; overflow: visible } +.forest .tick { stroke: var(--hair); stroke-width: 1 } +.forest .tl { fill: var(--muted); font-size: 11px; text-anchor: middle } +.forest .zero { stroke: var(--ink); stroke-width: 1.5 } +.forest .fn { fill: var(--ink); font-size: 13px } +.forest .band { stroke-width: 7; stroke-linecap: round; stroke: var(--warn); opacity: .45 } +.forest .est { fill: var(--warn); stroke: var(--surface); stroke-width: 2 } +.forest .f-go .band { stroke: var(--go) } .forest .f-go .est { fill: var(--go) } +.forest a:hover .fn { fill: var(--accent); text-decoration: underline } + +/* 가설·데이터 점검 */ +.fz { --fz: var(--accent); background: var(--surface); border: 1px solid var(--hair); border-left: 6px solid var(--fz); border-radius: 18px; padding: 20px 24px; margin: 18px 0 8px } +.fz.go { --fz: var(--go) } .fz.warn { --fz: var(--warn) } .fz.stop { --fz: var(--stop) } +.fz-head > div { display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap } +.fz-stamp { font-size: clamp(20px, 2.8vw, 26px); font-weight: 800; letter-spacing: -.03em; color: var(--fz) } +.fz-hyp { margin: 8px 0 12px; color: var(--ink2) } +.fz-list { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr)); gap: 10px 22px } +.fz-list li { display: grid; grid-template-columns: 24px minmax(0, 1fr); gap: 10px; align-items: start } +.fz-list li > span:last-child { display: flex; flex-direction: column; gap: 2px } +.fz-mark { width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-size: 12px; font-weight: 800; color: #fff; background: var(--go) } +.fz-warn .fz-mark { background: var(--warn) } .fz-miss .fz-mark { background: var(--stop) } +.fz-graph { margin: 14px 0 0; padding-top: 12px; border-top: 1px solid var(--hair) } +.v-feas { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--hair) } +.v-feas .v-label { margin: 0 } +.v-feas-stamp { font-size: 22px; font-weight: 800; letter-spacing: -.03em; margin: 2px 0 4px } +.v-feas-stamp.c-go { color: var(--go) } .v-feas-stamp.c-warn { color: var(--warn) } .v-feas-stamp.c-stop { color: var(--stop) } +.v-checks { list-style: none; padding: 0; margin: 8px 0 0; display: flex; flex-direction: column; gap: 6px; font-size: 14.5px } +.hot-h { font-size: 16px; margin: 22px 0 8px } +.hot { margin: 0; padding-left: 22px; display: flex; flex-direction: column; gap: 6px } +.hot li a { margin-right: 10px } diff --git a/tests/test_causal.py b/tests/test_causal.py new file mode 100644 index 0000000..17d117b --- /dev/null +++ b/tests/test_causal.py @@ -0,0 +1,124 @@ +"""PyWhy(DoWhy)·CausalML 연계와 가설·데이터 점검. + +feasibility·draft·unit_changes 는 추가 설치 없이, DoWhy·CausalML 단계는 설치돼 있을 때만 돈다(CI 의 causal 작업). +""" + +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +import yaml + +from core.causal.draft import draft +from core.causal.feasibility import space_level, time_level, topic_feasibility +from core.causal.pywhy import check_case, unit_changes +from core.discovery.catalog import load_topics +from core.discovery.ontology import load_datasets, load_issues +from core.schema.plan import Plan, load_plan + +ROOT = Path(__file__).resolve().parents[1] +EX = ROOT / "cases" / "_example_night_clinic" + + +def test_unit_levels(): + assert ( + space_level("시군구(법정동)") == 3 + and space_level("지점(역)") == 4 + and space_level("확인필요") is None + ) + assert time_level("월") == 2 and time_level("실시간") == 5 and time_level("수시") is None + + +def test_feasibility_for_every_topic_has_six_checks_and_graph(): + ds, iss = load_datasets(), load_issues() + for t in load_topics(): + f = topic_feasibility(t, ds, iss) + assert [c["key"] for c in f["checks"]] == [ + "when", + "who", + "what", + "confounders", + "space", + "time", + ] + assert f["verdict"] in {"go", "warn", "stop"} and f["label"] + assert ["정책", "결과"] in f["graph"]["edges"] + assert f["hypothesis"]["sentence"] + + +def test_draft_is_schema_valid_and_uses_official_date(): + r = draft("서울 토허제 전역 확대 뒤 집값이 잡혔나", "gildong-ltp") + assert r["matched"] and r["issue"] == "seoul-ltp-1015-2025" + plan = Plan.model_validate(yaml.safe_load(r["plan_yaml"])) + assert plan.treatment.treat_time == "2025-10" # issues.yaml 의 공식 시행일 2025-10-20 + assert r["todo"] > 0 # 사람이 채울 칸은 남긴다 + assert draft("반려동물 등록제 효과")["matched"] is False + + +def test_unit_changes_equals_two_by_two_did(): + plan = load_plan(EX / "plan.yaml") + df = pd.read_csv(EX / "data" / "panel.csv") + f = unit_changes(plan, df) + y = plan.primary_outcome.col + post = df[plan.time.col] >= plan.treatment.treat_time + m = df.groupby([plan.treatment.group_col, post])[y].mean() + did = (m[1, True] - m[1, False]) - (m[0, True] - m[0, False]) + est = f.loc[f["T"] == 1, "dy"].mean() - f.loc[f["T"] == 0, "dy"].mean() + assert np.isclose(est, did, atol=1e-9) + assert set(f.columns) >= {"T", "dy", "y_pre"} and f["T"].sum() == 30 + + +def test_check_case_without_data_says_so(tmp_path): + case = tmp_path / "c" + case.mkdir() + (case / "plan.yaml").write_text( + (EX / "plan.yaml").read_text(encoding="utf-8"), encoding="utf-8" + ) + assert check_case(case)["status"] == "no_data" + + +def test_dowhy_and_causalml_recover_the_synthetic_effect(): + pytest.importorskip("dowhy") + pytest.importorskip("causalml") + r = check_case(EX) + assert r["status"] == "ok" and r["same_direction_as_baseline"] is True + dw, ml = r["dowhy"], r["causalml"] + assert dw["status"] == "ok" and abs(dw["estimate"] - (-5.0)) < 0.6 # 합성 데이터의 참효과 -5.0 + assert {x["status"] for x in dw["refutations"]} == {"pass"} + assert "y_pre" in dw["identification"]["adjust_for"] + assert ml["status"] == "ok" and abs(ml["ate"] - (-5.0)) < 0.6 and len(ml["by_baseline"]) == 3 + + +def test_causalml_skips_with_few_treated_units(): + from core.causal.pywhy import causalml_hte + + f = pd.DataFrame({"T": [1] * 4 + [0] * 21, "dy": np.arange(25.0), "y_pre": np.arange(25.0)}) + assert causalml_hte(f, [])["status"] == "skipped" + + +def test_committed_second_opinion_renders_on_answer_page(): + import sys + from html import escape + + sys.path.insert(0, str(ROOT / "site")) + import answers as ans + + a = {x["case"]: x for x in ans.load_answers()}["t3-land-permit-2025"] + assert a["pywhy"] and a["pywhy"]["dowhy"]["status"] == "ok" + html = ans.pywhy_block(escape, a) + assert "DoWhy" in html and "CausalML" in html and "가짜 처치" in html + + +def test_news_rss_count_parses_items(): + import importlib.util + + spec = importlib.util.spec_from_file_location("rt", ROOT / "scripts" / "refresh_trends.py") + rt = importlib.util.module_from_spec(spec) + spec.loader.exec_module(rt) + xml = "ab" + assert rt.count_rss_items(xml) == 2 and rt.count_rss_items("not xml") == 0 + t = load_topics()[0] + assert "when:7d" in rt.news_query(t) and rt.news_link(t).startswith( + "https://news.google.com/search?" + ) From 56f5cf640d34853908df2e52a1db495cef570c5a Mon Sep 17 00:00:00 2001 From: Jinsoo Shin <59598545+jsshin2022@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:53:33 +0900 Subject: [PATCH 4/5] =?UTF-8?q?fix(causal):=20networkx<3.5=20=E2=80=94=20c?= =?UTF-8?q?ausalml=200.18=20=EC=9D=B4=20=EA=B3=A0=EB=A5=B4=EB=8A=94=20dowh?= =?UTF-8?q?y=200.12=20=EB=8A=94=20nx.d=5Fseparated=20=EB=A5=BC=20=EC=93=B4?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EMnmZPBD5PQJW1UQAARN7q --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index b3b57aa..f835e9f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,7 @@ dependencies = [ [project.optional-dependencies] agent = ["langgraph>=0.2", "langchain-core>=0.3"] -causal = ["dowhy>=0.12", "causalml>=0.15"] # PyWhy·CausalML 두 번째 의견: python -m core.causal +causal = ["dowhy>=0.12", "causalml>=0.15", "networkx<3.5"] # PyWhy·CausalML 두 번째 의견: python -m core.causal · networkx<3.5: causalml 0.18 이 고정하는 dowhy 0.12 가 nx.d_separated 를 씀 dev = ["pytest>=8", "ruff>=0.6", "pre-commit>=3.7"] app = ["streamlit>=1.35"] analysis = ["holidays>=0.50"] # 탐색 분석(공휴일 달력): scripts/explore_climate_card.py # 개발용 화면(선택). 공개 사이트는 site/ 의 정적 페이지 From 4dceeca1b0d9480c669fcf5b27454ac2d820e5f9 Mon Sep 17 00:00:00 2001 From: Jinsoo Shin <59598545+jsshin2022@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:23:43 +0900 Subject: [PATCH 5/5] =?UTF-8?q?feat(agent):=20=EC=9E=91=EC=97=85=20?= =?UTF-8?q?=EC=A0=9C=EC=95=88=20=E2=86=92=20=EA=B0=80=EC=84=A4=C2=B7?= =?UTF-8?q?=EB=8D=B0=EC=9D=B4=ED=84=B0=20=EC=A0=90=EA=B2=80=20=EB=8C=93?= =?UTF-8?q?=EA=B8=80=20=E2=86=92=20plan-approved=20=EB=9D=BC=EB=B2=A8?= =?UTF-8?q?=EB=A1=9C=20=EC=B4=88=EC=95=88=20PR,=20=EC=A3=BC=EC=9E=A5=20?= =?UTF-8?q?=EA=B2=80=ED=86=A0=20=EA=B8=B0=EB=A1=9D,=20=EA=B2=80=ED=86=A0?= =?UTF-8?q?=20=EC=A7=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 차별점 단계의 남은 고리를 닫는다 (사람이 승인하는 에이전트 · 실제 주장 검토 · 리뷰 문화). - .github/workflows/plan-agent.yml + core/causal/issue_agent.py 작업 제안 이슈가 열리거나 고쳐지면 가설·데이터 점검과 plan.yaml 초안을 댓글 하나로(계속 갱신), 메인테이너가 'plan-approved' 라벨을 붙이면 그 초안으로 브랜치·PR. 이슈 본문은 환경변수로만 넘기고 담당자 ID 는 GitHub ID 형식만, 질문은 한 줄로 접어 YAML 에 끼어들 수 없게 함 (tests) - draft: 주제·이슈 id 힌트는 매칭에만 쓰고 plan 의 질문에는 넣지 않음 - 주장 검토 기록: 검색 문장 검증 → '검토 기록으로 남기기' → claim-review 이슈 폼(주장·출처·날짜·케이스·자동 결과 미리 채움) → 검토자가 projects.yaml claims 에 추가하면 ClaimReview - 참여 화면 '검토 짝': 결과가 있는데 검토 전인 분석마다 다른 참여자를 돌아가며 제안 (자기 자신 배정 없음) - 문서: 분석 트랙 표, 검토 체크리스트 절차 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EMnmZPBD5PQJW1UQAARN7q --- .github/ISSUE_TEMPLATE/claim-review.yml | 59 ++++++++++++ .github/workflows/plan-agent.yml | 76 +++++++++++++++ core/causal/draft.py | 15 ++- core/causal/issue_agent.py | 120 ++++++++++++++++++++++++ docs/ops/review-checklist.md | 7 ++ docs/tracks/analysis.md | 1 + site/impact.py | 1 + site/projects.py | 28 +++++- site/search.js | 1 + tests/test_causal.py | 57 +++++++++++ tests/test_trust_claims.py | 22 +++++ 11 files changed, 383 insertions(+), 4 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/claim-review.yml create mode 100644 .github/workflows/plan-agent.yml create mode 100644 core/causal/issue_agent.py diff --git a/.github/ISSUE_TEMPLATE/claim-review.yml b/.github/ISSUE_TEMPLATE/claim-review.yml new file mode 100644 index 0000000..9f774a3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/claim-review.yml @@ -0,0 +1,59 @@ +name: 뉴스 주장 검토 기록 +description: 검색 화면의 '문장 검증' 결과를 실제 주장(기사·발표)의 검토 기록으로 남깁니다 → 답 페이지 팩트체크 마크업 +title: "[주장 검토] " +labels: ["claim-review"] +body: + - type: markdown + attributes: + value: | + 누군가 **실제로 한 주장**만 기록합니다. 검토자(작성자가 아닌 참여자)가 아래를 확인한 뒤 `catalog/projects.yaml` 의 + 그 케이스 `claims:` 에 한 줄을 추가하면 답 페이지에 schema.org ClaimReview 가 붙습니다. + 주장 문장은 원문 그대로, 짧게(한 문장) 적어 주세요. 기사 전문을 옮기지 마세요. + - type: input + id: claim + attributes: + label: 주장 문장 (원문 그대로 한 문장) + validations: + required: true + - type: input + id: by + attributes: + label: 누가 말했나 (기관·언론사·인물) + validations: + required: true + - type: input + id: url + attributes: + label: 주장이 실린 곳 (URL) + validations: + required: true + - type: input + id: date + attributes: + label: 주장 날짜 (YYYY-MM-DD) + - type: input + id: case + attributes: + label: 비교한 분석 (cases/ 폴더 이름) + validations: + required: true + - type: input + id: auto + attributes: + label: 자동 문장 검증 결과 + description: "뒷받침 · 범위 안 · 결과를 넘어섬 · 결과와 다름 — 검색 화면에서 채워집니다" + - type: dropdown + id: rating + attributes: + label: 검토자 평가 (projects.yaml claims.rating 에 그대로) + options: + - 결과와 맞음 + - 범위 안 + - 결과를 넘어섬 + - 결과와 다름 + validations: + required: true + - type: textarea + id: notes + attributes: + label: 검토 메모 — 주장과 분석의 지역·기간·지표가 같은가 diff --git a/.github/workflows/plan-agent.yml b/.github/workflows/plan-agent.yml new file mode 100644 index 0000000..f041bee --- /dev/null +++ b/.github/workflows/plan-agent.yml @@ -0,0 +1,76 @@ +name: Plan agent (작업 제안 → 가설·데이터 점검 → plan 초안 PR) + +# 작업 제안 이슈가 열리거나 고쳐지면: 가설·데이터 점검과 plan.yaml 초안을 댓글로 (하나의 댓글을 계속 고침) +# 메인테이너가 'plan-approved' 라벨을 붙이면: 그 초안으로 브랜치와 PR 을 연다 — 사람이 승인하는 관문 +# 이슈 본문은 믿지 않는 입력이라 셸에 넣지 않고 환경변수로만 파이썬에 넘긴다. +on: + issues: + types: [opened, edited, labeled] + +permissions: + contents: read + +jobs: + comment: + if: contains(github.event.issue.labels.*.name, 'case-proposal') && github.event.action != 'labeled' + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + cache-dependency-path: pyproject.toml + - run: pip install -e . + - name: Feasibility comment + env: + ISSUE_TITLE: ${{ github.event.issue.title }} + ISSUE_BODY: ${{ github.event.issue.body }} + GH_TOKEN: ${{ github.token }} + NUM: ${{ github.event.issue.number }} + run: | + python -m core.causal.issue_agent comment > comment.md + id=$(gh api "repos/$GITHUB_REPOSITORY/issues/$NUM/comments" --paginate \ + --jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(""))) | .id' | head -1) + if [ -n "$id" ]; then + gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -F body=@comment.md > /dev/null + else + gh api "repos/$GITHUB_REPOSITORY/issues/$NUM/comments" -F body=@comment.md > /dev/null + fi + + draft-pr: + if: github.event.action == 'labeled' && github.event.label.name == 'plan-approved' && contains(github.event.issue.labels.*.name, 'case-proposal') + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + issues: write + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + cache-dependency-path: pyproject.toml + - run: pip install -e . + - name: Write plan draft and open PR + env: + ISSUE_TITLE: ${{ github.event.issue.title }} + ISSUE_BODY: ${{ github.event.issue.body }} + GH_TOKEN: ${{ github.token }} + NUM: ${{ github.event.issue.number }} + run: | + branch="agent/plan-issue-$NUM" + git switch -c "$branch" + case=$(python -m core.causal.issue_agent write) + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add "cases/$case/plan.yaml" + git commit -m "plan($case): 작업 제안 #$NUM 에서 만든 plan.yaml 초안 (TODO 를 채운 뒤 머지)" + git push origin "$branch" + printf '작업 제안 #%s 에서 `python -m core.causal.draft` 로 만든 초안입니다.\n\n- [ ] 데이터를 보기 **전에** TODO 를 모두 채웠습니다\n- [ ] 처치 시점·비교 대상 근거를 확인했습니다\n\n이 PR 을 머지하는 것이 사전 등록입니다. Closes #%s 는 결과 PR 에서 씁니다.\n' "$NUM" "$NUM" > pr.md + if ! gh pr create --head "$branch" --title "plan($case): 질문에서 만든 초안 (#$NUM)" --body-file pr.md; then + gh api "repos/$GITHUB_REPOSITORY/issues/$NUM/comments" -f body="초안 브랜치 \`$branch\` 를 만들었어요. 저장소 설정에서 Actions 의 PR 생성이 꺼져 있어 PR 은 직접 열어 주세요." > /dev/null + fi diff --git a/core/causal/draft.py b/core/causal/draft.py index 3160c25..d986ae8 100644 --- a/core/causal/draft.py +++ b/core/causal/draft.py @@ -40,9 +40,18 @@ def _q(s: str) -> str: return '"' + str(s).replace("\\", "\\\\").replace('"', '\\"') + '"' -def draft(question: str, case_id: str = "gildong-topic") -> dict: +def draft(question: str, case_id: str = "gildong-topic", hint: str = "") -> dict: + """hint: 주제 id·이슈 id 처럼 매칭에만 쓰고 plan 에는 넣지 않는 글.""" + question = " ".join(str(question).split())[:300] # 한 줄로 — YAML 블록·주석을 깨지 않게 topics = load_topics() - m = match_topic(question, topics, load_catalog()) + ids = {t.id: t for t in topics} + hint_ids = [x for x in re.split(r"[\s/,]+", hint or "") if x] + hinted = next((ids[x] for x in hint_ids if x in ids), None) + m = match_topic(question + " " + (hint or ""), topics, load_catalog()) + if hinted: + from core.discovery.match import TopicMatch + + m = [TopicMatch(hinted, 99.0, ["hint"])] + [x for x in m if x.topic.id != hinted.id] if not m: return { "matched": False, @@ -53,7 +62,7 @@ def draft(question: str, case_id: str = "gildong-topic") -> dict: feas = topic_feasibility(topic, datasets, issues) my_issues = [i for i in issues if i.topic == topic.id] qn = re.sub(r"\s+", "", question) - issue = max( + issue = next((i for i in my_issues if i.id in hint_ids), None) or max( my_issues, key=lambda i: sum(w in qn for w in re.findall(r"[가-힣A-Za-z0-9]{2,}", i.name)), default=None, diff --git a/core/causal/issue_agent.py b/core/causal/issue_agent.py new file mode 100644 index 0000000..008111b --- /dev/null +++ b/core/causal/issue_agent.py @@ -0,0 +1,120 @@ +"""작업 제안 이슈 → 가설·데이터 점검 댓글 → (사람이 승인하면) plan.yaml 초안 PR. + +.github/workflows/plan-agent.yml 이 부른다. 이슈 본문은 믿지 않는 입력이라 셸에 넣지 않고 환경변수로만 받는다. + + ISSUE_NUMBER, ISSUE_TITLE, ISSUE_BODY 환경변수 + python -m core.causal.issue_agent comment → 댓글 본문(markdown)을 표준출력으로 + python -m core.causal.issue_agent write → cases/<케이스>/plan.yaml 을 쓰고 케이스 이름을 출력 + +사람의 관문: 메인테이너가 이슈에 'plan-approved' 라벨을 붙여야 PR 을 만든다. PR 을 머지하는 것이 사전 등록이다. +""" + +from __future__ import annotations + +import os +import re +import sys + +from core.discovery.catalog import ROOT + +from .draft import draft, write + +MARK = "" +SECTION = re.compile(r"^###\s+(.+?)\s*$", re.M) +OWNER = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$") + + +def parse_form(body: str) -> dict[str, str]: + """GitHub 이슈 폼 본문(### 라벨 \\n\\n 값) → {라벨: 값}.""" + out: dict[str, str] = {} + parts = SECTION.split(body or "") + for label, value in zip(parts[1::2], parts[2::2], strict=False): + v = value.strip() + out[label.strip()] = "" if v in ("_No response_", "미정") else v + return out + + +def _field(form: dict, prefix: str) -> str: + return next((v for k, v in form.items() if k.startswith(prefix)), "") + + +def case_name(form: dict, topic_id: str | None) -> str | None: + owner = _field(form, "담당자").lstrip("@").strip() + if not OWNER.match(owner): + return None + slug = topic_id or "topic" + name = re.sub(r"[^a-z0-9-]+", "-", f"{owner}-{slug}".lower()).strip("-") + return name[:60] + + +def plan_for_issue(title: str, body: str) -> dict: + form = parse_form(body) + question = _field(form, "하려는 것") or re.sub(r"^\[작업\]\s*", "", title or "") + question = " ".join(question.split())[:300] + topic_hint = _field(form, "주제") + r = draft(question, "gildong-topic", hint=topic_hint) + topic = r.get("topic") if r.get("matched") else None + case = case_name(form, topic) + if r.get("matched") and case: + r = draft(question, case, hint=topic_hint) + return {"question": question, "case": case, "topic": topic, **r} + + +def comment(title: str, body: str) -> str: + r = plan_for_issue(title, body) + if not r.get("question"): + return f"{MARK}\n질문 칸이 비어 있어 가설·데이터 점검을 하지 못했어요. '하려는 것'에 한두 문장을 적어 주세요." + if not r.get("matched"): + return ( + f"{MARK}\n### 가설·데이터 점검 (자동)\n이 질문과 맞는 주제를 카탈로그에서 찾지 못했어요. " + "새 주제라면 `catalog/topics.yaml` 에 주제를 먼저 제안해 주세요. 정책 이름·지역을 넣으면 다시 확인합니다." + ) + f = r["feasibility"] + mark = {"ok": "✅", "warn": "⚠️", "miss": "❌"} + rows = "\n".join(f"| {mark[c['status']]} | {c['label']} | {c['detail']} |" for c in f["checks"]) + case = r["case"] or "<담당자ID>-<주제>" + return f"""{MARK} +### 가설·데이터 점검 (자동) — **{f["label"]}** + +**가설** {f["hypothesis"]["sentence"]} + +| | 점검 | 근거 | +|---|---|---| +{rows} + +주제 `{r["topic"]}` · 지금 이슈 `{r.get("issue") or "없음"}` · 인과 그래프(PyWhy 방식): 정책 → 결과, 공통 원인 → 정책·결과 + +
plan.yaml 초안 (TODO {r["todo"]}곳) — cases/{case}/plan.yaml + +```yaml +{r["plan_yaml"]}``` +
+ +메인테이너가 이 이슈에 `plan-approved` 라벨을 붙이면 이 초안으로 PR 을 엽니다. 데이터를 보기 전에 TODO 를 채워 PR 을 머지하는 것이 사전 등록입니다. +숫자·날짜·데이터는 전부 카탈로그에서 왔고 LLM 은 쓰지 않았어요. (`python -m core.causal.draft`)""" + + +def write_plan(title: str, body: str) -> str: + r = plan_for_issue(title, body) + if not (r.get("matched") and r.get("case")): + raise SystemExit("주제나 담당자 ID 를 확인할 수 없어 초안을 쓰지 않았어요") + write(r["case"], r["plan_yaml"]) + return r["case"] + + +def main(argv=None) -> int: + argv = argv if argv is not None else sys.argv[1:] + title, body = os.environ.get("ISSUE_TITLE", ""), os.environ.get("ISSUE_BODY", "") + if argv[:1] == ["comment"]: + print(comment(title, body)) + elif argv[:1] == ["write"]: + print(write_plan(title, body)) + else: + print(__doc__) + return 2 + return 0 + + +if __name__ == "__main__": + os.chdir(ROOT) + raise SystemExit(main()) diff --git a/docs/ops/review-checklist.md b/docs/ops/review-checklist.md index 8840e48..de313ce 100644 --- a/docs/ops/review-checklist.md +++ b/docs/ops/review-checklist.md @@ -16,8 +16,15 @@ ## 절차 +검토 짝은 사이트 [참여](https://causalinferencelab.github.io/policy-effect-analytics-agent/projects.html#review) 화면의 '검토 짝'에 자동으로 제안됩니다(결과를 낸 다른 참여자를 돌아가며). + 1. 결과 PR에서 위 표를 복사해 PR 리뷰 댓글에 ✅/❌로 채웁니다. ❌가 있으면 작성자가 고친 뒤 다시 봅니다. 2. 여덟 개가 모두 ✅면 `catalog/projects.yaml`의 그 케이스에 `reviewed_by: [내 GitHub ID]`를 더하는 커밋을 같은 PR에 올립니다. 3. 사이트가 다시 빌드되면 결과 카드·검색 판정 패널에 **검토됨**, 답 페이지 신뢰 항목에 '검토 · 통과'가 나옵니다. 작성자 본인은 자기 결과를 검토할 수 없습니다. 멘토 예시도 같은 규칙을 따릅니다. + +## 뉴스 주장 검토 기록 + +검색 화면에 뉴스 문장을 붙여 넣어 나온 판정은 '실제 기사·발표의 주장이면 검토 기록으로 남기기'로 [주장 검토 이슈](../../.github/ISSUE_TEMPLATE/claim-review.yml)가 됩니다. +검토자가 주장 원문·출처·날짜와 분석의 지역·기간·지표가 맞는지 확인한 뒤 `catalog/projects.yaml` 의 그 케이스 `claims:` 에 한 줄을 더하면, 답 페이지에 schema.org ClaimReview 가 붙습니다. diff --git a/docs/tracks/analysis.md b/docs/tracks/analysis.md index 2ddc13c..d2a4cc1 100644 --- a/docs/tracks/analysis.md +++ b/docs/tracks/analysis.md @@ -49,6 +49,7 @@ pip install -e ".[causal]" && make pywhy CASE=cases/<내ID>-<주제> # make f | 단계 | 무엇을 하나 | 어디에 보이나 | |---|---|---| | 가설·데이터 점검 (`core/causal/feasibility.py`) | 주제마다 ① 처치 시점 근거 ② 비교 대상 ③ 결과 데이터 ④ 공통 원인(통제) 데이터 ⑤ 공간 ⑥ 시간 단위를 카탈로그로 확인. PyWhy 식 인과 그래프(정책 → 결과, 공통 원인 → 둘 다) | 이슈 보드 맨 위, 검색에서 결과가 없을 때 | +| 작업 제안 → 초안 PR (`.github/workflows/plan-agent.yml`) | 작업 제안 이슈가 열리면 가설·데이터 점검과 plan.yaml 초안을 **댓글**로 달고, 메인테이너가 `plan-approved` 라벨을 붙이면 그 초안으로 **PR**을 연다. 사람이 TODO 를 채워 머지하는 것이 사전 등록 | 이슈 댓글, PR | | plan.yaml 초안 (`core/causal/draft.py`) | 질문 → 주제·이슈 매칭 → 스키마를 통과하는 초안. 시행일은 `issues.yaml`의 공식 날짜만, 모르는 칸은 `TODO` | 터미널, `cases/` | | DoWhy (`core/causal/pywhy.py`) | 단위별 정책 전후 변화(Δy) 표 → 뒷문 기준 식별(정책 전 수준·공변량 보정) → 추정 → 반박 검정 3종(가짜 처치 · 무작위 공통 원인 · 80% 부분 표본) | 답 페이지 '두 번째 의견' | | CausalML | T-러너로 단위별 효과(CATE), 정책 전 수준 셋으로 나눠 평균. 처치·비교가 각각 10곳 이상일 때만 | 답 페이지 '두 번째 의견' | diff --git a/site/impact.py b/site/impact.py index 864dc1e..7c2892a 100644 --- a/site/impact.py +++ b/site/impact.py @@ -31,6 +31,7 @@ "home-search": "홈 검색창 사용", "search-propose": "검색 후 분석 요청", "claim-check": "뉴스 문장 검증", + "claim-record": "문장 검증을 검토 기록으로 남기기", "reproduce": "재현 기록 열기", "flow-stage": "홈 흐름 띠의 단계 누름", } diff --git a/site/projects.py b/site/projects.py index 490c012..6c9a102 100644 --- a/site/projects.py +++ b/site/projects.py @@ -264,6 +264,31 @@ def lineage_list(e, lineages, topics_by_id) -> str: return "".join(items) +def review_pairs(e, mentee: list[dict]) -> str: + """검토 짝 제안: 결과가 있는데 아직 검토받지 않은 분석마다, 결과가 있는 다른 참여자 한 명을 돌아가며 붙인다.""" + reg = load_registry() + done = [p for p in mentee if p.get("has_flow")] + owners = sorted({p["owner"] for p in done}) + if len(owners) < 2: + return "" + rows = [] + for i, p in enumerate(sorted(done, key=lambda x: x["case"])): + if reg.get(p["case"], {}).get("reviewed_by"): + continue + others = [o for o in owners if o != p["owner"]] + who = others[i % len(others)] + rows.append( + f"{e(p['title'])}
@{e(p['owner'])}
" + f"@{e(who)}" + ) + if not rows: + return "" + return f"""

검토 짝

+

결과가 있는데 아직 검토받지 않은 분석 {len(rows)}개입니다. 짝은 결과를 낸 다른 참여자 중에서 돌아가며 정했어요(바꿔도 됩니다). +검토 체크리스트 여덟 항목을 확인하면 catalog/projects.yaml에 reviewed_by를 더해 '검토됨' 배지를 붙입니다.

+
{"".join(rows)}
분석제안 검토자
""" + + def projects_body(e, projects, lineages, topics) -> str: tb = {t.id: t for t in topics} act = load_activity() @@ -307,6 +332,7 @@ def projects_body(e, projects, lineages, topics) -> str:
{cards or "

아직 없습니다.

"}
+{review_pairs(e, mentee)}

데이터 계보 (트랙 A)

이슈 → 정책 → 데이터 → 가공 → 지표의 길입니다. 빈칸은 아직 없는 데이터, 채울 곳입니다.

{lin_cards or "

아직 없습니다.

"}
@@ -402,7 +428,7 @@ def showcase(e, projects, answers, topics, crew: list[str], limit: int = 6) -> s tb = {t.id: t for t in topics} real = [a for a in answers if not a["mentor"] and not a["synthetic"]] - real.sort(key=lambda a: (a.get("finished") or ""), reverse=True) + real.sort(key=lambda a: a.get("finished") or "", reverse=True) rows = [] for a in real[:limit]: t = tb.get(a["topic"]) diff --git a/site/search.js b/site/search.js index b5dfbb8..d610002 100644 --- a/site/search.js +++ b/site/search.js @@ -109,6 +109,7 @@ `
${esc(q)}
` + `
    ${c.parts.map(([k, t]) => `
  • ${MARK[k][0]}${esc(t)}
  • `).join("")}
` + (r.rules && r.rules[0] && r.rules[0][0] ? `
이렇게 쓰면 결과 안에서 말할 수 있어요

${esc(r.rules[0][0])}

` : "") + + `

실제 기사·발표의 주장이면 검토 기록으로 남기기

` + `

비교한 분석: ${esc(r.title)}. 키워드 규칙으로 읽은 결과라, 문장의 지역·기간·지표가 이 분석과 같은지는 직접 확인하세요. 법률 자문이나 공식 팩트체크가 아니에요.

`; box.hidden = false; if (window.track) window.track("claim-check"); diff --git a/tests/test_causal.py b/tests/test_causal.py index 17d117b..ddca4ab 100644 --- a/tests/test_causal.py +++ b/tests/test_causal.py @@ -122,3 +122,60 @@ def test_news_rss_count_parses_items(): assert "when:7d" in rt.news_query(t) and rt.news_link(t).startswith( "https://news.google.com/search?" ) + + +ISSUE_BODY = """### 담당자 GitHub ID + +gildong + +### 주제 · 이슈 + +housing-regulation / seoul-ltp-gangnam-2025 + +### 하려는 것 (한두 문장) + +강남3구 재지정 뒤 +가격 급등이 멈췄나 +""" + + +def test_issue_agent_comment_and_plan(): + from core.causal.issue_agent import MARK, comment, parse_form, plan_for_issue + + form = parse_form(ISSUE_BODY) + assert form["담당자 GitHub ID"] == "gildong" + r = plan_for_issue("[작업] x", ISSUE_BODY) + assert r["case"] == "gildong-housing-regulation" and r["issue"] == "seoul-ltp-gangnam-2025" + plan = Plan.model_validate(yaml.safe_load(r["plan_yaml"])) + assert ( + plan.question.strip() == "강남3구 재지정 뒤 가격 급등이 멈췄나" + ) # 힌트는 plan 에 들어가지 않는다 + assert plan.treatment.treat_time == "2025-03" + c = comment("[작업] x", ISSUE_BODY) + assert c.startswith(MARK) and "plan-approved" in c and "```yaml" in c + + +def test_issue_agent_rejects_unsafe_owner_and_multiline_injection(): + from core.causal.issue_agent import plan_for_issue + + bad = plan_for_issue( + "[작업] x", "### 담당자 GitHub ID\n\n$(rm -rf /)\n\n### 하려는 것 (한두 문장)\n\n토허제\n" + ) + assert bad["case"] is None + inj = plan_for_issue( + "[작업] x", + "### 담당자 GitHub ID\n\ngildong\n\n### 하려는 것 (한두 문장)\n\n토허제 효과\nsynthetic_data: true\ncase_id: evil\n", + ) + d = yaml.safe_load(inj["plan_yaml"]) + assert d["case_id"] == "gildong-housing-regulation" and d["synthetic_data"] is False + + +def test_plan_agent_workflow_keeps_issue_text_out_of_shell(): + wf = (ROOT / ".github" / "workflows" / "plan-agent.yml").read_text(encoding="utf-8") + assert "plan-approved" in wf and "ISSUE_BODY: ${{ github.event.issue.body }}" in wf + run_lines = [ + ln + for ln in wf.splitlines() + if "github.event.issue.body" in ln or "github.event.issue.title" in ln + ] + assert all(ln.strip().startswith(("ISSUE_BODY:", "ISSUE_TITLE:")) for ln in run_lines) diff --git a/tests/test_trust_claims.py b/tests/test_trust_claims.py index 96cab7d..46abc8f 100644 --- a/tests/test_trust_claims.py +++ b/tests/test_trust_claims.py @@ -96,3 +96,25 @@ def test_search_index_carries_claim_check_fields(tmp_path): assert all({"v", "ro", "pr", "rules", "rev"} <= i.keys() for i in res) js = (ROOT / "site" / "search.js").read_text(encoding="utf-8") assert "checkClaim" in js and "결과와 다름" in js and "공식 팩트체크가 아니에요" in js + + +def test_claim_record_link_and_template(): + js = (ROOT / "site" / "search.js").read_text(encoding="utf-8") + assert "template=claim-review.yml" in js and "&claim=" in js and "&case=" in js + tpl = (ROOT / ".github" / "ISSUE_TEMPLATE" / "claim-review.yml").read_text(encoding="utf-8") + for fid in ("id: claim", "id: url", "id: case", "id: auto", "id: rating"): + assert fid in tpl + for rating in ans.CLAIM_RATINGS: + assert rating in tpl + + +def test_review_pairs_never_assign_self(): + import projects as proj + + mentee = [p for p in proj.load_projects() if not p["mentor"]] + html = proj.review_pairs(escape, mentee) + assert 'id="review"' in html + for row in re.findall(r"(.*?)", html): + owner = re.search(r"
@([^<]+)
", row).group(1) + reviewer = re.search(r"github.com/([^']+)'", row).group(1) + assert owner != reviewer