#!/usr/bin/env python3
"""规则自检:给每条规则造一个**必然触发**的最小样本,跑一遍看谁不响。

规则在自己的正样本上都不报 = 哑弹(要么正则写错,要么代码路径根本到不了,
要么扫描的目录/文件类型压根不对)。这类"永远返回 0"的检查比没有检查更危险,
因为它看起来像通过了。

    python3 selftest.py            # 建夹具、跑全 13 组、报哑弹
"""
from __future__ import annotations

import json
import re
import subprocess
import sys
import tempfile
from pathlib import Path

# 夹具落在本机临时目录下,不写死某台机器的 scratchpad——拷到别人机器上要能直接跑。
ROOT = Path(tempfile.gettempdir()) / "changwei-code-check-selftest" / "selftest_repo"
OP = "image/grid_unnormal"          # 算子名与假 canndev(build_canndev) 对齐,好让 G5/G7 能建基线
OP2 = "activation/celu"             # 第二个算子:覆盖与 OP 互斥的规则
OP4 = "activation/hard_shrink"      # 专给 G9-aclnn-doc-missing:有 op_api、无 docs/aclnn*.md
OP5 = "index/scatter_min"           # 专给 G16-noncontiguous-doc-no-autocontiguous:文档非连续√、def 无 AutoContiguous、无 op_api
OP3 = "array/non_zero_with_value"   # 第三个算子:假 canndev 里 A2 校验常量 {2},本仓只拦 4 → G18-partial

# 需要额外条件、不在默认夹具里覆盖的规则(写明原因,不许悄悄豁免)
KNOWN_CONDITIONAL = {
    "G13-multiple-commits": "夹具只有 1 个 commit,量不出多提交",
    "G13-mass-deletion": "夹具删除行数远小于阈值",
    "G10-tool-version-mismatch": "取决于本机 clang-format 与 CI pinned 是否一致",
    "G9-golden-not-runnable": "另有独立负向对照(见 g09 的 _probe_runnable 测试)",
}


def sh(*args: str, cwd: Path | None = None) -> str:
    r = subprocess.run(args, cwd=str(cwd) if cwd else None,
                       capture_output=True, text=True)
    return r.stdout


def w(rel: str, content: str) -> None:
    p = ROOT / rel
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(content, encoding="utf-8")


CANNDEV = ROOT.parent / "selftest_canndev"

# 假 canndev:只放组 5/7/18 真正读的那几个文件,信号照 canndev 真实情况配。
#
# ⚠️ **不许指向真 canndev。** selftest 是下载者验证"装好了没"的唯一入口;
# 一旦它依赖某台机器上的真仓,别人拷过去跑就会看到 7 条哑弹(G5×1/G7×2/G18×4),
# 读作"这 skill 坏了"。把机器状态从 checker 里清掉、却留在夹具里,等于没清。
_A2_SOC_MATRIX = {                       # soc -> 该 soc 的 ini 里有哪些算子段
    "ascend910b":   ["Celu", "GridUnnormal", "NonZeroWithValue"],
    "ascend910_93": ["Celu", "GridUnnormal", "NonZeroWithValue"],
    "ascend910":    ["Celu", "GridUnnormal"],
    "ascend310p":   ["Celu", "NonZeroWithValue"],   # 无 GridUnnormal → README 标 √ = overstated
    "ascend310b":   ["Celu"],
}


def build_canndev() -> None:
    def cw(rel: str, content: str) -> None:
        p = CANNDEV / rel
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(content, encoding="utf-8")

    for soc, ops in _A2_SOC_MATRIX.items():
        body = []
        for op in ops:
            body.append(f"[{op}]")
            # GridUnnormal:A2 dtype 面比夹具 def 的 {DT_FLOAT16} 宽 → G5-a5-scope-narrower-than-a2
            #               A2 有 2 输入 1 输出,def 只有 1 输入 0 输出 → G5-param-count-mismatch
            if op == "GridUnnormal":
                body += ["input0.name=grid", "input0.dtype=float,float16",
                         "input1.name=assist", "input1.dtype=float,float16",
                         "output0.name=diff", "output0.dtype=float,float16", ""]
            elif op == "NonZeroWithValue":
                # 与 OP3 的 def 逐维对不上,六维各触发一条:
                #   name(self vs x) / dtype(多 float16) / format(多 NC1HWC0) /
                #   paramType(optional vs REQUIRED) / attr 少 alpha / beta 类型与默认值不同
                body += ["input0.name=self", "input0.dtype=float,float16",
                         "input0.format=ND,NC1HWC0", "input0.paramType=optional",
                         "output0.name=index", "output0.dtype=int32,int32",
                         "output0.format=ND,ND", "output0.paramType=required",
                         "attr.list=alpha,beta",
                         "attr_alpha.type=float", "attr_alpha.paramType=optional",
                         "attr_alpha.defaultValue=1.0",
                         "attr_beta.type=float", "attr_beta.paramType=optional",
                         "attr_beta.defaultValue=1.0", ""]
            else:
                body += ["input0.dtype=float", "output0.dtype=float", ""]
        cw(f"ops/built-in/tbe/op_info_cfg/ai_core/{soc}/aic-{soc}-ops-info.ini",
           "\n".join(body) + "\n")

    # A2 的 IR 声明(REG_OP 上方注释块会被 refs 一并取走)
    cw("ops/built-in/op_proto/inc/fake_ops.h",
       "/**\n *@li grid: 4-D Tensor with shape `[batch, height, width, 2]`.\n */\n"
       "REG_OP(GridUnnormal)\n    .OP_END_FACTORY_REG(GridUnnormal)\n\n"
       "/**\n *@li x: 2-D Tensor.\n */\n"
       "REG_OP(NonZeroWithValue)\n    .OP_END_FACTORY_REG(NonZeroWithValue)\n")

    # A2 的 InferShape 校验:
    #   GridUnnormal 常量 {4,2},夹具本仓一道守卫都没有       → G18-a2-validation-dropped
    #   NonZeroWithValue 常量 {2},夹具本仓只拦 4,未对账 [2] → G18-a2-validation-partial
    cw("ops/built-in/op_proto/fake_ops.cc",
       "IMPLEMT_INFERFUNC(GridUnnormal, GridUnnormalInfer) {\n"
       "  auto grid_shape = op.GetInputDescByName(\"grid\").GetShape().GetDims();\n"
       "  auto x_shape = op.GetInputDescByName(\"assist\").GetShape().GetDims();\n"
       "  if (x_shape.size() != 4 || grid_shape.size() != 4) { return GRAPH_FAILED; }\n"
       "  if (grid_shape[3] != 2) { return GRAPH_FAILED; }\n"
       "  return GRAPH_SUCCESS;\n}\n\n"
       "IMPLEMT_INFERFUNC(NonZeroWithValue, NonZeroWithValueInfer) {\n"
       "  auto x_shape = op_desc->MutableInputDesc(0)->GetShape();\n"
       "  if (x_shape.GetDimNum() != 2) { return GRAPH_FAILED; }\n"
       "  return GRAPH_SUCCESS;\n}\n")

    cw("ops/built-in/tbe/impl/grid_unnormal.py", "# A2 TIK impl\n")
    # A2 有 TF plugin 而 A5 没有 → G5-pathway-missing;
    # A5 有 docs/aclnnNonZeroWithValue.md 而 A2 无 level2 头 → G5-pathway-added-needs-review
    cw("ops/built-in/framework/tf_plugin/non_zero_with_value_plugin.cc", "// A2 tf plugin\n")


