Skip to content

markleetw/reverse-due-diligence-skill

反向盡職調查(reverse due diligence)——求職者視角的公司調查。在接受 offer 或投入面試流程前,用公開資料把公司的財務體質、股價與股權、營收引擎、組織文化、低潮期與復原路徑查清楚,產出一份可存檔的 HTML 報告與一份面試提問清單。這個 skill 的簡稱是 rdd,使用者打 /rdd 就是要跑這套流程。Use this whenever the user is evaluating a job opportunity and wants to research the company behind it — triggers include /rdd, rdd, 反向盡職調查, 反向盡調, 調查這家公司, 我在面試某公司想先了解, 這份工作值不值得接, 幫我查某公司的財報與風評, 這家公司值得去嗎, background check on an employer, should I take this job, research this company before I interview, vet this employer. Also use when they name a company plus a role and ask what they should know about it, even if they never say the words "due diligence" or "rdd".

scripts/audit.py

View on GitHub
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Generic deterministic audit for RDD HTML reports.

Usage:
    python3 scripts/audit.py REPORT.html AUDIT_SPEC.json \
        [--renderer-template templates/report-shell.html]

The audit checks internal consistency and can also verify renderer parity with
the canonical report shell. It does not verify whether external facts are true;
source verification remains part of the research workflow.
"""
from __future__ import annotations

import argparse
import ast
import json
import operator
import re
import sys
from pathlib import Path
from typing import Any

DEFAULT_ALLOW_CONTEXT_TERMS = [
    "先前", "已更正", "已刪除", "已降級", "已移除", "已更新",
    "是錯的", "不可直接對照", "未能在", "找不到一手", "舊值",
    "不能主張", "不成立",
]

_BIN_OPS = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.truediv,
    ast.FloorDiv: operator.floordiv,
    ast.Mod: operator.mod,
    ast.Pow: operator.pow,
}
_UNARY_OPS = {ast.UAdd: operator.pos, ast.USub: operator.neg}
_CMP_OPS = {
    ast.Eq: operator.eq,
    ast.NotEq: operator.ne,
    ast.Lt: operator.lt,
    ast.LtE: operator.le,
    ast.Gt: operator.gt,
    ast.GtE: operator.ge,
}


def safe_eval(expression: str, variables: dict[str, float] | None = None) -> Any:
    """Evaluate a numeric/boolean expression without Python eval()."""
    variables = variables or {}
    node = ast.parse(expression, mode="eval").body

    def visit(n: ast.AST) -> Any:
        if isinstance(n, ast.Constant) and isinstance(n.value, (int, float, bool)):
            return n.value
        if isinstance(n, ast.Name) and n.id in variables:
            return variables[n.id]
        if isinstance(n, ast.BinOp) and type(n.op) in _BIN_OPS:
            return _BIN_OPS[type(n.op)](visit(n.left), visit(n.right))
        if isinstance(n, ast.UnaryOp) and type(n.op) in _UNARY_OPS:
            return _UNARY_OPS[type(n.op)](visit(n.operand))
        if isinstance(n, ast.Compare):
            left = visit(n.left)
            for op_node, right_node in zip(n.ops, n.comparators):
                op = _CMP_OPS.get(type(op_node))
                if op is None:
                    raise ValueError(f"unsupported comparison: {type(op_node).__name__}")
                right = visit(right_node)
                if not op(left, right):
                    return False
                left = right
            return True
        if isinstance(n, ast.BoolOp) and isinstance(n.op, (ast.And, ast.Or)):
            values = [bool(visit(v)) for v in n.values]
            return all(values) if isinstance(n.op, ast.And) else any(values)
        if (
            isinstance(n, ast.Call)
            and isinstance(n.func, ast.Name)
            and n.func.id == "abs"
            and len(n.args) == 1
            and not n.keywords
        ):
            return abs(visit(n.args[0]))
        raise ValueError(f"unsupported expression node: {type(n).__name__}")

    return visit(node)


def load_json(path: Path) -> dict[str, Any]:
    with path.open(encoding="utf-8") as fh:
        data = json.load(fh)
    if not isinstance(data, dict):
        raise ValueError("audit spec must be a JSON object")
    return data


def scan_claims(
    text: str,
    claims: list[dict[str, Any]],
    allow_terms: list[str],
    context_chars: int,
) -> list[str]:
    failures: list[str] = []
    allow_re = re.compile("|".join(re.escape(x) for x in allow_terms)) if allow_terms else None

    for item in claims:
        pattern = item["pattern"]
        reason = item.get("reason", pattern)
        flags = re.IGNORECASE if item.get("ignore_case") else 0
        for match in re.finditer(pattern, text, flags):
            lo = max(0, match.start() - context_chars)
            hi = min(len(text), match.end() + context_chars)
            context = text[lo:hi]
            if allow_re and allow_re.search(context):
                continue
            snippet = re.sub(r"\s+", " ", text[max(0, match.start()-45):match.end()+45])
            failures.append(f"[{reason}] …{snippet}…")
    return failures



def parse_extracted_number(raw: str, kind: str) -> float:
    """Normalize a captured numeric string for deterministic assertions."""
    value = (
        raw.strip()
        .replace(",", "")
        .replace(",", "")
        .replace("−", "-")
        .replace("-", "-")
        .replace("+", "+")
        .replace("%", "")
        .replace("%", "")
    )
    number = float(value)
    if kind == "percent":
        number /= 100.0
    elif kind != "number":
        raise ValueError(f"unsupported extracted value type: {kind}")
    return number


def extract_named_values(
    text: str,
    definitions: dict[str, dict[str, Any]],
) -> tuple[dict[str, float], list[str]]:
    """Extract report values by regex so assertions bind to what is displayed."""
    values: dict[str, float] = {}
    failures: list[str] = []

    for name, item in definitions.items():
        pattern = item["pattern"]
        flags = re.IGNORECASE if item.get("ignore_case") else 0
        matches = list(re.finditer(pattern, text, flags))
        if not matches:
            failures.append(f"named value {name!r} not found")
            continue
        if item.get("unique") and len(matches) != 1:
            failures.append(
                f"named value {name!r} expected one match, found {len(matches)}"
            )
            continue

        match = matches[0]
        group = item.get("group", 1)
        try:
            raw = match.group(group)
            kind = item.get("type", "number")
            value = parse_extracted_number(raw, kind)
            value *= float(item.get("scale", 1))
        except Exception as exc:
            failures.append(f"named value {name!r} could not be parsed: {exc}")
            continue

        values[name] = value

    return values, failures


def check_document_envelope(html: str) -> list[str]:
    """Require a complete standards-mode HTML document, not an inner fragment."""
    failures: list[str] = []
    source = html.lstrip("\ufeff \t\r\n")

    if not re.match(r"(?is)^<!doctype\s+html\s*>", source):
        failures.append("document must begin with <!DOCTYPE html>")

    tags = {
        "html_open": re.search(r"(?is)<html\b[^>]*>", source),
        "head_open": re.search(r"(?is)<head\b[^>]*>", source),
        "head_close": re.search(r"(?is)</head\s*>", source),
        "body_open": re.search(r"(?is)<body\b[^>]*>", source),
        "body_close": re.search(r"(?is)</body\s*>", source),
        "html_close": re.search(r"(?is)</html\s*>", source),
    }
    for name, match in tags.items():
        if match is None:
            failures.append(f"missing required document tag: {name}")

    if not failures:
        order = [
            tags["html_open"].start(),
            tags["head_open"].start(),
            tags["head_close"].start(),
            tags["body_open"].start(),
            tags["body_close"].start(),
            tags["html_close"].start(),
        ]
        if order != sorted(order):
            failures.append("document tags are not in html > head > body order")

    if len(re.findall(r"(?is)</html\s*>", source)) != 1:
        failures.append("document must contain exactly one </html> closing tag")
    if not re.search(r"(?is)</html\s*>\s*$", source):
        failures.append("</html> must be the final non-whitespace content")

    return failures


REPORT_DATA_START = "/* RDD_REPORT_DATA_START */"
REPORT_DATA_END = "/* RDD_REPORT_DATA_END */"


def extract_renderer_parts(html: str, *, label: str) -> tuple[str, str, str]:
    """Return immutable renderer parts: CSS, JS prefix, JS suffix."""
    # Strip HTML comments first so documentation such as literal <style> text
    # cannot be mistaken for the actual renderer stylesheet.
    source = re.sub(r"<!--[\s\S]*?-->", "", html)
    style_matches = list(re.finditer(r"<style>([\s\S]*?)</style>", source))
    script_matches = list(re.finditer(r"<script>([\s\S]*?)</script>", source))
    if len(style_matches) != 1 or len(script_matches) != 1:
        raise ValueError(
            f"{label}: expected exactly one inline <style> and one <script> block "
            f"after removing HTML comments; found {len(style_matches)} style / "
            f"{len(script_matches)} script"
        )

    style_match = style_matches[0]
    script_match = script_matches[0]
    script = script_match.group(1)
    start = script.find(REPORT_DATA_START)
    end = script.find(REPORT_DATA_END)
    if start < 0 or end < 0 or end <= start:
        raise ValueError(
            f"{label}: missing renderer data markers "
            f"{REPORT_DATA_START!r} / {REPORT_DATA_END!r}"
        )

    prefix = script[:start]
    suffix = script[end + len(REPORT_DATA_END):]
    return style_match.group(1), prefix, suffix


def check_renderer_parity(report_html: str, template_html: str) -> list[str]:
    """Detect accidental CSS or renderer-library drift."""
    failures: list[str] = []
    try:
        report_style, report_prefix, report_suffix = extract_renderer_parts(
            report_html, label="report"
        )
        template_style, template_prefix, template_suffix = extract_renderer_parts(
            template_html, label="template"
        )
    except ValueError as exc:
        return [str(exc)]

    if report_style != template_style:
        failures.append(
            "renderer CSS differs from templates/report-shell.html; "
            "keep the canonical <style> block unchanged"
        )
    if report_prefix != template_prefix or report_suffix != template_suffix:
        failures.append(
            "renderer JavaScript differs from templates/report-shell.html; "
            "only edit the block between RDD_REPORT_DATA_START/END"
        )
    return failures


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("report", type=Path)
    parser.add_argument("spec", type=Path)
    parser.add_argument(
        "--renderer-template",
        type=Path,
        help="canonical report shell; fail if CSS or renderer JS drifts",
    )
    args = parser.parse_args()

    html = args.report.read_text(encoding="utf-8")
    spec = load_json(args.spec)

    correction_marker = spec.get("correction_marker", "已移除或更正的主張")
    idx = html.find(correction_marker)
    body = html[:idx] if idx >= 0 else html

    allow_terms = spec.get("allow_context_terms", DEFAULT_ALLOW_CONTEXT_TERMS)
    context_chars = int(spec.get("allow_context_chars", 160))
    failures: list[str] = []

    print("═══ Document envelope ═══")
    envelope_failures = check_document_envelope(html)
    if envelope_failures:
        for failure in envelope_failures:
            print("  ✗", failure)
        failures.extend(envelope_failures)
    else:
        print("  ✓ complete standards-mode HTML document")

    claims = list(spec.get("stale_claims", [])) + list(spec.get("resolved_claims", []))
    claim_failures = scan_claims(body, claims, allow_terms, context_chars)
    if claim_failures:
        print("═══ Stale / resolved claim scan ═══")
        for failure in claim_failures:
            print("  ✗", failure)
        failures.extend(claim_failures)

    canonical = spec.get("canonical_values", [])
    if canonical:
        print("\n═══ Canonical values ═══")
    for item in canonical:
        value = str(item["value"])
        label = item.get("label", value)
        minimum = int(item.get("min_occurrences", 1))
        count = body.count(value)
        ok = count >= minimum
        print(f"  {'✓' if ok else '✗'} {label}: {value!r} — {count} occurrence(s), need {minimum}")
        if not ok:
            failures.append(f"missing canonical value: {label} ({value})")

    named_definitions = spec.get("values", {})
    named_values: dict[str, float] = {}
    if named_definitions:
        print("\n═══ Extracted report values ═══")
        named_values, value_failures = extract_named_values(body, named_definitions)
        if value_failures:
            for failure in value_failures:
                print("  ✗", failure)
            failures.extend(value_failures)
        for name, value in named_values.items():
            print(f"  ✓ {name} = {value:g}")

    assertions = spec.get("assertions", [])
    if assertions:
        print("\n═══ Report-bound assertions ═══")
    for item in assertions:
        label = item.get("label", item["expression"])
        expression = item["expression"]
        try:
            ok = bool(safe_eval(expression, named_values))
        except Exception as exc:
            ok = False
            print(f"  ✗ {label}: invalid expression ({exc})")
            failures.append(f"invalid report-bound assertion: {label}")
            continue
        print(f"  {'✓' if ok else '✗'} {label}")
        if not ok:
            failures.append(f"report-bound assertion failed: {label}")

    if args.renderer_template:
        print("\n═══ Renderer parity ═══")
        template_html = args.renderer_template.read_text(encoding="utf-8")
        renderer_failures = check_renderer_parity(html, template_html)
        if renderer_failures:
            for failure in renderer_failures:
                print("  ✗", failure)
            failures.extend(renderer_failures)
        else:
            print("  ✓ CSS and renderer JavaScript match canonical template")

    arithmetic = spec.get("arithmetic", [])
    if arithmetic:
        print("\n═══ Legacy literal arithmetic assertions ═══")
    for item in arithmetic:
        label = item.get("label", item["expression"])
        expression = item["expression"]
        try:
            ok = bool(safe_eval(expression))
        except Exception as exc:
            ok = False
            print(f"  ✗ {label}: invalid expression ({exc})")
            failures.append(f"invalid arithmetic assertion: {label}")
            continue
        print(f"  {'✓' if ok else '✗'} {label}")
        if not ok:
            failures.append(f"arithmetic assertion failed: {label}")

    print(f"\n{'═'*40}\nFailure count: {len(failures)}")
    return 1 if failures else 0


if __name__ == "__main__":
    sys.exit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall