Published Agent Skill package. Follow the instructions in SKILL.md to complete the user's task.

achieving-cmmc-level-2-compliance

>-

This page contains 5 files from the original skill zip. Supporting markdown and scripts are included below so you do not need extra downloads.

Files in this package

SKILL.md

Achieving CMMC Level 2 Compliance

When to Use

Prerequisites

Workflow

1. Determine applicability and CUI categories

Confirm the contract requires CMMC Level 2 (CUI present, not just FCI). FCI-only contracts are Level 1 (the 15 FAR 52.204-21 requirements). Identify CUI categories from the contract and the DoD CUI Registry.

2. Scope the environment

Classify every asset into one of the CMMC scoping categories:

Minimize scope deliberately — a smaller, well-segmented CUI enclave is far cheaper to certify than a flat network.

3. Implement the 110 requirements (NIST SP 800-171 Rev 2)

Work the 14 families (3.1–3.14). For each requirement, implement, then write the how in the SSP. High-leverage early wins: MFA (3.5.3), FIPS-validated cryptography (3.13.11), audit logging (3.3.x), access control + least privilege (3.1.x), and incident response (3.6.x).

4. Score with the DoD Assessment Methodology (SPRS)

Start at 110 and subtract the weighted value (1, 3, or 5 points) of each unmet requirement; partial credit applies to a small number of controls (e.g., MFA, FIPS crypto). The result is the SPRS score (maximum 110; the methodology floor is −203). Post the score, the SSP date, and the assessment scope to SPRS (or eMASS for higher assessments).

5. Build a compliant POA&M

Document every unmet requirement with owner, remediation, and milestone. Constraints under the CMMC rule: a Conditional status requires a score of at least 80% (≥ 88 of 110), only POA&M-eligible requirements may be deferred (the highest-weighted security requirements must be fully met — verify eligibility against 32 CFR Part 170), and all POA&M items must be closed within 180 days to convert Conditional → Final.

6. Assess (self or C3PAO)

7. Maintain certification

Certification is valid three years with annual affirmations. Maintain the SSP, re-score on change, keep evidence current, and feed significant changes back into the assessment.

Key Concepts

Concept Definition
FCI Federal Contract Information — Level 1 protects it (FAR 52.204-21).
CUI Controlled Unclassified Information — Level 2 protects it (NIST 800-171).
110 requirements The SP 800-171 Rev 2 security requirements across 14 families.
SPRS Supplier Performance Risk System — where the 800-171 score is posted.
DoD Assessment Methodology The 1/3/5-point weighting used to compute the score from 110.
C3PAO CMMC Third-Party Assessment Organization — performs Level 2 certification.
POA&M Plan of Action & Milestones — limited, must close in 180 days for Final status.
Conditional vs Final Conditional = open POA&M (score ≥ 80%); Final = all controls met.
ESP External Service Provider — must meet FedRAMP Moderate / equivalency for CUI.
Scoping categories CUI / Security Protection / Contractor Risk Managed / Specialized / Out-of-Scope.

Tools & Systems

Common Scenarios

Output Format

Produce a CMMC Level 2 Readiness Report using assets/template.md, containing:

  1. Applicability & CUI categories — why Level 2 applies.
  2. Scope — assets by scoping category and the CUI boundary diagram reference.
  3. Control status by family — met / not met / N/A across the 14 families.
  4. SPRS score — computed score, deductions, and the gap to 110 and to the 88 threshold.
  5. POA&M — unmet requirements, eligibility check, owners, 180-day milestones.
  6. Assessment path — self vs C3PAO, target date, affirmation owner.
  7. Remediation roadmap — sequenced by point value and effort.

Use scripts/process.py to compute the SPRS score from a control-status JSON, flag POA&M-eligibility concerns, and report the gap to the conditional-certification threshold.

Supporting file: assets/template.md

This file is part of the achieving-cmmc-level-2-compliance skill package. Use it when SKILL.md references assets/template.md.

CMMC Level 2 Readiness Report — Worked Example

Filled example for a small DIB manufacturer handling CUI on a segmented enclave.
Replace bracketed content for your own organization.

1. Applicability & CUI Categories

2. Scope (CMMC Level 2 Scoping Guide)

Category Examples in this environment
CUI Assets Engineering workstations, CUI file share, the segmented "Enclave-1" VLAN
Security Protection Assets EDR console, SIEM, firewall, IdP/MFA, jump host
Contractor Risk Managed General corporate laptops (policy-blocked from CUI)
Specialized Assets CNC machine controllers (documented, isolated)
Out-of-Scope Guest Wi-Fi, marketing SaaS