def build_fixture() -> None:
    if ROOT.exists():
        subprocess.run(["rm", "-rf", str(ROOT)])
    ROOT.mkdir(parents=True)
    sh("git", "init", "-q", cwd=ROOT)
    sh("git", "config", "user.email", "selftest@local", cwd=ROOT)
    sh("git", "config", "user.name", "selftest", cwd=ROOT)

    # ---- base 提交:放"既有文件",好让 head 里对它们的修改是 M 而不是 A ----
    w(".pre-commit-config.yaml", """repos:
  - repo: https://gitcode.com/pre-commit-clang/mirrors-clang-format
    rev: v18.1.8
    hooks: [{id: clang-format}]
  - repo: https://gitcode.com/gh_mirrors/ru/ruff-pre-commit
    rev: v0.14.14
    hooks: [{id: ruff-check}]
""")
    w(".clang-format", "BasedOnStyle: Google\nColumnLimit: 120\n")
    # A2 路径的既有内核(head 里会改它 → 触发 G4-a2-path-touched)
    w(f"{OP}/op_kernel/grid_unnormal.cpp", "// existing A2-side kernel\nvoid f() {}\n")
    w("cmake/func.cmake", "# existing framework file\n")
    w("common/inc/op_graph/proto_extend.h", "// shared proto header\n")
    # 同算子下一个**既有且本次不改**的文件,且自身有毛病(超长函数 + 中文冗余空格)。
    # 三角类 checker 会 glob 整个算子目录、把它扫出来——正是"锚点落在 diff 之外"的样本。
    # 没有这个文件,out_of_diff 机制在夹具上永远测不到(新算子夹具全是 A 新增)。
    # G4-shared-ut-modified 的前提:双代算子根目录已有一份共用 infershape UT(A2 门禁也在跑)。
    # head 提交里会去改它 → 必然触发。
    w(f"{OP}/tests/ut/op_host/test_grid_unnormal_infershape.cpp",
      "// 既有共用 infershape UT(A2 与 A5 共用,A2 门禁在跑)\n"
      "TEST_F(GridUnnormalInfer, basic) { EXPECT_EQ(1, 1); }\n")
    # G4-a2-auto-sync-disabled:A2 那条本来不带 AUTO_SYNC(缺省 true),head 里会被写成 false。
    w(f"{OP}/op_kernel/CMakeLists.txt",
      "add_kernel_sources(\n    COMPUTE_UNITS ascend910b ascend910_93\n)\n"
      "add_kernel_sources(\n    KERNEL_SRC arch35/grid_unnormal.cpp\n"
      "    COMPUTE_UNITS ascend950\n    AUTO_SYNC false\n)\n")
    w(f"{OP}/tests/ut/op_kernel/test_legacy_untouched.cpp",
      "// 既有 kernel UT,本次 PR 未改动。blockDim 恒为 1 → 触发 G17-kernel-ut-single-core-only,\n"
      "// 而 g17 是 glob 整个算子目录的,于是锚点落在 diff 之外。\n"
      "TEST_F(LegacyUt, single_core) {\n"
      "    ICPU_RUN_KF(grid_unnormal, 1, x, y, tiling);\n"
      "    ICPU_RUN_KF(grid_unnormal, 1, x2, y2, tiling);\n}\n")
    sh("git", "add", "-A", cwd=ROOT)
    sh("git", "commit", "-qm", "base", cwd=ROOT)
    base = sh("git", "rev-parse", "HEAD", cwd=ROOT).strip()

    # ---- head 提交:踩雷 ----
    # G4-a2-path-touched:修改既有的非 arch35 内核
    w(f"{OP}/op_kernel/grid_unnormal.cpp",
      "// existing A2-side kernel, now MODIFIED\nvoid f() { int a = 1; (void)a; }\n")
    # G4-shared-ut-modified:往 A2 也在跑的共用 infershape UT 里加 A5 用例(应被拦)
    w(f"{OP}/tests/ut/op_host/test_grid_unnormal_infershape.cpp",
      "// 既有共用 infershape UT(A2 与 A5 共用,A2 门禁在跑)\n"
      "TEST_F(GridUnnormalInfer, basic) { EXPECT_EQ(1, 1); }\n"
      "TEST_F(GridUnnormalInfer, unknown_rank) { EXPECT_EQ(1, 1); }  // A5 新增,越界\n")
    # G4-a2-auto-sync-disabled:给 A2 那条补上 AUTO_SYNC false(应被拦)
    w(f"{OP}/op_kernel/CMakeLists.txt",
      "add_kernel_sources(\n    COMPUTE_UNITS ascend910b ascend910_93\n    AUTO_SYNC false\n)\n"
      "add_kernel_sources(\n    KERNEL_SRC arch35/grid_unnormal.cpp\n"
      "    COMPUTE_UNITS ascend950\n    AUTO_SYNC false\n)\n")
    # G4-framework-file-modified
    w("cmake/func.cmake", "# existing framework file\n# hacked for local build\n")
    w("common/inc/op_graph/proto_extend.h", "// shared proto header\n// grid_unnormal migrated out\n")
    # G4-tiling-symbol-clash:顶层 + 子目录同时有 tiling
    w(f"{OP}/op_host/grid_unnormal_tiling.cpp", "// top-level tiling\n")
    w(f"{OP}/op_host/arch35/grid_unnormal_tiling_arch35.cpp", _tiling_cpp())
    # G4-team-slang-naming / G1 / G2 / G14 全塞进 arch35 内核头
    w(f"{OP}/op_kernel/arch35/grid_unnormal.h", _kernel_h())
    # G8:TilingData 定义死字段
    w(f"{OP}/op_host/arch35/grid_unnormal_tiling_arch35.h", _tiling_h())
    # G3:host 侧校验问题
    w(f"{OP}/framework/grid_unnormal_plugin.cpp", _plugin_cpp())
    # G6:proto 与 def 属性类型不一致 + 下标越界
    w(f"{OP}/op_graph/grid_unnormal_proto.h",
      '/**\n *@li grid: flow field grid, 4-D Tensor with shape `[batch, height, width, 2]`.\n */\n'
      'REG_OP(GridUnnormal)\n    .ATTR(align_corners, Bool, false)\n'
      '    .ATTR(only_in_proto, Bool, true)\n    .OP_END_FACTORY_REG(GridUnnormal)\n')
    w(f"{OP}/op_host/grid_unnormal_def.cpp", _def_cpp())
    w(f"{OP}/op_host/grid_unnormal_infershape.cpp",
      "auto* p = attrs->GetAttrPointer<float>(0);\nauto* q = attrs->GetAttrPointer<int64_t>(9);\n")
    # G12 + G7:README 各种毛病
    w(f"{OP}/README.md", _readme())
    # G9:golden 无竞品;缺 examples/tests.st 等;G14-golden-int-via-fp32:int 经 fp32 中转
    w(f"{OP}/tests/assets/golden.py",
      "import numpy as np\n\n\ndef grid_unnormal_golden(grid, assist, scalar):\n"
      '    """中间统一用 fp32 计算,与 kernel 一致。"""\n'
      "    scalar_val = scalar.astype('float32').reshape(-1)[0]  # int 标量先进 fp32\n"
      "    scalar_i = scalar_val.astype(out_dtype)               # 再转回 int → G14-golden-int-via-fp32\n"
      "    return [grid, assist]\n")
    # G11:超大头文件 + 超大函数 + C 风格 cast + 魔鬼数字 + 重复代码
    w(f"{OP}/op_host/big_header.h", _big_header())
    w(f"{OP}/op_host/dup_a.cpp", _dup_block("A"))
    w(f"{OP}/op_host/dup_b.cpp", _dup_block("B"))
    # G10:行尾空格 + 缺末尾换行
    (ROOT / OP / "op_host" / "bad_ws.cpp").write_text("int x = 1;   \nint y = 2;", encoding="utf-8")
    # gate10a:_apt.cpp 存在 → G4-apt-file-present
    w(f"{OP}/op_kernel/grid_unnormal_apt.cpp", "// legacy apt entry\n")
    # gate5 通路泄漏:OP3 是 A5-only(def 只 AddConfig ascend950)+ 有 op_api +
    # CMakeLists 未声明 ACLNNTYPE → aclnn 会被发布进 A2 包。
    # ⚠️ 别挂到 OP2:它的 def 被 G9-binary-json-missing-legacy-soc 的夹具加了 910b,
    # 就不是 A5-only 了,两个夹具会互相拆台。
    w(f"{OP3}/CMakeLists.txt",
      "add_modules_sources(HOSTNAME x MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR}\n"
      "  OPTYPE non_zero_with_value COMPUTE_UNIT ascend950 DISABLE_IN_OPP TRUE)\n")
    # gate10b:OP2 有 infershape 实现,IMPL_OP 链上只挂 InferDataType 没挂 InferShape
    # ⚠️ 别挂到 OP3:它是 G6-inferdatatype-missing 的正样本(输出 int32 ⊄ 输入 float
    # 且全仓无 InferDataType 注册),加上就把那条弄成哑弹了。
    w(f"{OP2}/op_host/celu_impl.cpp", "IMPL_OP(Celu).InferDataType(InferDtypeCelu);\n")
    # G7-empty-tensor-undeclared 的正样本:文档不提空Tensor **且** L2 里也没有 IsEmpty
    # (与 OP 区分开:OP 是"代码支持而文档没写"→ supported-undeclared)
    w(f"{OP2}/docs/aclnnCeluV2.md",
      "# aclnnCeluV2\n\n第一段接口 aclnnCeluV2GetWorkspaceSize。\n\n错误码:\n<table>\n"
      "<tr><td>ACLNN_ERR_PARAM_INVALID</td><td>161002</td>"
      "<td>self的数据类型不在支持的范围之内。</td></tr>\n</table>\n")
    w(f"{OP2}/op_api/aclnn_celu_v2.cpp",
      "aclnnStatus aclnnCeluV2GetWorkspaceSize(const aclTensor* self, aclTensor* out) {\n"
      "    CHECK_RET(CheckDtypeValid(self, out), ACLNN_ERR_PARAM_INVALID);\n"
      "    return ACLNN_SUCCESS;\n}\n")
    # gate9a:仓级目录里没有本算子条目 → G9-op-list-entry-missing
    w("docs/zh/op_list.md", "# 算子清单\n\n| 算子 | 说明 |\n|---|---|\n")
    w("docs/zh/op_api_list.md", "# aclnn 清单\n\n| 接口 | 说明 |\n|---|---|\n")

    # OP4:只为 G9-aclnn-doc-missing 存在——有 op_api 目录、没有 docs/aclnn*.md。
    # ⚠️ 单独开一个算子,别和别的规则共用同一个 OP:本轮已三次夹具互相拆台
    # (给 OP2 补 aclnn 文档 → G9-aclnn-doc-missing 变哑弹;给 OP 的 L2 加 IsEmpty
    #   → G7-empty-tensor-undeclared 变哑弹)。一个规则一块地,别抢。
    w(f"{OP4}/op_host/hard_shrink_def.cpp",
      "class HardShrink : public OpDef {\n"
      "    this->Input(\"x\").DataType({ge::DT_FLOAT});\n"
      "    this->AICore().AddConfig(\"ascend950\");\n};\n")
    w(f"{OP4}/op_host/op_api/aclnn_hard_shrink.cpp", "// aclnn entry, 但 docs/ 下没有 aclnnHardShrink.md\n")
    w(f"{OP4}/op_kernel/hard_shrink.cpp", "// kernel\n")

    # OP5:专给 G16-noncontiguous-doc-no-autocontiguous——文档写非连续 √,def 无
    # AutoContiguous/IgnoreContiguous,且无 op_api(自动生成 aclnn 框架默认拒绝非连续,
    # scatter_min 实证)。单开算子,不与别的规则共用。
    w(f"{OP5}/op_host/scatter_min_def.cpp",
      "class ScatterMin : public OpDef {\n"
      "    this->Input(\"var\").DataType({ge::DT_FLOAT});\n"
      "    this->AICore().AddConfig(\"ascend950\");\n};\n")
    w(f"{OP5}/docs/aclnnScatterMin.md",
      "# aclnnScatterMin\n\n<table>\n"
      "<tr><th>参数名</th><th>非连续Tensor</th></tr>\n"
      "<tr><td>varRef</td><td>√</td></tr>\n</table>\n")
    w(f"{OP5}/op_kernel/scatter_min.cpp", "// kernel\n")
    # OP5 补足三样兜底交付件,维持 G9 多数派统计样本结构(别让 OP5 稀释多数派)
    w(f"{OP5}/README.md", "# ScatterMin\n\n按 indices 取最小值更新。\n")
    w(f"{OP5}/tests/ut/op_host/test_scatter_min_tiling.cpp",
      "// DT_FLOAT 用例\nTEST_F(ScatterMinTiling, f32) { EXPECT_EQ(1, 1); }\n")
    w(f"{OP5}/tests/ut/op_kernel/test_scatter_min.cpp",
      "// kernel UT\nTEST_F(ScatterMinKernel, f32) { EXPECT_EQ(1, 1); }\n")

    # G13:杂散文件 + 大文件 + 绝对软链
    w(f"{OP}/tests/tmp_output.bin", "x" * 10)
    w(f"{OP}/op_host/huge_blob.inc", "x" * (600 * 1024))          # G13-large-file
    # ---- 第二个算子:覆盖与上面**互斥**的规则(缺 proto / 缺 tiling 头 / 缺 golden / 有 aclnn)----
    w(f"{OP2}/op_host/celu_def.cpp",
      "class Celu : public OpDef {\n"
      "    this->Input(\"x\").DataType({ge::DT_FLOAT16, ge::DT_BF16});\n"
      "    this->DynamicRankSupportFlag(true);\n"
      "    this->AICore().AddConfig(\"ascend950\");\n"   # G9-binary-json-missing(无 config 目录)
      "    this->DynamicRankSupportFlag(true);\n"          # 声明动态 rank 但 infershape 无 IsUnknownRank
      "    this->AICore().AddConfig(\"ascend910b\");\n"   # G9-binary-json-missing-legacy-soc(继承面只提示)
      "};\n")
    w(f"{OP2}/op_host/op_api/aclnn_celu.cpp", "// aclnn entry\n")   # → G9-aclnn-doc-missing
    # 组 21:文档返回码表承诺 3 类异常,而 L2 里**一个校验点都没有** → 全部报缺失。
    # 文档里也不提空 Tensor → G7-empty-tensor-undeclared(测试侧会当异常打)。
    w(f"{OP}/docs/aclnnGridUnnormal.md",
      "# aclnnGridUnnormal\n\n第一段接口 aclnnGridUnnormalGetWorkspaceSize。\n\n"
      "## 返回值\n\n错误码:\n\n<table>\n"
      "<tr><td>ACLNN_ERR_PARAM_NULLPTR</td><td>161001</td>"
      "<td>传入的self、alpha、out是空指针。</td></tr>\n"
      "<tr><td>ACLNN_ERR_PARAM_INVALID</td><td>161002</td>"
      "<td>self的数据类型不在支持的范围之内。</td></tr>\n"
      "<tr><td></td><td></td><td>self、out的维度大于8。</td></tr>\n"
      "</table>\n")
    w(f"{OP}/op_api/aclnn_grid_unnormal.cpp",
      "aclnnStatus aclnnGridUnnormalGetWorkspaceSize(const aclTensor* grid,\n"
      "                                              aclTensor* out, uint64_t* ws) {\n"
      "    if (grid->IsEmpty()) { return ACLNN_SUCCESS; }  // 代码支持空Tensor,"
      "而 aclnn 文档只字不提 → G7-empty-tensor-supported-undeclared\n"
      "    return ACLNN_SUCCESS;   // 一个校验都没有 → 组 21 全类缺失\n}\n")
    # 组 21 的待判题:有校验点、但名字归不到 dtype 类 → 出题让人读函数体,不硬报
    w(f"{OP3}/docs/aclnnNonZeroWithValue.md",
      "# aclnnNonZeroWithValue\n\naclnnNonZeroWithValueGetWorkspaceSize 支持空Tensor。\n\n"
      "错误码:\n<table>\n<tr><td>ACLNN_ERR_PARAM_INVALID</td><td>161002</td>"
      "<td>x的数据类型不在支持的范围之内。</td></tr>\n</table>\n")
    # L2 里有 IsEmpty 早退 + FillScalar:代码支持空Tensor 且有输出语义,
    # 而 OP3 的 aclnn 文档只写了「支持空Tensor」没写语义 → G7-empty-tensor-semantics-undeclared;
    # 若文档连「空Tensor」都没有 → G7-empty-tensor-supported-undeclared(挂在 OP 上)。
    w(f"{OP3}/op_api/aclnn_non_zero_with_value.cpp",
      "aclnnStatus aclnnNonZeroWithValueGetWorkspaceSize(const aclTensor* x, aclTensor* out) {\n"
      "    CHECK_RET(SomeOpaqueGuard(x, out), ACLNN_ERR_PARAM_INVALID);\n"
      "    if (x->IsEmpty()) {\n"
      "        FillScalar(out, 0, uniqueExecutor.get());\n"
      "        return ACLNN_SUCCESS;\n    }\n"
      "    return ACLNN_SUCCESS;\n}\n")

    w(f"{OP2}/op_kernel/arch35/celu.h",
      "// kernel, no tiling header\n"
      "RegTensor<float> reg;\n"
      "float r = (d == 0) ? 0.0f : a / d;\n")
    w("experimental/activation/foo_op/op_host/foo_op_def.cpp", "// contributed op\n")
    # 有 op_kernel 但完全没有 tiling 头 -> G8-tilingdata-header-not-found
    w("experimental/activation/foo_op/op_kernel/foo_op.cpp", "// kernel, no tiling header at all\n")
    # 新写算子却用宏式 TilingData -> G8-tilingdata-legacy-macro-style
    w(f"{OP2}/op_host/celu_tiling.h",
      "BEGIN_TILING_DATA_DEF(CeluTilingData)\n"
      "TILING_DATA_FIELD_DEF(int64_t, legacyField);\n"
      "END_TILING_DATA_DEF\n")
    # 认不出的写法 -> G8-tilingdata-fields-unparsed
    w(f"{OP2}/op_kernel/arch35/celu_tiling_data.h",
      "// 是 TilingData 头,但字段用了本规则不认识的写法\n"
      "struct CeluTilingData {\n    USING_UNKNOWN_MACRO(x);\n};\n")
    w(f"{OP2}/tests/assets/README.txt", "no golden here\n")         # → G9-golden-missing
    w(f"{OP2}/README.md",
      "# Celu\n\n## 功能说明\n\n- 非有限输入 inf / nan 不属于支持域。\n"
      "- 支持总元素数为 0 的空 Tensor,空进空出。\n"
      "- 支持动态 rank。\n")
    w(f"{OP2}/op_host/celu_infershape.cpp",
      "graphStatus Infer(gert::InferShapeContext* c) {\n"
      "    if (a != b) { return ge::GRAPH_FAILED; }\n"
      "    if (n != 4) { return ge::GRAPH_FAILED; }\n"
      "    return ge::GRAPH_SUCCESS;\n}\n")
    # UT 只有正例:无零元素 shape、无 -2、无期望失败断言
    w(f"{OP2}/tests/ut/op_host/test_celu_infershape.cpp",
      "TEST_F(CeluInfer, ok) { ExecuteTestCase({{2, 4}}, ge::GRAPH_SUCCESS); }\n")
    # 组17:kernel UT 恒单核 + 生产入口被屏蔽 + 随机无种子 + rtol/atol 同值
    w(f"{OP2}/op_kernel/celu.cpp",
      '#ifndef __CCE_KT_TEST__\nextern "C" __global__ __aicore__ void celu(GM_ADDR x) {}\n#endif\n')
    w(f"{OP2}/tests/ut/op_kernel/test_celu.cpp",
      "TEST_F(CeluKernel, run) { ICPU_RUN_KF(celu_ut_kernel<float>, 1, x, y); }\n")
    w(f"{OP2}/tests/ut/op_kernel/celu_data/gen_data.py",
      "import numpy as np\nx = np.random.uniform(-1, 1, (4, 4))\n")
    w(f"{OP2}/tests/ut/op_kernel/celu_data/compare_data.py",
      "import numpy as np\nnp.allclose(a, b, rtol=atol, atol=atol)\n")
    w(f"{OP}/op_host/config/ascend950/grid_unnormal_binary.json", "{not valid json\n")
    (ROOT / OP / "op_host" / "dead_link.h").symlink_to("/nonexistent/abs/path.h")

    # G18-a2-validation-partial:nzv 的 A2 InferShape 校验常量是 {2}(canndev 真实),
    # 本仓守卫只拦 4 → 未对账 [2] 触发 partial(OP 的 GridUnnormal 一道守卫都没有 → dropped)
    w(f"{OP3}/op_host/non_zero_with_value_infershape.cpp",
      "graphStatus Infer(gert::InferShapeContext* c) {\n"
      "    if (x.GetDimNum() != 4) { return ge::GRAPH_FAILED; }\n"
      "    return ge::GRAPH_SUCCESS;\n}\n")
    w(f"{OP3}/op_kernel/non_zero_with_value.cpp", "// minimal kernel so the dir counts as a real op\n")
    # G9-binary-json-dtype-gap:def 注册 fp32+int32,json 只覆盖 float32
    w(f"{OP3}/op_host/non_zero_with_value_def.cpp",
      "class NonZeroWithValue : public OpDef {\n"
      "    this->Input(\"x\").ParamType(REQUIRED).DataType({ge::DT_FLOAT})\n"
      "        .Format({ge::FORMAT_ND});\n"
      "    this->Output(\"index\").ParamType(REQUIRED).DataType({ge::DT_INT32})\n"
      "        .Format({ge::FORMAT_ND});\n"
      "    this->Attr(\"beta\").AttrType(OPTIONAL).Int(2);\n"
      "    this->AICore().AddConfig(\"ascend950\");\n"
      "};\n")
    w(f"{OP3}/op_host/config/ascend950/non_zero_with_value_binary.json",
      '{"op_type":"NonZeroWithValue","op_list":[{"bin_filename":"NonZeroWithValue_fp32_950",'
      '"inputs":[{"name":"x","index":0,"dtype":"float32","format":"ND","paramType":"required","shape":[-2]}],'
      '"outputs":[]}]}\n')

    sh("git", "add", "-A", cwd=ROOT)
    sh("git", "commit", "-qm", "head", cwd=ROOT)
    # 交付件根(**故意不齐**):01/02 骨架不足、缺 03-07、05 三类结果为空
    dl = ROOT.parent / "selftest_deliverables" / "GridUnnormal"
    subprocess.run(["rm", "-rf", str(dl.parent)])
    (dl / "05_test_result" / "generalization").mkdir(parents=True)
    # G15-05-csv-no-bom:有固定名 CSV 但不带 BOM;G15-05-whitelist-violation:白名单外文件
    (dl / "05_test_result" / "generalization" / "GridUnnormal_generalization.csv").write_text(
        "testcase,dtype\ncase1,fp16\n", encoding="utf-8")
    (dl / "05_test_result" / "generalization" / "notes.txt").write_text("stray\n", encoding="utf-8")
    # G15-05-csv-name-nonstandard:precision 档只有乱起名 CSV,缺固定名 <Op>_new_precision_3way.csv
    prec = dl / "05_test_result" / "precision"
    prec.mkdir(parents=True, exist_ok=True)
    (prec / "whatever.csv").write_text("case,r\nx,PASS\n", encoding="utf-8-sig")
    # 组 22:性能 CSV 一份有 GPU 基准(含必然不达标 + 灰区两类)、一份没有基准
    perf = dl / "05_test_result" / "performance"
    perf.mkdir(parents=True, exist_ok=True)
    (perf / "GridUnnormal_performance.csv").write_text(
        "case,dtype,npu_us,gpu_us\n"
        "gu_001,float16,452.0,100.0\n"      # 耗时比 4.52 → 必然不达标
        "gu_002,float16,80.0,100.0\n"       # 0.80 → 灰区(0.5~1.2) → 出题
        "gu_003,float16,30.0,100.0\n",      # 0.30 → 达标
        encoding="utf-8")
    # 组 23 新鲜度:结果产物 mtime 调到 1 小时前,源码是刚写的 → 必然 stale
    import os as _os, time as _t
    old = _t.time() - 3600
    (perf / "GridUnnormal_result_stale.csv").write_text("case,r\nx,PASS\n", encoding="utf-8")
    _os.utime(perf / "GridUnnormal_result_stale.csv", (old, old))
    vend = ROOT.parent / "selftest_vendor"
    (vend / "op_kernel").mkdir(parents=True, exist_ok=True)
    (vend / "op_kernel" / "grid_unnormal.o").write_text("fake binary\n", encoding="utf-8")

    (perf / "GridUnnormal_perf_no_baseline.csv").write_text(
        "case,dtype,bin_perf_us\ngu_010,float16,42.0\n", encoding="utf-8")  # 无 GPU 列
    (dl / "01_requirement.md").write_text(
        "# R\n\n## 一\n\n## 3. 910B/910C 支持范围(canndev 权威)\n\n"
        "| 名称 | shape |\n|---|---|\n| grid | 任意 shape |\n", encoding="utf-8")
    (dl / "02_design.md").write_text("# D\n\n## 一\n", encoding="utf-8")

    # G15 invoke_path 六规则夹具(每算子目录只读第一个 *_invoke_path.csv → 按算子分摊违规形态)
    # GridUnnormal:说明块后无空行 → no-blank-separator
    ip1 = dl / "05_test_result" / "invoke_path"
    ip1.mkdir(parents=True, exist_ok=True)
    (ip1 / "GridUnnormal_invoke_path.csv").write_text(
        "项,内容\n支持通路范围,kernel=✅\n通路,testcase,precision_status\ngeir,c1,PASS\n", encoding="utf-8-sig")
    # Celu:有空行但说明块首行非「支持通路范围」+ 明细 <50 例 + geir 行 xpu_device_us 非数值 + 缺 G/N 列
    dl2 = ROOT.parent / "selftest_deliverables" / "Celu"
    ip2 = dl2 / "05_test_result" / "invoke_path"
    ip2.mkdir(parents=True, exist_ok=True)
    (ip2 / "Celu_invoke_path.csv").write_text(
        "项,内容\n依据,01\n\n通路,testcase,precision_status,xpu_status,xpu_device_us\n"
        "geir,c1,PASS,PASS,NA\ngeir,c2,PASS,PASS,\n", encoding="utf-8-sig")
    # NonZeroWithValue:缺必带列(xpu_status/xpu_device_us) → column-missing
    dl3 = ROOT.parent / "selftest_deliverables" / "NonZeroWithValue"
    ip3 = dl3 / "05_test_result" / "invoke_path"
    ip3.mkdir(parents=True, exist_ok=True)
    (ip3 / "NonZeroWithValue_invoke_path.csv").write_text(
        "项,内容\n支持通路范围,geir=✅\n\n通路,testcase,precision_status\ngeir,c1,PASS\n", encoding="utf-8-sig")

    (ROOT / ".selftest_base").write_text(base)


