From ffe54ecd33a4f6630f9c5134687518126a4e2dc8 Mon Sep 17 00:00:00 2001 From: transitrix Date: Tue, 29 Sep 2026 07:56:56 +0400 Subject: [PATCH 1/3] feat: validate declared documents through package dispatch --- .../examples/packages/documents/README.md | 14 +- notations/packages/documents.md | 2 +- packages/documents-cli/README.md | 39 +++ packages/documents-cli/documents.mjs | 50 ++++ packages/documents-cli/package-lock.json | 37 +++ packages/documents-cli/package.json | 24 ++ packages/documents-cli/src/validate.mjs | 73 +++++ .../tests/test_documents_integrity.py | 263 +++++++++++------- packages/ingest-cli/src/packages.mjs | 5 + 9 files changed, 405 insertions(+), 102 deletions(-) create mode 100644 packages/documents-cli/README.md create mode 100644 packages/documents-cli/documents.mjs create mode 100644 packages/documents-cli/package-lock.json create mode 100644 packages/documents-cli/package.json create mode 100644 packages/documents-cli/src/validate.mjs diff --git a/notations/examples/packages/documents/README.md b/notations/examples/packages/documents/README.md index 4e745cac..7d159ea2 100644 --- a/notations/examples/packages/documents/README.md +++ b/notations/examples/packages/documents/README.md @@ -1,16 +1,22 @@ # Documents Package — Worked Example -A minimal example of the `documents` package in use: +A minimal synthetic example of the `documents` package in use: - **document-types/**: Templates for documents (requirements, specifications, etc.) - **documents/**: Issued instances, with various statuses (issued, superseded, archived) Each document is bound to core capabilities and requirements by reference ID. -Used by the removal-integrity test (`packages/documents-cli/tests/test_documents_integrity.py`) to validate that: +Copy `document-types/` and `documents/` into the adopter's top-level +`documents/` folder, declare `packages: [documents]`, and install the +[validator](../../../../packages/documents-cli/README.md). Run +`transitrix-ingest check-packages ` to validate the records. -1. Removal (delete both folders, drop from `packages:` list) leaves no trace in the repository. -2. Absence of the package is truly silent: a repository that never declared it is byte-identical to one where it was used then removed. +The integration test combines these records with synthetic core goals, validates +through generic package dispatch, then deletes the enclosing `documents/` folder +and removes the declaration. Core validation still passes and core bytes remain +unchanged. A separate never-declared repository is byte-identical before and +after real validation, even with invalid document records on disk. [RP-17: one document, two editions, independent reviews](../rp17.md) shows a synthetic recovery-arrangements document, its release binding, and use of the diff --git a/notations/packages/documents.md b/notations/packages/documents.md index 2e760f0f..ce7108b5 100644 --- a/notations/packages/documents.md +++ b/notations/packages/documents.md @@ -183,7 +183,7 @@ Per [`PACKAGES.md`](../PACKAGES.md) §4.3, removal is the baseline two-step proc Nothing else changes. No `canon/`, `field/`, or `codex/` file is touched by either step, because per §2.6 no core element ever references a package object — there is nothing in `canon/` for the two steps above to leave dangling. -Demonstrated as a test, not asserted in prose ([`PACKAGES.md`](../PACKAGES.md) §4.3): run `python packages/documents-cli/tests/test_documents_integrity.py` (also wired into CI). The test copies a worked example, performs both removal steps against the copy, and asserts that no `canon/` file still references a document id and that every `canon/` file still parses. +Demonstrated as a test, not asserted in prose ([`PACKAGES.md`](../PACKAGES.md) §4.3): run `python packages/documents-cli/tests/test_documents_integrity.py` (also wired into CI). The test installs the packed validator into a synthetic adopter with two admitted, linked core goals and three worked package records. It runs `check-packages`, `repo-check` and the core linter before and after both removal steps, checks that core bytes are retained, and runs real validation between byte snapshots of a never-declared repository. Install the validator's test dependencies with `npm ci --prefix packages/documents-cli` first; see its [usage guide](../../packages/documents-cli/README.md). --- diff --git a/packages/documents-cli/README.md b/packages/documents-cli/README.md new file mode 100644 index 00000000..ba9dfaf1 --- /dev/null +++ b/packages/documents-cli/README.md @@ -0,0 +1,39 @@ +# Documents validator + +`@transitrix/documents-cli` validates the optional [documents package](../../notations/packages/documents.md). It reads document types and document records, reports DOCS-001–007 errors, and never writes model files or resolves citations against core. + +Requires Node.js 20 or later. Install from a source checkout into your adopter repository: + +```sh +npm pack /path/to/methodology/packages/documents-cli +npm install ./transitrix-documents-cli-0.1.0.tgz +``` + +Declare `packages: [documents]` in the adopter's `transitrix.yaml`, and place records under `documents/document-types/` and `documents/documents/`, one YAML file per ID. Run the normal package entry point: + +```sh +transitrix-ingest check-packages /path/to/adopter +``` + +The generic command discovers the installed `@transitrix/documents-cli` and invokes it. Without the declaration, it does not read the documents folder or run this validator. A declared package whose validator is not installed is skipped under the generic package contract; install the package to obtain validation. + +For an explicit package-only check: + +```sh +npx --no-install transitrix-documents validate /path/to/adopter/documents +``` + +Each finding includes severity, rule and relative filename. Exit codes are 0 for clean input, 1 for record findings, and 2 for invocation or directory-read errors. Invalid YAML or schema structure is reported as an `INPUT` error rather than assigned an unrelated DOCS rule. The validator accepts YAML maps and lists, quoted scalars and comments; duplicate mapping keys fail. + +Versions accept the documented `"1.0"` compatibility form and full SemVer such as `"2.1.3"` or `"2.1.3-rc.1+build.2"`. Timestamps must be real calendar dates at UTC second precision, for example `"2026-09-01T14:30:00Z"`. DOCS-004 checks field membership and required entries; it does not add datatype-value rules. Citations check core ID syntax, including capability addresses, without requiring the target to exist. + +To remove the package, delete the adopter's `documents/` folder and remove `documents` from the manifest declaration. Core files need no changes. + +The synthetic integration tests pack and install the CLI, exercise each DOCS rule through generic dispatch, validate a core model before and after package removal, and check that a never-declared repository remains byte-identical after validation: + +```sh +npm ci --prefix packages/documents-cli +python3 packages/documents-cli/tests/test_documents_integrity.py +``` + +Run these commands from the methodology checkout, with Python 3 and PyYAML installed. The test installs the packed CLI into a temporary adopter and needs npm registry access or a populated npm cache. It also runs the generic package and ReqIF regression tests. diff --git a/packages/documents-cli/documents.mjs b/packages/documents-cli/documents.mjs new file mode 100644 index 00000000..68b8e776 --- /dev/null +++ b/packages/documents-cli/documents.mjs @@ -0,0 +1,50 @@ +#!/usr/bin/env node +import { readdir, readFile, stat } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { parseDocument } from 'yaml'; +import { validateRecords } from './src/validate.mjs'; + +async function validate(folder) { + const root = resolve(folder); + if (!(await stat(root)).isDirectory()) throw new Error('Expected a documents package directory.'); + const records = []; + const findings = []; + for (const [subdir, kind] of [['document-types', 'document-type'], ['documents', 'document']]) { + let entries; + try { entries = await readdir(join(root, subdir), { withFileTypes: true }); } + catch (error) { if (error.code === 'ENOENT') continue; throw error; } + for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) { + if (!/\.ya?ml$/.test(entry.name)) continue; + const file = `${subdir}/${entry.name}`; + try { + if (!entry.isFile()) throw new Error('Expected a regular YAML record file.'); + const parsed = parseDocument(await readFile(join(root, file), 'utf8'), { uniqueKeys: true }); + if (parsed.errors.length) throw new Error(parsed.errors.map(e => e.message).join('; ')); + const value = parsed.toJS({ maxAliasCount: 100 }); + records.push({ file, value }); + if (value?.kind !== kind || entry.name.replace(/\.ya?ml$/, '') !== value?.id) { + findings.push({ code: 'INPUT', severity: 'error', file, message: 'Filename must match id and folder must match kind (documents.md §2.3).' }); + } + } catch (error) { + findings.push({ code: 'INPUT', severity: 'error', file, message: error.message }); + } + } + } + findings.push(...validateRecords(records)); + for (const f of findings) console.log(`${f.code} ${f.severity} ${f.file}: ${f.message}`); + console.log(`documents validate: ${records.length} record(s), ${findings.length} error(s)${findings.length ? '' : ' — clean'}`); + return findings.length ? 1 : 0; +} + +const [command, folder, ...extra] = process.argv.slice(2); +if (command !== 'validate' || !folder || extra.length) { + console.error('Usage: transitrix-documents validate '); + process.exitCode = 2; +} else { + try { process.exitCode = await validate(folder); } + catch (error) { + // Generic dispatch retains stdout, including failures to read package input. + console.log(`INPUT error: ${error.message}`); + process.exitCode = 2; + } +} diff --git a/packages/documents-cli/package-lock.json b/packages/documents-cli/package-lock.json new file mode 100644 index 00000000..497eab4d --- /dev/null +++ b/packages/documents-cli/package-lock.json @@ -0,0 +1,37 @@ +{ + "name": "@transitrix/documents-cli", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@transitrix/documents-cli", + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "yaml": "2.9.1" + }, + "bin": { + "transitrix-documents": "documents.mjs" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + } + } +} diff --git a/packages/documents-cli/package.json b/packages/documents-cli/package.json new file mode 100644 index 00000000..8525ecf7 --- /dev/null +++ b/packages/documents-cli/package.json @@ -0,0 +1,24 @@ +{ + "name": "@transitrix/documents-cli", + "version": "0.1.0", + "description": "Standalone validator for the optional Transitrix documents package.", + "type": "module", + "bin": { + "transitrix-documents": "./documents.mjs" + }, + "engines": { + "node": ">=20" + }, + "files": [ + "documents.mjs", + "src/" + ], + "license": "MIT", + "author": { + "name": "Transitrix" + }, + "repository": "https://github.com/transitrix/methodology", + "dependencies": { + "yaml": "2.9.1" + } +} diff --git a/packages/documents-cli/src/validate.mjs b/packages/documents-cli/src/validate.mjs new file mode 100644 index 00000000..b6a962bc --- /dev/null +++ b/packages/documents-cli/src/validate.mjs @@ -0,0 +1,73 @@ +// Package-internal checks from notations/packages/documents.md §4. +// Citations are checked for syntax only; no core files are read. +const PREFIX = { 'document-type': 'doct', document: 'doc' }; +const CORE_ID = /^[A-Z][A-Z0-9_]*(?:-[A-Za-z0-9]+)*-[1-9][0-9]*$/; +const CAPABILITY_ID = /^CAPABILITY-[VH][1-9][0-9]*(?:\.[1-9][0-9]*){0,2}$/; +const VERSION = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)?$/; +const STATUSES = new Set(['draft', 'issued', 'superseded', 'archived']); +const DATATYPES = new Set(['STRING', 'TEXT', 'DATE', 'INTEGER', 'BOOLEAN']); +const map = v => v !== null && typeof v === 'object' && !Array.isArray(v); +const text = v => typeof v === 'string' && v.length > 0; + +function timestamp(value) { + if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(value)) return false; + const date = new Date(value); + return Number.isFinite(date.getTime()) && date.toISOString() === value.replace('Z', '.000Z'); +} + +// Each record carries its relative filename for actionable diagnostics. +// INPUT denotes unreadable/schema-invalid input, not an additional DOCS rule. +export function validateRecords(records) { + const findings = []; + const flag = (code, file, message) => findings.push({ code, severity: 'error', file, message }); + const ids = new Map(); + const types = new Map(); + for (const { file, value: obj } of records) { + if (!map(obj) || obj.package !== 'documents' || !Object.hasOwn(PREFIX, obj.kind)) { + flag('INPUT', file, 'Expected a mapping with package: documents and kind: document-type or document.'); + continue; + } + if (!text(obj.id) || !new RegExp(`^${PREFIX[obj.kind]}-[a-z0-9]+(?:-[a-z0-9]+)*-[1-9][0-9]*$`).test(obj.id)) { + flag('DOCS-001', file, `id ${JSON.stringify(obj.id)} must use the ${PREFIX[obj.kind]}-- grammar.`); + } + if (ids.has(obj.id)) flag('DOCS-002', file, `id ${JSON.stringify(obj.id)} is also used in ${ids.get(obj.id)}.`); + else ids.set(obj.id, file); + if (obj.kind === 'document-type') { + const fieldsValid = Array.isArray(obj.fields) && obj.fields.length > 0 && obj.fields.every(f => + map(f) && text(f.key) && DATATYPES.has(f.datatype) && typeof f.required === 'boolean'); + if (!text(obj.name) || !fieldsValid || new Set(obj.fields?.map?.(f => f?.key)).size !== obj.fields?.length) { + flag('INPUT', file, 'A document-type needs name and nonempty fields with unique key, supported datatype and boolean required.'); + } else types.set(obj.id, obj); + } + } + for (const { file, value: obj } of records) { + if (!map(obj) || obj.package !== 'documents' || obj.kind !== 'document') continue; + const type = types.get(obj.type); + if (!type) flag('DOCS-003', file, `type ${JSON.stringify(obj.type)} must resolve to a valid document-type in this package.`); + if (!map(obj.values)) flag('DOCS-004', file, 'values must be a map containing the document-type required fields.'); + else if (type) { + const keys = new Set(type.fields.map(f => f.key)); + for (const key of Object.keys(obj.values)) { + if (!keys.has(key)) flag('DOCS-004', file, `values.${key} is not defined by ${obj.type}.`); + } + for (const field of type.fields) { + if (field.required && !Object.hasOwn(obj.values, field.key)) flag('DOCS-004', file, `values is missing required field ${field.key} from ${obj.type}.`); + } + } + if (Object.hasOwn(obj, 'canon_refs')) { + if (!Array.isArray(obj.canon_refs)) flag('DOCS-005', file, 'canon_refs must be an array of core ID citations.'); + else for (const ref of obj.canon_refs) { + if (typeof ref !== 'string' || !(CORE_ID.test(ref) || CAPABILITY_ID.test(ref))) { + flag('DOCS-005', file, `canon_refs entry ${JSON.stringify(ref)} is not a grammar-valid core ID.`); + } + } + } + // §2.5 explicitly includes two-component versions such as "1.0". + if (typeof obj.version !== 'string' || !VERSION.test(obj.version)) { + flag('DOCS-006', file, 'version must be a quoted major.minor compatibility version or a full SemVer string.'); + } + if (!timestamp(obj.issued_at)) flag('DOCS-006', file, 'issued_at must be a valid UTC second-precision timestamp (YYYY-MM-DDTHH:mm:ssZ).'); + if (!STATUSES.has(obj.status)) flag('DOCS-007', file, 'status must be draft, issued, superseded or archived.'); + } + return findings; +} diff --git a/packages/documents-cli/tests/test_documents_integrity.py b/packages/documents-cli/tests/test_documents_integrity.py index 8b3215c9..a5ed8906 100644 --- a/packages/documents-cli/tests/test_documents_integrity.py +++ b/packages/documents-cli/tests/test_documents_integrity.py @@ -1,109 +1,178 @@ #!/usr/bin/env python3 -""" -Test suite for documents package removal integrity. +"""Synthetic documents fixtures: real dispatch, DOCS rules, removal and silence. -Per PACKAGES.md §4.3 and §5: -- Removal (delete documents/ folder, drop from packages:) leaves no trace -- Absence of the package is truly silent: byte-identical before/after removal +Tests install the packed validator and its dependencies in a temporary adopter. +Requires npm registry access, or a populated npm cache. """ - +import copy +import json import os +import re import shutil +import subprocess import tempfile -import yaml from pathlib import Path +import yaml -def test_documents_removal_clean(): - """ - Part A: Removal is clean. - - Worked example with packages: [documents] — after folder delete + name drop, - validate is green and no leftover type/rule/path remains. - """ - # Create a temporary working copy of the example - example_src = Path(__file__).parent.parent.parent.parent / "notations" / "examples" / "packages" / "documents" - - with tempfile.TemporaryDirectory() as tmpdir: - work_dir = Path(tmpdir) / "documents-removal-test" - shutil.copytree(example_src, work_dir) - - # Create transitrix.yaml with documents package declared - transitrix_yaml = work_dir / "transitrix.yaml" - transitrix_yaml.write_text( - "transitrix: 1\n" - 'methodology_version: "6.0.0"\n' - "packages: [documents]\n" - ) - - # Verify initial state: documents folder exists - assert (work_dir / "document-types").exists(), "Initial state: document-types/ missing" - assert (work_dir / "documents").exists(), "Initial state: documents/ missing" - assert "documents" in transitrix_yaml.read_text(), "Initial state: documents not in packages:" - - # Perform removal steps - shutil.rmtree(work_dir / "document-types") - shutil.rmtree(work_dir / "documents") - - # Remove from transitrix.yaml - yaml_data = yaml.safe_load(transitrix_yaml.read_text()) - yaml_data.pop("packages", None) - transitrix_yaml.write_text(yaml.dump(yaml_data, default_flow_style=False)) - - # Verify removal is clean - assert not (work_dir / "document-types").exists(), "After removal: document-types/ still exists" - assert not (work_dir / "documents").exists(), "After removal: documents/ still exists" - assert "documents" not in transitrix_yaml.read_text(), "After removal: documents still in transitrix.yaml" - - # No file in the work directory should reference document IDs - for root, dirs, files in os.walk(work_dir): - for f in files: - if f.endswith((".yaml", ".yml", ".md")): - content = (Path(root) / f).read_text() - # Check for document ID patterns: doc-* or doct-* - assert not any(pattern in content for pattern in ["doc-", "doct-"]), \ - f"Leftover document reference in {root}/{f}" - - -def test_absence_is_silent(): - """ - Part B: Absence is truly silent. - - Repository that never declared the package is byte-identical before/after - the methodology change (before/after documents package was added to shipped - packages in this methodology version). - """ - with tempfile.TemporaryDirectory() as tmpdir: - work_dir = Path(tmpdir) / "absence-test" - work_dir.mkdir() - - # Create transitrix.yaml without documents package - transitrix_yaml = work_dir / "transitrix.yaml" - yaml_content = ( - "transitrix: 1\n" - 'methodology_version: "6.0.0"\n' - "notations: [goals, activities]\n" - ) - transitrix_yaml.write_text(yaml_content) - - # Store the original state - original_files = set(work_dir.rglob("*")) - original_yaml = transitrix_yaml.read_text() - - # Simulate the methodology change: documents package was added to shipped packages - # (no action needed — we're not declaring it, so it has zero effect) - - # Verify state is unchanged - new_files = set(work_dir.rglob("*")) - assert original_files == new_files, "Files changed despite no packages: [documents]" - assert original_yaml == transitrix_yaml.read_text(), "transitrix.yaml changed despite no documents package" +ROOT = Path(__file__).resolve().parents[3] +PACKAGE = ROOT / "packages/documents-cli" +INGEST = ROOT / "packages/ingest-cli/ingest.mjs" +EXAMPLE = ROOT / "notations/examples/packages/documents" +VERSION = yaml.safe_load((ROOT / "notations/CURRENT_VERSION.yaml").read_text())["methodology_version"] + + +def run(*args, cwd=ROOT, env=None): + result = subprocess.run([str(a) for a in args], cwd=cwd, env=env, capture_output=True, text=True) + return result.returncode, result.stdout + result.stderr + + +def success(*args, **kwargs): + code, output = run(*args, **kwargs) + assert code == 0, output + return output + + +def snapshot(root): + return {p.relative_to(root).as_posix(): p.read_bytes() + for p in root.rglob("*") if p.is_file()} + + +def write(path, value): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(yaml.safe_dump(value, sort_keys=False), encoding="utf-8") + + +def core_validate(root): + report = yaml.safe_load(success("node", INGEST, "repo-check", root)) + assert report["integrity"]["canon_elements_scanned"] == 2, report + assert report["integrity"]["red_flags"] == [], report + assert report["profile_completeness"]["out_of_profile_types"] == [], report + env = dict(os.environ, REPO_ROOT=str(root)) + output = success("python3", ROOT / "tools/lint.py", env=env) + assert "Validation PASSED" in output, output + + +def main(): + success("node", "--test", ROOT / "packages/ingest-cli/src/packages.test.mjs") + success("python3", ROOT / "packages/reqif-cli/tests/test_reqif_integrity.py") + print("PASS regressions: generic package tests and ReqIF integrity") + with tempfile.TemporaryDirectory(prefix="documents-test-") as temp: + temp = Path(temp) + # Verify the distributable, not a fake validator or source-tree symlink. + packed = json.loads(success("npm", "pack", "--json", "--pack-destination", temp, cwd=PACKAGE)) + root = temp / "adopter" + root.mkdir() + success("npm", "install", "--ignore-scripts", "--no-audit", "--no-fund", + "--prefix", root, temp / packed[0]["filename"]) + manifest = f'transitrix: 1\nmethodology_version: "{VERSION}"\ncoverage_profile: core\n' + (root / "transitrix.yaml").write_text(manifest + "packages: [documents]\n") + # Two admitted synthetic goals, including an actual core-to-core reference. + for n in (1, 2): + goal = {"notation": "goal", "id": f"GOAL-synthetic-{n}", + "name": f"Synthetic goal {n}", "level": n - 1, + "description": "Synthetic documents validation fixture.", + "zone": "canon", "admitted_at": "2026-09-01", + "admitted_by": "synthetic-test", "valid_from": "2026-09-01", + "valid_to": None, "gate_checks": {k: "pass" for k in + ("uniqueness", "consistency", "completeness")}} + if n == 2: + goal["parent"] = "GOAL-synthetic-1" + write(root / f"canon/elements/01_motivation/goals/GOAL-synthetic-{n}.yaml", goal) + shutil.copytree(EXAMPLE / "document-types", root / "documents/document-types") + shutil.copytree(EXAMPLE / "documents", root / "documents/documents") + docpath = root / "documents/documents/doc-srs-v2-1.yaml" + doc = yaml.safe_load(docpath.read_text()) + doc["values"]["Title"] = "Synthetic requirements document" + doc["canon_refs"] = ["GOAL-synthetic-1", "CAPABILITY-V1.2", "REQUIREMENT-unresolved-1"] + write(docpath, doc) + baseline = snapshot(root) + core_validate(root) + output = success("node", INGEST, "check-packages", root) + assert "documents validator passed" in output and "3 record(s), 0 error(s)" in output, output + assert "PKG-001" not in output and "1 validator(s) ran" in output, output + assert snapshot(root) == baseline + print("PASS declared: packed validator discovered; 3 records clean; core validates; no writes") + + cases = [ + ("DOCS-001", "wrong kind ID", lambda d: d.update(id="doct-wrong-1")), + ("DOCS-002", "duplicate ID", lambda d: d.update(id="doc-srs-v1-1")), + ("DOCS-003", "missing type", lambda d: d.update(type="doct-missing-1")), + ("DOCS-004", "unknown value", lambda d: d["values"].update(Unknown="value")), + ("DOCS-004", "missing required", lambda d: d["values"].pop("Title")), + ("DOCS-005", "package citation", lambda d: d.update(canon_refs=["doc-srs-v1-1"])), + ("DOCS-005", "middle underscore", lambda d: d.update(canon_refs=["GOAL-bad_name-1"])), + ("DOCS-006", "invalid calendar date", lambda d: d.update(issued_at="2026-02-30T10:00:00Z")), + ("DOCS-006", "non-UTC timestamp", lambda d: d.update(issued_at="2026-09-01T10:00:00+01:00")), + ("DOCS-006", "invalid version", lambda d: d.update(version="01.2.3")), + ("DOCS-007", "unknown status", lambda d: d.update(status="approved")), + ] + for rule, name, mutate in cases: + bad = copy.deepcopy(doc) + mutate(bad) + write(docpath, bad) + code, output = run("node", INGEST, "check-packages", root) + assert code == 1 and f"{rule} error documents/doc-srs-v2-1.yaml" in output, output + assert set(re.findall(r"DOCS-\d{3}", output)) == {rule}, output + print(f"PASS {rule} error: {name}") + write(docpath, doc) + # Optional fields absent, required entries present (null still counts as + # an entry under DOCS-004), all statuses, SemVer and documented 1.0 form. + for status, version in zip(("draft", "issued", "superseded", "archived"), + ("1.0", "2.1.3", "1.2.3-rc.1+build.2", "0.0.0")): + valid = copy.deepcopy(doc) + valid.update(status=status, version=version, issued_at="2024-02-29T10:00:00Z") + valid.pop("canon_refs") + valid["values"].pop("CoverageArea", None) + valid["values"]["Title"] = None + write(docpath, valid) + success("node", INGEST, "check-packages", root) + print("PASS DOCS-001–007 positive: distinct valid IDs, resolved type, required entries, optional omission, grammar-only citations, dates/versions/statuses") + for bad in ("package: [", "package: documents\npackage: documents\n", "[]\n"): + docpath.write_text(bad) + code, output = run("node", INGEST, "check-packages", root) + assert code == 1 and "INPUT error" in output, output + print("PASS malformed YAML/schema: actionable input failure through dispatch") + write(docpath, doc) + + canon_before = snapshot(root / "canon") + shutil.rmtree(root / "documents") + (root / "transitrix.yaml").write_text(manifest) + after_removal = snapshot(root) + core_validate(root) + output = success("node", INGEST, "check-packages", root) + assert "no packages declared" in output and "DOCS-" not in output and "validator" not in output, output + assert snapshot(root) == after_removal + assert snapshot(root / "canon") == canon_before + assert not any(re.search(rb"\b(?:doc|doct)-", data) for data in canon_before.values()) + print("PASS removal: delete documents/ + declaration; actual core/package validation passes; core bytes retained") + + # A separate never-declared repository contains deliberately broken + # package content and an installed validator: neither is activated. + silent = temp / "never-declared" + shutil.copytree(root, silent) + write(silent / "documents/documents/doc-invalid-1.yaml", {"package": "documents", "kind": "document", "id": "invalid"}) + before = snapshot(silent) + core_validate(silent) + output = success("node", INGEST, "check-packages", silent) + assert "no packages declared" in output and "DOCS-" not in output and "validator" not in output, output + assert snapshot(silent) == before + print("PASS undeclared: broken documents ignored, no package types admitted, no package warnings; byte-identical after real validation") + + # Shipped packages coexist through unchanged generic dispatch. + packed_reqif = json.loads(success("npm", "pack", "--json", "--pack-destination", temp, + cwd=ROOT / "packages/reqif-cli")) + success("npm", "install", "--ignore-scripts", "--no-audit", "--no-fund", + "--prefix", root, temp / packed_reqif[0]["filename"]) + shutil.copytree(EXAMPLE / "document-types", root / "documents/document-types") + shutil.copytree(EXAMPLE / "documents", root / "documents/documents") + shutil.copytree(ROOT / "notations/examples/packages/reqif/reqif", root / "reqif") + (root / "transitrix.yaml").write_text(manifest + "packages: [documents, reqif]\n") + output = success("node", INGEST, "check-packages", root) + assert "documents validator passed" in output and "reqif validator passed" in output, output + assert "2 validator(s) ran, 0 failed" in output, output + print("PASS coexistence: installed documents + reqif both validate through generic dispatch") if __name__ == "__main__": - test_documents_removal_clean() - print("[PASS] Part A: Removal leaves no trace") - - test_absence_is_silent() - print("[PASS] Part B: Absence is truly silent") - - print("\n[PASS] All documents integrity tests passed") + main() diff --git a/packages/ingest-cli/src/packages.mjs b/packages/ingest-cli/src/packages.mjs index db8eb6fe..62edeb1e 100644 --- a/packages/ingest-cli/src/packages.mjs +++ b/packages/ingest-cli/src/packages.mjs @@ -33,6 +33,11 @@ const execFileAsync = promisify(execFile); // @transitrix/ingest-cli (§4.2) — discovery only checks whether that npm // package happens to be installed in the adopter repo's node_modules/. export const SHIPPED_PACKAGES = { + documents: { + npmPackage: '@transitrix/documents-cli', + bin: 'documents.mjs', + validatorArgs: (folder) => ['validate', folder], + }, reqif: { npmPackage: '@transitrix/reqif-cli', bin: 'reqif.mjs', From 4fe1a1bf9f89ee05c9bd3439690418de3e5d4fc9 Mon Sep 17 00:00:00 2001 From: transitrix Date: Tue, 29 Sep 2026 08:01:11 +0400 Subject: [PATCH 2/3] docs: reconcile document version compatibility and boundary cases --- notations/packages/documents.md | 4 ++-- .../tests/test_documents_integrity.py | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/notations/packages/documents.md b/notations/packages/documents.md index ce7108b5..e241664f 100644 --- a/notations/packages/documents.md +++ b/notations/packages/documents.md @@ -131,7 +131,7 @@ canon_refs: | `kind` | yes | Fixed value `document`. | | `id` | yes | `doc-…` per §2.2. | | `type` | yes | A `doct-…` id of the document-type this instance instantiates. | -| `version` | yes | A SemVer-shaped version string (e.g. "1.0", "2.1.3"). | +| `version` | yes | A full SemVer string (including valid prerelease/build forms), or the two-component numeric compatibility form (e.g. "1.0", "2.0"). Each numeric component is zero or a nonzero digit followed by digits; the compatibility form has no suffix. Preserve the supplied string without normalization. | | `status` | yes | One of: `draft`, `issued`, `superseded`, `archived`. | | `issued_at` | yes | ISO 8601 timestamp (UTC second-precision); the instant this version was released. | | `values` | yes | A map keyed by field names defined in the document-type's `fields`; every `required: true` field must have an entry. | @@ -167,7 +167,7 @@ Run by `@transitrix/documents-cli validate ` (the reference im | `DOCS-003` | error | A `document.type` does not resolve to a `document-type` id present in the package. | | `DOCS-004` | error | A `document` carries a `values` entry not defined in its `document-type`'s `fields`, or is missing a required field. | | `DOCS-005` | error | A `canon_refs` entry is present but is not a grammar-valid core id (syntax per [`IDS_AND_REFERENCES.md`](../IDS_AND_REFERENCES.md) §1). | -| `DOCS-006` | error | A `document.issued_at` is not a valid ISO 8601 timestamp, or `document.version` is not a valid SemVer string. | +| `DOCS-006` | error | A `document.issued_at` is not a valid ISO 8601 timestamp, or `document.version` is neither a full SemVer string nor the two-component numeric compatibility form in §2.5. | | `DOCS-007` | error | A `document.status` is not one of: `draft`, `issued`, `superseded`, `archived`. | No rule here reaches into `canon/`, `field/`, or `codex/` — package-internal integrity only, per [`PACKAGES.md`](../PACKAGES.md) §4.2. diff --git a/packages/documents-cli/tests/test_documents_integrity.py b/packages/documents-cli/tests/test_documents_integrity.py index a5ed8906..dc9a7e74 100644 --- a/packages/documents-cli/tests/test_documents_integrity.py +++ b/packages/documents-cli/tests/test_documents_integrity.py @@ -128,6 +128,26 @@ def main(): write(docpath, valid) success("node", INGEST, "check-packages", root) print("PASS DOCS-001–007 positive: distinct valid IDs, resolved type, required entries, optional omission, grammar-only citations, dates/versions/statuses") + # Both published compatibility versions and full SemVer remain literal + # data; no normalization or migration is a validation side effect. + for version in ("1.0", "2.0", "0.0", "2.1.3", "1.2.3-0", "1.2.3-rc.1+build.2", "1.2.3+001"): + valid = copy.deepcopy(doc) + valid["version"] = version + write(docpath, valid) + before_version = docpath.read_bytes() + success("node", INGEST, "check-packages", root) + assert docpath.read_bytes() == before_version + for version in ("1", "1.2.3.4", "01.0", "1.00", "01.2.3", "1.02.3", "1.2.03", + "1.0-rc.1", "1.0+build", "1.2.3-01", "1.2.3-", "1.2.3+", "1.2.3-rc..1", + "1.2.3+build..1", "1.2.3-rc_1", " 1.2.3", "1.2.3 ", 1.0, None): + bad = copy.deepcopy(doc) + bad["version"] = version + write(docpath, bad) + code, output = run("node", INGEST, "check-packages", root) + assert code == 1 and "DOCS-006 error documents/doc-srs-v2-1.yaml" in output, output + assert set(re.findall(r"DOCS-\d{3}", output)) == {"DOCS-006"}, output + print("PASS DOCS-006 versions: 7 valid preserved strings; 19 invalid counts, components, suffixes and scalar types rejected") + for bad in ("package: [", "package: documents\npackage: documents\n", "[]\n"): docpath.write_text(bad) code, output = run("node", INGEST, "check-packages", root) From 68dcfe5cfde42b753581caab5f0ac62cf3a7ed0f Mon Sep 17 00:00:00 2001 From: transitrix Date: Tue, 29 Sep 2026 08:01:35 +0400 Subject: [PATCH 3/3] docs: scope component wording to the compatibility version form --- notations/packages/documents.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/notations/packages/documents.md b/notations/packages/documents.md index e241664f..eca96a28 100644 --- a/notations/packages/documents.md +++ b/notations/packages/documents.md @@ -131,7 +131,7 @@ canon_refs: | `kind` | yes | Fixed value `document`. | | `id` | yes | `doc-…` per §2.2. | | `type` | yes | A `doct-…` id of the document-type this instance instantiates. | -| `version` | yes | A full SemVer string (including valid prerelease/build forms), or the two-component numeric compatibility form (e.g. "1.0", "2.0"). Each numeric component is zero or a nonzero digit followed by digits; the compatibility form has no suffix. Preserve the supplied string without normalization. | +| `version` | yes | A full SemVer string (including valid prerelease/build forms), or the two-component numeric compatibility form (e.g. "1.0", "2.0"). In the compatibility form, each component is zero or a nonzero digit followed by digits, with no suffix. Preserve the supplied string without normalization. | | `status` | yes | One of: `draft`, `issued`, `superseded`, `archived`. | | `issued_at` | yes | ISO 8601 timestamp (UTC second-precision); the instant this version was released. | | `values` | yes | A map keyed by field names defined in the document-type's `fields`; every `required: true` field must have an entry. |