Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions notations/packages/reqif.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,9 @@ The package does **not** carry:
- A revision-history or audit trail (no `revise` / `history` commands; §6.2 below deleted)
- Suspect-link detection as a package service (no `suspect` command; §6.3 below deleted)

**Representation for interchange:** when a `spec-object` or `spec-relation` is imported from ReqIF XML carrying foreign workflow state or revision-tracking fields that the standard's own XML schema defines — and equivalently, when a folder is exported that happened to have carried these before this section was written — the round-trip converter (§6, `export`/`import`) **preserves them as inert document attributes:**
**Representation for interchange:** the round-trip converter (§6, `export`/`import`) preserves the following package fields as inert metadata through the Transitrix tool extension described below. They are not built-in ReqIF XML attributes or a managed lifecycle. Arbitrary vendor-specific history formats are not automatically understood: a foreign adapter must explicitly map them to this representation.

- A `spec-object` MAY carry `workflow_state` (a string value from ReqIF's own state schema — the package imposes no constraint on this value, reads it, and writes it back unchanged). It is not a managed state machine; it is a citation of the source document's own lifecycle model, for fidelity.
- A `spec-object` MAY carry `workflow_state` (a source-defined string — the package imposes no state vocabulary, reads it, and writes it back unchanged). It is not a managed state machine; it is a citation of the source document's own lifecycle model, for fidelity.
- A `spec-object` MAY carry `revision` and `revisions` (the revision number and prior-snapshot list exactly as they arrived in the XML). These are not maintained by package tooling (no `revise` command); they are part of the imported payload and round-trip unchanged.

```yaml
Expand All @@ -193,7 +193,37 @@ revisions:
values: { ... }
```

A `spec-relation` MAY carry `recorded_target_revision` for the same reason — a field the ReqIF standard supports, imported and exported unchanged. **No suspect-link computation is performed by the package.**
A `spec-relation` MAY carry `recorded_target_revision` as inert source metadata,
imported and exported unchanged. **No suspect-link computation is performed by the package.**

#### Tool-extension mapping

The [OMG ReqIF schema](https://www.omg.org/spec/ReqIF/20110401/reqif.xsd)
provides `TOOL-EXTENSIONS/REQ-IF-TOOL-EXTENSION` for content in other namespaces.
The converter uses namespace `urn:transitrix:reqif:inert-metadata:1`, an
`INERT-METADATA` container with `VERSION="1"`, and one `RECORD` per object/relation
that has any of these fields. `KIND` identifies `spec-object` or `spec-relation`;
`REF` identifies its existing package ID. The record's XML-escaped text is a JSON
object containing only that kind's fields listed above. Namespace identity, rather
than a particular XML prefix, identifies the mapping.

Nested prior snapshots, source strings, numbers, booleans, nulls and empty
collections retain their values within the package's supported YAML/finite JSON
shapes. Missing fields remain absent; present zero/empty values are preserved.
This mapping does not insert fields into the ordinary `values` map or change its
attribute definitions. Packages without the metadata retain their ordinary export
shape without a tool extension.

Malformed JSON, duplicate JSON keys (including nested/escaped equivalents), unknown
fields, duplicate or unresolved record targets and unsupported mapping versions
are refused before writing an imported package. Metadata must also survive the
package's own YAML writer/reader without alteration. Finite JSON values outside
that dialect, such as arrays of arrays or an empty-map item in a list, are refused
before any output folder is created; they are never stringified or partially written.
Unrelated tool extensions are not interpreted. This is a Transitrix round-trip
mapping, not a claim that another ReqIF tool preserves it, nor generic vendor XML
preservation or complete ReqIF schema validation. Release and third-party
interoperability acceptance require their own evidence.

---

Expand Down
18 changes: 13 additions & 5 deletions packages/reqif-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,20 @@ transitrix-reqif <command> [args]
| `import <in.reqif> <reqif-folder>` | Read a ReqIF XML document and write the four object kinds back out as YAML. |
| `validate <reqif-folder>` | Run the package's own validator — `REQIF-001..007`, [`notations/packages/reqif.md`](../../notations/packages/reqif.md) §5. Package-internal only; never resolves a `Transitrix.CanonRef` against an adopter's `canon/`. |
| `roundtrip <reqif-folder>` | Export then re-import in memory (no disk write) and assert the resulting object set is identical to the one loaded from the folder — the package's own demonstration of the epic's round-trip success signal. |
| `transition <reqif-folder> <spec-object-id> <new-state>` | Advance a `spec-object`'s `workflow_state` by exactly one legal step (`draft → reviewed → approved → baselined → superseded`); rejects any other edge. |
| `revise <reqif-folder> <spec-object-id> <ReqIF.Attr> <new-value>` | Change one value, bumping `revision` and snapshotting the pre-change `values` into `revisions`. |
| `history <reqif-folder> <spec-object-id>` | Print a `spec-object`'s revision history, oldest first. |
| `suspect <reqif-folder>` | List every `spec-relation` with its computed suspect status — flagged when its target's text changed since the relation was recorded. |

The last four commands are the package's experimental surface (`REQIF-008`/`REQIF-009`, [`notations/packages/reqif.md`](../../notations/packages/reqif.md) §2.9) — not represented in ReqIF XML, so a folder exercising them is not expected to round-trip identically through `roundtrip`. Worked example: [`notations/examples/packages/reqif-workflow/`](../../notations/examples/packages/reqif-workflow/).
Foreign `workflow_state`, `revision`, `revisions` and relation
`recorded_target_revision` are passive interchange data. Export/import preserves
them through the versioned, namespaced tool extension in
[ReqIF §2.9](../../notations/packages/reqif.md#29-foreign-workflow-state-and-revision-history--interchange-representation-only),
including nested snapshots and explicit empty/zero values. Unknown targets,
duplicate payloads, unsupported versions and malformed known metadata are errors.
Ordinary attribute values and packages without this metadata keep their existing
representation. Other tools must support the mapping to preserve it; arbitrary
vendor history formats are not inferred or certified as interoperable.

The converter has no `transition`, `revise`, `history` or `suspect` commands.
Core retains admission/agreement ownership; metadata is neither updated nor
interpreted as a package-managed state machine, revision tracker or suspicion rule.

## The object model

Expand Down
133 changes: 132 additions & 1 deletion packages/reqif-cli/src/reqif-xml.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,114 @@
// spec-relation, for the same reason.

import { escapeXmlAttr, escapeXmlText, parseXml, findChild, findChildren, textAt } from './xml.mjs';
import { isDeepStrictEqual } from 'node:util';
import { dump, load } from './yaml.mjs';

const DATATYPE_TAG = { STRING: 'STRING', XHTML: 'XHTML', DATE: 'DATE', INTEGER: 'INTEGER', BOOLEAN: 'BOOLEAN' };
const METADATA_NS = 'urn:transitrix:reqif:inert-metadata:1';
const METADATA_FIELDS = {
'spec-object': ['workflow_state', 'revision', 'revisions'],
'spec-relation': ['recorded_target_revision'],
};

// These are passive interchange values, never a package-owned lifecycle.
function metadataFor(record, kind) {
return Object.fromEntries(METADATA_FIELDS[kind]
.filter(key => Object.hasOwn(record, key)).map(key => [key, record[key]]));
}

function assertJsonValue(value) {
if (value === null || typeof value === 'string' || typeof value === 'boolean') return;
if (typeof value === 'number' && Number.isFinite(value)) return;
if (Array.isArray(value)) { value.forEach(assertJsonValue); return; }
if (value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
Object.values(value).forEach(assertJsonValue); return;
}
throw new Error('ReqIF inert metadata must contain finite JSON-compatible values');
}

function assertRepresentableMetadata(data) {
assertJsonValue(data);
// The package owns a deliberately limited YAML dialect. Refuse values that
// would stringify, disappear or fail during a later disk write, before import
// creates any output folders. JSON compatibility alone is insufficient.
let restored;
try { restored = load(dump(data)); }
catch { throw new Error('ReqIF inert metadata is not representable in the supported YAML dialect'); }
if (!isDeepStrictEqual(restored, data)) {
throw new Error('ReqIF inert metadata is not losslessly representable in the supported YAML dialect');
}
}

function parseMetadata(text) {
const data = JSON.parse(text);
// JSON.parse alone silently chooses the last duplicate key. Check decoded
// keys at every object depth, after syntax validation, without interpreting
// braces/colons inside escaped strings as structure.
const stack = [];
for (const match of text.matchAll(/"(?:\\.|[^"\\])*"|[{}\[\]]/g)) {
const token = match[0];
if (token === '{') stack.push(new Set());
else if (token === '[') stack.push(null);
else if (token === '}' || token === ']') stack.pop();
else if (/^\s*:/.test(text.slice(match.index + token.length))) {
const key = JSON.parse(token);
if (stack.at(-1).has(key)) throw new Error('Duplicate ReqIF inert metadata JSON key');
stack.at(-1).add(key);
}
}
return data;
}

function namespaces(node, inherited = {}) {
const result = { ...inherited };
for (const [key, value] of Object.entries(node.attrs)) {
if (key === 'xmlns') result[''] = value;
else if (key.startsWith('xmlns:')) result[key.slice(6)] = value;
}
return result;
}

function namedInNamespace(node, local, ns) {
const parts = node.tag.split(':');
return parts.at(-1) === local && ns[parts.length === 2 ? parts[0] : ''] === METADATA_NS;
}

function readMetadata(root, model) {
const extensions = findChild(root, 'TOOL-EXTENSIONS');
if (!extensions) return;
const records = new Map();
for (const [kind, items] of [['spec-object', model.specObjects], ['spec-relation', model.specRelations]]) {
for (const item of items) records.set(`${kind}:${item.id}`, item);
}
const seen = new Set();
function visit(node, inherited) {
const ns = namespaces(node, inherited);
if (!namedInNamespace(node, 'INERT-METADATA', ns)) {
for (const child of node.children) visit(child, ns);
return;
}
if (node.attrs.VERSION !== '1') throw new Error('Unsupported ReqIF inert metadata version');
for (const entry of node.children) {
if (!namedInNamespace(entry, 'RECORD', namespaces(entry, ns)) || entry.children.length) {
throw new Error('Malformed ReqIF inert metadata record');
}
const kind = entry.attrs.KIND;
const key = `${kind}:${entry.attrs.REF}`;
const record = records.get(key);
if (!record || seen.has(key)) throw new Error(`Unknown or duplicate ReqIF inert metadata target: ${key}`);
const data = parseMetadata(entry.text);
if (!data || Array.isArray(data) || typeof data !== 'object'
|| Object.keys(data).some(field => !METADATA_FIELDS[kind].includes(field))) {
throw new Error('Unexpected ReqIF inert metadata fields');
}
assertRepresentableMetadata(data);
Object.assign(record, data);
seen.add(key);
}
}
visit(extensions, namespaces(root));
}

function slug(s) {
return String(s).toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
Expand Down Expand Up @@ -171,6 +277,29 @@ export function modelToReqifXml(model) {

out.push(close(2, 'REQ-IF-CONTENT'));
out.push(close(1, 'CORE-CONTENT'));
const metadata = [];
for (const [kind, items] of [['spec-object', model.specObjects], ['spec-relation', model.specRelations]]) {
for (const record of items) {
const data = metadataFor(record, kind);
if (!Object.keys(data).length) continue;
assertRepresentableMetadata(data);
metadata.push({ kind, id: record.id, data });
}
}
// No extension for ordinary packages: their emitted shape stays unchanged.
if (metadata.length) {
out.push(open(1, 'TOOL-EXTENSIONS'));
out.push(open(2, 'REQ-IF-TOOL-EXTENSION'));
out.push(open(3, 'tx:INERT-METADATA', { 'xmlns:tx': METADATA_NS, VERSION: '1' }));
for (const { kind, id, data } of metadata) {
out.push(open(4, 'tx:RECORD', { KIND: kind, REF: id }));
out.push(line(5, escapeXmlText(JSON.stringify(data))));
out.push(close(4, 'tx:RECORD'));
}
out.push(close(3, 'tx:INERT-METADATA'));
out.push(close(2, 'REQ-IF-TOOL-EXTENSION'));
out.push(close(1, 'TOOL-EXTENSIONS'));
}
out.push(close(0, 'REQ-IF'));

return out.join('\n') + '\n';
Expand Down Expand Up @@ -268,5 +397,7 @@ export function reqifXmlToModel(xmlText) {
specHierarchies.push(entry);
}

return { specObjectTypes, specObjects, specRelations, specHierarchies };
const model = { specObjectTypes, specObjects, specRelations, specHierarchies };
readMetadata(root, model);
return model;
}
92 changes: 92 additions & 0 deletions packages/reqif-cli/tests/test_reqif_integrity.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@
"""

import os
import json
import re
import shutil
import subprocess
import sys
import tempfile
import xml.etree.ElementTree as ET
from pathlib import Path

try:
Expand Down Expand Up @@ -173,6 +175,94 @@ def part_f_removal_is_clean():
check(not PKG_ID_RE.search(text), f"F: {f}: canon file references a reqif package id after removal — dangling reference")


def part_g_inert_metadata_roundtrip():
"""Exercise actual disk export/import, not just two inverse functions."""
metadata = {
"workflow_state": 'reviewed <&> "quoted"\nРусский\tstate',
"revision": 2,
"revisions": [{
"revision": 0,
"values": {"ReqIF.Text": "previous <wording> & details"},
"recorded_at": "2026-07-28T21:45:04Z",
"foreign": {"flag": False, "missing": None, "tags": ["one", "two"]},
}],
}
with tempfile.TemporaryDirectory(prefix="reqif-inert-") as td:
source = Path(td) / "source"
shutil.copytree(REQIF_DIR, source)
# Use the package's existing YAML writer: the supported source dialect,
# not PyYAML's optional block/flow scalar styles.
script = f'''
import {{ loadPackage, writePackage }} from {json.dumps((Path(PKG_DIR) / 'src/model.mjs').as_uri())};
const model = await loadPackage(process.argv[1]);
Object.assign(model.specObjects[0], JSON.parse(process.argv[2]));
model.specObjects[1].workflow_state = '';
model.specObjects[1].revision = 0;
model.specObjects[1].revisions = [];
model.specRelations[0].recorded_target_revision = 0;
await writePackage(process.argv[1], model);
'''
setup = subprocess.run(["node", "--input-type=module", "-e", script,
str(source), json.dumps(metadata)], capture_output=True, text=True)
if not check(setup.returncode == 0, f"G: fixture setup failed: {setup.stderr}"):
return
xml_path = Path(td) / "out.reqif"
exported = run_cli("export", str(source), str(xml_path))
if not check(exported.returncode == 0, f"G: export failed: {exported.stderr}"):
return
xml = xml_path.read_text(encoding="utf-8")
tree = ET.fromstring(xml) # Independent XML syntax/namespace parser.
ns = "urn:transitrix:reqif:inert-metadata:1"
container = tree.find(f"TOOL-EXTENSIONS/REQ-IF-TOOL-EXTENSION/{{{ns}}}INERT-METADATA")
check(container is not None, "G: missing namespaced tool extension")
for name, candidate in [("normal", xml), ("alternate-prefix", xml.replace("tx:", "other:").replace("xmlns:tx", "xmlns:other"))]:
xml_path.write_text(candidate, encoding="utf-8")
dest = Path(td) / name
imported = run_cli("import", str(xml_path), str(dest))
if not check(imported.returncode == 0, f"G: {name} import failed: {imported.stderr}"):
continue
for file in source.glob("*/*.yaml"):
check(load_yaml(file) == load_yaml(dest / file.relative_to(source)),
f"G: {name} changed {file.relative_to(source)}")
r = run_cli("roundtrip", str(source))
check(r.returncode == 0 and "PASS" in r.stdout, f"G: metadata roundtrip failed: {r.stderr}")

if container is None:
return # Preserve the actual missing-extension/mismatch findings.
# Known payloads fail before any imported folder is written, rather than
# dropping metadata, applying it to another record or overwriting identity.
for case in ("json", "field", "duplicate", "target", "version",
"nested-arrays", "empty-map-item", "duplicate-json-key", "nested-duplicate-key"):
bad = ET.fromstring(xml)
box = bad.find(f"TOOL-EXTENSIONS/REQ-IF-TOOL-EXTENSION/{{{ns}}}INERT-METADATA")
entry = box[0]
if case == "json": entry.text = "not-json"
elif case == "field": entry.text = '{"id":"so-overwrite-1"}'
elif case == "duplicate": box.append(ET.fromstring(ET.tostring(entry)))
elif case == "target": entry.set("REF", "so-missing-1")
elif case == "version": box.set("VERSION", "99")
elif case == "nested-arrays": entry.text = '{"revisions":[{"matrix":[[1,2],[3,4]]}]}'
elif case == "empty-map-item": entry.text = '{"revisions":[{}]}'
elif case == "duplicate-json-key": entry.text = '{"revision":1,"revision":2}'
elif case == "nested-duplicate-key": entry.text = '{"revisions":[{"revision":1,"\\u0072evision":2}]}'
# ET assigns an arbitrary namespace prefix; namespace identity must
# work independently of that serialization choice.
xml_path.write_text(ET.tostring(bad, encoding="unicode"), encoding="utf-8")
dest = Path(td) / f"bad-{case}"
r = run_cli("import", str(xml_path), str(dest))
check(r.returncode == 2 and not dest.exists(),
f"G: malformed {case} payload was not refused before write: {r.stdout} {r.stderr}")


def part_h_plain_export_has_no_metadata():
with tempfile.TemporaryDirectory(prefix="reqif-plain-") as td:
output = Path(td) / "plain.reqif"
r = run_cli("export", str(REQIF_DIR), str(output))
check(r.returncode == 0, f"H: plain export failed: {r.stderr}")
check("TOOL-EXTENSIONS" not in output.read_text(encoding="utf-8"),
"H: ordinary package gained an unnecessary extension")


if not shutil.which("node"):
print("SKIP: `node` not found on PATH (the CLI is Node).")
sys.exit(0)
Expand All @@ -185,6 +275,8 @@ def part_f_removal_is_clean():
part_d_canon_citation_resolves()
part_e_validator_catches_broken_input()
part_f_removal_is_clean()
part_g_inert_metadata_roundtrip()
part_h_plain_export_has_no_metadata()

if _failures:
print("FAIL - ReqIF package integrity:")
Expand Down
Loading