def _kernel_h() -> str:
    return """// A5 kernel for selftest
#include <cstdint>
constexpr int32_t NZV_ALL_CORE_NUM = 72 * 32;      // G1-hardcoded-platform-const
struct K {
    uint32_t gmOffset_ = 0;                         // G1-narrow-accumulator (同文件有 int64)
    int64_t totalNum_ = 0;
    void Run(int64_t row, int64_t col, int64_t denom) {
        int64_t numel = row * col;                  // G1-mul-overflow-unguarded
        uint16_t lc = static_cast<uint16_t>(numelCol / 8);  // G1-narrowing-cast (shape 溯源)
        int32_t v = (int32_t)row;                   // G1-c-style-narrow-cast / G11-c-style-cast
        int64_t q = row / denom;                    // G14-int-div-by-zero
        int32_t mag = abs(v);                       // G14-ask: 整型极值取负/abs 溢出
        __VEC_SCOPE__ { }                           // 真作用域,供 G2-ar-not-cleared 计数
        RegTensor<float> reg;                       // G2-vf-missing-vec-scope (无 __VEC_SCOPE__)
        CompareScalar(mask, reg, 1.0f);             // G2-comparescalar-no-mode
        pad.rightPadding = numColAlign - numCol;    // G2-rightpadding-wrong-base
        GatherMask<STORE_REG>(reg);                 // G2-ar-not-cleared
        (void)numel; (void)lc; (void)v; (void)q;
    }
    // A5 走 regbase,A2 走老路                      // G4-team-slang-naming
    __aicore__ inline void Process() {
        for (int64_t i = 0; i < totalNum_; ++i) { }  // G14-no-empty-tensor-guard
    }
};
long numelCol = 4096;
long numColAlign = 64, numCol = 50;
"""


