Python API
==========

The public API is intentionally small. Most callers should load a plan with
``load_plan`` or ``load_tasks`` and then use the CLI or exporters.

Configuration
-------------

``load_plan(path, config=configuration)`` and ``load_tasks`` accept a validated
``Configuration`` object. When omitted, they resolve and load the user file.
``write_docx``, ``write_svg``, ``write_pdf``, and ``write_pptx`` also accept
``config=configuration`` to resolve category and project priority labels. When omitted they load the
standard user configuration. The optional ``sites`` and ``bnrs`` allowlists
validate effective task values. Task types use the built-in vocabulary.
Unknown classification IDs fail before
replacing output. Use nested ``ExportOptions.from_mapping`` selections for new callers.
Legacy low-level option constructors remain supported for compatibility.
Presentation defaults remain independent; pass
``configuration.export`` as ``export_options`` to apply configured settings::

   config = load_configuration("team-config.yaml")
   plan = load_plan("plan.yaml", config=config)
   write_docx(plan, "plan.docx", config=config, export_options=config.export)


.. automodule:: planner.config
   :members: Configuration, VocabularyEntry, IdEntry, load_configuration, initialize_config, default_config_path

Loader
------

.. automodule:: planner.loader
   :members: load_plan, load_tasks

Models
------

``Activity.code`` is the optional labor allocation default. ``Task.code`` holds
the effective task default after activity inheritance; ``StaffCost.code`` records
the actually selected allocation. ``load_plan`` supplies activity context
internally. Direct ``Task.from_mapping`` callers may supply
``activity_codes={"DESIGN": "DEMO_CORE_0000"}`` alongside their funding resolver.


For plans with project commitments, retain the full plan and pass its dependency
definitions when validating or scheduling task collections::

   plan = load_plan("plan.yaml", config=config)
   schedule = build_schedule(plan.tasks, dependencies=plan.dependencies)

``ProjectPlan.dependencies`` contains ``Dependency`` records, while
``ProjectPlan.risks`` contains public ``ProjectRisk`` definitions. ``Task.risks``
remains a tuple of private inline ``Risk`` records. Task dependency references
remain strings. Exporters receive the complete plan to resolve both namespaces.

.. automodule:: planner.models
   :members: ProjectPlan, Task, Milestone, Deliverable, Dependency, ProjectRisk, Risk, Activity, ValidationError, validate_tasks, build_schedule, fiscal_year_range, funding_totals

Deadline Assessments
--------------------

.. automodule:: planner.deadlines
   :members: DeliverableTiming, DeadlineAssessment, assess_deadlines

Export Options
--------------

.. automodule:: planner.export_options
   :members: ExportOptions, TaskTableColumn, export_selection_schema, load_export_options

Exporters
---------

Set ``ExportOptions(elements=("project", "summary", "tasks"))`` to select
top-level output fields. ``elements=None`` selects all; ``elements=()`` selects
none. Pass these options through ``export_options`` in each plan exporter.
The validated plan remains complete for references and derived calculations.


.. automodule:: planner.exporters
   :members: write_docx, write_svg, write_pdf

PowerPoint Plans
----------------

.. automodule:: planner.slides
   :members: write_pptx, find_template

Word Import
-----------

.. automodule:: planner.importers
   :members: import_docx

Object Listings
---------------

.. automodule:: planner.listing
   :members: ListFilter, format_listing

Gantt Exporters
---------------

Both Gantt exporters accept optional ``range_begin`` and ``range_end`` keyword
arguments. Use ``FY26`` for a whole fiscal-year bound or ``M1Q1FY26`` for an
exact fiscal-month bound. The bounds are inclusive.

.. automodule:: planner.gantt
   :members: write_gantt_svg, write_gantt_pptx

Terminal Planning Documents
---------------------------

.. automodule:: planner.terminal_document
   :members: format_plan_document

Staff Funding
-------------

``Task.funding`` continues to map fiscal years to resolved annual amounts. Typed
inputs produce ``ResolvedFunding``, with ``by_type``, ``staff`` (``StaffCost``
records) and ``authored`` attributes retaining the detail.

``load_plan(..., funding_resolver=resolver)`` and
``Task.from_mapping(..., funding_resolver=resolver)`` accept explicit rates
resolution. For example::

   from planner.funding import FundingResolver, RatesCatalog

   catalog = RatesCatalog.from_mapping({
       "rates": [{"id": "STANDARD", "amount": "$300K"}],
       "staff": [{"id": "STAFF_A", "rate": "STANDARD", "fte": "40%"}],
   })
   resolver = FundingResolver(catalog=catalog, labor_costing="annual")
   plan = load_plan("plan.yaml", config=config, funding_resolver=resolver)