Boundary note: CUI is confined to Enclave-1 behind segmentation and MFA. Deliberately minimized to shrink the assessment surface. See network diagram CUI-boundary-v3.

3. Control Status by Family (NIST SP 800-171 Rev 2)

(summary; full per-requirement status lives in the SSP)

Family Met Partial Not Met N/A
3.1 Access Control 22 0 0 0
3.3 Audit & Accountability 8 0 1 0
3.5 Identification & Auth 10 1 0 0
3.8 Media Protection 8 0 1 0
3.13 System & Comms Protection 15 0 1 0
3.14 System & Info Integrity 6 0 1 0
(others) all met

4. SPRS Score

(computed by scripts/process.py from the control-status JSON)

5. POA&M (eligibility-checked)

ID Requirement Points Eligibility Remediation Owner Milestone (≤180d)
3.3.1 Audit log generation/coverage 5 Verify — high weight; confirm against 32 CFR 170 Enable full audit policy + ship to SIEM SecOps 2026-07-30
3.13.11 FIPS-validated cryptography 3 Verify eligibility Replace non-validated module with FIPS 140-validated Infra 2026-08-15
3.5.3 MFA (partial) 3 Partial-credit control Extend MFA to remaining admin paths IAM 2026-07-20
3.8.9 Backup CUI protection 1 Eligible Encrypt + access-control backup store Infra 2026-08-31
3.14.1 Flaw remediation 1 Eligible Formalize patch SLA + tracking IT 2026-08-31

The two 3-point and one 5-point items must clear eligibility review; the highest-weighted security requirements generally cannot remain on a POA&M. All items close within 180 days to convert Conditional → Final.

6. Assessment Path

7. Remediation Roadmap (sequenced by point value, then effort)

  1. 3.3.1 audit logging (5 pts) — biggest score lever and likely POA&M-ineligible → do first.
  2. 3.13.11 FIPS crypto (3 pts) and 3.5.3 MFA gap (3 pts) — close to remove eligibility risk.
  3. 3.8.9, 3.14.1 (1 pt each) — low-effort cleanups before the C3PAO date.
  4. Re-run the SPRS calculator after each closure; goal is 110 before assessment.

Supporting file: LICENSE

This file is part of the achieving-cmmc-level-2-compliance skill package. Use it when SKILL.md references LICENSE.


                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. Please do not remove or change
      the license header comment from a contributed file except when
      necessary.

   Copyright 2026 mukul975

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Supporting file: references/standards.md

This file is part of the achieving-cmmc-level-2-compliance skill package. Use it when SKILL.md references references/standards.md.

CMMC Level 2 — Standards & Reference

Governing rules

Rule Citation Status / effective date
CMMC Program rule 32 CFR Part 170 Effective December 16, 2024
CMMC acquisition rule (DFARS) 48 CFR; DFARS clause 252.204-7021 (and 204.7503) Published Sept 10, 2025; effective November 10, 2025
Safeguarding CUI / incident reporting DFARS 252.204-7012 In effect
NIST 800-171 self-assessment + SPRS posting DFARS 252.204-7019 / -7020 In effect

Always confirm current status at the source — acquisition rules and phase dates have moved before. Authoritative: https://dodcio.defense.gov/CMMC/ and the eCFR for 32 CFR Part 170.

Phased rollout (per the acquisition rule)

Phase Begins What applies
Phase 1 Nov 10, 2025 Level 1 and some Level 2 self-assessment required in solicitations
Phase 2 Nov 10, 2026 Level 2 C3PAO certification required for applicable contracts
Phase 3 Nov 10, 2027 Level 2 C3PAO + Level 3 DIBCAC assessment phased in
Phase 4 Nov 10, 2028 Full implementation across applicable DoD contracts

The three CMMC levels

Level Protects Requirements Assessment
Level 1 FCI 15 requirements (FAR 52.204-21) Annual self-assessment + affirmation
Level 2 CUI 110 requirements (NIST SP 800-171 Rev 2) Self or triennial C3PAO certification
Level 3 CUI (high priority) 110 + selected SP 800-172 enhanced DoD (DIBCAC) assessment

Certification validity: 3 years, with annual affirmation by a senior official in SPRS.

NIST SP 800-171 Rev 2 — the 14 families (110 requirements)

§ Family # reqs
3.1 Access Control 22
3.2 Awareness and Training 3
3.3 Audit and Accountability 9
3.4 Configuration Management 9
3.5 Identification and Authentication 11
3.6 Incident Response 3
3.7 Maintenance 6
3.8 Media Protection 9
3.9 Personnel Security 2
3.10 Physical Protection 6
3.11 Risk Assessment 3
3.12 Security Assessment 4
3.13 System and Communications Protection 16
3.14 System and Information Integrity 7
Total 110