def _tiling_cpp() -> str:
    body = "\n".join(f"    int v{i} = {i} + 1;" for i in range(60))
    return ("ge::graphStatus GridUnnormalTilingFunc(gert::TilingContext* context)\n{\n"
            + body + "\n    return ge::GRAPH_SUCCESS;\n}\n"   # G11-oversized-function
            "// G2-fixed-dim-array-no-rank-check: 用了定长维度模板但全目录无 rank 校验\n"
            "BroadcastBaseTiling<OpDag> brcBaseTiling(context_, BROADCAST_KERNEL_TYPE::KERNEL_TYPE_NDDMA);\n")


def _tiling_h() -> str:
    return ("BEGIN_TILING_DATA_DEF(GridUnnormalTilingData)\n"
            "TILING_DATA_FIELD_DEF(int64_t, totalNum);\n"
            "TILING_DATA_FIELD_DEF(int64_t, neverReadField);\n"   # G8-tilingdata-dead-field
            "END_TILING_DATA_DEF\n")


def _plugin_cpp() -> str:
    return ("""ge::graphStatus Parse(Operator& op) {
    ge::DataType outputDataType;              // G3-uninitialized-var
    op.GetAttr("output_type", outputDataType); // G3-getattr-unchecked
    if (!ok) {
        OP_LOGE(context->GetNodeName(), "dtype of grid is invalid");  // G3-bare-op-loge
        return ge::GRAPH_FAILED;
    }
    const int64_t* p = attrs->GetAttrPointer<int64_t>(0);
    int64_t v = *p;                            // G2-ptr-deref-unchecked
    (void)v;
    return ge::GRAPH_SUCCESS;
}
""")