An injected catalog bypasses file reads. A resolver holds one rates snapshot;
reuse it only when that snapshot is intentional. Normal ``load_plan`` calls
create a fresh resolver. See :doc:`funding` for calculation rules.

``RatesCatalog.rate_metadata`` maps rate IDs to ``RateMetadata`` records with
optional ``category`` and ``band`` text. Records are present when either field
is supplied. ``RatesCatalog.rates`` continues to contain only resolved monetary
amounts, and staff cost calculations use those amounts.

``RatesCatalog.staff_labels`` maps staff IDs to non-empty display labels.
``staff_label(id)`` returns the label or the ID when none is set. Labels apply
across allocations without changing staff lookup or costs.

Coded staff allocations use ``(staff_id, code)`` tuple keys in
``RatesCatalog.staff`` and ``RatesCatalog.fte``. Uncoded entries retain string
keys. ``allocation_key(id, code="")`` resolves an explicit code, an uncoded
default, or a single unambiguous coded allocation. ``StaffCost.code`` records
the selected code, including when a unique coded allocation was selected by ID.

Grouped staff ``codes`` lists normalize to the same tuple-keyed catalog as flat
coded entries. The parent rate is inherited by child codes unless overridden;
source mappings are not modified. Staff and task lookup APIs are unchanged.

Task Cost Estimates
-------------------

``Task.cost`` returns a ``CostEstimate`` with ``by_type``, ``total``, ``complete``,
``known_subtotal`` and ``shared_parent``. ``as_mapping()`` retains the aggregate
direct-cost mapping, rounding monetary values to whole K with halves up.
Terminal list output uses the separate ``planner.cost_display.cost_view``
projection for annual amounts, staff details and covered attribution. It groups
exact matching values before rounding and never changes resolved funding or
``CostEstimate`` values.
``by_type``, ``total`` and ``known_subtotal`` keep their exact decimal values;
rounding happens after aggregation. It reads existing resolved annual funding
rather than recalculating staff charges. ``Task.funding_excluded`` is true for
complete and closed tasks; their costs and current funding totals are zero.
Completed funding retains its authored input without resolving it. Closed
funding is validated but excluded from calculations. Funding projections mark
both statuses as excluded.

``load_plan(..., allow_incomplete_funding=True)`` opts into list-style resolution.
Alternatively, pass a ``FundingResolver(allow_incomplete=True)`` explicitly.
Default loading remains strict. ``IncompleteAmount`` values retain an exact
known subtotal and reasons; ``funding_totals`` and actual/potential values
propagate them instead of converting them to zero. Only missing calculation
inputs are deferred; malformed data and invalid references still raise. An
unavailable rates snapshot remains unavailable for that resolver's lifetime;
create a new resolver or load the plan again after fixing the file.

Funding range context
----------------------

``load_plan`` resolves typed funding ``fiscal_range`` defaults using the plan's
normalized fiscal years, preserving shorthand in ``ResolvedFunding.authored``.
Direct ``Task.from_mapping`` and ``FundingResolver.resolve`` callers can supply
``fiscal_years=("FY27", "FY28")`` to provide this context. Explicit year entries
replace the range default for that type/year.

Funding coverage
-----------------

``ResolvedFunding.coverage`` stores ``FundingCoverage`` records, separate from
its direct annual dollar mapping. ``load_plan`` resolves references only after
all direct budgets exist. Resolved ``share`` uses Decimal percentage points;
``amount`` and ``source_amount`` are in K. ``remainder`` records ``explicit`` or
``implicit`` for authored remainder attribution, or ``automatic`` for a derived
child split; ``share_description`` supplies
the display label. Before complete-plan resolution, an explicit remainder may
retain the string ``"remainder"`` in ``share``. External omitted shares remain
unquantified; a sole child-to-parent omitted share is inferred after numeric
claims. Complete-plan pools are resolved before filtering without mutating
``ResolvedFunding.authored``. Remainder claims preserve existing authoritative
parent ownership, annual totals and source availability/completeness rules.
``CostEstimate.by_type`` and ``total`` remain direct costs; ``coverage`` carries
included shares, and ``as_mapping`` labels its total as direct when necessary.

``load_plan`` tracks whether a child's funding was inherited with
``Task.funding_inherited``. Complete-plan coverage resolution populates
``ResolvedFunding.inferred_coverage`` with read-only equal remainder splits for
unallocated children, independently of authored ``coverage`` and annual amounts.
``funding_coverage(budget)`` combines both kinds for presentation. Cost display
uses these attributions without changing ``CostEstimate`` aggregate APIs,
financial totals, schedules or authored mappings. Re-running resolution replaces
inferred records rather than counting them as new claims. Stable child IDs place
any non-terminating division's sub-cent residual deterministically; exact split
amounts sum to the remaining source amount. Automatic percentages may be
abbreviated with an approximation marker for presentation.

