Needs

Every key, with its type and default: [needs].

The [needs] section is the heart of your ubproject.toml. It tells ubCode how to identify, validate, and relate the need objects in your reStructuredText files — types, link types, custom fields, statuses, tags, and external needs.

A key that takes one boolean, number or string (id_required, id_length, flow_engine, …) and is given a value of another type (id_required = "yes", id_length = -1, flow_engine = 1) is reported against ubproject.toml under the config code, naming the key and what was given, and is then ignored: the key takes its default, not a value from a file it extends, and the rest of the file still applies. The same holds for such a key given with -c: the key takes its default, not the file’s value. Sphinx-Needs, reading the same file, usually warns and goes on with the value as written. variant_data_file is the exception: a value of the wrong type stops the configuration loading, as it stops a Sphinx-Needs build.

See also

Key concepts

Minimal example

[needs]
id_required = true
id_regex = "^[A-Z]{3}_[0-9]{3}$"

[[needs.types]]
directive = "requirement"
title = "Requirement"
prefix = "REQ_"

[needs.links.implements]
outgoing = "implements"
incoming = "implemented by"

[needs.fields.priority]
description = "Priority level"

Core options

id_required

Type: boolean (default: false)

If true, every need must have an explicit ID. If false, IDs will be auto-generated when not provided.

id_regex

Type: string (default: "^[A-Z0-9_]{5,}")