def _def_cpp() -> str:
    return ("""class GridUnnormal : public OpDef {
    explicit GridUnnormal(const char* name) : OpDef(name) {
        this->Input("grid").DataType({ge::DT_FLOAT16})           // G5: 比 A2 少 float
            .Format({ge::FORMAT_NDC1HWC0, ge::FORMAT_NDC1HWC0}); // G6-format-rank-vs-doc-dims(配 README 0-8维)
        this->Attr("align_corners").AttrType(OPTIONAL).Int(0);   // G6-attr-type-mismatch (proto 是 Bool)
        this->Attr("extra_only_in_def").AttrType(OPTIONAL).Bool(false);
        this->AICore().AddConfig("ascend950");                   // G9-binary-json-invalid(下方非法 json)
        // ⚠️ 这一行是 G4-a2-path-touched 的**前提**,别删:
        // "改动会不会污染 A2"的判据是**本仓为哪些 soc 编译**(def 的 AddConfig),
        // 不是"存在非 arch35 的 .cpp"。只注册 ascend950 时本仓压根不出 A2 产物,
        // 改它的非 arch35 路径碰不到 A2 —— 真算子 NonZeroWithValue 就是这样被误报成红线 R2 的。
        // 夹具要有这一行,OP 才真是双代算子,规则才该响。
        this->AICore().AddConfig("ascend910b", cfg910b);
    }
};
""")


def _readme() -> str:
    return """# GridUnnormal

## 产品支持情况

| 产品 | 是否支持 |
| :--- | :---: |
| <term>Ascend 950PR/Ascend 950DT</term> | √ |
| <term>Atlas A2 训练系列产品/Atlas A2 推理系列产品</term> | x |
| <term>Atlas 推理系列产品</term> | √ |

## 功能说明

- 计算公式:

$$
GridUnnormal(grid) = grid \\ast (size - 1) / 2
$$

- 算子功能:这是 GridSample 链路的算子。非有限输入 inf / nan 不属于支持域。
说明缩进不对的续行

> 说明:这是一条 editorial 注。

## 约束说明

- 输入支持 0-8 维。
- <term>Ascend 950PR/Ascend 950DT</term>:不支持 BFLOAT16。
- <term>Atlas A2 训练系列产品</term>:支持 BFLOAT16。

## 参数说明

<table><thead><tr><th>参数名</th><th>描述</th></tr></thead>
<tbody><tr><td>x</td><td>表示输入张量,对应公式中的`x`(G12-md-syntax-in-html-table 正样本:HTML 表格内反引号不渲染)。</td></tr></tbody></table>

## 调用说明

| 方式 | 说明 |
| --- | --- |
| PyTorch | 通过 torch 接口调用。 |
"""