.. automodule:: planner.coverage
   :members: FundingCoverage, resolve_coverage

Task-date funding range context
--------------------------------

``Task.from_mapping`` resolves typed funding ``range`` from authored start/end
or start/expected. Plan fiscal metadata is unnecessary. Direct
``FundingResolver.resolve`` callers provide normalized ``start``, ``expected``
and ``explicit_timing=True``. Range expansion and annual/duration cost calculation
remain separate.

With incomplete resolution enabled, ``ResolvedFunding.unavailable`` retains
unknown range components by type, alongside known explicit annual amounts.
Unknown ranges have no synthetic fiscal-year keys. Cost and annual funding
aggregation preserve these unknowns; explicit overrides remain known for their
years. Strict callers and exporters reject missing timing. Authored shorthand
remains in ``ResolvedFunding.authored``.

Rates code validation
----------------------

``RatesCatalog.from_mapping`` validates flat staff ``code`` and grouped
``codes[].id`` against ``[A-Z0-9]{4}_[A-Z0-9]{4}_[A-Z0-9]{4}``, trimming
surrounding whitespace. Invalid values raise source-aware ``ValidationError``.
Uncoded allocations and the syntax of staff/rate IDs remain unchanged.

Implicit parent attribution
-----------------------------

``Task.from_mapping`` passes the loader's multipart funding context to coverage
parsing, allowing child ``share`` entries to infer their authoritative parent.
Explicit child-to-parent references use the same resolution and share pool.
Direct ``FundingResolver.resolve`` callers can supply ``coverage_parent`` when
parsing a child's budget; complete-plan ``resolve_coverage`` still validates
ownership and sources. Child cost estimates retain declared attribution, while
parent summaries and financial aggregation retain the full owned budget.

Monetary display and parent categories
---------------------------------------

``planner.budget.display_funding`` rounds monetary presentation to whole K with
halves up. ``money_text``, task funding, ``funding_totals``, project budget values
and staff/coverage amounts retain exact values for calculations and API callers.
List/export renderers apply rounding at their boundaries after aggregation,
including incomplete known subtotals. Budget comparison colors are selected
before display rounding.

For a derived ``ParentSummary``, ``category`` is the common scalar ID or a tuple
of distinct child IDs in authored part order. ``categories`` always returns a
tuple. Canonical source ``Task.category`` remains scalar. Classification helpers
render each parent category through the active vocabulary; table values use
newline-separated codes and each Word/PDF paragraph retains column alignment.

Monthly staff costs
-------------------

``RatesCatalog`` retains scalar values or normalized ``EffectiveHistory`` and
``FTEProfile`` records for authored histories. ``StaffCost.monthly`` contains
``StaffMonth`` records with the canonical fiscal period, available FTE, selected
rate ID and annual full-time rate used for each costed month. Annual funding
remains rounded once per staff/code/year. ``StaffCost.fte`` and ``annual_rate``
are ``None`` when their monthly values vary; ``rate_id`` is empty when multiple
rate IDs apply. Constant profiles retain the previous summary values.

Staff Subscription
------------------

``staff_subscription(plan, catalog, year=None, month=None)`` builds a read-only
``StaffReport`` of monthly ``StaffSubscription`` rows for every catalog
allocation. Use the same rates snapshot/catalog that resolved the plan's funding.
``staff_demands(tasks)`` supplies canonical direct budget-owner claims and is
also used by overcommitment validation. Plan validation uses the loaded catalog
to compare those claims with the same monthly person capacity as the report.
``StaffReport.person`` returns a
``PersonSubscription`` named tuple: ``subscription``, ``availability``,
``allocated``, ``proposed``, ``complete`` and ``proposed_complete``. Configured
capacity sums coded allocations or uses the uncoded allocation. If both exist,
use the larger alternative pool, not their sum. Person availability subtracts
total subscription from configured capacity and is unknown when capacity or
demand is unknown. It is not a balance against an assumed 100% FTE.

In ``StaffSubscription`` code rows, ``available``, ``used``, ``remaining`` and
``proposed`` retain their Decimal FTE meanings (allocated, subscribed, available
and proposed effort). ``subscription`` is the code-allocation percentage.
Text output names the FTE value Subscribed and the remaining FTE Available. CSV uses explicit ``allocated_fte``, ``subscription_fte``,
``availability_fte`` and ``code_subscription_percent`` column names.
``complete`` and ``proposed_complete`` describe demand completeness. Unknown
availability or incomplete demand yields ``remaining=None`` and
``subscription=None``; zero availability also has no subscription ratio.
``used`` and ``proposed`` retain known subtotals when demand is incomplete.
``format_staff_subscription`` provides terminal output;
``staff_subscription_csv`` provides monthly CSV. Display filters do not mutate
the full report or change person totals.