(Assessment objectives for each requirement are in NIST SP 800-171A.)

DoD Assessment Methodology — SPRS scoring

POA&M rules under the CMMC rule (32 CFR Part 170)

Scoping categories (CMMC Level 2 Scoping Guide)

Category Treatment
CUI Assets Process/store/transmit CUI — assessed against applicable requirements.
Security Protection Assets Provide security to the CUI environment — in scope.
Contractor Risk Managed Assets Capable of handling CUI but not intended to — managed by policy/config.
Specialized Assets IoT/OT, GFE, test equipment — documented, limited assessment.
Out-of-Scope Assets Isolated from CUI — not assessed.

External Service Providers / cloud

NIST CSF 2.0 alignment

CSF 2.0 ID Relevance
GV.OC-03 Legal/regulatory (DFARS/CMMC) requirements understood.
GV.SC-01 Supply-chain risk management — flowdown to subs / ESPs.
ID.AM-08 Assets managed across the lifecycle (scoping).
ID.RA-05 Risk informs prioritization of unmet requirements.
PR.AA-01 Identity and access (3.1 / 3.5 families).
PR.DS-01 Data-at-rest protection (FIPS crypto, media protection).

Supporting file: scripts/process.py

This file is part of the achieving-cmmc-level-2-compliance skill package. Use it when SKILL.md references scripts/process.py.

#!/usr/bin/env python3
"""
CMMC Level 2 / NIST SP 800-171 Rev 2 SPRS score calculator.

Implements the DoD Assessment Methodology arithmetic: start at 110 and subtract
the weighted value (1, 3, or 5) of each NOT MET requirement, with partial credit
for the small set of requirements that allow it. Reports the SPRS score, the gap
to a perfect 110 and to the 88-point (80%) conditional-certification threshold,
and flags higher-weighted unmet requirements whose POA&M eligibility must be
verified against 32 CFR Part 170.

NOTE: per-requirement point weights are defined by the DoD NIST SP 800-171
Assessment Methodology. Supply each requirement's official weight in the input
(this tool does not invent weights). Use status 'partial' with 'partial_deduction'
only for requirements the methodology allows partial credit on (e.g., 3.5.3 MFA,
3.13.11 FIPS crypto).

Input JSON shape:
{
  "org": {"name": "Acme Defense LLC", "scope": "CUI enclave"},
  "requirements": [
    {"id": "3.1.1",  "family": "3.1", "status": "met",      "weight": 5},
    {"id": "3.5.3",  "family": "3.5", "status": "partial",  "weight": 5, "partial_deduction": 3},
    {"id": "3.3.1",  "family": "3.3", "status": "not_met",  "weight": 5},
    {"id": "3.8.9",  "family": "3.8", "status": "not_met",  "weight": 1},
    {"id": "3.2.1",  "family": "3.2", "status": "na",       "weight": 1}
  ]
}

status: met | not_met | partial | na

Usage:
  python process.py --input controls.json [--output readiness.md]
  python process.py --input controls.json --require-conditional   # exit 1 if score < 88
"""

import argparse
import json
import sys

START_SCORE = 110
CONDITIONAL_THRESHOLD = 88   # 80% of 110
VALID_STATUS = {"met", "not_met", "partial", "na"}
VALID_WEIGHTS = {1, 3, 5}


def compute(data):
    reqs = data.get("requirements", [])
    if not reqs:
        raise ValueError("requirements list is required")

    deductions = 0
    counts = {"met": 0, "not_met": 0, "partial": 0, "na": 0}
    poam_flags = []   # higher-weight unmet -> verify POA&M eligibility
    by_family = {}    # family -> {met,not_met,partial,na}
    detail = []

    for r in reqs:
        rid = r.get("id", "?")
        status = r.get("status")
        weight = r.get("weight")
        if status not in VALID_STATUS:
            raise ValueError(f"{rid}: status '{status}' invalid (met|not_met|partial|na)")
        if status in ("not_met", "partial", "met") and weight not in VALID_WEIGHTS:
            raise ValueError(f"{rid}: weight '{weight}' invalid (must be 1, 3, or 5)")

        fam = r.get("family", rid.rsplit(".", 1)[0])
        fam_rec = by_family.setdefault(fam, {"met": 0, "not_met": 0, "partial": 0, "na": 0})
        fam_rec[status] += 1
        counts[status] += 1

        ded = 0
        if status == "not_met":
            ded = weight
            if weight > 1:
                poam_flags.append((rid, weight))
        elif status == "partial":
            ded = r.get("partial_deduction")
            if ded is None:
                raise ValueError(f"{rid}: status 'partial' requires 'partial_deduction'")
            if ded < 0 or ded > weight:
                raise ValueError(f"{rid}: partial_deduction {ded} out of range (0..{weight})")
            if ded > 1:
                poam_flags.append((rid, ded))
        deductions += ded
        detail.append((rid, fam, status, weight, ded))

    score = START_SCORE - deductions
    return {
        "score": score,
        "deductions": deductions,
        "counts": counts,
        "by_family": by_family,
        "poam_flags": poam_flags,
        "detail": detail,
    }


