[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BZT4XMS668V2EVW5MEH6GY":3,"skill-same:01M7BZT4XMS668V2EVW5MEH6GY":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M7BZT4XMS668V2EVW5MEH6GY","reflow-profile-compliance-toolkit",null,"Deterministic handbook-grounded retrieval and thermocouple computations for reflow profile compliance outputs such as ramp, TAL, peak, feasibility, and selection.","linyouxue\u002Fskill-repair-benchmark","linyouxue","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F216151464?v=4","01M7BJEVCXKD74KH6FG9CBVSQB","林宥学","01M7BJEVE02NP217V93BKZFC0J",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fevaluation\u002Fresults\u002FSkillGrad\u002Fopus47_clean_20261016_partial14\u002Ftasks\u002Fmanufacturing-equipment-maintenance\u002Frepaired_skill\u002Freflow-profile-compliance-toolkit\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: reflow-profile-compliance-toolkit\ndescription: Deterministic handbook-grounded retrieval and thermocouple computations for reflow profile compliance outputs such as ramp, TAL, peak, feasibility, and selection.\n---\n\n\n\nWhen to invoke:\n1. Whenever the task involves reflow related questions from thermocouple data, MES data or defect data and handbook-defined regions\u002Fwindows\u002Flimits.\n2. Extract numeric limits \u002F temperature regions \u002F timing windows \u002F margins \u002F feasibility rules from handbook.pdf.\n3. Compute run-level metrics from time–temperature thermocouple traces in a deterministic way.\n\nThis skill is designed to make the agent:\n- retrieve the right definitions from the handbook, and\n- compute metrics with predictable tie-breaks and interpolation.\n\n\n\n## 0. Handbook retrieval is a prerequisite\n\nEvery downstream section (TC selection, ramp, TAL, peak, feasibility, best-run\nranking, anomaly scan) depends on handbook-grounded thresholds. If the\nhandbook was not read, those sections operate on fabricated inputs and the\nanomaly scan cannot distinguish a wrong constant from a wrong rule. Do this\nfirst.\n\n**Reader retry queue** — try in order; move to the next on ImportError,\nFileNotFoundError, empty-text extraction (\u003C 50 chars returned), or encryption\nerror:\n\n1. `pypdf`\n2. `PyPDF2`\n3. `pdfplumber`\n4. `pdfminer.six`\n5. Shell `pdftotext` (poppler-utils, via `subprocess`)\n6. Claude's native PDF ingestion (attach the PDF file to the model turn)\n7. OCR fallback — `pdf2image` + `pytesseract`\n\nA `pip install \u003Creader>` is an acceptable intermediate step. **At least 3\nreaders must be attempted** before concluding the handbook is unreadable.\n\n**All-readers-fail rule:** if every reader genuinely fails, set every\nhandbook-derived `cfg` entry to `None` and emit `null` (not a pass\u002Ffail\nverdict) for every downstream metric that depended on it. Do NOT substitute\n\"typical reflow\" constants from memory — not even directionally plausible\nones. A memory-prior is a fabrication regardless of how it looks.\n\n**Parameter-grounding comment discipline:** every numeric value in `cfg` must\nhave an adjacent code comment with the verbatim handbook sentence that\nsupports it. A bare number with no quote is suspect and must become `None`.\n\n```python\n# minimal sketch — see ..\u002Freferences\u002Fhandbook-retrieval.md for the full\n# branched algorithm (ImportError, empty text, encrypted, all-readers-fail)\ntext, attempts = try_read_handbook(\"\u002Fapp\u002Fdata\u002Fhandbook.pdf\")\nif text is None:\n    assert len(attempts) >= 3, \"try more readers before giving up\"\n    cfg = {k: None for k in HANDBOOK_KEYS}\n    cfg[\"_handbook_status\"] = \"unreadable\"\nelse:\n    cfg = extract_cfg_from_handbook_text(text)   # with grounding comments\n    cfg[\"_handbook_status\"] = \"ok\"\n```\n\nDecision rule: if after a failed handbook read your reasoning contains\n\"typical reflow is …\", \"the standard limit is …\", or \"I'll assume …\", that\nis a memory-prior substituting for the handbook — delete the constants, re-run\nthe retry queue, and if it still fails, emit `null`.\n\nRead `..\u002Freferences\u002Fhandbook-retrieval.md` when any threshold the task depends\non comes from a PDF handbook\u002Fspec. Skip when every needed parameter is given\ninline in the task prompt or in a non-PDF structured file.\n\n\n\n## Handbook \"where to look\" checklist (after retrieval succeeds)\n\nSearch the extracted handbook text for these common sections\u002Ftables:\n- Thermal profile overview: defines \"preheat\", \"soak\", \"reflow\", \"cooling\".\n- Ramp rate guidance: \"ramp\", \"slope\", \"°C\u002Fs\", \"C\u002Fs\".\n- Liquidus & wetting time: \"liquidus\", \"time above liquidus\", \"TAL\", \"wetting\".\n- Peak temperature guidance: \"peak\", \"minimum peak\", \"margin above liquidus\".\n- Conveyor \u002F dwell feasibility: \"conveyor speed\", \"dwell time\", \"heated length\", \"zone length\", \"time-in-oven\", oven zone-count prefixes (e.g. `8Z`, `10Z`).\n- Thermocouple placement: \"cold spot\", \"worst case\", \"representative sensor\", named locations such as `largest_mass` \u002F `coldest_point` \u002F `smallest_mass`. Cross-check with the TC dataset's `location`\u002F`position` column so the handbook's named placement maps to a concrete `tc_id`. The handbook may name a location for one metric only — do not assume it governs every metric.\n\nGoal: extract a compact config object from the handbook and use it for all\ncomputations. **Every value carries an adjacent handbook quote in a comment**\n— if no quote can be produced, the value stays `None` and the dependent\nmetric emits `null`:\n\n```python\ncfg = {\n    # Handbook §X.Y: \"\u003Cverbatim preheat region sentence>\"\n    #   {\"type\":\"temp_band\", \"tmin\":..., \"tmax\":...}\n    #   or {\"type\":\"zone_band\", \"zones\":[...]}\n    #   or {\"type\":\"time_band\", \"t_start_s\":..., \"t_end_s\":...}\n    \"preheat_region\": None,\n\n    # Handbook §X.Y: \"\u003Cverbatim ramp-rate limit sentence>\"\n    \"ramp_limit_c_per_s\": None,\n\n    \"tal_threshold_c_source\": \"solder_liquidus_c\",   # if MES provides it\n    # Handbook §X.Y: \"\u003Cverbatim TAL lower bound sentence>\"\n    \"tal_min_s\": None,\n    # Handbook §X.Y: \"\u003Cverbatim TAL upper bound sentence>\"\n    \"tal_max_s\": None,\n\n    # Handbook §X.Y: \"\u003Cverbatim peak-margin sentence>\"\n    \"peak_margin_c\": None,\n\n    # Per-metric representative-TC locations from the handbook. Each is\n    # independent; leaving one None means fall back to generic per-TC\n    # reduction for that metric. Do NOT reuse a named placement across\n    # metrics without an explicit handbook sentence. See section 4.\n    \"ramp_rep_location\": None,\n    \"peak_rep_location\": None,\n    \"tal_rep_location\":  None,\n\n    # Conveyor feasibility rule-object; see section 6. Every parameter inside\n    # must likewise carry a handbook quote.\n    \"conveyor_rule\": None,\n}\n```\n\nIf the handbook provides multiple applicable constraints, implement all and\nuse the stricter constraint (document the choice in code comments).\n\n\n\nDeterministic thermocouple computation recipes\n\n1. Sorting and de-dup rules\nAlways sort samples by time before any computation:\n```python\ndf_tc = df_tc.sort_values([\"run_id\",\"tc_id\",\"time_s\"], kind=\"mergesort\")\n```\nIgnore segments where `dt \u003C= 0` (non-monotonic timestamps).\n\n2. Segment slope (ramp rate)\nFinite-difference slope on consecutive samples:\n- `s_i = (T_i - T_{i-1}) \u002F (t_i - t_{i-1})` for `dt > 0`\n- the \"max ramp\" is `max(s_i)` over the region.\n\nRegion filtering patterns:\n- Temperature band region: only include segments where **both endpoints** satisfy `tmin \u003C= T \u003C= tmax`.\n- Zone band region: filter by `zone_id in zones`.\n- Time band region: filter by `t_start_s \u003C= time_s \u003C= t_end_s`.\n\nRobust implementation (temperature-band example):\n```python\ndef max_slope_in_temp_band(df_tc, tmin, tmax):\n    g = df_tc.sort_values(\"time_s\")\n    t = g[\"time_s\"].to_numpy(dtype=float)\n    y = g[\"temp_c\"].to_numpy(dtype=float)\n    best = None\n    for i in range(1, len(g)):\n        dt = t[i] - t[i-1]\n        if dt \u003C= 0:\n            continue\n        if (tmin \u003C= y[i-1] \u003C= tmax) and (tmin \u003C= y[i] \u003C= tmax):\n            s = (y[i] - y[i-1]) \u002F dt\n            best = s if best is None else max(best, s)\n    return best  # None if no valid segments\n```\n\n3. Time above threshold with linear interpolation\nFor wetting\u002FTAL-type metrics, compute time above a threshold `thr` using segment interpolation.\n\nTwo defensible interpretations of \"time above threshold\" exist — check the handbook wording before choosing:\n- **Integral TAL** (default below): sum of every segment where temperature is above `thr`, including segments after a cooling discontinuity that briefly re-crosses. Matches \"total time above the melting point\".\n- **Contiguous TAL** (first-crossing to last-crossing): one window per run, from the first upward crossing of `thr` to the last downward crossing. Matches \"duration above liquidus\" when the handbook describes a single reflow dwell.\n\nIf the integral interpretation causes a mass compliance failure (e.g. > 80% of runs fall outside the TAL window), re-read the handbook for which interpretation it endorses, AND confirm the window itself (`tal_min_s`, `tal_max_s`) has a handbook quote and is not a memory-prior, before letting the verdict cascade into ranking.\n\n```python\ndef time_above_threshold_s(df_tc, thr):\n    g = df_tc.sort_values(\"time_s\")\n    t = g[\"time_s\"].to_numpy(dtype=float)\n    y = g[\"temp_c\"].to_numpy(dtype=float)\n    total = 0.0\n    for i in range(1, len(g)):\n        t0, t1 = t[i-1], t[i]\n        y0, y1 = y[i-1], y[i]\n        if t1 \u003C= t0:\n            continue\n\n        # fully above\n        if y0 > thr and y1 > thr:\n            total += (t1 - t0)\n            continue\n\n        # crossing: interpolate crossing time\n        crosses = (y0 \u003C= thr \u003C y1) or (y1 \u003C= thr \u003C y0)\n        if crosses and (y1 != y0):\n            frac = (thr - y0) \u002F (y1 - y0)\n            tcross = t0 + frac * (t1 - t0)\n            if y0 \u003C= thr and y1 > thr:\n                total += (t1 - tcross)\n            else:\n                total += (tcross - t0)\n    return total\n```\n\n4. Representative sensor selection — per metric, not per run\n\n**Default: different metrics have different governing worst-case TCs; use the same TC across metrics only when the handbook explicitly says so.** The handbook naming one location (e.g. `largest_mass`) is not a license to apply that one TC to every metric — it only governs the metric whose physical worst case matches the named location.\n\n**Setup prose vs. reducer prose — classify every handbook sentence before mapping to `cfg[\"\u003Cmetric>_rep_location\"]`.** A handbook sentence can be either (i) a *measurement-setup* instruction naming where probes should be *placed* during a thermal survey, or (ii) a *reducer* instruction naming which TC should *govern* a specific metric. Only (ii) licenses setting `cfg[\"\u003Cmetric>_rep_location\"]`.\n\n- **Setup prose — a noun phrase listing placements.** Signature: lists multiple locations without an imperative verb; often \"may be measured by thermocoupling a lead on …\", \"probes shall be placed at …\", \"thermocouples on \u003Cloc A> and \u003Cloc B>\". Examples: *\"may be measured by thermocoupling a lead on the largest and smallest device\"*, *\"thermocouples on exposed and shielded locations\"*. This tells the operator **where to place probes**; it does NOT designate any single TC as the representative for any single metric. Leave `cfg[\"\u003Cmetric>_rep_location\"] = None` and fall back to generic per-TC reduction.\n- **Reducer prose — an imperative verb pointing at one metric and one location.** Signature: single location + metric name + imperative verb. Examples: *\"use the coldest TC for the peak check\"*, *\"the ramp limit applies to the fastest-heating thermocouple\"*, *\"TAL is reported from the largest-mass sensor\"*. This DOES license `cfg[\"\u003Cmetric>_rep_location\"] = \u003Clocation>` for that one metric only.\n\nIf the only quotable sentence is setup prose, every `*_rep_location` stays `None`; the per-metric physical worst case (ramp → fastest-heating, peak → coolest-at-peak, TAL → both bounds via per-TC max\u002Fmin) governs instead. See `..\u002Freferences\u002Frepresentative-tc-selection.md` for the full classifier with worked positive and negative examples.\n\nPer-metric worst-case direction (quick table):\n\n| Metric | Governing worst case | Reducer across matching TCs |\n|---|---|---|\n| Ramp (upper limit) | fastest-heating | `max`, tie-break smallest `tc_id` |\n| Peak (minimum peak ≥ liquidus + margin) | coolest-at-peak | `min`, tie-break smallest `tc_id` |\n| TAL upper bound (overshoot) | hottest \u002F longest-above-liquidus | `max` TAL across TCs |\n| TAL lower bound (minimum dwell) | coolest | `min` TAL across TCs |\n\nPre-coding enumeration: before writing any reducer, for each per-run question write a one-line comment stating (i) what \"worst case\" means physically for this metric, (ii) which handbook-named TC location (if any) satisfies it via a *reducer* sentence (not setup prose), and (iii) the verbatim handbook sentence that supports (ii). If (iii) is empty OR is setup prose, use generic per-TC reduction and leave `cfg[\"\u003Cmetric>_rep_location\"] = None`.\n\n```python\n# generic sketch — one reducer per metric, not one TC for the whole run\ndef reduce_per_metric(tc_rows, metric_fn, direction, rep_location):\n    # direction: \"max\" (ramp, tal_upper) or \"min\" (peak, tal_lower)\n    pool = tc_rows\n    if rep_location is not None:\n        matched = tc_rows[tc_rows[\"location\"] == rep_location]\n        if not matched.empty:\n            pool = matched\n    per_tc = [(metric_fn(grp), tc_id) for tc_id, grp in pool.groupby(\"tc_id\")]\n    per_tc = [(v, t) for v, t in per_tc if v is not None]\n    if not per_tc:\n        return (None, None)\n    per_tc.sort(key=lambda x: ((-x[0] if direction == \"max\" else x[0]), x[1]))\n    return per_tc[0]\n```\n\n**Trial alternative policies when any red-flag fires.** When the pre-ship scan reports any metric with `\u003C 10 %` or `> 80 %` violators, do NOT ship on the first interpretation. Re-compute Q1\u002FQ2\u002FQ3 violator counts under at least two additional TC-selection policies — e.g. (α) a single consistent channel across metrics (handbook-named placement applied to all); (β) per-metric physical worst case per the table above; (γ) run-level max\u002Fmin\u002Fmean across all TCs. The policy that both quotes a *reducer* sentence AND produces a plausible distribution (roughly 5–30 % non-compliance per metric for typical reflow data) is the one to ship. Record the three distributions in a comment next to the final choice.\n\nDecision rule: if the handbook names `largest_mass`\u002F\"coldest point\" only, use it ONLY for peak (and TAL lower bound if applicable). Do NOT reuse it for ramp or TAL upper bound — those need the fastest-heating \u002F hottest channel. Consistency of `tc_id` across ramp\u002FTAL\u002Fpeak is NOT a goal.\n\nRead `..\u002Freferences\u002Frepresentative-tc-selection.md` when the handbook mentions any TC-placement by name OR when the task has questions for more than one of ramp\u002FTAL\u002Fpeak. Skip when the handbook makes no placement statement anywhere and only one of ramp\u002FTAL\u002Fpeak is asked.\n\n5. Peak and margin\nPer TC: `peak_tc = max(temp_c)`. Run-level peak uses the per-metric reducer in section 4 with `direction=\"min\"` and `rep_location = cfg[\"peak_rep_location\"]`. Requirement: `required_peak = liquidus + peak_margin`.\n\n6. Conveyor feasibility (grounded derivation, never fabricate)\nRepresent the handbook rule as a structured object and compute `required_min_speed_cm_min` only if every input is grounded in handbook text or oven_model geometry.\n\nGrounded templates:\n- Minimum dwell across effective heated length: `speed_max_cm_min = (L_eff_cm \u002F t_min_s) * 60`\n- Maximum time-in-oven across length:         `speed_min_cm_min = (L_eff_cm \u002F t_max_s) * 60`\n\nDeriving `L_eff_cm` when the handbook does not state it directly:\n- Parse the oven_model string: a leading digit prefix is the zone count (e.g. `8Z…` → 8 zones, `10Z…` → 10 zones). Multiply zone count × handbook zone length.\n- Use TAL min\u002Fmax as the dwell bound only when the handbook ties conveyor dwell to TAL; otherwise find the handbook's own dwell\u002Ftime-in-oven bound.\n\n**Parameter-grounding prerequisite (applies to every variable in the chosen formula — `L_eff_cm`, `zone_length_cm`, `t_min_s`, `t_max_s`, any `loading_factor` \u002F `boards_per_min` term):** each must have an adjacent code comment quoting the handbook sentence that defines it. If any variable is a bare number with no quote, treat the whole formula as fabricated: emit `required_min_speed_cm_min = null` and `meets = false`.\n\n**Operator-precedence \u002F dimensional check (PDF OCR is a source of operator drift — `×`, `÷`, parentheses are routinely dropped or misread).** After translating the handbook sentence to code, instantiate with one or two sample values and verify the units reduce to the expected output (`cm\u002Fmin` for `required_min_speed_cm_min`). A dimensionless parameter (e.g. `loading_factor`) must enter as a divisor or multiplier such that the units balance. If `(boards\u002Fmin) × cm \u002F loading_factor` → `cm\u002Fmin` only when `loading_factor` is dimensionless and placed as a divisor — if the computed magnitude is implausibly tiny or implausibly large with every run clearing\u002Ffailing trivially, re-read the handbook and try the opposite arrangement (divisor ↔ multiplier) before shipping.\n\n```python\n# generic sketch — every input must carry a handbook quote in a comment\n# Handbook §X.Y: \"\u003Cverbatim zone length sentence>\"\nzone_length_cm = ...\n# Handbook §X.Y: \"\u003Cverbatim dwell \u002F time-in-oven bound sentence>\"\nt_max_s = ...\nzone_count = int(re.match(r\"(\\d+)Z\", oven_model).group(1))\nL_eff_cm   = zone_count * zone_length_cm\nspeed_min  = (L_eff_cm \u002F t_max_s) * 60   # cm\u002Fmin — dimensional check: cm \u002F s * 60 = cm\u002Fmin ✓\n```\n\nHard rule — do NOT invent a formula. If `L_eff_cm` or the dwell bound cannot be grounded in the handbook or in oven_model geometry, emit:\n- `required_min_speed_cm_min = null`\n- `meets = false`\n- a code comment stating which input was ungrounded.\n\nDecision rule: if your own narrative contains \"I'll assume…\", \"this seems suspicious\", \"probably all runs clear this\", or \"typical loading factor is …\", that is a stop signal — the formula is fabricated. Return to the handbook (section 0 retry queue) or emit null.\n\nRead `..\u002Freferences\u002Fconveyor-feasibility.md` when the handbook does not spell out a speed rule for the oven_model in use, when `L_eff_cm`\u002Fdwell bounds must be derived, OR when the handbook sentence used arithmetic operators (`×`, `÷`, parentheses) that may have drifted during OCR. Skip when the handbook gives a direct `oven_model → required_speed` mapping in plain-text table form.\n\n7. Ranking \u002F \"best run\" questions\nWhen the task asks for the best \u002F top \u002F recommended \u002F highest-yielding run (per family or overall), the prompt wording decides whether compliance is a hard gate or a quality signal:\n\n- **Strict scope** (\"best **compliant** run\", \"top performer that meets all specs\"): rank only the mask=True subset where `ramp_ok AND tal_ok AND peak_ok AND feasibility_ok`; emit `null` for groups with no compliant runs.\n- **Soft scope** (\"best based on **quality and efficiency**\", \"recommended run\", unqualified \"top performer\"): rank ALL runs in the group by a composite score (yield desc, throughput desc, `compliance_violation_count` asc as tie-break\u002Fpenalty, `run_id` asc). Compliance is a signal, not a gate. Only emit `null` when the group has zero runs at all.\n\n```python\n# generic sketch — mode is \"strict\" or \"graded\"; both branches reuse the mask\nmask = df[\"ramp_ok\"] & df[\"tal_ok\"] & df[\"peak_ok\"] & df[\"feasibility_ok\"]\ndf[\"_violations\"] = (~df[[\"ramp_ok\",\"tal_ok\",\"peak_ok\",\"feasibility_ok\"]]).sum(axis=1)\npool = df[mask] if mode == \"strict\" else df\nbest = (pool.sort_values(\n            quality_cols + ([\"_violations\"] if mode == \"graded\" else []) + [\"run_id\"],\n            ascending=[False]*len(quality_cols) + ([True] if mode == \"graded\" else []) + [True])\n            .groupby(group_col).head(1))\n```\n\nDecision rule: a per-group sanity log reading `0\u002FN compliant` is a stop signal — re-read the task prompt to decide strict vs. graded before writing output. Never pick a \"best\" run that is listed as a violator in your own earlier Q1–Q4 outputs if the prompt is in strict scope.\n\nRead `..\u002Freferences\u002Fbest-run-ranking.md` when the task asks for a best \u002F top \u002F recommended run per group AND either (i) the prompt wording is ambiguous between strict and graded, or (ii) a strict mask would wipe out ≥ 1 group. Skip when the prompt explicitly says \"compliant\" and every group has ≥ 1 compliant run.\n\n\n\nOutput construction guardrails\n\n1. Sorting\n- Lists: sort by primary ID (run_id \u002F board_family) lexicographically.\n- Dicts keyed by ID: emit in sorted key order.\n\n2. Rounding and NaNs\n- Round floats to 2 decimals.\n- Never emit NaN\u002FInf; use `null`.\n\n```python\ndef r2(x):\n    if x is None:\n        return None\n    if isinstance(x, float) and (math.isnan(x) or math.isinf(x)):\n        return None\n    return float(round(float(x), 2))\n```\n\n3. Missing thermocouple data OR ungrounded threshold\nIf a run has no TC records (or no valid segments for a metric), set numeric outputs to `null`, and avoid claiming \"pass\". The same rule applies when the handbook threshold for that metric is `None` (ungrounded): emit `null` for the metric, never a pass\u002Ffail verdict derived from a memory-prior.\n\n\n## Minimal end-to-end scaffold\n\n```python\nimport os, json, math, re\nimport pandas as pd\n\nDATA_DIR = \"\u002Fapp\u002Fdata\"\nOUT_DIR  = \"\u002Fapp\u002Foutput\"\n\nruns = pd.read_csv(os.path.join(DATA_DIR, \"mes_log.csv\"))\ntc   = pd.read_csv(os.path.join(DATA_DIR, \"thermocouples.csv\"))\n\nruns[\"run_id\"] = runs[\"run_id\"].astype(str)\ntc[\"run_id\"]   = tc[\"run_id\"].astype(str)\ntc[\"tc_id\"]    = tc[\"tc_id\"].astype(str)\n\nruns = runs.sort_values([\"run_id\"], kind=\"mergesort\")\ntc   = tc.sort_values([\"run_id\",\"tc_id\",\"time_s\"], kind=\"mergesort\")\n\n# 0) Retrieve handbook text via the reader retry queue (section 0 above \u002F\n#    ..\u002Freferences\u002Fhandbook-retrieval.md). If all readers fail, every\n#    handbook-derived cfg entry is None and every dependent metric emits null.\n# 1) Build cfg with grounding-comment discipline (every value has a handbook\n#    quote in a comment, or it stays None).\ncfg = {...}\n\n# 2) Compute per-run metrics deterministically with stable tie-breaks and\n#    interpolation. For any metric whose threshold is None, emit null — do NOT\n#    fall back to a memory-prior.\n#    Use the PER-METRIC representative-TC rule (section 4) — ramp, TAL, peak\n#    may select different tc_ids; that is expected.\n# 3) Build JSON objects with sorted IDs and 2dp rounding.\n# 4) For \"best run\" questions, pick strict vs. graded mode by prompt wording (section 7).\n# 5) Write outputs into \u002Fapp\u002Foutput.\n```\n\n---\n\nSanity checks before writing outputs\n\nMechanical:\n- ID fields are strings.\n- Arrays sorted lexicographically.\n- Floats rounded to 2 decimals.\n- No NaN\u002FInf in JSON.\n- Sensor selection uses deterministic tie-breaks AND respects the handbook's named placement for the metric whose physical worst case matches (section 4).\n- Any \"time above threshold\" uses interpolation (not naive threshold counting).\n\nSemantic — run in this order; do not skip:\n\n- **(1) Handbook-grounding check (precedes everything else).** For every numeric threshold used in a verdict in this run's outputs (`ramp_limit_c_per_s`, `tal_min_s`, `tal_max_s`, `peak_margin_c`, `preheat_region` tmin\u002Ftmax, feasibility inputs `L_eff_cm` \u002F `t_min_s` \u002F `t_max_s` \u002F `zone_length_cm` \u002F any `loading_factor`), confirm there is an adjacent code comment quoting the handbook sentence that defines it. If any threshold is a bare number with no quote, set it to `None` and change the per-metric output to `null`. **On ANY mass-fail or near-zero signal flagged in checks 3\u002F4 below, re-run this check first on the specific threshold driving the verdict** — if that threshold is ungrounded, it is the suspect, not the TC-selection rule or TAL interpretation; do NOT branch into (4) until (1) is clean.\n\n- **(2) Narrative hedge check — scan for a class, not a fixed phrase list.** The hedge is any phrase in one of three classes, not a literal match from a catalogue:\n    - *Outside-expectation adjectives* (synonym family of \"suspicious\"): \"suspicious\", \"surprising\", \"unusual\", \"unusually extreme\", \"unexpected\", \"weird\", \"strange\", \"odd\", \"off\", \"implausible\". A near-synonym from this family counts (e.g. \"unusually extreme numbers\" from iter_4 shares the mechanism with the catalogued \"this seems suspicious\" and must trip the scan).\n    - *Hedging modals \u002F memory-prior substitutions*: \"probably\", \"might\", \"I'll assume\", \"I think\", \"typical reflow is …\", \"the standard limit is …\", \"the handbook doesn't say directly\".\n    - *Rationalisations that explain away an anomaly*: \"real production anomaly\", \"systemic production pattern\", \"the data is just unusual\", \"that's just how reflow works\", \"the process is just running hot\", \"genuine over-cooked profiles\".\n   Any match: stop, re-open the handbook on the specific concept, and re-run the policy \u002F interpretation decision — do NOT ship behind the hedge.\n\n- **(3) Mechanical quantitative-anomaly scan (no judgement call).** Immediately after per-run verdicts are computed, emit a one-line summary of violator counts across the per-run questions, e.g. `Q1: X\u002FN violators, Q2: Y\u002FN violators, Q3: Z\u002FN violators`. If any count is `\u003C 0.10 * N` (near-zero) or `> 0.80 * N` (mass-fail), the scan has fired — no judgement call. First re-run check (1) on the threshold driving the fired verdict; only after (1) is clean, proceed to check (4).\n\n- **(4) Paired quantitative-anomaly scan.** When two metrics share a selection rule (same TC-selection policy, same TAL interpretation, same feasibility arrangement) and show *asymmetric* flag rates — one metric `\u003C 10 %` violators AND another `> 80 %` violators — the shared rule is miscalibrated per metric, not the data. Hard stop: re-examine the shared rule per metric (see `..\u002Freferences\u002Frepresentative-tc-selection.md` for the trial-alternative-policies procedure) before shipping. **Prerequisite:** confirm via (1) that both metrics' thresholds are handbook-grounded; if either is a memory-prior, the apparent asymmetry is an artifact of the wrong constant.\n\n- **(5) Per-question spot-check must compare against an alternative interpretation.** An arithmetic spot check on the already-chosen policy only verifies *computation*, not *interpretation* — it is tautological against the policy that produced the number. For each per-run question type, re-compute the same representative cell under at least ONE alternative interpretation and compare: (α) different TC-selection policy for Q1\u002FQ2\u002FQ3 (fastest-heating vs. coolest vs. run-level max\u002Fmin\u002Fmean); (β) different TAL window reading (integral vs. contiguous) for TAL; (γ) different operator arrangement (divisor ↔ multiplier) for feasibility. If the two outputs differ dramatically (e.g. 5\u002FN vs. 51\u002FN violators), the policy choice is driving the verdict and must be re-examined before shipping. For \"best run\" picks, verify compliance \u002F non-null emission against the prompt mode (section 7).\n\n## Common pitfalls\n\n- **Hard-coding handbook constants from memory after a failed PDF read.** A single reader failure (ImportError, FileNotFoundError, empty text, encryption) is NOT a license to fall back to \"typical reflow\" priors (TAL 30–60 s, ramp 2 °C\u002Fs, margin +20 °C, invented `loading_factor`). The retry queue (section 0) requires ≥ 3 reader attempts, and if all genuinely fail, every handbook-derived threshold is `None` and every dependent verdict is `null`. Any `cfg` value lacking an adjacent handbook-quote comment is suspect regardless of how plausible it looks. See `..\u002Freferences\u002Fhandbook-retrieval.md`.\n- **Wrong representative-TC rule — four flavours of one mechanism.** All four share the same root: the handbook contains placement language that is syntactically close to a reducer policy, the agent locks on the first mapping that compiles, and no alternative TC-selection policy is trialled. (a) generic `max`\u002F`min` across all TCs when the handbook names a placement; (b) applying one handbook-named TC uniformly to ramp AND TAL AND peak; (c) *inventing* a per-metric placement from memory without a handbook quote; (d) reading a *measurement-setup* sentence (\"thermocouple a lead on the largest and smallest device\") as a *per-metric reducer policy*. Fix: per-metric selection with a quoted reducer sentence (not setup prose) per placement, plus trial-alternative-policies when the mechanical anomaly scan fires. See section 4 and `..\u002Freferences\u002Frepresentative-tc-selection.md`.\n- **Inventing a conveyor feasibility formula, fabricating its parameters, or shipping an OCR-drifted operator arrangement.** The grounded templates `(L_eff \u002F t_bound) * 60` are the only sanctioned path; every parameter inside the chosen formula (`L_eff_cm`, `zone_length_cm`, `t_min_s`, `t_max_s`, `loading_factor`) must carry a handbook quote; AND the operator arrangement (divisor vs. multiplier) must survive a dimensional check (`cm\u002Fmin` falls out of the formula with sample values). \"Suspiciously tiny thresholds that every run clears\", \"a plausible-looking formula whose parameters have no handbook quote\", and \"a formula whose units don't balance when instantiated\" are three signatures of the same failure. See `..\u002Freferences\u002Fconveyor-feasibility.md`.\n- **Miscalibrated compliance filter in \"best run\" ranking.** Picking a violator from your own Q1–Q4 outputs (under-filter) and emitting `null` for most groups because a hard mask wiped them out (over-filter) are both failures of the same mechanism: not matching the filter strictness to the prompt wording. Section 7 names the two modes.\n- **Shipping on an acknowledged anomaly without trialling an alternative interpretation.** Hedge-class phrases (adjectives \u002F modals \u002F rationalisations — see semantic check 2), isolated quantitative anomalies (near-zero or mass-fail from check 3), AND paired asymmetric anomalies across metrics sharing a rule (check 4) are all stop signals of one class: the threshold is ungrounded, the policy is miscalibrated, or the interpretation is wrong — not the data. The resolution is NOT an arithmetic re-check on the already-chosen policy (that is tautological) — it is re-computing the same cell under an alternative interpretation and comparing (check 5).\n","When to invoke:\n1. Whenever the task involves reflow related questions from thermocouple data, MES data or defect data and handbook-defined regions\u002Fwindows\u002Flimits.\n2. Extract numeric limits \u002F temperature regions \u002F timing windows \u002F margins \u002F feasibility rules from handbook.pdf.\n3. Compute run-level metrics from time–temperature thermocouple traces in a deterministic way.\n\nThis skill is designed to make the agent:\n- retrieve the right definitions from the handbook, and\n- compute metrics with predictable tie-breaks and interpolation.\n\n\n\n## 0. Handbook retrieval is a prerequisite\n\nEvery downstream section (TC selection, ramp, TAL, peak, feasibility, best-run\nranking, anomaly scan) depends on handbook-grounded thresholds. If the\nhandbook was not read, those sections operate on fabricated inputs and the\nanomaly scan cannot distinguish a wrong constant from a wrong rule. Do this\nfirst.\n\n**Reader retry queue** — try in order; move to the next on ImportError,\nFileNotFoundError, empty-text extraction (\u003C 50 chars returned), or encryption\nerror:\n\n1. `pypdf`\n2. `PyPDF2`\n3. `pdfplumber`\n4. `pdfminer.six`\n5. Shell `pdftotext` (poppler-utils, via `subprocess`)\n6. Claude's native PDF ingestion (attach the PDF file to the model turn)\n7. OCR fallback — `pdf2image` + `pytesseract`\n\nA `pip install \u003Creader>` is an acceptable intermediate step. **At least 3\nreaders must be attempted** before concluding the handbook is unreadable.\n\n**All-readers-fail rule:** if every reader genuinely fails, set every\nhandbook-derived `cfg` entry to `None` and emit `null` (not a pass\u002Ffail\nverdict) for every downstream metric that depended on it. Do NOT substitute\n\"typical reflow\" constants from memory — not even directionally plausible\nones. A memory-prior is a fabrication regardless of how it looks.\n\n**Parameter-grounding comment discipline:** every numeric value in `cfg` must\nhave an adjacent code comment with the verbatim handbook sentence that\nsupports it. A bare number with no quote is suspect and must become `None`.\n\n```python\n# minimal sketch — see ..\u002Freferences\u002Fhandbook-retrieval.md for the full\n# branched algorithm (ImportError, empty text, encrypted, all-readers-fail)\ntext, attempts = try_read_handbook(\"\u002Fapp\u002Fdata\u002Fhandbook.pdf\")\nif text is None:\n    assert len(attempts) >= 3, \"try more readers before giving up\"\n    cfg = {k: None for k in HANDBOOK_KEYS}\n    cfg[\"_handbook_status\"] = \"unreadable\"\nelse:\n    cfg = extract_cfg_from_handbook_text(text)   # with grounding comments\n    cfg[\"_handbook_status\"] = \"ok\"\n```\n\nDecision rule: if after a failed handbook read your reasoning contains\n\"typical reflow is …\", \"the standard limit is …\", or \"I'll assume …\", that\nis a memory-prior substituting for the handbook — delete the constants, re-run\nthe retry queue, and if it still fails, emit `null`.\n\nRead `..\u002Freferences\u002Fhandbook-retrieval.md` when any threshold the task depends\non comes from a PDF handbook\u002Fspec. Skip when every needed parameter is given\ninline in the task prompt or in a non-PDF structured file.\n\n\n\n## Handbook \"where to look\" checklist (after retrieval succeeds)\n\nSearch the extracted handbook text for these common sections\u002Ftables:\n- Thermal profile overview: defines \"preheat\", \"soak\", \"reflow\", \"cooling\".\n- Ramp rate guidance: \"ramp\", \"slope\", \"°C\u002Fs\", \"C\u002Fs\".\n- Liquidus & wetting time: \"liquidus\", \"time above liquidus\", \"TAL\", \"wetting\".\n- Peak temperature guidance: \"peak\", \"minimum peak\", \"margin above liquidus\".\n- Conveyor \u002F dwell feasibility: \"conveyor speed\", \"dwell time\", \"heated length\", \"zone length\", \"time-in-oven\", oven zone-count prefixes (e.g. `8Z`, `10Z`).\n- Thermocouple placement: \"cold spot\", \"worst case\", \"representative sensor\", named locations such as `largest_mass` \u002F `coldest_point` \u002F `smallest_mass`. Cross-check with the TC dataset's `location`\u002F`position` column so the handbook's named placement maps to a concrete `tc_id`. The handbook may name a location for one metric only — do not assume it governs every metric.\n\nGoal: extract a compact config object from the handbook and use it for all\ncomputations. **Every value carries an adjacent handbook quote in a comment**\n— if no quote can be produced, the value stays `None` and the dependent\nmetric emits `null`:\n\n```python\ncfg = {\n    # Handbook §X.Y: \"\u003Cverbatim preheat region sentence>\"\n    #   {\"type\":\"temp_band\", \"tmin\":..., \"tmax\":...}\n    #   or {\"type\":\"zone_band\", \"zones\":[...]}\n    #   or {\"type\":\"time_band\", \"t_start_s\":..., \"t_end_s\":...}\n    \"preheat_region\": None,\n\n    # Handbook §X.Y: \"\u003Cverbatim ramp-rate limit sentence>\"\n    \"ramp_limit_c_per_s\": None,\n\n    \"tal_threshold_c_source\": \"solder_liquidus_c\",   # if MES provides it\n    # Handbook §X.Y: \"\u003Cverbatim TAL lower bound sentence>\"\n    \"tal_min_s\": None,\n    # Handbook §X.Y: \"\u003Cverbatim TAL upper bound sentence>\"\n    \"tal_max_s\": None,\n\n    # Handbook §X.Y: \"\u003Cverbatim peak-margin sentence>\"\n    \"peak_margin_c\": None,\n\n    # Per-metric representative-TC locations from the handbook. Each is\n    # independent; leaving one None means fall back to generic per-TC\n    # reduction for that metric. Do NOT reuse a named placement across\n    # metrics without an explicit handbook sentence. See section 4.\n    \"ramp_rep_location\": None,\n    \"peak_rep_location\": None,\n    \"tal_rep_location\":  None,\n\n    # Conveyor feasibility rule-object; see section 6. Every parameter inside\n    # must likewise carry a handbook quote.\n    \"conveyor_rule\": None,\n}\n```\n\nIf the handbook provides multiple applicable constraints, implement all and\nuse the stricter constraint (document the choice in code comments).\n\n\n\nDeterministic thermocouple computation recipes\n\n1. Sorting and de-dup rules\nAlways sort samples by time before any computation:\n```python\ndf_tc = df_tc.sort_values([\"run_id\",\"tc_id\",\"time_s\"], kind=\"mergesort\")\n```\nIgnore segments where `dt \u003C= 0` (non-monotonic timestamps).\n\n2. Segment slope (ramp rate)\nFinite-difference slope on consecutive samples:\n- `s_i = (T_i - T_{i-1}) \u002F (t_i - t_{i-1})` for `dt > 0`\n- the \"max ramp\" is `max(s_i)` over the region.\n\nRegion filtering patterns:\n- Temperature band region: only include segments where **both endpoints** satisfy `tmin \u003C= T \u003C= tmax`.\n- Zone band region: filter by `zone_id in zones`.\n- Time band region: filter by `t_start_s \u003C= time_s \u003C= t_end_s`.\n\nRobust implementation (temperature-band example):\n```python\ndef max_slope_in_temp_band(df_tc, tmin, tmax):\n    g = df_tc.sort_values(\"time_s\")\n    t = g[\"time_s\"].to_numpy(dtype=float)\n    y = g[\"temp_c\"].to_numpy(dtype=float)\n    best = None\n    for i in range(1, len(g)):\n        dt = t[i] - t[i-1]\n        if dt \u003C= 0:\n            continue\n        if (tmin \u003C= y[i-1] \u003C= tmax) and (tmin \u003C= y[i] \u003C= tmax):\n            s = (y[i] - y[i-1]) \u002F dt\n            best = s if best is None else max(best, s)\n    return best  # None if no valid segments\n```\n\n3. Time above threshold with linear interpolation\nFor wetting\u002FTAL-type metrics, compute time above a threshold `thr` using segment interpolation.\n\nTwo defensible interpretations of \"time above threshold\" exist — check the handbook wording before choosing:\n- **Integral TAL** (default below): sum of every segment where temperature is above `thr`, including segments after a cooling discontinuity that briefly re-crosses. Matches \"total time above the melting point\".\n- **Contiguous TAL** (first-crossing to last-crossing): one window per run, from the first upward crossing of `thr` to the last downward crossing. Matches \"duration above liquidus\" when the handbook describes a single reflow dwell.\n\nIf the integral interpretation causes a mass compliance failure (e.g. > 80% of runs fall outside the TAL window), re-read the handbook for which interpretation it endorses, AND confirm the window itself (`tal_min_s`, `tal_max_s`) has a handbook quote and is not a memory-prior, before letting the verdict cascade into ranking.\n\n```python\ndef time_above_threshold_s(df_tc, thr):\n    g = df_tc.sort_values(\"time_s\")\n    t = g[\"time_s\"].to_numpy(dtype=float)\n    y = g[\"temp_c\"].to_numpy(dtype=float)\n    total = 0.0\n    for i in range(1, len(g)):\n        t0, t1 = t[i-1], t[i]\n        y0, y1 = y[i-1], y[i]\n        if t1 \u003C= t0:\n            continue\n\n        # fully above\n        if y0 > thr and y1 > thr:\n            total += (t1 - t0)\n            continue\n\n        # crossing: interpolate crossing time\n        crosses = (y0 \u003C= thr \u003C y1) or (y1 \u003C= thr \u003C y0)\n        if crosses and (y1 != y0):\n            frac = (thr - y0) \u002F (y1 - y0)\n            tcross = t0 + frac * (t1 - t0)\n            if y0 \u003C= thr and y1 > thr:\n                total += (t1 - tcross)\n            else:\n                total += (tcross - t0)\n    return total\n```\n\n4. Representative sensor selection — per metric, not per run\n\n**Default: different metrics have different governing worst-case TCs; use the same TC across metrics only when the handbook explicitly says so.** The handbook naming one location (e.g. `largest_mass`) is not a license to apply that one TC to every metric — it only governs the metric whose physical worst case matches the named location.\n\n**Setup prose vs. reducer prose — classify every handbook sentence before mapping to `cfg[\"\u003Cmetric>_rep_location\"]`.** A handbook sentence can be either (i) a *measurement-setup* instruction naming where probes should be *placed* during a thermal survey, or (ii) a *reducer* instruction naming which TC should *govern* a specific metric. Only (ii) licenses setting `cfg[\"\u003Cmetric>_rep_location\"]`.\n\n- **Setup prose — a noun phrase listing placements.** Signature: lists multiple locations without an imperative verb; often \"may be measured by thermocoupling a lead on …\", \"probes shall be placed at …\", \"thermocouples on \u003Cloc A> and \u003Cloc B>\". Examples: *\"may be measured by thermocoupling a lead on the largest and smallest device\"*, *\"thermocouples on exposed and shielded locations\"*. This tells the operator **where to place probes**; it does NOT designate any single TC as the representative for any single metric. Leave `cfg[\"\u003Cmetric>_rep_location\"] = None` and fall back to generic per-TC reduction.\n- **Reducer prose — an imperative verb pointing at one metric and one location.** Signature: single location + metric name + imperative verb. Examples: *\"use the coldest TC for the peak check\"*, *\"the ramp limit applies to the fastest-heating thermocouple\"*, *\"TAL is reported from the largest-mass sensor\"*. This DOES license `cfg[\"\u003Cmetric>_rep_location\"] = \u003Clocation>` for that one metric only.\n\nIf the only quotable sentence is setup prose, every `*_rep_location` stays `None`; the per-metric physical worst case (ramp → fastest-heating, peak → coolest-at-peak, TAL → both bounds via per-TC max\u002Fmin) governs instead. See `..\u002Freferences\u002Frepresentative-tc-selection.md` for the full classifier with worked positive and negative examples.\n\nPer-metric worst-case direction (quick table):\n\n| Metric | Governing worst case | Reducer across matching TCs |\n|---|---|---|\n| Ramp (upper limit) | fastest-heating | `max`, tie-break smallest `tc_id` |\n| Peak (minimum peak ≥ liquidus + margin) | coolest-at-peak | `min`, tie-break smallest `tc_id` |\n| TAL upper bound (overshoot) | hottest \u002F longest-above-liquidus | `max` TAL across TCs |\n| TAL lower bound (minimum dwell) | coolest | `min` TAL across TCs |\n\nPre-coding enumeration: before writing any reducer, for each per-run question write a one-line comment stating (i) what \"worst case\" means physically for this metric, (ii) which handbook-named TC location (if any) satisfies it via a *reducer* sentence (not setup prose), and (iii) the verbatim handbook sentence that supports (ii). If (iii) is empty OR is setup prose, use generic per-TC reduction and leave `cfg[\"\u003Cmetric>_rep_location\"] = None`.\n\n```python\n# generic sketch — one reducer per metric, not one TC for the whole run\ndef reduce_per_metric(tc_rows, metric_fn, direction, rep_location):\n    # direction: \"max\" (ramp, tal_upper) or \"min\" (peak, tal_lower)\n    pool = tc_rows\n    if rep_location is not None:\n        matched = tc_rows[tc_rows[\"location\"] == rep_location]\n        if not matched.empty:\n            pool = matched\n    per_tc = [(metric_fn(grp), tc_id) for tc_id, grp in pool.groupby(\"tc_id\")]\n    per_tc = [(v, t) for v, t in per_tc if v is not None]\n    if not per_tc:\n        return (None, None)\n    per_tc.sort(key=lambda x: ((-x[0] if direction == \"max\" else x[0]), x[1]))\n    return per_tc[0]\n```\n\n**Trial alternative policies when any red-flag fires.** When the pre-ship scan reports any metric with `\u003C 10 %` or `> 80 %` violators, do NOT ship on the first interpretation. Re-compute Q1\u002FQ2\u002FQ3 violator counts under at least two additional TC-selection policies — e.g. (α) a single consistent channel across metrics (handbook-named placement applied to all); (β) per-metric physical worst case per the table above; (γ) run-level max\u002Fmin\u002Fmean across all TCs. The policy that both quotes a *reducer* sentence AND produces a plausible distribution (roughly 5–30 % non-compliance per metric for typical reflow data) is the one to ship. Record the three distributions in a comment next to the final choice.\n\nDecision rule: if the handbook names `largest_mass`\u002F\"coldest point\" only, use it ONLY for peak (and TAL lower bound if applicable). Do NOT reuse it for ramp or TAL upper bound — those need the fastest-heating \u002F hottest channel. Consistency of `tc_id` across ramp\u002FTAL\u002Fpeak is NOT a goal.\n\nRead `..\u002Freferences\u002Frepresentative-tc-selection.md` when the handbook mentions any TC-placement by name OR when the task has questions for more than one of ramp\u002FTAL\u002Fpeak. Skip when the handbook makes no placement statement anywhere and only one of ramp\u002FTAL\u002Fpeak is asked.\n\n5. Peak and margin\nPer TC: `peak_tc = max(temp_c)`. Run-level peak uses the per-metric reducer in section 4 with `direction=\"min\"` and `rep_location = cfg[\"peak_rep_location\"]`. Requirement: `required_peak = liquidus + peak_margin`.\n\n6. Conveyor feasibility (grounded derivation, never fabricate)\nRepresent the handbook rule as a structured object and compute `required_min_speed_cm_min` only if every input is grounded in handbook text or oven_model geometry.\n\nGrounded templates:\n- Minimum dwell across effective heated length: `speed_max_cm_min = (L_eff_cm \u002F t_min_s) * 60`\n- Maximum time-in-oven across length:         `speed_min_cm_min = (L_eff_cm \u002F t_max_s) * 60`\n\nDeriving `L_eff_cm` when the handbook does not state it directly:\n- Parse the oven_model string: a leading digit prefix is the zone count (e.g. `8Z…` → 8 zones, `10Z…` → 10 zones). Multiply zone count × handbook zone length.\n- Use TAL min\u002Fmax as the dwell bound only when the handbook ties conveyor dwell to TAL; otherwise find the handbook's own dwell\u002Ftime-in-oven bound.\n\n**Parameter-grounding prerequisite (applies to every variable in the chosen formula — `L_eff_cm`, `zone_length_cm`, `t_min_s`, `t_max_s`, any `loading_factor` \u002F `boards_per_min` term):** each must have an adjacent code comment quoting the handbook sentence that defines it. If any variable is a bare number with no quote, treat the whole formula as fabricated: emit `required_min_speed_cm_min = null` and `meets = false`.\n\n**Operator-precedence \u002F dimensional check (PDF OCR is a source of operator drift — `×`, `÷`, parentheses are routinely dropped or misread).** After translating the handbook sentence to code, instantiate with one or two sample values and verify the units reduce to the expected output (`cm\u002Fmin` for `required_min_speed_cm_min`). A dimensionless parameter (e.g. `loading_factor`) must enter as a divisor or multiplier such that the units balance. If `(boards\u002Fmin) × cm \u002F loading_factor` → `cm\u002Fmin` only when `loading_factor` is dimensionless and placed as a divisor — if the computed magnitude is implausibly tiny or implausibly large with every run clearing\u002Ffailing trivially, re-read the handbook and try the opposite arrangement (divisor ↔ multiplier) before shipping.\n\n```python\n# generic sketch — every input must carry a handbook quote in a comment\n# Handbook §X.Y: \"\u003Cverbatim zone length sentence>\"\nzone_length_cm = ...\n# Handbook §X.Y: \"\u003Cverbatim dwell \u002F time-in-oven bound sentence>\"\nt_max_s = ...\nzone_count = int(re.match(r\"(\\d+)Z\", oven_model).group(1))\nL_eff_cm   = zone_count * zone_length_cm\nspeed_min  = (L_eff_cm \u002F t_max_s) * 60   # cm\u002Fmin — dimensional check: cm \u002F s * 60 = cm\u002Fmin ✓\n```\n\nHard rule — do NOT invent a formula. If `L_eff_cm` or the dwell bound cannot be grounded in the handbook or in oven_model geometry, emit:\n- `required_min_speed_cm_min = null`\n- `meets = false`\n- a code comment stating which input was ungrounded.\n\nDecision rule: if your own narrative contains \"I'll assume…\", \"this seems suspicious\", \"probably all runs clear this\", or \"typical loading factor is …\", that is a stop signal — the formula is fabricated. Return to the handbook (section 0 retry queue) or emit null.\n\nRead `..\u002Freferences\u002Fconveyor-feasibility.md` when the handbook does not spell out a speed rule for the oven_model in use, when `L_eff_cm`\u002Fdwell bounds must be derived, OR when the handbook sentence used arithmetic operators (`×`, `÷`, parentheses) that may have drifted during OCR. Skip when the handbook gives a direct `oven_model → required_speed` mapping in plain-text table form.\n\n7. Ranking \u002F \"best run\" questions\nWhen the task asks for the best \u002F top \u002F recommended \u002F highest-yielding run (per family or overall), the prompt wording decides whether compliance is a hard gate or a quality signal:\n\n- **Strict scope** (\"best **compliant** run\", \"top performer that meets all specs\"): rank only the mask=True subset where `ramp_ok AND tal_ok AND peak_ok AND feasibility_ok`; emit `null` for groups with no compliant runs.\n- **Soft scope** (\"best based on **quality and efficiency**\", \"recommended run\", unqualified \"top performer\"): rank ALL runs in the group by a composite score (yield desc, throughput desc, `compliance_violation_count` asc as tie-break\u002Fpenalty, `run_id` asc). Compliance is a signal, not a gate. Only emit `null` when the group has zero runs at all.\n\n```python\n# generic sketch — mode is \"strict\" or \"graded\"; both branches reuse the mask\nmask = df[\"ramp_ok\"] & df[\"tal_ok\"] & df[\"peak_ok\"] & df[\"feasibility_ok\"]\ndf[\"_violations\"] = (~df[[\"ramp_ok\",\"tal_ok\",\"peak_ok\",\"feasibility_ok\"]]).sum(axis=1)\npool = df[mask] if mode == \"strict\" else df\nbest = (pool.sort_values(\n            quality_cols + ([\"_violations\"] if mode == \"graded\" else []) + [\"run_id\"],\n            ascending=[False]*len(quality_cols) + ([True] if mode == \"graded\" else []) + [True])\n            .groupby(group_col).head(1))\n```\n\nDecision rule: a per-group sanity log reading `0\u002FN compliant` is a stop signal — re-read the task prompt to decide strict vs. graded before writing output. Never pick a \"best\" run that is listed as a violator in your own earlier Q1–Q4 outputs if the prompt is in strict scope.\n\nRead `..\u002Freferences\u002Fbest-run-ranking.md` when the task asks for a best \u002F top \u002F recommended run per group AND either (i) the prompt wording is ambiguous between strict and graded, or (ii) a strict mask would wipe out ≥ 1 group. Skip when the prompt explicitly says \"compliant\" and every group has ≥ 1 compliant run.\n\n\n\nOutput construction guardrails\n\n1. Sorting\n- Lists: sort by primary ID (run_id \u002F board_family) lexicographically.\n- Dicts keyed by ID: emit in sorted key order.\n\n2. Rounding and NaNs\n- Round floats to 2 decimals.\n- Never emit NaN\u002FInf; use `null`.\n\n```python\ndef r2(x):\n    if x is None:\n        return None\n    if isinstance(x, float) and (math.isnan(x) or math.isinf(x)):\n        return None\n    return float(round(float(x), 2))\n```\n\n3. Missing thermocouple data OR ungrounded threshold\nIf a run has no TC records (or no valid segments for a metric), set numeric outputs to `null`, and avoid claiming \"pass\". The same rule applies when the handbook threshold for that metric is `None` (ungrounded): emit `null` for the metric, never a pass\u002Ffail verdict derived from a memory-prior.\n\n\n## Minimal end-to-end scaffold\n\n```python\nimport os, json, math, re\nimport pandas as pd\n\nDATA_DIR = \"\u002Fapp\u002Fdata\"\nOUT_DIR  = \"\u002Fapp\u002Foutput\"\n\nruns = pd.read_csv(os.path.join(DATA_DIR, \"mes_log.csv\"))\ntc   = pd.read_csv(os.path.join(DATA_DIR, \"thermocouples.csv\"))\n\nruns[\"run_id\"] = runs[\"run_id\"].astype(str)\ntc[\"run_id\"]   = tc[\"run_id\"].astype(str)\ntc[\"tc_id\"]    = tc[\"tc_id\"].astype(str)\n\nruns = runs.sort_values([\"run_id\"], kind=\"mergesort\")\ntc   = tc.sort_values([\"run_id\",\"tc_id\",\"time_s\"], kind=\"mergesort\")\n\n# 0) Retrieve handbook text via the reader retry queue (section 0 above \u002F\n#    ..\u002Freferences\u002Fhandbook-retrieval.md). If all readers fail, every\n#    handbook-derived cfg entry is None and every dependent metric emits null.\n# 1) Build cfg with grounding-comment discipline (every value has a handbook\n#    quote in a comment, or it stays None).\ncfg = {...}\n\n# 2) Compute per-run metrics deterministically with stable tie-breaks and\n#    interpolation. For any metric whose threshold is None, emit null — do NOT\n#    fall back to a memory-prior.\n#    Use the PER-METRIC representative-TC rule (section 4) — ramp, TAL, peak\n#    may select different tc_ids; that is expected.\n# 3) Build JSON objects with sorted IDs and 2dp rounding.\n# 4) For \"best run\" questions, pick strict vs. graded mode by prompt wording (section 7).\n# 5) Write outputs into \u002Fapp\u002Foutput.\n```\n\n---\n\nSanity checks before writing outputs\n\nMechanical:\n- ID fields are strings.\n- Arrays sorted lexicographically.\n- Floats rounded to 2 decimals.\n- No NaN\u002FInf in JSON.\n- Sensor selection uses deterministic tie-breaks AND respects the handbook's named placement for the metric whose physical worst case matches (section 4).\n- Any \"time above threshold\" uses interpolation (not naive threshold counting).\n\nSemantic — run in this order; do not skip:\n\n- **(1) Handbook-grounding check (precedes everything else).** For every numeric threshold used in a verdict in this run's outputs (`ramp_limit_c_per_s`, `tal_min_s`, `tal_max_s`, `peak_margin_c`, `preheat_region` tmin\u002Ftmax, feasibility inputs `L_eff_cm` \u002F `t_min_s` \u002F `t_max_s` \u002F `zone_length_cm` \u002F any `loading_factor`), confirm there is an adjacent code comment quoting the handbook sentence that defines it. If any threshold is a bare number with no quote, set it to `None` and change the per-metric output to `null`. **On ANY mass-fail or near-zero signal flagged in checks 3\u002F4 below, re-run this check first on the specific threshold driving the verdict** — if that threshold is ungrounded, it is the suspect, not the TC-selection rule or TAL interpretation; do NOT branch into (4) until (1) is clean.\n\n- **(2) Narrative hedge check — scan for a class, not a fixed phrase list.** The hedge is any phrase in one of three classes, not a literal match from a catalogue:\n    - *Outside-expectation adjectives* (synonym family of \"suspicious\"): \"suspicious\", \"surprising\", \"unusual\", \"unusually extreme\", \"unexpected\", \"weird\", \"strange\", \"odd\", \"off\", \"implausible\". A near-synonym from this family counts (e.g. \"unusually extreme numbers\" from iter_4 shares the mechanism with the catalogued \"this seems suspicious\" and must trip the scan).\n    - *Hedging modals \u002F memory-prior substitutions*: \"probably\", \"might\", \"I'll assume\", \"I think\", \"typical reflow is …\", \"the standard limit is …\", \"the handbook doesn't say directly\".\n    - *Rationalisations that explain away an anomaly*: \"real production anomaly\", \"systemic production pattern\", \"the data is just unusual\", \"that's just how reflow works\", \"the process is just running hot\", \"genuine over-cooked profiles\".\n   Any match: stop, re-open the handbook on the specific concept, and re-run the policy \u002F interpretation decision — do NOT ship behind the hedge.\n\n- **(3) Mechanical quantitative-anomaly scan (no judgement call).** Immediately after per-run verdicts are computed, emit a one-line summary of violator counts across the per-run questions, e.g. `Q1: X\u002FN violators, Q2: Y\u002FN violators, Q3: Z\u002FN violators`. If any count is `\u003C 0.10 * N` (near-zero) or `> 0.80 * N` (mass-fail), the scan has fired — no judgement call. First re-run check (1) on the threshold driving the fired verdict; only after (1) is clean, proceed to check (4).\n\n- **(4) Paired quantitative-anomaly scan.** When two metrics share a selection rule (same TC-selection policy, same TAL interpretation, same feasibility arrangement) and show *asymmetric* flag rates — one metric `\u003C 10 %` violators AND another `> 80 %` violators — the shared rule is miscalibrated per metric, not the data. Hard stop: re-examine the shared rule per metric (see `..\u002Freferences\u002Frepresentative-tc-selection.md` for the trial-alternative-policies procedure) before shipping. **Prerequisite:** confirm via (1) that both metrics' thresholds are handbook-grounded; if either is a memory-prior, the apparent asymmetry is an artifact of the wrong constant.\n\n- **(5) Per-question spot-check must compare against an alternative interpretation.** An arithmetic spot check on the already-chosen policy only verifies *computation*, not *interpretation* — it is tautological against the policy that produced the number. For each per-run question type, re-compute the same representative cell under at least ONE alternative interpretation and compare: (α) different TC-selection policy for Q1\u002FQ2\u002FQ3 (fastest-heating vs. coolest vs. run-level max\u002Fmin\u002Fmean); (β) different TAL window reading (integral vs. contiguous) for TAL; (γ) different operator arrangement (divisor ↔ multiplier) for feasibility. If the two outputs differ dramatically (e.g. 5\u002FN vs. 51\u002FN violators), the policy choice is driving the verdict and must be re-examined before shipping. For \"best run\" picks, verify compliance \u002F non-null emission against the prompt mode (section 7).\n\n## Common pitfalls\n\n- **Hard-coding handbook constants from memory after a failed PDF read.** A single reader failure (ImportError, FileNotFoundError, empty text, encryption) is NOT a license to fall back to \"typical reflow\" priors (TAL 30–60 s, ramp 2 °C\u002Fs, margin +20 °C, invented `loading_factor`). The retry queue (section 0) requires ≥ 3 reader attempts, and if all genuinely fail, every handbook-derived threshold is `None` and every dependent verdict is `null`. Any `cfg` value lacking an adjacent handbook-quote comment is suspect regardless of how plausible it looks. See `..\u002Freferences\u002Fhandbook-retrieval.md`.\n- **Wrong representative-TC rule — four flavours of one mechanism.** All four share the same root: the handbook contains placement language that is syntactically close to a reducer policy, the agent locks on the first mapping that compiles, and no alternative TC-selection policy is trialled. (a) generic `max`\u002F`min` across all TCs when the handbook names a placement; (b) applying one handbook-named TC uniformly to ramp AND TAL AND peak; (c) *inventing* a per-metric placement from memory without a handbook quote; (d) reading a *measurement-setup* sentence (\"thermocouple a lead on the largest and smallest device\") as a *per-metric reducer policy*. Fix: per-metric selection with a quoted reducer sentence (not setup prose) per placement, plus trial-alternative-policies when the mechanical anomaly scan fires. See section 4 and `..\u002Freferences\u002Frepresentative-tc-selection.md`.\n- **Inventing a conveyor feasibility formula, fabricating its parameters, or shipping an OCR-drifted operator arrangement.** The grounded templates `(L_eff \u002F t_bound) * 60` are the only sanctioned path; every parameter inside the chosen formula (`L_eff_cm`, `zone_length_cm`, `t_min_s`, `t_max_s`, `loading_factor`) must carry a handbook quote; AND the operator arrangement (divisor vs. multiplier) must survive a dimensional check (`cm\u002Fmin` falls out of the formula with sample values). \"Suspiciously tiny thresholds that every run clears\", \"a plausible-looking formula whose parameters have no handbook quote\", and \"a formula whose units don't balance when instantiated\" are three signatures of the same failure. See `..\u002Freferences\u002Fconveyor-feasibility.md`.\n- **Miscalibrated compliance filter in \"best run\" ranking.** Picking a violator from your own Q1–Q4 outputs (under-filter) and emitting `null` for most groups because a hard mask wiped them out (over-filter) are both failures of the same mechanism: not matching the filter strictness to the prompt wording. Section 7 names the two modes.\n- **Shipping on an acknowledged anomaly without trialling an alternative interpretation.** Hedge-class phrases (adjectives \u002F modals \u002F rationalisations — see semantic check 2), isolated quantitative anomalies (near-zero or mass-fail from check 3), AND paired asymmetric anomalies across metrics sharing a rule (check 4) are all stop signals of one class: the threshold is ungrounded, the policy is miscalibrated, or the interpretation is wrong — not the data. The resolution is NOT an arithmetic re-check on the already-chosen policy (that is tautological) — it is re-computing the same cell under an alternative interpretation and comparing (check 5).\n",{"name":5,"description":7},"main","cdcb6d230f3b15c3c33f8a2bdd16439f43602cbe","evaluation\u002Fresults\u002FSkillGrad\u002Fopus47_clean_20261016_partial14\u002Ftasks\u002Fmanufacturing-equipment-maintenance\u002Frepaired_skill\u002Freflow-profile-compliance-toolkit",1,"https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark","https:\u002F\u002Fgithub.com\u002Flinyouxue","2026-11-14 20:28:35",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add linyouxue\u002Fskill-repair-benchmark --skill reflow-profile-compliance-toolkit",{"tool":37,"command":38},"bunx","bunx skills add linyouxue\u002Fskill-repair-benchmark --skill reflow-profile-compliance-toolkit",{"tool":40,"command":41},"pnpm","pnpm dlx skills add linyouxue\u002Fskill-repair-benchmark --skill reflow-profile-compliance-toolkit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fevaluation\u002Fresults\u002FSkillGrad\u002Fopus47_clean_20261016_partial14\u002Ftasks\u002Fmanufacturing-equipment-maintenance\u002Frepaired_skill\u002Freflow-profile-compliance-toolkit\u002FSKILL.md",true,[],[46,53,60,67,72,77],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":19},"01M7E1HGVRY73NBJ022CJG13X6","video-frame-extraction","Extract frames from video files and save them as images using OpenCV","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fvideo-frame-extraction\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7E1HAG5R7CJ9C8NYJS771MB","openai-vision","Analyze images and multi-frame sequences using OpenAI GPT vision models","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fopenai-vision\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7E1H7DADKB6QBWKC2KQ63SZ","image-ocr","Extract text content from images using Tesseract OCR via Python, including structured field extraction from receipts and forms","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[],{"skillNo":68,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M7E1H0WBNT43TENGQY7AVZHD","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fvideo-frame-extraction\u002FSKILL.md",[],[],{"skillNo":73,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7E1GTC7D4N4Q2EF03875J9E","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fopenai-vision\u002FSKILL.md",[],[],{"skillNo":78,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7E1GQ92CWFMGH53KSSE4WER","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[]]