#!/usr/bin/env python3
"""Build an audit report in Markdown from a JSON audit record, with the content ISO 19011 6.5.1 expects.
Audit JSON keys:
audit_id, type (internal/supplier/certification-readiness), organization, site, objectives, scope,
criteria (list), start, end, lead_auditor, team (list), auditees (list of roles), sampled (list),
strengths (list), findings (list of {id, grade major/minor/ofi, clause, statement, evidence, requirement}),
conclusion (optional; generated from the findings when absent), diverging_opinions, distribution (list),
response_due_days (default 30)
Missing required content (objectives, scope, criteria, dates, lead auditor) is listed as RP001 warnings and
exits 1 so incomplete reports are not issued.
Usage:
python report_build.py audit.json > report.md
Exit codes: 0 report complete, 1 report written but required content missing, 2 read or JSON error.
"""
import argparse
import json
import sys
from collections import Counter
REQUIRED = ["objectives", "scope", "criteria", "start", "lead_auditor"]
GRADE_ORDER = {"major": 0, "minor": 1, "ofi": 2}
def conclusion(a, counts):
if counts["major"]:
return (f"The management system is not effectively implemented within the audit scope: {counts['major']} major "
f"nonconformit{'y' if counts['major'] == 1 else 'ies'} show(s) a required process absent or broken down. "
"Corrective action and verification are required before the next milestone.")
if counts["minor"]:
return (f"The management system is implemented and generally effective within the audit scope, with "
f"{counts['minor']} minor nonconformit{'y' if counts['minor'] == 1 else 'ies'} requiring corrective action.")
return "The management system conforms to the audit criteria and is effectively implemented within the audit scope."
def bullet(items):
return "\n".join(f"- {x}" for x in items) if items else "- None recorded."
def render(a):
f = sorted(a.get("findings", []), key=lambda x: (GRADE_ORDER.get(str(x.get("grade", "")).lower(), 3), str(x.get("id"))))
counts = Counter(str(x.get("grade", "")).lower() for x in f)
due = a.get("response_due_days", 30)
rows = ["| ID | Grade | Clause | Finding |", "|----|-------|--------|---------|"]
rows += [f"| {x.get('id')} | {x.get('grade', '').upper()} | {x.get('clause', '')} | {x.get('statement', '')} |" for x in f]
detail = []
for x in f:
detail.append(f"### {x.get('id')} - {x.get('grade', '').upper()} - {x.get('clause', '')}\n")
if x.get("requirement"):
detail.append(f"**Requirement:** {x['requirement']}\n")
detail.append(f"**Evidence:** {x.get('evidence', 'TODO')}\n")
detail.append(f"**Statement:** {x.get('statement', 'TODO')}\n")
end = a.get("end") or a.get("start", "TODO")
return f"""# Audit Report {a.get('audit_id', 'TODO')} - {a.get('organization', 'TODO')}
| | |
|---|---|
| Audit type | {a.get('type', 'internal')} |
| Site | {a.get('site', 'TODO')} |
| Dates | {a.get('start', 'TODO')} to {end} |
| Lead auditor | {a.get('lead_auditor', 'TODO')} |
| Audit team | {', '.join(a.get('team', [])) or '-'} |
| Auditees | {', '.join(a.get('auditees', [])) or 'TODO'} |
## 1. Summary
{a.get('conclusion') or conclusion(a, counts)}
| Major | Minor | OFI |
|-------|-------|-----|
| {counts['major']} | {counts['minor']} | {counts['ofi']} |
## 2. Objectives
{a.get('objectives', 'TODO')}
## 3. Scope
{a.get('scope', 'TODO')}
## 4. Criteria
{bullet(a.get('criteria', []))}
## 5. Method and sampling
The audit was performed by interviews, observation and review of records on a sample basis; findings relate
only to the items sampled and other nonconformities may exist. Items sampled:
{bullet(a.get('sampled', []))}
## 6. Strengths
{bullet(a.get('strengths', []))}
## 7. Findings
{chr(10).join(rows)}
{chr(10).join(detail) if detail else 'No findings.'}
## 8. Diverging opinions
{a.get('diverging_opinions') or 'None. Findings were presented and agreed at the closing meeting.'}
## 9. Follow-up
Nonconformities require a response with containment/correction, root cause, corrective action, owner and due
date within {due} days of this report. Major nonconformities are verified before closure; OFIs are for the
auditee's consideration.
## 10. Distribution
{bullet(a.get('distribution', []))}
"""
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("audit", help="audit JSON, or - for stdin")
args = ap.parse_args()
try:
a = json.load(sys.stdin if args.audit == "-" else open(args.audit, encoding="utf-8"))
if not isinstance(a, dict):
raise ValueError("audit JSON must be an object")
except (OSError, ValueError) as e:
print(f"error: {e}", file=sys.stderr)
return 2
print(render(a))
missing = [k for k in REQUIRED if not a.get(k)]
for k in missing:
print(f"RP001 [high] report lacks '{k}' (ISO 19011 6.5.1)", file=sys.stderr)
for x in a.get("findings", []):
if str(x.get("grade", "")).lower() in ("major", "minor") and not (x.get("evidence") and x.get("clause")):
print(f"RP002 [high] finding {x.get('id')} has no clause or evidence", file=sys.stderr)
missing.append(x.get("id"))
return 1 if missing else 0
if __name__ == "__main__":
sys.exit(main())
8d-problem-solving-report-writer
Write and review 8D problem-solving reports for customer complaints and serious nonconformities (automotive and aerospace practice: Ford Global 8D, VDA, GM, Stellantis formats): D0 emergency response, D1 cross-functional team and champion, D2 problem description with 5W2H and is / is-not and no cause in the statement, D3 interim containment within 24 hours with verification and clean point, D4 verified occurrence and escape (non-detection) root causes plus systemic cause, D5 permanent corrective actions for each cause verified before implementation, D6 implementation, validation with production data and removal of containment, D7 PFMEA, control plan and read-across to similar products, D8 closure and recognition. Checks an 8D discipline by discipline for missing content, human-error root causes, missing escape cause or action, late containment and dates out of order.
acceptance-sampling-plan-selector
Select and evaluate acceptance sampling plans for incoming, in-process and final inspection: ANSI/ASQ Z1.4 / ISO 2859-1 single sampling under normal inspection (code letter from lot size and inspection level I, II, III, S-1 to S-4; sample size, Ac and Re from AQL, following the table's arrows to the correct plan; 100% when n reaches the lot size; AQLs above 10 per 100 units), operating characteristic curves (Pa at any quality, producer's quality level, indifference point, LTPD, AOQ and AOQL, binomial or hypergeometric), plans designed from producer and consumer risk, and c = 0 zero-acceptance plans. Covers AQL choice by defect class, switching rules between normal, tightened and reduced inspection, when sampling is not appropriate, and random sampling.
approved-supplier-list-manager
Manage and audit an approved supplier list (ASL) / external provider register for ISO 9001 8.4.1, IATF 16949 8.4 and AS9100 8.4.1: supplier status (approved, conditional, probation, pending, disqualified), scope of approval by commodity and process, risk class, certification and expiry, re-evaluation intervals by risk, conditions with end dates, single-source contingency, approver and customer-directed sources. Audits the list for expired or expiring certificates, overdue re-evaluations, conditional or probation status past its decision date, high-risk suppliers without the required certification, single-source suppliers without backup and missing approvers, and checks purchase orders for suppliers that are off-list, disqualified or pending, or buying outside the approved scope. Covers ERP blocks, PO requirements, off-list and emergency purchases.
apqp-phase-planner
Plan and track Advanced Product Quality Planning (AIAG APQP 3rd edition, IATF 16949) for a new or changed automotive part: back-schedule the five phases (plan and define, product design, process design, product and process validation, launch and feedback) from the start-of-production date by program complexity, with overlap, PPAP lead and safe-launch period; list the deliverables and gate for each phase (DFMEA, DVP&R, feasibility, process flow, PFMEA, control plans, MSA, Ppk, run at rate, PPAP, safe launch, lessons learned); adjust for build-to-print suppliers; flag compressed timelines and late or untracked deliverables against a status list. Covers gate reviews, red/yellow/green status reporting, run at rate and safe-launch exit criteria.
as9100-gap-analyzer
Run an AS9100D / EN 9100:2018 gap analysis for aviation, space and defence suppliers on the requirements added to ISO 9001: on-time delivery and conformity focus, management representative, ethics and human-factors awareness, operational planning and operational risk management, configuration management, product safety, counterfeit-part prevention, special requirements, critical items and key characteristics, external provider register and flow-down, FOD prevention, tooling and NC program control, special process validation, first article inspection (AS9102), traceability, in-service data and nonconforming product control. Generates and scores a worksheet, grades missing core controls as major, and checks invalid n/a claims. Covers AS9101/AS9104, OASIS, AS9102 FAI forms, counterfeit standards (AS5553, AS6174, AS6081), NADCAP and the planned IA9100 transition.
capa-effectiveness-checker
Verify whether a corrective action actually worked (ISO 9001 10.2.1 d, IATF 16949, 8D D6) with statistics instead of 'no complaints so far': before/after defect-rate comparison with an exact conditional binomial test for Poisson counts and a minimum practical reduction, zero-defect demonstration size (n = ln(1-C)/ln(1-p), rule of three) with progress so far, and exact Clopper-Pearson upper bounds on the post-action defect rate. Returns effective, not yet demonstrated (with the units still needed) or not effective. Covers setting effectiveness criteria when the CAPA is opened, choosing the window by problem frequency, leading indicators for rare failures (Cpk, SPC stability, error-proofing checks, LPA), and traps such as volume changes, detection changes and containment masking.