def render(data, res):
    org = data.get("org", {})
    lines = []
    lines.append(f"# CMMC Level 2 Readiness - {org.get('name','Organization')}")
    lines.append("")
    if org.get("scope"):
        lines.append(f"- **Scope:** {org['scope']}")
    lines.append("")

    score = res["score"]
    lines.append("## SPRS Score (DoD Assessment Methodology)")
    lines.append("")
    lines.append(f"- **Score:** **{score}** / 110  (started at 110, deducted {res['deductions']})")
    lines.append(f"- **Gap to perfect (110):** {110 - score}")
    if score >= CONDITIONAL_THRESHOLD:
        lines.append(f"- **Conditional threshold (>= {CONDITIONAL_THRESHOLD}):** MET "
                     f"(margin {score - CONDITIONAL_THRESHOLD}) - eligible for Conditional status "
                     "if remaining items are POA&M-eligible.")
    else:
        lines.append(f"- **Conditional threshold (>= {CONDITIONAL_THRESHOLD}):** NOT MET "
                     f"(short by {CONDITIONAL_THRESHOLD - score}) - not eligible for Conditional "
                     "certification until the score reaches 88.")
    c = res["counts"]
    lines.append(f"- **Status tally:** met {c['met']}, partial {c['partial']}, "
                 f"not met {c['not_met']}, N/A {c['na']}")
    lines.append("")

    # by family
    lines.append("## Status by family")
    lines.append("")
    lines.append("| Family | Met | Partial | Not Met | N/A |")
    lines.append("|---|---|---|---|---|")
    for fam in sorted(res["by_family"]):
        f = res["by_family"][fam]
        lines.append(f"| {fam} | {f['met']} | {f['partial']} | {f['not_met']} | {f['na']} |")
    lines.append("")

    # POA&M eligibility flags
    lines.append("## POA&M eligibility check")
    lines.append("")
    if not res["poam_flags"]:
        lines.append("No unmet requirement carries more than 1 point of deduction. "
                     "Remaining gaps are most likely POA&M-eligible (still verify against 32 CFR Part 170).")
    else:
        lines.append("The following unmet/partial requirements carry **> 1 point**. The highest-weighted "
                     "security requirements generally **cannot** sit on a POA&M - verify each against "
                     "32 CFR Part 170 before relying on Conditional status:")
        lines.append("")
        lines.append("| Requirement | Points lost |")
        lines.append("|---|---|")
        for rid, w in sorted(res["poam_flags"], key=lambda x: -x[1]):
            lines.append(f"| {rid} | {w} |")
    lines.append("")
    lines.append("> All POA&M items must be closed within **180 days** to convert Conditional -> Final.")

    return "\n".join(lines)


def main():
    ap = argparse.ArgumentParser(description="CMMC L2 / NIST 800-171 SPRS score calculator")
    ap.add_argument("--input", "-i", required=True, help="Path to control-status JSON")
    ap.add_argument("--output", "-o", help="Write Markdown readiness report to this path")
    ap.add_argument("--require-conditional", action="store_true",
                    help="Exit non-zero if SPRS score < 88 (conditional threshold)")
    args = ap.parse_args()

    try:
        with open(args.input) as f:
            data = json.load(f)
    except (OSError, json.JSONDecodeError) as e:
        print(f"ERROR: could not read input JSON: {e}", file=sys.stderr)
        return 2

    try:
        res = compute(data)
        md = render(data, res)
    except ValueError as e:
        print(f"ERROR: {e}", file=sys.stderr)
        return 2

    if args.output:
        with open(args.output, "w") as f:
            f.write(md + "\n")
        print(f"Readiness report written to {args.output}", file=sys.stderr)
    else:
        print(md)

    print(f"SPRS score {res['score']}/110 (deductions {res['deductions']}; "
          f"not met {res['counts']['not_met']}, partial {res['counts']['partial']}).",
          file=sys.stderr)

    if args.require_conditional and res["score"] < CONDITIONAL_THRESHOLD:
        print(f"FAIL: score {res['score']} < {CONDITIONAL_THRESHOLD} conditional threshold.",
              file=sys.stderr)
        return 1
    return 0


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