def _big_header() -> str:
    return "#pragma once\n" + "".join(f"// filler line {i}\nint g{i} = {i};\n" for i in range(300))


def _dup_block(tag: str) -> str:
    blk = "\n".join(f"    int shared_{i} = {i} * 3 + 7;" for i in range(14))
    return f"void func_{tag}() {{\n{blk}\n}}\n"


def main() -> int:
    build_fixture()
    build_canndev()
    base = (ROOT / ".selftest_base").read_text().strip()
    # 远程 + 本地**两趟**都跑:local-only 的规则(组 13 的作者流程卫生、组 15 转测交付件)
    # 只在 --local 下才有代码路径,只跑远程一趟的话它们会永远显示成"哑弹"而测不到。
    fired: set[str] = set()
    # 可达性待判题也要测哑弹。它们从 🔴 规则改成了派题——若只统计 rule="",
    # 这三类就从"可测"变成"不可测",等于拿丢覆盖换精确率。ask 不响同样算哑弹。
    asks: set[str] = set()
    ood_seen: set[str] = set()
    data = {"findings": [], "skipped": []}
    for extra in ([], ["--local"]):
        import os
        env = {**os.environ,
               "CHANGWEI_DELIVERABLES_ROOT": str(ROOT.parent / "selftest_deliverables"),
               "CHANGWEI_CANNDEV": str(CANNDEV)}
        r = subprocess.run(
            [sys.executable, str(Path(__file__).parent / "check.py"),
             "--repo", str(ROOT), "--base", base, "--head", "HEAD", "--json",
             "--vendor", str(ROOT.parent / "selftest_vendor"), *extra],
            capture_output=True, text=True, env=env)
        if r.returncode != 0 or not r.stdout.strip():
            print(f"❌ check.py 跑挂了({'local' if extra else 'remote'} 趟):")
            print(r.stderr[-2500:])
            return 1
        d = json.loads(r.stdout)
        fired |= {f["rule"] for f in d["findings"]}
        asks |= {a["topic"] for a in d.get("judgment_asks", [])}
        ood_seen |= {f["rule"] for f in d["findings"] if f.get("out_of_diff")}
        if not extra:
            data = d
        else:
            data["skipped"] = [s for s in data["skipped"] if "组 15" not in s and "组 13" not in s]

    all_rules = set()
    for p in (Path(__file__).parent / "checkers").glob("*.py"):
        all_rules |= set(re.findall(r'rule="([^"]+)"', p.read_text(encoding="utf-8")))

    silent = sorted(all_rules - fired - set(KNOWN_CONDITIONAL))
    conditional = sorted(all_rules & set(KNOWN_CONDITIONAL) - fired)

    print(f"规则总数 {len(all_rules)}|夹具触发 {len(fired & all_rules)}|"
          f"哑弹 {len(silent)}|条件豁免 {len(conditional)}\n")
    if silent:
        print("❌ 哑弹(在必然触发的样本上没响,要查):")
        for s in silent:
            print(f"   {s}")
    else:
        print("✅ 无哑弹")
    if conditional:
        print("\n○ 条件豁免(已登记原因):")
        for s in conditional:
            print(f"   {s:<38} {KNOWN_CONDITIONAL[s]}")
    # 判断类待判题:每一类都必须在夹具上被提出来。
    # 这些是从"报错误结论的规则"改过来的,若在夹具上提不出题,等于那条检查凭空消失了。
    want_asks = {
        "整型除零可达性", "空 Tensor 可达性", "乘法溢出可达性",   # 原 g14/g01 的 🔴
        "收窄到 uint16_t 的上界", "32 位累加器",                  # 原 G1-narrowing/narrow-accumulator
        "rightPadding 的对齐基准",                                # 原 G2-rightpadding-wrong-base
        "浮点除法的兜底是不是多余的除零保护",                     # 原 G14-float-div-over-guarded
        "公共/框架文件改动", "该算子到底有没有 aclnn 对外接口",    # 原 G4×2 / G9
        "整型极值取负/abs 溢出", "产品隔离疑似传播",                 # 0730 新增(g14/g04)
        "grid_unnormal 性能是否达标取决于芯片对",
        "grid_unnormal 的 golden 实现是否与 README 计算公式一致",   # 组 9 L3                      # 组 22:灰区不猜
    }
    # topic 里带具体变量名,用前缀匹配
    miss_asks = sorted(w for w in want_asks if not any(a.startswith(w[:8]) for a in asks))
    print(f"\n判断类待判题 {len(want_asks) - len(miss_asks)}/{len(want_asks)} 类被提出"
          + (" ✅" if not miss_asks else f" ❌ 缺:{'、'.join(miss_asks)}"))

    # 锚点约束:夹具里有未改动文件上的 finding,必须被标成 diff 外
    print(f"锚点约束:标出 {len(ood_seen)} 类 diff 外 finding"
          + (" ✅" if ood_seen else " ⚠️ 夹具未覆盖到(新算子夹具全是新增文件),机制未被验证"))

    if data["skipped"]:
        print("\n⚠️ 夹具上被跳过的组:")
        for s in data["skipped"]:
            print(f"   {s}")
    return 1 if (silent or miss_asks) else 0


if __name__ == "__main__":
    sys.exit(main())