Regular expression pattern every need ID must match, as Sphinx-Needs applies it: matched from the start of the ID, with nothing required after the match (Python’s re.match; end the pattern with $ to require the whole ID), in Python’s syntax, lookarounds and backreferences included, as the regex and fancy-regex crates read it: a rare construct reads differently ([[A-Z]]+ is a nested class here and a literal [ in Python; (a+)+\1b refuses aaab, which Python matches). An ID that does not match is reported as needs.id_regex, an ID generated for a test-report need included, and the need is kept (a Sphinx build does not create it). A need type may add a pattern of its own (id_regex on its entry, see the ids of a type). "" turns the check off. A pattern ubCode cannot read is reported against ubproject.toml under the config code, and then no ID is checked. With namespaced_ids on, a pattern accepts an ID whose local id matches (it is tried first), or which matches as a whole: with the default, nc::REQ_00001 is accepted through REQ_00001, SUPPLIER::REQ_1 as before, and nc::req is refused, the finding naming its local id too. So a pattern cannot be used to refuse a namespace: a project that wants none leaves namespaced_ids off.

namespaced_ids

Type: boolean (default: false)

Added in version 0.40.0.

When true, every need ID that holds :: is read as a namespace and a local ID, split at its last ::: nc::m2::REQ_1 is the local ID REQ_1 in the namespace nc::m2 (Namespaced ids). The ID itself is unchanged. With it on, filters read c.id.ns, c.id.local and c.in_namespace(), the ID patterns accept a matching local ID, an ID the project writes that holds :: but does not split cleanly is reported (needs.id_namespace), and dead links and need-id completion know the local ID. With it off, those three names still read every need as in no namespace, and a filter that reads one of them is reported (needs.namespaced_ids_off), naming this key. Off by default in this release; it becomes the default together with Sphinx-Needs 10.0. Turn it off (or leave it unset) in a project whose IDs hold :: for another reason, such as a C++ name. Changing it re-reads every document.

id_length

Type: integer (default: 5)

Length of auto-generated IDs when not explicitly provided. At least 1 (config.value_below_minimum reports 0; a negative value is reported and ignored).

id_from_title

Type: boolean (default: false)

When true, auto-generated IDs will be based on the need title instead of being random.

title_optional

Type: boolean (default: false)

When true, allows needs to be created without a title.

title_from_content

Type: boolean (default: false)

When true, auto-generates titles from the first line of need content when no title is provided.

default_layout

Type: string (default: "")

The card design every need with no :layout: of its own is drawn with.

The value is any design this project knows — see the list under [needs.fields.layout] for what that means, and Card designs with [needs.card_layouts] for what each design shows. A :layout: written on the need itself wins over this, and so does a value a [needs.fields.layout] default or predicates row puts on the need: this key only catches needs that end up with no value at all. An empty string is the same as unset, which is the same as clean — the design that draws ubCode’s ordinary card. A value naming no known design is reported and treated as unset.

[needs]
default_layout = "complete"

Moving the default changes what writing nothing means, so :layout: clean stops being a no-op and becomes a deliberate override: under the example above, a need with no :layout: draws complete and a need with :layout: clean draws clean.

This is the ubCode spelling of Sphinx-Needs’ needs_default_layout, and it is the same key in the same table: needs_from_toml maps [needs] default_layout onto needs_default_layout, so a ubproject.toml shared between sphinx-build and ubc build html now means one thing to both. Two behaviours differ deliberately — an empty string is unset here and a build error there, and an unknown name is reported here rather than aborting the build; see Differences from a Sphinx build.

views_max_items

Type: integer (default: 100)

The default :max_items: cap for the view directives (needlist, needtable, needflow and needsequence).

A view that sets no :max_items: of its own renders at most this many items and appends a notice saying how many of how many are shown; a view that sets one uses its own value instead. Set 0 for no cap — from either source. The cap applies after the filter and the sort, in both the editor’s rendered preview and ubc build html. A build also emits a build.need_view_truncated warning for each truncated view, so a capped view is visible in the build log without opening the built page.

table_style

Type: string (default: "datatables")

The style a needtable renders in when it sets no :style: of its own.

datatables is the interactive table: the reader sorts by column, filters, pages, hides columns, and copies or downloads the rows as CSV, all in the browser. table is the static one — a scroll frame with a sticky header row and no client-side behaviour. A needtable that sets its own :style: uses that instead; a :style: naming neither style falls back to this key, as it does in a Sphinx-Needs build.

This is the ubCode spelling of Sphinx-Needs’ needs_table_style, with the same default and the same two values. Nothing called DataTables is involved: the interactive table is ubCode’s and Sphinx-Needs’ own shared asset, and the value keeps its name because it is the one both tools already write.

table_page_size

Type: integer (default: 10)

How many rows an interactive needtable shows per page.

A needtable that sets its own :page_size: uses that instead, and a reader can choose another size from the table’s own control. It must be a positive integer — 0 means “All” in the offered sizes below, not a page size — and an invalid value is reported and this default used. A :style: table table ignores it and shows every row it rendered.

table_page_sizes

Type: list[integer] (default: [10, 25, 50, 0])

The page sizes an interactive needtable’s control offers, where 0 means All.

Must be a non-empty list of non-negative integers. The page size actually in use is added to the list when it is not already there, so the control can always show the size the table is on.

part_prefix

Type: string (default: "→ " — a right arrow and a non-breaking space)

The text put in front of a need part’s ID and content in a needtable that sets :show_parts:.

It marks a part’s row as belonging to the need above it. The default’s space is non-breaking on purpose, so the marker cannot wrap away from what it labels. Set "" for no prefix at all. It applies in the editor’s rendered preview and in ubc build html alike, and nothing but a :show_parts: table reads it.

This is the ubCode spelling of Sphinx-Needs’ needs_part_prefix, with the same default.

report_template

Type: string (default: "")

A Jinja template file that every .. needreport:: in the project renders from, instead of ubCode’s built-in report. A relative path is taken from the directory holding ubproject.toml; an absolute one is used as written. Unset — or set to "" — renders the built-in report.

A directive’s own :template: option wins over this key, and resolves differently: relative to the document that writes it, with a leading / meaning relative to the project source root — which it may not leave. A :template: that resolves outside the source root is refused (needs.report_template_outside_project) and the built-in report renders instead; this key is the supported way to use a template that lives outside it, because you write it in the project’s own configuration file rather than in a document. (With no ubproject.toml at all there is no configured source root, and the boundary is the host document’s own directory — the diagnostic says which of the two it used.)

[needs]
report_template = "templates/report.need"

The template must produce reStructuredText, and is given the same five names a Sphinx-Needs build supplies:

Name

Value

types

one entry per configured need type, in declaration order, with the keys directive, title, prefix, color and style

links

one entry per configured link type, with the keys option, incoming, outgoing, copy and allow_dead_links

options

the project’s extra field names

usage

needs_amount and needs_types (a count per configured type)

report_directive

the string dropdown

A section the directive did not ask for arrives as the empty value rather than as a missing name, so a template can always reference all five and guard with {% if types|length != 0 %}.

{% if types|length != 0 %}
.. dropdown:: Need Types
{% for type in types %}
   * {{ type.title }} (``{{ type.directive }}``)
{%- endfor %}
{% endif %}

Requirements: :need_count:`type == "req"`.

Two practical notes:

  • Give the file an extension your project does not build — .need or .txt, not .rst or .md — or it is also indexed as a document of its own. (The Sphinx-Needs documentation gives the same advice.)

  • Python method calls work in every ubCode Jinja surface, this one included: link.get('copy', None), d.items() and s.upper() all resolve, so a template written for a Sphinx-Needs build runs unchanged.

If the template cannot be used, the directive renders the built-in report and says why — needs.report_template_not_found, needs.report_template_outside_project or needs.report_template_failed.

flow_direction

Type: string (default: "down")

The default layout direction for needflow diagrams — where the graph grows.

One of down, up, right or left, or the equivalent engine tokens TB/TD, BT, LR and RL. A needflow that sets its own :direction: uses that instead. An empty string is the same as unset.

flow_show_links

Type: string or boolean (default: "none")

The default edge labelling for needflow diagrams.

outgoing and incoming label each edge with the link type’s corresponding display name, type labels it with the link type’s own name, and none leaves edges unlabelled. true means outgoing and false means none, so a value carried over from Sphinx-Needs’ needs_flow_show_links means the same thing here. A needflow that sets its own :show_link_names: uses that instead, including :show_link_names: none to leave one diagram unlabelled in a project that labels edges by default. An empty string is the same as unset.

flow_show_legend

Type: string (default: "")

Which named legend a needflow gets when its :show_legend: names none.

The value is a key of flow_legends below. This selects which legend a diagram gets, never whether it gets one: only a :show_legend: on the directive itself draws a legend, so setting this cannot add a legend to a diagram that did not ask for one. A needflow whose :show_legend: names a key uses that key instead. An empty string is the same as unset, which leaves the choice to the diagram engine — for the Mermaid flowcharts ubCode draws, a table beside the diagram listing the drawn need types. A value naming no configured legend is reported and treated as unset.

flow_legends

Type: table of tables (default: none)

The project’s named legend configurations, each selected by name from a needflow’s :show_legend: or by flow_show_legend above.

[needs.flow_legends.wide]
parts = ["types", "links"]
placement = "external"
parts

The sections the legend lists, as a list, in the order they are drawn: types (each drawn need type with its colour) and links (each drawn link type with its display name). Unset is the same as ["types"].

Order is significant. parts = ["links", "types"] draws the link table first. That is why this key is a list and not a single name: a name per combination could not express order without inventing one per permutation.

parts = ["types"]            # just the need types
parts = ["types", "links"]   # both tables, types first
parts = ["links", "types"]   # both tables, links first

A list is the only accepted spelling. A bare string is reported, with the list form to write instead.

placement

Where the legend is drawn: internal (inside the diagram itself) or external (a table beside it). Unset takes the diagram engine’s default placement, which for the Mermaid flowcharts ubCode draws is external.

internal is a preference, not a guarantee. An engine that cannot draw a legend inside the diagram draws the external one instead, with the same rows. Mermaid is such an engine — its flowchart syntax has no legend construct — so ubCode always draws the external table and says nothing about it. The key is still worth setting for a project whose ubproject.toml is shared with a Sphinx-Needs build, where internal is honoured and is that engine’s default.

Every mistake in a legend costs only what it names, and the legend still renders: an unknown section is reported and skipped, a repeated one is reported and kept once, and an empty or non-list parts is reported and takes the default. A legend name that could never be selected — one that is empty or has surrounding whitespace — is reported and the entry is ignored.

diagram_template

Type: string (default: "")

The per-node Jinja template that a .. needuml:: or .. needarch:: body’s flow() renders each need with, and that each node of a .. needflow:: drawn by a PlantUML executable is drawn from ([build.plantuml] needflow). Unset — or set to "" — uses ubCode’s built-in template, which is byte-identical to the Sphinx-Needs default.

[needs]
diagram_template = """{{ need.type_name }} {{ need.id }}"""

The template produces PlantUML, is given the need as need, and sees every name [needs.render_context] adds.

This is the ubCode spelling of Sphinx-Needs’ needs_diagram_template, with the same default. For a needuml ubCode transpiles the produced diagram to Mermaid rather than rendering it with PlantUML, so a template that emits a PlantUML construct Mermaid has no equivalent for is reported (needs.uml_unconvertible) rather than drawn — or, when only part of the diagram is affected, needs.uml_partially_converted, which names the lines that are missing. A needflow drawn by a PlantUML executable has no such limit — the executable draws whatever the template produced, with one narrowing: a % or an & in the produced label is escaped, so a template that deliberately writes %version() or %date("yyyy") draws that text literally here where a Sphinx build lets PlantUML’s preprocessor expand it. (The label is a need’s data; a [needs.flow_configs] block is not, and its content is spliced verbatim — that is the one place a PlantUML built-in is honoured.) A needflow drawn as a Mermaid flowchart does not read this key at all: it draws the same three parts (the type title, the wrapped title in bold, the id) in Mermaid’s own label syntax.

[needs.render_context]

Type: table of string → value (default: empty)

Extra names every template ubCode executes can read — a needuml or needarch body, diagram_template, and the needreport report_template.

[needs.render_context]
product = "ubCode"
release = "2026.1"

Values may be strings, numbers, booleans, arrays of those, or nested tables. A TOML date-time is reported as a config diagnostic at needs.render_context — quote it as a string (release = "2026-01-01"); one inside an array is a configuration error, like an array of tables or of arrays.

Names here do not reach two template surfaces, deliberately: [needs.string_links] templates and needs_role_need_template. Both see their pattern’s named capture groups and nothing else, which is also what keeps a project-wide name from silently shadowing a capture group called value.

This is the ubCode spelling of Sphinx-Needs’ needs_render_context.

flow_engine

Type: string (default: "")

Added in version 0.36.0.

Which engine draws the project’s needflow diagrams.

[needs]
flow_engine = "plantuml"

plantuml asks for them to be drawn by the PlantUML executable [build.plantuml] names, and graphviz asks for them not to be — ubCode has no Graphviz pathway, so graphviz means “not PlantUML” rather than naming a second engine. Any other value is reported once for the project (config, at needs.flow_engine) and ignored.

This is only the default: [build.plantuml] needflow — or a builder’s own [build.html.plantuml] / [build.pdf.plantuml] — wins over it, and a diagram’s own :engine: wins over both. Drawing with PlantUML also needs [build.plantuml] enabled, since that is what names the executable. Unset (or "") leaves the choice to [build.plantuml] needflow, which is off by default.

This is the ubCode spelling of Sphinx-Needs’ needs_flow_engine, and it is read here so that one ubproject.toml shared by both tools need not say the same thing twice. Where the two halves of that shared file disagree — this key saying graphviz while [build.plantuml] needflow is true, or the reverse — ubCode follows the build key and a Sphinx build of the same file follows this one, so the same project draws its diagrams with different engines in the two tools. Neither tool reports it: each is doing what its own precedence rules say. If you want one answer from both, set only this key and leave [build.plantuml] needflow unset.

[needs.flow_configs]

Type: table of string → string (default: empty)

Named blocks of PlantUML configuration that a .. needuml::, .. needarch:: or .. needflow:: pulls in with its :config: option. Each value is a block of PlantUML lines; the option names one or more blocks, comma-separated, and their lines are prepended to the produced diagram.

[needs.flow_configs]
monochrome = """
skinparam monochrome true
skinparam shadowing false"""
.. needuml::
  :config: monochrome

  {{ flow('R_LOGIN') }}

A :config: naming a block this table does not define is reported (needs.uml_config_unknown) and contributes nothing; a Sphinx build is silent about it, which leaves a diagram that renders perfectly and merely looks wrong. The two needflow direction names below are the exception: they are read as a direction rather than looked up here, so they are never reported.

Because ubCode transpiles the produced diagram to Mermaid rather than rendering it with PlantUML, a block’s lines reach the diagram but only the ones Mermaid has an equivalent for change what is drawn — skinparam in particular is dropped. Adding :debug: to the directive shows the produced PlantUML with the block’s lines in place, which is the way to check that a name resolved.

A needflow inserts a named block’s lines only when it is drawn by a PlantUML executable ([build.plantuml] needflow), and then exactly as they are inserted for a needuml. Its :config: is read on both arms for the layout DIRECTION, though: a block containing left to right direction or top to bottom direction sets that direction as the low-precedence source for the diagram’s :direction:, which is how Sphinx-Needs reads it, and a block setting both resolves to top-to-bottom as it does there. Two names also work with no entry behind them: lefttoright and toptobottom are read as the direction itself and are never reported as unknown — Sphinx-Needs ships them as entries of this table and ubCode ships none, so the two spellings are built in instead. A block defined under either name is read like any other block: its content decides the direction, and the name does not override it. Because a block’s content is spliced verbatim, it is also the one place a PlantUML built-in such as %version() is honoured — a % in a need’s title or in a diagram_template’s output is escaped and drawn literally, but configuration you wrote is passed through as you wrote it, exactly as Sphinx-Needs passes it.

This is the ubCode spelling of Sphinx-Needs’ needs_flow_configs.

Need types

types defines the available need directives in your project, as an array of [[needs.types]] entries:

[[needs.types]]
directive = "requirement"  # The RST directive name
title = "Requirement"     # Human-readable title
prefix = "REQ_"          # Prefix for auto-generated IDs
color = "#BFD8D2"        # Color for diagrams and the need-card accent
style = "node"           # Style for diagrams

Each type supports:

  • directive (required): The reStructuredText directive name

  • title (required): Human-readable title for the need type

  • prefix (required): Prefix used for auto-generated need IDs

  • color (optional, default: "#000000"): Color used in need diagrams and as the accent on this type’s need cards, where it outlines the type badge and paints the card’s leading edge. An explicit *_border style frames all four edges and takes that one; on cards that show a type badge, the badge outline still carries the type colour (the focus layout family shows no badge, and a hidden card’s badge outline is zero-width). The card accent applies only to a colour you have chosen — see When a type colour accents a card below. Cards use only #RGB, #RRGGBB and #RRGGBBAA values; any other value is ignored for the card. Diagrams are unaffected and always use the color.

  • style (optional, default: "node"): Style used in need diagrams

  • directive_name (optional): whether the bare directive writes this type’s need where another directive has the same name; unset, [needs] directive_name applies (see When a type’s directive is another directive’s name)

prefix and color may be "". A directive may not contain :: every type is also written need:<directive> (see When a type’s directive is another directive’s name). A project that sets types replaces the four built-in types (req, spec, impl, test) with its own, once an entry gives a title or a prefix.

An entry naming a built-in type with neither title nor prefix narrows that type: it keeps the built-in’s title and prefix, and its color and style where it gives none, and its own fields, links and inherits apply. While no entry gives a title or a prefix, all four built-in types are kept, each narrowed in place by the entry naming it, so a rule on a built-in type needs no copy of the type:

[needs.fields.summary]

# `req`, `spec`, `impl` and `test` all stay; `req` gains a rule
[needs.types.req.fields.summary]
derive = { kind = "copy", field = "title" }

Once an entry gives a title or a prefix, the types are the entries given, and a bare entry naming a built-in type is that type, narrowed, at its own position. An entry with neither key naming a need type [test_reports] adds narrows that type in the same way (see What the section adds). An entry with neither key naming any other type is ignored and reported, and declares nothing (need, a default type of Sphinx-Needs, is no built-in type here); the warning names derive_by_type (The derive_by_type table), the spelling for a rule on a type the project does not declare. An empty types (types = []) declares no type.

The table shape

Instead of the array, types can be one [needs.types.<directive>] table per type, keyed by the directive name:

[needs.types.req]
title = "Requirement"
prefix = "R_"
color = "#BFD8D2"

[needs.types.spec]
title = "Specification"
prefix = "S_"
color = "#FEDCD2"

is the same as

[[needs.types]]
directive = "req"
title = "Requirement"
prefix = "R_"
color = "#BFD8D2"

[[needs.types]]
directive = "spec"
title = "Specification"
prefix = "S_"
color = "#FEDCD2"

The two shapes are equivalent, and the types keep the order they are given in both: it is the order needreport lists them in. (The needflow legend lists the drawn types alphabetically, where Sphinx-Needs follows this order.) This is the ubproject.toml spelling of Sphinx-Needs’ needs_types given as a dictionary.

What is reported

An entry that cannot be used does not stop the configuration from loading. Each problem is a config.need_type warning (see Configuration diagnostics (config and config.*)) at the entry’s key, and the project goes on without what cannot be used:

  • an entry that is not a table is ignored;

  • an entry that names no directive is ignored: in the array, a directive that is missing or not a non-empty string; in the table shape, an empty key. A directive inside a [needs.types.<directive>] table that differs from its key is reported, and the key is used;

  • an entry whose title or prefix is missing or not a string is ignored: its type does not exist (an entry giving neither, naming a built-in type, narrows that type instead: see above);

  • an entry whose directive contains : is ignored: its type does not exist;

  • a color or style that is not a string is ignored, and its default is used;

  • a directive_name that is not "claim", "yield" or "qualified" is ignored, and [needs] directive_name applies;

  • a key other than directive, directive_name, title, prefix, color, style, inherits, fields, links, back_links (incoming links) and id_regex (the ids of a type) is ignored, and the type kept;

  • an inherits that is not a non-empty string, or a fields, links or back_links that is not a table, is ignored, and the type kept; so is a declaration in one of them that is not a table, and a key of a declaration it does not take or that is not of its shape (see Fields per need type);

  • a directive declared more than once in the array: the last entry is used, at its own position, and one warning names every entry that declares it.

A types value that is neither an array nor a table declares no type, and is reported; Sphinx-Needs stops the build on it instead.

When a type’s directive is another directive’s name

Every need type has two directive names: its bare directive (.. step::) and the qualified need:<directive> (.. need:step::, or a {need:step} fence in MyST), which always writes the type’s need, whatever other directives the project has (see The qualified spelling: need:<type>).

When another directive has the bare name — a sphinx-design step, Sphinx’s todo, a docutils note, a [parse.extend_directives] entry — directive_name decides which directive the bare name is. Set it under [needs] for every type, or in a [[needs.types]] entry for that type alone, which wins:

directive_name

.. step::

.. need:step::

"claim" (unset is the same)

The need; the other directive is not available in the project.

The need.

"yield"

The other directive, when the project has one; otherwise the need.

The need.

"qualified"

Never the need: the other directive, or an unknown directive.

The need.

So a project can keep its step needs and use sphinx-design’s steps side by side:

[[needs.types]]
directive = "step"
title = "Test step"
prefix = "ST_"
directive_name = "yield"
.. need:step:: Press the button
   :id: ST_001

.. steps::

   .. step:: Install

      The sphinx-design step, as before.

Under "yield", the other directives that keep a bare name are: a built-in directive ubCode knows (a docutils or Sphinx directive, a domain directive such as option, and the directive of an extension port, only while that port is on); a directive of an active sphinx-test-reports; a [parse.extend_directives] entry; and a name in [parse] ignore_directives.

What is reported. While directive_name is unset (for the type and under [needs]), a type that takes another directive’s name is reported once, at its entry: as the warning config.conflicting_directive_registration, as Sphinx warns (app.add_directive) when the later registration wins; and, for the directive of an extension port that is on only by default ([parse] extensions does not name it: todo, sphinx-design’s directives, video, …), as the information config.port_directive_name_kept instead, so that a project that built without warnings still does. With the port switched off, nothing is reported: the name is not the port’s. Setting directive_name, to any value, says the clash is intended, and nothing is reported for it. A directive_name under [needs] that is not one of the three values is reported and ignored.

Fields per need type

A need type may declare fields and link types anew for its needs, in its entry:

  • fields: a table from the name of a field – one of [needs.fields] (or extra_options), a core field such as status, a field [codelinks] or [test_reports] adds, or a name nothing else declares, a field of this type’s needs alone (below) – to the type’s declaration of it;

  • links: a table from the name of a link type – one of [needs.links] (or extra_links), links, or a name nothing else declares, a link type of this type’s needs alone (below) – to the type’s declaration of it;

  • inherits: the directive name of one other need type, whose declarations this type starts from.

A declaration in fields may set description, schema (only the keywords it changes), nullable (false where the field is nullable, never true where it is not), default and predicates (in place of the field’s; [] is none), and derive, a rule computing the field on the type’s needs (below). A declaration in links may set description, schema (maxItems, minItems, …), default, predicates, derive, and target_types, the need types the links of the type’s needs may point to, within those it inherits (the subtypes of a listed type included), never others (below), and, of a link type declared on need types alone, the keys a [needs.links] entry gives a link type for every need type: incoming, outgoing, copy, allow_dead_links, summary, color, style, style_part, style_start and style_end (below).

[needs.fields.asil]
nullable = true
schema = { type = "string", enum = ["QM", "A", "B", "C", "D"] }

[needs.types.req]
title = "Requirement"
prefix = "R_"

[needs.types.req.fields.asil]
nullable = false
default = "QM"

[needs.types.safety_req]
title = "Safety requirement"
prefix = "SR_"
inherits = "req"

[needs.types.safety_req.fields.asil]
schema = { enum = ["A", "B", "C", "D"] }
default = "A"

[needs.types.safety_req.links.links]
schema = { maxItems = 3 }

Here a req has an asil (QM unless it says), a safety_req one of A to D (A unless it says), a safety_req links to three needs at most, and the needs of every other type read asil and links as declared for all. In the array shape, a [needs.types.fields.asil] table after the [[needs.types]] tables belongs to the last of them.

Where the asil and hazard of each type’s needs come from, in this example, with the hazard field safety_req declares alone (see below) and a test type that declares neither:

        flowchart LR
  field["[needs.fields.asil]<br/>nullable, enum QM, A, B, C, D<br/>no default"]
  req["req declares asil<br/>not nullable, default QM"]
  safety["safety_req inherits req<br/>and declares asil:<br/>enum A, B, C, D, default A"]
  hazard["safety_req declares hazard<br/>no [needs.fields] entry declares it"]
  test_type["test declares no asil"]
  req_need(["a req need<br/>asil: QM unless it says<br/>hazard: null, a value set is ignored"])
  safety_need(["a safety_req need<br/>asil: A unless it says, one of A to D<br/>hazard: null unless it says"])
  test_need(["a test need<br/>asil: null unless it says<br/>hazard: null, a value set is ignored"])
  field -->|narrowed by| req -->|narrowed further by| safety
  field -->|as declared for all| test_type
  req --> req_need
  safety --> safety_need
  hazard --> safety_need
  test_type --> test_need
    

Narrowing. A type’s declaration of a field starts from the field’s own declaration, takes the declarations of its ancestors from the root down, then its own; a key it leaves out, and a schema keyword, is kept from the declaration before it. Each declaration must narrow the one before it, so that a need of the type is valid wherever a need of any type is: a schema keyword only becomes stricter (an enum a subset, a minimum higher, a maxItems lower, …), nullable only changes from true to false, and a default – the type’s own, or the one it keeps – is valid against the narrowed schema (so an enum that leaves out the field’s default needs a default inside it). The empty value of the field’s type ([], "", 0, false), kept from the field’s own declaration, is no default: a minItems needs no default, and makes a need of the type without a value fail validation. An ancestor that sets default = [] itself sets one, which a child’s minItems must admit. A link type’s target_types narrows too. A declaration accepts each type it lists and every type inheriting from one of them, and it may accept only types that the declaration before it accepts. Say hw_test inherits test, and test gives verifies the target types ["req"]. Then hw_test may give ["safety_req"], because a safety_req inherits req and so is accepted already. It may not give ["spec"] or ["req", "spec"]: a spec is not accepted for a test, so that widens.

[needs.types.test.links.verifies]
target_types = ["req"]

[needs.types.hw_test]
title = "Hardware test"
prefix = "HT_"
inherits = "test"

[needs.types.hw_test.links.verifies]
target_types = ["safety_req"]

A declaration that gives no target_types, or names no need type in it, keeps the target types before it, and the need type that gave them is the one a needs.link_target_type warning names; where no declaration before it gives any, the links may point to any type. The names that are no need type are one config.need_type warning per declaration, and ignored. A declaration that widens is ignored as a whole, its other keys included, and the type keeps the declaration before it; each reason is one config.type_widening warning:

needs.types.hw_test.links.verifies: widens the link type as need type 'test' declares it: Child 'target_types' accept 'spec', which parent 'target_types' 'req' (or a type inheriting from it) do not.

inherits. A type has one parent, given before or after it, or added by [test_reports]. A type with no declaration of its own of a field reads its parent’s. An inherits naming no need type, or on a cycle, is ignored, and the type stays, without a parent: one config.type_inherits warning each, every type on a cycle reported. A filter’s c.is_a('req') selects a req and every type inheriting from it, however deep (see Special functions), and so does the Cypher label (:req) (see Need types and inherits); type == 'req' and n.type = 'req' compare the type’s name alone.

derive. A derive in a declaration is the field’s (or link type’s) derive_by_type entry for the type, and for each type inheriting from it that gives no derive of its own: the field is then derived on every need type, closed to authors there too, and a need of a type without a rule holds what derive_by_type says. Beside a derive_by_type entry of the field for the same type, it is one config warning, and the derive_by_type entry is used for that type alone: the types inheriting from it, without a rule of their own, still read the entry’s rule. A rule that cannot be read is config.derive_invalid at the entry it came from (needs.types.task.fields.total.derive), and a rule on a core field or on parent_needs is refused there the same way.

A field or link type that need types declare alone, such as hazard and verifies below, reaches the type that declares it and the types inheriting from it, never the types above it or beside it:

        flowchart LR
  req["req"]
  safety["safety_req<br/>inherits req"]
  test_type["test"]
  hazard["hazard<br/>declared by safety_req alone"]
  verifies["verifies, a link type<br/>declared by test alone"]
  req_need(["a req need<br/>hazard: null, verifies: []<br/>a value set is ignored, needs.undeclared_for_type"])
  safety_need(["a safety_req need<br/>hazard: as safety_req declares it<br/>verifies: [], a value set is ignored"])
  test_need(["a test need<br/>verifies: its links<br/>hazard: null, a value set is ignored"])
  req -->|inherited by| safety
  hazard --> safety
  verifies --> test_type
  req --> req_need
  safety --> safety_need
  test_type --> test_need
    

Every type that declares such a name agrees on its shape, which the first declaration of a type without a declaring ancestor sets, in the order the types are resolved (a parent before its children): for a field, the first that gives a schema type sets that type and whether the field is derived; for a link type, the first, an empty one too, sets whether it is derived, its labels, its styles, copy and whether dead links are allowed. Another declaration that disagrees with the shape is ignored, as a config.type_conflict warning. The rules in full are in the two paragraphs below.

Fields declared on need types alone. A fields entry naming a field nothing else declares – no [needs.fields] or extra_options entry, no core field, no field [codelinks] or [test_reports] adds, no link type, nor a link type’s back links (<link>_back) – declares a field of the types that declare it, by their own entry or an ancestor’s; an entry that changes nothing ([needs.types.spec.fields.x] with no key) declares the field as it is.

[needs.types.safety_req.fields.hazard]
description = "The hazard a safety requirement mitigates"
schema = { type = "string" }

Every type that declares it agrees on its type, its items’ type, and whether it is derived; each is free in the rest. The first declaration of a type none of whose ancestors declares the field – in the order the types are resolved (a parent before its children; the members of a broken inherits cycle up from the first type given that is on it or inherits into it, the last reached first) – that gives a schema type sets them; the first declaration of an array field gives its items’ type too. Such a declaration that gives no type takes the agreed one, and a child narrows its parent’s as for any field. A declaration of another type, or derived where the field is not (or the other way round), is one config.type_conflict warning, and does not declare the field, so a child’s entry under it is a declaration of its own; an entry that cannot be used for another reason (it widens, or its default cannot be used) declares the field all the same. A field no such declaration gives a type is refused on every entry, and does not exist. A name close to one the project declares otherwise – a core field an author sets (status, hide, …), a field of [needs.fields], extra_options, [codelinks] or [test_reports], or a link type – is likely misspelt: [needs.types.req.fields.asl] beside a [needs.fields.asil] is one config.type_near_name warning at its first declaring entry (“did you mean ‘asil’?”), and the field is declared all the same. Close is a similarity ratio of 0.8 or more, as Python’s difflib measures it (Sphinx-Needs calls it, and ubCode computes the same ratio), so a deliberate plural (owners beside owner) is reported as well: ignore the code to keep it. Names need types declare alone are not compared with each other. The same holds for a link type need types declare alone. A derived field declared on need types alone takes no enum.

The field is declared once for all, nullable and without a default, which each declaring type narrows: one that declares it not nullable, with no default, requires it on its own needs alone. On a need of a type that does not declare it, the field holds null (a derived one too), and the need stores nothing for it. A value set for it there is ignored, as one needs.undeclared_for_type warning:

Field 'x' is not declared on need type 'spec' and cannot be set in need 'S_001'; the value '4' is ignored

in a need directive and a list2need item at the option, and for a need a needimport imports at the needimport; a need from external_needs drops it with the same warning, at the source. From outside, a value equal to the null the need holds anyway is dropped silently, and on a type that declares a derived field, its value from outside is kept, as data. A needextend setting, appending to or deleting it does not extend the needs of the type, one needs.needextend warning for each needextend, need type and option:

Option 'x' does not support extend operations on need type 'spec'; it does not extend 3 needs (S_001, S_002, S_003).

The field is a field of the project: its value enters the fingerprint of a need where it is not null, never on a need of another type. Every reader knows it as any field: a filter, a needtable column, a Cypher property, and the editor’s option completions on the directives of the types that declare it. On a need of another type it reads null there too, but is no property of that need: Cypher’s keys(n) and properties(n) leave it out, where they list a field the need’s type declares even while it holds null. The graph schema (get_graph_schema, ubc query cypher --schema) lists it as a property of the types that declare it, and of no other. needs.json carries it on every need, null on the needs of the other types, and its schema once, nullable, with no default, and the description Declared by need types 'req', 'spec', naming the declarations without a declaring ancestor that are not refused.

Link types declared on need types alone. A links entry naming a link type nothing else declares – no [needs.links] or extra_links entry, not links or parent_needs, no field (one declared on need types alone included), nor a link type’s back links (<link>_back, whose count is a back_links entry, below) – declares a link type of the types that declare it, as a fields entry declares a field: by their own entry or an ancestor’s, an empty entry included.

[needs.types.test]
title = "Test case"
prefix = "T_"

[needs.types.test.links.verifies]
incoming = "is verified by"
outgoing = "verifies"

Its back links are named <link>_back on every need, so one whose back links would have the name of a field or a link type is refused on every entry, one config.type_conflict warning each, and does not exist. Every type that declares it agrees on its shape: whether it is derived, and its incoming, outgoing, copy, allow_dead_links, summary, color, style, style_part, style_start and style_end. target_types is not part of its shape: each declaration of a type without a declaring ancestor gives its own (a test may verify a req while a review verifies a spec), and the types inheriting from it narrow that one. The first declaration of a type none of whose ancestors declares it, in the order the types are resolved (as for a field), sets them, an empty one too: the keys it gives, and a [needs.links] entry’s defaults for the others (incoming is "<link> incoming", outgoing the name, copy and allow_dead_links are false, summary is false, or true where a copy or collect computes the link type – a derived one, in the derive of a declaration not refused for another key –, color is #000000, style empty, style_part dotted, style_start - and style_end ->), and derived if it gives a derive. Beside such a copy or collect, summary = false is refused in any declaration, the first included (config.derive_invalid, Summary link types): the key is ignored and the declaration used. Every other declaration may repeat a value, and no more: one that gives another value – of a key the first declaration leaves out too – or is derived where the link type is not (or the other way round), is one config.type_conflict warning, and the entry is ignored: one of a type without a declaring ancestor does not declare the link type (a child’s entry under it is a declaration of its own), a child’s still declares it, through its parent.

On a need of a type that does not declare it, the link type holds [], no links – where a field holds null – and the need stores nothing for it. A link set for it there is ignored, as one needs.undeclared_for_type warning:

Link type 'verifies' is not declared on need type 'spec' and cannot be set in need 'S_001'; the value 'R_001' is ignored

at the same places as for a field; from outside, links of [] are dropped silently, and on a declaring type a derived link type’s links from outside are kept, as data. A needextend setting, appending to or deleting it does not extend the needs of the type, counted in one needs.needextend warning for each needextend, need type and option, as for a field. Its back links, verifies_back, are on every need, as for any link type. With copy the links of the declaring needs are copied into links, and a need of another type copies none; copy beside a derive is config.derive_invalid, as on a [needs.links] entry, and nothing is copied. A derived one is derived on every type that declares it (a child reading its parent’s rule), and holds [] on the others. These link types come after the [needs.links] and extra_links ones, in the order their first declarations are resolved: in a need’s links, a needflow legend, a needtable column two link types name, a needreport. Every reader knows it as any link type – a filter, a needtable column, a needflow edge, a Cypher relationship type – and the editor offers it, and shows it as a link on hover, on the directives of the types that declare it. needs.json declares it once, with the description Declared by need types 'req', 'test', naming the declarations without a declaring ancestor that are not refused, and, as for every link type, leaves it out of a need that carries no links of it. A name one type declares under fields and another under links, neither declared otherwise, is a field when a declaration of a type without a declaring ancestor gives it a schema type, and the links entries are refused, as below; otherwise the fields entries are refused, and the links entries declare the link type.

What cannot be declared. A declaration that cannot be applied is ignored as a whole, as one config.type_conflict warning: one naming no field of its table (a link type, or a link type’s back links, under fields – whose count is a back_links entry, below –; a field under links; under fields a name no root declaration types, above), one changing the field’s type, which is the same on every need type, or one setting a schema, default or predicates that cannot be used (a value of another type, a default of title, which takes none, a schema key the field’s type does not take, such as minimum on a string or a misspelt keyword). A core field may be declared like any other: status takes a default and an enum. doctype and external_url, which are set by the engine, name no field here, nor do id and type (the shape of a type’s ids is its id_regex, below); constraints, template, pre_template, post_template and the fields of Sphinx-Needs’ GitHub services (query, max_amount, …) are not applied yet: an entry naming one is a config.need_type warning, and ignored. A derived field or link type takes only a description, a narrower schema, (a field) nullable and a severity: a default, predicates or (a link type) target_types is refused, and so is a schema adding an enum to a field that has none, as its rules are checked against the field’s own declaration. A link type’s incoming, outgoing, copy, allow_dead_links, summary, color and style* are the same on every need type: the first declaration of a link type declared on need types alone sets them (above); given in a declaration of any other link type, even with the link type’s own value, they are one config.need_type warning, ignored, and the rest of the declaration used.

The value of a need. A field a need of the type does not set takes the first matching predicate of the type’s declaration (the field’s own, unless the type declares predicates), else the type’s default, else the field’s default; a value set in the need wins over all of them. A field the type makes not nullable, with no default, is required on the type’s needs: a need without a value is not created; a need directive, list2need item or src-trace need is reported as needs.create_need, a warning. Below violation (severity, next) the field is reported instead, and the need created, holding null. A needextend deleting a field (:-x:) empties it as the matched need’s type declares it: null where the field is nullable on that type, else the empty value of the field’s type. Schema validation judges each need against its type’s declarations, and the editor’s checks and value completions do too. A default a type declares is not the one a fingerprint compares against: a need’s value equal to its type’s default enters the fingerprint, unless it equals the field’s own default too.

Severity. A type’s declaration of a field or link type carries a severity: how a need of the type that fails it is reported, violation (an error, the default), warning or info. It applies to every constraint of the declaration, the schema keywords it keeps from before it included:

[needs.types.req.fields.category]
schema = { enum = ["functional", "safety"] }
severity = "warning"

[needs.types.req.links.satisfies]
schema = { minItems = 1 }
severity = "info"

A req outside the enum is a warning, needs.invalid_field_value, and one that satisfies nothing is information, needs.invalid_link_value; ubc check grades each so (--deny error passes on both), the editor’s quick check shows it so, and ubc schema validate reports it as Sphinx-Needs logs it (sn_schema_warning, sn_schema_info). Below violation, nullable = false is reported rather than enforced: a need of the type without a value is created, holding null, and is one needs.invalid_field_value at that severity (Field 'owner' is not nullable, but no value or default was given.). A derived field holds its empty value instead, and is not reported. needs.json has one needs_schema for every need type, so it writes such a field nullable ("type": ["string", "null"], a default of null where it has none) on every type, and a field declared not nullable at violation alone as declared. A type inheriting a declaration keeps its severity, may raise it, and may not lower one an ancestor gives: that is one config.type_widening warning, naming the type that gave it, and the declaration is ignored as a whole:

needs.types.lax.fields.category: widens the field as need type 'req' declares it: Child 'severity' 'info' is lower than parent 'severity' 'warning'.

Under an ancestor that gives none, a child sets any severity. A severity that is none of the three is a config warning, ignored, and the rest of the declaration used; on a field’s or link type’s own entry ([needs.fields.<name>], [needs.links.<name>]) it is a config warning too, and ignored: a severity is a need type’s. Sphinx-Needs checks nullable = false below violation in its schema validation, so there needs_schema_validation_enabled = False silences it; ubCode has no such setting and always reports it.

[needs.types.req.back_links.satisfies]
description = "The architecture elements satisfying the requirement"
schema = { minItems = 1 }

A req no need satisfies is one needs.invalid_link_value, at the req, about satisfies_back. The count is every link of the link type pointing to the need, whatever its source and its source’s target_types, each source need once; a link to a part of the need counts for the need, and so does a link to a part it lacks (a dead link where it is written). It is checked once every link is final, on the needs of the type and of the types inheriting from it, which may narrow it (a minItems only higher, a maxItems only lower, a severity only higher; a widening is one config.type_widening warning, and the entry ignored). A need from external_needs is not counted: its own project’s links to it are not loaded here, so its count would be partial; a need a needimport imports is. Any other key (default, predicates, target_types, derive, incoming, …, or one no entry has, such as a misspelt severty) or schema keyword, and a count that is not a non-negative integer, is one config.type_conflict warning, and the entry is ignored as a whole; an entry without a schema declares nothing to count. needs.json writes nothing for it, as it writes no back links. The entry names any link type of the project, whose links may come from a need of any type: one declared otherwise (links and parent_needs included), or one need types declare alone, by this type or another (a spec may count the verifies links a test gives), a summary link type too, whose count counts the links a copy or collect computes; any other name is one config.type_conflict warning, the entry ignored, with the closest link type as a “did you mean” (implemnts: did you mean implements?). A fields or links entry named as the back links, <link>_back, is refused, naming the back_links entry; a links entry named <x>_back where there is no link type x is no back links, and declares a link type of the type alone. A needs.invalid_link_value of a count reads the links of other needs, so a project with a count validates every need again when one changes.

The ids of a type. id_regex on a [needs.types.<type>] entry is a pattern the ids of the type’s needs match, beside [needs] id_regex and the id_regex of each type it inherits from:

[needs.types.req]
title = "Requirement"
prefix = "REQ_"
id_regex = "REQ_"

[needs.types.safety_req]
title = "Safety requirement"
prefix = "REQ_S"
inherits = "req"
id_regex = "[A-Z]+_S[0-9]"

It is matched as [needs] id_regex is (with namespaced_ids on, against the need’s local id or its whole id), from the start of the id and open at its end (Python’s re.match), so X_REQ_001 fails REQ_. A need whose id fails one of them is kept and reported, needs.id_regex at its :id:, naming the pattern and the type that gives it (Need directive ID "SPEC_001" does not match the id_regex 'REQ_' of need type 'req'), as for [needs] id_regex; Sphinx-Needs does not create it (needs.create_need). A need a needimport imports, or one from external_needs, keeps its id unchecked. A pattern that is not a regular expression is one config.type_conflict warning, and ignored: the type’s needs, and those of the types inheriting from it, are checked against the others. A value that is not a string is a config.need_type warning. A test-report need’s id, written or generated, is checked the same way, against [needs] id_regex and the patterns of its test-report type (see What the section adds). ubc agent reads the key too, for the id prefix of a type that gives no prefix.

When a type colour accents a card

A type’s color accents its need cards only where you have chosen it. Two cases are deliberately not treated as a choice:

  • a type declared without a color — the #000000 default means no accent rather than black. So do #000, #000000FF and any fully transparent value (an 00 alpha, e.g. #00000000), since an invisible accent is not one. A partly transparent colour such as #00000080 is a choice, and paints. For a near-black accent write #010101.

  • a built-in type still carrying its shipped colour. Every project gets the four built-ins whether or not it asks, and their colours were picked to fill diagram nodes, so accenting them would colour every card of every project:

    Directive

    Shipped color

    Accents a card?

    req

    #BFD8D2

    no — this exact pair is the shipped default

    spec

    #FEDCD2

    no

    impl

    #DF744A

    no

    test

    #DCB239

    no

    The rule matches the pair, so these colours accent normally on any other directive, and any other colour accents normally on these four.

Note

Migrating from sphinx-needs? Those four values are sphinx-needs’ own defaults, so a [[needs.types]] block copied across lands on them exactly — and your cards will show no accent. If a colour of yours is being ignored, change it by one digit (#BFD8D2 → #BFD8D3) and it will paint. Spelling does not help: the comparison ignores case and a fully opaque alpha, so #bfd8d2 and #BFD8D2FF on req are the same pair.

Fields

Every need carries fields — named pieces of metadata such as status, tags, or any custom attribute you define. Some fields are built in (id, title, status, tags); you can add your own through the configuration.

ubCode supports two formats: the dict-based [needs.fields] format (aligned with sphinx-needs ≥ 7) and the list-based extra_options format (for sphinx-needs < 7).

Note

Three names cannot be shadowed by a custom field: id and type are refused outright, and content — the need’s own body — is reported as config.field_shadowed_by_identity. A content field is still created and can still be set on a directive, but every filter, table, variant condition, report template and needs.json key answers the body for that name, so the declared value is invisible to every one of them. See Variants for the shadowing rule in full.

Dict-based format (recommended)

Note

The dict-based [needs.fields] format requires sphinx-needs ≥ 7.0. It replaces the older list-based needs_extra_options and also allows specializing core fields (e.g. status, tags) by narrowing their type constraints. A specialization that does not narrow – a schema keyword relaxed or its type changed, nullable turned on – is reported (config.field_narrowing) and not applied: the core field keeps its own schema and type, and the default and predicates are read against them.

Use [needs.fields.<name>] to define each custom field:

[needs.fields.priority]
description = "Priority level"
default = "medium"

[needs.fields.assignee]
description = "Assigned team member"

[needs.fields.effort]
description = "Story points"
schema = {type = "integer", minimum = 1, maximum = 13}

Each field supports:

  • description (optional): Human-readable description

  • default (optional): Default value if not specified on a need

  • schema (optional): JSON Schema to validate values (see Field schemas below). Schema support for fields was introduced in sphinx-needs 6.0 (via needs_extra_options) and carried forward to needs_fields in sphinx-needs 7.0.

  • nullable (optional): Whether the field accepts null values. sphinx-needs ≥ 7.0.

  • predicates (optional): Conditional defaults (see Global options). sphinx-needs ≥ 7.0.

  • parse_variants (optional): Whether to parse variant functions (<<...>>) and variant data references (<{ ... }>, see Variant data) in this field’s values. sphinx-needs ≥ 7.0.

  • parse_dynamic_functions (optional): Whether to parse dynamic functions in this field’s values. sphinx-needs ≥ 6.3.

A field can also name the code a need traces to, for the code coverage report: see symbol_fields in Coverage policy ([codelinks_coverage]).

A default or predicates set both here and under [needs.global_options.<name>] is this table’s: the global one is ignored and reported. A key only [needs.global_options.<name>] sets still applies, beside this table’s.

A key the entry does not have (a misspelt derive, a type written beside schema) is one config warning at the entry, naming the key and the keys it has; the key is ignored and the field kept. The same holds for a table entry of extra_options, whose keys are name, description, schema, derive and derive_by_type. A name left from the list spelling is accepted where it repeats the entry’s name, and reported where it gives another (the entry is named by its key). A keyword the schema of its type does not have, at its top or in its items or contains (enmu, minimum on a string, default written inside schema), is one config warning at the schema: the keyword is ignored, the rest of the schema applies. A boolean schema takes const alone: an enum on one is reported and ignored too. Sphinx-Needs reports both the same way.

Once declared, these fields can be used on any need:

.. req:: Encrypt data at rest
   :id: REQ_002
   :status: open
   :priority: high
   :assignee: alice
   :effort: 5

Styling cards with [needs.fields.style]

style is an ordinary core field, so the same default and predicates keys give a project-wide card style and per-condition ones — this is ubCode’s replacement for sphinx-needs’ needs_default_style, and no separate configuration key is needed:

[needs.fields.style]
# Every card starts discreet …
default = "discreet"
# … except that closed needs go green and blocked ones get a red frame.
predicates = [
    ['status == "closed"', 'green'],
    ['status == "blocked"', 'red_border'],
]

A :style: written on the need itself wins over both. The value is a comma-separated list of tokens; each becomes a ub-need-style-<token> class on the card, in the order written and with duplicates collapsed. ubCode ships styling for the twenty sphinx-needs palette names — the green / red / yellow / blue / gray / discreet fills (with implemented / open / in_progress as aliases), the green / red / yellow / blue / discreet _border frames, the green / red / orange / yellow / blue _bar stripes, and clean. A token that is not a valid CSS identifier is ignored and reported as build.need_style_invalid; see Differences from a Sphinx build for how this differs from a Sphinx-Needs build.

Choosing a card design with [needs.fields.layout]

layout is an ordinary core field too, so the same two keys give a project-wide card design and per-condition ones — which is more than Sphinx-Needs can express, where the card design is one global value:

[needs.fields.layout]
# Every card is the default design …
default = "clean"
# … except that specifications show everything, and needs marked
# `:hide_meta:` show only their content.
predicates = [
    ['type == "spec"', 'complete'],
    ['hide_meta == True', 'focus'],
]

Note

Earlier versions of this page said that this made a separate configuration key unnecessary. That was wrong in the one case that matters. A ubproject.toml is read by both engines, and Sphinx-Needs’ needs_from_toml already maps [needs] default_layout onto needs_default_layout while silently skipping [needs.fields] entirely — so a project that wrote its card design the field way got it from ubc build html and not from sphinx-build, with no warning from either. ubCode therefore has [needs] default_layout as well, and it is the key to reach for when one file feeds both engines.

The two mechanisms are not competing tiers of one chain, and the precedence follows from what each one does:

  1. a :layout: written on the need itself wins over everything;

  2. then a [needs.fields.layout] predicates row, then its default — both write a value onto the need, which is why they beat the key below;

  3. then [needs] default_layout, which catches only the needs that end up with no value at all;

  4. then clean.

Use default_layout for the project-wide design — it is the spelling both engines read — and [needs.fields.layout] predicates for the per-condition exceptions, which have no Sphinx-Needs equivalent. The value is any design this project knows: one of the ten built-in ones — clean (the default), complete, focus, debug, and the six side-column names clean_l, clean_lp, clean_r, clean_rp, focus_l and focus_r — one of the two sphinx-needs identities (test, focus_f), or a design the project defines for itself with [needs.card_layouts]. An unknown name is reported as build.need_layout_unknown and the card renders with the default design; see Card designs with [needs.card_layouts] for what each design shows and how to define your own, and Differences from a Sphinx build for how this differs from a Sphinx-Needs build.

Hiding cards conditionally with [needs.fields.hide]

hide is an ordinary core field as well, and a boolean rather than a string — so default and predicates take true / false, and give you conditional hiding: hide every draft need, or every need of a type, without writing :hide: on any of them. This is parity rather than divergence — a Sphinx-Needs build reaches the same result through needs_fields’ default / predicates on the hide core field, which upstream flags allow_default for exactly this purpose:

[needs.fields.hide]
# Nothing is hidden by default …
default = false
# … except needs still being drafted, and the ones an internal
# process owns rather than the document.
predicates = [
    ['status == "draft"', true],
    ['type == "internal"', true],
]

A :hide: written on the need itself wins over both. A hidden need renders its whole card inside a closed disclosure — one compact summary line the reader can expand in place — so nothing is withheld, and references, link rows, needlist entries and the built site’s search index all still reach it; see Differences from a Sphinx build for the full behaviour and for how this differs from a Sphinx-Needs build.

Hiding a need does not remove it from the project, nor its content from the page: it stays in the index, in needs.json, in every filter result and in the published HTML, merely collapsed. :hide: is not a confidentiality boundary; use :delete: for a need that should produce no output at all.

List-based format (sphinx-needs < 7)

Deprecated since version 0.25.0: The list-based extra_options format (needs_extra_options in sphinx-needs) was deprecated in sphinx-needs 7.0 in favour of the dict-based format. It remains supported for backward compatibility. For new projects, prefer the dict-based [needs.fields] format.

Simple format (string list):

extra_options = ["priority", "effort", "assignee", "component"]

Detailed format (with descriptions and schemas):

extra_options = [
    {name = "priority", description = "Priority level"},
    {name = "effort", description = "Story points", schema = {type = "integer", minimum = 1, maximum = 13}},
    {name = "assignee", description = "Assigned team member"},
]

Field schemas

The schema key on a field applies JSON Schema validation to every value entered for that field. Invalid data is caught at index time, before the docs are built.

External-needs sources and needimport refuse a record that gives a field a value its type cannot hold, as Sphinx-Needs does: the need is not imported, and the finding names it (ubc check and ubc build needs fail on it at their default --deny warning). A JSON number for a string field is such a value, an integer as much as a float: write it as a JSON string ("1.10", not 1.10) to keep it exactly as written. Standalone needs.json validation is strict about field types too.

String schemas:

[needs.fields.contact]
schema = {type = "string", format = "email"}

[needs.fields.id_pattern]
schema = {type = "string", pattern = "^[A-Z]{3}-[0-9]{4}$"}

[needs.fields.severity]
schema = {type = "string", enum = ["low", "medium", "high", "critical"]}

String format options:

The format property supports various predefined formats:

  • "date": RFC 3339 date format (e.g., 2023-10-22)

  • "date-time": RFC 3339 date-time format (e.g., 2023-10-22T14:30:00Z)

  • "time": RFC 3339 time format (e.g., 14:30:00Z)

  • "email": RFC 5322 email address (e.g., user@example.com)

  • "hostname": RFC 1123 hostname (e.g., example.com)

  • "uri": RFC 3986 URI (e.g., https://example.com/path)

  • "uuid": RFC 4122 UUID (e.g., 550e8400-e29b-41d4-a716-446655440000)

  • "regex": ECMAScript regular expression

Integer and number schemas:

[needs.fields.priority]
schema = {type = "integer", minimum = 1, maximum = 10}

[needs.fields.rating]
schema = {type = "number", minimum = 0.0, maximum = 5.0}

[needs.fields.fibonacci]
schema = {type = "integer", enum = [1, 2, 3, 5, 8, 13, 21]}

Boolean schemas:

[needs.fields.approved]
schema = {type = "boolean"}

Array schemas:

[needs.fields.reviewers]
schema = {type = "array", items = {type = "string", format = "email"}, minItems = 1, maxItems = 3}

[needs.fields.categories]
schema = {type = "array", items = {type = "string"}, uniqueItems = true}

Usage in need directives:

Once defined, these fields can be used in your need directives:

.. requirement:: User Authentication
    :priority: 5
    :effort: 8
    :assignee: developer@company.com
    :due_date: 2024-12-31
    :tags: security, authentication
    :component: auth, backend
    :active: true

    Users must be able to authenticate using their corporate credentials.

A value that breaks its schema is reported on the need when the project is indexed, and as you type in the editor (there a lighter check: no type, pattern or format checks), naming the need, the field and the schema rule it broke: needs.invalid_field_value for a field, and needs.invalid_link_value for a link type’s schema (see Link types). Both are errors, whether the field’s own declaration or a need type’s entry for it was broken, so ubc check --deny error fails on them and the editor shows an error, as a Sphinx build logs the same failure as an error (sn_schema_violation) and ubc schema validate reports it as a violation; a need type’s entry may lower that to a warning or information (severity, see Severity). A need is checked against the schema its own type declares for the field, where it declares one (see Fields per need type). A schema that is not valid itself is reported against ubproject.toml under the plain config code, and then no value is checked.

Derived fields

A derive table on a [needs.fields.<name>] or [needs.links.<name>] entry, or, for a rule per need type, in a need type’s own declaration of the field ([needs.types.<type>.fields.<name>]; derive_by_type covers the cases a type’s entry cannot, see The derive_by_type table), makes the field or link type a derived field: a rule written once in ubproject.toml computes its value, and no author can set it. The kinds, the roles, rules per need type, unions of link types and the fingerprint have a page of their own: Derived fields.

Computed values. A derived field is one of three ways a need’s value is computed from other values, and which one to use depends on what the value depends on:

mechanism

written as

use it when

a derived field (recommended)

in ubproject.toml: derive = {…} on [needs.fields.<name>] or [needs.links.<name>]

a field is computed the same way on every need, or on every need of a type: a roll-up over links or back links, a lookup, a hash, a filtered link list

a dynamic function

[[…]] in a need’s option, the ndf role in its content

the value is a one-off: only some needs compute it, or different needs compute it differently; or it calls echo or test; or no kind expresses the computation yet

a variant

<<…>>, or a variant data reference <{ var.* }>, in a field that sets parse_variants = true

the value depends on the build (its tags or variant data), or picks one of several written values by a condition: a derived field’s rule does not vary from build to build

Prefer a derived field where it fits: it is declared once instead of repeated in every need; it is checked when the configuration is read, so a mistake in it is reported at once; it is closed to authors, so no stale value written in a need overrides it; and needs.json marks the field "readOnly": true.

Statuses and tags

You can constrain the allowed values for a need’s status and tags fields. The recommended approach depends on your sphinx-needs version.

Legacy list-based constraints (sphinx-needs < 7)

Deprecated since version 0.25.0: The [[needs.statuses]] and [[needs.tags]] list formats (needs_statuses / needs_tags in sphinx-needs) were deprecated in sphinx-needs 7.0 in favour of schema enum constraints on the status and tags fields (see above). They remain supported for backward compatibility.

[[needs.statuses]]
name = "draft"
description = "Work in progress"

[[needs.statuses]]
name = "approved"
description = "Reviewed and approved"

[[needs.tags]]
name = "security"
description = "Security-related needs"

External needs

Load needs from external sources (JSON files or URLs):

# From local file
[[needs.external_needs]]
json_path = "external/project_needs.json"
id_prefix = "EXT"
base_url = "https://external-project.com"
target_url = "docs/{{ need.id }}.html"

# From remote URL
[[needs.external_needs]]
json_url = "https://api.example.com/needs.json"
id_prefix = "REMOTE"

Each external needs source supports:

  • json_path: Path to a local JSON file

  • json_url: URL to a remote JSON file

  • id_prefix: Prefix prepended to external need IDs, as written, and to every link of the source that names one of its own needs, to a part (ID.part) or with a condition (ID[condition]) alike, a link default of the source’s needs_schema that a need takes included; a link value written as a string is prefixed item by item, unless it holds [[ (a dynamic function, or a condition in double brackets), << or <{, which keeps the whole string as written

  • base_url: Base URL for linking back to the source project

  • target_url: URL template for individual need links, relative to base_url unless it renders an absolute URL (scheme://… or //…), which is used as it is (so base_url may be ""), except that one with a javascript:, vbscript: or data: scheme, or a control character, gives no link; the need is available as need, so {{ need.id }} is its id (a bare {{ id }} renders empty, in ubCode and in Sphinx-Needs alike)

  • css_class: CSS class applied to external needs

  • version: The version of the source to read; unset or "" reads the source’s current_version

  • skip_in_ubcode (default: false): When true, skip loading these external needs in ubCode analysis

Each need is named by the key it is filed under in the source’s needs.json. A need whose own "id" differs from that key is still read under the key, and reported once (needs.external), naming both.

A value of the source’s needs that is not a JSON object is not a need: it is skipped and reported (needs.external), and the source’s other needs are read. A need written by Sphinx-Needs before 4.0 states its content as description: when it has no content key at all (after the needs_schema defaults), the description is its content, and is not reported as an unknown key. A need with a content keeps its description beside it, an empty "" included, and so does a need whose content is a default of the needs_schema, an empty one included: the description is then a key like any other, reported as an unknown key unless the project declares it. A need whose content is not a string (null, false, 0, [] or {} included) is not read, as in Sphinx-Needs: it is reported (needs.external), naming the need and what its content is, and the source’s other needs are read. A need’s id is its key, whether it states one or not, so a target_url can render {{ need.id }}. A need that states null for a field or a link type gives it no value, as in Sphinx-Needs: the project’s default for it applies, as for a key the need leaves out (a default of the source’s needs_schema fills only a key it leaves out, and a default of null is none), and without one what a missing value gives. A default of the needs_schema that the project’s field or link type cannot hold costs only the needs that would take it: each need that leaves the key out, and whose type declares it, is not read, and is reported (needs.external), naming the need and the default. A needs_schema, a properties or a property that is not an object gives no defaults, and is not reported; a version written without its defaults (needs_defaults_removed) and with no needs_schema is read, and reported. See Importing needs for the same rules on needimport.

A source whose needs.json states a format_version other than 1 is refused: a later format (an integer above 1, or a pre-release such as "2b1"), or a value that is not a format version ("1", 1.0, true). It contributes no needs, and the source reports why (needs.external). A file that leaves the key out, as every file written so far does, is read. A file of the draft format "2a1" is read too (experimental), and each need keeps the places its record says its text came through, as Importing needs describes for needimport.

Remote sources

The [needs.remote] section controls how ubCode fetches needs.json over HTTP(S). It applies to every remote source: [[needs.external_needs]] entries with a json_url, and needimport directives whose argument is a URL. Local sources — a json_path, or a file:// URL, which is read straight from disk — are unaffected by every key here.

[needs.remote]
cache_days = 1
timeout = 10.0
offline = false
  • cache_days (default: 1): How long, in days, an already-loaded remote source’s needs are reused before ubCode re-checks the source. 0 re-checks on every pass, and a negative value never re-checks. A re-check sends the ETag / Last-Modified of the last response, so an unchanged source costs one small request and its needs are kept as they are.

  • timeout (default: 10.0): Timeout, in seconds, for each request.

  • offline (default: false): When true, never fetch remote sources. Each one keeps the needs it was last loaded with and is reported as skipped — useful in network-restricted CI, or for working offline against an index built while online.

A remote source whose fetch fails keeps the needs it loaded last time, rather than losing them until the next success, and the failure is reported. Within one long-running process — the language server, or a watch loop — an unreachable host is not re-attempted for five minutes, so an editing session against a source that is down does not pay a connection timeout on every pass. That backoff is per-process and is not persisted, so a one-shot ubc build or ubc check against an unreachable host waits for timeout on every run; lower timeout, or set offline = true, if that is the situation you are in.

Variants

The [needs.variants] section defines named filter expressions that can be referenced from need fields using the <<name: value, fallback>> syntax. This implements the Sphinx-Needs variant functions feature.

[needs.variants]
is_open = "status == 'open'"
is_html = "'html' in build_tags"
is_production = "environment == 'production'"

With these variants defined, need fields can use them:

.. req:: My requirement
   :id: REQ_001
   :status: open
   :phase: <<is_open: active, inactive>>
   :extra: <<is_html: web_only, general>>

You can also use inline bracketed expressions without pre-defining a variant:

.. req:: Another requirement
   :id: REQ_002
   :status: open
   :phase: <<[status == 'open']: active, inactive>>

The last comma-separated value is always the fallback when no expression matches.

A variant cannot read the field it fills: :status: <<[status == 'open']: active, inactive>> asks for status to decide status, which is a cycle (needs.derive_cycle), and the field keeps its empty value. Put the variant on another field, as above; see When a call reads a value another call computes.

A variant expression resolves the need’s own fields and links, the project’s filter_data keys, the build_tags of the current build, and the context fields — content, docname, lineno, sections, section_name, is_external, is_directive, is_import, is_src_trace, is_modified, modifications, is_need, is_part, id_parent, id_complete — the same names a :filter: expression resolves:

.. req:: Section-aware requirement
   :id: REQ_003
   :status: <<[section_name == 'Interfaces']: interface, internal>>

A project-declared field or link of the same name wins over a context field, except for id, type and content, which cannot be shadowed. Inside a variant expression is_modified and modifications count needextend matches only — a need’s own variant resolution cannot be an input to itself.

A name may also carry the n. prefix (<<[n.status == 'open']: a, b>>), matching what a :filter: expression accepts; any other namespace is reported as an unknown name.

Note

Variant syntax is only parsed for fields that opt in. In sphinx-needs ≥ 7.0, set parse_variants = true on individual fields in [needs.fields]. For older versions, use the deprecated variant_options list (see Deprecated needs options).

Parse and evaluation errors are surfaced as needs.variant diagnostics, including a name the expression cannot resolve — which is reported with a “did you mean” suggestion, while the expression still resolves to its fallback value.

See also

Variant data for the related var.* namespace and the <{ ... }> reference syntax, which inject build-wide data rather than selecting between values conditionally.

Variant data

sphinx-needs ≥ 8.2.

Variant data is a nested, read-only key-value store that ubCode exposes under the var.* namespace inside filter expressions. It lets a single “150%” model — one set of needs that describes every product variant — be filtered, extended, and rendered differently for each build, without duplicating content.

See also

Variant builds walks through the end-to-end workflow — including building and diffing each variant from the command line. This section is the configuration reference for the options it uses.

For example, a project that targets several CPU architectures and build configurations can keep one copy of its requirements and select the data relevant to the current build:

[variants.data]
platform = "arm"
debug = false
opt_level = 2
archs = ["arm", "x86"]

[variants.data.build]
compiler = "clang"
features = ["networking", "logging"]

With this configuration the following values are available in any filter expression:

var.platform == "arm"                 # scalar string
var.opt_level == 2                    # scalar integer
var.debug == False                    # scalar boolean
"x86" in var.archs                    # membership in an array
var.build.compiler == "clang"         # nested scalar
"networking" in var.build.features    # membership in a nested array

Note

var.* resolves only against the configured variant data. Unlike need fields or filter_data keys, it does not depend on the need currently being evaluated, which makes it suitable for global, build-wide switches. Looking up an unknown key (e.g. var.missing) is a needs.variant diagnostic, not a silent false.

Defining variant data

Variant data can be provided inline, from a JSON file, or both. It lives in one of two places in ubproject.toml: the shared [variants] table, which every tool reading the file uses, or the legacy variant_data and variant_data_file keys of [needs], which ubCode still reads, without a warning.

Note

Sphinx-Needs reads [variants] from 9.0.0 and sphinx-mounts from 0.3.0; an older release ignores the table silently, so a project built with one keeps the [needs] keys.

variant_data

Type: object (default: unset)

An inline, nested table of variant data, declared directly in ubproject.toml under [needs.variant_data]. Its [variants] spelling, used in the examples above, is data. Setting variant_data = {} counts as setting the table (see below).

variant_data_file

Type: string (default: unset)

Path to a JSON file containing variant data, resolved relative to the ubproject.toml that declares it. This is convenient when the values are generated by a build system or shared across several projects. Its [variants] spelling is data_file, and it follows the same rules: one non-empty path, joined as written.

[needs]
variant_data_file = "variant_data.json"
{
  "platform": "linux",
  "build": {"compiler": "gcc", "features": ["networking"]}
}

When both are set, the file is loaded first as the base, and the inline values are deep-merged on top, with the inline values winning:

  • At nested maps, keys are merged recursively.

  • At scalars and arrays, the inline value replaces the file value entirely.

[variants]
# file sets platform = "linux", build.compiler = "gcc", build.features = [...]
data_file = "variant_data.json"

[variants.data]
platform = "windows"   # overrides the file's scalar value

[variants.data.build]
compiler = "clang"     # overrides build.compiler;
                       # build.features is preserved from the file

Because inline values take precedence, you can keep shared defaults in the file under version control and override individual switches per build.

The [variants] table

Added in version 0.37.0.

[variants] holds the same two values under the names the whole tool family shares, so one ubproject.toml gives sphinx-needs, sphinx-mounts and ubCode the same variant data:

[variants]
data_file = "variant_data.json"

[variants.data]
platform = "windows"
data

Type: object (default: unset)

An inline, nested table of variant data, under [variants.data], merged over the file exactly as [needs.variant_data] is. Setting data = {} counts as setting the table (see below).

data_file

Type: string (default: unset)

Path to a JSON file holding one object of variant data. It is one non-empty path — a list of paths, and an empty string, are refused. A relative path is joined to the directory of the ubproject.toml that sets it, as written: a .. in it is kept, not folded away.

Any other key under [variants] is ignored and reported as config.variants_unknown_key, so one file can serve tool versions that read more keys. A variants that is not a table, or a data or data_file of the wrong type, is a configuration error.

Which table is read

The variant data is read from one table, never one key from each:

  • [variants], when it sets data or data_file — data = {} included; an empty [variants] table, or one holding only other keys, sets neither;

  • otherwise the legacy [needs] keys;

  • otherwise nothing, and var.* is empty.

When both tables set variant data, [variants] is read and each [needs] key it ignores is reported as config.variant_data_location, at that key (needs.variant_data or needs.variant_data_file). The ignored data file is never opened, so a missing or broken one there is not reported.

Across extend and -c, the inline table is merged key by key: the nearer configuration’s values (a -c override is the nearest) are deep-merged over the inherited ones, exactly as the inline table is merged over the file, and a nearer data file replaces an inherited one (a -c of the data file is the exception: see the next section). The table is chosen once, after that merge. [variants] wins wherever the chain or an inline override declares it: an inline override of [variants] data, or a configuration that sets data or data_file, switches a [needs] project to it, and one that sets [needs] under a [variants] declaration is ignored — both warned. So migrating a shared base moves every child still on [needs] to the base’s table, and each such child’s own [needs] values are dropped (warned at its keys). Conversely, a project on [variants] that extends a base still on [needs] reads its own [variants] alone and reports the base’s [needs] keys: migrate the base first, or, while a shared base is still on [needs], add config.variant_data_location to the child’s lint.ignore (which replaces an inherited list — repeat the base’s entries), or pass it for one run (ubc check --extend-ignore, ubc build html --lint-extend-ignore). An unknown [variants] key in a base is reported in every configuration that extends it.

A data-file override swaps the file, never the table

The data file is the one key a -c override does not merge in like the others. -c "variants.data_file = '…'" and -c "needs.variant_data_file = '…'" are two spellings of one data-file override, which:

  • replaces the data file of the table the project reads, chosen as above from its configuration without the override — [variants] when it sets data or data_file, else [needs], and with neither, the override is the whole variant data;

  • never opens the file it replaces, so a missing or broken one is not reported (an empty data_file in the configuration is still refused);

  • keeps that table’s inline values, merged over the override’s file;

  • never switches the table, and is never reported as config.variant_data_location.

So the same -c selects the data file of a [variants] project and of one still on [needs], and a [needs] project keeps its [needs.variant_data] under -c "variants.data_file = '…'". A relative path is taken from the working directory, as every -c path is. -c "variants.data_file = ''" (or the [needs] spelling) reads no data file: the table’s inline values are the whole variant data. Giving both spellings with different files is a configuration error (./v.json, a/../v.json and v.json are the same file).

Only -c is an override: the same key in a configuration the project extends declares its table, as above. This is the rule Sphinx-Needs applies to -D needs_variant_data_file — both follow the shared ubproject.toml reading contract. The two anchor a relative path differently: ubCode takes a relative -c path from the working directory, Sphinx-Needs a relative -D path from the directory holding conf.py, so the same relative path selects the same data file under both tools when the command is run from that directory.

Value types

Variant data values may be:

  • Scalars — string, integer, number (float), or boolean.

  • Uniform arrays of scalars — every element must share the same type.

  • Nested maps — arbitrarily deep tables, accessed with further dots (var.build.sanitizers.asan).

A mixed-type array, and a TOML date-time value (which is not a variant value), are reported as config.variant_data_invalid at the inline table’s key; a date-time inside an array is a configuration error, like an array of tables or of arrays in ubproject.toml. The data file is checked on its own, before the merge, so an inline value cannot hide an invalid file value by replacing it. Everything wrong with the file — missing, not JSON, not one object, a JSON null, or a value of a shape above — is reported at the data-file key, under the same code, as is an empty file name. Each is a warning, so ubc check and ubc build html exit non-zero, and a bare "config" in lint.ignore does not silence it (see Code matching and .* wildcards).

Using var.* in filters

The var.* namespace is available anywhere ubCode evaluates a filter expression against your needs configuration.

Variant functions — select a field value per build (see Variants):

.. req:: Bootloader
   :id: REQ_001
   :status: <<[var.platform == "windows"]: active, inactive>>

Conditional defaults — vary a field’s default via predicates:

[needs.fields.compiler_note]
default = "unknown-compiler"
predicates = [
    ['var.build.compiler == "clang"', "using-clang"],
    ['var.build.compiler == "gcc"', "using-gcc"],
]

needextend — extend only the needs relevant to the current build:

.. needextend:: var.platform == "windows"
   :status: supported

needimport — import only the needs that match:

.. needimport:: external.json
   :filter: var.platform == "windows"

External needs — filter needs loaded from another project:

[[needs.external_needs]]
json_path = "imported.json"
filter = 'var.platform == "windows"'

Referencing variant data in field values (<{ ... }>)

In addition to filtering, variant data can be injected directly into a field or link value using the <{ ... }> syntax. The text between the delimiters is a var.* path, and ubCode substitutes the stored value at index time.

Unlike variant functions (<<...>>), which choose between candidate values using conditional logic, a <{ ... }> reference is a direct lookup — there is no condition, just a substitution.

This syntax is only parsed for fields and links that opt in with parse_variants = true (the same flag that enables <<...>>):

[variants.data]
platform = "arm"
links = ["REQ_001", "REQ_002"]

[variants.data.build]
opt_level = 2

[needs.fields.arch]
schema = {type = "string"}
parse_variants = true

[needs.fields.opt]
schema = {type = "integer"}
parse_variants = true

[needs.links.derived_from]
parse_variants = true

The references can then be used on any need:

.. req:: Scalar reference
   :id: REQ_001
   :arch: <{ var.platform }>
   :opt: <{ var.build.opt_level }>

.. req:: Embedded in a string
   :id: REQ_002
   :arch: built for <{ var.platform }>

.. req:: Within an array and a link field
   :id: REQ_003
   :tags: a, <{ var.platform }>, c
   :derived_from: <{ var.links }>

A few rules apply:

  • For string fields the reference may be embedded inside surrounding text; for non-string scalar fields (integer, number, boolean) the reference must be the entire value.

  • The resolved value is type-checked against the field’s schema.

  • If the field does not set parse_variants = true, the <{ ... }> text is kept literally.

The following situations are reported as needs.variant diagnostics, and leave the field at its placeholder (unset in a nullable field, otherwise its type’s empty value; an array or link field keeps its literal items); in a string field that is the whole value, including the text around the reference:

  • Invalid expression — the content is not a dotted var.* path, e.g. <{ platform }> (missing the var. root).

  • Unknown key — the path does not exist in the variant data, e.g. <{ var.nonexistent }> or <{ var.build.missing }>.

  • Non-leaf value — the path resolves to a nested map rather than a scalar or array, e.g. <{ var.build }>.

  • Type mismatch — the resolved value’s type does not match the field, e.g. injecting a string into an integer field, or a list, a number or a boolean into a string field (built for <{ var.links }> is a mismatch, not built for REQ_001 REQ_002).

See also

The corresponding sphinx-needs feature is documented under variant data.

Dynamic functions

ubCode resolves the built-in dynamic functions using the [[...]] syntax from sphinx-needs.

All eight built-in functions are supported:

  • echo("text") — returns the given string unchanged

  • test(*args, **kwargs) — returns a debug string with the need ID and arguments

  • copy("field", need_id=None, filter=None) — copies a field value (also supports lower and upper kwargs). field may be any of the need’s own fields or links, or a context field — id, type, content, docname, lineno, sections, section_name, parent_need, is_external, is_directive, is_import, is_src_trace, is_modified, modifications, is_need, is_part, id_parent, id_complete. A project-declared field of the same name wins, except for id, type and content. need_id — as a keyword or as the second positional argument — copies from that need instead of the current one. With filter, it copies from the need passing the filter whose id sorts first character by character, and falls back to the need need_id names, or to the current need, when none passes. To copy from the needs whose field equals one of this need’s values (a filter naming current_need, which ubCode does not evaluate), declare a copy with join (Matching a field: the join role)

  • links_from_content(need_id=None, filter=None) — returns the needs referenced via :need: roles in a need’s own content, the current need’s unless need_id names another (a need_id naming no need, or an external need, which has no content, fails the call, which is reported), keeping with filter only the needs that pass it. need_id may be given as a keyword or as the first positional argument, filter as the second. Its declared form is the content_links kind (The kinds at a glance), and a link type it fills may be a member of a union (union)

  • check_linked_values(result, search_option, search_value, filter_string=None, one_hit=False) — compares the search_option field of every need this one :links: to (with filter_string, of those passing it) against search_value. Without one_hit, result is returned only when they all match — and also when the need links to nothing at all. With one_hit, result is returned whatever the values are: that is a quirk of Sphinx-Needs itself, mirrored here deliberately so the two tools agree. Otherwise the call yields nothing. A link to no need is skipped (the dead link is reported on its own). It fails only on a search_option that is not a field, link or context field of the linked need — a failed call renders ?? in a role or :style_row:, and is skipped silently in a field or link value

  • calc_sum("option", filter=None, links_only=False) — sums a numeric field across the project’s needs, or across only the needs this one links to when links_only is set (a link to no need skipped), counting with filter only the needs that pass it

  • links_from_filter(filter, include_self=False, include_parts=False) — links every need passing the filter, in need-id order (stored character by character, SPC_10 before SPC_9; a needs.json export sorts them naturally), leaving the current need out unless include_self is set; an empty filter is an error. include_parts=True tests every need’s parts too, as the links kind’s include_parts does (also when a need.<attr> gives it). Its declared form is the links kind, filter as where (The kinds at a glance), and a link type it fills may be a member of a union (union)

  • links_from_match(field, equals, include_self=False, filter=None) — links every need whose field equals one of the current need’s equals values, the per-need spelling of a links rule with join (Matching a field: the join role): both read as text (a string split on ,, an array by item, each value stripped), each need once, in need-id order, the current need left out unless include_self is set, needs only, and with filter only the needs that pass it. An empty field or equals, or one naming no field, a link type, or a field that does not hold text, fails the call, which is reported

Several of them are the inline spelling of a derived-field kind, which writes the same rule once for every need.

A filter (filter, filter_string on check_linked_values) is written in the filter language and evaluated on each candidate need. An empty filter ("") is no filter; one that is only whitespace is a filter that cannot be evaluated on any need, and each call treats it as it treats such a need: calc_sum still counts every need and check_linked_values still tests every linked need (each reporting needs.filter), copy and links_from_content fail the call, and links_from_filter refuses it. A filter naming needs or current_need, or reading a c. attribute such as c.this_doc(), reads beyond the candidate need, and is not evaluated here (the portable form of a test over other needs is a boolean field derived with kind = "any", filtered on in a sum rule’s where = "<flag>" or with calc_sum(…, filter="<flag>")). c.is_a('req') with a string literal is the exception: it reads the candidate’s type alone, against the project’s need types (see Special functions). A call with such a filter is reported where it is written (needs.dynamic_functions, info), and what you see in its place depends on where you wrote it: a role keeps rendering as the role chip — its own text, unevaluated; a [[...]] written in a needtable’s :style_row: renders ??; and a [[...]] written in a need’s field or link value is skipped silently, leaving the field at its other values. (A bare [[...]] in a need’s body content is not evaluated at all — use the ndf role there.) Functions a project registers through needs_functions are not resolved, nor those an extension registers: sphinx-test-reports’ tr_link(test_option, target_option) is reported with the call to write instead, links_from_match(target_option, test_option, include_self=True) — the arguments swapped — which ubCode resolves; the two differ where tr_link links a need twice, keeps the project’s order, compares a value whole, or fails on an array or a number (see Matching a field: the join role).

For example:

.. req:: My requirement
   :id: REQ_001
   :status: [[copy("priority")]]

.. spec:: My specification
   :id: SPEC_001
   :links: [[links_from_content()]]

   This specification realises :need:`REQ_001`.

Note

In a need’s own field or link value, copy('is_modified') and copy('modifications') count needextend matches only — the same caveat the Variants section carries, and for the same reason: a need’s own resolution cannot be an input to itself. Every other context field resolves as a :filter: resolves it.

In prose: the ndf and need_func roles

The same functions can be called from inside prose, and the result is rendered in place as plain text:

A dynamic function :ndf:`echo("in a paragraph")` reads inline.

.. req:: My requirement
   :id: REQ_002

   This need's own id is :ndf:`copy("id")`.

ndf takes the bare call. need_func takes text containing a [[...]] call and substitutes the result into that text, keeping what surrounds it:

:need_func:`before [[echo("x")]] after`

renders before x after. Upstream deprecated need_func in favour of ndf in sphinx-needs 3.1.0 and removed it in 9.0.0, where a Sphinx build reports it as an unknown role (docutils’ error in reStructuredText, MyST-Parser’s myst.role_unknown warning in Markdown); ubCode still resolves both.

Which need a call reads depends on where it is written. Inside a need’s body, the call reads that need, so copy("id") above renders REQ_002. Outside any need there is no current need, so a function that needs one — copy and links_from_content — renders ??. A Sphinx build renders ?? there too, but it also logs a warning saying which function failed and why; ubCode renders the ?? silently. That difference is deliberate and is recorded under When ubCode cannot resolve a call. echo and test need no need and resolve anywhere.

MyST works the same way, with the role spelled {ndf} / {need_func}.

Note

A need_func whose text contains no [[...]] at all renders that text literally and reports nothing, as a Sphinx-Needs build before 9.0.0 did.

When ubCode cannot resolve a call

A call that cannot resolve for any need is reported once, at the place it is written, under the needs.dynamic_functions code. Three things trigger it: the text does not parse as a function call, it names a function ubCode does not implement, or it names one that cannot be called that way. The report covers need field and link values, a needtable :style_row:, and the two roles above.

These findings are informational, not warnings, and that is deliberate: ubCode implements every built-in, but a Sphinx project also has everything needs_functions registers and ubCode cannot run project Python, so an unresolvable call is often a statement about ubCode rather than about the document. They are reported, they do not fail ubc check, and they can be silenced like any other code:

[lint]
ignore = ["needs.dynamic_functions"]

A role whose call is reported this way keeps rendering as the role chip — its own text, unevaluated — rather than as ??. ?? would claim the call ran and failed, which is not true of a function a Sphinx build resolves and ubCode does not. A call that ubCode does implement but that fails when it runs — copy("status") on a need that has no status, or any call needing a need when there is none — renders ?? and is not reported.

A Sphinx build reports these: it renders the same ?? and logs, for example, Error while executing function 'copy': Option status not found in need REQ_002. ubCode is silent, and that is a known gap rather than a considered quietness: the value is computed while the page is being rendered, which is after the point where ubCode attaches findings to a source location. Reporting it is planned. Everything ubCode can decide from the text you wrote — an unparseable call, an unknown function name, a bad argument list — is reported, once, at the place you wrote it.

A call in a need’s field that runs but returns a value of the wrong type for that field — a number, an integer, a boolean or a list in a string field, or a string or a list in an integer, number or boolean one — is a warning on the need, as in a Sphinx build, and the field keeps its empty value (a list keeps the items written beside the call): needs.dynamic_function, Dynamic function value type mismatch for field 'summary' on need 'REQ_001': expected string, got number. An integer is accepted in a number field. An array field takes a value of its item type or a list of such values, and stores an empty list as []; one item of another type fails the whole field, the values written beside the call included (… expected array(integer), got string). To store such a result, declare the field with its type, for example { name = "total", schema = { type = "number" } } under extra_options. A call that returns nothing (None) is the same warning, … got null, in a field that may not be empty — an extra_options entry without a schema is one — and leaves a field that may be empty (nullable) at null.

Dynamic function parsing is enabled by default and can be controlled globally or per-field/per-link:

[needs]
parse_dynamic_functions = false  # disable globally (sphinx-needs ≥ 7.0)

[needs.fields.my_field]
parse_dynamic_functions = true   # re-enable for this field (sphinx-needs ≥ 6.3)

[needs.links.implements]
parse_dynamic_functions = true   # re-enable for this link (sphinx-needs ≥ 6.3)
parse_dynamic_functions

Type: boolean (default: true)

Whether dynamic functions are parsed by default. Applies to extra fields and links unless overridden per-field/per-link. Core fields are not affected by this global setting.

The global parse_dynamic_functions option was added in sphinx-needs 7.0 (needs_parse_dynamic_functions). Per-field and per-link parse_dynamic_functions was added in sphinx-needs 6.3.

When a call reads a value another call computes

Added in version 0.37.0.

A call may read a value another call computes: copy('summary', 'B') where B’s summary is itself a [[...]] or a <<...>> variant, a calc_sum over such values, a calc_sum(..., links_only=True) or check_linked_values whose own links carry a call, or a variant condition naming one. ubCode resolves the calls in dependency order: first every call in a link type, such as links, then every other call, each after every value it reads. So the reader gets the computed value, on every build, whatever order the needs and documents are written in. A call in a link type that reads through its need’s own links, when those are computed too, runs after them, and after every need that computes the value it reads there. Between the two steps the backlinks are built, so a call or a variant condition can read them as <link type>_back: copy('links_back') lists the needs whose links name this one, sorted by id, and is an empty list when there are none — a list either way, so it belongs in an array field; <<['REQ_1' in links_back]:linked, unlinked>> tests it, and len(links_back) == 0 holds when none links here. The dead-link flags are set at the same point: has_dead_links, whether a link of the need names a need that does not exist or a part its need does not have, and has_forbidden_dead_links, the same over the link types that do not set allow_dead_links. The derive rules run in the same two steps, those of the link kinds with the calls in link types and those of the value kinds with the other calls, and the late stage after both.

Before these steps, each need is created as its document is read (a need from a needs.json, by needimport or [[needs.external_needs]], as it is loaded): a field or link type it does not set takes its default, as its need type declares it (Fields per need type), and the links of a link type with copy = true are copied into links, so the links a needextend adds to such a link type are not copied. The whole path of a need’s values:

        flowchart LR
  subgraph created["When a need is created"]
    direction TB
    written["What the need sets:<br/>its directive, list2need item or src-trace marker,<br/>or its needs.json record"]
    defaults["Each field and link type it does not set:<br/>the first matching predicate, else the default,<br/>as its need type declares them"]
    copied["copy = true: the links of those link types<br/>are copied into links"]
  end
  subgraph resolved["Resolution"]
    direction TB
    extend["Every needextend, matched and applied<br/>before any dynamic function or rule runs"]
    link_types["The link types, each after every value it reads:<br/>dynamic functions and variants in a link type,<br/>and the rules of the links, content_links and union kinds"]
    back["The back links of every link type,<br/>and has_dead_links, has_forbidden_dead_links"]
    fields["The fields, each after every value it reads:<br/>dynamic functions and variants in a field,<br/>and the rules of the value kinds (copy, sum, count, ...)"]
    late["The late stage: hash, fingerprint,<br/>and the rules with after = derived"]
  end
  checked(["Validation: field and link schemas, as the need's type declares them,<br/>schemas.json, dead links, link conditions"])
  written --> defaults --> copied
  extend --> link_types --> back --> fields --> late
  created --> resolved --> checked
    

Two kinds of read cannot be ordered, and each is a warning on the need that makes it:

needs.derive_cycle

The value is on a cycle of reads: A’s summary copies B’s, which copies A’s; :hours: [[calc_sum('hours')]], which sums every need’s hours, its own included; or a variant whose condition reads the field it fills, :status: <<[status == 'open']: active, inactive>>. Every value on the cycle keeps its empty value (a list keeps the items written beside its calls), and each gets one finding naming the cycle. Break the cycle: read another field, or give one of the values an authored value. A call that reads a value on a cycle reads that empty value and gets no finding of its own.

needs.derive_scope

The read needs a value that is not final where it is made: a call in a link type reading a field another call computes, or a backlink, both of which are computed after the links (through the need’s own links, when those are computed too, a field that any need computes); a call, or a rule without after = "derived", reading a field a hash rule or a value kind with after = "derived" computes, which runs after every other field; a need.<attr> argument naming which need or field a call reads, where that attribute is itself a call (one the need does not set at all — an unset untyped extra option is the empty string — fails the call instead, needs.dynamic_function, need.src selects what the call reads, and is not set); or a needextend filter naming a field that a call or variant computes on some need, since every needextend applies before any call resolves. The call is not run and its field keeps its empty value (a link or an array keeps the items written beside the call); a needextend still applies, matched against the values as written. Read a value that is final before the read: an authored field, or, for a needextend, write the condition as a variant or a call on the field the extend would set.

Both fail ubc check and the build gate, as warnings do, and can be silenced like any other code:

[lint]
ignore = ["needs.derive_cycle", "needs.derive_scope"]

A silenced finding still leaves the value empty.

ubCode 0.36.0 and earlier resolved every call in one pass: a call read the value stored before resolution — the field’s empty value, or only the literal part of a list — silently, with no finding. Sphinx-Needs before 9.0.0 answers these reads by document order; 9.0.0 computes them in dependency order too; see Dynamic functions resolve all eight built-ins, and their filters.

filter_data

Type: object (default: {})

Additional context variables that can be referenced in filter expressions throughout your needs configuration. This allows you to define custom variables for conditional logic in multiple contexts.

Where filter_data can be used:

  1. Predicate default filters — in global_options predicates (or predicates on individual fields/links in sphinx-needs ≥ 7.0) to conditionally set default values

  2. needimport item filters — to filter which needs are imported from external sources

  3. needextend filters — to conditionally extend or modify needs based on context

[needs]
filter_data = { environment = "production", team = "backend", version = "2.0" }

# Using predicates on a field directly (sphinx-needs ≥ 7.0, recommended)
[needs.fields.priority]
default = "medium"
predicates = [
  ["environment == 'production'", "high"],
  ["team == 'backend'", "high"]
]

# Or via global_options (sphinx-needs < 7, deprecated)
# [needs.global_options.priority]
# default = "medium"
# predicates = [
#   ["environment == 'production'", "high"],
#   ["team == 'backend'", "high"]
# ]

Example with needimport:

.. needimport:: external_needs.json
   :filter: environment == 'production' and version == '2.0'

Example with needextend:

.. needextend:: team == 'backend'
   :status: critical

Common use cases:

  • Setting environment-specific defaults (development, staging, production)

  • Filtering imported needs based on release version or team ownership

  • Applying team or project-specific configurations

  • Conditional formatting or validation based on build context

  • Dynamic behaviour in CI/CD pipelines

import_keys

Type: object (default: {})

Mapping of keys for needimport directives, allowing short keys to reference longer file paths. Available since sphinx-needs 4.2.

[needs.import_keys]
backend = "/path/to/backend_needs.json"
frontend = "/path/to/frontend_needs.json"

JSON output

These keys shape the needs.json export. They apply to whatever writes that file — ubc build needs (the default --format json), and ubc build html when build_json is on — so the shaping below is identical whichever command wrote the file.

The two commands still differ in one respect these keys do not govern: ubc build needs writes source maps by default (an __source__ entry per need, recording where each need was written), while the build_json sidecar omits them, which is closer to what Sphinx-Needs writes. In the draft format "2a1" (json_format_version) neither writes __source__: every need records its source instead.

In the default format, both write a docname on every need, as Sphinx-Needs does: the document the need belongs to — for a need written in a file that .. include:: pulls in, the page that includes it, and for an imported need, the page holding the needimport — or null for a need from [[needs.external_needs]]. json_remove_defaults leaves that null out, and json_exclude_fields can drop the key. Every need also carries every declared link type, as [] where it holds none of it (whichever need types declare the link type), and a need with no body carries "content": "", as Sphinx-Needs writes them; json_remove_defaults leaves out the empty content, and an empty list that is the link type’s default.

Sphinx-Needs does not let a project declare a field or link type named docname. ubCode does, and writes your own field or link type under that key instead of the document name.

Note

The keys do not shape ubc diff. That command projects the index through the same writer with no shaping applied, so an excluded field is still compared, and without the docname each need records. Note that its link comparison is currently condition-blind: it reads link values without their [condition] suffixes, so editing only a link’s condition does not register as a change. Splitting the two uses apart — conditions for the field-by-field comparison, bare IDs for the impact graph, which keys nodes on them — is a separate piece of work.

build_json

Type: boolean (default: false)

When true, ubc build html also writes needs.json into the root of the output directory, beside the pages. Clearing the key removes the copy an earlier build wrote, provided the output directory is one ubCode owns (one it created itself, or an empty one) — in a directory it does not own it never deletes anything, so a stale export would have to be removed by hand.

Warning

In an output directory ubCode owns, needs.json at the root is a builder-managed name, like the generated pages and the _static/ and _images/ trees. A file you place there yourself under that name is removed by the next build, whether or not build_json is set. Keep a hand-maintained needs.json outside the output directory.

[needs]
build_json = true

json_exclude_fields

Type: array of string

Default:

json_exclude_fields = [
  "lineno_content", "collapse", "hide",
  "type_prefix", "type_color", "type_style",
  "is_need", "is_part", "id_parent", "id_complete",
]

Need fields to leave out of the file. A listed name is dropped from every need object and from the file’s needs_schema, so the schema always describes exactly what the file contains.

An authored list replaces the default rather than adding to it. Names that no need or schema uses are ignored, so listing a field the project does not define is harmless — which is why the default can carry the Sphinx-Needs core-field names that have no ubCode equivalent. Set an empty list to write every field:

[needs]
json_exclude_fields = []

json_remove_defaults

Type: boolean (default: false)

When true, a field whose value equals that field’s default is left out. This shrinks the file considerably on projects where most needs take the defaults. The file records "needs_defaults_removed": true, and a reader must re-apply the defaults published in needs_schema itself. A field’s default in needs_schema is its own, global default – the value restored for an omitted key – not the value an unset field holds on every need type: a need whose type declares another default (see Fields per need type) holds that one, and it is written, so the file reads back the same with or without this option. A link type’s default in needs_schema is its literal default (its own, or its [needs.global_options] one), written as a need holding it writes its links: sorted, without duplicates, and with each link’s condition exactly when json_include_link_conditions keeps the needs’. A link type whose default is a dynamic function or a variant, and a derived link type, give []. A need holding no link of a link type whose default is not [] is written with [], so it does not read back as holding the default.

json_format_version

CLI Experimental

Type: integer or string (default: 1)

The format needs.json is written in, by ubc build needs and by the build_json sidecar of ubc build html:

  • 1 (the default): the format described above, unchanged. The text "1" is the same, as Sphinx-Needs reads it.

  • "2a1": the first draft of format 2, written as Sphinx-Needs writes it (needs_json_format_version, read from the same key of a shared ubproject.toml). Each need records the places its text came through — the file and the lines of its directive, each file it was included through, the needs.json it was imported from, the code a marker is in, the test report — and the page and sections it is placed in. A need read from another project’s "2a1" file (by a needimport or as an external need, see Importing and extending needs) is written with that project’s places first, as the file gave them, each naming the project it belongs to, then this project’s, so its source grows with each project it passes through.

[needs]
json_format_version = "2a1"

Any other value is reported as a config finding, and the file is written in format 1. A -c override sets the key like any other (-c 'needs.json_format_version = "2a1"').

Attention

Experimental.

A "2a1" file is readable only by the release that wrote it: the draft may change, or be replaced by the next one, in any release. In ubCode, needimport and external needs read it (see Importing and extending needs); ubc diff, ubc build validate-json, the needs.json panel and ubc agent install --from-needs-json do not read it yet, and refuse it. Each command that writes such a file says so once, in an info finding (build.needs_json_experimental), which the default --deny warning gate does not count, so a project that sets the key for Sphinx-Needs keeps a passing ubc build html; a build that writes no needs.json says nothing. Use it to try the format, not for a file another project relies on.

The format is specified by Sphinx-Needs: see its needs.json format 2a1 (draft). In short: the document has a format_version, the writing project (its name and version) and the creator, and no versions or needs_schema; its needs are a list of records, in the order of their ids, each with id, type, fields (every value of the fields its need type declares, a default and an empty list or string too, except a null value, which is left out: a reader reads a missing field as unset), links (a bare id, or {"id", "part", "condition"}; no back links), content (its text, doctype and parts) and source.

Of the other keys, under "2a1":

  • json_exclude_fields leaves out a field or a link type it names, content (doctype and parts its keys), and source; a key of format 1 the source carries in "2a1" — docname, lineno, sections, section_name, signature, external_url, is_import, is_external — is reported, once, as having no key of its own (exclude source instead);

  • json_include_link_conditions works as in format 1;

  • json_remove_defaults is ignored, with one warning: a "2a1" file carries every value and no schema;

  • reproducible_json still has no effect: ubCode writes no created time in either format;

  • of the flags of ubc build needs, --pretty and --no-content apply, and --source-maps does not.

Each key the draft does not obey as format 1 does is reported once, as a build.needs_json_option_ignored warning.

ubCode writes every need, external needs included: it has no needs_builder_filter, whose Sphinx-Needs default (is_external==False) leaves external needs out. To compare the two tools’ files, set Sphinx-Needs’ filter to "".

Where ubCode does not record what Sphinx-Needs writes, it leaves the value out rather than guess: the field constraints (which ubCode does not model), duration and completion where a need sets them (nor these), and sphinx-codelinks’ project, directory and file where they hold a value, which ubCode does not declare (file only on the test-report types); the last line of a needimport, src-trace or test-report directive (its first line is written); the suites, scope and case a test report’s need is read from; and the domain object (a py:function, say) a need is written inside. Two values differ, in both formats: an integer read into a number field is written as a number with a fraction (3.0), and so is each integer of an array(number) value ([1.0, 2.0]), where Sphinx-Needs writes it as read (3, [1, 2]); and an external need whose record states no sections at all has an empty section list ("semantic": []), where Sphinx-Needs writes no semantic (neither tool’s own needs.json leaves sections out of a record).

reproducible_json

Type: boolean (default: false)

Accepted for Sphinx-Needs compatibility; it has no effect in ubCode.

Sphinx-Needs writes a wall-clock created timestamp into needs.json unless this key is set, which makes the file differ on every build. ubCode never writes that timestamp, so its needs.json is already byte-identical across builds of unchanged sources — the behaviour reproducible_json = true asks for is what ubCode always does. The key is accepted so that a configuration shared with Sphinx-Needs does not have to be edited.